From 1f4e14b2e973ee7de337fd4866d9a5ceff5cb6d1 Mon Sep 17 00:00:00 2001 From: Lucas Faria Mendes Date: Mon, 30 Mar 2026 10:38:18 -0300 Subject: chore: location --- Codemerx/App.config | 44 + ...tor.Application.Migration.Files.20200219_01.SQL | 192 + ...tor.Application.Migration.Files.20200219_02.SQL | 116 + ...tor.Application.Migration.Files.20200219_03.SQL | 468 + ...tor.Application.Migration.Files.20200219_04.SQL | 4 + ...tor.Application.Migration.Files.20200219_05.SQL | 768 + ...tor.Application.Migration.Files.20200219_06.SQL | 544 + ...tor.Application.Migration.Files.20200311_07.SQL | 14 + ...tor.Application.Migration.Files.20200311_08.SQL | 8 + ...tor.Application.Migration.Files.20200403_09.SQL | 24 + ...tor.Application.Migration.Files.20200403_10.SQL | 16 + ...tor.Application.Migration.Files.20200403_11.SQL | 29 + ...tor.Application.Migration.Files.20200403_12.SQL | 19 + ...tor.Application.Migration.Files.20200403_13.SQL | 19 + ...tor.Application.Migration.Files.20200403_14.SQL | 29 + ...tor.Application.Migration.Files.20200403_15.SQL | 19 + ...tor.Application.Migration.Files.20200403_16.SQL | 19 + ...tor.Application.Migration.Files.20200403_17.SQL | 19 + ...tor.Application.Migration.Files.20200403_18.SQL | 4 + ...tor.Application.Migration.Files.20200403_19.SQL | 14 + ...tor.Application.Migration.Files.20200403_20.SQL | 4 + ...tor.Application.Migration.Files.20200403_21.SQL | 19 + ...tor.Application.Migration.Files.20200403_22.SQL | 4 + ...tor.Application.Migration.Files.20200403_23.SQL | 19 + ...tor.Application.Migration.Files.20200406_24.SQL | 38 + ...tor.Application.Migration.Files.20200406_25.SQL | 4 + ...tor.Application.Migration.Files.20200406_26.SQL | 4 + ...tor.Application.Migration.Files.20200408_27.SQL | 19 + ...tor.Application.Migration.Files.20200408_28.SQL | 19 + ...tor.Application.Migration.Files.20200408_29.SQL | 40 + ...tor.Application.Migration.Files.20200408_30.SQL | 19 + ...tor.Application.Migration.Files.20200408_31.SQL | 28 + ...tor.Application.Migration.Files.20200408_32.SQL | 34 + ...tor.Application.Migration.Files.20200419_33.SQL | 4 + ...tor.Application.Migration.Files.20200419_34.SQL | 4 + ...tor.Application.Migration.Files.20200430_35.SQL | 4 + ...tor.Application.Migration.Files.20200505_36.SQL | 4 + ...tor.Application.Migration.Files.20200505_37.SQL | 4 + ...tor.Application.Migration.Files.20200505_38.SQL | 9 + ...tor.Application.Migration.Files.20200505_39.SQL | 14 + ...tor.Application.Migration.Files.20200506_40.SQL | 12 + ...tor.Application.Migration.Files.20200512_41.SQL | 62 + ...tor.Application.Migration.Files.20200512_42.SQL | 19 + ...tor.Application.Migration.Files.20200512_43.SQL | 4 + ...tor.Application.Migration.Files.20200514_44.SQL | 4 + ...tor.Application.Migration.Files.20200514_45.SQL | 109 + ...tor.Application.Migration.Files.20200520_46.SQL | 4 + ...tor.Application.Migration.Files.20200520_47.SQL | 8 + ...tor.Application.Migration.Files.20200525_48.SQL | 4 + ...tor.Application.Migration.Files.20200527_49.SQL | 39 + ...tor.Application.Migration.Files.20200527_50.SQL | 5 + ...tor.Application.Migration.Files.20200612_51.SQL | 4 + ...tor.Application.Migration.Files.20200702_52.SQL | 4 + ...tor.Application.Migration.Files.20200709_53.SQL | 4 + ...tor.Application.Migration.Files.20200714_54.SQL | 4 + ...tor.Application.Migration.Files.20200714_55.SQL | 4 + ...tor.Application.Migration.Files.20200716_56.SQL | 4 + ...tor.Application.Migration.Files.20200730_57.SQL | 9 + ...tor.Application.Migration.Files.20200811_58.SQL | 4 + ...tor.Application.Migration.Files.20200817_59.SQL | 9 + ...tor.Application.Migration.Files.20200818_60.SQL | 16 + ...tor.Application.Migration.Files.20200820_61.SQL | 16 + ...tor.Application.Migration.Files.20200820_62.SQL | 16 + ...tor.Application.Migration.Files.20200820_63.SQL | 4 + ...tor.Application.Migration.Files.20200825_64.SQL | 4 + ...tor.Application.Migration.Files.20200831_65.SQL | 4 + ...tor.Application.Migration.Files.20200914_66.SQL | 4 + ...tor.Application.Migration.Files.20200915_67.SQL | 4 + ...tor.Application.Migration.Files.20200924_68.SQL | 4 + ...tor.Application.Migration.Files.20200925_69.SQL | 4 + ...tor.Application.Migration.Files.20200929_70.SQL | 4 + ...tor.Application.Migration.Files.20201001_71.SQL | 4 + ...tor.Application.Migration.Files.20201007_72.SQL | 4 + ...tor.Application.Migration.Files.20201007_73.SQL | 4 + ...tor.Application.Migration.Files.20201008_74.SQL | 4 + ...tor.Application.Migration.Files.20201015_75.SQL | 8 + ...tor.Application.Migration.Files.20201026_76.SQL | 4 + ...tor.Application.Migration.Files.20201027_77.SQL | 4 + ...tor.Application.Migration.Files.20201028_78.SQL | 174 + ...tor.Application.Migration.Files.20201030_79.SQL | 13 + ...tor.Application.Migration.Files.20201104_80.SQL | 4 + ...tor.Application.Migration.Files.20201112_81.SQL | 9 + ...tor.Application.Migration.Files.20201113_82.SQL | 4 + ...tor.Application.Migration.Files.20201117_83.SQL | 4 + ...tor.Application.Migration.Files.20201127_84.SQL | 5 + ...tor.Application.Migration.Files.20201127_85.SQL | 4 + ...tor.Application.Migration.Files.20201127_86.SQL | 4 + ...tor.Application.Migration.Files.20201127_87.SQL | 4 + ...tor.Application.Migration.Files.20201127_88.SQL | 4 + ...tor.Application.Migration.Files.20201127_89.SQL | 6 + ...tor.Application.Migration.Files.20201201_90.SQL | 14 + ...tor.Application.Migration.Files.20201203_91.SQL | 6 + ...tor.Application.Migration.Files.20201203_92.SQL | 4 + ...tor.Application.Migration.Files.20201210_93.SQL | 4 + ...tor.Application.Migration.Files.20201230_94.SQL | 5 + ...tor.Application.Migration.Files.20210107_95.SQL | 4 + ...tor.Application.Migration.Files.20210118_96.SQL | 9 + ...tor.Application.Migration.Files.20210209_97.SQL | 9 + ...tor.Application.Migration.Files.20210217_98.SQL | 9 + ...tor.Application.Migration.Files.20210217_99.SQL | 5 + ...or.Application.Migration.Files.20210301_100.SQL | 4 + ...or.Application.Migration.Files.20210302_101.SQL | 4 + ...or.Application.Migration.Files.20210302_102.SQL | 10 + ...or.Application.Migration.Files.20210302_103.SQL | 4 + ...or.Application.Migration.Files.20210309_104.SQL | 9 + ...or.Application.Migration.Files.20210309_105.SQL | 4 + ...or.Application.Migration.Files.20210315_106.SQL | 4 + ...r.Application.Migration.Files.20210315_107 .SQL | 15 + ...or.Application.Migration.Files.20210323_108.SQL | 4 + ...or.Application.Migration.Files.20210323_109.SQL | 4 + ...or.Application.Migration.Files.20210324_110.SQL | 6 + ...or.Application.Migration.Files.20210324_111.SQL | 4 + ...or.Application.Migration.Files.20210329_112.SQL | 9 + ...or.Application.Migration.Files.20210408_113.SQL | 9 + ...r.Application.Migration.Files.20210415_114 .SQL | 15 + ...r.Application.Migration.Files.20210415_115 .SQL | 16 + ...or.Application.Migration.Files.20210415_116.SQL | 4 + ...or.Application.Migration.Files.20210426_117.SQL | 14 + ...or.Application.Migration.Files.20210510_118.SQL | 8 + ...or.Application.Migration.Files.20210512_119.SQL | 4 + ...or.Application.Migration.Files.20210524_120.SQL | 9 + ...or.Application.Migration.Files.20210525_121.SQL | 4 + ...or.Application.Migration.Files.20210607_122.SQL | 11 + ...or.Application.Migration.Files.20210610_123.SQL | 4 + ...or.Application.Migration.Files.20210610_124.SQL | 25 + ...or.Application.Migration.Files.20210610_125.SQL | 4 + ...or.Application.Migration.Files.20210610_126.SQL | 20 + ...or.Application.Migration.Files.20210610_127.SQL | 4 + ...or.Application.Migration.Files.20210610_128.SQL | 24 + ...or.Application.Migration.Files.20210610_129.SQL | 4 + ...or.Application.Migration.Files.20210610_130.SQL | 26 + ...or.Application.Migration.Files.20210610_131.SQL | 4 + ...or.Application.Migration.Files.20210610_132.SQL | 23 + ...r.Application.Migration.Files.20210614_133 .SQL | 4 + ...or.Application.Migration.Files.20210614_134.SQL | 16 + ...or.Application.Migration.Files.20210614_135.SQL | 4 + ...or.Application.Migration.Files.20210614_136.SQL | 20 + ...or.Application.Migration.Files.20210614_137.SQL | 4 + ...or.Application.Migration.Files.20210614_138.SQL | 16 + ...or.Application.Migration.Files.20210614_139.SQL | 4 + ...or.Application.Migration.Files.20210614_140.SQL | 18 + ...or.Application.Migration.Files.20210614_141.SQL | 4 + ...or.Application.Migration.Files.20210614_142.SQL | 23 + ...or.Application.Migration.Files.20210614_143.SQL | 4 + ...or.Application.Migration.Files.20210614_144.SQL | 27 + ...or.Application.Migration.Files.20210614_145.SQL | 4 + ...or.Application.Migration.Files.20210614_146.SQL | 18 + ...or.Application.Migration.Files.20210615_147.SQL | 4 + ...or.Application.Migration.Files.20210615_148.SQL | 17 + ...or.Application.Migration.Files.20210615_149.SQL | 4 + ...or.Application.Migration.Files.20210615_150.SQL | 10 + ...or.Application.Migration.Files.20210615_151.SQL | 4 + ...or.Application.Migration.Files.20210615_152.SQL | 16 + ...or.Application.Migration.Files.20210615_153.SQL | 4 + ...or.Application.Migration.Files.20210615_154.SQL | 14 + ...or.Application.Migration.Files.20210615_155.SQL | 4 + ...or.Application.Migration.Files.20210615_156.SQL | 13 + ...or.Application.Migration.Files.20210615_157.SQL | 4 + ...or.Application.Migration.Files.20210615_158.SQL | 21 + ...or.Application.Migration.Files.20210615_159.SQL | 4 + ...or.Application.Migration.Files.20210615_160.SQL | 23 + ...or.Application.Migration.Files.20210622_161.SQL | 4 + ...or.Application.Migration.Files.20210622_162.SQL | 16 + ...or.Application.Migration.Files.20210622_163.SQL | 4 + ...or.Application.Migration.Files.20210622_164.SQL | 28 + ...or.Application.Migration.Files.20210629_165.SQL | 4 + ...r.Application.Migration.Files.20210708_166 .SQL | 4 + ...or.Application.Migration.Files.20210708_167.SQL | 30 + ...r.Application.Migration.Files.20210708_168 .SQL | 4 + ...or.Application.Migration.Files.20210722_169.SQL | 5 + ...or.Application.Migration.Files.20210819_170.SQL | 5 + ...or.Application.Migration.Files.20210820_171.SQL | 14 + ...or.Application.Migration.Files.20210823_172.SQL | 4 + ...or.Application.Migration.Files.20210825_173.SQL | 6 + ...or.Application.Migration.Files.20210825_174.SQL | 9 + ...or.Application.Migration.Files.20210910_175.SQL | 4 + ...or.Application.Migration.Files.20210916_176.SQL | 16 + ...or.Application.Migration.Files.20210916_177.SQL | 4 + ...or.Application.Migration.Files.20211104_178.SQL | 1 + ...or.Application.Migration.Files.20211223_179.SQL | 12 + ...or.Application.Migration.Files.20211230_180.SQL | 4 + ...or.Application.Migration.Files.20211230_181.SQL | 4 + ...or.Application.Migration.Files.20220104_182.SQL | 4 + ...or.Application.Migration.Files.20220105_183.SQL | 4 + ...or.Application.Migration.Files.20220112_184.SQL | 4 + ...or.Application.Migration.Files.20220119_185.SQL | 4 + ...or.Application.Migration.Files.20220119_186.SQL | 4 + ...or.Application.Migration.Files.20220131_187.SQL | 4 + ...or.Application.Migration.Files.20220225_190.SQL | 4 + ...or.Application.Migration.Files.20220225_191.SQL | 9 + ...or.Application.Migration.Files.20220307_192.SQL | 16 + ...or.Application.Migration.Files.20220315_193.SQL | 4 + ...or.Application.Migration.Files.20220321_194.SQL | 7 + ...or.Application.Migration.Files.20220325_195.SQL | 4 + ...or.Application.Migration.Files.20220329_196.SQL | 24 + ...or.Application.Migration.Files.20220330_197.SQL | 4 + ...or.Application.Migration.Files.20220404_198.SQL | 4 + ...or.Application.Migration.Files.20220404_199.SQL | 4 + ...or.Application.Migration.Files.20220408_200.SQL | 5 + ...or.Application.Migration.Files.20220413_201.SQL | 4 + ...or.Application.Migration.Files.20220419_202.SQL | 6 + ...or.Application.Migration.Files.20220419_203.SQL | 6 + ...or.Application.Migration.Files.20220429_204.SQL | 4 + ...r.Application.Migration.Files.20220502_205 .SQL | 5 + ...r.Application.Migration.Files.20220502_206 .SQL | 4 + ...or.Application.Migration.Files.20220603_207.SQL | 4 + ...or.Application.Migration.Files.20220608_208.SQL | 4 + ...or.Application.Migration.Files.20220726_209.SQL | 4 + ...or.Application.Migration.Files.20220804_210.SQL | 4 + ...or.Application.Migration.Files.20220817_211.SQL | 4 + ...r.Application.Migration.Files.20220926_212 .SQL | 4 + ...r.Application.Migration.Files.20220929_213 .SQL | 4 + ...r.Application.Migration.Files.20221007_214 .SQL | 4 + ...r.Application.Migration.Files.20221018_215 .SQL | 4 + ...or.Application.Migration.Files.20221028_216.SQL | 4 + ...or.Application.Migration.Files.20221110_217.SQL | 4 + ...or.Application.Migration.Files.20221110_218.SQL | 4 + ...or.Application.Migration.Files.20230208_219.SQL | 4 + ...or.Application.Migration.Files.20230301_220.SQL | 4 + ...or.Application.Migration.Files.20230308_221.SQL | 4 + ...or.Application.Migration.Files.20230502_222.SQL | 4 + ...or.Application.Migration.Files.20230619_223.SQL | 8 + ...or.Application.Migration.Files.20230619_224.SQL | 4 + ...or.Application.Migration.Files.20230705_225.SQL | 4 + ...or.Application.Migration.Files.20230718_226.SQL | 9 + ...or.Application.Migration.Files.20230727_227.SQL | 4 + ...r.Application.Migration.Files.20230807_228 .SQL | 4 + ...r.Application.Migration.Files.20230829_229 .SQL | 4 + ...or.Application.Migration.Files.20231011_230.SQL | 4 + ...or.Application.Migration.Files.20231024_231.SQL | 4 + ...or.Application.Migration.Files.20231031_232.SQL | 4 + ...or.Application.Migration.Files.20240131_233.SQL | 11 + ...or.Application.Migration.Files.20240131_234.SQL | 11 + ...or.Application.Migration.Files.20240322_235.SQL | 6 + ...or.Application.Migration.Files.20240322_236.SQL | 4 + ...or.Application.Migration.Files.20240325_237.SQL | 4 + ...or.Application.Migration.Files.20240415_238.SQL | 4 + ...or.Application.Migration.Files.20240422_239.SQL | 4 + ...or.Application.Migration.Files.20240521_240.SQL | 4 + ...or.Application.Migration.Files.20240522_241.SQL | 4 + ...or.Application.Migration.Files.20240604_242.SQL | 9 + ...or.Application.Migration.Files.20240708_243.SQL | 4 + ...or.Application.Migration.Files.20240722_244.SQL | 7 + ...or.Application.Migration.Files.20240723_245.SQL | 4 + ...or.Application.Migration.Files.20240724_246.SQL | 4 + ...or.Application.Migration.Files.20240729_247.SQL | 4 + ...or.Application.Migration.Files.20240816_248.SQL | 1 + ...or.Application.Migration.Files.20240821_249.SQL | 7 + ...or.Application.Migration.Files.20240821_250.SQL | 4 + ...or.Application.Migration.Files.20240826_251.SQL | 8 + ...or.Application.Migration.Files.20240902_252.SQL | 4 + ...or.Application.Migration.Files.20240919_253.SQL | 7 + ...or.Application.Migration.Files.20241015_254.SQL | 4 + ...or.Application.Migration.Files.20250204_255.SQL | 4 + ...or.Application.Migration.Files.20250210_256.SQL | 4 + ...r.Application.Migration.Files.20250307_257 .SQL | 4 + ...r.Application.Migration.Files.20250314_258 .SQL | 4 + ...r.Application.Migration.Files.20250314_259 .SQL | 4 + ...or.Application.Migration.Files.20250328_260.SQL | 4 + ...or.Application.Migration.Files.20250331_261.SQL | 6 + ...r.Application.Migration.Files.20250401_262 .SQL | 11 + ...or.Application.Migration.Files.20250423_263.SQL | 4 + ...or.Application.Migration.Files.20250424_264.SQL | 4 + ...or.Application.Migration.Files.20250425_265.SQL | 4 + ...or.Application.Migration.Files.20250523_266.SQL | 6 + ...or.Application.Migration.Files.20250625_267.SQL | 4 + ...or.Application.Migration.Files.20250625_268.SQL | 4 + ...or.Application.Migration.Files.20250728_269.SQL | 4 + ...or.Application.Migration.Files.20250815_270.SQL | 4 + ...or.Application.Migration.Files.20250905_271.SQL | 9 + ...or.Application.Migration.Files.20250908_272.SQL | 4 + ...or.Application.Migration.Files.20250909_273.SQL | 14 + ...or.Application.Migration.Files.20250919_274.SQL | 4 + ...or.Application.Migration.Files.20250926_275.SQL | 4 + ...or.Application.Migration.Files.20251002_276.SQL | 4 + ...or.Application.Migration.Files.20251010_277.SQL | 4 + ...or.Application.Migration.Files.20251014_278.SQL | 4 + ...or.Application.Migration.Files.20251030_279.SQL | 4 + Codemerx/Gestor.Application.csproj | 2140 +++ Codemerx/Gestor.Application.sln | 21 + Codemerx/Gestor.Application/Actions/Actions.cs | 222 + Codemerx/Gestor.Application/App.cs | 276 + .../Componentes/CalculoControl.cs | 680 + .../Componentes/CoberturaView.cs | 139 + .../Gestor.Application/Componentes/ContasDialog.cs | 73 + .../Componentes/CustomIsReadOnlyControl.cs | 76 + .../Componentes/CustomItemControl.cs | 54 + .../Componentes/CustomItemValidation.cs | 11 + .../Componentes/CustomLegendChart.cs | 140 + .../Componentes/CustomPasswordBox.cs | 203 + .../Componentes/CustomSenhaLoginBox.cs | 338 + .../Componentes/CustomSeriesViewModel.cs | 72 + .../Componentes/DefaultDialog.cs | 40 + .../Componentes/DialogAdvertising.cs | 101 + .../Componentes/DialogAnaliticoBi.cs | 387 + .../Gestor.Application/Componentes/DialogAnexar.cs | 98 + .../Gestor.Application/Componentes/DialogCopia.cs | 160 + .../Componentes/DialogCopiarCliente.cs | 92 + .../Componentes/DialogCopiarPermissao.cs | 73 + .../Componentes/DialogDetalheExtrato.cs | 119 + .../Componentes/DialogEditarParcelas.cs | 170 + .../Componentes/DialogEnviarEmails.cs | 62 + .../Componentes/DialogExportarPermissao.cs | 103 + .../Componentes/DialogExtratoComissao.cs | 207 + .../Componentes/DialogGrafico.cs | 47 + .../Gestor.Application/Componentes/DialogHoster.cs | 73 + .../Componentes/DialogInstalacoes.cs | 125 + .../Componentes/DialogLogAcesso.cs | 71 + .../Componentes/DialogMedalha.cs | 49 + .../Componentes/DialogObservacao.cs | 85 + .../Componentes/DialogPesquisaAvancada.cs | 129 + .../Gestor.Application/Componentes/DialogPrint.cs | 176 + .../Componentes/DialogProtocolo.cs | 51 + .../Componentes/DialogReordenarItens.cs | 67 + .../Componentes/DialogSelecionarItens.cs | 49 + .../Componentes/DialogSenhaAdm.cs | 125 + .../Gestor.Application/Componentes/DialogTarefa.cs | 391 + .../Componentes/DialogTransferencia.cs | 110 + .../Gestor.Application/Componentes/DialogTrilha.cs | 134 + .../Componentes/DialogVinculo.cs | 89 + .../Gestor.Application/Componentes/ErrorDialog.cs | 40 + .../Componentes/GridRelatorio.cs | 695 + Codemerx/Gestor.Application/Componentes/Loading.cs | 40 + .../Componentes/NRecoHtmlToPdfConverter.cs | 13 + Codemerx/Gestor.Application/Componentes/PassBox.cs | 213 + .../Componentes/ProgressDialog.cs | 40 + .../Componentes/ProspeccaoDialog.cs | 398 + .../Componentes/VincularLancamentoDialog.cs | 82 + .../Gestor.Application/Componentes/WebBrowser.cs | 197 + .../Gestor.Application/Componentes/WebEditor.cs | 704 + .../Converters/ActualHeightConverter.cs | 33 + .../ArquivoDigitalVisibilityConverter.cs | 30 + .../Converters/AssinaturasVisibilityConverter.cs | 32 + .../Converters/AssistenciaVisibilityConverter.cs | 35 + .../Converters/AtivoToColorConverter.cs | 35 + .../Converters/AtivoToStringConverter.cs | 33 + .../Converters/BaixarVisibilityConverter.cs | 41 + .../Converters/BoletosNotasConverter.cs | 31 + .../Converters/BoolToGridHeightOneStarConverter.cs | 40 + .../Converters/CalculoIconConverter.cs | 42 + .../Converters/ColorStatusConverter.cs | 75 + .../ContatoSeguradoraVisibiltyConverter.cs | 35 + .../Converters/DesconsiderarVisibilityConverter.cs | 43 + .../Converters/DiasPentendesConverter.cs | 33 + .../Converters/DocumentoEtiquetaConverter.cs | 49 + .../Converters/EmpresaNomeConverter.cs | 38 + .../Converters/EnderecoConverter.cs | 191 + .../Converters/EnviadoColorConverter.cs | 69 + .../Converters/EnviadoConverter.cs | 39 + .../Converters/EnviadoIconConverter.cs | 65 + .../Converters/EnviadoTooTipConverter.cs | 67 + .../Converters/EqualToCollapsedConverter.cs | 47 + .../Converters/ExcluidoStringConverter.cs | 33 + .../Converters/ExcluirVendedorLabelConverter.cs | 33 + .../Converters/ExpanderHeaderConverter.cs | 41 + .../Converters/ExtensaoVisibilityConverter.cs | 57 + .../Converters/FaturaVisibilityConverter.cs | 31 + .../Converters/FilialStringConverter.cs | 33 + .../Converters/IdVisibilityConverter.cs | 30 + .../Converters/IncluirApoliceEnabledConverter.cs | 37 + .../Converters/IntToMedalConverter.cs | 55 + .../Converters/IntToMedalTextConverter.cs | 47 + .../Converters/IntToVisibilityConverter.cs | 35 + .../InvertedBoolToGridHeightOneStarConverter.cs | 30 + .../Converters/IsNamedObjectVisibilityConverter.cs | 77 + .../ManutencaoPagamentoGroupHeaderConverter.cs | 41 + .../Converters/MenosZeroVirgulaZeroUmConverter.cs | 57 + .../Converters/MimeIconConverter.cs | 267 + .../Converters/ModeloExisteTooltipConverter.cs | 37 + .../Converters/MultiBoolReadOnly.cs | 35 + .../Converters/MultiBoolToVisibilityConverter.cs | 36 + .../Converters/MultiVisibilityConverter.cs | 36 + .../Converters/NullToFalseConverter.cs | 33 + .../Converters/NullToTrueConverter.cs | 37 + .../Converters/PackIconToImage.cs | 41 + .../Converters/PackIconToImageConverter.cs | 39 + .../Converters/RamoToImageConverter.cs | 214 + .../Converters/ResultadoToBoolConverter.cs | 35 + .../StatusComissaoAutomaticaTooltipConverter.cs | 115 + .../Converters/StatusIconConverter.cs | 80 + .../Converters/StatusPagamentoColorConverter.cs | 40 + .../StatusPagamentoVisibilityConverter.cs | 35 + .../Converters/StringToFontWeightConverter.cs | 34 + .../StringToStringFontWeightCleanConverter.cs | 33 + .../Converters/SubTipoEnableConverter.cs | 30 + .../Converters/TelaRelatorioConverter.cs | 41 + .../Converters/TelefoneToVisibilityConverter.cs | 35 + .../Converters/TextInputToVisibilityConverter.cs | 36 + .../TipoDependenteToVisibilityConverter.cs | 35 + .../Converters/TipoEmailVisibilityConverter.cs | 31 + .../Converters/TipoRepasseGlobalFilterConverter.cs | 41 + .../TipoRepasseVendedorVisibilityConverter.cs | 152 + .../Converters/TipoRepasseVisibilityConverter.cs | 56 + .../Converters/TipoSinistroConverter.cs | 30 + .../Converters/TipoTelefoneVisibilityConverter.cs | 35 + .../Converters/TootipStatusConverter.cs | 75 + .../Converters/TypeVisibilityConverter.cs | 33 + .../Converters/ValorTipoConverter.cs | 47 + .../Converters/VariavelExisteColorConverter.cs | 38 + .../Converters/VariavelExisteTooltipConverter.cs | 37 + .../Converters/VerApoliceComissaoConverter.cs | 52 + .../Drawers/AdiantamentoDrawerView.cs | 243 + .../Gestor.Application/Drawers/AgendaDrawer.cs | 563 + .../Drawers/Ajuda/BoletosNotasDrawerView.cs | 174 + .../Drawers/Ajuda/ContratosDrawerView.cs | 69 + .../Drawers/Ajuda/InstalacaoDrawerView.cs | 181 + .../Drawers/ArquivoDigitalDrawer.cs | 835 ++ .../Drawers/Configuracoes/ConfiguracoesDrawer.cs | 159 + .../Gestor.Application/Drawers/ExpedicaoDrawer.cs | 265 + .../Gestor.Application/Drawers/ExtratosDrawer.cs | 281 + .../Gestor.Application/Drawers/ImpostoDrawer.cs | 296 + .../Drawers/InclusaoArquivoDigitalDrawer.cs | 186 + Codemerx/Gestor.Application/Drawers/InfoDrawer.cs | 219 + Codemerx/Gestor.Application/Drawers/LogDrawer.cs | 90 + .../Gestor.Application/Drawers/LogEmailDrawer.cs | 75 + .../Gestor.Application/Drawers/LogSistemaAntigo.cs | 67 + .../Drawers/LogUtilizacaoDrawer.cs | 65 + .../Drawers/MetaSeguradoraView.cs | 224 + .../Gestor.Application/Drawers/MetaVendedorView.cs | 226 + .../Drawers/ObservacoesDrawer.cs | 265 + .../Drawers/PermissaoUsuarioDrawer.cs | 672 + .../Drawers/Relatorios/ConfiguracaoRelatorio.cs | 421 + .../Drawers/Relatorios/FiltroRelatorio.cs | 152 + .../Gestor.Application/Drawers/TarefaDrawer.cs | 631 + .../Drawers/ValoresApoliceDrawer.cs | 63 + .../Drawers/ValoresParcelaDrawer.cs | 70 + .../Drawers/VinculoVendedorDrawer.cs | 124 + .../Helpers/ApplicationHelper.cs | 98 + .../Gestor.Application/Helpers/ArquivoDigital.cs | 65 + .../Gestor.Application/Helpers/AssinadorHelper.cs | 211 + .../Helpers/BindingEnumHelper.cs | 56 + .../Gestor.Application/Helpers/BindingHelper.cs | 239 + Codemerx/Gestor.Application/Helpers/Connection.cs | 632 + .../Gestor.Application/Helpers/ConnectionHelper.cs | 521 + Codemerx/Gestor.Application/Helpers/CustomLinq.cs | 421 + .../Helpers/DataGridExtensions.cs | 83 + Codemerx/Gestor.Application/Helpers/Erro.cs | 24 + Codemerx/Gestor.Application/Helpers/Funcoes.cs | 6825 +++++++++ Codemerx/Gestor.Application/Helpers/HttpHelper.cs | 103 + Codemerx/Gestor.Application/Helpers/Instancia.cs | 75 + .../Helpers/InstanciaAssinador.cs | 44 + .../Gestor.Application/Helpers/LicenseHelper.cs | 572 + Codemerx/Gestor.Application/Helpers/MailHelper.cs | 745 + .../Helpers/NotifyPropertyChangedExtension.cs | 23 + .../Helpers/ObrigatorioValidationRule.cs | 34 + .../Helpers/PasswordBoxAssistant.cs | 95 + Codemerx/Gestor.Application/Helpers/PipeClient.cs | 52 + Codemerx/Gestor.Application/Helpers/PipeServer.cs | 115 + .../Gestor.Application/Helpers/QueryableHelper.cs | 26 + Codemerx/Gestor.Application/Helpers/Recursos.cs | 170 + Codemerx/Gestor.Application/Helpers/TipoToggle.cs | 14 + Codemerx/Gestor.Application/Helpers/ViewHelper.cs | 462 + Codemerx/Gestor.Application/MainWindow.cs | 3069 ++++ Codemerx/Gestor.Application/Migration/Migrator.cs | 189 + .../Gestor.Application/Model/Ajuda/Atendimento.cs | 106 + Codemerx/Gestor.Application/Model/Ajuda/Boleto.cs | 48 + .../Gestor.Application/Model/Ajuda/Contrato.cs | 24 + .../Model/Ajuda/EmailAtendimento.cs | 68 + .../Gestor.Application/Model/Ajuda/Instalacao.cs | 60 + .../Gestor.Application/Model/AnaliticoSource.cs | 24 + Codemerx/Gestor.Application/Model/Configuracoes.cs | 24 + Codemerx/Gestor.Application/Model/Grafico.cs | 25 + Codemerx/Gestor.Application/Model/RelacaoItens.cs | 259 + .../Gestor.Application/Model/SinteticoSource.cs | 97 + Codemerx/Gestor.Application/Properties/Settings.cs | 31 + .../Servicos/Ajuda/AjudaServico.cs | 129 + .../Servicos/ArquivoDigitalServico.cs | 538 + .../Servicos/AssinaturaServico.cs | 178 + Codemerx/Gestor.Application/Servicos/CepService.cs | 161 + .../Servicos/Configuracoes/ConfuguracoesServico.cs | 464 + .../Servicos/Ferramentas/AdiantamentoServico.cs | 281 + .../Servicos/Ferramentas/AgendaServico.cs | 257 + .../Servicos/Ferramentas/EmailServico.cs | 127 + .../Servicos/Ferramentas/EmpresaServico.cs | 287 + .../Servicos/Ferramentas/EstipulanteServico.cs | 124 + .../Servicos/Ferramentas/ImpostoServico.cs | 171 + .../Servicos/Ferramentas/MetaSeguradoraServico.cs | 182 + .../Servicos/Ferramentas/MetaVendedorServico.cs | 182 + .../Servicos/Ferramentas/NotaFiscalServico.cs | 176 + .../Servicos/Ferramentas/ProdutoServico.cs | 92 + .../Servicos/Ferramentas/QualificacaoServico.cs | 57 + .../Servicos/Ferramentas/RamoServico.cs | 192 + .../Servicos/Ferramentas/ReciboServico.cs | 123 + .../Servicos/Ferramentas/SeguradoraServico.cs | 372 + .../Servicos/Ferramentas/SocioServico.cs | 97 + .../Ferramentas/StatusProspeccaoServico.cs | 93 + .../Servicos/Ferramentas/StatusServico.cs | 124 + .../Servicos/Ferramentas/TipoTarefaServico.cs | 93 + .../Servicos/Ferramentas/TipoVendedorServico.cs | 131 + .../Servicos/Ferramentas/UsuarioServico.cs | 303 + .../Servicos/Ferramentas/VendedorServico.cs | 851 ++ .../Servicos/Financeiro/BancosContasServico.cs | 362 + .../Servicos/Financeiro/CentroServico.cs | 92 + .../Servicos/Financeiro/FinanceiroServico.cs | 738 + .../Servicos/Financeiro/FornecedorServico.cs | 123 + .../Servicos/Financeiro/PlanoServico.cs | 120 + .../Servicos/Financeiro/PlanosServico.cs | 93 + .../Servicos/Generic/BaseServico.cs | 2567 ++++ Codemerx/Gestor.Application/Servicos/LogServico.cs | 262 + .../Servicos/MalaDiretaServico.cs | 188 + .../Gestor.Application/Servicos/ParceiroServico.cs | 123 + .../Gestor.Application/Servicos/ParcelaServico.cs | 1006 ++ .../Servicos/PermissaoArquivoDigitalServico.cs | 167 + .../Servicos/PermissaoUsuarioServico.cs | 152 + .../Servicos/ProspeccaoServico.cs | 338 + .../Servicos/RestricaoUsuarioServico.cs | 221 + .../Servicos/Seguros/ApoliceServico.cs | 1848 +++ .../Servicos/Seguros/AtividadeServico.cs | 78 + .../Servicos/Seguros/ClienteServico.cs | 1194 ++ .../Servicos/Seguros/CriticaApoliceServico.cs | 321 + .../Servicos/Seguros/ExpedicaoServico.cs | 192 + .../Servicos/Seguros/Itens/AeronauticoServico.cs | 121 + .../Servicos/Seguros/Itens/AutoServico.cs | 262 + .../Servicos/Seguros/Itens/ConsorcioServico.cs | 156 + .../Servicos/Seguros/Itens/GranizoServico.cs | 156 + .../Servicos/Seguros/Itens/ItemServico.cs | 1900 +++ .../Servicos/Seguros/Itens/PatrimonialServico.cs | 196 + .../Seguros/Itens/RiscosDiversosServico.cs | 156 + .../Servicos/Seguros/Itens/VidaServico.cs | 156 + .../Servicos/Seguros/PerfilEmpresaServico.cs | 179 + .../Servicos/Seguros/PerfilServico.cs | 241 + .../Servicos/Seguros/ProfissaoServico.cs | 78 + .../Servicos/Seguros/SinistroServico.cs | 400 + .../Gestor.Application/Servicos/ServicoExtrato.cs | 335 + .../Gestor.Application/Servicos/TarefaServico.cs | 795 + .../Servicos/VendedorUsuarioServico.cs | 160 + .../ViewModels/AnaliticoViewModel.cs | 210 + Codemerx/Gestor.Application/ViewModels/Arquivo.cs | 24 + .../ViewModels/BI/BISeriesViewModel.cs | 70 + .../ViewModels/BI/NotasViewModel.cs | 311 + .../ViewModels/BI/PainelBiViewModel.cs | 1590 ++ .../ViewModels/BI/ProspeccaoViewModel.cs | 553 + .../ViewModels/BI/TarefaBIViewModel.cs | 1453 ++ .../ViewModels/CoberturaViewModel.cs | 285 + .../ViewModels/Comissao/ComissaoViewModel.cs | 3450 +++++ .../ViewModels/Command/RelayCommand.cs | 29 + .../Configuracoes/ConfiguracoesViewModel.cs | 178 + .../ViewModels/DashboardViewModel.cs | 1111 ++ .../ViewModels/Drawer/AdiantamentoViewModel.cs | 310 + .../ViewModels/Drawer/AgendaViewModel.cs | 427 + .../Drawer/Ajuda/AtendimentosViewModel.cs | 514 + .../Drawer/Ajuda/BoletosNotasViewModel.cs | 122 + .../ViewModels/Drawer/Ajuda/ContratosViewModel.cs | 112 + .../ViewModels/Drawer/Ajuda/InstalacaoViewModel.cs | 281 + .../ViewModels/Drawer/ArquivoDigitalViewModel.cs | 1414 ++ .../ViewModels/Drawer/ExpedicaoViewModel.cs | 196 + .../ViewModels/Drawer/ExtratosViewModel.cs | 5516 +++++++ .../ViewModels/Drawer/ImpostoViewModel.cs | 484 + .../ViewModels/Drawer/InfoViewModel.cs | 208 + .../ViewModels/Drawer/LogAcaoViewModel.cs | 262 + .../ViewModels/Drawer/LogEmailViewModel.cs | 163 + .../ViewModels/Drawer/LogSistemaAntigoViewModel.cs | 42 + .../ViewModels/Drawer/LogViewModel.cs | 1784 +++ .../ViewModels/Drawer/MetaSeguradoraViewModel.cs | 258 + .../ViewModels/Drawer/MetaVendedorViewModel.cs | 244 + .../ViewModels/Drawer/PermissaoUsuarioViewModel.cs | 1939 +++ .../ViewModels/Drawer/TarefaDrawerViewModel.cs | 1283 ++ .../ViewModels/Drawer/ValoresApoliceViewModel.cs | 345 + .../ViewModels/Drawer/ValoresParcelaViewModel.cs | 583 + .../ViewModels/Drawer/VinculoVendedorViewModel.cs | 307 + .../Ferramentas/CadastroEmailViewModel.cs | 362 + .../Ferramentas/CadastroParceiroViewModel.cs | 413 + .../ViewModels/Ferramentas/ComboModelo.cs | 43 + .../ViewModels/Ferramentas/ComboVariavel.cs | 45 + .../ViewModels/Ferramentas/DownloadViewModel.cs | 550 + .../ViewModels/Ferramentas/EmpresaViewModel.cs | 512 + .../ViewModels/Ferramentas/EstipulanteViewModel.cs | 380 + .../ViewModels/Ferramentas/EtiquetaViewModel.cs | 1163 ++ .../ViewModels/Ferramentas/IncluirRamoViewModel.cs | 110 + .../Ferramentas/IncluirSeguradoraViewModel.cs | 110 + .../ViewModels/Ferramentas/MalaDiretaViewModel.cs | 821 ++ .../Ferramentas/ManutencaoPagamentosViewModel.cs | 821 ++ .../ViewModels/Ferramentas/NotaFiscalViewModel.cs | 482 + .../ViewModels/Ferramentas/ProdutoViewModel.cs | 303 + .../Ferramentas/ProtocoloDocumentosViewModel.cs | 399 + .../ViewModels/Ferramentas/ProtocoloEtiqueta.cs | 26 + .../Ferramentas/QualificacaoViewModel.cs | 122 + .../ViewModels/Ferramentas/RamoViewModel.cs | 332 + .../ViewModels/Ferramentas/ReciboViewModel.cs | 769 + .../ViewModels/Ferramentas/SeguradoraViewModel.cs | 621 + .../ViewModels/Ferramentas/SocioViewModel.cs | 358 + .../Ferramentas/StatusProspeccaoViewModel.cs | 326 + .../ViewModels/Ferramentas/StatusViewModel.cs | 367 + .../ViewModels/Ferramentas/TipoTarefaViewModel.cs | 325 + .../Ferramentas/TipoVendedorViewModel.cs | 338 + .../ViewModels/Ferramentas/UsuarioViewModel.cs | 826 ++ .../ViewModels/Ferramentas/VendedorViewModel.cs | 913 ++ .../ViewModels/Financeiro/BancosContasViewModel.cs | 604 + .../Financeiro/CentroDeCustoViewmodel.cs | 255 + .../ViewModels/Financeiro/ContasDialogModel.cs | 48 + .../Financeiro/CopiarClienteViewModel.cs | 28 + .../ViewModels/Financeiro/ExtratoContaViewModel.cs | 552 + .../ViewModels/Financeiro/FinanceiroViewModel.cs | 5973 ++++++++ .../ViewModels/Financeiro/FornecedorViewModel.cs | 780 + .../ViewModels/Financeiro/InfoExtratoViewModel.cs | 81 + .../Financeiro/MenuFinanceiroViewModel.cs | 30 + .../ViewModels/Financeiro/PlanoViewModel.cs | 147 + .../ViewModels/Financeiro/PlanosViewModel.cs | 330 + .../Relatorios/FechamentoFinanceiroViewModel.cs | 2746 ++++ .../ViewModels/Financeiro/TranferenciaViewModel.cs | 99 + .../ViewModels/Generic/BaseApoliceViewModel.cs | 6893 +++++++++ .../ViewModels/Generic/BaseDialogViewModel.cs | 11 + .../ViewModels/Generic/BaseFinanceiroViewModel.cs | 512 + .../ViewModels/Generic/BaseSegurosViewModel.cs | 1238 ++ .../ViewModels/Generic/BaseTarefaViewModel.cs | 233 + .../ViewModels/Generic/BaseViewModel.cs | 3140 ++++ .../Generic/DialogAdvertisingViewModel.cs | 292 + .../ViewModels/Generic/DialogAnexarViewModel.cs | 44 + .../ViewModels/Generic/DialogCopiaViewModel.cs | 168 + .../Generic/DialogCopiarPermissaoViewModel.cs | 350 + .../Generic/DialogEditarParcelasViewModel.cs | 342 + .../Generic/DialogEnviarEmailsViewModel.cs | 394 + .../Generic/DialogExportarPermissaoViewModel.cs | 122 + .../ViewModels/Generic/DialogGraficoViewModel.cs | 45 + .../ViewModels/Generic/DialogMedalhaViewModel.cs | 75 + .../Generic/DialogPesquisaAvancadaViewModel.cs | 604 + .../Generic/DialogProspeccaoViewModel.cs | 352 + .../ViewModels/Generic/DialogTarefaViewModel.cs | 296 + .../ViewModels/Generic/DialogTrilhaViewModel.cs | 102 + .../ViewModels/Generic/DialogViewModel.cs | 87 + .../ViewModels/Generic/DialogVinculoViewModel.cs | 257 + .../ViewModels/Generic/ErrorDialogViewModel.cs | 49 + .../ViewModels/Generic/ExtratoComissaoViewModel.cs | 147 + .../ViewModels/Generic/ItemViewModel.cs | 843 ++ .../ViewModels/Generic/ProtocoloViewModel.cs | 30 + .../ViewModels/Generic/ReordenarItensViewModel.cs | 68 + .../ViewModels/Generic/SelecionarItensViewModel.cs | 89 + .../ViewModels/ImportViewModel.cs | 105 + .../ViewModels/LoginImageModel.cs | 24 + .../ViewModels/LoginViewModel.cs | 1495 ++ .../Gestor.Application/ViewModels/MainViewModel.cs | 1273 ++ .../ViewModels/MenuBIViewModel.cs | 12 + .../ViewModels/MenuFerramentasViewModel.cs | 88 + .../ViewModels/MenuItemViewModel.cs | 1048 ++ .../ViewModels/Relatorios/DialogPrintViewModel.cs | 193 + .../ViewModels/Relatorios/RelatorioViewModel.cs | 14619 +++++++++++++++++++ .../ViewModels/Relatorios/SinteticoViewModel.cs | 424 + .../ViewModels/Seguros/ApoliceViewModel.cs | 124 + .../ViewModels/Seguros/ClienteViewModel.cs | 1787 +++ .../ViewModels/Seguros/ConsultaViewModel.cs | 2425 +++ .../ViewModels/Seguros/CriticaApoliceViewModel.cs | 1486 ++ .../Seguros/Itens/AeronauticoViewModel.cs | 554 + .../ViewModels/Seguros/Itens/AutoViewModel.cs | 3018 ++++ .../Seguros/Itens/BuscarModeloViewModel.cs | 95 + .../ViewModels/Seguros/Itens/ConsorcioViewModel.cs | 520 + .../ViewModels/Seguros/Itens/GranizoViewModel.cs | 500 + .../Seguros/Itens/PatrimonialViewModel.cs | 678 + .../Seguros/Itens/RiscosDiversosViewModel.cs | 626 + .../ViewModels/Seguros/Itens/VidaViewModel.cs | 661 + .../ViewModels/Seguros/PerfilEmpresaViewModel.cs | 274 + .../ViewModels/Seguros/PerfilViewModel.cs | 183 + .../ViewModels/Seguros/SinistroViewModel.cs | 2104 +++ .../ViewModels/Seguros/TrocarClienteViewModel.cs | 92 + .../ViewModels/TrilhaViewModel.cs | 284 + .../ViewModels/TutorialViewModel.cs | 612 + .../Views/Ajuda/AtendimentosView.cs | 302 + .../Views/BI/AcompanhamentoView.cs | 339 + .../Gestor.Application/Views/BI/AgendaBIView.cs | 81 + Codemerx/Gestor.Application/Views/BI/NotasView.cs | 298 + .../Gestor.Application/Views/BI/PainelBiView.cs | 502 + .../Gestor.Application/Views/BI/ProspeccaoView.cs | 422 + Codemerx/Gestor.Application/Views/BI/TarefaView.cs | 628 + .../Views/ConnectionRetryView.cs | 218 + .../Views/Ferramentas/CadastroEmailView.cs | 400 + .../Views/Ferramentas/CadastroParceiroView.cs | 387 + .../Views/Ferramentas/DownloadWindow.cs | 171 + .../Views/Ferramentas/EmpresaView.cs | 424 + .../Views/Ferramentas/EstipulanteView.cs | 395 + .../Views/Ferramentas/EtiquetaView.cs | 157 + .../Views/Ferramentas/IncluirRamoView.cs | 133 + .../Views/Ferramentas/IncluirSeguradoraView.cs | 133 + .../Views/Ferramentas/MalaDiretaView.cs | 301 + .../Views/Ferramentas/ManutencaoPagamentosView.cs | 252 + .../Views/Ferramentas/NotaFiscalView.cs | 327 + .../Views/Ferramentas/ProdutoView.cs | 215 + .../Views/Ferramentas/ProtocoloDocumentosView.cs | 209 + .../Views/Ferramentas/QualificacaoView.cs | 197 + .../Views/Ferramentas/RamoView.cs | 282 + .../Views/Ferramentas/ReciboView.cs | 280 + .../Views/Ferramentas/SeguradoraView.cs | 643 + .../Views/Ferramentas/SocioView.cs | 266 + .../Views/Ferramentas/StatusProspeccaoView.cs | 213 + .../Views/Ferramentas/StatusView.cs | 232 + .../Views/Ferramentas/TipoTarefaView.cs | 213 + .../Views/Ferramentas/TipoVendedorView.cs | 225 + .../Views/Ferramentas/UsuarioView.cs | 545 + .../Views/Ferramentas/VendedorView.cs | 927 ++ .../Views/Financeiro/BancosContasView.cs | 371 + .../Views/Financeiro/CentroDeCustoView.cs | 199 + .../Views/Financeiro/ExtratoWindow.cs | 511 + .../Views/Financeiro/FinanceiroView.cs | 1560 ++ .../Views/Financeiro/FornecedorView.cs | 419 + .../Views/Financeiro/InfoExtratoView.cs | 127 + .../Views/Financeiro/PlanoView.cs | 117 + .../Views/Financeiro/PlanosView.cs | 262 + .../Relatorios/FechamentoFinanceiroView.cs | 285 + .../Views/Generic/BaseUserControl.cs | 104 + .../Views/Generic/DragOverPopup.cs | 57 + .../Views/Generic/ErrorWindow.cs | 101 + .../Views/Generic/HosterWindow.cs | 460 + Codemerx/Gestor.Application/Views/ImportView.cs | 69 + Codemerx/Gestor.Application/Views/LoginWindow.cs | 825 ++ .../Views/Menus/DashboardView.cs | 1002 ++ .../Views/Menus/MenuItensView.cs | 375 + .../Views/Relatorios/RelatorioView.cs | 1167 ++ .../Views/Relatorios/SinteticoView.cs | 509 + .../Views/Seguros/ApoliceView.cs | 3609 +++++ .../Views/Seguros/ClienteView.cs | 1307 ++ .../Views/Seguros/ComissaoView.cs | 1336 ++ .../Views/Seguros/ConsultaOriginalView.cs | 1502 ++ .../Views/Seguros/CriticaApoliceView.cs | 2010 +++ .../Views/Seguros/Itens/AeronauticoView.cs | 373 + .../Views/Seguros/Itens/AutoView.cs | 718 + .../Views/Seguros/Itens/BuscarModeloView.cs | 85 + .../Views/Seguros/Itens/ConsorcioView.cs | 320 + .../Views/Seguros/Itens/GranizoView.cs | 383 + .../Views/Seguros/Itens/PatrimonialView.cs | 466 + .../Views/Seguros/Itens/RiscosDiversosView.cs | 683 + .../Views/Seguros/Itens/VidaView.cs | 705 + .../Views/Seguros/PerfilEmpresaView.cs | 267 + .../Gestor.Application/Views/Seguros/PerfilView.cs | 320 + .../Views/Seguros/SinistroView.cs | 1003 ++ .../Views/Seguros/TrocarClienteView.cs | 154 + Codemerx/Gestor.Application/Views/TutorialView.cs | 369 + .../ApolicePendenteConverter.cs | 33 + .../ArquivoDigitalToolTipConverter.cs | 38 + .../AtivoConverterColor.cs | 35 + .../AtivoVisibilityConverter.cs | 38 + .../Gestor.Common.Converters/BoolToEyeConverter.cs | 37 + .../BoolToYesNoConverter.cs | 33 + .../ComissaoColorConverter.cs | 39 + .../Gestor.Common.Converters/ComissaoConverter.cs | 43 + .../ComissaoConverterMulti.cs | 74 + .../ComparativoColorConverter.cs | 71 + .../ComparativoConverter.cs | 55 + .../ComparativoPercentualToolTipConverter.cs | 33 + .../ComparativoToolTipConverter.cs | 24 + .../EnumDescriptionConverter.cs | 34 + .../ExpanderHeaderConverter.cs | 33 + .../IdToVisibilityConverter.cs | 30 + .../InativoVisibilityConverter.cs | 38 + .../InvertedBooleanConverter.cs | 29 + .../InvertedBooleanToVisibilityConverter.cs | 30 + .../InvertedVisibilityConverter.cs | 30 + .../IsInsertedBoolConverter.cs | 29 + .../IsNotNullBoolConverter.cs | 29 + .../Gestor.Common.Converters/MesConverter.cs | 39 + .../MultiBoolAndConverter.cs | 35 + .../NegativoColorConverter.cs | 38 + .../NullVisibilityConverter.cs | 30 + .../NullVisibilityInvertedConverter.cs | 30 + .../ObjectToStringConverter.cs | 56 + .../ObjectVisibilityConverter.cs | 31 + ...agamentoVendedorCorretoraVisibilityConverter.cs | 28 + .../ParcelaVisibilityConverter.cs | 31 + .../Gestor.Common.Converters/PendenciaConverter.cs | 35 + .../PendenciaVisibilityConverter.cs | 35 + .../RamoAutoVisibilityConverter.cs | 50 + .../RecebidoColorConverter.cs | 32 + .../SaldoWeightConverter.cs | 30 + .../SinalColorConverter.cs | 35 + .../StatusExtratoColorConverter.cs | 65 + .../StatusParcelaVisibilityConverter.cs | 42 + .../StatusTarefaVisibilityConverter.cs | 43 + .../StringNullOrEmptyToVisibilityConverter.cs | 30 + .../TarefaBackgroundColorConverter.cs | 54 + .../TemTarefaVisibilityConverter.cs | 32 + .../TipoCriticaConverter.cs | 40 + .../TipoSinistroConverter.cs | 43 + .../TipoTelefoneVisibilityConverter.cs | 39 + .../TotalizacaoExpanderConverter.cs | 33 + .../Gestor.Common.Converters/ValorTipoConverter.cs | 47 + .../ZeroToEmptyConverter.cs | 41 + .../ZeroToVisibilityConverter.cs | 30 + .../ZeroToVisibilityInvertedConverter.cs | 30 + .../ZeroToVisibilityValorConverter.cs | 31 + .../Gestor.Common.Exceptions/AbortException.cs | 11 + .../Gestor.Common.Exceptions/BaseException.cs | 15 + .../Gestor.Common.Exceptions/ForbiddenException.cs | 15 + .../Gestor.Common.Exceptions/MailingException.cs | 15 + .../PermissionException.cs | 15 + .../UnauthorizedException.cs | 15 + .../ValidationException.cs | 15 + .../Gestor.Common.Helpers/DataBaseParameters.cs | 14 + .../Gestor.Common.Helpers/DefaultAttribute.cs | 19 + .../Gestor.Common.Helpers/EncryptionHelper.cs | 106 + .../EnumBindingSourceExtension.cs | 59 + .../Gestor.Common.Helpers/EnumHelper.cs | 166 + .../Gestor.Common.Helpers/FindVisualChild.cs | 32 + .../Gestor.Common.Helpers/FindVisualChildren.cs | 38 + .../Gestor.Common.Helpers/Functions.cs | 110 + .../Gestor.Common.Helpers/HiddenAttribute.cs | 12 + .../Gestor.Common.Helpers/HttpHelper.cs | 25 + .../Gestor.Common.Helpers/OrderAttribute.cs | 20 + .../ScrollAnimationBehavior.cs | 124 + .../Gestor.Common/Gestor.Common.Security/Token.cs | 148 + .../Gestor.Common.Validation/SemValicao.cs | 18 + .../Gestor.Common.Validation/ValidacaoAno.cs | 27 + .../ValidacaoAnoObrigatorio.cs | 31 + .../ValidacaoCeiObrigatorio.cs | 31 + .../Gestor.Common.Validation/ValidacaoCep.cs | 27 + .../ValidacaoCepObrigatorio.cs | 31 + .../Gestor.Common.Validation/ValidacaoChassi.cs | 27 + .../ValidacaoChassiObrigatorio.cs | 31 + .../Gestor.Common.Validation/ValidacaoData.cs | 27 + .../ValidacaoDataFutura.cs | 27 + .../Gestor.Common.Validation/ValidacaoDataMaior.cs | 38 + .../ValidacaoDataObrigatoria.cs | 31 + .../ValidacaoDataPassada.cs | 27 + .../ValidacaoDataPassadaObrigatoria.cs | 31 + .../Gestor.Common.Validation/ValidacaoDocumento.cs | 27 + .../ValidacaoDocumentoObrigatorio.cs | 31 + .../Gestor.Common.Validation/ValidacaoDouble.cs | 27 + .../Gestor.Common.Validation/ValidacaoEmail.cs | 27 + .../ValidacaoEmailObrigatorio.cs | 31 + .../Gestor.Common.Validation/ValidacaoEstado.cs | 27 + .../ValidacaoEstadoObrigatorio.cs | 31 + .../ValidacaoFipeObrigatorio.cs | 31 + .../Gestor.Common.Validation/ValidacaoInt.cs | 27 + .../ValidacaoIntObrigatorio.cs | 31 + .../Gestor.Common.Validation/ValidacaoLong.cs | 27 + .../ValidacaoLongObrigatorio.cs | 31 + .../ValidacaoObrigatorio.cs | 27 + .../Gestor.Common.Validation/ValidacaoOrgao.cs | 27 + .../Gestor.Common.Validation/ValidacaoPlaca.cs | 27 + .../ValidacaoPlacaObrigatorio.cs | 31 + .../Gestor.Common.Validation/ValidacaoPrefixo.cs | 27 + .../ValidacaoPrefixoObrigatorio.cs | 31 + .../ValidacaoRneObrigatorio.cs | 31 + .../Gestor.Common.Validation/ValidacaoTelefone.cs | 27 + .../ValidacaoTelefoneObrigatorio.cs | 31 + .../ValidacaoValorDiferenteZero.cs | 31 + .../ValidacaoValorMaiorQueZero.cs | 31 + .../Gestor.Common.Validation/ValidationHelper.cs | 992 ++ Codemerx/Gestor.Common/Gestor.Common.csproj | 490 + Codemerx/Gestor.Common/Gestor.Common.sln | 21 + .../Gestor.CommonReferences/Gestor.Model.dll | Bin 0 -> 833808 bytes Codemerx/Gestor.Common/Properties/AssemblyInfo.cs | 20 + .../57a0321b-2dd7-4d59-adab-1ed08962f43e.vsidx | Bin 0 -> 637227 bytes .../.vs/Gestor.Infrastructure/v18/.suo | Bin 0 -> 176640 bytes .../v18/DocumentLayout.backup.json | 12 + .../Gestor.Infrastructure/v18/DocumentLayout.json | 37 + .../ConfigurationFileCache.cs | 133 + .../SessionFactory.cs | 144 + .../VinculoDocumentoDb.cs | 31 + .../AtividadeDb.cs | 25 + .../AtualizacaoDb.cs | 24 + .../BancoDb.cs | 36 + .../ControleArquivoDigitalDb.cs | 25 + .../EmpresaDb.cs | 189 + .../IndiceArquivoDigitalDb.cs | 181 + .../ModeloMalaDiretaDb.cs | 25 + .../ProfissaoDb.cs | 31 + .../RegistroAcaoDb.cs | 81 + .../RegistroLogDb.cs | 81 + .../SocioDb.cs | 62 + .../ConfiguracaoSistemaDb.cs | 20 + .../AgendaDb.cs | 67 + .../AgendaEmailDb.cs | 19 + .../AgendaTelefoneDb.cs | 25 + .../CategoriaTarefaDb.cs | 19 + .../CredencialDb.cs | 104 + .../FaseDb.cs | 37 + .../ImpostoDb.cs | 56 + .../LogEmailDb.cs | 105 + .../NotaFiscalDb.cs | 74 + .../OrigemClienteDb.cs | 32 + .../ReciboDb.cs | 68 + .../ResponsavelTarefaDb.cs | 26 + .../StatusDeProspeccaoDb.cs | 37 + .../TarefaDb.cs | 123 + .../TipoDeTarefaDb.cs | 37 + .../TrilhaDb.cs | 44 + .../VinculoRepasseDb.cs | 38 + .../BancosContasDb.cs | 56 + .../CentroDb.cs | 31 + .../ControleFinanceiroDb.cs | 43 + .../FornecedorDb.cs | 110 + .../LancamentoDb.cs | 116 + .../PlanoDb.cs | 25 + .../PlanosDb.cs | 45 + .../SaldoDb.cs | 49 + .../EmailBase.cs | 20 + .../EnderecoBase.cs | 54 + .../EntityBase.cs | 18 + .../TelefoneBase.cs | 31 + .../ParametrosRelatorioDb.cs | 56 + .../ParametrosTotalizacaoDb.cs | 44 + .../AdiantamentoDb.cs | 56 + .../AeronauticoDb.cs | 110 + .../AutoDb.cs | 218 + .../ClienteDb.cs | 213 + .../ClienteEmailDb.cs | 31 + .../ClienteEnderecoDb.cs | 31 + .../ClienteTelefoneDb.cs | 31 + .../ClienteVinculoDb.cs | 32 + .../CoberturaDb.cs | 49 + .../CoberturaGranizoDb.cs | 61 + .../CoberturaPadraoDb.cs | 31 + .../CondicaoRepasseDb.cs | 31 + .../ConfigExtratoImportDb.cs | 37 + .../ConsorcioDb.cs | 49 + .../ControleDb.cs | 62 + .../ControleSinistroDb.cs | 25 + .../CriticaApoliceDb.cs | 67 + .../DetalheExtratoDb.cs | 110 + .../DocumentoDb.cs | 321 + .../EstipulanteDb.cs | 86 + .../ExpedicaoDb.cs | 73 + .../ExtratoDb.cs | 98 + .../FabricanteDb.cs | 24 + .../FaturaDb.cs | 43 + .../GranizoDb.cs | 55 + .../ItemDb.cs | 105 + .../MaisContatoDb.cs | 123 + .../MetaSeguradoraDb.cs | 56 + .../MetaVendedorDb.cs | 38 + .../ParceiroDb.cs | 128 + .../ParcelaDb.cs | 212 + .../PatrimonialDb.cs | 140 + .../PerfilCondominioDb.cs | 11 + .../PerfilDb.cs | 170 + .../PerfilEmpresaDb.cs | 116 + .../PermissaoArquivoDigitalDb.cs | 44 + .../PermissaoUsuarioDb.cs | 50 + .../ProdutoDb.cs | 25 + .../ProspeccaoDb.cs | 159 + .../QualificacaoDb.cs | 67 + .../RamoDb.cs | 49 + .../RepasseDb.cs | 74 + .../ResponsavelAssinaturaDb.cs | 37 + .../RestricaoUsuarioCamposRelatoriosDb.cs | 38 + .../RestricaoUsuarioDb.cs | 32 + .../RiscosDiversosDb.cs | 43 + .../SeguradoraContatoDb.cs | 45 + .../SeguradoraDb.cs | 121 + .../SeguradoraEnderecoDb.cs | 33 + .../SinistroAutoDb.cs | 110 + .../SinistroDb.cs | 152 + .../SinistroVidaDb.cs | 56 + .../StatusDb.cs | 25 + .../TipoContaDb.cs | 25 + .../TipoVendedorDb.cs | 25 + .../TitularesVidaDb.cs | 98 + .../UsuarioDb.cs | 267 + .../VendedorDb.cs | 98 + .../VendedorParcelaDb.cs | 103 + .../VendedorTelefoneDb.cs | 31 + .../VendedorUsuarioDb.cs | 25 + .../VidaDb.cs | 55 + .../Gestor.Infrastructure.Helpers/Auxiliar.cs | 2068 +++ .../AuxiliarFinanceiro.cs | 127 + .../Gestor.Infrastructure.Helpers/Comparador.cs | 38 + .../Gestor.Infrastructure.Helpers/Funcoes.cs | 1403 ++ .../QueryableHelper.cs | 48 + .../SqlDataReaderHelper.cs | 66 + .../ApplicationMapper.cs | 123 + .../Gestor.Infrastructure.Mappers/CustomMap.cs | 1185 ++ .../VinculoDocumentoMap.cs | 22 + .../AtividadeMap.cs | 21 + .../AtualizacaoMap.cs | 19 + .../BancoMap.cs | 21 + .../ControleArquivoDigitalMap.cs | 21 + .../EmpresaMap.cs | 53 + .../IndiceArquivoDigitalMap.cs | 47 + .../ModeloMalaDiretaMap.cs | 21 + .../ProfissaoMap.cs | 22 + .../RegistroAcaoMap.cs | 31 + .../RegistroLogMap.cs | 31 + .../SocioMap.cs | 25 + .../ConfiguracaoSistemaMap.cs | 20 + .../AgendaEmailMap.cs | 21 + .../AgendaMap.cs | 28 + .../AgendaTelefoneMap.cs | 24 + .../CategoriaTarefaMap.cs | 20 + .../CredencialMap.cs | 34 + .../FaseMap.cs | 23 + .../ImpostoMap.cs | 27 + .../LogEmailMap.cs | 34 + .../NotaFiscalMap.cs | 30 + .../OrigemClienteMap.cs | 23 + .../ReciboMap.cs | 28 + .../ResponsavelTarefaMap.cs | 22 + .../StatusProspeccaoMap.cs | 23 + .../TarefaMap.cs | 38 + .../TipoTarefaMap.cs | 23 + .../TrilhaMap.cs | 24 + .../VinculoRepasseMap.cs | 24 + .../BancosContasMap.cs | 27 + .../CentroMap.cs | 22 + .../ControleFinanceiroMap.cs | 24 + .../FornecedorMap.cs | 42 + .../LancamentoMap.cs | 36 + .../PlanoMap.cs | 21 + .../PlanosMap.cs | 25 + .../SaldoMap.cs | 25 + .../TipoContaMap.cs | 21 + .../ParametrosRelatorioMap.cs | 26 + .../ParametrosTotalizacaoMap.cs | 24 + .../AdiantamentoMap.cs | 26 + .../AeronauticoMap.cs | 35 + .../AutoMap.cs | 51 + .../ClienteEmailMap.cs | 23 + .../ClienteEnderecoMap.cs | 29 + .../ClienteMap.cs | 53 + .../ClienteTelefoneMap.cs | 25 + .../ClienteVinculoMap.cs | 22 + .../CoberturaGranizoMap.cs | 27 + .../CoberturaMap.cs | 25 + .../CoberturaPadraoMap.cs | 22 + .../CondicaoRepasseMap.cs | 22 + .../ConfigExtratoImportMap.cs | 23 + .../ConsorcioMap.cs | 25 + .../ControleMap.cs | 27 + .../ControleSinistroMap.cs | 21 + .../CriticaApoliceMap.cs | 28 + .../DetalheExtratoMap.cs | 35 + .../DocumentoMap.cs | 70 + .../EstipulanteMap.cs | 38 + .../ExpedicaoMap.cs | 29 + .../ExtratoMap.cs | 33 + .../FabricanteMap.cs | 19 + .../FaturaMap.cs | 24 + .../GranizoMap.cs | 33 + .../ItemMap.cs | 33 + .../MaisContatoMap.cs | 38 + .../MetaSeguradoraMap.cs | 26 + .../MetaVendedorMap.cs | 23 + .../ParceiroMap.cs | 37 + .../ParcelaMap.cs | 52 + .../PatrimonialMap.cs | 47 + .../PerfilEmpresaMap.cs | 36 + .../PerfilMap.cs | 45 + .../PermissaoArquivoDigitalMap.cs | 24 + .../PermissaoUsuarioMap.cs | 25 + .../ProdutoMap.cs | 21 + .../ProspeccaoMap.cs | 44 + .../QualificacaoMap.cs | 28 + .../RamoMap.cs | 25 + .../RepasseMap.cs | 29 + .../ResponsavelAssinaturaMap.cs | 23 + .../RestricaoUsuarioCamposRelatoriosMap.cs | 23 + .../RestricaoUsuarioMap.cs | 22 + .../RiscosDiversosMap.cs | 24 + .../SeguradoraContatoMap.cs | 28 + .../SeguradoraEnderecoMap.cs | 30 + .../SeguradoraMap.cs | 37 + .../SinistroAutoMap.cs | 35 + .../SinistroMap.cs | 42 + .../SinistroVidaMap.cs | 26 + .../StatusMap.cs | 21 + .../TipoContaMap.cs | 21 + .../TipoVendedorMap.cs | 21 + .../TitularesVidaMap.cs | 33 + .../UsuarioMap.cs | 69 + .../VendedorMap.cs | 34 + .../VendedorParcelaMap.cs | 34 + .../VendedorTelefoneMap.cs | 25 + .../VendedorUsuarioMap.cs | 21 + .../VidaMap.cs | 26 + .../GenericRepository_T_.cs | 90 + .../IGenericRepository_TEntity_.cs | 31 + .../IAdiantamentoRepository.cs | 31 + .../IAeronauticoRepository.cs | 23 + .../IAgendaEmailRepository.cs | 29 + .../IAgendaRepository.cs | 25 + .../IAgendaTelefoneRepository.cs | 29 + .../IAtividadeRepository.cs | 19 + .../IAtualizacaoRepository.cs | 11 + .../IAutoRepository.cs | 31 + .../IBancoRepository.cs | 23 + .../IBancosContasRepository.cs | 23 + .../ICategoriaTarefaRepository.cs | 18 + .../ICentroRepository.cs | 19 + .../IClienteEmailRepository.cs | 31 + .../IClienteEnderecoRepository.cs | 29 + .../IClienteRepository.cs | 72 + .../IClienteTelefoneRepository.cs | 31 + .../IClienteVinculoRepository.cs | 25 + .../ICoberturaGranizoRepository.cs | 21 + .../ICoberturaPadraoRepository.cs | 23 + .../ICoberturaRepository.cs | 29 + .../ICondicaoRepasseRepository.cs | 18 + .../IConfigExtratoImportRepository.cs | 27 + .../IConfiguracaoRepository.cs | 22 + .../IConsorcioRepository.cs | 23 + .../IControleFinanceiroRepository.cs | 21 + .../IControleRepository.cs | 23 + .../IControleSinistroRepository.cs | 27 + .../ICredencialRepository.cs | 23 + .../ICriticaApoliceRepository.cs | 33 + .../IDetalheExtratoRepository.cs | 25 + .../IDocumentoRepository.cs | 68 + .../IEmpresaRepository.cs | 32 + .../IEstipulanteRepository.cs | 23 + .../IExpedicaoRepository.cs | 19 + .../IExtratoRepository.cs | 31 + .../IFabricanteRepository.cs | 23 + .../IFornecedorRepository.cs | 23 + .../IGranizoRepository.cs | 23 + .../IImpostoRepository.cs | 23 + .../IIndiceArquivoDigitalRepository.cs | 34 + .../IItemRepository.cs | 44 + .../ILancamentoRepository.cs | 55 + .../IMaisContatoRepository.cs | 27 + .../IMetaSeguradoraRepository.cs | 24 + .../IMetaVendedorRepository.cs | 24 + .../IModeloMalaDiretaRepository.cs | 21 + .../INotaFiscalRepository.cs | 24 + .../IParametrosRelatorioRepository.cs | 20 + .../IParametrosTotalizacaoRepository.cs | 20 + .../IParceiroRepository.cs | 25 + .../IParcelaRepository.cs | 67 + .../IPatrimonialRepository.cs | 29 + .../IPerfilEmpresaRepository.cs | 20 + .../IPerfilRepository.cs | 23 + .../IPermissaoArquivoDigitalRepository.cs | 18 + .../IPermissaoUsuarioRepository.cs | 18 + .../IPlanoRepository.cs | 19 + .../IPlanosRepository.cs | 23 + .../IProdutoRepository.cs | 23 + .../IProfissaoRepository.cs | 19 + .../IProspectRepository.cs | 35 + .../IQualificacaoRepository.cs | 16 + .../IRamoRepository.cs | 25 + .../IReciboRepository.cs | 23 + .../IRegistroAcaoRepository.cs | 25 + .../IRegistroLogRepository.cs | 41 + .../IRepasseRepository.cs | 33 + .../IReportRepository.cs | 16 + .../IRestricaoUsuarioCamposRelatoriosRepository.cs | 15 + .../IRestricaoUsuarioRepository.cs | 18 + .../IRiscosDiversosRepository.cs | 23 + .../ISaldoRepository.cs | 27 + .../ISeguradoraContatoRepository.cs | 25 + .../ISeguradoraEnderecoRepository.cs | 23 + .../ISeguradoraRepository.cs | 25 + .../ISinistroAutoRepository.cs | 22 + .../ISinistroRepository.cs | 30 + .../ISinistroVidaRepository.cs | 20 + .../ISocioRepository.cs | 23 + .../IStatusProspeccaoRepository.cs | 16 + .../IStatusRepository.cs | 23 + .../ITarefaRepository.cs | 69 + .../ITipoContaRepository.cs | 16 + .../ITipoTarefaRepository.cs | 16 + .../ITipoVendedorRepository.cs | 29 + .../ITitularesVidaRepository.cs | 23 + .../IUsuarioRepository.cs | 41 + .../IVendedorParcelaRepository.cs | 45 + .../IVendedorRepository.cs | 27 + .../IVendedorTelefoneRepository.cs | 27 + .../IVendedorUsuarioRepository.cs | 27 + .../IVidaRepository.cs | 23 + .../IVinculoDocumentoRepository.cs | 25 + .../AdiantamentoRepository.cs | 168 + .../AeronauticoRepository.cs | 71 + .../AgendaEmailRepository.cs | 151 + .../AgendaRepository.cs | 86 + .../AgendaTelefoneRepository.cs | 149 + .../AtividadeRepository.cs | 92 + .../AtualizacaoRepository.cs | 44 + .../AutoRepository.cs | 607 + .../BancoRepository.cs | 69 + .../BancosContasRepository.cs | 119 + .../CategoriaTarefaRepository.cs | 46 + .../CentroRepository.cs | 96 + .../ClienteEmailRepository.cs | 248 + .../ClienteEnderecoRepository.cs | 223 + .../ClienteRepository.cs | 3102 ++++ .../ClienteTelefoneRepository.cs | 220 + .../ClienteVinculoRepository.cs | 112 + .../CoberturaGranizoRepository.cs | 65 + .../CoberturaPadraoRepository.cs | 70 + .../CoberturaRepository.cs | 174 + .../CondicaoRepasseRepository.cs | 46 + .../ConfigExtratoImportRepository.cs | 101 + .../ConfiguracaoRepository.cs | 61 + .../ConsorcioRepository.cs | 66 + .../ControleFinanceiroRepository.cs | 73 + .../ControleRepository.cs | 68 + .../ControleSinistroRepository.cs | 161 + .../CredencialRepository.cs | 75 + .../CriticaApoliceRepository.cs | 315 + .../DetalheExtratoRepository.cs | 99 + .../DocumentoRepository.cs | 5095 +++++++ .../EmpresaRepository.cs | 143 + .../EstipulanteRepository.cs | 93 + .../ExpedicaoRepository.cs | 55 + .../ExtratoRepository.cs | 237 + .../FabricanteRepository.cs | 65 + .../FornecedorRepository.cs | 103 + .../GranizoRepository.cs | 71 + .../ImpostoRepository.cs | 102 + .../IndiceArquivoDigitalRepository.cs | 402 + .../ItemRepository.cs | 1450 ++ .../LancamentoRepository.cs | 345 + .../MaisContatoRepository.cs | 158 + .../MetaSeguradoraRepository.cs | 127 + .../MetaVendedorRepository.cs | 125 + .../ModeloMalaDiretaRepository.cs | 59 + .../NotaFiscalRepository.cs | 131 + .../ParametrosRelatorioRepository.cs | 111 + .../ParametrosTotalizacaoRepository.cs | 59 + .../ParceiroRepository.cs | 108 + .../ParcelaRepository.cs | 4562 ++++++ .../PatrimonialRepository.cs | 251 + .../PerfilEmpresaRepository.cs | 64 + .../PerfilRepository.cs | 191 + .../PermissaoArquivoDigitalRepository.cs | 54 + .../PermissaoUsuarioRepository.cs | 84 + .../PlanoRepository.cs | 93 + .../PlanosRepository.cs | 101 + .../ProdutoRepository.cs | 76 + .../ProfissaoRepository.cs | 92 + .../ProspectRepository.cs | 245 + .../QualificacaoRepository.cs | 38 + .../RamoRepository.cs | 85 + .../ReciboRepository.cs | 71 + .../RegistroAcaoRepository.cs | 183 + .../RegistroLogRepository.cs | 222 + .../RepasseRepository.cs | 298 + .../ReportRepository.cs | 1991 +++ .../RestricaoUsuarioCamposRelatoriosRepository.cs | 44 + .../RestricaoUsuarioRepository.cs | 54 + .../RiscosDiversosRepository.cs | 66 + .../SaldoRepository.cs | 136 + .../SeguradoraContatoRepository.cs | 131 + .../SeguradoraEnderecoRepository.cs | 97 + .../SeguradoraRepository.cs | 76 + .../SinistroAutoRepository.cs | 61 + .../SinistroRepository.cs | 415 + .../SinistroVidaRepository.cs | 56 + .../SocioRepository.cs | 75 + .../StatusProspeccaoRepository.cs | 54 + .../StatusRepository.cs | 76 + .../TarefaRepository.cs | 462 + .../TipoContaRepository.cs | 52 + .../TipoTarefaRepository.cs | 54 + .../TipoVendedorRepository.cs | 139 + .../TitularesVidaRepository.cs | 152 + .../UsuarioRepository.cs | 305 + .../VendedorParcelaRepository.cs | 474 + .../VendedorRepository.cs | 132 + .../VendedorTelefoneRepository.cs | 115 + .../VendedorUsuarioRepository.cs | 94 + .../VidaRepository.cs | 66 + .../VinculoDocumentoRepository.cs | 345 + .../Gestor.Infrastructure.Types/CustomBoolType.cs | 150 + .../CustomEnumType2_T_.cs | 163 + .../CustomEnumType_T_.cs | 163 + .../Gestor.Infrastructure.Types/CustomIntType.cs | 150 + .../GenericUnitOfWork.cs | 148 + .../IGenericUnitOfWork.cs | 19 + .../IUnitOfWork.cs | 343 + .../UnitOfWork.cs | 1069 ++ .../Gestor.Infrastructure.csproj | 1717 +++ .../Gestor.Infrastructure.sln | 21 + .../Gestor.InfrastructureReferences/AutoMapper.dll | Bin 0 -> 273920 bytes .../FluentNHibernate.dll | Bin 0 -> 557056 bytes .../Gestor.Common.dll | Bin 0 -> 68368 bytes .../Gestor.Model.dll | Bin 0 -> 833808 bytes .../Gestor.InfrastructureReferences/NHibernate.dll | Bin 0 -> 3358208 bytes .../Properties/AssemblyInfo.cs | 22 + ...NETFramework,Version=v4.8.AssemblyAttributes.cs | 4 + .../DesignTimeResolveAssemblyReferencesInput.cache | Bin 0 -> 2183 bytes ...r.Infrastructure.csproj.AssemblyReference.cache | Bin 0 -> 11034 bytes ...r.Infrastructure.csproj.CoreCompileInputs.cache | 1 + ...stor.Infrastructure.csproj.FileListAbsolute.txt | 2 + Codemerx/Gestor.Model/Gestor.Model.csproj | 1644 +++ Codemerx/Gestor.Model/Gestor.Model.sln | 21 + .../Gestor.ModelReferences/Newtonsoft.Json.dll | Bin 0 -> 701992 bytes Codemerx/Gestor.Model/Model.API/Access.cs | 67 + Codemerx/Gestor.Model/Model.API/AccessControl.cs | 42 + Codemerx/Gestor.Model/Model.API/AjudaTela.cs | 55 + Codemerx/Gestor.Model/Model.API/Attachment.cs | 30 + Codemerx/Gestor.Model/Model.API/AuthSso.cs | 24 + .../Gestor.Model/Model.API/ConnectionAddress.cs | 114 + Codemerx/Gestor.Model/Model.API/Customer.cs | 127 + .../Gestor.Model/Model.API/CustomerAttendance.cs | 37 + Codemerx/Gestor.Model/Model.API/CustomerData.cs | 42 + .../Gestor.Model/Model.API/HorarioAtendimento.cs | 48 + Codemerx/Gestor.Model/Model.API/LogError.cs | 126 + Codemerx/Gestor.Model/Model.API/Owner.cs | 54 + Codemerx/Gestor.Model/Model.API/Parameters.cs | 48 + Codemerx/Gestor.Model/Model.API/Payment.cs | 67 + Codemerx/Gestor.Model/Model.API/TipoErro.cs | 1014 ++ Codemerx/Gestor.Model/Model.API/TokenSso.cs | 36 + Codemerx/Gestor.Model/Model.API/UploadFile.cs | 61 + Codemerx/Gestor.Model/Model.API/UserSso.cs | 78 + .../Model.API/UsuarioCentralSegurado.cs | 112 + Codemerx/Gestor.Model/Model.API/Version.cs | 60 + .../Model.Attributes/EntityAttribute.cs | 40 + .../Model.Attributes/ForceLogAttribute.cs | 39 + .../Gestor.Model/Model.Attributes/HelpAttribute.cs | 40 + .../Gestor.Model/Model.Attributes/LogAttribute.cs | 40 + .../Gestor.Model/Model.Attributes/NameAttribute.cs | 40 + .../Model.Attributes/OldValue2Attribute.cs | 20 + .../Model.Attributes/OldValueAttribute.cs | 20 + .../Gestor.Model/Model.Attributes/TipoAttribute.cs | 40 + .../Model.Attributes/WidthAttribute.cs | 40 + .../Model.CalculoWeb/Auto/CalculoAuto.cs | 61 + .../Gestor.Model/Model.CalculoWeb/Auto/Caminhao.cs | 78 + .../Model.CalculoWeb/Auto/CoberturaAuto.cs | 132 + .../Model.CalculoWeb/Auto/ComissaoSeguradora.cs | 24 + .../Model.CalculoWeb/Auto/CondutorPrincipal.cs | 127 + .../Gestor.Model/Model.CalculoWeb/Auto/Fipe.cs | 84 + .../Model.CalculoWeb/Auto/QuestionarioAuto.cs | 90 + .../Gestor.Model/Model.CalculoWeb/Auto/Veiculo.cs | 217 + Codemerx/Gestor.Model/Model.CalculoWeb/Calculo.cs | 73 + .../Condominio/CalculoCondominio.cs | 44 + .../Condominio/CoberturaCondominio.cs | 186 + .../Condominio/QuestionarioCondominio.cs | 96 + .../Model.CalculoWeb/Empresa/CalculoEmpresa.cs | 43 + .../Model.CalculoWeb/Empresa/CoberturaEmpresa.cs | 186 + .../Model.CalculoWeb/Empresa/EnderecoEmpresa.cs | 60 + .../Empresa/QuestionarioEmpresa.cs | 115 + .../Residencia/CalculoResidencia.cs | 43 + .../Residencia/CoberturaResidencia.cs | 138 + .../Residencia/EnderecoResidencia.cs | 60 + .../Model.CalculoWeb/Residencia/Imovel.cs | 42 + .../Residencia/QuestionarioResidencia.cs | 66 + .../Gestor.Model/Model.CalculoWeb/Resultados.cs | 18 + Codemerx/Gestor.Model/Model.CalculoWeb/Segurado.cs | 158 + Codemerx/Gestor.Model/Model.CalculoWeb/Seguro.cs | 110 + Codemerx/Gestor.Model/Model.CalculoWeb/Telefone.cs | 30 + Codemerx/Gestor.Model/Model.CalculoWeb/Usuario.cs | 18 + .../VidaGlobal/CalculoVidaGlobal.cs | 44 + .../VidaGlobal/CoberturaVidaGlobal.cs | 66 + .../VidaGlobal/QuestionarioVidaGlobal.cs | 37 + .../VidaIndividual/CalculoVidaIndividual.cs | 44 + .../VidaIndividual/CoberturaVidaIndividual.cs | 108 + .../Model.CalculoWeb/VidaIndividual/Profissao.cs | 36 + .../VidaIndividual/QuestionarioVidaIndividual.cs | 67 + .../Gestor.Model/Model.Common/AcessoApolice.cs | 17 + Codemerx/Gestor.Model/Model.Common/Agrupamento.cs | 23 + Codemerx/Gestor.Model/Model.Common/Antifurto.cs | 30 + .../Gestor.Model/Model.Common/AtividadeEmpresa.cs | 129 + .../Gestor.Model/Model.Common/BandeiraCartao.cs | 33 + Codemerx/Gestor.Model/Model.Common/BaseRepasse.cs | 27 + Codemerx/Gestor.Model/Model.Common/Categoria.cs | 51 + Codemerx/Gestor.Model/Model.Common/Combustivel.cs | 60 + Codemerx/Gestor.Model/Model.Common/Condicao.cs | 43 + Codemerx/Gestor.Model/Model.Common/Configuracao.cs | 179 + .../Model.Common/ConfiguracaoImpressao.cs | 32 + Codemerx/Gestor.Model/Model.Common/Cor.cs | 63 + Codemerx/Gestor.Model/Model.Common/Correcao.cs | 18 + .../Gestor.Model/Model.Common/DistanciaTrabalho.cs | 30 + .../Model.Common/EquipamentoIncendio.cs | 19 + .../Model.Common/EquipamentoSeguranca.cs | 19 + Codemerx/Gestor.Model/Model.Common/EstadoCivil.cs | 36 + .../Model.Common/FiltroArquivoDigital.cs | 36 + .../Gestor.Model/Model.Common/FiltroCritica.cs | 15 + .../Gestor.Model/Model.Common/FiltroLancamento.cs | 23 + .../Model.Common/FiltroLancamentoData.cs | 17 + .../Model.Common/FiltroStatusDocumento.cs | 21 + .../Gestor.Model/Model.Common/FormaPagamento.cs | 63 + Codemerx/Gestor.Model/Model.Common/FormaRepasse.cs | 21 + .../Gestor.Model/Model.Common/GaragemResidencia.cs | 27 + .../Model.Common/GaragemTrabalhoEstudo.cs | 30 + Codemerx/Gestor.Model/Model.Common/Isencao.cs | 24 + Codemerx/Gestor.Model/Model.Common/Localizacao.cs | 30 + .../Gestor.Model/Model.Common/ManutencaoItem.cs | 25 + Codemerx/Gestor.Model/Model.Common/Mes.cs | 48 + Codemerx/Gestor.Model/Model.Common/Negocio.cs | 18 + .../Gestor.Model/Model.Common/NegocioCorretora.cs | 18 + Codemerx/Gestor.Model/Model.Common/Ocupacao.cs | 30 + Codemerx/Gestor.Model/Model.Common/Operacao.cs | 13 + Codemerx/Gestor.Model/Model.Common/Operador.cs | 29 + Codemerx/Gestor.Model/Model.Common/Parentesco.cs | 99 + .../Gestor.Model/Model.Common/ParentescoVinculo.cs | 84 + .../Model.Common/PermissaoAggilizador.cs | 19 + Codemerx/Gestor.Model/Model.Common/Rastreador.cs | 66 + Codemerx/Gestor.Model/Model.Common/Relacao.cs | 42 + Codemerx/Gestor.Model/Model.Common/Relatorio.cs | 132 + Codemerx/Gestor.Model/Model.Common/Sexo.cs | 20 + Codemerx/Gestor.Model/Model.Common/Sinal.cs | 18 + .../Model.Common/SinteticoFinanceiroTipo.cs | 21 + .../Gestor.Model/Model.Common/SqlQueryCondition.cs | 26 + .../Gestor.Model/Model.Common/StatusAssinatura.cs | 21 + .../Gestor.Model/Model.Common/StatusCalculo.cs | 25 + .../Model.Common/StatusDocumentoAssinado.cs | 49 + .../Gestor.Model/Model.Common/StatusExtrato.cs | 23 + Codemerx/Gestor.Model/Model.Common/StatusItem.cs | 12 + .../Gestor.Model/Model.Common/StatusLancamento.cs | 17 + .../Gestor.Model/Model.Common/StatusPagamento.cs | 17 + .../Gestor.Model/Model.Common/StatusParcela.cs | 75 + .../Gestor.Model/Model.Common/StatusProspeccao.cs | 27 + .../Gestor.Model/Model.Common/StatusSinistro.cs | 27 + Codemerx/Gestor.Model/Model.Common/StatusTarefa.cs | 17 + Codemerx/Gestor.Model/Model.Common/SubTipo.cs | 30 + .../Gestor.Model/Model.Common/TabelaReferencia.cs | 18 + .../Gestor.Model/Model.Common/TempoHabilitacao.cs | 45 + Codemerx/Gestor.Model/Model.Common/TipoAcao.cs | 17 + .../Gestor.Model/Model.Common/TipoAeronautico.cs | 120 + .../Model.Common/TipoArquivoDigital.cs | 47 + .../Model.Common/TipoArquivoVinculo.cs | 10 + .../Gestor.Model/Model.Common/TipoCobertura.cs | 27 + .../Gestor.Model/Model.Common/TipoConstrucao.cs | 24 + Codemerx/Gestor.Model/Model.Common/TipoConta.cs | 17 + Codemerx/Gestor.Model/Model.Common/TipoContato.cs | 10 + .../Model.Common/TipoContatoSeguradora.cs | 17 + .../Gestor.Model/Model.Common/TipoDocumento.cs | 24 + Codemerx/Gestor.Model/Model.Common/TipoEmail.cs | 17 + Codemerx/Gestor.Model/Model.Common/TipoEndereco.cs | 33 + Codemerx/Gestor.Model/Model.Common/TipoEndosso.cs | 27 + Codemerx/Gestor.Model/Model.Common/TipoExtrato.cs | 17 + .../Gestor.Model/Model.Common/TipoFiltroBusca.cs | 15 + .../Gestor.Model/Model.Common/TipoFiltroCliente.cs | 17 + .../Model.Common/TipoFiltroFinanceiro.cs | 21 + .../Model.Common/TipoFiltroRelatorio.cs | 27 + .../Gestor.Model/Model.Common/TipoIncidencia.cs | 18 + .../Model.Common/TipoIncidenciaDesconto.cs | 15 + .../Gestor.Model/Model.Common/TipoManutencao.cs | 19 + Codemerx/Gestor.Model/Model.Common/TipoMoradia.cs | 15 + .../Gestor.Model/Model.Common/TipoPagamento.cs | 63 + .../Gestor.Model/Model.Common/TipoPavimentacao.cs | 21 + Codemerx/Gestor.Model/Model.Common/TipoPerda.cs | 27 + Codemerx/Gestor.Model/Model.Common/TipoPesquisa.cs | 49 + .../Model.Common/TipoProtocoloEtiqueta.cs | 15 + .../Gestor.Model/Model.Common/TipoRecebimento.cs | 18 + Codemerx/Gestor.Model/Model.Common/TipoRecibo.cs | 18 + Codemerx/Gestor.Model/Model.Common/TipoRepasse.cs | 24 + .../Gestor.Model/Model.Common/TipoResidencia.cs | 24 + .../Gestor.Model/Model.Common/TipoRestricao.cs | 528 + Codemerx/Gestor.Model/Model.Common/TipoSeguro.cs | 33 + Codemerx/Gestor.Model/Model.Common/TipoSinistro.cs | 18 + Codemerx/Gestor.Model/Model.Common/TipoTarefa.cs | 29 + Codemerx/Gestor.Model/Model.Common/TipoTela.cs | 216 + .../Gestor.Model/Model.Common/TipoTelaInicial.cs | 21 + Codemerx/Gestor.Model/Model.Common/TipoTelefone.cs | 56 + Codemerx/Gestor.Model/Model.Common/TipoTitular.cs | 21 + Codemerx/Gestor.Model/Model.Common/TipoTrilha.cs | 12 + .../Model.Common/TpoSituacaoSinistro.cs | 21 + .../Gestor.Model/Model.Common/UsoDependetes.cs | 27 + Codemerx/Gestor.Model/Model.Common/UsoVeiculo.cs | 24 + Codemerx/Gestor.Model/Model.Common/Utilizacao.cs | 18 + .../Gestor.Model/Model.Common/ValidationStates.cs | 11 + .../EnumDescriptionTypeConverter.cs | 37 + .../Model.Domain.Aggilizador/ArquivoVinculo.cs | 48 + .../Model.Domain.Aggilizador/Calculo.cs | 39 + .../Model.Domain.Aggilizador/LocalArquivo.cs | 36 + .../Model.Domain.Aggilizador/ParcelaPendente.cs | 60 + .../Model.Domain.Aggilizador/VinculoDocumento.cs | 36 + Codemerx/Gestor.Model/Model.Domain.BI/Analitico.cs | 240 + .../Gestor.Model/Model.Domain.BI/AtalhosApolice.cs | 112 + .../Gestor.Model/Model.Domain.BI/AtalhosCalculo.cs | 28 + .../Gestor.Model/Model.Domain.BI/AtalhosCliente.cs | 50 + .../Model.Domain.BI/AtalhosComissao.cs | 36 + .../Gestor.Model/Model.Domain.BI/AtalhosParcela.cs | 72 + .../Model.Domain.BI/AtalhosSinistro.cs | 28 + .../Gestor.Model/Model.Domain.Card/Assistance.cs | 180 + .../Model.Domain.Card/AssistenciaCia.cs | 114 + Codemerx/Gestor.Model/Model.Domain.Card/Card.cs | 120 + Codemerx/Gestor.Model/Model.Domain.Card/Logo.cs | 42 + .../Model.Domain.Common/ArquivoDigital.cs | 213 + .../Gestor.Model/Model.Domain.Common/Atividade.cs | 50 + Codemerx/Gestor.Model/Model.Domain.Common/Banco.cs | 87 + .../Gestor.Model/Model.Domain.Common/Contato.cs | 31 + .../Model.Domain.Common/ControleArquivoDigital.cs | 25 + .../Gestor.Model/Model.Domain.Common/Empresa.cs | 546 + Codemerx/Gestor.Model/Model.Domain.Common/Fipe.cs | 138 + .../Model.Domain.Common/FipeDetalhe.cs | 24 + .../Model.Domain.Common/IndiceArquivoDigital.cs | 246 + .../Model.Domain.Common/PesquisaAvancada.cs | 55 + .../Gestor.Model/Model.Domain.Common/Profissao.cs | 69 + .../Model.Domain.Common/RegistroAcao.cs | 81 + .../Model.Domain.Common/RegistroLog.cs | 81 + Codemerx/Gestor.Model/Model.Domain.Common/Socio.cs | 159 + .../Model.Domain.Common/TrocaCliente.cs | 117 + .../ConfiguracaoSistema.cs | 20 + .../Model.Domain.Ferramentas/Agenda.cs | 178 + .../Model.Domain.Ferramentas/AgendaEmail.cs | 57 + .../Model.Domain.Ferramentas/AgendaTelefone.cs | 42 + .../Model.Domain.Ferramentas/CategoriaTarefa.cs | 19 + .../Model.Domain.Ferramentas/Credencial.cs | 278 + .../Model.Domain.Ferramentas/Destinatario.cs | 63 + .../Gestor.Model/Model.Domain.Ferramentas/Fase.cs | 44 + .../Model.Domain.Ferramentas/Imposto.cs | 177 + .../Model.Domain.Ferramentas/LogEmail.cs | 157 + .../Model.Domain.Ferramentas/LogEnvio.cs | 36 + .../ManutencaoPagamentos.cs | 361 + .../Model.Domain.Ferramentas/NotaFiscal.cs | 217 + .../Model.Domain.Ferramentas/OrigemCliente.cs | 35 + .../Model.Domain.Ferramentas/Recibo.cs | 202 + .../Model.Domain.Ferramentas/ResponsavelTarefa.cs | 54 + .../Model.Domain.Ferramentas/StatusDeProspeccao.cs | 103 + .../Model.Domain.Ferramentas/Tarefa.cs | 264 + .../Model.Domain.Ferramentas/TipoDeTarefa.cs | 103 + .../Model.Domain.Ferramentas/Trilha.cs | 122 + .../Model.Domain.Financeiro/BancosContas.cs | 195 + .../Gestor.Model/Model.Domain.Financeiro/Centro.cs | 93 + .../Model.Domain.Financeiro/ControleFinanceiro.cs | 143 + .../Model.Domain.Financeiro/ExtratoConta.cs | 97 + .../Model.Domain.Financeiro/FiltroPersonalizado.cs | 54 + .../Model.Domain.Financeiro/Fornecedor.cs | 430 + .../Model.Domain.Financeiro/Lancamento.cs | 285 + .../Gestor.Model/Model.Domain.Financeiro/Plano.cs | 68 + .../Gestor.Model/Model.Domain.Financeiro/Planos.cs | 165 + .../RelatorioLancamentos.cs | 132 + .../Relatorios/DadosFechamento.cs | 82 + .../Relatorios/DadosFechamentoAnalitico.cs | 154 + .../Relatorios/FechamentoFinanceiro.cs | 25 + .../Relatorios/FechamentoFinanceiroAnalitico.cs | 25 + .../Relatorios/FiltroFinanceiro.cs | 55 + .../Gestor.Model/Model.Domain.Financeiro/Saldo.cs | 89 + .../Model.Domain.Financeiro/SinteticoFinanceiro.cs | 60 + .../Model.Domain.Financeiro/TipoConta.cs | 62 + .../Model.Domain.Financeiro/Transferencia.cs | 76 + .../Gestor.Model/Model.Domain.Generic/Diferenca.cs | 36 + .../Model.Domain.Generic/DomainBase.cs | 1067 ++ .../Gestor.Model/Model.Domain.Generic/EmailBase.cs | 32 + .../Model.Domain.Generic/EnderecoBase.cs | 128 + .../Model.Domain.Generic/FieldInformation.cs | 30 + .../Gestor.Model/Model.Domain.Generic/IDomain.cs | 15 + .../Model.Domain.Generic/TelefoneBase.cs | 82 + .../Model.Domain.Generic/ValorOriginal.cs | 30 + .../Gestor.Model/Model.Domain.MalaDireta/Copia.cs | 25 + .../Model.Domain.MalaDireta/MalaDireta.cs | 118 + .../Model.Domain.MalaDireta/ModeloMalaDireta.cs | 53 + .../Model.Domain.MalaDireta/VariaveisMalaDireta.cs | 87 + .../ApolicePendente/ApolicePendente.cs | 244 + .../ApolicePendente/ContainerApolicePendente.cs | 32 + .../Model.Domain.Relatorios/Auditoria/Auditoria.cs | 221 + .../Model.Domain.Relatorios/CartaoSegurado.cs | 60 + .../Classificacao/Classificacao.cs | 71 + .../Cliente/SinteticoClientes.cs | 28 + .../ClientesAtivosInativos.cs | 477 + .../SinteticoClientesAtivosInativos.cs | 44 + .../Model.Domain.Relatorios/Comissao/Comissao.cs | 345 + .../Comissao/SinteticoComissao.cs | 68 + .../CriticaApolice/ApoliceCritica.cs | 123 + .../Model.Domain.Relatorios/DadosRelatorio.cs | 312 + .../Model.Domain.Relatorios/DadosVinculo.cs | 67 + .../Dashboard/Prospectar.cs | 112 + .../EndossoCancelamento/Endosso.cs | 323 + .../Extrato/DetalhesExtrato.cs | 73 + .../Model.Domain.Relatorios/Extrato/Extrato.cs | 120 + .../Extrato/ExtratoComissao.cs | 37 + .../Extrato/InformacoesExtrato.cs | 93 + .../Extrato/SinteticoExtrato.cs | 28 + .../ExtratoBaixado/ExtratoBaixadoRelatorio.cs | 127 + .../FaturaPendente/FaturaPendente.cs | 189 + .../Fechamento/Fechamento.cs | 319 + .../Fechamento/Fechamentos.cs | 31 + .../Fechamento/SinteticoFechamento.cs | 94 + .../Model.Domain.Relatorios/FiltroPersonalizado.cs | 66 + .../Model.Domain.Relatorios/FiltroRelatorio.cs | 54 + .../Model.Domain.Relatorios/FiltroTipoParcela.cs | 38 + .../Model.Domain.Relatorios/Filtros.cs | 138 + .../Licenciamento/Licenciamento.cs | 174 + .../Model.Domain.Relatorios/Listagem.cs | 33 + .../Log/LogAcaoRelatorio.cs | 145 + .../Model.Domain.Relatorios/LogsEnvio/LogsEnvio.cs | 211 + .../MetaSeguradora/MetaSeguradoraRelatorio.cs | 51 + .../MetaSeguradora/SinteticoMetaSeguradora.cs | 27 + .../MetaVendedor/MetaVendedorRelatorio.cs | 51 + .../MetaVendedor/SinteticoMetaVendedor.cs | 27 + .../Model.Domain.Relatorios/NegocioRelatorio.cs | 58 + .../NotaFiscal/NotaFiscalRelatorio.cs | 96 + .../Pagamento/AgrupamentoPagamentoSintetico.cs | 37 + .../Pagamento/AgrupamentoVendedor.cs | 113 + .../Model.Domain.Relatorios/Pagamento/Pagamento.cs | 38 + .../Pagamento/PagamentoSintetico.cs | 25 + .../Pagamento/SinteticoPagamento.cs | 60 + .../Model.Domain.Relatorios/ParametrosRelatorio.cs | 90 + .../ParametrosTotalizacao.cs | 49 + .../Model.Domain.Relatorios/Pendente/Pendente.cs | 308 + .../Pendente/SinteticoPendente.cs | 52 + .../Model.Domain.Relatorios/Placa/Placas.cs | 167 + .../Model.Domain.Relatorios/PlanilhaCompleta.cs | 1595 ++ .../AgrupamentoSintetico.cs | 37 + .../PrevisaoPagamentoComissao/PrevisaoPagamento.cs | 132 + .../PrevisaoPagamentoComissao.cs | 25 + .../PrevisaoPagamentoComissaoSintetico.cs | 25 + .../Model.Domain.Relatorios/Producao/Producao.cs | 372 + .../Producao/SinteticoProducao.cs | 68 + .../Model.Domain.Relatorios/Renovacao/Renovacao.cs | 296 + .../Renovacao/SinteticoRenovacao.cs | 76 + .../Model.Domain.Relatorios/Sinistro/Sinistro.cs | 359 + .../Sinistro/SinteticoSinistro.cs | 68 + .../Model.Domain.Relatorios/SinteticModel.cs | 30 + .../Model.Domain.Relatorios/SinteticModelList.cs | 25 + .../Model.Domain.Relatorios/Sintetico.cs | 448 + .../Model.Domain.Relatorios/SinteticoFinanceiro.cs | 37 + .../Model.Domain.Relatorios/StatusRelatorio.cs | 58 + .../Model.Domain.Relatorios/Tarefa/Tarefa.cs | 160 + .../Model.Domain.Relatorios/TipoRelatorio.cs | 30 + .../Model.Domain.Relatorios/ValorSintetico.cs | 55 + .../Model.Domain.Seguros/Adiantamento.cs | 145 + .../Model.Domain.Seguros/Aeronautico.cs | 475 + .../Model.Domain.Seguros/AggilizadorPermissao.cs | 25 + Codemerx/Gestor.Model/Model.Domain.Seguros/Auto.cs | 793 + .../Gestor.Model/Model.Domain.Seguros/Cliente.cs | 1193 ++ .../Model.Domain.Seguros/ClienteEmail.cs | 88 + .../Model.Domain.Seguros/ClienteEndereco.cs | 155 + .../Model.Domain.Seguros/ClienteTelefone.cs | 82 + .../Model.Domain.Seguros/ClienteVinculo.cs | 56 + .../Gestor.Model/Model.Domain.Seguros/Cobertura.cs | 86 + .../Model.Domain.Seguros/CoberturaGranizo.cs | 125 + .../Model.Domain.Seguros/CoberturaPadrao.cs | 67 + .../Model.Domain.Seguros/CondicaoRepasse.cs | 49 + .../Model.Domain.Seguros/ConfigExtratoImport.cs | 50 + .../Gestor.Model/Model.Domain.Seguros/Consorcio.cs | 191 + .../Gestor.Model/Model.Domain.Seguros/Controle.cs | 128 + .../Model.Domain.Seguros/ControleSinistro.cs | 118 + .../Model.Domain.Seguros/CriticaApolice.cs | 116 + .../Model.Domain.Seguros/DetalheExtrato.cs | 250 + .../Gestor.Model/Model.Domain.Seguros/Documento.cs | 1426 ++ .../Model.Domain.Seguros/Estipulante.cs | 373 + .../Gestor.Model/Model.Domain.Seguros/Expedicao.cs | 94 + .../Gestor.Model/Model.Domain.Seguros/Extrato.cs | 177 + .../Model.Domain.Seguros/Fabricante.cs | 62 + .../Gestor.Model/Model.Domain.Seguros/Granizo.cs | 247 + Codemerx/Gestor.Model/Model.Domain.Seguros/Item.cs | 505 + .../Model.Domain.Seguros/MaisContato.cs | 340 + .../Model.Domain.Seguros/MetaSeguradora.cs | 60 + .../Model.Domain.Seguros/MetaVendedor.cs | 56 + .../Gestor.Model/Model.Domain.Seguros/Parceiro.cs | 528 + .../Gestor.Model/Model.Domain.Seguros/Parcela.cs | 789 + .../Gestor.Model/Model.Domain.Seguros/Parcelas.cs | 204 + .../Model.Domain.Seguros/Patrimonial.cs | 574 + .../Gestor.Model/Model.Domain.Seguros/Perfil.cs | 275 + .../Model.Domain.Seguros/PerfilEmpresa.cs | 141 + .../PermissaoArquivoDigital.cs | 69 + .../Model.Domain.Seguros/PermissaoUsuario.cs | 57 + .../Gestor.Model/Model.Domain.Seguros/Produto.cs | 120 + .../Model.Domain.Seguros/Prospeccao.cs | 400 + .../Model.Domain.Seguros/ProspeccaoToPrint.cs | 149 + .../Model.Domain.Seguros/Qualificacao.cs | 152 + Codemerx/Gestor.Model/Model.Domain.Seguros/Ramo.cs | 165 + .../Gestor.Model/Model.Domain.Seguros/Repasse.cs | 187 + .../Model.Domain.Seguros/ResponsavelAssinatura.cs | 109 + .../Model.Domain.Seguros/RestricaoUsuario.cs | 60 + .../RestricaoUsuarioCamposRelatorios.cs | 61 + .../Model.Domain.Seguros/RiscosDiversos.cs | 130 + .../Model.Domain.Seguros/Seguradora.cs | 1804 +++ .../Model.Domain.Seguros/SeguradoraContato.cs | 90 + .../Model.Domain.Seguros/SeguradoraEndereco.cs | 115 + .../Gestor.Model/Model.Domain.Seguros/Sinistro.cs | 1132 ++ .../Model.Domain.Seguros/SinistroAuto.cs | 284 + .../Model.Domain.Seguros/SinistroVida.cs | 138 + .../Gestor.Model/Model.Domain.Seguros/Status.cs | 86 + .../Model.Domain.Seguros/TipoVendedor.cs | 138 + .../Model.Domain.Seguros/TitularesVida.cs | 269 + .../Gestor.Model/Model.Domain.Seguros/TupleList.cs | 19 + .../Gestor.Model/Model.Domain.Seguros/Usuario.cs | 872 ++ .../Gestor.Model/Model.Domain.Seguros/Vendedor.cs | 375 + .../Model.Domain.Seguros/VendedorParcela.cs | 235 + .../Model.Domain.Seguros/VendedorParcelas.cs | 162 + .../Model.Domain.Seguros/VendedorTelefone.cs | 89 + .../Model.Domain.Seguros/VendedorUsuario.cs | 51 + Codemerx/Gestor.Model/Model.Domain.Seguros/Vida.cs | 306 + .../Model.Domain.Seguros/VinculoRepasse.cs | 159 + .../Model.Domain.Seguros/VinculoVendedor.cs | 25 + .../Gestor.Model/Model.Helper/ValidationHelper.cs | 518 + Codemerx/Gestor.Model/Model.License/Instalacao.cs | 79 + Codemerx/Gestor.Model/Model.License/Licenca.cs | 42 + Codemerx/Gestor.Model/Model.License/Produto.cs | 41 + .../Gestor.Model/Model.License/StatusLicenca.cs | 19 + Codemerx/Gestor.Model/Model.Relatorios/Cliente.cs | 18 + .../Gestor.Model/Model.Relatorios/ClienteEmail.cs | 41 + .../Model.Relatorios/ClienteEndereco.cs | 191 + .../Model.Relatorios/ClienteTelefone.cs | 64 + Codemerx/Gestor.Model/Model.Relatorios/Controle.cs | 30 + .../Gestor.Model/Model.Relatorios/Documento.cs | 37 + .../Model.Relatorios/EstipulanteCliente.cs | 30 + Codemerx/Gestor.Model/Model.Relatorios/Ramo.cs | 41 + Codemerx/Gestor.Model/Model.Relatorios/Vendedor.cs | 41 + .../Model.Validation/ControleValidacao.cs | 36 + Codemerx/Gestor.Model/Model.Validation/Funcoes.cs | 167 + Codemerx/Gestor.Model/Properties/AssemblyInfo.cs | 20 + Codemerx/Properties/AssemblyInfo.cs | 30 + 1673 files changed, 304507 insertions(+) create mode 100644 Codemerx/App.config create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200219_01.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200219_02.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200219_03.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200219_04.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200219_05.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200219_06.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200311_07.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200311_08.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200403_09.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200403_10.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200403_11.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200403_12.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200403_13.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200403_14.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200403_15.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200403_16.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200403_17.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200403_18.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200403_19.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200403_20.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200403_21.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200403_22.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200403_23.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200406_24.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200406_25.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200406_26.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200408_27.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200408_28.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200408_29.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200408_30.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200408_31.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200408_32.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200419_33.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200419_34.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200430_35.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200505_36.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200505_37.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200505_38.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200505_39.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200506_40.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200512_41.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200512_42.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200512_43.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200514_44.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200514_45.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200520_46.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200520_47.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200525_48.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200527_49.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200527_50.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200612_51.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200702_52.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200709_53.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200714_54.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200714_55.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200716_56.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200730_57.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200811_58.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200817_59.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200818_60.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200820_61.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200820_62.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200820_63.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200825_64.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200831_65.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200914_66.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200915_67.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200924_68.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200925_69.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20200929_70.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20201001_71.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20201007_72.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20201007_73.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20201008_74.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20201015_75.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20201026_76.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20201027_77.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20201028_78.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20201030_79.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20201104_80.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20201112_81.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20201113_82.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20201117_83.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20201127_84.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20201127_85.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20201127_86.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20201127_87.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20201127_88.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20201127_89.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20201201_90.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20201203_91.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20201203_92.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20201210_93.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20201230_94.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210107_95.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210118_96.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210209_97.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210217_98.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210217_99.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210301_100.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210302_101.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210302_102.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210302_103.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210309_104.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210309_105.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210315_106.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210315_107 .SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210323_108.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210323_109.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210324_110.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210324_111.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210329_112.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210408_113.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210415_114 .SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210415_115 .SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210415_116.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210426_117.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210510_118.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210512_119.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210524_120.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210525_121.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210607_122.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210610_123.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210610_124.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210610_125.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210610_126.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210610_127.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210610_128.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210610_129.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210610_130.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210610_131.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210610_132.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210614_133 .SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210614_134.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210614_135.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210614_136.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210614_137.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210614_138.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210614_139.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210614_140.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210614_141.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210614_142.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210614_143.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210614_144.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210614_145.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210614_146.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210615_147.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210615_148.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210615_149.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210615_150.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210615_151.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210615_152.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210615_153.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210615_154.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210615_155.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210615_156.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210615_157.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210615_158.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210615_159.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210615_160.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210622_161.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210622_162.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210622_163.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210622_164.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210629_165.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210708_166 .SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210708_167.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210708_168 .SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210722_169.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210819_170.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210820_171.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210823_172.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210825_173.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210825_174.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210910_175.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210916_176.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20210916_177.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20211104_178.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20211223_179.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20211230_180.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20211230_181.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20220104_182.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20220105_183.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20220112_184.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20220119_185.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20220119_186.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20220131_187.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20220225_190.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20220225_191.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20220307_192.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20220315_193.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20220321_194.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20220325_195.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20220329_196.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20220330_197.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20220404_198.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20220404_199.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20220408_200.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20220413_201.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20220419_202.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20220419_203.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20220429_204.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20220502_205 .SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20220502_206 .SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20220603_207.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20220608_208.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20220726_209.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20220804_210.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20220817_211.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20220926_212 .SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20220929_213 .SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20221007_214 .SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20221018_215 .SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20221028_216.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20221110_217.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20221110_218.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20230208_219.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20230301_220.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20230308_221.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20230502_222.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20230619_223.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20230619_224.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20230705_225.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20230718_226.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20230727_227.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20230807_228 .SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20230829_229 .SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20231011_230.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20231024_231.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20231031_232.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20240131_233.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20240131_234.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20240322_235.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20240322_236.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20240325_237.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20240415_238.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20240422_239.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20240521_240.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20240522_241.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20240604_242.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20240708_243.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20240722_244.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20240723_245.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20240724_246.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20240729_247.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20240816_248.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20240821_249.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20240821_250.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20240826_251.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20240902_252.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20240919_253.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20241015_254.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20250204_255.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20250210_256.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20250307_257 .SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20250314_258 .SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20250314_259 .SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20250328_260.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20250331_261.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20250401_262 .SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20250423_263.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20250424_264.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20250425_265.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20250523_266.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20250625_267.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20250625_268.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20250728_269.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20250815_270.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20250905_271.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20250908_272.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20250909_273.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20250919_274.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20250926_275.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20251002_276.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20251010_277.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20251014_278.SQL create mode 100644 Codemerx/Gestor.Application.Migration.Files.20251030_279.SQL create mode 100644 Codemerx/Gestor.Application.csproj create mode 100644 Codemerx/Gestor.Application.sln create mode 100644 Codemerx/Gestor.Application/Actions/Actions.cs create mode 100644 Codemerx/Gestor.Application/App.cs create mode 100644 Codemerx/Gestor.Application/Componentes/CalculoControl.cs create mode 100644 Codemerx/Gestor.Application/Componentes/CoberturaView.cs create mode 100644 Codemerx/Gestor.Application/Componentes/ContasDialog.cs create mode 100644 Codemerx/Gestor.Application/Componentes/CustomIsReadOnlyControl.cs create mode 100644 Codemerx/Gestor.Application/Componentes/CustomItemControl.cs create mode 100644 Codemerx/Gestor.Application/Componentes/CustomItemValidation.cs create mode 100644 Codemerx/Gestor.Application/Componentes/CustomLegendChart.cs create mode 100644 Codemerx/Gestor.Application/Componentes/CustomPasswordBox.cs create mode 100644 Codemerx/Gestor.Application/Componentes/CustomSenhaLoginBox.cs create mode 100644 Codemerx/Gestor.Application/Componentes/CustomSeriesViewModel.cs create mode 100644 Codemerx/Gestor.Application/Componentes/DefaultDialog.cs create mode 100644 Codemerx/Gestor.Application/Componentes/DialogAdvertising.cs create mode 100644 Codemerx/Gestor.Application/Componentes/DialogAnaliticoBi.cs create mode 100644 Codemerx/Gestor.Application/Componentes/DialogAnexar.cs create mode 100644 Codemerx/Gestor.Application/Componentes/DialogCopia.cs create mode 100644 Codemerx/Gestor.Application/Componentes/DialogCopiarCliente.cs create mode 100644 Codemerx/Gestor.Application/Componentes/DialogCopiarPermissao.cs create mode 100644 Codemerx/Gestor.Application/Componentes/DialogDetalheExtrato.cs create mode 100644 Codemerx/Gestor.Application/Componentes/DialogEditarParcelas.cs create mode 100644 Codemerx/Gestor.Application/Componentes/DialogEnviarEmails.cs create mode 100644 Codemerx/Gestor.Application/Componentes/DialogExportarPermissao.cs create mode 100644 Codemerx/Gestor.Application/Componentes/DialogExtratoComissao.cs create mode 100644 Codemerx/Gestor.Application/Componentes/DialogGrafico.cs create mode 100644 Codemerx/Gestor.Application/Componentes/DialogHoster.cs create mode 100644 Codemerx/Gestor.Application/Componentes/DialogInstalacoes.cs create mode 100644 Codemerx/Gestor.Application/Componentes/DialogLogAcesso.cs create mode 100644 Codemerx/Gestor.Application/Componentes/DialogMedalha.cs create mode 100644 Codemerx/Gestor.Application/Componentes/DialogObservacao.cs create mode 100644 Codemerx/Gestor.Application/Componentes/DialogPesquisaAvancada.cs create mode 100644 Codemerx/Gestor.Application/Componentes/DialogPrint.cs create mode 100644 Codemerx/Gestor.Application/Componentes/DialogProtocolo.cs create mode 100644 Codemerx/Gestor.Application/Componentes/DialogReordenarItens.cs create mode 100644 Codemerx/Gestor.Application/Componentes/DialogSelecionarItens.cs create mode 100644 Codemerx/Gestor.Application/Componentes/DialogSenhaAdm.cs create mode 100644 Codemerx/Gestor.Application/Componentes/DialogTarefa.cs create mode 100644 Codemerx/Gestor.Application/Componentes/DialogTransferencia.cs create mode 100644 Codemerx/Gestor.Application/Componentes/DialogTrilha.cs create mode 100644 Codemerx/Gestor.Application/Componentes/DialogVinculo.cs create mode 100644 Codemerx/Gestor.Application/Componentes/ErrorDialog.cs create mode 100644 Codemerx/Gestor.Application/Componentes/GridRelatorio.cs create mode 100644 Codemerx/Gestor.Application/Componentes/Loading.cs create mode 100644 Codemerx/Gestor.Application/Componentes/NRecoHtmlToPdfConverter.cs create mode 100644 Codemerx/Gestor.Application/Componentes/PassBox.cs create mode 100644 Codemerx/Gestor.Application/Componentes/ProgressDialog.cs create mode 100644 Codemerx/Gestor.Application/Componentes/ProspeccaoDialog.cs create mode 100644 Codemerx/Gestor.Application/Componentes/VincularLancamentoDialog.cs create mode 100644 Codemerx/Gestor.Application/Componentes/WebBrowser.cs create mode 100644 Codemerx/Gestor.Application/Componentes/WebEditor.cs create mode 100644 Codemerx/Gestor.Application/Converters/ActualHeightConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/ArquivoDigitalVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/AssinaturasVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/AssistenciaVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/AtivoToColorConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/AtivoToStringConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/BaixarVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/BoletosNotasConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/BoolToGridHeightOneStarConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/CalculoIconConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/ColorStatusConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/ContatoSeguradoraVisibiltyConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/DesconsiderarVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/DiasPentendesConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/DocumentoEtiquetaConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/EmpresaNomeConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/EnderecoConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/EnviadoColorConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/EnviadoConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/EnviadoIconConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/EnviadoTooTipConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/EqualToCollapsedConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/ExcluidoStringConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/ExcluirVendedorLabelConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/ExpanderHeaderConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/ExtensaoVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/FaturaVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/FilialStringConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/IdVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/IncluirApoliceEnabledConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/IntToMedalConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/IntToMedalTextConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/IntToVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/InvertedBoolToGridHeightOneStarConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/IsNamedObjectVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/ManutencaoPagamentoGroupHeaderConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/MenosZeroVirgulaZeroUmConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/MimeIconConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/ModeloExisteTooltipConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/MultiBoolReadOnly.cs create mode 100644 Codemerx/Gestor.Application/Converters/MultiBoolToVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/MultiVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/NullToFalseConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/NullToTrueConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/PackIconToImage.cs create mode 100644 Codemerx/Gestor.Application/Converters/PackIconToImageConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/RamoToImageConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/ResultadoToBoolConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/StatusComissaoAutomaticaTooltipConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/StatusIconConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/StatusPagamentoColorConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/StatusPagamentoVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/StringToFontWeightConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/StringToStringFontWeightCleanConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/SubTipoEnableConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/TelaRelatorioConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/TelefoneToVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/TextInputToVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/TipoDependenteToVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/TipoEmailVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/TipoRepasseGlobalFilterConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/TipoRepasseVendedorVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/TipoRepasseVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/TipoSinistroConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/TipoTelefoneVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/TootipStatusConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/TypeVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/ValorTipoConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/VariavelExisteColorConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/VariavelExisteTooltipConverter.cs create mode 100644 Codemerx/Gestor.Application/Converters/VerApoliceComissaoConverter.cs create mode 100644 Codemerx/Gestor.Application/Drawers/AdiantamentoDrawerView.cs create mode 100644 Codemerx/Gestor.Application/Drawers/AgendaDrawer.cs create mode 100644 Codemerx/Gestor.Application/Drawers/Ajuda/BoletosNotasDrawerView.cs create mode 100644 Codemerx/Gestor.Application/Drawers/Ajuda/ContratosDrawerView.cs create mode 100644 Codemerx/Gestor.Application/Drawers/Ajuda/InstalacaoDrawerView.cs create mode 100644 Codemerx/Gestor.Application/Drawers/ArquivoDigitalDrawer.cs create mode 100644 Codemerx/Gestor.Application/Drawers/Configuracoes/ConfiguracoesDrawer.cs create mode 100644 Codemerx/Gestor.Application/Drawers/ExpedicaoDrawer.cs create mode 100644 Codemerx/Gestor.Application/Drawers/ExtratosDrawer.cs create mode 100644 Codemerx/Gestor.Application/Drawers/ImpostoDrawer.cs create mode 100644 Codemerx/Gestor.Application/Drawers/InclusaoArquivoDigitalDrawer.cs create mode 100644 Codemerx/Gestor.Application/Drawers/InfoDrawer.cs create mode 100644 Codemerx/Gestor.Application/Drawers/LogDrawer.cs create mode 100644 Codemerx/Gestor.Application/Drawers/LogEmailDrawer.cs create mode 100644 Codemerx/Gestor.Application/Drawers/LogSistemaAntigo.cs create mode 100644 Codemerx/Gestor.Application/Drawers/LogUtilizacaoDrawer.cs create mode 100644 Codemerx/Gestor.Application/Drawers/MetaSeguradoraView.cs create mode 100644 Codemerx/Gestor.Application/Drawers/MetaVendedorView.cs create mode 100644 Codemerx/Gestor.Application/Drawers/ObservacoesDrawer.cs create mode 100644 Codemerx/Gestor.Application/Drawers/PermissaoUsuarioDrawer.cs create mode 100644 Codemerx/Gestor.Application/Drawers/Relatorios/ConfiguracaoRelatorio.cs create mode 100644 Codemerx/Gestor.Application/Drawers/Relatorios/FiltroRelatorio.cs create mode 100644 Codemerx/Gestor.Application/Drawers/TarefaDrawer.cs create mode 100644 Codemerx/Gestor.Application/Drawers/ValoresApoliceDrawer.cs create mode 100644 Codemerx/Gestor.Application/Drawers/ValoresParcelaDrawer.cs create mode 100644 Codemerx/Gestor.Application/Drawers/VinculoVendedorDrawer.cs create mode 100644 Codemerx/Gestor.Application/Helpers/ApplicationHelper.cs create mode 100644 Codemerx/Gestor.Application/Helpers/ArquivoDigital.cs create mode 100644 Codemerx/Gestor.Application/Helpers/AssinadorHelper.cs create mode 100644 Codemerx/Gestor.Application/Helpers/BindingEnumHelper.cs create mode 100644 Codemerx/Gestor.Application/Helpers/BindingHelper.cs create mode 100644 Codemerx/Gestor.Application/Helpers/Connection.cs create mode 100644 Codemerx/Gestor.Application/Helpers/ConnectionHelper.cs create mode 100644 Codemerx/Gestor.Application/Helpers/CustomLinq.cs create mode 100644 Codemerx/Gestor.Application/Helpers/DataGridExtensions.cs create mode 100644 Codemerx/Gestor.Application/Helpers/Erro.cs create mode 100644 Codemerx/Gestor.Application/Helpers/Funcoes.cs create mode 100644 Codemerx/Gestor.Application/Helpers/HttpHelper.cs create mode 100644 Codemerx/Gestor.Application/Helpers/Instancia.cs create mode 100644 Codemerx/Gestor.Application/Helpers/InstanciaAssinador.cs create mode 100644 Codemerx/Gestor.Application/Helpers/LicenseHelper.cs create mode 100644 Codemerx/Gestor.Application/Helpers/MailHelper.cs create mode 100644 Codemerx/Gestor.Application/Helpers/NotifyPropertyChangedExtension.cs create mode 100644 Codemerx/Gestor.Application/Helpers/ObrigatorioValidationRule.cs create mode 100644 Codemerx/Gestor.Application/Helpers/PasswordBoxAssistant.cs create mode 100644 Codemerx/Gestor.Application/Helpers/PipeClient.cs create mode 100644 Codemerx/Gestor.Application/Helpers/PipeServer.cs create mode 100644 Codemerx/Gestor.Application/Helpers/QueryableHelper.cs create mode 100644 Codemerx/Gestor.Application/Helpers/Recursos.cs create mode 100644 Codemerx/Gestor.Application/Helpers/TipoToggle.cs create mode 100644 Codemerx/Gestor.Application/Helpers/ViewHelper.cs create mode 100644 Codemerx/Gestor.Application/MainWindow.cs create mode 100644 Codemerx/Gestor.Application/Migration/Migrator.cs create mode 100644 Codemerx/Gestor.Application/Model/Ajuda/Atendimento.cs create mode 100644 Codemerx/Gestor.Application/Model/Ajuda/Boleto.cs create mode 100644 Codemerx/Gestor.Application/Model/Ajuda/Contrato.cs create mode 100644 Codemerx/Gestor.Application/Model/Ajuda/EmailAtendimento.cs create mode 100644 Codemerx/Gestor.Application/Model/Ajuda/Instalacao.cs create mode 100644 Codemerx/Gestor.Application/Model/AnaliticoSource.cs create mode 100644 Codemerx/Gestor.Application/Model/Configuracoes.cs create mode 100644 Codemerx/Gestor.Application/Model/Grafico.cs create mode 100644 Codemerx/Gestor.Application/Model/RelacaoItens.cs create mode 100644 Codemerx/Gestor.Application/Model/SinteticoSource.cs create mode 100644 Codemerx/Gestor.Application/Properties/Settings.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Ajuda/AjudaServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/ArquivoDigitalServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/AssinaturaServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/CepService.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Configuracoes/ConfuguracoesServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Ferramentas/AdiantamentoServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Ferramentas/AgendaServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Ferramentas/EmailServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Ferramentas/EmpresaServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Ferramentas/EstipulanteServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Ferramentas/ImpostoServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Ferramentas/MetaSeguradoraServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Ferramentas/MetaVendedorServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Ferramentas/NotaFiscalServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Ferramentas/ProdutoServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Ferramentas/QualificacaoServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Ferramentas/RamoServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Ferramentas/ReciboServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Ferramentas/SeguradoraServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Ferramentas/SocioServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Ferramentas/StatusProspeccaoServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Ferramentas/StatusServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Ferramentas/TipoTarefaServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Ferramentas/TipoVendedorServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Ferramentas/UsuarioServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Ferramentas/VendedorServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Financeiro/BancosContasServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Financeiro/CentroServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Financeiro/FinanceiroServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Financeiro/FornecedorServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Financeiro/PlanoServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Financeiro/PlanosServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Generic/BaseServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/LogServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/MalaDiretaServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/ParceiroServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/ParcelaServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/PermissaoArquivoDigitalServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/PermissaoUsuarioServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/ProspeccaoServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/RestricaoUsuarioServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Seguros/ApoliceServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Seguros/AtividadeServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Seguros/ClienteServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Seguros/CriticaApoliceServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Seguros/ExpedicaoServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Seguros/Itens/AeronauticoServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Seguros/Itens/AutoServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Seguros/Itens/ConsorcioServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Seguros/Itens/GranizoServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Seguros/Itens/ItemServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Seguros/Itens/PatrimonialServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Seguros/Itens/RiscosDiversosServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Seguros/Itens/VidaServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Seguros/PerfilEmpresaServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Seguros/PerfilServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Seguros/ProfissaoServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/Seguros/SinistroServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/ServicoExtrato.cs create mode 100644 Codemerx/Gestor.Application/Servicos/TarefaServico.cs create mode 100644 Codemerx/Gestor.Application/Servicos/VendedorUsuarioServico.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/AnaliticoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Arquivo.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/BI/BISeriesViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/BI/NotasViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/BI/PainelBiViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/BI/ProspeccaoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/BI/TarefaBIViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/CoberturaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Comissao/ComissaoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Command/RelayCommand.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Configuracoes/ConfiguracoesViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/DashboardViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/AdiantamentoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/AgendaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/Ajuda/AtendimentosViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/Ajuda/BoletosNotasViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/Ajuda/ContratosViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/Ajuda/InstalacaoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/ArquivoDigitalViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/ExpedicaoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/ExtratosViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/ImpostoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/InfoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/LogAcaoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/LogEmailViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/LogSistemaAntigoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/LogViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/MetaSeguradoraViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/MetaVendedorViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/PermissaoUsuarioViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/TarefaDrawerViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/ValoresApoliceViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/ValoresParcelaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/VinculoVendedorViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/CadastroEmailViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/CadastroParceiroViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/ComboModelo.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/ComboVariavel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/DownloadViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/EmpresaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/EstipulanteViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/EtiquetaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/IncluirRamoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/IncluirSeguradoraViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/MalaDiretaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/ManutencaoPagamentosViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/NotaFiscalViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/ProdutoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/ProtocoloDocumentosViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/ProtocoloEtiqueta.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/QualificacaoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/RamoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/ReciboViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/SeguradoraViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/SocioViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/StatusProspeccaoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/StatusViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/TipoTarefaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/TipoVendedorViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/UsuarioViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/VendedorViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Financeiro/BancosContasViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Financeiro/CentroDeCustoViewmodel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Financeiro/ContasDialogModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Financeiro/CopiarClienteViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Financeiro/ExtratoContaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Financeiro/FinanceiroViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Financeiro/FornecedorViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Financeiro/InfoExtratoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Financeiro/MenuFinanceiroViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Financeiro/PlanoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Financeiro/PlanosViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Financeiro/Relatorios/FechamentoFinanceiroViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Financeiro/TranferenciaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/BaseApoliceViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/BaseDialogViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/BaseFinanceiroViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/BaseSegurosViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/BaseTarefaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/BaseViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/DialogAdvertisingViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/DialogAnexarViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/DialogCopiaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/DialogCopiarPermissaoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/DialogEditarParcelasViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/DialogEnviarEmailsViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/DialogExportarPermissaoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/DialogGraficoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/DialogMedalhaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/DialogPesquisaAvancadaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/DialogProspeccaoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/DialogTarefaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/DialogTrilhaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/DialogViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/DialogVinculoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/ErrorDialogViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/ExtratoComissaoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/ItemViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/ProtocoloViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/ReordenarItensViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/SelecionarItensViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/ImportViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/LoginImageModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/LoginViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/MainViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/MenuBIViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/MenuFerramentasViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/MenuItemViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Relatorios/DialogPrintViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Relatorios/RelatorioViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Relatorios/SinteticoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Seguros/ApoliceViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Seguros/ClienteViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Seguros/ConsultaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Seguros/CriticaApoliceViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Seguros/Itens/AeronauticoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Seguros/Itens/AutoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Seguros/Itens/BuscarModeloViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Seguros/Itens/ConsorcioViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Seguros/Itens/GranizoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Seguros/Itens/PatrimonialViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Seguros/Itens/RiscosDiversosViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Seguros/Itens/VidaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Seguros/PerfilEmpresaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Seguros/PerfilViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Seguros/SinistroViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Seguros/TrocarClienteViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/TrilhaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/TutorialViewModel.cs create mode 100644 Codemerx/Gestor.Application/Views/Ajuda/AtendimentosView.cs create mode 100644 Codemerx/Gestor.Application/Views/BI/AcompanhamentoView.cs create mode 100644 Codemerx/Gestor.Application/Views/BI/AgendaBIView.cs create mode 100644 Codemerx/Gestor.Application/Views/BI/NotasView.cs create mode 100644 Codemerx/Gestor.Application/Views/BI/PainelBiView.cs create mode 100644 Codemerx/Gestor.Application/Views/BI/ProspeccaoView.cs create mode 100644 Codemerx/Gestor.Application/Views/BI/TarefaView.cs create mode 100644 Codemerx/Gestor.Application/Views/ConnectionRetryView.cs create mode 100644 Codemerx/Gestor.Application/Views/Ferramentas/CadastroEmailView.cs create mode 100644 Codemerx/Gestor.Application/Views/Ferramentas/CadastroParceiroView.cs create mode 100644 Codemerx/Gestor.Application/Views/Ferramentas/DownloadWindow.cs create mode 100644 Codemerx/Gestor.Application/Views/Ferramentas/EmpresaView.cs create mode 100644 Codemerx/Gestor.Application/Views/Ferramentas/EstipulanteView.cs create mode 100644 Codemerx/Gestor.Application/Views/Ferramentas/EtiquetaView.cs create mode 100644 Codemerx/Gestor.Application/Views/Ferramentas/IncluirRamoView.cs create mode 100644 Codemerx/Gestor.Application/Views/Ferramentas/IncluirSeguradoraView.cs create mode 100644 Codemerx/Gestor.Application/Views/Ferramentas/MalaDiretaView.cs create mode 100644 Codemerx/Gestor.Application/Views/Ferramentas/ManutencaoPagamentosView.cs create mode 100644 Codemerx/Gestor.Application/Views/Ferramentas/NotaFiscalView.cs create mode 100644 Codemerx/Gestor.Application/Views/Ferramentas/ProdutoView.cs create mode 100644 Codemerx/Gestor.Application/Views/Ferramentas/ProtocoloDocumentosView.cs create mode 100644 Codemerx/Gestor.Application/Views/Ferramentas/QualificacaoView.cs create mode 100644 Codemerx/Gestor.Application/Views/Ferramentas/RamoView.cs create mode 100644 Codemerx/Gestor.Application/Views/Ferramentas/ReciboView.cs create mode 100644 Codemerx/Gestor.Application/Views/Ferramentas/SeguradoraView.cs create mode 100644 Codemerx/Gestor.Application/Views/Ferramentas/SocioView.cs create mode 100644 Codemerx/Gestor.Application/Views/Ferramentas/StatusProspeccaoView.cs create mode 100644 Codemerx/Gestor.Application/Views/Ferramentas/StatusView.cs create mode 100644 Codemerx/Gestor.Application/Views/Ferramentas/TipoTarefaView.cs create mode 100644 Codemerx/Gestor.Application/Views/Ferramentas/TipoVendedorView.cs create mode 100644 Codemerx/Gestor.Application/Views/Ferramentas/UsuarioView.cs create mode 100644 Codemerx/Gestor.Application/Views/Ferramentas/VendedorView.cs create mode 100644 Codemerx/Gestor.Application/Views/Financeiro/BancosContasView.cs create mode 100644 Codemerx/Gestor.Application/Views/Financeiro/CentroDeCustoView.cs create mode 100644 Codemerx/Gestor.Application/Views/Financeiro/ExtratoWindow.cs create mode 100644 Codemerx/Gestor.Application/Views/Financeiro/FinanceiroView.cs create mode 100644 Codemerx/Gestor.Application/Views/Financeiro/FornecedorView.cs create mode 100644 Codemerx/Gestor.Application/Views/Financeiro/InfoExtratoView.cs create mode 100644 Codemerx/Gestor.Application/Views/Financeiro/PlanoView.cs create mode 100644 Codemerx/Gestor.Application/Views/Financeiro/PlanosView.cs create mode 100644 Codemerx/Gestor.Application/Views/Financeiro/Relatorios/FechamentoFinanceiroView.cs create mode 100644 Codemerx/Gestor.Application/Views/Generic/BaseUserControl.cs create mode 100644 Codemerx/Gestor.Application/Views/Generic/DragOverPopup.cs create mode 100644 Codemerx/Gestor.Application/Views/Generic/ErrorWindow.cs create mode 100644 Codemerx/Gestor.Application/Views/Generic/HosterWindow.cs create mode 100644 Codemerx/Gestor.Application/Views/ImportView.cs create mode 100644 Codemerx/Gestor.Application/Views/LoginWindow.cs create mode 100644 Codemerx/Gestor.Application/Views/Menus/DashboardView.cs create mode 100644 Codemerx/Gestor.Application/Views/Menus/MenuItensView.cs create mode 100644 Codemerx/Gestor.Application/Views/Relatorios/RelatorioView.cs create mode 100644 Codemerx/Gestor.Application/Views/Relatorios/SinteticoView.cs create mode 100644 Codemerx/Gestor.Application/Views/Seguros/ApoliceView.cs create mode 100644 Codemerx/Gestor.Application/Views/Seguros/ClienteView.cs create mode 100644 Codemerx/Gestor.Application/Views/Seguros/ComissaoView.cs create mode 100644 Codemerx/Gestor.Application/Views/Seguros/ConsultaOriginalView.cs create mode 100644 Codemerx/Gestor.Application/Views/Seguros/CriticaApoliceView.cs create mode 100644 Codemerx/Gestor.Application/Views/Seguros/Itens/AeronauticoView.cs create mode 100644 Codemerx/Gestor.Application/Views/Seguros/Itens/AutoView.cs create mode 100644 Codemerx/Gestor.Application/Views/Seguros/Itens/BuscarModeloView.cs create mode 100644 Codemerx/Gestor.Application/Views/Seguros/Itens/ConsorcioView.cs create mode 100644 Codemerx/Gestor.Application/Views/Seguros/Itens/GranizoView.cs create mode 100644 Codemerx/Gestor.Application/Views/Seguros/Itens/PatrimonialView.cs create mode 100644 Codemerx/Gestor.Application/Views/Seguros/Itens/RiscosDiversosView.cs create mode 100644 Codemerx/Gestor.Application/Views/Seguros/Itens/VidaView.cs create mode 100644 Codemerx/Gestor.Application/Views/Seguros/PerfilEmpresaView.cs create mode 100644 Codemerx/Gestor.Application/Views/Seguros/PerfilView.cs create mode 100644 Codemerx/Gestor.Application/Views/Seguros/SinistroView.cs create mode 100644 Codemerx/Gestor.Application/Views/Seguros/TrocarClienteView.cs create mode 100644 Codemerx/Gestor.Application/Views/TutorialView.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/ApolicePendenteConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/ArquivoDigitalToolTipConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/AtivoConverterColor.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/AtivoVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/BoolToEyeConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/BoolToYesNoConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/ComissaoColorConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/ComissaoConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/ComissaoConverterMulti.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/ComparativoColorConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/ComparativoConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/ComparativoPercentualToolTipConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/ComparativoToolTipConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/EnumDescriptionConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/ExpanderHeaderConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/IdToVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/InativoVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/InvertedBooleanConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/InvertedBooleanToVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/InvertedVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/IsInsertedBoolConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/IsNotNullBoolConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/MesConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/MultiBoolAndConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/NegativoColorConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/NullVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/NullVisibilityInvertedConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/ObjectToStringConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/ObjectVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/PagamentoVendedorCorretoraVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/ParcelaVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/PendenciaConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/PendenciaVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/RamoAutoVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/RecebidoColorConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/SaldoWeightConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/SinalColorConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/StatusExtratoColorConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/StatusParcelaVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/StatusTarefaVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/StringNullOrEmptyToVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/TarefaBackgroundColorConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/TemTarefaVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/TipoCriticaConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/TipoSinistroConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/TipoTelefoneVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/TotalizacaoExpanderConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/ValorTipoConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/ZeroToEmptyConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/ZeroToVisibilityConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/ZeroToVisibilityInvertedConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Converters/ZeroToVisibilityValorConverter.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Exceptions/AbortException.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Exceptions/BaseException.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Exceptions/ForbiddenException.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Exceptions/MailingException.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Exceptions/PermissionException.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Exceptions/UnauthorizedException.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Exceptions/ValidationException.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Helpers/DataBaseParameters.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Helpers/DefaultAttribute.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Helpers/EncryptionHelper.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Helpers/EnumBindingSourceExtension.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Helpers/EnumHelper.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Helpers/FindVisualChild.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Helpers/FindVisualChildren.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Helpers/Functions.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Helpers/HiddenAttribute.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Helpers/HttpHelper.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Helpers/OrderAttribute.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Helpers/ScrollAnimationBehavior.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Security/Token.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/SemValicao.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoAno.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoAnoObrigatorio.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoCeiObrigatorio.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoCep.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoCepObrigatorio.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoChassi.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoChassiObrigatorio.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoData.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoDataFutura.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoDataMaior.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoDataObrigatoria.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoDataPassada.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoDataPassadaObrigatoria.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoDocumento.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoDocumentoObrigatorio.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoDouble.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoEmail.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoEmailObrigatorio.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoEstado.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoEstadoObrigatorio.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoFipeObrigatorio.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoInt.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoIntObrigatorio.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoLong.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoLongObrigatorio.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoObrigatorio.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoOrgao.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoPlaca.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoPlacaObrigatorio.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoPrefixo.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoPrefixoObrigatorio.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoRneObrigatorio.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoTelefone.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoTelefoneObrigatorio.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoValorDiferenteZero.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoValorMaiorQueZero.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.Validation/ValidationHelper.cs create mode 100644 Codemerx/Gestor.Common/Gestor.Common.csproj create mode 100644 Codemerx/Gestor.Common/Gestor.Common.sln create mode 100644 Codemerx/Gestor.Common/Gestor.CommonReferences/Gestor.Model.dll create mode 100644 Codemerx/Gestor.Common/Properties/AssemblyInfo.cs create mode 100644 Codemerx/Gestor.Infrastructure/.vs/Gestor.Infrastructure/FileContentIndex/57a0321b-2dd7-4d59-adab-1ed08962f43e.vsidx create mode 100644 Codemerx/Gestor.Infrastructure/.vs/Gestor.Infrastructure/v18/.suo create mode 100644 Codemerx/Gestor.Infrastructure/.vs/Gestor.Infrastructure/v18/DocumentLayout.backup.json create mode 100644 Codemerx/Gestor.Infrastructure/.vs/Gestor.Infrastructure/v18/DocumentLayout.json create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Configuration/ConfigurationFileCache.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Configuration/SessionFactory.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Aggilizador/VinculoDocumentoDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/AtividadeDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/AtualizacaoDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/BancoDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/ControleArquivoDigitalDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/EmpresaDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/IndiceArquivoDigitalDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/ModeloMalaDiretaDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/ProfissaoDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/RegistroAcaoDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/RegistroLogDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/SocioDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Configuracoes/ConfiguracaoSistemaDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/AgendaDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/AgendaEmailDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/AgendaTelefoneDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/CategoriaTarefaDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/CredencialDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/FaseDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/ImpostoDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/LogEmailDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/NotaFiscalDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/OrigemClienteDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/ReciboDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/ResponsavelTarefaDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/StatusDeProspeccaoDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/TarefaDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/TipoDeTarefaDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/TrilhaDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/VinculoRepasseDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Financeiro/BancosContasDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Financeiro/CentroDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Financeiro/ControleFinanceiroDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Financeiro/FornecedorDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Financeiro/LancamentoDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Financeiro/PlanoDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Financeiro/PlanosDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Financeiro/SaldoDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Generic/EmailBase.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Generic/EnderecoBase.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Generic/EntityBase.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Generic/TelefoneBase.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Relatorios/ParametrosRelatorioDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Relatorios/ParametrosTotalizacaoDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/AdiantamentoDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/AeronauticoDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/AutoDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ClienteDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ClienteEmailDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ClienteEnderecoDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ClienteTelefoneDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ClienteVinculoDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/CoberturaDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/CoberturaGranizoDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/CoberturaPadraoDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/CondicaoRepasseDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ConfigExtratoImportDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ConsorcioDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ControleDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ControleSinistroDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/CriticaApoliceDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/DetalheExtratoDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/DocumentoDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/EstipulanteDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ExpedicaoDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ExtratoDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/FabricanteDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/FaturaDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/GranizoDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ItemDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/MaisContatoDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/MetaSeguradoraDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/MetaVendedorDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ParceiroDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ParcelaDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/PatrimonialDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/PerfilCondominioDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/PerfilDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/PerfilEmpresaDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/PermissaoArquivoDigitalDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/PermissaoUsuarioDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ProdutoDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ProspeccaoDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/QualificacaoDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/RamoDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/RepasseDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ResponsavelAssinaturaDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/RestricaoUsuarioCamposRelatoriosDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/RestricaoUsuarioDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/RiscosDiversosDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/SeguradoraContatoDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/SeguradoraDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/SeguradoraEnderecoDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/SinistroAutoDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/SinistroDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/SinistroVidaDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/StatusDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/TipoContaDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/TipoVendedorDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/TitularesVidaDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/UsuarioDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/VendedorDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/VendedorParcelaDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/VendedorTelefoneDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/VendedorUsuarioDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/VidaDb.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Helpers/Auxiliar.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Helpers/AuxiliarFinanceiro.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Helpers/Comparador.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Helpers/Funcoes.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Helpers/QueryableHelper.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Helpers/SqlDataReaderHelper.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappers/ApplicationMapper.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappers/CustomMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Aggilizador/VinculoDocumentoMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/AtividadeMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/AtualizacaoMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/BancoMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/ControleArquivoDigitalMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/EmpresaMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/IndiceArquivoDigitalMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/ModeloMalaDiretaMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/ProfissaoMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/RegistroAcaoMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/RegistroLogMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/SocioMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Configuracoes/ConfiguracaoSistemaMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/AgendaEmailMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/AgendaMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/AgendaTelefoneMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/CategoriaTarefaMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/CredencialMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/FaseMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/ImpostoMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/LogEmailMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/NotaFiscalMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/OrigemClienteMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/ReciboMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/ResponsavelTarefaMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/StatusProspeccaoMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/TarefaMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/TipoTarefaMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/TrilhaMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/VinculoRepasseMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/BancosContasMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/CentroMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/ControleFinanceiroMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/FornecedorMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/LancamentoMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/PlanoMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/PlanosMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/SaldoMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/TipoContaMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Relatorios/ParametrosRelatorioMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Relatorios/ParametrosTotalizacaoMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/AdiantamentoMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/AeronauticoMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/AutoMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ClienteEmailMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ClienteEnderecoMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ClienteMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ClienteTelefoneMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ClienteVinculoMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/CoberturaGranizoMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/CoberturaMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/CoberturaPadraoMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/CondicaoRepasseMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ConfigExtratoImportMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ConsorcioMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ControleMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ControleSinistroMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/CriticaApoliceMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/DetalheExtratoMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/DocumentoMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/EstipulanteMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ExpedicaoMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ExtratoMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/FabricanteMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/FaturaMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/GranizoMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ItemMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/MaisContatoMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/MetaSeguradoraMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/MetaVendedorMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ParceiroMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ParcelaMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/PatrimonialMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/PerfilEmpresaMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/PerfilMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/PermissaoArquivoDigitalMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/PermissaoUsuarioMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ProdutoMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ProspeccaoMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/QualificacaoMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/RamoMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/RepasseMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ResponsavelAssinaturaMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/RestricaoUsuarioCamposRelatoriosMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/RestricaoUsuarioMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/RiscosDiversosMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/SeguradoraContatoMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/SeguradoraEnderecoMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/SeguradoraMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/SinistroAutoMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/SinistroMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/SinistroVidaMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/StatusMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/TipoContaMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/TipoVendedorMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/TitularesVidaMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/UsuarioMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/VendedorMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/VendedorParcelaMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/VendedorTelefoneMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/VendedorUsuarioMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/VidaMap.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Generic/GenericRepository_T_.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Generic/IGenericRepository_TEntity_.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IAdiantamentoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IAeronauticoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IAgendaEmailRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IAgendaRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IAgendaTelefoneRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IAtividadeRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IAtualizacaoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IAutoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IBancoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IBancosContasRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ICategoriaTarefaRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ICentroRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IClienteEmailRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IClienteEnderecoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IClienteRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IClienteTelefoneRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IClienteVinculoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ICoberturaGranizoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ICoberturaPadraoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ICoberturaRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ICondicaoRepasseRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IConfigExtratoImportRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IConfiguracaoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IConsorcioRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IControleFinanceiroRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IControleRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IControleSinistroRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ICredencialRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ICriticaApoliceRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IDetalheExtratoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IDocumentoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IEmpresaRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IEstipulanteRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IExpedicaoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IExtratoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IFabricanteRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IFornecedorRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IGranizoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IImpostoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IIndiceArquivoDigitalRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IItemRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ILancamentoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IMaisContatoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IMetaSeguradoraRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IMetaVendedorRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IModeloMalaDiretaRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/INotaFiscalRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IParametrosRelatorioRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IParametrosTotalizacaoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IParceiroRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IParcelaRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IPatrimonialRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IPerfilEmpresaRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IPerfilRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IPermissaoArquivoDigitalRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IPermissaoUsuarioRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IPlanoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IPlanosRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IProdutoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IProfissaoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IProspectRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IQualificacaoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IRamoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IReciboRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IRegistroAcaoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IRegistroLogRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IRepasseRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IReportRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IRestricaoUsuarioCamposRelatoriosRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IRestricaoUsuarioRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IRiscosDiversosRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ISaldoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ISeguradoraContatoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ISeguradoraEnderecoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ISeguradoraRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ISinistroAutoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ISinistroRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ISinistroVidaRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ISocioRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IStatusProspeccaoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IStatusRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ITarefaRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ITipoContaRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ITipoTarefaRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ITipoVendedorRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ITitularesVidaRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IUsuarioRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IVendedorParcelaRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IVendedorRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IVendedorTelefoneRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IVendedorUsuarioRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IVidaRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IVinculoDocumentoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AdiantamentoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AeronauticoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaEmailRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaTelefoneRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AtividadeRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AtualizacaoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AutoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/BancoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/BancosContasRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CategoriaTarefaRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CentroRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteEmailRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteEnderecoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteTelefoneRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteVinculoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaGranizoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaPadraoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CondicaoRepasseRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConfigExtratoImportRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConfiguracaoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConsorcioRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleFinanceiroRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleSinistroRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CredencialRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CriticaApoliceRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/DetalheExtratoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/DocumentoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/EmpresaRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/EstipulanteRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ExpedicaoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ExtratoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/FabricanteRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/FornecedorRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/GranizoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ImpostoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/IndiceArquivoDigitalRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ItemRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/LancamentoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MaisContatoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MetaSeguradoraRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MetaVendedorRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ModeloMalaDiretaRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/NotaFiscalRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParametrosRelatorioRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParametrosTotalizacaoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParceiroRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParcelaRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PatrimonialRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PerfilEmpresaRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PerfilRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PermissaoArquivoDigitalRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PermissaoUsuarioRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PlanoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PlanosRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProdutoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProfissaoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProspectRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/QualificacaoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RamoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ReciboRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RegistroAcaoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RegistroLogRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RepasseRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ReportRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RestricaoUsuarioCamposRelatoriosRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RestricaoUsuarioRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RiscosDiversosRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SaldoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraContatoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraEnderecoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroAutoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroVidaRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SocioRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/StatusProspeccaoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/StatusRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TarefaRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoContaRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoTarefaRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoVendedorRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TitularesVidaRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/UsuarioRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorParcelaRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorTelefoneRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorUsuarioRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VidaRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VinculoDocumentoRepository.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Types/CustomBoolType.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Types/CustomEnumType2_T_.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Types/CustomEnumType_T_.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Types/CustomIntType.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.UnitOfWork.Generic/GenericUnitOfWork.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.UnitOfWork.Generic/IGenericUnitOfWork.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.UnitOfWork.Interface/IUnitOfWork.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.UnitOfWork.Logic/UnitOfWork.cs create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.csproj create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.sln create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.InfrastructureReferences/AutoMapper.dll create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.InfrastructureReferences/FluentNHibernate.dll create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.InfrastructureReferences/Gestor.Common.dll create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.InfrastructureReferences/Gestor.Model.dll create mode 100644 Codemerx/Gestor.Infrastructure/Gestor.InfrastructureReferences/NHibernate.dll create mode 100644 Codemerx/Gestor.Infrastructure/Properties/AssemblyInfo.cs create mode 100644 Codemerx/Gestor.Infrastructure/obj/Debug/.NETFramework,Version=v4.8.AssemblyAttributes.cs create mode 100644 Codemerx/Gestor.Infrastructure/obj/Debug/DesignTimeResolveAssemblyReferencesInput.cache create mode 100644 Codemerx/Gestor.Infrastructure/obj/Debug/Gestor.Infrastructure.csproj.AssemblyReference.cache create mode 100644 Codemerx/Gestor.Infrastructure/obj/Debug/Gestor.Infrastructure.csproj.CoreCompileInputs.cache create mode 100644 Codemerx/Gestor.Infrastructure/obj/Debug/Gestor.Infrastructure.csproj.FileListAbsolute.txt create mode 100644 Codemerx/Gestor.Model/Gestor.Model.csproj create mode 100644 Codemerx/Gestor.Model/Gestor.Model.sln create mode 100644 Codemerx/Gestor.Model/Gestor.ModelReferences/Newtonsoft.Json.dll create mode 100644 Codemerx/Gestor.Model/Model.API/Access.cs create mode 100644 Codemerx/Gestor.Model/Model.API/AccessControl.cs create mode 100644 Codemerx/Gestor.Model/Model.API/AjudaTela.cs create mode 100644 Codemerx/Gestor.Model/Model.API/Attachment.cs create mode 100644 Codemerx/Gestor.Model/Model.API/AuthSso.cs create mode 100644 Codemerx/Gestor.Model/Model.API/ConnectionAddress.cs create mode 100644 Codemerx/Gestor.Model/Model.API/Customer.cs create mode 100644 Codemerx/Gestor.Model/Model.API/CustomerAttendance.cs create mode 100644 Codemerx/Gestor.Model/Model.API/CustomerData.cs create mode 100644 Codemerx/Gestor.Model/Model.API/HorarioAtendimento.cs create mode 100644 Codemerx/Gestor.Model/Model.API/LogError.cs create mode 100644 Codemerx/Gestor.Model/Model.API/Owner.cs create mode 100644 Codemerx/Gestor.Model/Model.API/Parameters.cs create mode 100644 Codemerx/Gestor.Model/Model.API/Payment.cs create mode 100644 Codemerx/Gestor.Model/Model.API/TipoErro.cs create mode 100644 Codemerx/Gestor.Model/Model.API/TokenSso.cs create mode 100644 Codemerx/Gestor.Model/Model.API/UploadFile.cs create mode 100644 Codemerx/Gestor.Model/Model.API/UserSso.cs create mode 100644 Codemerx/Gestor.Model/Model.API/UsuarioCentralSegurado.cs create mode 100644 Codemerx/Gestor.Model/Model.API/Version.cs create mode 100644 Codemerx/Gestor.Model/Model.Attributes/EntityAttribute.cs create mode 100644 Codemerx/Gestor.Model/Model.Attributes/ForceLogAttribute.cs create mode 100644 Codemerx/Gestor.Model/Model.Attributes/HelpAttribute.cs create mode 100644 Codemerx/Gestor.Model/Model.Attributes/LogAttribute.cs create mode 100644 Codemerx/Gestor.Model/Model.Attributes/NameAttribute.cs create mode 100644 Codemerx/Gestor.Model/Model.Attributes/OldValue2Attribute.cs create mode 100644 Codemerx/Gestor.Model/Model.Attributes/OldValueAttribute.cs create mode 100644 Codemerx/Gestor.Model/Model.Attributes/TipoAttribute.cs create mode 100644 Codemerx/Gestor.Model/Model.Attributes/WidthAttribute.cs create mode 100644 Codemerx/Gestor.Model/Model.CalculoWeb/Auto/CalculoAuto.cs create mode 100644 Codemerx/Gestor.Model/Model.CalculoWeb/Auto/Caminhao.cs create mode 100644 Codemerx/Gestor.Model/Model.CalculoWeb/Auto/CoberturaAuto.cs create mode 100644 Codemerx/Gestor.Model/Model.CalculoWeb/Auto/ComissaoSeguradora.cs create mode 100644 Codemerx/Gestor.Model/Model.CalculoWeb/Auto/CondutorPrincipal.cs create mode 100644 Codemerx/Gestor.Model/Model.CalculoWeb/Auto/Fipe.cs create mode 100644 Codemerx/Gestor.Model/Model.CalculoWeb/Auto/QuestionarioAuto.cs create mode 100644 Codemerx/Gestor.Model/Model.CalculoWeb/Auto/Veiculo.cs create mode 100644 Codemerx/Gestor.Model/Model.CalculoWeb/Calculo.cs create mode 100644 Codemerx/Gestor.Model/Model.CalculoWeb/Condominio/CalculoCondominio.cs create mode 100644 Codemerx/Gestor.Model/Model.CalculoWeb/Condominio/CoberturaCondominio.cs create mode 100644 Codemerx/Gestor.Model/Model.CalculoWeb/Condominio/QuestionarioCondominio.cs create mode 100644 Codemerx/Gestor.Model/Model.CalculoWeb/Empresa/CalculoEmpresa.cs create mode 100644 Codemerx/Gestor.Model/Model.CalculoWeb/Empresa/CoberturaEmpresa.cs create mode 100644 Codemerx/Gestor.Model/Model.CalculoWeb/Empresa/EnderecoEmpresa.cs create mode 100644 Codemerx/Gestor.Model/Model.CalculoWeb/Empresa/QuestionarioEmpresa.cs create mode 100644 Codemerx/Gestor.Model/Model.CalculoWeb/Residencia/CalculoResidencia.cs create mode 100644 Codemerx/Gestor.Model/Model.CalculoWeb/Residencia/CoberturaResidencia.cs create mode 100644 Codemerx/Gestor.Model/Model.CalculoWeb/Residencia/EnderecoResidencia.cs create mode 100644 Codemerx/Gestor.Model/Model.CalculoWeb/Residencia/Imovel.cs create mode 100644 Codemerx/Gestor.Model/Model.CalculoWeb/Residencia/QuestionarioResidencia.cs create mode 100644 Codemerx/Gestor.Model/Model.CalculoWeb/Resultados.cs create mode 100644 Codemerx/Gestor.Model/Model.CalculoWeb/Segurado.cs create mode 100644 Codemerx/Gestor.Model/Model.CalculoWeb/Seguro.cs create mode 100644 Codemerx/Gestor.Model/Model.CalculoWeb/Telefone.cs create mode 100644 Codemerx/Gestor.Model/Model.CalculoWeb/Usuario.cs create mode 100644 Codemerx/Gestor.Model/Model.CalculoWeb/VidaGlobal/CalculoVidaGlobal.cs create mode 100644 Codemerx/Gestor.Model/Model.CalculoWeb/VidaGlobal/CoberturaVidaGlobal.cs create mode 100644 Codemerx/Gestor.Model/Model.CalculoWeb/VidaGlobal/QuestionarioVidaGlobal.cs create mode 100644 Codemerx/Gestor.Model/Model.CalculoWeb/VidaIndividual/CalculoVidaIndividual.cs create mode 100644 Codemerx/Gestor.Model/Model.CalculoWeb/VidaIndividual/CoberturaVidaIndividual.cs create mode 100644 Codemerx/Gestor.Model/Model.CalculoWeb/VidaIndividual/Profissao.cs create mode 100644 Codemerx/Gestor.Model/Model.CalculoWeb/VidaIndividual/QuestionarioVidaIndividual.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/AcessoApolice.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/Agrupamento.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/Antifurto.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/AtividadeEmpresa.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/BandeiraCartao.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/BaseRepasse.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/Categoria.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/Combustivel.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/Condicao.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/Configuracao.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/ConfiguracaoImpressao.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/Cor.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/Correcao.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/DistanciaTrabalho.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/EquipamentoIncendio.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/EquipamentoSeguranca.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/EstadoCivil.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/FiltroArquivoDigital.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/FiltroCritica.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/FiltroLancamento.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/FiltroLancamentoData.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/FiltroStatusDocumento.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/FormaPagamento.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/FormaRepasse.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/GaragemResidencia.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/GaragemTrabalhoEstudo.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/Isencao.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/Localizacao.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/ManutencaoItem.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/Mes.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/Negocio.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/NegocioCorretora.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/Ocupacao.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/Operacao.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/Operador.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/Parentesco.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/ParentescoVinculo.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/PermissaoAggilizador.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/Rastreador.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/Relacao.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/Relatorio.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/Sexo.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/Sinal.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/SinteticoFinanceiroTipo.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/SqlQueryCondition.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/StatusAssinatura.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/StatusCalculo.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/StatusDocumentoAssinado.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/StatusExtrato.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/StatusItem.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/StatusLancamento.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/StatusPagamento.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/StatusParcela.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/StatusProspeccao.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/StatusSinistro.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/StatusTarefa.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/SubTipo.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TabelaReferencia.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TempoHabilitacao.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoAcao.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoAeronautico.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoArquivoDigital.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoArquivoVinculo.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoCobertura.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoConstrucao.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoConta.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoContato.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoContatoSeguradora.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoDocumento.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoEmail.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoEndereco.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoEndosso.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoExtrato.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoFiltroBusca.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoFiltroCliente.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoFiltroFinanceiro.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoFiltroRelatorio.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoIncidencia.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoIncidenciaDesconto.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoManutencao.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoMoradia.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoPagamento.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoPavimentacao.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoPerda.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoPesquisa.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoProtocoloEtiqueta.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoRecebimento.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoRecibo.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoRepasse.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoResidencia.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoRestricao.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoSeguro.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoSinistro.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoTarefa.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoTela.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoTelaInicial.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoTelefone.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoTitular.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TipoTrilha.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/TpoSituacaoSinistro.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/UsoDependetes.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/UsoVeiculo.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/Utilizacao.cs create mode 100644 Codemerx/Gestor.Model/Model.Common/ValidationStates.cs create mode 100644 Codemerx/Gestor.Model/Model.Converter/EnumDescriptionTypeConverter.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Aggilizador/ArquivoVinculo.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Aggilizador/Calculo.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Aggilizador/LocalArquivo.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Aggilizador/ParcelaPendente.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Aggilizador/VinculoDocumento.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.BI/Analitico.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.BI/AtalhosApolice.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.BI/AtalhosCalculo.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.BI/AtalhosCliente.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.BI/AtalhosComissao.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.BI/AtalhosParcela.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.BI/AtalhosSinistro.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Card/Assistance.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Card/AssistenciaCia.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Card/Card.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Card/Logo.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Common/ArquivoDigital.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Common/Atividade.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Common/Banco.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Common/Contato.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Common/ControleArquivoDigital.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Common/Empresa.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Common/Fipe.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Common/FipeDetalhe.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Common/IndiceArquivoDigital.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Common/PesquisaAvancada.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Common/Profissao.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Common/RegistroAcao.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Common/RegistroLog.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Common/Socio.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Common/TrocaCliente.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Configuracoes/ConfiguracaoSistema.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Ferramentas/Agenda.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Ferramentas/AgendaEmail.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Ferramentas/AgendaTelefone.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Ferramentas/CategoriaTarefa.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Ferramentas/Credencial.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Ferramentas/Destinatario.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Ferramentas/Fase.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Ferramentas/Imposto.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Ferramentas/LogEmail.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Ferramentas/LogEnvio.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Ferramentas/ManutencaoPagamentos.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Ferramentas/NotaFiscal.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Ferramentas/OrigemCliente.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Ferramentas/Recibo.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Ferramentas/ResponsavelTarefa.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Ferramentas/StatusDeProspeccao.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Ferramentas/Tarefa.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Ferramentas/TipoDeTarefa.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Ferramentas/Trilha.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Financeiro/BancosContas.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Financeiro/Centro.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Financeiro/ControleFinanceiro.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Financeiro/ExtratoConta.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Financeiro/FiltroPersonalizado.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Financeiro/Fornecedor.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Financeiro/Lancamento.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Financeiro/Plano.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Financeiro/Planos.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Financeiro/RelatorioLancamentos.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Financeiro/Relatorios/DadosFechamento.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Financeiro/Relatorios/DadosFechamentoAnalitico.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Financeiro/Relatorios/FechamentoFinanceiro.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Financeiro/Relatorios/FechamentoFinanceiroAnalitico.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Financeiro/Relatorios/FiltroFinanceiro.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Financeiro/Saldo.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Financeiro/SinteticoFinanceiro.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Financeiro/TipoConta.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Financeiro/Transferencia.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Generic/Diferenca.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Generic/DomainBase.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Generic/EmailBase.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Generic/EnderecoBase.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Generic/FieldInformation.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Generic/IDomain.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Generic/TelefoneBase.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Generic/ValorOriginal.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.MalaDireta/Copia.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.MalaDireta/MalaDireta.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.MalaDireta/ModeloMalaDireta.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.MalaDireta/VariaveisMalaDireta.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/ApolicePendente/ApolicePendente.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/ApolicePendente/ContainerApolicePendente.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/Auditoria/Auditoria.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/CartaoSegurado.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/Classificacao/Classificacao.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/Cliente/SinteticoClientes.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/ClientesAtivosInativos/ClientesAtivosInativos.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/ClientesAtivosInativos/SinteticoClientesAtivosInativos.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/Comissao/Comissao.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/Comissao/SinteticoComissao.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/CriticaApolice/ApoliceCritica.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/DadosRelatorio.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/DadosVinculo.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/Dashboard/Prospectar.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/EndossoCancelamento/Endosso.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/Extrato/DetalhesExtrato.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/Extrato/Extrato.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/Extrato/ExtratoComissao.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/Extrato/InformacoesExtrato.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/Extrato/SinteticoExtrato.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/ExtratoBaixado/ExtratoBaixadoRelatorio.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/FaturaPendente/FaturaPendente.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/Fechamento/Fechamento.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/Fechamento/Fechamentos.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/Fechamento/SinteticoFechamento.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/FiltroPersonalizado.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/FiltroRelatorio.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/FiltroTipoParcela.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/Filtros.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/Licenciamento/Licenciamento.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/Listagem.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/Log/LogAcaoRelatorio.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/LogsEnvio/LogsEnvio.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/MetaSeguradora/MetaSeguradoraRelatorio.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/MetaSeguradora/SinteticoMetaSeguradora.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/MetaVendedor/MetaVendedorRelatorio.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/MetaVendedor/SinteticoMetaVendedor.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/NegocioRelatorio.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/NotaFiscal/NotaFiscalRelatorio.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/Pagamento/AgrupamentoPagamentoSintetico.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/Pagamento/AgrupamentoVendedor.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/Pagamento/Pagamento.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/Pagamento/PagamentoSintetico.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/Pagamento/SinteticoPagamento.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/ParametrosRelatorio.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/ParametrosTotalizacao.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/Pendente/Pendente.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/Pendente/SinteticoPendente.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/Placa/Placas.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/PlanilhaCompleta.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/PrevisaoPagamentoComissao/AgrupamentoSintetico.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/PrevisaoPagamentoComissao/PrevisaoPagamento.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/PrevisaoPagamentoComissao/PrevisaoPagamentoComissao.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/PrevisaoPagamentoComissao/PrevisaoPagamentoComissaoSintetico.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/Producao/Producao.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/Producao/SinteticoProducao.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/Renovacao/Renovacao.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/Renovacao/SinteticoRenovacao.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/Sinistro/Sinistro.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/Sinistro/SinteticoSinistro.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/SinteticModel.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/SinteticModelList.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/Sintetico.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/SinteticoFinanceiro.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/StatusRelatorio.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/Tarefa/Tarefa.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/TipoRelatorio.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Relatorios/ValorSintetico.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/Adiantamento.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/Aeronautico.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/AggilizadorPermissao.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/Auto.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/Cliente.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/ClienteEmail.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/ClienteEndereco.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/ClienteTelefone.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/ClienteVinculo.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/Cobertura.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/CoberturaGranizo.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/CoberturaPadrao.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/CondicaoRepasse.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/ConfigExtratoImport.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/Consorcio.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/Controle.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/ControleSinistro.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/CriticaApolice.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/DetalheExtrato.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/Documento.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/Estipulante.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/Expedicao.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/Extrato.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/Fabricante.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/Granizo.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/Item.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/MaisContato.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/MetaSeguradora.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/MetaVendedor.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/Parceiro.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/Parcela.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/Parcelas.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/Patrimonial.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/Perfil.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/PerfilEmpresa.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/PermissaoArquivoDigital.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/PermissaoUsuario.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/Produto.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/Prospeccao.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/ProspeccaoToPrint.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/Qualificacao.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/Ramo.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/Repasse.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/ResponsavelAssinatura.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/RestricaoUsuario.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/RestricaoUsuarioCamposRelatorios.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/RiscosDiversos.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/Seguradora.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/SeguradoraContato.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/SeguradoraEndereco.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/Sinistro.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/SinistroAuto.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/SinistroVida.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/Status.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/TipoVendedor.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/TitularesVida.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/TupleList.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/Usuario.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/Vendedor.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/VendedorParcela.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/VendedorParcelas.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/VendedorTelefone.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/VendedorUsuario.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/Vida.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/VinculoRepasse.cs create mode 100644 Codemerx/Gestor.Model/Model.Domain.Seguros/VinculoVendedor.cs create mode 100644 Codemerx/Gestor.Model/Model.Helper/ValidationHelper.cs create mode 100644 Codemerx/Gestor.Model/Model.License/Instalacao.cs create mode 100644 Codemerx/Gestor.Model/Model.License/Licenca.cs create mode 100644 Codemerx/Gestor.Model/Model.License/Produto.cs create mode 100644 Codemerx/Gestor.Model/Model.License/StatusLicenca.cs create mode 100644 Codemerx/Gestor.Model/Model.Relatorios/Cliente.cs create mode 100644 Codemerx/Gestor.Model/Model.Relatorios/ClienteEmail.cs create mode 100644 Codemerx/Gestor.Model/Model.Relatorios/ClienteEndereco.cs create mode 100644 Codemerx/Gestor.Model/Model.Relatorios/ClienteTelefone.cs create mode 100644 Codemerx/Gestor.Model/Model.Relatorios/Controle.cs create mode 100644 Codemerx/Gestor.Model/Model.Relatorios/Documento.cs create mode 100644 Codemerx/Gestor.Model/Model.Relatorios/EstipulanteCliente.cs create mode 100644 Codemerx/Gestor.Model/Model.Relatorios/Ramo.cs create mode 100644 Codemerx/Gestor.Model/Model.Relatorios/Vendedor.cs create mode 100644 Codemerx/Gestor.Model/Model.Validation/ControleValidacao.cs create mode 100644 Codemerx/Gestor.Model/Model.Validation/Funcoes.cs create mode 100644 Codemerx/Gestor.Model/Properties/AssemblyInfo.cs create mode 100644 Codemerx/Properties/AssemblyInfo.cs (limited to 'Codemerx') diff --git a/Codemerx/App.config b/Codemerx/App.config new file mode 100644 index 0000000..eb11ef4 --- /dev/null +++ b/Codemerx/App.config @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codemerx/Gestor.Application.Migration.Files.20200219_01.SQL b/Codemerx/Gestor.Application.Migration.Files.20200219_01.SQL new file mode 100644 index 0000000..0511b35 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200219_01.SQL @@ -0,0 +1,192 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 112) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (112, N'CAPEMISA CAPITALIZAÇÃO S/A', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 131) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (131, N'CHUBB DO BRASIL CIA DE SEGUROS', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 14) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (14, N'ALFA SEGURADORA S.A.', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 182) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (182, N'COMPANHIA EXCELSIOR DE SEGUROS', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 19) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (19, N'ALLIANZ SEGUROS S.A.', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 192) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (192, N'CONFIANÇA CIA DE SEGUROS', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 216) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (216, N'ESSOR SEGUROS S.A.', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 228) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (228, N'FAIRFAX BRASIL SEGUROS CORPORATIVOS S.A.', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 244) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (244, N'GENERALI BRASIL SEGUROS S.A.', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 245) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (245, N'GENTE SEGURADORA S.A.', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 259) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (259, N'HDI SEGUROS S.A.', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 276) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (276, N'INDIANA SEGUROS S/A', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 285) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (285, N'INVESTPREV SEGURADORA S.A', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 292) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (292, N'ITAU SEGUROS S/A', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 310) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (310, N'LIBERTY SEGUROS S/A', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 311) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (311, N'LIDERANÇA CAPITALIZAÇÃO S/A', 0, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 328) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (328, N'MAPFRE SEGUROS GERAIS S/A', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 331) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (331, N'MARITIMA SEGUROS S/A', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 338) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (338, N'MBM SEGURADORA S/A', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 341) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (341, N'METLIFE VIDA E PREVIDÊNCIA S/A', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 348) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (348, N'MITSUI SUMITOMO SEGUROS S/A', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 372) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (372, N'NOBRE SEGURADORA DO BRASIL S/A', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 4) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (4, N'ACE SEGURADORA S.A.', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 400) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (400, N'PORTO SEGURO CIA DE SEGUROS GERAIS', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 42) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (42, N'ARGO SEGUROS BRASIL S.A', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 480) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (480, N'SULAMÉRICA CIA NACIONAL DE SEGUROS', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 491) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (491, N'SWISS RE CORPORATE SOLUTIONS BRASIL SE S', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 501) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (501, N'TOKIO MARINE SEGURADORA S.A.', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 522) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (522, N'UNIMED SEGURADORA S/A', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 543) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (543, N'YASUDA SEGUROS S.A', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 548) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (548, N'ZURICH MINAS BRASIL SEGUROS S/A', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 557) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (557, N'SUHAI SEGUROS S.A.', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 559) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (559, N'SANCOR SEGUROS DO BRASIL S.A.', 1, 2); +END +--IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 560) +--BEGIN +-- INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (560, N'AGROBRASIL - CORRETORA DE SEGUROS LTDA - ME ', 1, 2); +--END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 561) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (561, N'RSA SEGUROS', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 562) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (562, N'YASUDA MARITIMA SEGUROS S.A.', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 578) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (578, N'NOTRE DAME INTERMÉDICA', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 595) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (595, N'SOMPO SEGUROS', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 600) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (600, N'ASSIST CARD SEGURO VIAGEM', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 603) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (603, N'AXA SEGUROS', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 639) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (639, N'ALIRO SEGUROS S.A.', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 642) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (642, N'SURA SEGUROS S/A', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 647) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (647, N'PREVISUL SEGURADORA', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 695) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (695, N'ARUANA SEGURADORA', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 70) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (70, N'AZUL COMPANHIA DE SEGUROS GERAIS', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 9) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (9, N'AIG SEGUROS BRASIL S.A', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 92) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (92, N'BRADESCO SEGUROS S.A', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 614) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (614, N'TOO SEGUROS S.A.', 1, 2); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200219_02.SQL b/Codemerx/Gestor.Application.Migration.Files.20200219_02.SQL new file mode 100644 index 0000000..27f9797 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200219_02.SQL @@ -0,0 +1,116 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 1) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (1, N'RESIDÊNCIA',0.0738,0,1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 2) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (2, N'EMPRESA',0.0738,0,1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 3) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (3, N'CONDOMÍNIO',0.0738,0,1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 4) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (4, N'RISCOS DIVERSOS',0.0738,1,1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 5) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (5, N'AUTOMOVEL',0.0738,0,1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 6) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (6, N'VIDA INDIVIDUAL',0.0738,1,1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 7) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (7, N'VG/APC',0.0738,1,1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 8) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (8, N'TRANSPORTES',0.0738,1,1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 14) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (14, N'DPVAT',0.0738,0,0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 15) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (15, N'FIANÇA LOCATÍCIA',0.0738,0,1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 18) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (18, N'IMOBILIÁRIO',0.0738,1,1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 20) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (20, N'GRANIZO',0.0738,0,1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 23) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (23, N'SEGURO VIAGEM',0.0738,0,0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 24) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (24, N'SEGURO DE EVENTOS',0.0738,0,1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 25) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (25, N'AGRÍCOLA',0.0738,1,0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 28) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (28, N'RC PROFISSIONAL',0.0738,0,0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 30) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (30, N'RC AMBIENTAL',0.0738,0,0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 31) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (31, N'ACIDENTES PESSOAIS',0.0738,0,1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 32) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (32, N'RESP. CIVIL GERAL',0.0738,0,1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 33) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (33, N'MULTIRISCO RURAL',0.0738,0,1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 34) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (34, N'ANIMAIS',0.0738,0,0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 37) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (37, N'RESP. CIVIL ÔNIBUS',0.0738,0,1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 38) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (38, N'SEGURO GARANTIA',0.0738,0,0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 39) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (39, N'RISCOS DE ENGENHARIA',0.0738,0,1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 41) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (41, N'ACIDENTES PESSOAIS COLETIVOS',0.0738,0,1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 44) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (44, N'PENHOR RURAL',0.0738,0,0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 49) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (49, N'RCTR-C',0.0738,1,0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 54) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (54, N'BENFEITORIA RURAL',0.0738,0,0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 56) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (56, N'RC PRESTAÇÃO DE SERVIÇO',0.0738,0,1); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200219_03.SQL b/Codemerx/Gestor.Application.Migration.Files.20200219_03.SQL new file mode 100644 index 0000000..17e1099 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200219_03.SQL @@ -0,0 +1,468 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 1) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (1,1, N'BANCO DO BRASIL S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 10) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (10,41, N'BANCO DO ESTADO DO RIO GRANDE DO SUL S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 100) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (100,738, N'BANCO MORADA S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 101) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (101,739, N'BANCO BGN S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 102) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (102,740, N'BANCO BARCLAYS S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 103) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (103,741, N'BANCO RIBEIRAO PRETO S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 104) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (104,743, N'BANCO EMBLEMA S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 105) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (105,745, N'BANCO CITIBANK S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 106) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (106,746, N'BANCO MODAL S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 107) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (107,747, N'BANCO RABOBANK INTERNATIONAL BRASIL S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 108) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (108,748, N'BANCO COOPERATIVO SICREDI S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 109) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (109,749, N'BANCO SIMPLES S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 11) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (11,44, N'BANCO BVA S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 110) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (110,751, N'DRESDNER BANK BRASIL S.A. BANCO MULTIPLO'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 111) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (111,752, N'BANCO BNP PARIBAS BRASIL S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 112) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (112,753, N'NBC BANK BRASIL S. A. - BANCO M?LTIPLO'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 113) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (113,756, N'BANCO COOPERATIVO DO BRASIL S.A. - BANCOOB'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 114) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (114,757, N'BANCO KEB DO BRASIL S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 115) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (115,0, N'NENHUM'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 116) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (116,85, N'BANCO CECRED'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 117) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (117,290, N'PAGSEGURO INTERNET S.A'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 12) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (12,45, N'BANCO OPPORTUNITY S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 13) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (13,47, N'BANCO DO ESTADO DE SERGIPE S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 14) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (14,62, N'HIPERCARD BANCO M?LTIPLO S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 15) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (15,63, N'BANCO IBI S.A. - BANCO M?LTIPLO'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 16) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (16,65, N'BANCO LEMON S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 17) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (17,66, N'BANCO MORGAN STANLEY S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 18) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (18,69, N'BPN BRASIL BANCO M?LTIPLO S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 19) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (19,70, N'BRB - BANCO DE BRASILIA S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 2) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (2,3, N'BANCO DA AMAZONIA S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 20) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (20,72, N'BANCO RURAL MAIS S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 21) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (21,73, N'BB BANCO POPULAR DO BRASIL S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 22) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (22,74, N'BANCO J. SAFRA S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 23) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (23,75, N'BANCO CR2 S/A'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 24) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (24,76, N'BANCO KDB DO BRASIL S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 25) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (25,77, N'BANCO INTERMEDIUM S/A'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 26) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (26,79, N'JBS BANCO S/A'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 27) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (27,81, N'CONC?RDIA BANCO S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 28) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (28,96, N'BANCO BM&F DE SERVI?OS DE LIQUIDA??O E CUST?DIA S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 29) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (29,104, N'CAIXA ECONOMICA FEDERAL'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 3) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (3,4, N'BANCO DO NORDESTE DO BRASIL S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 30) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (30,107, N'BANCO BBM S/A'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 31) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (31,151, N'BANCO NOSSA CAIXA S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 32) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (32,208, N'BANCO UBS PACTUAL S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 33) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (33,212, N'BANCO MATONE S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 34) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (34,213, N'BANCO ARBI S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 35) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (35,214, N'BANCO DIBENS S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 36) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (36,217, N'BANCO JOHN DEERE S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 37) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (37,218, N'BANCO BONSUCESSO S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 38) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (38,222, N'BANCO CALYON BRASIL S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 39) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (39,224, N'BANCO FIBRA S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 4) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (4,19, N'BANCO AZTECA DO BRASIL S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 40) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (40,225, N'BANCO BRASCAN S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 41) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (41,229, N'BANCO CRUZEIRO DO SUL S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 42) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (42,230, N'UNICARD BANCO M?LTIPLO S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 43) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (43,233, N'BANCO GE CAPITAL S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 44) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (44,237, N'BANCO BRADESCO S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 45) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (45,241, N'BANCO CLASSICO S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 46) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (46,243, N'BANCO M?XIMA S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 47) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (47,246, N'BANCO ABC BRASIL S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 48) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (48,248, N'BANCO BOAVISTA INTERATLANTICO S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 49) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (49,249, N'BANCO INVESTCRED UNIBANCO S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 5) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (5,21, N'BANESTES S.A. BANCO DO ESTADO DO ESPIRITO SANTO'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 50) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (50,250, N'BANCO SCHAHIN S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 51) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (51,254, N'PARAN? BANCO S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 52) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (52,263, N'BANCO CACIQUE S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 53) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (53,265, N'BANCO FATOR S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 54) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (54,266, N'BANCO CEDULA S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 55) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (55,300, N'BANCO DE LA NACION ARGENTINA'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 56) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (56,318, N'BANCO BMG S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 57) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (57,341, N'BANCO ITAU S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 58) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (58,356, N'BANCO ABN AMRO REAL S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 59) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (59,366, N'BANCO SOCIETE GENERALE BRASIL S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 6) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (6,25, N'BANCO ALFA S.A'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 60) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (60,370, N'BANCO WESTLB DO BRASIL S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 61) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (61,376, N'BANCO J.P. MORGAN S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 62) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (62,389, N'BANCO MERCANTIL DO BRASIL S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 63) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (63,394, N'BANCO FINASA BMC S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 64) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (64,399, N'HSBC BANK BRASIL S.A. - BANCO MULTIPLO'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 65) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (65,409, N'UNIBANCO-UNIAO DE BANCOS BRASILEIROS S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 66) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (66,412, N'BANCO CAPITAL S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 67) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (67,422, N'BANCO SAFRA S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 68) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (68,453, N'BANCO RURAL S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 69) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (69,456, N'BANCO DE TOKYO-MITSUBISHI UFJ BRASIL S/A'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 7) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (7,33, N'BANCO SANTANDER BANESPA S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 70) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (70,464, N'BANCO SUMITOMO MITSUI BRASILEIRO S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 71) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (71,477, N'CITIBANK N.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 72) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (72,487, N'DEUTSCHE BANK S.A. - BANCO ALEMAO'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 73) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (73,488, N'JPMORGAN CHASE BANK, NATIONAL ASSOCIATION'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 74) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (74,492, N'ING BANK N.V.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 75) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (75,494, N'BANCO DE LA REPUBLICA ORIENTAL DEL URUGUAY'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 76) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (76,495, N'BANCO DE LA PROVINCIA DE BUENOS AIRES'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 77) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (77,505, N'BANCO CREDIT SUISSE (BRASIL) S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 78) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (78,600, N'BANCO LUSO BRASILEIRO S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 79) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (79,604, N'BANCO INDUSTRIAL DO BRASIL S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 8) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (8,37, N'BANCO DO ESTADO DO PAR? S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 80) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (80,610, N'BANCO VR S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 81) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (81,611, N'BANCO PAULISTA S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 82) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (82,612, N'BANCO GUANABARA S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 83) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (83,613, N'BANCO PECUNIA S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 84) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (84,623, N'BANCO PANAMERICANO S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 85) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (85,626, N'BANCO FICSA S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 86) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (86,630, N'BANCO INTERCAP S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 87) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (87,633, N'BANCO RENDIMENTO S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 88) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (88,634, N'BANCO TRIANGULO S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 89) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (89,637, N'BANCO SOFISA S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 9) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (9,40, N'BANCO CARGILL S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 90) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (90,638, N'BANCO PROSPER S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 91) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (91,643, N'BANCO PINE S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 92) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (92,653, N'BANCO INDUSVAL S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 93) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (93,654, N'BANCO A.J. RENNER S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 94) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (94,655, N'BANCO VOTORANTIM S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 95) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (95,707, N'BANCO DAYCOVAL S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 96) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (96,719, N'BANIF - BANCO INTERNACIONAL DO FUNCHAL (BRASIL), S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 97) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (97,721, N'BANCO CREDIBEL S.A.'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 98) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (98,734, N'BANCO GERDAU S.A'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 99) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (99,735, N'BANCO POTTENCIAL S.A.'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200219_04.SQL b/Codemerx/Gestor.Application.Migration.Files.20200219_04.SQL new file mode 100644 index 0000000..16c421c --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200219_04.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[TIPOVENDEDOR] WHERE [IDTIPOVENDEDOR] = 1) +BEGIN + INSERT INTO [dbo].[TIPOVENDEDOR] ([IDTIPOVENDEDOR],[DESCRICAO]) VALUES (1, N'VENDEDOR'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200219_05.SQL b/Codemerx/Gestor.Application.Migration.Files.20200219_05.SQL new file mode 100644 index 0000000..fcd9539 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200219_05.SQL @@ -0,0 +1,768 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 1) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (1, N'ACURA'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 2) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (2, N'AGRALE'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 3) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (3, N'AGRALE'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 5) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (5, N'AUDI'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 6) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (6, N'BMW'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 7) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (7, N'BRM'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 8) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (8, N'BUGGY'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 9) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (9, N'CADILLAC'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 11) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (11, N'CHEVROLET'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 12) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (12, N'CHRYSLER'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 13) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (13, N'CITROEN'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 14) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (14, N'DAEWOO'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 15) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (15, N'DAIHATSU'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 16) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (16, N'DODGE'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 17) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (17, N'ENGESA'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 18) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (18, N'ENVEMO'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 19) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (19, N'FERRARI'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 20) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (20, N'FIAT'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 21) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (21, N'FORD'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 23) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (23, N'GMC'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 24) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (24, N'GURGEL'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 25) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (25, N'HONDA'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 26) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (26, N'HYUNDAI'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 28) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (28, N'ISUZU'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 29) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (29, N'IVECO'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 30) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (30, N'JAGUAR'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 31) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (31, N'JEEP'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 32) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (32, N'JPX'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 34) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (34, N'LADA'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 35) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (35, N'LAND ROVER'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 36) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (36, N'LEXUS'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 38) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (38, N'MARCOPOLO'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 39) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (39, N'MASERATI'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 40) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (40, N'MATRA'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 41) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (41, N'MAZDA'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 42) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (42, N'MERCEDES-BENZ'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 43) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (43, N'MERCURY'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 44) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (44, N'MINI'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 45) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (45, N'MITSUBISHI'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 46) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (46, N'MIURA'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 47) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (47, N'NAVISTAR'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 48) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (48, N'NISSAN'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 49) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (49, N'PEUGEOT'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 50) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (50, N'PLYMOUTH'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 51) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (51, N'PONTIAC'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 52) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (52, N'PORSCHE'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 53) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (53, N'PUMA-ALFA'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 54) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (54, N'RENAULT'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 55) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (55, N'ROVER'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 56) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (56, N'SAAB'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 57) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (57, N'SCANIA'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 58) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (58, N'SATURN'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 61) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (61, N'SEAT'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 62) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (62, N'SMART'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 63) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (63, N'SSANGYONG'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 64) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (64, N'SUBARU'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 65) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (65, N'SUZUKI'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 66) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (66, N'TOYOTA'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 67) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (67, N'TROLLER'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 68) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (68, N'VOLKSWAGEN'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 69) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (69, N'VOLVO'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 72) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (72, N'SEMI-REBOQUE'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 74) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (74, N'APRILIA'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 75) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (75, N'ATALA'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 76) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (76, N'BRANDY'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 77) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (77, N'BUELL'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 79) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (79, N'CAGIVA'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 80) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (80, N'CALOI'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 81) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (81, N'DAELIM'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 82) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (82, N'DUCATI'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 83) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (83, N'EMME'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 85) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (85, N'HARLEY-DAVIDSON'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 86) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (86, N'HUSQVARNA'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 88) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (88, N'KAHENA'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 89) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (89, N'KASINSKI'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 90) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (90, N'KAWASAKI'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 91) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (91, N'KTM'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 92) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (92, N'L AQUILA'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 93) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (93, N'MOTO GUZZI'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 95) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (95, N'MV AGUSTA'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 96) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (96, N'MVK'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 98) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (98, N'ORCA'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 99) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (99, N'PIAGGIO'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 100) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (100, N'RSANYANG'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 101) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (101, N'SUNDOWN'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 102) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (102, N'TRAXX'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 103) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (103, N'TRIUMPH'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 104) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (104, N'VENTO'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 105) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (105, N'YAMAHA'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 108) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (108, N'MIZA'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 109) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (109, N'GREEN'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 110) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (110, N'SHINERAY'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 111) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (111, N'MAHINDRA'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 112) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (112, N'CHANA'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 113) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (113, N'MALAGUTI'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 114) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (114, N'DAFRA'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 117) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (117, N'HUSABERG'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 118) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (118, N'AMAZONAS'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 119) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (119, N'FYM'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 120) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (120, N'BIMOTA'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 121) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (121, N'BRP'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 123) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (123, N'LAMBORGHINI'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 124) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (124, N'LOBINI'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 125) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (125, N'HAFEI'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 126) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (126, N'JINBEI'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 128) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (128, N'CHERY'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 129) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (129, N'SINOTRUK'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 130) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (130, N'TAC'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 131) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (131, N'DAYUN'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 132) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (132, N'LIFAN'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 133) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (133, N'ASTON MARTIN'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 134) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (134, N'JAC'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 135) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (135, N'JOHNNYPAG'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 137) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (137, N'CHANGAN'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 139) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (139, N'MAN'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 140) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (140, N'RELY'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 141) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (141, N'RAM'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 142) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (142, N'MOTORINO'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 144) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (144, N'GEELY'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 145) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (145, N'DAF'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 147) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (147, N'INDIAN'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 148) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (148, N'FOTON'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 150) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (150, N'ROYAL ENFIELD'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 151) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (151, N'KYMCO'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 152) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (152, N'MG'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 153) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (153, N'HAOJUE'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 154) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (154, N'AM GEN'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 155) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (155, N'ASIA MOTORS'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 156) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (156, N'CROSS LANDER'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 157) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (157, N'FIBRAVAN'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 158) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (158, N'FYBER'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 159) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (159, N'GREAT WALL'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 160) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (160, N'KIA MOTORS'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 161) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (161, N'LOTUS'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 162) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (162, N'ROLLS-ROYCE'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 163) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (163, N'WAKE'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 164) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (164, N'WALK'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 165) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (165, N'ADLY'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 166) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (166, N'BUGGY'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 167) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (167, N'CBT JIPE'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 168) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (168, N'BAJAJ'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 169) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (169, N'BEE'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 170) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (170, N'BENELLI'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 171) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (171, N'BETA'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 172) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (172, N'BRAVA'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 173) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (173, N'BUENO'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 174) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (174, N'BYCRISTO'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 175) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (175, N'DAYANG'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 176) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (176, N'DERBI'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 177) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (177, N'FOX'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 178) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (178, N'GARINNI'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 179) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (179, N'GAS GAS'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 180) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (180, N'HAOBAO'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 181) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (181, N'HARTFORD'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 182) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (182, N'HERO'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 183) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (183, N'IROS'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 184) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (184, N'JIAPENG VOLCANO'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 185) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (185, N'JONNY'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 186) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (186, N'LANDUM'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 187) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (187, N'LAVRALE'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 188) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (188, N'LERIVO'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 189) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (189, N'LON-V'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 190) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (190, N'MAGRAO TRICICLOS'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 191) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (191, N'MOTOCAR'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 192) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (192, N'MRX'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 193) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (193, N'PEGASSI'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 194) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (194, N'REGAL RAPTOR'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 195) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (195, N'RIGUETE'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 196) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (196, N'SIAMOTO'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 197) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (197, N'TARGOS'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 198) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (198, N'TIGER'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 199) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (199, N'WUYANG'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 200) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (200, N'CICCOBUS'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 201) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (201, N'EFFA-JMC'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 202) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (202, N'MASCARELLO'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 203) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (203, N'MAXIBUS'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 204) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (204, N'NEOBUS'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 205) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (205, N'SAAB-SCANIA'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 206) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (206, N'SHACMAN'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 207) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (207, N'SINOTRUK'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 208) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (208, N'ITAPEMIRIM'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 209) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (209, N'RANDON'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 210) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (210, N'ALFA ROMEO'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 211) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (211, N'FACCHINI'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 212) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (212, N'MASSEY FERGUSON'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 213) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (213, N'NEW HOLLAN'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 214) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (214, N'NOMA'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 215) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (215, N'CATERPILLAR'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 216) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (216, N'GUERRA'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 217) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (217, N'RECRUSUL'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 218) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (218, N'GUERRA'); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 219) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (219, N'GLOOV'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200219_06.SQL b/Codemerx/Gestor.Application.Migration.Files.20200219_06.SQL new file mode 100644 index 0000000..cde991c --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200219_06.SQL @@ -0,0 +1,544 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 1) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (1,5, N'Veiculo (Casco)', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 10) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (10,1, N'Roubo e/ou Furto Qualificado de Bens', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 1062) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (1062,3, N'PORTOES', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 1063) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (1063,3, N'ALAGAMENTO', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 1064) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (1064,3, N'CHUVEIROS', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 1065) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (1065,3, N'VAZAMENTO', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 1066) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (1066,3, N'DANOS MORAIS', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 1097) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (1097,5, N'Extensão Perímetro-Auto', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 11) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (11,1, N'Vendaval, Furacão, Ciclone, Tornado,...', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 12) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (12,1, N'Vidros, Espelhos e Mármores', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 1257) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (1257,37, N'Danos Estéticos Causados a Passageiros', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 1258) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (1258,37, N'Danos Estéticos Causados a Terceiros não Transportados', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 1299) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (1299,39, N'BÁSICA', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 13) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (13,1, N'Responsabilidade Civil Familiar', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 1300) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (1300,39, N'DESPESAS EXTRAORDINÁRIAS', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 1302) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (1302,39, N'DESPESAS COM DESENTULHO', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 1304) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (1304,39, N'OBRAS TEMPORÁRIAS', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 1306) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (1306,39, N'DESPESAS COM SALVAMENTO E CONTENÇÃO', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 1307) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (1307,39, N'DANOS MORAIS DECORRENTES DE RESPONSABILIDADE', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 1308) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (1308,39, N'RESPONSABILIDADE CIVIL SEM FUNDAÇÃO E CRUZADA', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 1309) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (1309,39, N'PROPRIEDADE PRÉ EXISTENTE NO CANTEIRO DE OBRA', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 1310) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (1310,39, N'EQUIPAMENTOS MÓVEIS E ESTACIONÁRIOS', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 1315) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (1315,39, N'RESPONSABILIDADE CIVIL EMPREGADOR', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 134) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (134,4, N'Roubo e/ou Furto Qualificado de Bens', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 135) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (135,4, N'Danos Materiais', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 136) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (136,4, N'Danos Corporais', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 137) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (137,4, N'Responsabilidade Civil', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 138) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (138,4, N'Danos Elétricos', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 14) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (14,1, N'Salvamento, Limpeza e/ou Desentulho', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 140) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (140,4, N'Básica', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 1422) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (1422,27, N'Básica – Obras Civis em Construção e Instalação e Montagem', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 16) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (16,5, N'Objetos Transportados', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 1609) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (1609,28, N'Notários e Registradores', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 1611) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (1611,28, N'Danos a Reputação', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 17) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (17,5, N'Danos Morais', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 18) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (18,5, N'Decessos', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 182) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (182,19, N'Propriedades Circunvizinhas', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 19) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (19,5, N'Assistência (Guincho)', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 193) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (193,6, N'Invalidez Permanente Por Doença Funcional', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 2) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (2,5, N'Danos Materiais', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 20) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (20,5, N'Assistência (Casa)', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 204) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (204,15, N'Incêndio', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 205) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (205,15, N'Danos Elétricos', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 21) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (21,5, N'Kit Gás', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 218) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (218,15, N'Aluguel', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 22) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (22,5, N'Blindagem', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 220) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (220,15, N'Energia Elétrica / Luz', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 224) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (224,18, N'Pinturas Interna', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 228) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (228,18, N'Danos ao Imovel', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 23) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (23,5, N'Acessórios', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 230) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (230,15, N'I.P.T.U.', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 232) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (232,15, N'Multa p/Resc.Contratual', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 233) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (233,15, N'Danos ao Imovel', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 234) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (234,4, N'Complemento Pagamento', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 24) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (24,5, N'Despesas Extras', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 240) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (240,1, N'Danos Rompimento de Tubulações', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 25) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (25,5, N'Carroceria', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 250) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (250,18, N'Luz', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 255) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (255,5, N'TETO SOLAR', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 256) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (256,6, N'Indenização Especial por Acidente', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 26) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (26,1, N'Danos causados por Veículos', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 264) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (264,4, N'Morte Acidental', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 265) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (265,4, N'Invalidez Permanente por Acidente', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 266) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (266,4, N'Despesas Médicas/Hospitalares', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 267) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (267,4, N'Extravio de bagagem', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 27) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (27,1, N'Despesas com Aluguel', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 28) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (28,2, N'Incêndio, Raio, Explosão, Tumultos', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 280) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (280,5, N'Roubo/Furto', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 29) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (29,2, N'Danos Elétricos', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 3) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (3,5, N'Danos Corporais', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 30) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (30,2, N'Vidros, Espelhos e Mármores', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 304) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (304,23, N'Cancelamento de Viagem', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 305) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (305,23, N'Interrupção de Viagem', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 31) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (31,2, N'Despesas com Aluguel', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 313) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (313,1, N'RC - Familiar', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 315) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (315,1, N'Ruptura de Tubulacoes', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 316) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (316,1, N'Impacto de Veiculo', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 317) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (317,1, N'Fumaca', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 32) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (32,2, N'Responsabilidade Civil', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 33) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (33,2, N'Roubo e/ou Furto Qualificado de Bens', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 34) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (34,1, N'Danos causados por Água', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 35) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (35,1, N'Perda de Documentos', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 351) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (351,23, N'Traslado de Corpo', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 352) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (352,23, N'Traslado Médico ', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 353) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (353,23, N'Regresso Sanitário', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 354) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (354,23, N'Hospedagem após Alta Hospitalar', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 357) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (357,23, N'Despesas Farmacêuticas Despesas Jurídicas', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 358) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (358,23, N'Pagamento de Fiança', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 36) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (36,5, N'Garantia 0KM', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 361) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (361,23, N'Despesas Médico Hospitalares e Odontológicas', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 362) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (362,23, N'Assistência Funeral Viagem', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 37) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (37,5, N'Despesas Médicas/Hospitalares', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 381) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (381,23, N'Hospedagem Acompanhante – Hospitalização Prolongada', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 39) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (39,1, N'Desmoronamento', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 4) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (4,5, N'Morte', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 40) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (40,1, N'Acidentes Domésticos', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 408) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (408,3, N'IPA', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 41) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (41,2, N'Vendaval, Furacão, Ciclone, Tornado,...', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 42) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (42,2, N'Despesas Fixas', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 432) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (432,18, N'Conteúdo', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 44) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (44,2, N'Tumultos, Greves, Lock-Out, ...', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 46) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (46,2, N'Equipamentos Eletrônicos', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 47) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (47,2, N'Equipamentos Estacionários', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 475) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (475,3, N'Auxílio Alimentação', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 48) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (48,2, N'Equipamentos Móveis', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 49) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (49,2, N'Assistência Empresarial', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 5) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (5,5, N'Invalidez', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 50) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (50,2, N'Perda de Documentos', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 51) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (51,2, N'Danos causados por Veículos', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 53) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (53,5, N'Acidentes Pessoais', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 54) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (54,5, N'Equipamentos', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 56) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (56,6, N'Morte', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 561) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (561,2, N'RESP. CIVIL GUARDA DE VEICULO', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 565) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (565,28, N'Propriedade Intelectual', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 569) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (569,28, N'Comparecimento ao Tribunal', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 57) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (57,6, N'Morte Acidental', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 58) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (58,6, N'Invalidez Permanente por Acidente', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 59) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (59,6, N'Funeral - Decessos', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 6) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (6,5, N'Vidros', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 64) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (64,3, N'Incêndio, Raio, Explosão', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 65) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (65,3, N'Danos Elétricos', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 66) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (66,3, N'Vidros, Espelhos e Mármores', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 69) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (69,3, N'Roubo e/ou Furto Qualificado de Bens', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 7) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (7,5, N'Carro Reserva', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 70) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (70,3, N'Vendaval, Furacão, Ciclone, Tornado,...', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 8) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (8,1, N'Incêndio, Raio, Explosão', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 80) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (80,1, N'Assistência 24 horas', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 819) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (819,28, N'Responsabilidade Civil Profissional', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 82) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (82,2, N'Operações', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 821) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (821,28, N'Ato Desonesto de Empregados', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 83) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (83,2, N'Empregador', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 85) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (85,2, N'Lucros Cessantes', 0); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 875) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (875,8, N'COBERTURA BÁSICA AMPLA A', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 9) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (9,1, N'Danos Elétricos', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 904) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (904,8, N'COBERTURA ADICIONAL DE RISCOS DE GREVES', 1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 909) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (909,8, N'COBERTURA ADICIONAL PARA MERCADORIAS TRANSPORTADAS EM VEÍCULOS DO SEGURADO', 1); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200311_07.SQL b/Codemerx/Gestor.Application.Migration.Files.20200311_07.SQL new file mode 100644 index 0000000..99220f5 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200311_07.SQL @@ -0,0 +1,14 @@ +IF EXISTS(SELECT 1 FROM [dbo].[cliente] WHERE [idempresa] IS NULL) +BEGIN + UPDATE [dbo].[cliente] SET [idempresa] = 1 WHERE [idempresa] IS NULL; +END + +IF EXISTS(SELECT 1 FROM [dbo].[parcela] WHERE [idempresa] IS NULL) +BEGIN + UPDATE [dbo].[parcela] SET [idempresa] = 1 WHERE [idempresa] IS NULL; +END + +IF EXISTS(SELECT 1 FROM [dbo].[parcela] WHERE [idempresa] IS NULL) +BEGIN + UPDATE [dbo].[parcela] SET [idempresa] = 1 WHERE [idempresa] IS NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200311_08.SQL b/Codemerx/Gestor.Application.Migration.Files.20200311_08.SQL new file mode 100644 index 0000000..0c1d85c --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200311_08.SQL @@ -0,0 +1,8 @@ +IF EXISTS(SELECT 1 FROM [dbo].[item] WHERE [cancelado] IS NULL) +BEGIN + UPDATE [dbo].[item] SET [cancelado] = 0 WHERE [cancelado] IS NULL; +END +IF EXISTS(SELECT 1 FROM [dbo].[item] WHERE [sinistrado] IS NULL) +BEGIN + UPDATE [dbo].[item] SET [sinistrado] = 0 WHERE [sinistrado] IS NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200403_09.SQL b/Codemerx/Gestor.Application.Migration.Files.20200403_09.SQL new file mode 100644 index 0000000..b201157 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200403_09.SQL @@ -0,0 +1,24 @@ +IF COL_LENGTH('[dbo].[cliente]', 'inativo') IS NULL +BEGIN + ALTER TABLE [dbo].[cliente] ADD inativo CHAR(1) NULL; +END + +IF COL_LENGTH('[dbo].[cliente]', 'cri_data') IS NULL +BEGIN + ALTER TABLE [dbo].[cliente] ADD cri_data DATETIME2 NULL; +END + +IF COL_LENGTH('[dbo].[cliente]', 'usuariocriacao') IS NULL +BEGIN + ALTER TABLE [dbo].[cliente] ADD usuariocriacao BIGINT NULL; +END + +IF COL_LENGTH('[dbo].[cliente]', 'atu_data') IS NULL +BEGIN + ALTER TABLE [dbo].[cliente] ADD atu_data DATETIME2 NULL; +END + +IF COL_LENGTH('[dbo].[cliente]', 'usuarioalteracao') IS NULL +BEGIN + ALTER TABLE [dbo].[cliente] ADD usuarioalteracao BIGINT NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200403_10.SQL b/Codemerx/Gestor.Application.Migration.Files.20200403_10.SQL new file mode 100644 index 0000000..ee55f30 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200403_10.SQL @@ -0,0 +1,16 @@ +IF COL_LENGTH('[dbo].[documento]', 'banco') IS NULL +BEGIN + ALTER TABLE [dbo].[documento] ADD banco VARCHAR(255) NULL; +END +IF COL_LENGTH('[dbo].[documento]', 'idresponsavel') IS NULL +BEGIN + ALTER TABLE [dbo].[documento] ADD idresponsavel BIGINT NULL; +END +IF COL_LENGTH('[dbo].[documento]', 'recto') IS NULL +BEGIN + ALTER TABLE [dbo].[documento] ADD recto CHAR(1) NULL; +END +IF COL_LENGTH('[dbo].[documento]', 'final_vig') IS NULL +BEGIN + ALTER TABLE [dbo].[documento] ADD final_vig CHAR(1) NULL; +END diff --git a/Codemerx/Gestor.Application.Migration.Files.20200403_11.SQL b/Codemerx/Gestor.Application.Migration.Files.20200403_11.SQL new file mode 100644 index 0000000..5e9ef96 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200403_11.SQL @@ -0,0 +1,29 @@ +IF COL_LENGTH('[dbo].[item]', 'idramo') IS NULL +BEGIN + ALTER TABLE [dbo].[item] ADD idramo BIGINT NULL; +END + +IF COL_LENGTH('[dbo].[item]', 'datacriacao') IS NULL +BEGIN + ALTER TABLE [dbo].[item] ADD datacriacao DATETIME2 NULL; +END + +IF COL_LENGTH('[dbo].[item]', 'usuariocriacao') IS NULL +BEGIN + ALTER TABLE [dbo].[item] ADD usuariocriacao BIGINT NULL; +END + +IF COL_LENGTH('[dbo].[item]', 'dataalteracao') IS NULL +BEGIN + ALTER TABLE [dbo].[item] ADD dataalteracao DATETIME2 NULL; +END + +IF COL_LENGTH('[dbo].[item]', 'usuarioalteracao') IS NULL +BEGIN + ALTER TABLE [dbo].[item] ADD usuarioalteracao BIGINT NULL; +END + +IF COL_LENGTH('[dbo].[item]', 'tipoendosso') IS NULL +BEGIN + ALTER TABLE [dbo].[item] ADD tipoendosso INTEGER NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200403_12.SQL b/Codemerx/Gestor.Application.Migration.Files.20200403_12.SQL new file mode 100644 index 0000000..83c76e7 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200403_12.SQL @@ -0,0 +1,19 @@ +IF COL_LENGTH('[dbo].[parcela]', 'cri_data') IS NULL +BEGIN + ALTER TABLE [dbo].[parcela] ADD cri_data DATETIME2 NULL; +END + +IF COL_LENGTH('[dbo].[parcela]', 'usuariocriacao') IS NULL +BEGIN + ALTER TABLE [dbo].[parcela] ADD usuariocriacao BIGINT NULL; +END + +IF COL_LENGTH('[dbo].[parcela]', 'atu_data') IS NULL +BEGIN + ALTER TABLE [dbo].[parcela] ADD atu_data DATETIME2 NULL; +END + +IF COL_LENGTH('[dbo].[parcela]', 'usuarioalteracao') IS NULL +BEGIN + ALTER TABLE [dbo].[parcela] ADD usuarioalteracao BIGINT NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200403_13.SQL b/Codemerx/Gestor.Application.Migration.Files.20200403_13.SQL new file mode 100644 index 0000000..bf2c0e4 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200403_13.SQL @@ -0,0 +1,19 @@ +IF COL_LENGTH('[dbo].[auto]', 'datacriacao') IS NULL +BEGIN + ALTER TABLE [dbo].[auto] ADD datacriacao DATETIME2 NULL; +END + +IF COL_LENGTH('[dbo].[auto]', 'usuariocriacao') IS NULL +BEGIN + ALTER TABLE [dbo].[auto] ADD usuariocriacao BIGINT NULL; +END + +IF COL_LENGTH('[dbo].[auto]', 'dataalteracao') IS NULL +BEGIN + ALTER TABLE [dbo].[auto] ADD dataalteracao DATETIME2 NULL; +END + +IF COL_LENGTH('[dbo].[auto]', 'usuarioalteracao') IS NULL +BEGIN + ALTER TABLE [dbo].[auto] ADD usuarioalteracao BIGINT NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200403_14.SQL b/Codemerx/Gestor.Application.Migration.Files.20200403_14.SQL new file mode 100644 index 0000000..44da860 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200403_14.SQL @@ -0,0 +1,29 @@ +IF COL_LENGTH('[dbo].[resempco]', 'tiporesidencia') IS NULL +BEGIN + ALTER TABLE [dbo].[resempco] ADD tiporesidencia NUMERIC(1,0) NULL; +END + +IF COL_LENGTH('[dbo].[resempco]', 'obs') IS NULL +BEGIN + ALTER TABLE [dbo].[resempco] ADD obs VARCHAR(MAX) NULL; +END + +IF COL_LENGTH('[dbo].[resempco]', 'datacriacao') IS NULL +BEGIN + ALTER TABLE [dbo].[resempco] ADD datacriacao DATETIME2 NULL; +END + +IF COL_LENGTH('[dbo].[resempco]', 'usuariocriacao') IS NULL +BEGIN + ALTER TABLE [dbo].[resempco] ADD usuariocriacao BIGINT NULL; +END + +IF COL_LENGTH('[dbo].[resempco]', 'dataalteracao') IS NULL +BEGIN + ALTER TABLE [dbo].[resempco] ADD dataalteracao DATETIME2 NULL; +END + +IF COL_LENGTH('[dbo].[resempco]', 'usuarioalteracao') IS NULL +BEGIN + ALTER TABLE [dbo].[resempco] ADD usuarioalteracao BIGINT NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200403_15.SQL b/Codemerx/Gestor.Application.Migration.Files.20200403_15.SQL new file mode 100644 index 0000000..f67a88f --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200403_15.SQL @@ -0,0 +1,19 @@ +IF COL_LENGTH('[dbo].[sinistro]', 'datacriacao') IS NULL +BEGIN + ALTER TABLE [dbo].[sinistro] ADD datacriacao DATETIME2 NULL; +END + +IF COL_LENGTH('[dbo].[sinistro]', 'usuariocriacao') IS NULL +BEGIN + ALTER TABLE [dbo].[sinistro] ADD usuariocriacao BIGINT NULL; +END + +IF COL_LENGTH('[dbo].[sinistro]', 'dataalteracao') IS NULL +BEGIN + ALTER TABLE [dbo].[sinistro] ADD dataalteracao DATETIME2 NULL; +END + +IF COL_LENGTH('[dbo].[sinistro]', 'usuarioalteracao') IS NULL +BEGIN + ALTER TABLE [dbo].[sinistro] ADD usuarioalteracao BIGINT NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200403_16.SQL b/Codemerx/Gestor.Application.Migration.Files.20200403_16.SQL new file mode 100644 index 0000000..4be0a0c --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200403_16.SQL @@ -0,0 +1,19 @@ +IF COL_LENGTH('[dbo].[cobertura]', 'datacriacao') IS NULL +BEGIN + ALTER TABLE [dbo].[cobertura] ADD datacriacao DATETIME2 NULL; +END + +IF COL_LENGTH('[dbo].[cobertura]', 'usuariocriacao') IS NULL +BEGIN + ALTER TABLE [dbo].[cobertura] ADD usuariocriacao BIGINT NULL; +END + +IF COL_LENGTH('[dbo].[cobertura]', 'dataalteracao') IS NULL +BEGIN + ALTER TABLE [dbo].[cobertura] ADD dataalteracao DATETIME2 NULL; +END + +IF COL_LENGTH('[dbo].[cobertura]', 'usuarioalteracao') IS NULL +BEGIN + ALTER TABLE [dbo].[cobertura] ADD usuarioalteracao BIGINT NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200403_17.SQL b/Codemerx/Gestor.Application.Migration.Files.20200403_17.SQL new file mode 100644 index 0000000..46884ac --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200403_17.SQL @@ -0,0 +1,19 @@ +IF COL_LENGTH('[dbo].[extrato]', 'datacriacao') IS NULL +BEGIN + ALTER TABLE [dbo].[extrato] ADD datacriacao DATETIME2 NULL; +END + +IF COL_LENGTH('[dbo].[extrato]', 'usuariocriacao') IS NULL +BEGIN + ALTER TABLE [dbo].[extrato] ADD usuariocriacao BIGINT NULL; +END + +IF COL_LENGTH('[dbo].[extrato]', 'dataalteracao') IS NULL +BEGIN + ALTER TABLE [dbo].[extrato] ADD dataalteracao DATETIME2 NULL; +END + +IF COL_LENGTH('[dbo].[extrato]', 'usuarioalteracao') IS NULL +BEGIN + ALTER TABLE [dbo].[extrato] ADD usuarioalteracao BIGINT NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200403_18.SQL b/Codemerx/Gestor.Application.Migration.Files.20200403_18.SQL new file mode 100644 index 0000000..976212a --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200403_18.SQL @@ -0,0 +1,4 @@ +IF COL_LENGTH('[dbo].[cliendereco]', 'padrao') IS NULL +BEGIN + ALTER TABLE [dbo].[cliendereco] ADD padrao CHAR(1) NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200403_19.SQL b/Codemerx/Gestor.Application.Migration.Files.20200403_19.SQL new file mode 100644 index 0000000..2cd86f2 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200403_19.SQL @@ -0,0 +1,14 @@ +IF COL_LENGTH('[dbo].[clitelefone]', 'padrao') IS NULL +BEGIN + ALTER TABLE [dbo].[clitelefone] ADD padrao CHAR(1) NULL; +END + +IF COL_LENGTH('[dbo].[clitelefone]', 'operadora') IS NULL +BEGIN + ALTER TABLE [dbo].[clitelefone] ADD operadora NUMERIC(5,0) NULL; +END + +IF COL_LENGTH('[dbo].[clitelefone]', 'ramal') IS NULL +BEGIN + ALTER TABLE [dbo].[clitelefone] ADD ramal VARCHAR(5) NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200403_20.SQL b/Codemerx/Gestor.Application.Migration.Files.20200403_20.SQL new file mode 100644 index 0000000..3fa84a4 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200403_20.SQL @@ -0,0 +1,4 @@ +IF COL_LENGTH('[dbo].[climail]', 'padrao') IS NULL +BEGIN + ALTER TABLE [dbo].[climail] ADD padrao CHAR(1) NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200403_21.SQL b/Codemerx/Gestor.Application.Migration.Files.20200403_21.SQL new file mode 100644 index 0000000..df4427a --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200403_21.SQL @@ -0,0 +1,19 @@ +IF COL_LENGTH('[dbo].[vendedorparcela]', 'cri_data') IS NULL +BEGIN + ALTER TABLE [dbo].[vendedorparcela] ADD cri_data DATETIME2 NULL; +END + +IF COL_LENGTH('[dbo].[vendedorparcela]', 'usuariocriacao') IS NULL +BEGIN + ALTER TABLE [dbo].[vendedorparcela] ADD usuariocriacao BIGINT NULL; +END + +IF COL_LENGTH('[dbo].[vendedorparcela]', 'atu_data') IS NULL +BEGIN + ALTER TABLE [dbo].[vendedorparcela] ADD atu_data DATETIME2 NULL; +END + +IF COL_LENGTH('[dbo].[vendedorparcela]', 'usuarioalteracao') IS NULL +BEGIN + ALTER TABLE [dbo].[vendedorparcela] ADD usuarioalteracao BIGINT NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200403_22.SQL b/Codemerx/Gestor.Application.Migration.Files.20200403_22.SQL new file mode 100644 index 0000000..8e42802 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200403_22.SQL @@ -0,0 +1,4 @@ +IF COL_LENGTH('[dbo].[perfil]', 'banco') IS NULL +BEGIN + ALTER TABLE [dbo].[perfil] ADD banco VARCHAR(3) NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200403_23.SQL b/Codemerx/Gestor.Application.Migration.Files.20200403_23.SQL new file mode 100644 index 0000000..76c5ccc --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200403_23.SQL @@ -0,0 +1,19 @@ +IF COL_LENGTH('[dbo].[newarquivodigital]', 'datacriacao') IS NULL +BEGIN + ALTER TABLE [dbo].[newarquivodigital] ADD datacriacao DATETIME2 NULL; +END + +IF COL_LENGTH('[dbo].[newarquivodigital]', 'usuariocriacao') IS NULL +BEGIN + ALTER TABLE [dbo].[newarquivodigital] ADD usuariocriacao BIGINT NULL; +END + +IF COL_LENGTH('[dbo].[newarquivodigital]', 'dataalteracao') IS NULL +BEGIN + ALTER TABLE [dbo].[newarquivodigital] ADD dataalteracao DATETIME2 NULL; +END + +IF COL_LENGTH('[dbo].[newarquivodigital]', 'usuarioalteracao') IS NULL +BEGIN + ALTER TABLE [dbo].[newarquivodigital] ADD usuarioalteracao BIGINT NULL; +END diff --git a/Codemerx/Gestor.Application.Migration.Files.20200406_24.SQL b/Codemerx/Gestor.Application.Migration.Files.20200406_24.SQL new file mode 100644 index 0000000..393e57c --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200406_24.SQL @@ -0,0 +1,38 @@ +IF (NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'controlelog')) +BEGIN + +CREATE TABLE [dbo].[controlelog]( +[idcontrolelog] [bigint] IDENTITY(1,1) NOT NULL PRIMARY KEY, +[bdname] [varchar](255) NULL, +[tabela] [varchar](255) NULL); + +DECLARE @banco VARCHAR(255) = (SELECT DB_NAME()); + +INSERT INTO [dbo].[controlelog] VALUES (@banco, N'oldbacklog'); + +CREATE TABLE [dbo].[actionlog]( +[IDACTION] [bigint] IDENTITY(1,1) NOT NULL PRIMARY KEY, +[IDEMPRESA] [bigint] NULL, +[FORM] [varchar](30) NULL, +[DESCRICAO] [varchar](50) NULL, +[ACAO] [varchar](200) NULL, +[IDNAME] [varchar](30) NULL, +[ID] [bigint] NULL, +[IDUSUARIO] [bigint] NULL, +[DATA] [datetime] NULL, +[historico] [VARCHAR](MAX) NULL, +[maquina] [VARCHAR](100) NULL); + +CREATE TABLE [dbo].[oldbacklog]( +[IDBACKLOG] [bigint] IDENTITY(1,1) NOT NULL PRIMARY KEY, +[IDEMPRESA] [bigint] NULL, +[FORM] [varchar](30) NULL, +[DESCRICAO] [varchar](50) NULL, +[HISTORICO] [text] NULL, +[IDNAME] [varchar](30) NULL, +[ID] [bigint] NULL, +[INCLUINDO] [numeric](1, 0) NULL, +[IDUSUARIO] [bigint] NULL, +[DATA] [datetime] NULL); + +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200406_25.SQL b/Codemerx/Gestor.Application.Migration.Files.20200406_25.SQL new file mode 100644 index 0000000..cd14e5c --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200406_25.SQL @@ -0,0 +1,4 @@ +IF COL_LENGTH('[dbo].[empresa]', 'newad') IS NULL +BEGIN + ALTER TABLE [dbo].[empresa] ADD [newad] varchar(1) NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200406_26.SQL b/Codemerx/Gestor.Application.Migration.Files.20200406_26.SQL new file mode 100644 index 0000000..531011c --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200406_26.SQL @@ -0,0 +1,4 @@ +IF COL_LENGTH('[dbo].[empresa]', 'newad') IS NOT NULL +BEGIN + UPDATE [dbo].[empresa] SET newad='1'; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200408_27.SQL b/Codemerx/Gestor.Application.Migration.Files.20200408_27.SQL new file mode 100644 index 0000000..7cd1ee1 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200408_27.SQL @@ -0,0 +1,19 @@ +IF COL_LENGTH('[dbo].[parcelaextrato]', 'datacriacao') IS NULL +BEGIN + ALTER TABLE [dbo].[parcelaextrato] ADD datacriacao DATETIME2 NULL; +END + +IF COL_LENGTH('[dbo].[parcelaextrato]', 'usuariocriacao') IS NULL +BEGIN + ALTER TABLE [dbo].[parcelaextrato] ADD usuariocriacao BIGINT NULL; +END + +IF COL_LENGTH('[dbo].[parcelaextrato]', 'dataalteracao') IS NULL +BEGIN + ALTER TABLE [dbo].[parcelaextrato] ADD dataalteracao DATETIME2 NULL; +END + +IF COL_LENGTH('[dbo].[parcelaextrato]', 'usuarioalteracao') IS NULL +BEGIN + ALTER TABLE [dbo].[parcelaextrato] ADD usuarioalteracao BIGINT NULL; +END diff --git a/Codemerx/Gestor.Application.Migration.Files.20200408_28.SQL b/Codemerx/Gestor.Application.Migration.Files.20200408_28.SQL new file mode 100644 index 0000000..2ea9c61 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200408_28.SQL @@ -0,0 +1,19 @@ +IF COL_LENGTH('[dbo].[granizo]', 'datacriacao') IS NULL +BEGIN + ALTER TABLE [dbo].[granizo] ADD datacriacao DATETIME2 NULL; +END + +IF COL_LENGTH('[dbo].[granizo]', 'usuariocriacao') IS NULL +BEGIN + ALTER TABLE [dbo].[granizo] ADD usuariocriacao BIGINT NULL; +END + +IF COL_LENGTH('[dbo].[granizo]', 'dataalteracao') IS NULL +BEGIN + ALTER TABLE [dbo].[granizo] ADD dataalteracao DATETIME2 NULL; +END + +IF COL_LENGTH('[dbo].[granizo]', 'usuarioalteracao') IS NULL +BEGIN + ALTER TABLE [dbo].[granizo] ADD usuarioalteracao BIGINT NULL; +END diff --git a/Codemerx/Gestor.Application.Migration.Files.20200408_29.SQL b/Codemerx/Gestor.Application.Migration.Files.20200408_29.SQL new file mode 100644 index 0000000..3419e2d --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200408_29.SQL @@ -0,0 +1,40 @@ +IF COL_LENGTH('[dbo].[coberturagranizo]', 'datacriacao') IS NULL +BEGIN + ALTER TABLE [dbo].[coberturagranizo] ADD datacriacao DATETIME2 NULL; +END + +IF COL_LENGTH('[dbo].[coberturagranizo]', 'usuariocriacao') IS NULL +BEGIN + ALTER TABLE [dbo].[coberturagranizo] ADD usuariocriacao BIGINT NULL; +END + +IF COL_LENGTH('[dbo].[coberturagranizo]', 'dataalteracao') IS NULL +BEGIN + ALTER TABLE [dbo].[coberturagranizo] ADD dataalteracao DATETIME2 NULL; +END + +IF COL_LENGTH('[dbo].[coberturagranizo]', 'usuarioalteracao') IS NULL +BEGIN + ALTER TABLE [dbo].[coberturagranizo] ADD usuarioalteracao BIGINT NULL; +END + +IF COL_LENGTH('[dbo].[riscosdiversos]', 'datacriacao') IS NULL +BEGIN + ALTER TABLE [dbo].[riscosdiversos] ADD datacriacao DATETIME2 NULL; +END + +IF COL_LENGTH('[dbo].[riscosdiversos]', 'usuariocriacao') IS NULL +BEGIN + ALTER TABLE [dbo].[riscosdiversos] ADD usuariocriacao BIGINT NULL; +END + +IF COL_LENGTH('[dbo].[riscosdiversos]', 'dataalteracao') IS NULL +BEGIN + ALTER TABLE [dbo].[riscosdiversos] ADD dataalteracao DATETIME2 NULL; +END + +IF COL_LENGTH('[dbo].[riscosdiversos]', 'usuarioalteracao') IS NULL +BEGIN + ALTER TABLE [dbo].[riscosdiversos] ADD usuarioalteracao BIGINT NULL; +END + diff --git a/Codemerx/Gestor.Application.Migration.Files.20200408_30.SQL b/Codemerx/Gestor.Application.Migration.Files.20200408_30.SQL new file mode 100644 index 0000000..4d4c039 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200408_30.SQL @@ -0,0 +1,19 @@ +IF COL_LENGTH('[dbo].[vida]', 'datacriacao') IS NULL +BEGIN + ALTER TABLE [dbo].[vida] ADD datacriacao DATETIME2 NULL; +END + +IF COL_LENGTH('[dbo].[vida]', 'usuariocriacao') IS NULL +BEGIN + ALTER TABLE [dbo].[vida] ADD usuariocriacao BIGINT NULL; +END + +IF COL_LENGTH('[dbo].[vida]', 'dataalteracao') IS NULL +BEGIN + ALTER TABLE [dbo].[vida] ADD dataalteracao DATETIME2 NULL; +END + +IF COL_LENGTH('[dbo].[vida]', 'usuarioalteracao') IS NULL +BEGIN + ALTER TABLE [dbo].[vida] ADD usuarioalteracao BIGINT NULL; +END diff --git a/Codemerx/Gestor.Application.Migration.Files.20200408_31.SQL b/Codemerx/Gestor.Application.Migration.Files.20200408_31.SQL new file mode 100644 index 0000000..4b03778 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200408_31.SQL @@ -0,0 +1,28 @@ +IF (NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'titular')) +BEGIN + +CREATE TABLE [dbo].[titular]( + [IDTITULAR] [bigint] IDENTITY(1,1) NOT NULL PRIMARY KEY, + [idvida] [bigint] NULL, + [plano] [varchar](120) NULL, + [nome] [varchar](120) NULL, + [nascimento] [date] NULL, + [CGCCPF] [varchar](18) NULL, + [certificado] [varchar](30) NULL, + [matricula] [varchar](30) NULL, + [capital] [numeric](12, 2) NULL, + [premio] [numeric](8, 2) NULL, + [usuariocriacao] [bigint] NULL, + [usuarioalteracao] [bigint] NULL, + [datacriacao] [datetime] NULL, + [dataalteracao] [datetime] NULL, + [idtitularcopiado] [bigint] NULL, + [saida] [date] NULL, + [obs] [varchar](max) NULL, + [RG] [varchar](13) NULL, + [emissao] [date] NULL, + [rguf] [varchar](2) NULL, + [entrada] [date] NULL); + +END + diff --git a/Codemerx/Gestor.Application.Migration.Files.20200408_32.SQL b/Codemerx/Gestor.Application.Migration.Files.20200408_32.SQL new file mode 100644 index 0000000..027e5a0 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200408_32.SQL @@ -0,0 +1,34 @@ + +IF (NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'beneficiario')) +BEGIN + +CREATE TABLE [dbo].[beneficiario]( + [IDBENEFICIARIO] [bigint] IDENTITY(1,1) NOT NULL PRIMARY KEY, + [idtitular] [bigint] NULL, + [idparentesco] [bigint] NULL, + [nome] [varchar](120) NULL, + [CEP] [varchar](10) NULL, + [ENDERECO] [varchar](60) NULL, + [NUMERO] [varchar](5) NULL, + [CIDADE] [varchar](30) NULL, + [UF] [varchar](2) NULL, + [BAIRRO] [varchar](60) NULL, + [CGCCPF] [varchar](18) NULL, + [RG] [varchar](13) NULL, + [emissao] [date] NULL, + [rguf] [varchar](2) NULL, + [beneficio] [numeric](6, 2) NULL, + [usuariocriacao] [bigint] NULL, + [usuarioalteracao] [bigint] NULL, + [datacriacao] [datetime] NULL, + [dataalteracao] [datetime] NULL, + [complemento] [varchar](30) NULL, + [saida] [date] NULL, + [obs] [varchar](max) NULL, + [idprofissao] [bigint] NULL, + [iditem] [bigint] NULL, + [entrada] [date] NULL, + [porcentagem] [numeric](6, 2) NULL, + [dtnasc] [date] NULL); + +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200419_33.SQL b/Codemerx/Gestor.Application.Migration.Files.20200419_33.SQL new file mode 100644 index 0000000..7b6fe28 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200419_33.SQL @@ -0,0 +1,4 @@ +IF COL_LENGTH('[dbo].[controledbad]', 'tabela') IS NULL +BEGIN + ALTER TABLE [dbo].[controledbad] ADD tabela VARCHAR(255) NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200419_34.SQL b/Codemerx/Gestor.Application.Migration.Files.20200419_34.SQL new file mode 100644 index 0000000..a9761dd --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200419_34.SQL @@ -0,0 +1,4 @@ +IF EXISTS(SELECT 1 FROM [dbo].[controledbad] WHERE [tabela] IS NULL) +BEGIN + UPDATE [controledbad] SET [tabela] = N'arquivodigital' WHERE [tabela] IS NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200430_35.SQL b/Codemerx/Gestor.Application.Migration.Files.20200430_35.SQL new file mode 100644 index 0000000..e6f919d --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200430_35.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Meta') AND COL_LENGTH('[dbo].[Meta]', 'IdSeguradora') IS NOT NULL +BEGIN + ALTER TABLE [dbo].[Meta] ALTER COLUMN IdSeguradora BIGINT NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200505_36.SQL b/Codemerx/Gestor.Application.Migration.Files.20200505_36.SQL new file mode 100644 index 0000000..35fffa4 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200505_36.SQL @@ -0,0 +1,4 @@ +IF COL_LENGTH('[dbo].[extratoconfig]', 'codigocia') IS NULL +BEGIN + ALTER TABLE [dbo].[extratoconfig] ADD codigocia VARCHAR(20) NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200505_37.SQL b/Codemerx/Gestor.Application.Migration.Files.20200505_37.SQL new file mode 100644 index 0000000..b0bf10e --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200505_37.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 291) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (291, N'ITAU SEGUROS DE AUTO E RESIDNCIA S/A', 1, 2); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200505_38.SQL b/Codemerx/Gestor.Application.Migration.Files.20200505_38.SQL new file mode 100644 index 0000000..c5eb8f8 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200505_38.SQL @@ -0,0 +1,9 @@ +IF COL_LENGTH('[dbo].[documento]', 'atu_data') IS NULL +BEGIN + ALTER TABLE [dbo].[documento] ADD atu_data DATETIME2 NULL; +END + +IF COL_LENGTH('[dbo].[documento]', 'usuarioalteracao') IS NULL +BEGIN + ALTER TABLE [dbo].[documento] ADD usuarioalteracao BIGINT NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200505_39.SQL b/Codemerx/Gestor.Application.Migration.Files.20200505_39.SQL new file mode 100644 index 0000000..4b55cf6 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200505_39.SQL @@ -0,0 +1,14 @@ +IF (NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'averbacao')) +BEGIN + CREATE TABLE [dbo].[averbacao]( + [idaverbacao] [bigint] IDENTITY(1,1) NOT NULL PRIMARY KEY, + [idparcela] [bigint] NULL, + [origem] [varchar](250) NULL, + [destino] [varchar](250) NULL, + [movimento] [numeric](20, 2) NULL, + [premio] [numeric](15, 2) NULL, + [usuariocriacao] [bigint] NULL, + [usuarioalteracao] [bigint] NULL, + [datacriacao] [datetime] NULL, + [dataalteracao] [datetime] NULL); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200506_40.SQL b/Codemerx/Gestor.Application.Migration.Files.20200506_40.SQL new file mode 100644 index 0000000..5df5db0 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200506_40.SQL @@ -0,0 +1,12 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 272) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (272, N'ICATU CAPITALIZAÇÃO S.A.', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 484) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (484, N'SUL AMERICA SEGUROS DE PESSOAS E PREVID', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 62) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (62, N'PRESTAMISTA',0.0738,0,0); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200512_41.SQL b/Codemerx/Gestor.Application.Migration.Files.20200512_41.SQL new file mode 100644 index 0000000..b92048a --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200512_41.SQL @@ -0,0 +1,62 @@ +IF (NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'mensagempadrao')) +BEGIN + + CREATE TABLE [dbo].[mensagempadrao] ( + [id] int NOT NULL PRIMARY KEY, + [conteudo] nvarchar(max) NULL, + [titulo] nvarchar(255) NULL, + [filter] nvarchar(max) NULL, + [field] nvarchar(100) NULL); + +END + +IF (NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'mensagem')) +BEGIN + + CREATE TABLE [dbo].[mensagem] ( + [id] bigint IDENTITY(1,1) NOT NULL PRIMARY KEY, + [conteudo] nvarchar(max) NULL, + [titulo] nvarchar(255) NULL, + [envio] datetime2 NULL, + [lido] bit NULL, + [idcliente] bigint NULL, + [idusuario] int NULL, + [idpadrao] int NULL); + +END + +IF (NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Device')) +BEGIN + + CREATE TABLE [dbo].[Device] ( + [Id] bigint IDENTITY(1,1) NOT NULL PRIMARY KEY, + [DeviceId] nvarchar(255) NULL, + [IdCliente] bigint NULL); + +END + +IF (NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'logconvite')) +BEGIN + + CREATE TABLE [dbo].[logconvite] ( + [id] int IDENTITY(1,1) NOT NULL, + [idcliente] bigint NULL, + [email] nvarchar(250) NULL, + [sent] bit NULL, + [idusuario] bigint NULL, + [data] datetime2 NULL); + +END + +IF (NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'mensagemenviada')) +BEGIN + + CREATE TABLE [dbo].[mensagemenviada] ( + [id] int IDENTITY(1,1) NOT NULL PRIMARY KEY, + [resposta] nvarchar(max) NULL, + [idusuario] int NULL, + [idpadrao] int NULL, + [data] datetime2 NULL); + + +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200512_42.SQL b/Codemerx/Gestor.Application.Migration.Files.20200512_42.SQL new file mode 100644 index 0000000..07585f9 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200512_42.SQL @@ -0,0 +1,19 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[mensagempadrao] WHERE [id] = 1) +BEGIN + INSERT INTO [dbo].[mensagempadrao] ([id], [conteudo], [titulo], [filter], [field]) VALUES (N'1', N'Prezado Cliente, informamos que sua apólice de seguro foi emitida. Acesse seu aplicativo e faça o download da sua Apólice. Obrigado.', N'Aviso de Apólice Emitida', N'SELECT DISTINCT c.idcliente FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole WHERE (d.excluido IS NULL OR d.excluido != 1)', N'd.emissao'); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[mensagempadrao] WHERE [id] = 2) +BEGIN +INSERT INTO [dbo].[mensagempadrao] ([id], [conteudo], [titulo], [filter], [field]) VALUES (N'2', N'Prezado Cliente, informamos que seu seguros está prestes a vencer. Pedimos gentilmente que aguarde nosso contato para realizarmos sua renovação. Obrigado.', N'Aviso de Renovações', N'SELECT DISTINCT c.idcliente FROM controle c CROSS APPLY (SELECT TOP 1 excluido, vigencia2, iddocumento FROM documento WHERE idcontrole = c.idcontrole AND excluido IS NULL ORDER BY IDDOCUMENTO) d WHERE (d.excluido IS NULL OR d.excluido != 1)', N'd.vigencia2'); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[mensagempadrao] WHERE [id] = 3) +BEGIN +INSERT INTO [dbo].[mensagempadrao] ([id], [conteudo], [titulo], [filter], [field]) VALUES (N'3', N'Prezado Cliente, informamos que a parcela do seu seguro esta prestes a vencer. Pedimos atenção aos clientes que optaram pelo pagamento em boleto. Se optou por débito automático ou cartão, fique tranquilo o débito deve ser efetuado automaticamente.', N'Aviso de Vencimento de Parcela', N'SELECT DISTINCT c.idcliente FROM parcela p INNER JOIN documento d on d.iddocumento = p.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole WHERE (d.excluido IS NULL OR d.excluido != 1)', N'p.vencto'); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[mensagempadrao] WHERE [id] = 4) +BEGIN +INSERT INTO [dbo].[mensagempadrao] ([id], [conteudo], [titulo], [filter], [field]) VALUES (N'4', NULL, N'Aviso Personalizado', N'SELECT DISTINCT c.idcliente FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole WHERE (d.excluido IS NULL OR d.excluido != 1) AND c.IDCLIENTE IS NOT NULL', NULL) +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200512_43.SQL b/Codemerx/Gestor.Application.Migration.Files.20200512_43.SQL new file mode 100644 index 0000000..956b889 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200512_43.SQL @@ -0,0 +1,4 @@ +IF COL_LENGTH('[dbo].[usuario]', 'inativo') IS NULL +BEGIN + ALTER TABLE [dbo].[usuario] ADD inativo nvarchar(1) NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200514_44.SQL b/Codemerx/Gestor.Application.Migration.Files.20200514_44.SQL new file mode 100644 index 0000000..10f93cd --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200514_44.SQL @@ -0,0 +1,4 @@ +IF COL_LENGTH('[dbo].[extratoconfig]', 'descricao') IS NULL +BEGIN + ALTER TABLE [dbo].[extratoconfig] ADD descricao nvarchar(255) NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200514_45.SQL b/Codemerx/Gestor.Application.Migration.Files.20200514_45.SQL new file mode 100644 index 0000000..7ef7b2f --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200514_45.SQL @@ -0,0 +1,109 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[extratoconfig] WHERE [idciaseg] = 400 AND [codigocia] = '35') +BEGIN + INSERT INTO [dbo].[extratoconfig] ([idciaseg], [codigocia], [descricao], [ativo]) VALUES (400, N'35', N'Defasagem de Cheque', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[extratoconfig] WHERE [idciaseg] = 400 AND [codigocia] = '45') +BEGIN +INSERT INTO [dbo].[extratoconfig] ([idciaseg], [codigocia], [descricao], [ativo]) VALUES (400, N'45', N'Comissão Fracionada', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[extratoconfig] WHERE [idciaseg] = 400 AND [codigocia] = '69') +BEGIN +INSERT INTO [dbo].[extratoconfig] ([idciaseg], [codigocia], [descricao], [ativo]) VALUES (400, N'69', N'Comissão Total', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[extratoconfig] WHERE [idciaseg] = 400 AND [codigocia] = '70') +BEGIN +INSERT INTO [dbo].[extratoconfig] ([idciaseg], [codigocia], [descricao], [ativo]) VALUES (400, N'70', N'Comissão Total Endosso', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[extratoconfig] WHERE [idciaseg] = 400 AND [codigocia] = '107') +BEGIN +INSERT INTO [dbo].[extratoconfig] ([idciaseg], [codigocia], [descricao], [ativo]) VALUES (400, N'107' , N'Emissão Cartão Porto Seguro', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[extratoconfig] WHERE [idciaseg] = 400 AND [codigocia] = '150') +BEGIN +INSERT INTO [dbo].[extratoconfig] ([idciaseg], [codigocia], [descricao], [ativo]) VALUES (400, N'150' , N'Cartão Porto Seguro', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[extratoconfig] WHERE [idciaseg] = 400 AND [codigocia] = '5') +BEGIN +INSERT INTO [dbo].[extratoconfig] ([idciaseg], [codigocia], [descricao], [ativo]) VALUES (400, N'5', N'Acerto Taxa', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[extratoconfig] WHERE [idciaseg] = 400 AND [codigocia] = '1') +BEGIN +INSERT INTO [dbo].[extratoconfig] ([idciaseg], [codigocia], [descricao], [ativo]) VALUES (400, N'1', N'Antecipação', 0); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[extratoconfig] WHERE [idciaseg] = 400 AND [codigocia] = '2') +BEGIN +INSERT INTO [dbo].[extratoconfig] ([idciaseg], [codigocia], [descricao], [ativo]) VALUES (400, N'2', N'Recuperação Antecipação', 0); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[extratoconfig] WHERE [idciaseg] = 400 AND [codigocia] = '21') +BEGIN +INSERT INTO [dbo].[extratoconfig] ([idciaseg], [codigocia], [descricao], [ativo]) VALUES (400, N'21', N'Acerto Fracionado', 0); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[extratoconfig] WHERE [idciaseg] = 259 AND [codigocia] = '1') +BEGIN +INSERT INTO [dbo].[extratoconfig] ([idciaseg], [codigocia], [descricao], [ativo]) VALUES (259, N'1', N'Parcela Especial', 0); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[extratoconfig] WHERE [idciaseg] = 400 AND [codigocia] = '149') +BEGIN +INSERT INTO [dbo].[extratoconfig] ([idciaseg], [codigocia], [descricao], [ativo]) VALUES (400, N'149', N'Cartão Porto Seguro',0); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[extratoconfig] WHERE [idciaseg] = 400 AND [codigocia] = '1391rv') +BEGIN +INSERT INTO [dbo].[extratoconfig] ([idciaseg], [codigocia], [descricao], [ativo]) VALUES (400, N'1391rv', N'Desconsiderar Nº Endosso Vida',0); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[extratoconfig] WHERE [idciaseg] = 501 AND [codigocia] = '1') +BEGIN +INSERT INTO [dbo].[extratoconfig] ([idciaseg], [codigocia], [descricao], [ativo]) VALUES (501, N'1', N'Bônus "PLUS AUTO”', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[extratoconfig] WHERE [idciaseg] = 19 AND [codigocia] = '1') +BEGIN +INSERT INTO [dbo].[extratoconfig] ([idciaseg], [codigocia], [descricao], [ativo]) VALUES (19, N'1', N'Bônus "PLUS”', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[extratoconfig] WHERE [idciaseg] = 595 AND [codigocia] = 'viacorretor') +BEGIN +INSERT INTO [dbo].[extratoconfig] ([idciaseg], [codigocia], [descricao], [ativo]) VALUES (595, N'viacorretor', N'Importar Via Corretor', 0); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[extratoconfig] WHERE [idciaseg] = 216 AND [codigocia] = 'Fed999') +BEGIN +INSERT INTO [dbo].[extratoconfig] ([idciaseg], [codigocia], [descricao], [ativo]) VALUES (216, N'Fed999', N'Importar Sub. Fed. como 999', 0); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[extratoconfig] WHERE [idciaseg] = 216 AND [codigocia] = 'Est999') +BEGIN +INSERT INTO [dbo].[extratoconfig] ([idciaseg], [codigocia], [descricao], [ativo]) VALUES (216, N'Est999', N'Importar Sub. Est. como 999', 0); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[extratoconfig] WHERE [idciaseg] = 92 AND [codigocia] = '1') +BEGIN +INSERT INTO [dbo].[extratoconfig] ([idciaseg], [codigocia], [descricao], [ativo]) VALUES (92, N'1', N'Parcela Especial', 0); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[extratoconfig] WHERE [idciaseg] = 400 AND [codigocia] = '72') +BEGIN +INSERT INTO [dbo].[extratoconfig] ([idciaseg], [codigocia], [descricao], [ativo]) VALUES (400, N'72', N'Cancelamento da Apólice', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[extratoconfig] WHERE [idciaseg] = 70 AND [codigocia] = '1') +BEGIN +INSERT INTO [dbo].[extratoconfig] ([idciaseg], [codigocia], [descricao], [ativo]) VALUES (70, N'1', N'Parcela Especial', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[extratoconfig] WHERE [idciaseg] = 400 AND [codigocia] = '148') +BEGIN +INSERT INTO [dbo].[extratoconfig] ([idciaseg], [codigocia], [descricao], [ativo]) VALUES (400, N'148', N'Cartão Porto Seguro', 1); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200520_46.SQL b/Codemerx/Gestor.Application.Migration.Files.20200520_46.SQL new file mode 100644 index 0000000..e8cefcf --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200520_46.SQL @@ -0,0 +1,4 @@ +IF EXISTS(SELECT 1 FROM [dbo].[perfil] WHERE [sexo] = '0') +BEGIN + UPDATE [dbo].[perfil] SET [sexo] = '1' WHERE [sexo] = '0'; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200520_47.SQL b/Codemerx/Gestor.Application.Migration.Files.20200520_47.SQL new file mode 100644 index 0000000..a746d63 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200520_47.SQL @@ -0,0 +1,8 @@ +IF (NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'ciavend')) +BEGIN + CREATE TABLE [dbo].[ciavend] ( + [idciavend] [bigint] IDENTITY(1,1) NOT NULL PRIMARY KEY, + [idciaseg] [bigint] NOT NULL, + [idramo] [bigint] NOT NULL, + [idvendedor] [bigint] NOT NULL); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200525_48.SQL b/Codemerx/Gestor.Application.Migration.Files.20200525_48.SQL new file mode 100644 index 0000000..d38b146 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200525_48.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 403) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (403, N'POTTENCIAL SEGURADORA SA', 1, 2); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200527_49.SQL b/Codemerx/Gestor.Application.Migration.Files.20200527_49.SQL new file mode 100644 index 0000000..f39021c --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200527_49.SQL @@ -0,0 +1,39 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[controledbad]) +BEGIN + DECLARE @banco VARCHAR(255) = (SELECT DB_NAME()); + INSERT INTO [dbo].[controledbad] (bdname, tabela) VALUES (@banco, N'Arquivos'); + + CREATE TABLE [dbo].[Arquivos]( + [IDARQUIVODIGITAL] [bigint] IDENTITY(1,1) NOT NULL PRIMARY KEY, + [IDCLIENTE] [bigint] NULL, + [IDDOCUMENTO] [bigint] NULL, + [IDATENDIMENTO] [bigint] NULL, + [IDITEM] [bigint] NULL, + [IDPARCELA] [bigint] NULL, + [IDSINISTRO] [bigint] NULL, + [IDVENCTOALEATORIO] [bigint] NULL, + [IDMALADIRETA] [bigint] NULL, + [IDFORNECEDOR] [bigint] NULL, + [IDCIASEG] [bigint] NULL, + [IDORCCLI] [bigint] NULL, + [IDORCAMEN] [bigint] NULL, + [IDORCITEM] [bigint] NULL, + [IDVENDEDOR] [bigint] NULL, + [IDEXTRATO] [bigint] NULL, + [IDLANCAMEN] [bigint] NULL, + [IDEMPRESA] [bigint] NULL, + [IDSOCIO] [bigint] NULL, + [DESCRICAO] [varchar](300) NULL, + [IMGBLOB] [varbinary](max) NULL, + [EXTENSION] [varchar](5) NULL, + [USUARIOCRIACAO] [bigint] NULL, + [USUARIOALTERACAO] [bigint] NULL, + [DATACRIACAO] [datetime] NULL, + [DATAALTERACAO] [datetime] NULL, + [idrecibofiscal] [bigint] NULL, + [idprojeto] [bigint] NULL, + [idagsproduto] [bigint] NULL, + [excluido] [varchar](1) NULL, + [idnota] [bigint] NULL, + [idguiaremessa] [bigint] NULL); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200527_50.SQL b/Codemerx/Gestor.Application.Migration.Files.20200527_50.SQL new file mode 100644 index 0000000..8cc12f1 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200527_50.SQL @@ -0,0 +1,5 @@ +IF EXISTS(SELECT 1 FROM [dbo].[empresa]) AND NOT EXISTS(SELECT 1 FROM [dbo].[vendedor]) +BEGIN + DECLARE @nomeempresa VARCHAR(255) = (SELECT nome from empresa); + INSERT INTO [dbo].[vendedor] (idempresa,nome,corretora,ativo) VALUES (1,@nomeempresa,'1','1'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200612_51.SQL b/Codemerx/Gestor.Application.Migration.Files.20200612_51.SQL new file mode 100644 index 0000000..8665529 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200612_51.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 230) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (230, N'FATOR SEGURADORA', 1, 2); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200702_52.SQL b/Codemerx/Gestor.Application.Migration.Files.20200702_52.SQL new file mode 100644 index 0000000..8a60cf8 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200702_52.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'ConfigSistema' ) +BEGIN + CREATE TABLE [dbo].[ConfigSistema] ( Id BIGINT IDENTITY ( 1, 1 ) PRIMARY KEY NOT NULL, Codigo INTEGER NOT NULL ); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200709_53.SQL b/Codemerx/Gestor.Application.Migration.Files.20200709_53.SQL new file mode 100644 index 0000000..185cf12 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200709_53.SQL @@ -0,0 +1,4 @@ +IF COL_LENGTH('[dbo].[sinistro]', 'descricao') IS NOT NULL +BEGIN +ALTER TABLE sinistro ALTER COLUMN descricao varchar(MAX); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200714_54.SQL b/Codemerx/Gestor.Application.Migration.Files.20200714_54.SQL new file mode 100644 index 0000000..59daa9b --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200714_54.SQL @@ -0,0 +1,4 @@ +IF COL_LENGTH('[dbo].[controle]', 'idestipulante') IS NULL +BEGIN + ALTER TABLE controle ADD idestipulante BIGINT NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200714_55.SQL b/Codemerx/Gestor.Application.Migration.Files.20200714_55.SQL new file mode 100644 index 0000000..103e060 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200714_55.SQL @@ -0,0 +1,4 @@ +IF COL_LENGTH('[dbo].[documento]', 'idestipulante') IS NOT NULL AND COL_LENGTH('[dbo].[controle]', 'idestipulante') IS NOT NULL +BEGIN + UPDATE documento SET idestipulante = c.idestipulante FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole WHERE d.idestipulante is null and c.idestipulante IS NOT NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200716_56.SQL b/Codemerx/Gestor.Application.Migration.Files.20200716_56.SQL new file mode 100644 index 0000000..9c6e7fe --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200716_56.SQL @@ -0,0 +1,4 @@ +IF EXISTS(SELECT 1 FROM [dbo].[enviosmtp] WHERE [Excluido] IS NULL) +BEGIN + UPDATE [dbo].[enviosmtp] SET Excluido = 0 WHERE [Excluido] IS NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200730_57.SQL b/Codemerx/Gestor.Application.Migration.Files.20200730_57.SQL new file mode 100644 index 0000000..56600f1 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200730_57.SQL @@ -0,0 +1,9 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'clitelefone') AND COL_LENGTH('[dbo].[clitelefone]', 'fone') IS NOT NULL +BEGIN + ALTER TABLE [dbo].[clitelefone] ALTER COLUMN fone VARCHAR(20) NULL; +END + +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'clicontato') AND COL_LENGTH('[dbo].[clicontato]', 'fone') IS NOT NULL +BEGIN + ALTER TABLE [dbo].[clicontato] ALTER COLUMN fone VARCHAR(20) NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200811_58.SQL b/Codemerx/Gestor.Application.Migration.Files.20200811_58.SQL new file mode 100644 index 0000000..6da82e3 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200811_58.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 28) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (28, N'AMIL SEGURADORA S/A', 1, 2); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200817_59.SQL b/Codemerx/Gestor.Application.Migration.Files.20200817_59.SQL new file mode 100644 index 0000000..4f46df2 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200817_59.SQL @@ -0,0 +1,9 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'ArquivoParaAssinatura') AND COL_LENGTH('[dbo].[ArquivoParaAssinatura]', 'Enviado') IS NULL +BEGIN + ALTER TABLE [dbo].[ArquivoParaAssinatura] ADD Enviado DATETIME2 NULL; +END + +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'ArquivoParaAssinatura') AND COL_LENGTH('[dbo].[ArquivoParaAssinatura]', 'UsuarioId') IS NULL +BEGIN + ALTER TABLE [dbo].[ArquivoParaAssinatura] ADD UsuarioId BIGINT NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200818_60.SQL b/Codemerx/Gestor.Application.Migration.Files.20200818_60.SQL new file mode 100644 index 0000000..efd8526 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200818_60.SQL @@ -0,0 +1,16 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND NOT EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 2 AND [IdUsuario] = 0) +BEGIN + INSERT INTO [dbo].[CamposRelatorios] +VALUES + ( 0, 2, 'Cliente', NULL, 0, NULL, 1 ), + ( 0, 2, 'Apolice', 'APÓLICE', 0, NULL, 2 ), + ( 0, 2, 'Endosso', NULL, 0, NULL, 3 ), + ( 0, 2, 'Status', NULL, 0, NULL, 4 ), + ( 0, 2, 'VigenciaInicial', 'VIGÊNCIA INICIAL', 0, 'DATA?', 5 ), + ( 0, 2, 'Comissao', 'COMISSÃO', 0, 'PERCENTUAL', 6 ), + ( 0, 2, 'PremioLiquido', 'PRÊMIO LÍQUIDO', 0, 'VALOR', 7 ), + ( 0, 2, 'Seguradora', NULL, 0, NULL, 8 ), + ( 0, 2, 'Ramo', NULL, 0, NULL, 9 ), + ( 0, 2, 'Vendedor', 'VENDEDOR PRINCIPAL', 0, NULL, 10 ), + ( 0, 2, 'Item', NULL, 0, NULL, 11 ); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200820_61.SQL b/Codemerx/Gestor.Application.Migration.Files.20200820_61.SQL new file mode 100644 index 0000000..8638e5c --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200820_61.SQL @@ -0,0 +1,16 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND NOT EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 0 AND [IdUsuario] = 0) +BEGIN + INSERT INTO [dbo].[CamposRelatorios] +VALUES + ( 0, 0, 'Nome', NULL, 0, NULL, 1 ), + ( 0, 0, 'Documento', 'CPF/CNPJ', 0, NULL, 2 ), + ( 0, 0, 'TipoPessoa', 'TIPO DE PESSOA', 0, NULL, 3 ), + ( 0, 0, 'Nascimento', NULL, 0, 'DATA?', 4 ), + ( 0, 0, 'Telefone', NULL, 0, NULL, 5 ), + ( 0, 0, 'Email', 'E-MAIL', 0, NULL, 6 ), + ( 0, 0, 'Cep', NULL, 0, NULL, 7 ), + ( 0, 0, 'Cidade', NULL, 0, NULL, 8 ), + ( 0, 0, 'Estado', NULL, 0, NULL, 9 ), + ( 0, 0, 'Ativo', null, 0, NULL, 10 ), + ( 0, 0, 'Ramo', NULL, 0, NULL, 11 ); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200820_62.SQL b/Codemerx/Gestor.Application.Migration.Files.20200820_62.SQL new file mode 100644 index 0000000..e94f321 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200820_62.SQL @@ -0,0 +1,16 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND NOT EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 1 AND [IdUsuario] = 0) +BEGIN + INSERT INTO [dbo].[CamposRelatorios] +VALUES + ( 0, 1, 'Aniversario', 'ANIVERSÁRIO', 0, NULL, 0 ), + ( 0, 1, 'Nome', NULL, 0, NULL, 1 ), + ( 0, 1, 'Documento', 'CPF/CNPJ', 0, NULL, 2 ), + ( 0, 1, 'TipoPessoa', 'TIPO DE PESSOA', 0, NULL, 3 ), + ( 0, 1, 'Nascimento', NULL, 0, 'DATA?', 4 ), + ( 0, 1, 'Telefone', NULL, 0, NULL, 5 ), + ( 0, 1, 'Email', 'E-MAIL', 0, NULL, 6 ), + ( 0, 1, 'Cep', NULL, 0, NULL, 7 ), + ( 0, 1, 'Cidade', NULL, 0, NULL, 8 ), + ( 0, 1, 'Estado', NULL, 0, NULL, 9 ), + ( 0, 1, 'Ativo', null, 0, NULL, 10 ); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200820_63.SQL b/Codemerx/Gestor.Application.Migration.Files.20200820_63.SQL new file mode 100644 index 0000000..54804d8 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200820_63.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Meta') AND COL_LENGTH('[dbo].[Meta]', 'IdCiaSeg') IS NOT NULL +BEGIN + ALTER TABLE [dbo].[Meta] ALTER COLUMN IdCiaSeg BIGINT NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200825_64.SQL b/Codemerx/Gestor.Application.Migration.Files.20200825_64.SQL new file mode 100644 index 0000000..2d9c594 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200825_64.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Meta') AND COL_LENGTH('[dbo].[Meta]', 'IdSeguradora') IS NOT NULL +BEGIN + ALTER TABLE [dbo].[Meta] ALTER COLUMN IdSeguradora BIGINT NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200831_65.SQL b/Codemerx/Gestor.Application.Migration.Files.20200831_65.SQL new file mode 100644 index 0000000..42d4e01 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200831_65.SQL @@ -0,0 +1,4 @@ +IF EXISTS(SELECT 1 FROM [dbo].[estipulante] WHERE [idempresa] IS NULL) +BEGIN + UPDATE [estipulante] SET [idempresa] = 1 WHERE [idempresa] IS NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200914_66.SQL b/Codemerx/Gestor.Application.Migration.Files.20200914_66.SQL new file mode 100644 index 0000000..9dac066 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200914_66.SQL @@ -0,0 +1,4 @@ +IF COL_LENGTH('[dbo].[usuario]', 'inativo') IS NOT NULL +BEGIN + UPDATE usuario SET INATIVO = 0 WHERE INATIVO IS NULL OR LTRIM(RTRIM(INATIVO)) = ''; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200915_67.SQL b/Codemerx/Gestor.Application.Migration.Files.20200915_67.SQL new file mode 100644 index 0000000..9e8a535 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200915_67.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 122) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (122,085, N'TRANSPOCRED'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200924_68.SQL b/Codemerx/Gestor.Application.Migration.Files.20200924_68.SQL new file mode 100644 index 0000000..4bde4f6 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200924_68.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'recibo') AND COL_LENGTH('[dbo].[recibo]', 'DATARECIBO') IS NOT NULL +BEGIN + ALTER TABLE [dbo].[recibo] ALTER COLUMN DATARECIBO datetime; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200925_69.SQL b/Codemerx/Gestor.Application.Migration.Files.20200925_69.SQL new file mode 100644 index 0000000..7966142 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200925_69.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND NOT EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 2 AND [IdUsuario] = 0 AND [Campo] = 'ComissaoGerada') +BEGIN + INSERT INTO [dbo].[CamposRelatorios] VALUES ( 0, 2, 'ComissaoGerada', 'COMISSÃO GERADA', 0, 'VALOR', 7 ); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20200929_70.SQL b/Codemerx/Gestor.Application.Migration.Files.20200929_70.SQL new file mode 100644 index 0000000..709b52d --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20200929_70.SQL @@ -0,0 +1,4 @@ +IF COL_LENGTH('[dbo].[resempco]', 'CEP') = 9 +BEGIN + ALTER TABLE [dbo].[resempco] ALTER COLUMN cep VARCHAR(10); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20201001_71.SQL b/Codemerx/Gestor.Application.Migration.Files.20201001_71.SQL new file mode 100644 index 0000000..585516b --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20201001_71.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND NOT EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 2 AND [IdUsuario] = 0 AND [Campo] = 'TipoPagamento') +BEGIN + INSERT INTO [dbo].[CamposRelatorios] VALUES ( 0, 2, 'TipoPagamento', 'TIPO PAGAMENTO', 0, NULL, 15 ); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20201007_72.SQL b/Codemerx/Gestor.Application.Migration.Files.20201007_72.SQL new file mode 100644 index 0000000..0205c52 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20201007_72.SQL @@ -0,0 +1,4 @@ +IF COL_LENGTH('[dbo].[documento]', 'pasta') IS NOT NULL +BEGIN + ALTER TABLE [dbo].[documento] ALTER COLUMN pasta VARCHAR(15); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20201007_73.SQL b/Codemerx/Gestor.Application.Migration.Files.20201007_73.SQL new file mode 100644 index 0000000..5c8a2e8 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20201007_73.SQL @@ -0,0 +1,4 @@ +IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'repasse' ) +BEGIN + INSERT INTO repasse ( tipo, incidencia, forma, vlrnovo, vlrrenovacao, ativo, idvendedor ) SELECT 2, 1, 1, 0, 0, 1, v.idvendedor FROM vendedor v LEFT OUTER JOIN repasse r ON r.idvendedor = v.idvendedor WHERE v.corretora = '1' AND r.idrepasse IS NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20201008_74.SQL b/Codemerx/Gestor.Application.Migration.Files.20201008_74.SQL new file mode 100644 index 0000000..59ff52a --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20201008_74.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND NOT EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 2 AND [IdUsuario] = 0 AND [Campo] = 'DataCriacao') +BEGIN + INSERT INTO [dbo].[CamposRelatorios] VALUES ( 0, 2, 'DataCriacao', 'DATA DE CADASTRO', 0, 'DATA?', 16 ); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20201015_75.SQL b/Codemerx/Gestor.Application.Migration.Files.20201015_75.SQL new file mode 100644 index 0000000..6a04cc2 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20201015_75.SQL @@ -0,0 +1,8 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 801) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (801, N'CABERJ', 1, 2); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 802) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (802, N'INFINITI', 1, 2); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20201026_76.SQL b/Codemerx/Gestor.Application.Migration.Files.20201026_76.SQL new file mode 100644 index 0000000..9d370d2 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20201026_76.SQL @@ -0,0 +1,4 @@ +IF EXISTS(SELECT 1 FROM [dbo].[Tarefa] WHERE [IdUsuarioCadastro] IS NULL) +BEGIN + UPDATE [dbo].[Tarefa] SET [IdUsuarioCadastro] = [IdUsuario] WHERE [IdUsuarioCadastro] IS NULL +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20201027_77.SQL b/Codemerx/Gestor.Application.Migration.Files.20201027_77.SQL new file mode 100644 index 0000000..ae54143 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20201027_77.SQL @@ -0,0 +1,4 @@ +IF COL_LENGTH('[dbo].[documento]', 'NegocioCorretora') IS NOT NULL AND EXISTS(SELECT 1 FROM [dbo].[documento] WHERE [NegocioCorretora] IS NULL) +BEGIN + UPDATE [dbo].[documento] SET [NegocioCorretora] = CASE WHEN(situacao = 2 AND idnegocio IS NOT NULL AND idnegocio = 1) THEN 1 ELSE 0 END WHERE [NegocioCorretora] IS NULL +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20201028_78.SQL b/Codemerx/Gestor.Application.Migration.Files.20201028_78.SQL new file mode 100644 index 0000000..98b05e8 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20201028_78.SQL @@ -0,0 +1,174 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 469) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (469,2, N'Básica - Inc, raio, Explosão/Implosão', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 488) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (488,2, N'Básica - Incêndio, Raio, Explosão/Implosão', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 720) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (720,2, N'Incêndio, Raio, Explosão', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 467) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (467,2, N'Roubo/Furto Qualificado', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 289) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (289,2, N'Perda/Pagamento de Aluguel', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 276) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (276,2, N'Recomposição de Documentos', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 274) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (274,2, N'Impacto de Veiculos e Queda de Aeronaves', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 492) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (492,2, N'Impacto de veículos/Queda de Aeronaves', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 43) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (43,2, N'Desmoronamento', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 186) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (186,2, N'Anúncios / Letreiros Luminosos ', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 246) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (246,2, N'Anúncios / Letreiros Luminosos ', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 1056) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (1056,2, N'INC/RAIO/EXPL/QUEDA AERON/FUM', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 374) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (374,2, N'Danos Morais', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 1017) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (1017,2, N'R.C. Portoes', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 1074) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (1074,2, N'R C DANOS MORAIS', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 283) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (283,2, N'Portões', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 556) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (556,2, N'PORTÕES E CANCELAS', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 1107) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (1107,2, N'RC Portões', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 1091) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (1091,2, N'Quebra de vidros/espelhos/mármores', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 709) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (709,2, N'Furto/Roubo de Bens-condomínio', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 152) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (152,2, N'Tumultos / Greve / Lock-Out', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 417) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (417,2, N'Despesas Fixas', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 375) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (375,2, N'Impacto de veiculos terrestres', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 71) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (71,2, N'Desmoronamento', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 223) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (223,2, N'RC Síndico', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 222) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (222,2, N'RC Condomínio', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 474) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (474,2, N'RC Garagista Incêndio e Roubo', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 477) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (477,2, N'Anúncios Luminosos / Letreiros / Antenas', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 241) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (241,2, N'Cobertura Básica', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 487) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (487,2, N'Básica - Incêndio, Raio, Explosão/Implosão', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 260) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (260,2, N'Impacto de Veiculos', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 275) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (275,2, N'Impacto de Veiculos e Queda de Aeronaves', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 151) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (151,2, N'Tumultos / Greve / Lock-Out', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 262) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (262,2, N'Resp. Civil Danos Morais', 1); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[coberturapadrao] WHERE [idcoberturapadrao] = 252) +BEGIN + INSERT INTO [dbo].[coberturapadrao] ([idcoberturapadrao],[idramo],[descricao],[padrao]) VALUES (252,2, N'Equipamentos Portáteis', 1); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20201030_79.SQL b/Codemerx/Gestor.Application.Migration.Files.20201030_79.SQL new file mode 100644 index 0000000..b4ca119 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20201030_79.SQL @@ -0,0 +1,13 @@ +IF COL_LENGTH( '[dbo].[documento]', 'banco' ) IS NOT NULL AND COL_LENGTH( '[dbo].[documento]', 'idbanco' ) IS NOT NULL +BEGIN + IF (SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'documento' AND COLUMN_NAME = 'idbanco' AND DATA_TYPE = 'int') IS NOT NULL + BEGIN + UPDATE [dbo].[documento] + SET idbanco = TRY_CAST ( banco AS INT ) + WHERE + ( + SELECT idcodigobanco FROM codigobanco + WHERE idcodigobanco = TRY_CAST ( banco AS INT ) + ) IS NOT NULL AND banco IS NOT NULL AND banco != '' AND idbanco IS NULL; + END +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20201104_80.SQL b/Codemerx/Gestor.Application.Migration.Files.20201104_80.SQL new file mode 100644 index 0000000..13d6784 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20201104_80.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 123) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (123,756, N'SICOOB'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20201112_81.SQL b/Codemerx/Gestor.Application.Migration.Files.20201112_81.SQL new file mode 100644 index 0000000..27eb4f1 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20201112_81.SQL @@ -0,0 +1,9 @@ +IF COL_LENGTH('[dbo].[usuario]', 'AdmGestor') IS NOT NULL AND EXISTS(SELECT 1 FROM [dbo].[usuario] WHERE [AdmGestor] IS NULL) +BEGIN + UPDATE [dbo].[usuario] SET [AdmGestor] = '0' WHERE [AdmGestor] IS NULL; +END + +IF COL_LENGTH('[dbo].[usuario]', 'Removido') IS NOT NULL AND EXISTS(SELECT 1 FROM [dbo].[usuario] WHERE [Removido] IS NULL) +BEGIN + UPDATE [dbo].[usuario] SET [Removido] = '0' WHERE [Removido] IS NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20201113_82.SQL b/Codemerx/Gestor.Application.Migration.Files.20201113_82.SQL new file mode 100644 index 0000000..d0b8b4b --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20201113_82.SQL @@ -0,0 +1,4 @@ +IF COL_LENGTH('[dbo].[cobertura]', 'observacao') < 255 AND COL_LENGTH('[dbo].[cobertura]', 'observacao') > -1 +BEGIN + ALTER TABLE [dbo].[cobertura] ALTER COLUMN observacao VARCHAR(max); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20201117_83.SQL b/Codemerx/Gestor.Application.Migration.Files.20201117_83.SQL new file mode 100644 index 0000000..323ec27 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20201117_83.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 121) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (121,260, N'NUBANK'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20201127_84.SQL b/Codemerx/Gestor.Application.Migration.Files.20201127_84.SQL new file mode 100644 index 0000000..0911593 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20201127_84.SQL @@ -0,0 +1,5 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') +BEGIN + UPDATE CamposRelatorios SET Tipo = 'DATA/TIME' WHERE Relatorio = 18 AND Campo = 'Agendamento'; + UPDATE CamposRelatorios SET Tipo = 'DATA/TIME?' WHERE Relatorio = 18 AND Campo = 'Conclusao'; +END diff --git a/Codemerx/Gestor.Application.Migration.Files.20201127_85.SQL b/Codemerx/Gestor.Application.Migration.Files.20201127_85.SQL new file mode 100644 index 0000000..0f9a71d --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20201127_85.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'recibo') AND COL_LENGTH('[dbo].[recibo]', 'tipopagamento') IS NULL +BEGIN + ALTER TABLE [dbo].[recibo] ADD tipopagamento VARCHAR(250) NULL; +END diff --git a/Codemerx/Gestor.Application.Migration.Files.20201127_86.SQL b/Codemerx/Gestor.Application.Migration.Files.20201127_86.SQL new file mode 100644 index 0000000..606f144 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20201127_86.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'recibo') AND COL_LENGTH('[dbo].[recibo]', 'tipopagamento') IS NOT NULL AND COL_LENGTH('[dbo].[recibo]', 'IdTipoRecibo') IS NULL +BEGIN + ALTER TABLE [dbo].[recibo] ADD IdTipoRecibo INTEGER; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20201127_87.SQL b/Codemerx/Gestor.Application.Migration.Files.20201127_87.SQL new file mode 100644 index 0000000..c256b8c --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20201127_87.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'recibo') AND COL_LENGTH('[dbo].[recibo]', 'tipopagamento') IS NOT NULL AND COL_LENGTH('[dbo].[recibo]', 'IdTipoRecibo') IS NOT NULL +BEGIN + UPDATE [dbo].[recibo] SET IdTipoRecibo = CASE WHEN(tipopagamento = 'PAGAMENTO') THEN 0 ELSE 1 END; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20201127_88.SQL b/Codemerx/Gestor.Application.Migration.Files.20201127_88.SQL new file mode 100644 index 0000000..a5f9da7 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20201127_88.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'recibo') AND COL_LENGTH('[dbo].[recibo]', 'tipopagamento') IS NOT NULL +BEGIN + ALTER TABLE [dbo].[recibo] ALTER COLUMN tipopagamento VARCHAR(250) NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20201127_89.SQL b/Codemerx/Gestor.Application.Migration.Files.20201127_89.SQL new file mode 100644 index 0000000..611068d --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20201127_89.SQL @@ -0,0 +1,6 @@ + + +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 807) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (807, N'SANTANDER AUTO S.A.', 1, 2); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20201201_90.SQL b/Codemerx/Gestor.Application.Migration.Files.20201201_90.SQL new file mode 100644 index 0000000..ff1baf5 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20201201_90.SQL @@ -0,0 +1,14 @@ +IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'sinistroauto' ) AND COL_LENGTH('[dbo].[sinistroauto]', 'culpado') IS NOT NULL +BEGIN + UPDATE [dbo].[sinistroauto] + SET culpado = 2 + WHERE culpado is null OR culpado = 1; + + UPDATE [dbo].[sinistroauto] + SET culpado = 1 + WHERE culpado = 0; + + UPDATE [dbo].[sinistroauto] + SET culpado = 0 + WHERE culpado = 2; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20201203_91.SQL b/Codemerx/Gestor.Application.Migration.Files.20201203_91.SQL new file mode 100644 index 0000000..72b0253 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20201203_91.SQL @@ -0,0 +1,6 @@ + + +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 813) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (813, N'LEVE SAUDE OPERADORA DE PLANOS DE SAUDE LTDA', 1, 2); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20201203_92.SQL b/Codemerx/Gestor.Application.Migration.Files.20201203_92.SQL new file mode 100644 index 0000000..53e770e --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20201203_92.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'vendedorparcela') AND EXISTS(SELECT 1 FROM [dbo].[vendedorparcela] vp INNER JOIN [dbo].[parcela] p on p.idparcela = vp.idparcela INNER JOIN [dbo].[repasse] r on r.idrepasse = vp.idrepasse WHERE p.datarec IS NOT NULL AND vp.dataprepagto IS NOT NULL AND r.forma = 1 AND vp.datapgt IS NULL AND vp.dataprepagto != p.datarec) +BEGIN + update [dbo].[vendedorparcela] set dataprepagto = p.datarec FROM [dbo].[vendedorparcela] vp INNER JOIN [dbo].[parcela] p on p.idparcela = vp.idparcela INNER JOIN [dbo].[repasse] r on r.idrepasse = vp.idrepasse WHERE p.datarec IS NOT NULL AND vp.dataprepagto IS NOT NULL AND r.forma = 1 AND vp.datapgt IS NULL AND vp.dataprepagto != p.datarec +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20201210_93.SQL b/Codemerx/Gestor.Application.Migration.Files.20201210_93.SQL new file mode 100644 index 0000000..1e96b49 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20201210_93.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [IDCIASEG] = 791) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (791, N'JUNTO SEGUROS', 1, 2); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20201230_94.SQL b/Codemerx/Gestor.Application.Migration.Files.20201230_94.SQL new file mode 100644 index 0000000..717598e --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20201230_94.SQL @@ -0,0 +1,5 @@ +IF EXISTS(SELECT 1 FROM [dbo].[cliente] WHERE sexo = 'F' OR sexo = 'M') +BEGIN + UPDATE [dbo].[cliente] SET sexo=1 WHERE sexo = 'F'; + UPDATE [dbo].[cliente] SET sexo=0 WHERE sexo = 'M'; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210107_95.SQL b/Codemerx/Gestor.Application.Migration.Files.20210107_95.SQL new file mode 100644 index 0000000..f32bf50 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210107_95.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 818) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (818, N'MAPFRE VERA CRUZ PREVIDÊNCIA SA', 1, 2); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210118_96.SQL b/Codemerx/Gestor.Application.Migration.Files.20210118_96.SQL new file mode 100644 index 0000000..034ce3d --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210118_96.SQL @@ -0,0 +1,9 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 819) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (819, N'SAMOC', 0, 2); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 820) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (820, N'PEVENT SENIOR', 0, 2); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210209_97.SQL b/Codemerx/Gestor.Application.Migration.Files.20210209_97.SQL new file mode 100644 index 0000000..daa9ab2 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210209_97.SQL @@ -0,0 +1,9 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 835) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (835, N'LINCX', 0, 2); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 836) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (836, N'ONE HEALTH', 0, 2); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210217_98.SQL b/Codemerx/Gestor.Application.Migration.Files.20210217_98.SQL new file mode 100644 index 0000000..b1d17c0 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210217_98.SQL @@ -0,0 +1,9 @@ +DECLARE @index_name NVARCHAR(MAX), @table_name NVARCHAR(MAX) +SET @table_name = 'documento' + +SELECT TOP 1 @index_name = ind.name FROM sys.indexes ind INNER JOIN sys.index_columns ic ON ind.object_id = ic.object_id and ind.index_id = ic.index_id INNER JOIN sys.columns col ON ic.object_id = col.object_id and ic.column_id = col.column_id INNER JOIN sys.tables t ON ind.object_id = t.object_id WHERE ind.is_primary_key = 0 AND ind.is_unique = 0 AND ind.is_unique_constraint = 0 AND t.is_ms_shipped = 0 AND col.name = 'contrato' AND t.name = @table_name + +DECLARE @sql NVARCHAR(MAX) = N'DROP INDEX dbo.' + @table_name + '.' + @index_name + +IF @index_name IS NOT NULL + exec sp_executesql @sql diff --git a/Codemerx/Gestor.Application.Migration.Files.20210217_99.SQL b/Codemerx/Gestor.Application.Migration.Files.20210217_99.SQL new file mode 100644 index 0000000..22f7cbe --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210217_99.SQL @@ -0,0 +1,5 @@ +IF COL_LENGTH('[dbo].[documento]', 'contrato') IS NOT NULL +BEGIN + ALTER TABLE [dbo].[documento] ALTER COLUMN contrato VARCHAR(50) NULL; + ALTER TABLE [dbo].[documento] ALTER COLUMN apol_antes VARCHAR(50) NULL; +END diff --git a/Codemerx/Gestor.Application.Migration.Files.20210301_100.SQL b/Codemerx/Gestor.Application.Migration.Files.20210301_100.SQL new file mode 100644 index 0000000..2b7fd94 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210301_100.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 837) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (837, N'W DENTAL', 0, 2); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210302_101.SQL b/Codemerx/Gestor.Application.Migration.Files.20210302_101.SQL new file mode 100644 index 0000000..1c962e3 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210302_101.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 128) --ID ANTERIOR 124 AJUSTADO CONFORME O BANCO OFICIAL +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (128,336, N'BANCO C6 S.A.'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210302_102.SQL b/Codemerx/Gestor.Application.Migration.Files.20210302_102.SQL new file mode 100644 index 0000000..40a967c --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210302_102.SQL @@ -0,0 +1,10 @@ +DECLARE @fk_name NVARCHAR(MAX) + +SELECT TOP 1 @fk_name = name +FROM sys.foreign_keys +WHERE parent_object_id = object_id('adiantamento') AND object_name(referenced_object_id) = 'tipopagto' + +DECLARE @sql NVARCHAR(MAX) = N'ALTER TABLE adiantamento DROP CONSTRAINT ' + @fk_name + +IF @fk_name IS NOT NULL + exec sp_executesql @sql \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210302_103.SQL b/Codemerx/Gestor.Application.Migration.Files.20210302_103.SQL new file mode 100644 index 0000000..faed352 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210302_103.SQL @@ -0,0 +1,4 @@ +IF COL_LENGTH('[dbo].[sinistro]', 'observacaoint') IS NOT NULL +BEGIN + ALTER TABLE [dbo].sinistro ALTER COLUMN observacaoint VARCHAR(max) NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210309_104.SQL b/Codemerx/Gestor.Application.Migration.Files.20210309_104.SQL new file mode 100644 index 0000000..c7bcfc4 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210309_104.SQL @@ -0,0 +1,9 @@ +DECLARE @index_name NVARCHAR(MAX), @table_name NVARCHAR(MAX) +SET @table_name = 'agendatelefone' + +SELECT TOP 1 @index_name = ind.name FROM sys.indexes ind INNER JOIN sys.index_columns ic ON ind.object_id = ic.object_id and ind.index_id = ic.index_id INNER JOIN sys.columns col ON ic.object_id = col.object_id and ic.column_id = col.column_id INNER JOIN sys.tables t ON ind.object_id = t.object_id WHERE ind.is_primary_key = 0 AND ind.is_unique = 0 AND ind.is_unique_constraint = 0 AND t.is_ms_shipped = 0 AND col.name = 'ddd' AND t.name = @table_name + +DECLARE @sql NVARCHAR(MAX) = N'DROP INDEX dbo.' + @table_name + '.' + @index_name + +IF @index_name IS NOT NULL + exec sp_executesql @sql diff --git a/Codemerx/Gestor.Application.Migration.Files.20210309_105.SQL b/Codemerx/Gestor.Application.Migration.Files.20210309_105.SQL new file mode 100644 index 0000000..50ba4ca --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210309_105.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'agendatelefone') AND COL_LENGTH('[dbo].[agendatelefone]', 'ddd') IS NOT NULL +BEGIN + ALTER TABLE [dbo].[agendatelefone] ALTER COLUMN ddd VARCHAR(20) NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210315_106.SQL b/Codemerx/Gestor.Application.Migration.Files.20210315_106.SQL new file mode 100644 index 0000000..f9503c4 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210315_106.SQL @@ -0,0 +1,4 @@ +IF EXISTS(SELECT 1 FROM [dbo].[documento] WHERE apoconferida is null) +BEGIN + UPDATE [dbo].[documento] SET apoconferida=0 WHERE apoconferida is null; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210315_107 .SQL b/Codemerx/Gestor.Application.Migration.Files.20210315_107 .SQL new file mode 100644 index 0000000..b3cdba9 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210315_107 .SQL @@ -0,0 +1,15 @@ +DECLARE @index_name_Entidade NVARCHAR(MAX), @index_name_Tela NVARCHAR(MAX) + +SELECT TOP 1 @index_name_Entidade = ind.name FROM sys.indexes ind INNER JOIN sys.index_columns ic ON ind.object_id = ic.object_id and ind.index_id = ic.index_id INNER JOIN sys.columns col ON ic.object_id = col.object_id and ic.column_id = col.column_id INNER JOIN sys.tables t ON ind.object_id = t.object_id WHERE ind.is_primary_key = 0 AND ind.is_unique = 0 AND ind.is_unique_constraint = 0 AND t.is_ms_shipped = 0 AND col.name = 'EntidadeId' AND t.name = 'RegistroLog' + +DECLARE @sqlEntidade NVARCHAR(MAX) = N'CREATE INDEX idx_EntidadeId ON RegistroLog (EntidadeId)' + +IF @index_name_Entidade IS NULL + exec sp_executesql @sqlEntidade + +SELECT TOP 1 @index_name_Tela = ind.name FROM sys.indexes ind INNER JOIN sys.index_columns ic ON ind.object_id = ic.object_id and ind.index_id = ic.index_id INNER JOIN sys.columns col ON ic.object_id = col.object_id and ic.column_id = col.column_id INNER JOIN sys.tables t ON ind.object_id = t.object_id WHERE ind.is_primary_key = 0 AND ind.is_unique = 0 AND ind.is_unique_constraint = 0 AND t.is_ms_shipped = 0 AND col.name = 'Tela' AND t.name = 'RegistroLog' + +DECLARE @sqlTela NVARCHAR(MAX) = N'CREATE INDEX idx_Tela ON RegistroLog (Tela)' + +IF @index_name_Tela IS NULL + exec sp_executesql @sqlTela \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210323_108.SQL b/Codemerx/Gestor.Application.Migration.Files.20210323_108.SQL new file mode 100644 index 0000000..5411c35 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210323_108.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 838) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (838, N'BEST DOCTORS INSURANCE', 0, 2); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210323_109.SQL b/Codemerx/Gestor.Application.Migration.Files.20210323_109.SQL new file mode 100644 index 0000000..4133dd2 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210323_109.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 839) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (839, N'STARR INSURANCE COMPANIES', 0, 2); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210324_110.SQL b/Codemerx/Gestor.Application.Migration.Files.20210324_110.SQL new file mode 100644 index 0000000..f9bbc9d --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210324_110.SQL @@ -0,0 +1,6 @@ +DECLARE @index_name NVARCHAR(MAX), @table_name NVARCHAR(MAX) +SET @table_name = 'TitularesVida' +SELECT TOP 1 @index_name = ind.name FROM sys.indexes ind INNER JOIN sys.index_columns ic ON ind.object_id = ic.object_id and ind.index_id = ic.index_id INNER JOIN sys.columns col ON ic.object_id = col.object_id and ic.column_id = col.column_id INNER JOIN sys.tables t ON ind.object_id = t.object_id WHERE ind.is_primary_key = 0 AND ind.is_unique = 0 AND ind.is_unique_constraint = 0 AND t.is_ms_shipped = 0 AND col.name = 'Cpf' AND t.name = @table_name +DECLARE @sql NVARCHAR(MAX) = N'DROP INDEX dbo.' + @table_name + '.' + @index_name +IF @index_name IS NOT NULL + exec sp_executesql @sql \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210324_111.SQL b/Codemerx/Gestor.Application.Migration.Files.20210324_111.SQL new file mode 100644 index 0000000..3b92cc2 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210324_111.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'TitularesVida') AND COL_LENGTH('[dbo].[TitularesVida]', 'Cpf') IS NOT NULL +BEGIN + ALTER TABLE [dbo].[TitularesVida] ALTER COLUMN Cpf VARCHAR(255) NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210329_112.SQL b/Codemerx/Gestor.Application.Migration.Files.20210329_112.SQL new file mode 100644 index 0000000..654923c --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210329_112.SQL @@ -0,0 +1,9 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 840) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (840, N'CAOA - CONVEF ADMINISTRADORA DE CONSORCIOS LTDA', 0, 2); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 841) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (841, N'CLUBCARE – ADMINISTRADORA DE BENEFICIOS – PLANO DE SAÚDE ADESÃO', 0, 2); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210408_113.SQL b/Codemerx/Gestor.Application.Migration.Files.20210408_113.SQL new file mode 100644 index 0000000..2388cc2 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210408_113.SQL @@ -0,0 +1,9 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 843) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (843, N'AMHEMED ASSITENCIA Á SAÚDE', 0, 2); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 844) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (844, N'UNIMED VITÓRIA', 0, 2); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210415_114 .SQL b/Codemerx/Gestor.Application.Migration.Files.20210415_114 .SQL new file mode 100644 index 0000000..92d711f --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210415_114 .SQL @@ -0,0 +1,15 @@ +--DECLARE @index_name_Entidade NVARCHAR(MAX), @index_name_Tela NVARCHAR(MAX) + +--SELECT TOP 1 @index_name_Entidade = ind.name FROM sys.indexes ind INNER JOIN sys.index_columns ic ON ind.object_id = ic.object_id and ind.index_id = ic.index_id INNER JOIN sys.columns col ON ic.object_id = col.object_id and ic.column_id = col.column_id INNER JOIN sys.tables t ON ind.object_id = t.object_id WHERE ind.is_primary_key = 0 AND ind.is_unique = 0 AND ind.is_unique_constraint = 0 AND t.is_ms_shipped = 0 AND col.name = 'idmepresa' AND t.name = 'enviosmtp' + +--DECLARE @sqlEntidade NVARCHAR(MAX) = N'CREATE INDEX idx_IdEmpresa ON enviosmtp (idempresa)' + +--IF @index_name_Entidade IS NULL +-- exec sp_executesql @sqlEntidade + +--SELECT TOP 1 @index_name_Tela = ind.name FROM sys.indexes ind INNER JOIN sys.index_columns ic ON ind.object_id = ic.object_id and ind.index_id = ic.index_id INNER JOIN sys.columns col ON ic.object_id = col.object_id and ic.column_id = col.column_id INNER JOIN sys.tables t ON ind.object_id = t.object_id WHERE ind.is_primary_key = 0 AND ind.is_unique = 0 AND ind.is_unique_constraint = 0 AND t.is_ms_shipped = 0 AND col.name = 'excluido' AND t.name = 'enviosmtp' + +--DECLARE @sqlTela NVARCHAR(MAX) = N'CREATE INDEX idx_Excluido ON enviosmtp (excluido)' + +--IF @index_name_Tela IS NULL +-- exec sp_executesql @sqlTela \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210415_115 .SQL b/Codemerx/Gestor.Application.Migration.Files.20210415_115 .SQL new file mode 100644 index 0000000..72bca36 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210415_115 .SQL @@ -0,0 +1,16 @@ +DECLARE @constraint_name NVARCHAR(MAX), @table_name NVARCHAR(MAX), @column_name NVARCHAR(MAX) + +SET @table_name = 'ciacontato' +SET @column_name = 'idfonetipo' + +select TOP 1 @constraint_name = fk.name +from sys.tables tab + inner join sys.columns col on col.object_id = tab.object_id + inner join sys.foreign_key_columns fk_cols on fk_cols.parent_object_id = tab.object_id and fk_cols.parent_column_id = col.column_id + inner join sys.foreign_keys fk on fk.object_id = fk_cols.constraint_object_id + WHERE tab.name = @table_name and col.name = @column_name; + +DECLARE @sqlDrop NVARCHAR(MAX) = N'ALTER TABLE ' + @table_name + ' DROP CONSTRAINT ' + @constraint_name + ';' + +IF @constraint_name IS NOT NULL + exec sp_executesql @sqlDrop diff --git a/Codemerx/Gestor.Application.Migration.Files.20210415_116.SQL b/Codemerx/Gestor.Application.Migration.Files.20210415_116.SQL new file mode 100644 index 0000000..ba58310 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210415_116.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 226) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (226, N'POLARIS'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210426_117.SQL b/Codemerx/Gestor.Application.Migration.Files.20210426_117.SQL new file mode 100644 index 0000000..40ff23e --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210426_117.SQL @@ -0,0 +1,14 @@ +IF EXISTS(SELECT 1 FROM [dbo].[vendedorparcela] WHERE [valortotal] = 0) +BEGIN + UPDATE vendedorparcela + SET valortotal = +CASE + WHEN ( d.ADINACOMIS = 1 ) THEN + ( d.PR_LIQ + PR_ADIC ) * ( d.com01 * 0.01 ) * ( vrep * 0.01 ) ELSE d.PR_LIQ * ( d.com01 * 0.01 ) * ( vrep * 0.01 ) +END +FROM + vendedorparcela vp + INNER JOIN documento d ON d.iddocumento = vp.iddocumento +WHERE +vp.valortotal = 0; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210510_118.SQL b/Codemerx/Gestor.Application.Migration.Files.20210510_118.SQL new file mode 100644 index 0000000..3cc72dc --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210510_118.SQL @@ -0,0 +1,8 @@ +DECLARE @col_length nvarchar(max) + +SELECT @col_length = COL_LENGTH('[dbo].[adiantamento]', 'datapgt') + +DECLARE @sql NVARCHAR(MAX) = N'UPDATE adiantamento SET Pagamento = datapgt WHERE Pagamento IS NULL AND datapgt IS NOT NULL;' + +IF @col_length IS NOT NULL + exec sp_executesql @sql \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210512_119.SQL b/Codemerx/Gestor.Application.Migration.Files.20210512_119.SQL new file mode 100644 index 0000000..b86c25e --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210512_119.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[ConfigSistema] WHERE [codigo] = 17) +BEGIN + DELETE FROM [dbo].[ConfigSistema] WHERE [codigo] = 17 +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210524_120.SQL b/Codemerx/Gestor.Application.Migration.Files.20210524_120.SQL new file mode 100644 index 0000000..51af9ac --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210524_120.SQL @@ -0,0 +1,9 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'vendedorparcela') +BEGIN + UPDATE vendedorparcela + SET dataprepagto = p.datarec + FROM vendedorparcela vp + INNER JOIN repasse r on r.idrepasse = vp.idrepasse + INNER JOIN parcela p on p.idparcela = vp.idparcela + WHERE vp.datapgt IS NULL AND r.forma = 1 AND p.datarec IS NOT NULL AND vp.DATAPREPAGTO != p.DATAREC; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210525_121.SQL b/Codemerx/Gestor.Application.Migration.Files.20210525_121.SQL new file mode 100644 index 0000000..f710845 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210525_121.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 126) --ID ANTERIOR 125 AJUSTADO CONFORME O BANCO OFICIAL +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (126,102, N'BANCO XP INVESTIMENTOS'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210607_122.SQL b/Codemerx/Gestor.Application.Migration.Files.20210607_122.SQL new file mode 100644 index 0000000..e9ef686 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210607_122.SQL @@ -0,0 +1,11 @@ +DECLARE @has_column NVARCHAR(MAX), @table_name NVARCHAR(MAX), @column_name NVARCHAR(MAX), @column_type NVARCHAR(MAX) +SET @table_name = '[dbo].[recibo]' +SET @column_name = 'tiporecibo' +SELECT @has_column = COL_LENGTH(@table_name, 'tiporecibo') + +SELECT @column_type = DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'recibo' AND COLUMN_NAME = 'tiporecibo' + +DECLARE @sql NVARCHAR(MAX) = N'ALTER TABLE ' + @table_name + N' ALTER COLUMN ' + @column_name + N' ' + CASE WHEN(@column_type = 'nvarchar' OR @column_type = 'varchar') THEN 'NVARCHAR(255)' ELSE 'INTEGER' END + N' NULL;' + +IF @has_column IS NOT NULL + exec sp_executesql @sql \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210610_123.SQL b/Codemerx/Gestor.Application.Migration.Files.20210610_123.SQL new file mode 100644 index 0000000..b9ba4db --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210610_123.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 2 AND [IdUsuario] = 0) +BEGIN + DELETE FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 2 AND [IdUsuario] = 0; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210610_124.SQL b/Codemerx/Gestor.Application.Migration.Files.20210610_124.SQL new file mode 100644 index 0000000..78adb40 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210610_124.SQL @@ -0,0 +1,25 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND NOT EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 2 AND [IdUsuario] = 0) +BEGIN + INSERT INTO [dbo].[CamposRelatorios] +VALUES +(0, 2, N'Cliente', N'CLIENTE', 0, N'', 0), +(0, 2, N'TipoDocumento', N'TIPO DOCUMENTO', 0, N'', 1), +(0, 2, N'VigenciaInicial', N'VIGNCIA INICIAL', 0, N'DATA', 2), +(0, 2, N'PremioLiquido', N'PRMIO LQUIDO', 0, N'VALOR', 3), +(0, 2, N'Comissao', N'COMISSO', 0, N'PERCENTUAL', 4), +(0, 2, N'ComissaoGerada', N'COMISSO GERADA', 0, N'VALOR', 5), +(0, 2, N'NumeroParcelas', N'QUANTIDADE PARCELAS', 0, N'QUANTIDADE', 6), +(0, 2, N'TipoPagamento', N'TIPO PAGAMENTO', 0, N'', 7), +(0, 2, N'Seguradora', N'SEGURADORA', 0, N'', 8), +(0, 2, N'Ramo', N'RAMO', 0, N'', 9), +(0, 2, N'Produto', N'PRODUTO', 0, N'', 10), +(0, 2, N'Status', N'STATUS', 0, N'', 11), +(0, 2, N'Negocio', N'NEGCIO CORRETORA', 0, N'', 12), +(0, 2, N'Item', N'ITEM', 0, N'', 13), +(0, 2, N'Vendedor', N'VENDEDOR PRINCIPAL', 0, N'', 14), +(0, 2, N'TodosVendedores', N'TODOS VENDEDORES', 0, N'', 15), +(0, 2, N'Proposta', N'PROPOSTA', 0, N'', 16), +(0, 2, N'Apolice', N'APLICE', 0, N'', 17), +(0, 2, N'PropostaEndosso', N'PROPOSTA ENDOSSO', 0, N'', 18), +(0, 2, N'Endosso', N'ENDOSSO', 0, N'', 19) +END diff --git a/Codemerx/Gestor.Application.Migration.Files.20210610_125.SQL b/Codemerx/Gestor.Application.Migration.Files.20210610_125.SQL new file mode 100644 index 0000000..182c368 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210610_125.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 8 AND [IdUsuario] = 0) +BEGIN + DELETE FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 8 AND [IdUsuario] = 0; +END diff --git a/Codemerx/Gestor.Application.Migration.Files.20210610_126.SQL b/Codemerx/Gestor.Application.Migration.Files.20210610_126.SQL new file mode 100644 index 0000000..849d697 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210610_126.SQL @@ -0,0 +1,20 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND NOT EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 8 AND [IdUsuario] = 0) +BEGIN + INSERT INTO [dbo].[CamposRelatorios] +VALUES +(0, 8, N'Cliente', N'CLIENTE', 0, N'', 0), +(0, 8, N'PremioLiquido', N'PRMIO LQUIDO', 0, N'VALOR', 1), +(0, 8, N'Comissao', N'COMISSO', 0, N'PERCENTUAL', 2), +(0, 8, N'ComissaoPrevista', N'COMISSO PREVISTA', 0, N'VALOR', 3), +(0, 8, N'ComissaoRecebida', N'COMISSO RECEBIDA', 0, N'VALOR', 4), +(0, 8, N'ComissaoPendente', N'COMISSO PENDENTE', 0, N'VALOR', 5), +(0, 8, N'Completo', N'RECEBIDO POR COMPLETO', 0, N'', 6), +(0, 8, N'Seguradora', N'SEGURADORA', 0, N'', 7), +(0, 8, N'Ramo', N'RAMO', 0, N'', 8), +(0, 8, N'Apolice', N'APLICE', 0, N'', 9), +(0, 8, N'Endosso', N'ENDOSSO', 0, N'', 10), +(0, 8, N'Vendedor', N'VENDEDOR PRINCIPAL', 0, N'', 13), +(0, 8, N'VigenciaInicial', N'VIGNCIA INICIAL', 0, N'DATA', 12), +(0, 8, N'Status', N'STATUS', 0, N'', 11), +(0, 8, N'Item', N'ITEM', 0, N'', 14) +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210610_127.SQL b/Codemerx/Gestor.Application.Migration.Files.20210610_127.SQL new file mode 100644 index 0000000..d400115 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210610_127.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 4 AND [IdUsuario] = 0) +BEGIN + DELETE FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 4 AND [IdUsuario] = 0; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210610_128.SQL b/Codemerx/Gestor.Application.Migration.Files.20210610_128.SQL new file mode 100644 index 0000000..8098fbe --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210610_128.SQL @@ -0,0 +1,24 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND NOT EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 4 AND [IdUsuario] = 0) +BEGIN + INSERT INTO [dbo].[CamposRelatorios] +VALUES +(0, 4, N'VigenciaFinal', N'VIGNCIA FINAL', 0, N'DATA?', 0), +(0, 4, N'Cliente', N'CLIENTE', 0, N'', 1), +(0, 4, N'DocumentoCliente', N'DOCUMENTO DO CLIENTE', 0, N'', 2), +(0, 4, N'Telefone', N'TELEFONE', 0, N'', 17), +(0, 4, N'Seguradora', N'SEGURADORA', 0, N'', 3), +(0, 4, N'Ramo', N'RAMO', 0, N'', 4), +(0, 4, N'Produto', N'PRODUTO', 0, N'', 5), +(0, 4, N'PremioLiquido', N'PRMIO LQUIDO', 0, N'VALOR', 6), +(0, 4, N'PremioTotal', N'PRMIO TOTAL', 0, N'VALOR', 7), +(0, 4, N'Comissao', N'COMISSO', 0, N'PERCENTUAL', 8), +(0, 4, N'Apolice', N'APLICE', 0, N'', 9), +(0, 4, N'Sinistro', N'SINISTRO', 0, N'', 10), +(0, 4, N'QtdSinistro', N'QUANTIDADE DE SINISTRO', 0, N'INT', 11), +(0, 4, N'Item', N'ITEM', 0, N'', 12), +(0, 4, N'TipoDocumento', N'TIPO DOCUMENTO', 0, N'', 13), +(0, 4, N'Negocio', N'TIPO RENOVAO', 0, N'', 14), +(0, 4, N'Vendedor', N'VENDEDOR PRINCIPAL', 0, N'', 15), +(0, 4, N'TodosVendedores', N'TODOS VENDEDORES', 0, N'', 16), +(0, 4, N'Status', N'STATUS', 0, N'', 18) +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210610_129.SQL b/Codemerx/Gestor.Application.Migration.Files.20210610_129.SQL new file mode 100644 index 0000000..c83ae86 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210610_129.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 10 AND [IdUsuario] = 0) +BEGIN + DELETE FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 10 AND [IdUsuario] = 0; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210610_130.SQL b/Codemerx/Gestor.Application.Migration.Files.20210610_130.SQL new file mode 100644 index 0000000..a4b2ca5 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210610_130.SQL @@ -0,0 +1,26 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND NOT EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 10 AND [IdUsuario] = 0) +BEGIN + INSERT INTO [dbo].[CamposRelatorios] +VALUES +(0, 10, N'Pendencia', N'PENDNCIA', 0, N'', 0), +(0, 10, N'Reclamacao', N'RECLAMAO', 0, N'DATA/TIME', 1), +(0, 10, N'DataSinistro', N'DATA OCORRNCIA', 0, N'DATA/TIME', 2), +(0, 10, N'TipoSinistro', N'TIPO', 0, N'ENUM', 3), +(0, 10, N'Nome', N'NOME', 0, N'', 4), +(0, 10, N'CpfCnpj', N'CPF/CNPJ', 0, N'', 5), +(0, 10, N'NumeroSinistro', N'NMERO SINISTRO', 0, N'', 6), +(0, 10, N'Ramo', N'RAMO', 0, N'', 7), +(0, 10, N'Item', N'ITEM', 0, N'', 8), +(0, 10, N'Seguradora', N'SEGURADORA', 0, N'', 9), +(0, 10, N'Apolice', N'APLICE', 0, N'', 10), +(0, 10, N'ValorFranquia', N'VALOR FRANQUIA', 0, N'VALOR', 11), +(0, 10, N'TipoPerda', N'TIPO PERDA', 0, N'', 12), +(0, 10, N'ValorOrcado', N'VALOR ORADO', 0, N'VALOR', 13), +(0, 10, N'ValorLiberado', N'VALOR LIBERADO', 0, N'VALOR', 14), +(0, 10, N'ValorSalvado', N'VALOR SALVADO', 0, N'VALOR', 15), +(0, 10, N'ValorPago', N'VALOR PAGO', 0, N'VALOR', 16), +(0, 10, N'Vendedor', N'VENDEDOR PRINCIPAL', 0, N'', 17), +(0, 10, N'VigenciaFinal', N'VIGNCIA FINAL', 0, N'DATA?', 19), +(0, 10, N'StatusSinistro', N'STATUS', 0, N'ENUM', 20), +(0, 10, N'Liquidacao', N'LIQUIDAO', 0, N'DATA?', 18) +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210610_131.SQL b/Codemerx/Gestor.Application.Migration.Files.20210610_131.SQL new file mode 100644 index 0000000..4385c66 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210610_131.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 9 AND [IdUsuario] = 0) +BEGIN + DELETE FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 9 AND [IdUsuario] = 0; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210610_132.SQL b/Codemerx/Gestor.Application.Migration.Files.20210610_132.SQL new file mode 100644 index 0000000..5544da7 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210610_132.SQL @@ -0,0 +1,23 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND NOT EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 9 AND [IdUsuario] = 0) +BEGIN + INSERT INTO [dbo].[CamposRelatorios] +VALUES +(0, 9, 'Pendencia', 'PENDNCIA', 0, '', 0), +(0, 9, 'Reclamacao', 'RECLAMAO', 0, 'DATA/TIME', 1), +(0, 9, 'DataSinistro', 'DATA OCORRNCIA', 0, 'DATA/TIME', 2), +(0, 9, 'TipoSinistro', 'TIPO', 0, 'ENUM', 3), +(0, 9, 'Nome', 'NOME', 0, '', 4), +(0, 9, 'CpfCnpj', 'CPF/CNPJ', 0, '', 5), +(0, 9, 'NumeroSinistro', 'NMERO SINISTRO', 0, '', 6), +(0, 9, 'Auxiliar', 'AUXILIAR', 0, '', 7), +(0, 9, 'Ramo', 'RAMO', 0, '', 8), +(0, 9, 'Item', 'ITEM', 0, '', 9), +(0, 9, 'Seguradora', 'SEGURADORA', 0, '', 10), +(0, 9, 'Apolice', 'APLICE', 0, '', 11), +(0, 9, 'TipoPerda', 'TIPO PERDA', 0, '', 12), +(0, 9, 'Mecanica', 'MECNICA', 0, '', 13), +(0, 9, 'Funilaria', 'FUNILARIA', 0, '', 14), +(0, 9, 'Vendedor', 'VENDEDOR PRINCIPAL', 0, '', 15), +(0, 9, 'VigenciaFinal', 'VIGNCIA FINAL', 0, 'DATA?', 16), +(0, 9, 'StatusSinistro', 'STATUS', 0, 'ENUM', 17) +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210614_133 .SQL b/Codemerx/Gestor.Application.Migration.Files.20210614_133 .SQL new file mode 100644 index 0000000..503c52d --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210614_133 .SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 1 AND [IdUsuario] = 0) +BEGIN + DELETE FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 1 AND [IdUsuario] = 0; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210614_134.SQL b/Codemerx/Gestor.Application.Migration.Files.20210614_134.SQL new file mode 100644 index 0000000..f88a557 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210614_134.SQL @@ -0,0 +1,16 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND NOT EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 1 AND [IdUsuario] = 0) +BEGIN + INSERT INTO [dbo].[CamposRelatorios] +VALUES +(0, 1, 'Nascimento', 'NASCIMENTO', NULL, 'DATA?', 0), +(0, 1, 'Idade', 'ANOS DE IDADE', NULL, '', 1), +(0, 1, 'Nome', 'CLIENTE', NULL, '', 2), +(0, 1, 'TipoPessoa', 'TIPO DE PESSOA', NULL, '', 3), +(0, 1, 'Ativo', 'ATIVO', NULL, '', 4), +(0, 1, 'Telefone', 'TELEFONE', NULL, '', 5), +(0, 1, 'Email', 'E-MAIL', NULL, '', 6), +(0, 1, 'Cidade', 'CIDADE', NULL, '', 7), +(0, 1, 'Estado', 'ESTADO', NULL, '', 8), +(0, 1, 'Ramo', 'RAMO', NULL, '', 9), +(0, 1, 'Vendedor', 'VENDEDOR', NULL, '', 10) +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210614_135.SQL b/Codemerx/Gestor.Application.Migration.Files.20210614_135.SQL new file mode 100644 index 0000000..c40fc81 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210614_135.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 0 AND [IdUsuario] = 0) +BEGIN + DELETE FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 0 AND [IdUsuario] = 0; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210614_136.SQL b/Codemerx/Gestor.Application.Migration.Files.20210614_136.SQL new file mode 100644 index 0000000..a10e58f --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210614_136.SQL @@ -0,0 +1,20 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND NOT EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 0 AND [IdUsuario] = 0) +BEGIN + INSERT INTO [dbo].[CamposRelatorios] +VALUES +(0, 0, N'Nome', N'CLIENTE', NULL, N'', 0), +(0, 0, N'TipoPessoa', N'TIPO DE PESSOA', NULL, N'', 1), +(0, 0, N'Documento', N'CPF/CNPJ', NULL, N'', 2), +(0, 0, N'Ativo', N'ATIVO', NULL, N'', 3), +(0, 0, N'Sexo', N'SEXO', NULL, N'', 4), +(0, 0, N'Cidade', N'CIDADE', NULL, N'', 5), +(0, 0, N'Estado', N'ESTADO', NULL, N'', 6), +(0, 0, N'Telefone', N'TELEFONE', NULL, N'', 7), +(0, 0, N'Email', N'E-MAIL', NULL, N'', 8), +(0, 0, N'Nascimento', N'NASCIMENTO', NULL, N'DATA?', 9), +(0, 0, N'Idade', N'ANOS DE IDADE', NULL, N'', 10), +(0, 0, N'Profissao', N'PROFISSO', NULL, N'', 11), +(0, 0, N'Ramo', N'RAMO', NULL, N'', 12), +(0, 0, N'VencimentoCnh', N'VENCIMENTO CNH', NULL, N'DATA?', 13), +(0, 0, N'Vendedor', N'VENDEDOR', NULL, N'', 14) +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210614_137.SQL b/Codemerx/Gestor.Application.Migration.Files.20210614_137.SQL new file mode 100644 index 0000000..83dfb41 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210614_137.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 17 AND [IdUsuario] = 0) +BEGIN + DELETE FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 17 AND [IdUsuario] = 0; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210614_138.SQL b/Codemerx/Gestor.Application.Migration.Files.20210614_138.SQL new file mode 100644 index 0000000..fd7be84 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210614_138.SQL @@ -0,0 +1,16 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND NOT EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 17 AND [IdUsuario] = 0) +BEGIN + INSERT INTO [dbo].[CamposRelatorios] +VALUES +(0, 17, N'Vencimento', N'VENCIMENTO', NULL, N'', 0), +(0, 17, N'Cliente', N'CLIENTE', NULL, N'', 1), +(0, 17, N'Telefone', N'TELEFONE', NULL, N'', 2), +(0, 17, N'Email', N'E-MAIL', NULL, N'', 3), +(0, 17, N'Categoria', N'CATEGORIA', NULL, N'', 5), +(0, 17, N'Ramo', N'RAMO', NULL, N'', 4), +(0, 17, N'Item', N'ITEM', NULL, N'', 6), +(0, 17, N'Placa', N'PLACA', NULL, N'', 7), +(0, 17, N'Seguradora', N'SEGURADORA', NULL, N'', 8), +(0, 17, N'Vendedor', N'VENDEDOR PRINCIPAL', NULL, N'', 9), +(0, 17, N'TodosVendedores', N'TODOS VENDEDORES', NULL, N'', 10) +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210614_139.SQL b/Codemerx/Gestor.Application.Migration.Files.20210614_139.SQL new file mode 100644 index 0000000..b1b4486 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210614_139.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 26 AND [IdUsuario] = 0) +BEGIN + DELETE FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 26 AND [IdUsuario] = 0; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210614_140.SQL b/Codemerx/Gestor.Application.Migration.Files.20210614_140.SQL new file mode 100644 index 0000000..4820498 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210614_140.SQL @@ -0,0 +1,18 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND NOT EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 26 AND [IdUsuario] = 0) +BEGIN + INSERT INTO [dbo].[CamposRelatorios] +VALUES +(0, 26, N'VigenciaInicial', N'VIGNCIA INICIAL', NULL, N'DATA', 2), +(0, 26, N'Cliente', N'CLIENTE', NULL, N'', 1), +(0, 26, N'Importado', N'DATA IMPORTAO', NULL, N'DATA', 0), +(0, 26, N'Criticado', N'DATA CRTICA', NULL, N'DATA?', 3), +(0, 26, N'Tipo', N'TIPO DOCUMENTO', NULL, N'', 4), +(0, 26, N'Ramo', N'RAMO', NULL, N'', 5), +(0, 26, N'Seguradora', N'SEGURADORA', NULL, N'', 6), +(0, 26, N'Proposta', N'PROPOSTA', NULL, N'', 7), +(0, 26, N'Apolice', N'APLICE', NULL, N'', 8), +(0, 26, N'PropostaEndosso', N'PROPOSTA ENDOSSO', NULL, N'', 9), +(0, 26, N'UsuarioImportacao', N'USURIO IMPORTAO', NULL, N'', 10), +(0, 26, N'UsuarioCritica', N'USURIO CRTICA', NULL, N'', 11), +(0, 26, N'Pendencia', N'PENDNCIA', NULL, N'', 12) +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210614_141.SQL b/Codemerx/Gestor.Application.Migration.Files.20210614_141.SQL new file mode 100644 index 0000000..e7c640e --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210614_141.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 6 AND [IdUsuario] = 0) +BEGIN + DELETE FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 6 AND [IdUsuario] = 0; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210614_142.SQL b/Codemerx/Gestor.Application.Migration.Files.20210614_142.SQL new file mode 100644 index 0000000..22c3c91 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210614_142.SQL @@ -0,0 +1,23 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND NOT EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 6 AND [IdUsuario] = 0) +BEGIN + INSERT INTO [dbo].[CamposRelatorios] +VALUES +(0, 6, N'Pendencia', N'PENDNCIA', NULL, N'', 0), +(0, 6, N'Vencimento', N'VENCIMENTO', NULL, N'DATA', 1), +(0, 6, N'Cliente', N'CLIENTE', NULL, N'', 2), +(0, 6, N'Pendentes', N'PARCELA', NULL, N'', 3), +(0, 6, N'ValorParcela', N'VALOR PARCELA', NULL, N'VALOR', 4), +(0, 6, N'ComissaoPerc', N'COMISSO', NULL, N'PERCENTUAL', 5), +(0, 6, N'ComissaoPrevista', N'COMISSO PREVISTA', NULL, N'VALOR', 6), +(0, 6, N'Ramo', N'RAMO', NULL, N'', 8), +(0, 6, N'Seguradora', N'SEGURADORA', NULL, N'', 9), +(0, 6, N'TipoDocumento', N'TIPO DOCUMENTO', NULL, N'', 10), +(0, 6, N'ComissaoGerada', N'COMISSO GERADA', NULL, N'VALOR', 7), +(0, 6, N'Apolice', N'APLICE', NULL, N'', 12), +(0, 6, N'Endosso', N'ENDOSSO', NULL, N'', 13), +(0, 6, N'Vendedor', N'VENDEDOR PRINCIPAL', NULL, N'', 14), +(0, 6, N'TodosVendedores', N'TODOS VENDEDORES', NULL, N'', 15), +(0, 6, N'VigenciaFinal', N'VIGNCIA FINAL', NULL, N'DATA?', 16), +(0, 6, N'Status', N'STATUS', NULL, N'', 11) + +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210614_143.SQL b/Codemerx/Gestor.Application.Migration.Files.20210614_143.SQL new file mode 100644 index 0000000..619eacd --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210614_143.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 7 AND [IdUsuario] = 0) +BEGIN + DELETE FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 7 AND [IdUsuario] = 0; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210614_144.SQL b/Codemerx/Gestor.Application.Migration.Files.20210614_144.SQL new file mode 100644 index 0000000..c64ae79 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210614_144.SQL @@ -0,0 +1,27 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND NOT EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 7 AND [IdUsuario] = 0) +BEGIN + INSERT INTO [dbo].[CamposRelatorios] +VALUES +(0, 7, N'Recebimento', N'RECEBIMENTO', NULL, N'DATA?', 0), +(0, 7, N'Cliente', N'CLIENTE', NULL, N'', 1), +(0, 7, N'ComissaoRepasse', N'% REPASSE', NULL, N'PERCENTUAL', 5), +(0, 7, N'Repasse', N'REPASSE', NULL, N'VALOR', 6), +(0, 7, N'ValorLiquido', N'VALOR LQUIDO', NULL, N'VALOR', 7), +(0, 7, N'PremioLiquido', N'PRMIO LQUIDO', NULL, N'VALOR?', 2), +(0, 7, N'PremioTotal', N'PRMIO TOTAL', NULL, N'VALOR?', 3), +(0, 7, N'Comissao', N'COMISSO', NULL, N'PERCENTUAL', 4), +(0, 7, N'Parcela', N'PARCELA', NULL, N'', 8), +(0, 7, N'ValorParcela', N'VALOR PARCELA', NULL, N'VALOR?', 9), +(0, 7, N'Ramo', N'RAMO', NULL, N'', 10), +(0, 7, N'Seguradora', N'SEGURADORA', NULL, N'', 11), +(0, 7, N'Status', N'STATUS', NULL, N'', 12), +(0, 7, N'Negocio', N'TIPO RENOVAO', NULL, N'', 13), +(0, 7, N'Proposta', N'PROPOSTA', NULL, N'', 14), +(0, 7, N'Apolice', N'APLICE', NULL, N'', 15), +(0, 7, N'PedidoEndosso', N'PEDIDO ENDOSSO', NULL, N'', 16), +(0, 7, N'Endosso', N'ENDOSSO', NULL, N'', 17), +(0, 7, N'DataPagamento', N'DATA PAGAMENTO', NULL, N'DATA?', 21), +(0, 7, N'Vendedor', N'VENDEDOR', NULL, N'', 18), +(0, 7, N'VigenciaIncial', N'VIGNCIA INICIAL', NULL, N'DATA?', 19), +(0, 7, N'VigenciaFinal', N'VIGNCIA FINAL', NULL, N'DATA?', 20) +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210614_145.SQL b/Codemerx/Gestor.Application.Migration.Files.20210614_145.SQL new file mode 100644 index 0000000..80c7bc7 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210614_145.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 20 AND [IdUsuario] = 0) +BEGIN + DELETE FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 20 AND [IdUsuario] = 0; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210614_146.SQL b/Codemerx/Gestor.Application.Migration.Files.20210614_146.SQL new file mode 100644 index 0000000..2e39761 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210614_146.SQL @@ -0,0 +1,18 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND NOT EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 20 AND [IdUsuario] = 0) +BEGIN + INSERT INTO [dbo].[CamposRelatorios] +VALUES +(0, 20, N'VencimentoParcela', N'VENCIMENTO PARCELA', NULL, N'DATA', 0), +(0, 20, N'Nome', N'NOME', NULL, N'', 1), +(0, 20, N'Repasse', N'REPASSE', NULL, N'VALOR', 2), +(0, 20, N'RepasseLiquido', N'REPASSE LQUIDO', NULL, N'VALOR', 3), +(0, 20, N'Parcela', N'PARCELA', NULL, N'', 4), +(0, 20, N'PremioLiquido', N'PRMIO LQUIDO', NULL, N'VALOR', 5), +(0, 20, N'NomeRamo', N'RAMO', NULL, N'', 6), +(0, 20, N'NomeSeguradora', N'SEGURADORA', NULL, N'', 7), +(0, 20, N'TipoDocumento', N'TIPO DOCUMENTO', NULL, N'', 8), +(0, 20, N'Status', N'STATUS', NULL, N'', 9), +(0, 20, N'Apolice', N'APLICE', NULL, N'', 10), +(0, 20, N'Endosso', N'ENDOSSO', NULL, N'', 11), +(0, 20, N'VigenciaInicial', N'VIGNCIA INICIAL', NULL, N'DATA', 12) +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210615_147.SQL b/Codemerx/Gestor.Application.Migration.Files.20210615_147.SQL new file mode 100644 index 0000000..3d1d2bc --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210615_147.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 13 AND [IdUsuario] = 0) +BEGIN + DELETE FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 13 AND [IdUsuario] = 0; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210615_148.SQL b/Codemerx/Gestor.Application.Migration.Files.20210615_148.SQL new file mode 100644 index 0000000..46c6c61 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210615_148.SQL @@ -0,0 +1,17 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND NOT EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 13 AND [IdUsuario] = 0) +BEGIN + INSERT INTO [dbo].[CamposRelatorios] +VALUES +(0, 13, N'Numero', N'NMERO', NULL, N'', 0), +(0, 13, N'Data', N'DATA', NULL, N'DATA?', 1), +(0, 13, N'DataCredito', N'DATA DE CRDITO', NULL, N'DATA?', 2), +(0, 13, N'Seguradora', N'SEGURADORA', NULL, N'', 3), +(0, 13, N'Liquido', N'LQUIDO', NULL, N'VALOR', 4), +(0, 13, N'Bruto', N'BRUTO', NULL, N'VALOR', 5), +(0, 13, N'Iss', N'ISS', NULL, N'VALOR', 6), +(0, 13, N'Ir', N'IR', NULL, N'VALOR', 7), +(0, 13, N'Outro', N'OUTRO', NULL, N'VALOR', 8), +(0, 13, N'Status', N'STATUS', NULL, N'', 9), +(0, 13, N'Historico', N'HISTRICO', NULL, N'', 10), +(0, 13, N'Observacao', N'OBSERVAO', NULL, N'', 11) +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210615_149.SQL b/Codemerx/Gestor.Application.Migration.Files.20210615_149.SQL new file mode 100644 index 0000000..bad972a --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210615_149.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 19 AND [IdUsuario] = 0) +BEGIN + DELETE FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 19 AND [IdUsuario] = 0; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210615_150.SQL b/Codemerx/Gestor.Application.Migration.Files.20210615_150.SQL new file mode 100644 index 0000000..d236e99 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210615_150.SQL @@ -0,0 +1,10 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND NOT EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 19 AND [IdUsuario] = 0) +BEGIN + INSERT INTO [dbo].[CamposRelatorios] +VALUES +(0, 19, N'Data', N'DATA', NULL, N'DATA?', 0), +(0, 19, N'Seguradora', N'SEGURADORA', NULL, N'', 1), +(0, 19, N'Bruto', N'VALOR BRUTO', NULL, N'VALOR', 2), +(0, 19, N'Liquido', N'VALOR LQUIDO', NULL, N'VALOR', 3), +(0, 19, N'Iss', N'ISS', NULL, N'VALOR', 4) +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210615_151.SQL b/Codemerx/Gestor.Application.Migration.Files.20210615_151.SQL new file mode 100644 index 0000000..0e432be --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210615_151.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 23 AND [IdUsuario] = 0) +BEGIN + DELETE FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 23 AND [IdUsuario] = 0; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210615_152.SQL b/Codemerx/Gestor.Application.Migration.Files.20210615_152.SQL new file mode 100644 index 0000000..2213c2a --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210615_152.SQL @@ -0,0 +1,16 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND NOT EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 23 AND [IdUsuario] = 0) +BEGIN + INSERT INTO [dbo].[CamposRelatorios] +VALUES +(0, 23, N'Data', N'DATA', NULL, N'DATA', 0), +(0, 23, N'UsuarioAgger', N'USURIO AGGER', NULL, N'', 1), +(0, 23, N'Remetente', N'REMETENTE', NULL, N'', 2), +(0, 23, N'Assunto', N'ASSUNTO', NULL, N'', 3), +(0, 23, N'Destinatarios', N'DESTINATRIOS', NULL, N'', 4), +(0, 23, N'Cco', N'CCO', NULL, N'', 5), +(0, 23, N'Tela', N'TELA', NULL, N'', 6), +(0, 23, N'Ip', N'IP', NULL, N'', 7), +(0, 23, N'Maquina', N'MQUINA', NULL, N'', 8), +(0, 23, N'UsuarioMaquina', N'USURIO DA MQUINA', NULL, N'', 9), +(0, 23, N'Versao', N'VERSO', NULL, N'', 10) +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210615_153.SQL b/Codemerx/Gestor.Application.Migration.Files.20210615_153.SQL new file mode 100644 index 0000000..f3058b8 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210615_153.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 24 AND [IdUsuario] = 0) +BEGIN + DELETE FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 24 AND [IdUsuario] = 0; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210615_154.SQL b/Codemerx/Gestor.Application.Migration.Files.20210615_154.SQL new file mode 100644 index 0000000..aa74cf2 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210615_154.SQL @@ -0,0 +1,14 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND NOT EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 24 AND [IdUsuario] = 0) +BEGIN + INSERT INTO [dbo].[CamposRelatorios] +VALUES +(0, 24, N'Data', N'DATA', NULL, N'DATA/TIME', 0), +(0, 24, N'UsuarioAgger', N'USURIO AGGER', NULL, N'', 1), +(0, 24, N'EntidadeId', N'CDIGO', NULL, N'', 2), +(0, 24, N'Acesso', N'ACESSO', NULL, N'', 3), +(0, 24, N'Descricao', N'DESCRIO', NULL, N'', 4), +(0, 24, N'Ip', N'IP', NULL, N'', 5), +(0, 24, N'Maquina', N'MQUINA', NULL, N'', 6), +(0, 24, N'UsuarioMaquina', N'USURIO DA MQUINA', NULL, N'', 7), +(0, 24, N'Versao', N'VERSO SISTEMA', NULL, N'', 8) +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210615_155.SQL b/Codemerx/Gestor.Application.Migration.Files.20210615_155.SQL new file mode 100644 index 0000000..9d17f22 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210615_155.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 18 AND [IdUsuario] = 0) +BEGIN + DELETE FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 18 AND [IdUsuario] = 0; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210615_156.SQL b/Codemerx/Gestor.Application.Migration.Files.20210615_156.SQL new file mode 100644 index 0000000..94e7f03 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210615_156.SQL @@ -0,0 +1,13 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND NOT EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 18 AND [IdUsuario] = 0) +BEGIN + INSERT INTO [dbo].[CamposRelatorios] +VALUES +(0, 18, N'Agendamento', N'AGENDAMENTO', NULL, N'DATA/TIME', 0), +(0, 18, N'Usuario', N'USURIO', NULL, N'', 1), +(0, 18, N'Cliente', N'CLIENTE', NULL, N'', 2), +(0, 18, N'Titulo', N'TTULO', NULL, N'', 3), +(0, 18, N'Status', N'STATUS', NULL, N'', 4), +(0, 18, N'Conclusao', N'CONCLUSO', NULL, N'DATA/TIME?', 5), +(0, 18, N'Referencia', N'REFERNCIA', NULL, N'', 6), +(0, 18, N'TipoTarefa', N'TIPO DE TAREFA', NULL, N'', 7) +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210615_157.SQL b/Codemerx/Gestor.Application.Migration.Files.20210615_157.SQL new file mode 100644 index 0000000..15b0b48 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210615_157.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 5 AND [IdUsuario] = 0) +BEGIN + DELETE FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 5 AND [IdUsuario] = 0; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210615_158.SQL b/Codemerx/Gestor.Application.Migration.Files.20210615_158.SQL new file mode 100644 index 0000000..0576b8c --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210615_158.SQL @@ -0,0 +1,21 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND NOT EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 5 AND [IdUsuario] = 0) +BEGIN + INSERT INTO [dbo].[CamposRelatorios] +VALUES +(0, 5, N'Recebimento', N'RECEBIMENTO', NULL, N'DATA?', 0), +(0, 5, N'Cliente', N'CLIENTE', NULL, N'', 1), +(0, 5, N'ComissaoBruta', N'RECEBIMENTO BRUTO', NULL, N'VALOR', 2), +(0, 5, N'ComissaoRecebida', N'COMISSO RECEBIDA', NULL, N'VALOR', 3), +(0, 5, N'Repasse', N'REPASSE', NULL, N'VALOR', 4), +(0, 5, N'Vendedor', N'VENDEDOR PRINCIPAL', NULL, N'', 5), +(0, 5, N'Parcela', N'PARCELA', NULL, N'', 6), +(0, 5, N'SubTipo', N'TIPO DE PARCELA', NULL, N'ENUM', 7), +(0, 5, N'Ramo', N'RAMO', NULL, N'', 8), +(0, 5, N'Seguradora', N'SEGURADORA', NULL, N'', 9), +(0, 5, N'TipoDocumento', N'TIPO', NULL, N'', 10), +(0, 5, N'Status', N'STATUS', NULL, N'', 11), +(0, 5, N'TodosVendedores', N'TODOS VENDEDORES', NULL, N'', 12), +(0, 5, N'Apolice', N'APLICE', NULL, N'', 13), +(0, 5, N'Endosso', N'ENDOSSO', NULL, N'', 14), +(0, 5, N'VigenciaInicial', N'VIGNCIA INICIAL', NULL, N'DATA', 15) +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210615_159.SQL b/Codemerx/Gestor.Application.Migration.Files.20210615_159.SQL new file mode 100644 index 0000000..7336ed5 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210615_159.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 16 AND [IdUsuario] = 0) +BEGIN + DELETE FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 16 AND [IdUsuario] = 0; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210615_160.SQL b/Codemerx/Gestor.Application.Migration.Files.20210615_160.SQL new file mode 100644 index 0000000..2fa6740 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210615_160.SQL @@ -0,0 +1,23 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND NOT EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 16 AND [IdUsuario] = 0) +BEGIN + INSERT INTO [dbo].[CamposRelatorios] +VALUES +(0, 16, N'Vencimento', N'VENCIMENTO', NULL, N'DATA', 0), +(0, 16, N'Cliente', N'CLIENTE', NULL, N'', 1), +(0, 16, N'ValorParcela', N'VALOR PARCELA', NULL, N'VALOR', 2), +(0, 16, N'ComissaoPerc', N'COMISSO', NULL, N'PERCENTUAL', 3), +(0, 16, N'ComissaoPrevista', N'COMISSO PREVISTA', NULL, N'VALOR', 4), +(0, 16, N'ComissaoGerada', N'COMISSO GERADA', NULL, N'VALOR', 5), +(0, 16, N'Pendentes', N'PARCELA', NULL, N'', 6), +(0, 16, N'SubTipo', N'TIPO DE PARCELA', NULL, N'ENUM', 7), +(0, 16, N'FormaPagamento', N'FORMA DE PAGAMENTO', NULL, N'', 8), +(0, 16, N'Pendencia', N'PENDNCIA', NULL, N'', 9), +(0, 16, N'Ramo', N'RAMO', NULL, N'', 10), +(0, 16, N'Seguradora', N'SEGURADORA', NULL, N'', 11), +(0, 16, N'TipoDocumento', N'TIPO DOCUMENTO', NULL, N'', 12), +(0, 16, N'Apolice', N'APLICE', NULL, N'', 13), +(0, 16, N'Endosso', N'ENDOSSO', NULL, N'', 14), +(0, 16, N'Vendedor', N'VENDEDOR PRINCIPAL', NULL, N'', 15), +(0, 16, N'TodosVendedores', N'TODOS VENDEDORES', NULL, N'', 16), +(0, 16, N'VigenciaInicial', N'VIGNCIA INICIAL', NULL, N'DATA', 17) +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210622_161.SQL b/Codemerx/Gestor.Application.Migration.Files.20210622_161.SQL new file mode 100644 index 0000000..e4f3d79 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210622_161.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 12 AND [IdUsuario] = 0) +BEGIN + DELETE FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 12 AND [IdUsuario] = 0; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210622_162.SQL b/Codemerx/Gestor.Application.Migration.Files.20210622_162.SQL new file mode 100644 index 0000000..efc7af3 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210622_162.SQL @@ -0,0 +1,16 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND NOT EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 12 AND [IdUsuario] = 0) +BEGIN + INSERT INTO [dbo].[CamposRelatorios] +VALUES +(0, 12, N'Pendencia', N'PENDNCIA', NULL, N'', 0), +(0, 12, N'VigenciaFinalFatura', N'FINAL FATURA', NULL, N'DATA?', 1), +(0, 12, N'Cliente', N'CLIENTE', NULL, N'', 2), +(0, 12, N'Apolice', N'APLICE', NULL, N'', 3), +(0, 12, N'Fatura', N'ULTIMA FATURA', NULL, N'', 4), +(0, 12, N'Ramo', N'RAMO', NULL, N'', 5), +(0, 12, N'Seguradora', N'SEGURADORA', NULL, N'', 6), +(0, 12, N'Status', N'STATUS', NULL, N'', 7), +(0, 12, N'Vendedor', N'VENDEDOR PRINCIPAL', NULL, N'', 8), +(0, 12, N'VigenciaInicial', N'VIGNCIA INICIAL', NULL, N'DATA', 9), +(0, 12, N'Item', N'ITEM', NULL, N'', 10) +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210622_163.SQL b/Codemerx/Gestor.Application.Migration.Files.20210622_163.SQL new file mode 100644 index 0000000..649e3e6 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210622_163.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 11 AND [IdUsuario] = 0) +BEGIN + DELETE FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 11 AND [IdUsuario] = 0; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210622_164.SQL b/Codemerx/Gestor.Application.Migration.Files.20210622_164.SQL new file mode 100644 index 0000000..1e4ebb4 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210622_164.SQL @@ -0,0 +1,28 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND NOT EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 11 AND [IdUsuario] = 0) +BEGIN + INSERT INTO [dbo].[CamposRelatorios] +VALUES +(0, 11, N'Nome', N'NOME', NULL, N'', 1), +(0, 11, N'Gerada', N'COMISSO GERADA', NULL, N'VALOR', 2), +(0, 11, N'GeradaAnterior', N'COMISSO GERADA ANTERIOR', NULL, N'VALOR', 3), +(0, 11, N'Paga', N'COMISSO PAGA', NULL, N'VALOR', 4), +(0, 11, N'PagaAnterior', N'COMISSO PAGA ANTERIOR', NULL, N'VALOR', 5), +(0, 11, N'Recebida', N'COMISSO RECEBIDA', NULL, N'VALOR', 6), +(0, 11, N'RecebidaAnterior', N'COMISSO RECEBIDA ANTERIOR', NULL, N'VALOR', 7), +(0, 11, N'Fechada', N'MDIA FECHADA', NULL, N'PERCENTUAL', 8), +(0, 11, N'FechadaAnterior', N'MDIA FECHADA ANTERIOR', NULL, N'PERCENTUAL', 9), +(0, 11, N'Mix', N'MDIA MIX %', NULL, N'PERCENTUAL', 10), +(0, 11, N'MixAnterior', N'MDIA MIX % ANTERIOR', NULL, N'PERCENTUAL', 11), +(0, 11, N'PremioLiquido', N'PRMIO LQUIDO', NULL, N'VALOR', 12), +(0, 11, N'PremioLiquidoAnterior', N'PRMIO LQUIDO ANTERIOR', NULL, N'VALOR', 13), +(0, 11, N'PremioTotal', N'PRMIO TOTAL', NULL, N'VALOR', 14), +(0, 11, N'PremioTotalAnterior', N'PRMIO TOTAL ANTERIOR', NULL, N'VALOR', 15), +(0, 11, N'Apolice', N'QTD APLICE', NULL, N'QUANTIDADE', 16), +(0, 11, N'ApoliceAnterior', N'QTD APLICE ANTERIOR', NULL, N'QUANTIDADE', 17), +(0, 11, N'Endosso', N'QTD ENDOSSO', NULL, N'QUANTIDADE', 18), +(0, 11, N'Fatura', N'QTD FATURA', NULL, N'QUANTIDADE', 19), +(0, 11, N'EndossoAnterior', N'QTD ENDOSSO ANTERIOR', NULL, N'QUANTIDADE', 20), +(0, 11, N'FaturaAnterior', N'QTD FATURA ANTERIOR', NULL, N'QUANTIDADE', 21), +(0, 11, N'Itens', N'QTD ITENS', NULL, N'QUANTIDADE', 22), +(0, 11, N'ItensAnterior', N'QTD ITENS ANTERIOR', NULL, N'QUANTIDADE', 23) +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210629_165.SQL b/Codemerx/Gestor.Application.Migration.Files.20210629_165.SQL new file mode 100644 index 0000000..1c61c3b --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210629_165.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 602) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (602, N'ITURAN SERVIOS LTDA.', 0, 2); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210708_166 .SQL b/Codemerx/Gestor.Application.Migration.Files.20210708_166 .SQL new file mode 100644 index 0000000..649e3e6 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210708_166 .SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 11 AND [IdUsuario] = 0) +BEGIN + DELETE FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 11 AND [IdUsuario] = 0; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210708_167.SQL b/Codemerx/Gestor.Application.Migration.Files.20210708_167.SQL new file mode 100644 index 0000000..0820982 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210708_167.SQL @@ -0,0 +1,30 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND NOT EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 11 AND [IdUsuario] = 0) +BEGIN + INSERT INTO [dbo].[CamposRelatorios] +VALUES +(0, 11, N'Nome', N'NOME', NULL, N'', 1), +(0, 11, N'Gerada', N'COMISSO GERADA', NULL, N'VALOR', 2), +(0, 11, N'GeradaAnterior', N'COMISSO GERADA ANTERIOR', NULL, N'VALOR', 3), +(0, 11, N'Paga', N'COMISSO PAGA', NULL, N'VALOR', 4), +(0, 11, N'PagaAnterior', N'COMISSO PAGA ANTERIOR', NULL, N'VALOR', 5), +(0, 11, N'Recebida', N'COMISSO RECEBIDA', NULL, N'VALOR', 6), +(0, 11, N'RecebidaAnterior', N'COMISSO RECEBIDA ANTERIOR', NULL, N'VALOR', 7), +(0, 11, N'Pendente', N'COMISSO PENDENTE', NULL, N'VALOR', 8), +(0, 11, N'PendenteAnterior', N'COMISSO PENDENTE ANTERIOR', NULL, N'VALOR', 9), +(0, 11, N'Fechada', N'MDIA FECHADA', NULL, N'PERCENTUAL', 10), +(0, 11, N'FechadaAnterior', N'MDIA FECHADA ANTERIOR', NULL, N'PERCENTUAL', 11), +(0, 11, N'Mix', N'MDIA MIX %', NULL, N'PERCENTUAL', 12), +(0, 11, N'MixAnterior', N'MDIA MIX % ANTERIOR', NULL, N'PERCENTUAL', 13), +(0, 11, N'PremioLiquido', N'PRMIO LQUIDO', NULL, N'VALOR', 14), +(0, 11, N'PremioLiquidoAnterior', N'PRMIO LQUIDO ANTERIOR', NULL, N'VALOR', 15), +(0, 11, N'PremioTotal', N'PRMIO TOTAL', NULL, N'VALOR', 16), +(0, 11, N'PremioTotalAnterior', N'PRMIO TOTAL ANTERIOR', NULL, N'VALOR', 17), +(0, 11, N'Apolice', N'QTD APLICE', NULL, N'QUANTIDADE', 18), +(0, 11, N'ApoliceAnterior', N'QTD APLICE ANTERIOR', NULL, N'QUANTIDADE', 19), +(0, 11, N'Endosso', N'QTD ENDOSSO', NULL, N'QUANTIDADE', 20), +(0, 11, N'Fatura', N'QTD FATURA', NULL, N'QUANTIDADE', 21), +(0, 11, N'EndossoAnterior', N'QTD ENDOSSO ANTERIOR', NULL, N'QUANTIDADE', 22), +(0, 11, N'FaturaAnterior', N'QTD FATURA ANTERIOR', NULL, N'QUANTIDADE', 23), +(0, 11, N'Itens', N'QTD ITENS', NULL, N'QUANTIDADE', 24), +(0, 11, N'ItensAnterior', N'QTD ITENS ANTERIOR', NULL, N'QUANTIDADE', 25) +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210708_168 .SQL b/Codemerx/Gestor.Application.Migration.Files.20210708_168 .SQL new file mode 100644 index 0000000..b5fb925 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210708_168 .SQL @@ -0,0 +1,4 @@ +IF EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 285) +BEGIN + UPDATE [dbo].[ciaseg] SET [NOME] = N'KOVR SEGURADORA' WHERE [IDCIASEG] = 285; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210722_169.SQL b/Codemerx/Gestor.Application.Migration.Files.20210722_169.SQL new file mode 100644 index 0000000..e4b21af --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210722_169.SQL @@ -0,0 +1,5 @@ +DECLARE @sql NVARCHAR(MAX) = N'ALTER TABLE cliente ADD MalaDireta BIT' +IF COL_LENGTH('[dbo].[cliente]', 'MalaDireta') IS NULL +BEGIN + exec sp_executesql @sql +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210819_170.SQL b/Codemerx/Gestor.Application.Migration.Files.20210819_170.SQL new file mode 100644 index 0000000..9b54e10 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210819_170.SQL @@ -0,0 +1,5 @@ +DECLARE @sql NVARCHAR(MAX) = N'ALTER TABLE empresa ADD LogoId VARCHAR(255);' +IF COL_LENGTH('[dbo].[empresa]', 'LogoId') IS NULL +BEGIN + exec sp_executesql @sql +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210820_171.SQL b/Codemerx/Gestor.Application.Migration.Files.20210820_171.SQL new file mode 100644 index 0000000..32b42b7 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210820_171.SQL @@ -0,0 +1,14 @@ +IF COL_LENGTH('[dbo].[vendedor]', 'idtipoconta') IS NULL +BEGIN + ALTER TABLE [dbo].vendedor ADD idtipoconta INT NULL; +END + +IF COL_LENGTH('[dbo].[vendedor]', 'titularconta') IS NULL +BEGIN + ALTER TABLE [dbo].vendedor ADD titularconta NVARCHAR NULL; +END + +IF COL_LENGTH('[dbo].[vendedor]', 'cpfcnpjtitular') IS NULL +BEGIN + ALTER TABLE [dbo].vendedor ADD cpfcnpjtitular NVARCHAR NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210823_172.SQL b/Codemerx/Gestor.Application.Migration.Files.20210823_172.SQL new file mode 100644 index 0000000..0339fbc --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210823_172.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 402) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (402, N'PORTO SEGURO-SEGURO SADE S/A', 0, 2); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210825_173.SQL b/Codemerx/Gestor.Application.Migration.Files.20210825_173.SQL new file mode 100644 index 0000000..522ad8a --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210825_173.SQL @@ -0,0 +1,6 @@ +DECLARE @sql NVARCHAR(MAX) = N'ALTER TABLE [dbo].[vida] ADD obs VARCHAR(MAX) NULL;' + +IF COL_LENGTH('[dbo].[vida]', 'obs') IS NULL +BEGIN + exec sp_executesql @sql +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210825_174.SQL b/Codemerx/Gestor.Application.Migration.Files.20210825_174.SQL new file mode 100644 index 0000000..3776d35 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210825_174.SQL @@ -0,0 +1,9 @@ +DECLARE @sql NVARCHAR(MAX) = N'INSERT INTO vida (iditem, plano, obs) SELECT i.iditem, i.descricao, r.obs FROM item i INNER JOIN documento d on d.iddocumento = i.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN riscosdiversos r on r.iditem = i.iditem WHERE c.idramo = 47;' + +DECLARE @sqlDelete NVARCHAR(MAX) = N'DELETE FROM riscosdiversos WHERE iditem in (SELECT i.iditem FROM item i INNER JOIN documento d on d.iddocumento = i.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN riscosdiversos r on r.iditem = i.iditem WHERE c.idramo = 47);' + +IF EXISTS(SELECT 1 FROM item i INNER JOIN documento d on d.iddocumento = i.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN riscosdiversos r on r.iditem = i.iditem WHERE c.idramo = 47) +BEGIN + exec sp_executesql @sql + exec sp_executesql @sqlDelete +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210910_175.SQL b/Codemerx/Gestor.Application.Migration.Files.20210910_175.SQL new file mode 100644 index 0000000..f4043fe --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210910_175.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 27) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (27, N'AMERICAN LIFE COMPANHIA DE SEGUROS', 0, 2); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210916_176.SQL b/Codemerx/Gestor.Application.Migration.Files.20210916_176.SQL new file mode 100644 index 0000000..eaa4b59 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210916_176.SQL @@ -0,0 +1,16 @@ +DECLARE @constraint_name NVARCHAR(MAX), @table_name NVARCHAR(MAX), @column_name NVARCHAR(MAX) + +SET @table_name = 'origemcliente' +SET @column_name = 'idtipoorigemcli' + +select TOP 1 @constraint_name = fk.name +from sys.tables tab + inner join sys.columns col on col.object_id = tab.object_id + inner join sys.foreign_key_columns fk_cols on fk_cols.parent_object_id = tab.object_id and fk_cols.parent_column_id = col.column_id + inner join sys.foreign_keys fk on fk.object_id = fk_cols.constraint_object_id + WHERE tab.name = @table_name and col.name = @column_name; + +DECLARE @sqlDrop NVARCHAR(MAX) = N'ALTER TABLE ' + @table_name + ' DROP CONSTRAINT ' + @constraint_name + ';' + +IF @constraint_name IS NOT NULL + exec sp_executesql @sqlDrop \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20210916_177.SQL b/Codemerx/Gestor.Application.Migration.Files.20210916_177.SQL new file mode 100644 index 0000000..809eeab --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20210916_177.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 228) +BEGIN + INSERT INTO [dbo].[fabricante] ([IDFABRICANTE],[DESCRICAO]) VALUES (228, N'CFMOTO'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20211104_178.SQL b/Codemerx/Gestor.Application.Migration.Files.20211104_178.SQL new file mode 100644 index 0000000..bcc8d83 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20211104_178.SQL @@ -0,0 +1 @@ +UPDATE documento SET situacao = 5, situant = SITUACAO FROM documento d CROSS APPLY(select idcontrole FROMdocumento WHERE situacao = 5 AND idcontrole = d.idcontrole and tipo = 0) c WHERE d.situacao NOT IN (5,3,7) AND d.tipo = 1; \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20211223_179.SQL b/Codemerx/Gestor.Application.Migration.Files.20211223_179.SQL new file mode 100644 index 0000000..ea47ee1 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20211223_179.SQL @@ -0,0 +1,12 @@ +DECLARE @SQL NVARCHAR ( MAX ) = N'INSERT INTO auto (iditem, obs) SELECT i.iditem, r.obs FROM item i INNER JOIN documento d on d.iddocumento = i.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN riscosdiversos r on r.iditem = i.iditem WHERE c.idramo = 37;' +DECLARE @sqlDelete NVARCHAR ( MAX ) = N'DELETE FROM riscosdiversos WHERE iditem in (SELECT i.iditem FROM item i INNER JOIN documento d on d.iddocumento = i.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN riscosdiversos r on r.iditem = i.iditem WHERE c.idramo = 37);' +IF + EXISTS ( +SELECT 1 FROM item i INNER JOIN documento d ON d.iddocumento = i.iddocumento + INNER JOIN controle c ON c.idcontrole = d.idcontrole + INNER JOIN riscosdiversos r ON r.iditem = i.iditem +WHERE + c.idramo = 37 + ) BEGIN + EXEC sp_executesql @SQL EXEC sp_executesql @sqlDelete +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20211230_180.SQL b/Codemerx/Gestor.Application.Migration.Files.20211230_180.SQL new file mode 100644 index 0000000..bfd26fa --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20211230_180.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 885) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (885, N'SICOOB SEGURADORA DE VIDA E PREVIDENCIA SA', 0, 2); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20211230_181.SQL b/Codemerx/Gestor.Application.Migration.Files.20211230_181.SQL new file mode 100644 index 0000000..c2f4bc9 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20211230_181.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 129) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (129, 403, N'BANCO CORA'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20220104_182.SQL b/Codemerx/Gestor.Application.Migration.Files.20220104_182.SQL new file mode 100644 index 0000000..717461e --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20220104_182.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 229) +BEGIN + INSERT INTO [dbo].[fabricante] ([IDFABRICANTE],[DESCRICAO]) VALUES (229, N'PASTRE'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20220105_183.SQL b/Codemerx/Gestor.Application.Migration.Files.20220105_183.SQL new file mode 100644 index 0000000..84b5d4d --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20220105_183.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 886) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (886, N'UNIMED DE SANTOS COOPERATIVA DE TRABALHO MEDICO', 0, 2); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20220112_184.SQL b/Codemerx/Gestor.Application.Migration.Files.20220112_184.SQL new file mode 100644 index 0000000..d0cbf19 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20220112_184.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 887) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (887, N'COLUMBIA INVESTIMENTOS E PARTICIPAES LTDA', 0, 2); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20220119_185.SQL b/Codemerx/Gestor.Application.Migration.Files.20220119_185.SQL new file mode 100644 index 0000000..2931cc3 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20220119_185.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 888) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (888, N'RECON ADMINISTRADORA DE CONSORCIOS LTDA', 0, 2); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20220119_186.SQL b/Codemerx/Gestor.Application.Migration.Files.20220119_186.SQL new file mode 100644 index 0000000..0b567c0 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20220119_186.SQL @@ -0,0 +1,4 @@ +IF EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 128 AND descricao = 'CHERY') +BEGIN + UPDATE [dbo].[fabricante] SET [DESCRICAO] = N'CAOA CHERY' WHERE [idfabricante] = 128; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20220131_187.SQL b/Codemerx/Gestor.Application.Migration.Files.20220131_187.SQL new file mode 100644 index 0000000..4967c6d --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20220131_187.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 230) +BEGIN + INSERT INTO [dbo].[fabricante] ([IDFABRICANTE],[DESCRICAO]) VALUES (230, N'TESLA'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20220225_190.SQL b/Codemerx/Gestor.Application.Migration.Files.20220225_190.SQL new file mode 100644 index 0000000..85d05ea --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20220225_190.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM [dbo].[CamposRelatorios] WHERE [Header] like 'PARENTESCO') +BEGIN + DELETE FROM [dbo].[CamposRelatorios] WHERE [Header] like 'PARENTESCO'; +END diff --git a/Codemerx/Gestor.Application.Migration.Files.20220225_191.SQL b/Codemerx/Gestor.Application.Migration.Files.20220225_191.SQL new file mode 100644 index 0000000..0a03082 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20220225_191.SQL @@ -0,0 +1,9 @@ +IF NOT EXISTS (SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 891) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (891, N'PROPULSAO PLANOS ODONTOLOGICOS LTDA', 0, 2); +END + +IF NOT EXISTS (SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 890) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (890, N'SMILE SAUDE', 0, 2); +END diff --git a/Codemerx/Gestor.Application.Migration.Files.20220307_192.SQL b/Codemerx/Gestor.Application.Migration.Files.20220307_192.SQL new file mode 100644 index 0000000..5f9e187 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20220307_192.SQL @@ -0,0 +1,16 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 13) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (13, N'AERONÁUTICO',0.0738,0,1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 20) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (20, N'GRANIZO',0.0738,0,1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 26) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (26, N'NÁUTICO',0.0738,0,1); +END +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 50) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (50, N'RCF-DC',0.0738,1,1); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20220315_193.SQL b/Codemerx/Gestor.Application.Migration.Files.20220315_193.SQL new file mode 100644 index 0000000..9b8a1cd --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20220315_193.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS (SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 243) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (243, N'GENERAL REINSURANCE AG', 0, 2); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20220321_194.SQL b/Codemerx/Gestor.Application.Migration.Files.20220321_194.SQL new file mode 100644 index 0000000..fce2aa4 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20220321_194.SQL @@ -0,0 +1,7 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Usuario') +BEGIN + IF COL_LENGTH('usuario','cgccpf') < 18 + BEGIN + ALTER TABLE [dbo].[Usuario] ALTER COLUMN CgcCpf NVARCHAR(18) NULL; + END +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20220325_195.SQL b/Codemerx/Gestor.Application.Migration.Files.20220325_195.SQL new file mode 100644 index 0000000..80ae92b --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20220325_195.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS (SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 893) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (893, N'ELO ADMINISTRADORA DE BENEFICIOS LTDA', 0, 2); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20220329_196.SQL b/Codemerx/Gestor.Application.Migration.Files.20220329_196.SQL new file mode 100644 index 0000000..ddd6f15 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20220329_196.SQL @@ -0,0 +1,24 @@ +IF NOT EXISTS (SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 894) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[CGCCPF],[ATIVO],[TOLERANCIA]) VALUES (894, N'OPERADORA UNICENTRAL DE PLANOS DE SAUDE LTDA', '02.888.465/0001-56', 0, 2); +END +--IF NOT EXISTS (SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 895) +--BEGIN +-- INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[CGCCPF],[ATIVO],[TOLERANCIA]) VALUES (895, N'BEPLUS SAUDE CORRETORA DE SEGUROS LTDA', '12.402.717/0001-49', 0, 2); +--END +--IF NOT EXISTS (SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 896) +--BEGIN +-- INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[CGCCPF],[ATIVO],[TOLERANCIA]) VALUES (896, N'HEBROM CORRETORA DE SEGUROS LTDA', '08.179.439/0001-35', 0, 2); +--END +--IF NOT EXISTS (SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 898) +--BEGIN +-- INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[CGCCPF],[ATIVO],[TOLERANCIA]) VALUES (898, N'RAMED 4YOU CORRETORA DE SEGUROS LTDA', '36.454.780/0001-97', 0, 2); +--END +--IF NOT EXISTS (SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 899) +--BEGIN +-- INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[CGCCPF],[ATIVO],[TOLERANCIA]) VALUES (899, N'DINASTY CORRETORA DE SEGUROS UNIPESSOAL LTDA', '40.514.996/0001-78', 0, 2); +--END +--IF NOT EXISTS (SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 900) +--BEGIN +-- INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[CGCCPF],[ATIVO],[TOLERANCIA]) VALUES (900, N'RAMED MIX CORRETORA DE SEGUROS LTDA', '12.346.564.0001-60', 0, 2); +--END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20220330_197.SQL b/Codemerx/Gestor.Application.Migration.Files.20220330_197.SQL new file mode 100644 index 0000000..a7e4ebc --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20220330_197.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS (SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 901) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[CGCCPF],[ATIVO],[TOLERANCIA]) VALUES (901, N'OABPREV-GO', '01.715.394/0001-27', 0, 2); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20220404_198.SQL b/Codemerx/Gestor.Application.Migration.Files.20220404_198.SQL new file mode 100644 index 0000000..4daf2d4 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20220404_198.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS (SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 902) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[CGCCPF],[ATIVO],[TOLERANCIA]) VALUES (902, N'UNIMED NORDESTE RS SOCIEDADE COOP DE SERV MEDICOS LTDA', '87.827.689/0001-00', 0, 2); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20220404_199.SQL b/Codemerx/Gestor.Application.Migration.Files.20220404_199.SQL new file mode 100644 index 0000000..7785010 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20220404_199.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS (SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 903) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[CGCCPF],[ATIVO],[TOLERANCIA]) VALUES (903, N'SERVIX ADMINISTRADORA DE BENEFICIOS SOCIEDADE', '10.495.931/0001-61', 0, 2); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20220408_200.SQL b/Codemerx/Gestor.Application.Migration.Files.20220408_200.SQL new file mode 100644 index 0000000..02b5975 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20220408_200.SQL @@ -0,0 +1,5 @@ +IF EXISTS (SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 699) +BEGIN + UPDATE controle SET idciaseg = 699 WHERE IDCIASEG = 791; + UPDATE ciaseg SET NOME = 'SEGURADORA DESATIVADA' WHERE IDCIASEG IN (791); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20220413_201.SQL b/Codemerx/Gestor.Application.Migration.Files.20220413_201.SQL new file mode 100644 index 0000000..8f7166a --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20220413_201.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS (SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 904) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[CGCCPF],[ATIVO],[TOLERANCIA]) VALUES (904, N'SEGURADORA DESATIVADA', '05.538.968/0001-90', 0, 2); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20220419_202.SQL b/Codemerx/Gestor.Application.Migration.Files.20220419_202.SQL new file mode 100644 index 0000000..34f2407 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20220419_202.SQL @@ -0,0 +1,6 @@ +DECLARE @sql NVARCHAR(MAX) = N'UPDATE fornecedor SET ativo = 1 WHERE ativo IS NULL;' + +IF COL_LENGTH('[dbo].[fornecedor]', 'ativo') IS NOT NULL +BEGIN + exec sp_executesql @sql +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20220419_203.SQL b/Codemerx/Gestor.Application.Migration.Files.20220419_203.SQL new file mode 100644 index 0000000..d778462 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20220419_203.SQL @@ -0,0 +1,6 @@ +UPDATE [dbo].[ciaseg] SET NOME = 'SEGURADORA DESATIVADA' WHERE IDCIASEG = 820; +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 665) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (665, N'PREVENT SENIOR PRIVATE OPERADORA DE SAUDE', 0, 2); +END +UPDATE CONTROLE SET IDCIASEG = 665 WHERE IDCIASEG = 820; \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20220429_204.SQL b/Codemerx/Gestor.Application.Migration.Files.20220429_204.SQL new file mode 100644 index 0000000..78dacc2 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20220429_204.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 905) +BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA]) VALUES (905, N'IDEAL SAUDE', 0, 2); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20220502_205 .SQL b/Codemerx/Gestor.Application.Migration.Files.20220502_205 .SQL new file mode 100644 index 0000000..7324289 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20220502_205 .SQL @@ -0,0 +1,5 @@ +IF EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [idramo] = 52) +BEGIN + UPDATE controle SET IDRAMO = 4 WHERE IDRAMO = 52; + DELETE FROM ramo WHERE IDRAMO = 52; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20220502_206 .SQL b/Codemerx/Gestor.Application.Migration.Files.20220502_206 .SQL new file mode 100644 index 0000000..83dfb41 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20220502_206 .SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CamposRelatorios') AND EXISTS(SELECT 1 FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 17 AND [IdUsuario] = 0) +BEGIN + DELETE FROM [dbo].[CamposRelatorios] WHERE [Relatorio] = 17 AND [IdUsuario] = 0; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20220603_207.SQL b/Codemerx/Gestor.Application.Migration.Files.20220603_207.SQL new file mode 100644 index 0000000..81c8fa3 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20220603_207.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 222) +BEGIN + INSERT INTO [dbo].[fabricante] ([IDFABRICANTE],[DESCRICAO]) VALUES (222, N'VOLTZ'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20220608_208.SQL b/Codemerx/Gestor.Application.Migration.Files.20220608_208.SQL new file mode 100644 index 0000000..baaeba0 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20220608_208.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 231) +BEGIN + INSERT INTO [dbo].[fabricante] ([IDFABRICANTE],[DESCRICAO]) VALUES (231, N'APOLO'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20220726_209.SQL b/Codemerx/Gestor.Application.Migration.Files.20220726_209.SQL new file mode 100644 index 0000000..ad414a3 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20220726_209.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 119) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (119, 77, N'BANCO INTER SA'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20220804_210.SQL b/Codemerx/Gestor.Application.Migration.Files.20220804_210.SQL new file mode 100644 index 0000000..19d05d3 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20220804_210.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 232) +BEGIN + INSERT INTO [dbo].[fabricante] ([IDFABRICANTE],[DESCRICAO]) VALUES (232, N'BULL'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20220817_211.SQL b/Codemerx/Gestor.Application.Migration.Files.20220817_211.SQL new file mode 100644 index 0000000..bac799e --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20220817_211.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 233) +BEGIN + INSERT INTO [dbo].[fabricante] ([IDFABRICANTE],[DESCRICAO]) VALUES (233, N'BYD'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20220926_212 .SQL b/Codemerx/Gestor.Application.Migration.Files.20220926_212 .SQL new file mode 100644 index 0000000..c27ce2d --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20220926_212 .SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM [dbo].[CamposRelatorios] WHERE [Header] LIKE 'VENDEDOR PRINCIPAL') +BEGIN + DELETE FROM [dbo].[CamposRelatorios] WHERE [Header] LIKE 'VENDEDOR PRINCIPAL'; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20220929_213 .SQL b/Codemerx/Gestor.Application.Migration.Files.20220929_213 .SQL new file mode 100644 index 0000000..adf3aa6 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20220929_213 .SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 234) +BEGIN + INSERT INTO [dbo].[fabricante] ([IDFABRICANTE],[DESCRICAO]) VALUES (234, N'CITYCOCO'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20221007_214 .SQL b/Codemerx/Gestor.Application.Migration.Files.20221007_214 .SQL new file mode 100644 index 0000000..f37e120 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20221007_214 .SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 131) +BEGIN + INSERT INTO [dbo].[CODIGOBANCO] ([IDCODIGOBANCO],[CODIGO],[NOMEBANCO]) VALUES (131, 218, N'Banco BS2 S.A.'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20221018_215 .SQL b/Codemerx/Gestor.Application.Migration.Files.20221018_215 .SQL new file mode 100644 index 0000000..72967ce --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20221018_215 .SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT * FROM [dbo].[CamposRelatorios] WHERE [Header] LIKE 'REPASSE VENDEDOR') +BEGIN + DELETE FROM [dbo].[CamposRelatorios] WHERE [Header] LIKE 'REPASSE VENDEDOR'; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20221028_216.SQL b/Codemerx/Gestor.Application.Migration.Files.20221028_216.SQL new file mode 100644 index 0000000..42ac739 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20221028_216.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 42) +BEGIN + UPDATE ciaseg SET NOME = 'AKAD SEGUROS S.A.', NOMESOCIAL = 'AKAD SEGUROS S.A.' WHERE IDCIASEG IN (42); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20221110_217.SQL b/Codemerx/Gestor.Application.Migration.Files.20221110_217.SQL new file mode 100644 index 0000000..6556bc2 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20221110_217.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 118) +BEGIN + INSERT INTO codigobanco (IDCODIGOBANCO,CODIGO,NOMEBANCO) VALUES (118, 212, N'BANCO ORIGINAL'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20221110_218.SQL b/Codemerx/Gestor.Application.Migration.Files.20221110_218.SQL new file mode 100644 index 0000000..7f4fd1f --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20221110_218.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 235) +BEGIN + INSERT INTO [dbo].[fabricante] ([IDFABRICANTE],[DESCRICAO]) VALUES (235, N'VINCENZI'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20230208_219.SQL b/Codemerx/Gestor.Application.Migration.Files.20230208_219.SQL new file mode 100644 index 0000000..0fc72f8 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20230208_219.SQL @@ -0,0 +1,4 @@ +IF ((SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'clitelefone' AND COLUMN_NAME = 'TIPO') = 'numeric') +BEGIN +ALTER TABLE [dbo].[clitelefone] ALTER COLUMN TIPO INT; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20230301_220.SQL b/Codemerx/Gestor.Application.Migration.Files.20230301_220.SQL new file mode 100644 index 0000000..b2c72d5 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20230301_220.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 236) +BEGIN + INSERT INTO [dbo].[fabricante] ([IDFABRICANTE],[DESCRICAO]) VALUES (236, N'FORTCAR'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20230308_221.SQL b/Codemerx/Gestor.Application.Migration.Files.20230308_221.SQL new file mode 100644 index 0000000..a33757b --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20230308_221.SQL @@ -0,0 +1,4 @@ +IF ((SELECT character_maximum_length FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'parceiro' AND COLUMN_NAME = 'EMAIL') < 100) +BEGIN +ALTER TABLE parceiro ALTER COLUMN EMAIL VARCHAR(100) NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20230502_222.SQL b/Codemerx/Gestor.Application.Migration.Files.20230502_222.SQL new file mode 100644 index 0000000..925c569 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20230502_222.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 237) +BEGIN + INSERT INTO [dbo].[fabricante] ([IDFABRICANTE],[DESCRICAO]) VALUES (237, N'GWM'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20230619_223.SQL b/Codemerx/Gestor.Application.Migration.Files.20230619_223.SQL new file mode 100644 index 0000000..1238ef1 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20230619_223.SQL @@ -0,0 +1,8 @@ +IF ((SELECT character_maximum_length FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'perfil' AND COLUMN_NAME = 'ceppernoite') <= 9 ) +BEGIN +ALTER TABLE perfil ALTER COLUMN ceppernoite VARCHAR(10) NULL; +END +IF ((SELECT character_maximum_length FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'perfil' AND COLUMN_NAME = 'cepcirculacao') <= 9 ) +BEGIN +ALTER TABLE perfil ALTER COLUMN cepcirculacao VARCHAR(10) NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20230619_224.SQL b/Codemerx/Gestor.Application.Migration.Files.20230619_224.SQL new file mode 100644 index 0000000..7820279 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20230619_224.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 238) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (238, N'ZONTES'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20230705_225.SQL b/Codemerx/Gestor.Application.Migration.Files.20230705_225.SQL new file mode 100644 index 0000000..a54a934 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20230705_225.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 239) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (239, N'SCHIFFER'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20230718_226.SQL b/Codemerx/Gestor.Application.Migration.Files.20230718_226.SQL new file mode 100644 index 0000000..3b30e8b --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20230718_226.SQL @@ -0,0 +1,9 @@ +IF (object_id( 'Permissao' ) IS NOT NULL) +BEGIN + IF NOT EXISTS(SELECT 1 FROM [dbo].[Permissao] WHERE [idpermissao] = 0) + BEGIN + SET IDENTITY_INSERT Permissao ON + INSERT INTO Permissao (idpermissao,Nome,Tipo) VALUES (0,'Sem Acesso',0) + SET IDENTITY_INSERT Permissao OFF + END +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20230727_227.SQL b/Codemerx/Gestor.Application.Migration.Files.20230727_227.SQL new file mode 100644 index 0000000..9f73f4b --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20230727_227.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 130) +BEGIN + INSERT INTO codigobanco (IDCODIGOBANCO,CODIGO,NOMEBANCO) VALUES (130, 136, N'UNICRED'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20230807_228 .SQL b/Codemerx/Gestor.Application.Migration.Files.20230807_228 .SQL new file mode 100644 index 0000000..ef0d25c --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20230807_228 .SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 127) +BEGIN + INSERT INTO codigobanco (IDCODIGOBANCO,CODIGO,NOMEBANCO) VALUES (127, 208, N'BANCO BTG PACTUAL S.A'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20230829_229 .SQL b/Codemerx/Gestor.Application.Migration.Files.20230829_229 .SQL new file mode 100644 index 0000000..6f604f8 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20230829_229 .SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[CODIGOBANCO] WHERE [IDCODIGOBANCO] = 132) +BEGIN + INSERT INTO codigobanco (IDCODIGOBANCO,CODIGO,NOMEBANCO) VALUES (132, 396, N'HUB PAGAMENTOS S.A'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20231011_230.SQL b/Codemerx/Gestor.Application.Migration.Files.20231011_230.SQL new file mode 100644 index 0000000..6a662fc --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20231011_230.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 240) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (240, N'CAOA CHERY/CHERY'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20231024_231.SQL b/Codemerx/Gestor.Application.Migration.Files.20231024_231.SQL new file mode 100644 index 0000000..c38942a --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20231024_231.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 241) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (241, N'TRAILER'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20231031_232.SQL b/Codemerx/Gestor.Application.Migration.Files.20231031_232.SQL new file mode 100644 index 0000000..61c4c61 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20231031_232.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 242) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (242, N'JCB'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20240131_233.SQL b/Codemerx/Gestor.Application.Migration.Files.20240131_233.SQL new file mode 100644 index 0000000..9df1c24 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20240131_233.SQL @@ -0,0 +1,11 @@ +IF (object_id( 'fonetipo' ) IS NOT NULL) + BEGIN + declare @sql nvarchar(max) = (select + 'alter table ' + quotename(schema_name(schema_id)) + '.' + + quotename(object_name(parent_object_id)) + + ' drop constraint '+quotename(name) + ';' + from sys.foreign_keys s + where object_name(referenced_object_id) = 'fonetipo' for xml path('') + ) + EXEC sp_executesql @sql; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20240131_234.SQL b/Codemerx/Gestor.Application.Migration.Files.20240131_234.SQL new file mode 100644 index 0000000..9eed697 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20240131_234.SQL @@ -0,0 +1,11 @@ +IF (object_id( 'tipopagto' ) IS NOT NULL) + BEGIN + declare @sql nvarchar(max) = (select + 'alter table ' + quotename(schema_name(schema_id)) + '.' + + quotename(object_name(parent_object_id)) + + ' drop constraint '+quotename(name) + ';' + from sys.foreign_keys s + where object_name(referenced_object_id) = 'tipopagto' for xml path('') + ) + EXEC sp_executesql @sql; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20240322_235.SQL b/Codemerx/Gestor.Application.Migration.Files.20240322_235.SQL new file mode 100644 index 0000000..a2fcd41 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20240322_235.SQL @@ -0,0 +1,6 @@ +IF (EXISTS ( SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME = 'ToleranciaPremio' AND TABLE_NAME = 'ciaseg') +AND EXISTS ( SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME = 'ToleranciaPremio' AND DATA_TYPE = 'nvarchar' AND TABLE_NAME = 'ciaseg')) +BEGIN + UPDATE ciaseg SET ToleranciaPremio = NULL; + ALTER TABLE ciaseg ALTER COLUMN ToleranciaPremio numeric(8,2) NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20240322_236.SQL b/Codemerx/Gestor.Application.Migration.Files.20240322_236.SQL new file mode 100644 index 0000000..18078dd --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20240322_236.SQL @@ -0,0 +1,4 @@ +IF (EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME = 'ToleranciaPremio' AND TABLE_NAME = 'ciaseg')) +BEGIN + UPDATE ciaseg SET ToleranciaPremio = tolerancia WHERE ToleranciaPremio IS NULL; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20240325_237.SQL b/Codemerx/Gestor.Application.Migration.Files.20240325_237.SQL new file mode 100644 index 0000000..25e64c7 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20240325_237.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 243) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (243, N'NEXT ELETRIC'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20240415_238.SQL b/Codemerx/Gestor.Application.Migration.Files.20240415_238.SQL new file mode 100644 index 0000000..c4d7172 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20240415_238.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 244) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (244, N'VENTANE MOTORS'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20240422_239.SQL b/Codemerx/Gestor.Application.Migration.Files.20240422_239.SQL new file mode 100644 index 0000000..40addbe --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20240422_239.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 245) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (245, N'ROSSETTI'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20240521_240.SQL b/Codemerx/Gestor.Application.Migration.Files.20240521_240.SQL new file mode 100644 index 0000000..bbcb307 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20240521_240.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 246) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (246, N'LIESS'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20240522_241.SQL b/Codemerx/Gestor.Application.Migration.Files.20240522_241.SQL new file mode 100644 index 0000000..cc9dabc --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20240522_241.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 247) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (247, N'MCLAREN'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20240604_242.SQL b/Codemerx/Gestor.Application.Migration.Files.20240604_242.SQL new file mode 100644 index 0000000..f8c217e --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20240604_242.SQL @@ -0,0 +1,9 @@ +IF EXISTS (SELECT 1 FROM Ciaseg WHERE IdCiaSeg = 851) +BEGIN + IF NOT EXISTS(SELECT 1 FROM ciaseg WHERE idciaseg = 285) + BEGIN + INSERT INTO [dbo].[ciaseg] ([IDCIASEG],[NOME],[ATIVO],[TOLERANCIA],[ToleranciaPremio]) VALUES (285, N'KOVR SEGURADORA', 1, 2,2); + END + UPDATE controle SET idciaseg = 285 WHERE idciaseg = 851; + UPDATE ciaseg set nome = 'SEGURADORA DESATIVADA' WHERE idciaseg = 851; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20240708_243.SQL b/Codemerx/Gestor.Application.Migration.Files.20240708_243.SQL new file mode 100644 index 0000000..f0f6814 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20240708_243.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 248) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (248, N'DUACT'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20240722_244.SQL b/Codemerx/Gestor.Application.Migration.Files.20240722_244.SQL new file mode 100644 index 0000000..efa9260 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20240722_244.SQL @@ -0,0 +1,7 @@ +IF EXISTS (SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'lancamen' AND COLUMN_NAME = 'documento') +BEGIN + IF ((SELECT CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'lancamen' AND COLUMN_NAME = 'documento') < 255) + BEGIN + ALTER TABLE lancamen ALTER COLUMN documento VARCHAR(255) + END +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20240723_245.SQL b/Codemerx/Gestor.Application.Migration.Files.20240723_245.SQL new file mode 100644 index 0000000..f6e310b --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20240723_245.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM fabricante WHERE idfabricante = 249) +BEGIN + INSERT INTO fabricante (idfabricante, descricao) VALUES (249, N'AVELLOZ'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20240724_246.SQL b/Codemerx/Gestor.Application.Migration.Files.20240724_246.SQL new file mode 100644 index 0000000..81cbed3 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20240724_246.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM CODIGOBANCO WHERE IDCODIGOBANCO = 133) +BEGIN + INSERT INTO codigobanco (IDCODIGOBANCO,CODIGO,NOMEBANCO) VALUES (133, 301, N'CONTABILIZEI'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20240729_247.SQL b/Codemerx/Gestor.Application.Migration.Files.20240729_247.SQL new file mode 100644 index 0000000..676b81a --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20240729_247.SQL @@ -0,0 +1,4 @@ +IF EXISTS(SELECT 1 FROM ciaseg WHERE IDCIASEG = 310) +BEGIN + UPDATE ciaseg SET NOME = 'YELUM SEGUROS' WHERE IDCIASEG = 310; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20240816_248.SQL b/Codemerx/Gestor.Application.Migration.Files.20240816_248.SQL new file mode 100644 index 0000000..d9829db --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20240816_248.SQL @@ -0,0 +1 @@ +--UPDATE usuario SET identif = CONCAT(identif, '_REMOVIDO') WHERE Removido = 1 and identif NOT LIKE '%_REMOVIDO'; \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20240821_249.SQL b/Codemerx/Gestor.Application.Migration.Files.20240821_249.SQL new file mode 100644 index 0000000..1770521 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20240821_249.SQL @@ -0,0 +1,7 @@ +IF EXISTS (SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'usuario' AND COLUMN_NAME = 'identif') +BEGIN + IF ((SELECT CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'usuario' AND COLUMN_NAME = 'identif') < 255) + BEGIN + ALTER TABLE usuario ALTER COLUMN identif VARCHAR(255) + END +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20240821_250.SQL b/Codemerx/Gestor.Application.Migration.Files.20240821_250.SQL new file mode 100644 index 0000000..ecd8381 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20240821_250.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'usuario' AND COLUMN_NAME = 'identif') +BEGIN + UPDATE usuario SET identif = CONCAT(identif, '_REM') WHERE Removido = 1 and (identif NOT LIKE '%_REM' AND identif NOT LIKE '%_REMOVIDO'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20240826_251.SQL b/Codemerx/Gestor.Application.Migration.Files.20240826_251.SQL new file mode 100644 index 0000000..bbad7a6 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20240826_251.SQL @@ -0,0 +1,8 @@ +IF NOT EXISTS(SELECT 1 FROM fabricante WHERE idfabricante = 250) +BEGIN + INSERT INTO fabricante (idfabricante, descricao) VALUES (250, N'JLRP'); +END +IF NOT EXISTS(SELECT 1 FROM fabricante WHERE idfabricante = 251) +BEGIN + INSERT INTO fabricante (idfabricante, descricao) VALUES (251, N'TRUCKVAN'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20240902_252.SQL b/Codemerx/Gestor.Application.Migration.Files.20240902_252.SQL new file mode 100644 index 0000000..67688be --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20240902_252.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM fabricante WHERE idfabricante = 253) +BEGIN + INSERT INTO fabricante (idfabricante, descricao) VALUES (253, N'LIUGONG'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20240919_253.SQL b/Codemerx/Gestor.Application.Migration.Files.20240919_253.SQL new file mode 100644 index 0000000..a627e4c --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20240919_253.SQL @@ -0,0 +1,7 @@ +IF EXISTS (SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'usuario' AND COLUMN_NAME = 'cgccpf') +BEGIN + IF ((SELECT CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'usuario' AND COLUMN_NAME = 'cgccpf') < 20) + BEGIN + ALTER TABLE usuario ALTER COLUMN cgccpf VARCHAR(20) + END +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20241015_254.SQL b/Codemerx/Gestor.Application.Migration.Files.20241015_254.SQL new file mode 100644 index 0000000..247f1f8 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20241015_254.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'usuario' AND COLUMN_NAME ='inativo') +BEGIN + UPDATE usuario SET identif = identif + '_REM', Removido = 1 WHERE inativo = 1 AND Removido != 1; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20250204_255.SQL b/Codemerx/Gestor.Application.Migration.Files.20250204_255.SQL new file mode 100644 index 0000000..fa5d701 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20250204_255.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM fabricante WHERE idfabricante = 254) +BEGIN + INSERT INTO fabricante (idfabricante, descricao) VALUES (254, N'MOTTU'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20250210_256.SQL b/Codemerx/Gestor.Application.Migration.Files.20250210_256.SQL new file mode 100644 index 0000000..3f57d55 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20250210_256.SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT Id FROM CamposRelatorios WHERE relatorio = 27 and campo = 'VENCIMENTO') +BEGIN + DELETE FROM CamposRelatorios WHERE id in (SELECT Id FROM CamposRelatorios WHERE relatorio = 27 and campo = 'VENCIMENTO'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20250307_257 .SQL b/Codemerx/Gestor.Application.Migration.Files.20250307_257 .SQL new file mode 100644 index 0000000..712b1b9 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20250307_257 .SQL @@ -0,0 +1,4 @@ +IF EXISTS (SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 201) +BEGIN + UPDATE fabricante SET descricao = 'EFFA' WHERE idfabricante = 201; +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20250314_258 .SQL b/Codemerx/Gestor.Application.Migration.Files.20250314_258 .SQL new file mode 100644 index 0000000..66df67c --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20250314_258 .SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 255) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (255, N'WATTS'); +END diff --git a/Codemerx/Gestor.Application.Migration.Files.20250314_259 .SQL b/Codemerx/Gestor.Application.Migration.Files.20250314_259 .SQL new file mode 100644 index 0000000..155c4e1 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20250314_259 .SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 256) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (256, N'GALEGO'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20250328_260.SQL b/Codemerx/Gestor.Application.Migration.Files.20250328_260.SQL new file mode 100644 index 0000000..fbe201f --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20250328_260.SQL @@ -0,0 +1,4 @@ +IF EXISTS(SELECT 1 FROM [dbo].[ciaseg] WHERE [idciaseg] = 27) +BEGIN + UPDATE [dbo].[ciaseg] SET NOME = 'ALLSEG' WHERE IDCIASEG IN(27); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20250331_261.SQL b/Codemerx/Gestor.Application.Migration.Files.20250331_261.SQL new file mode 100644 index 0000000..4fd824f --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20250331_261.SQL @@ -0,0 +1,6 @@ +IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'parceiro' + AND COLUMN_NAME = 'complemento' + AND CHARACTER_MAXIMUM_LENGTH < 255) +BEGIN + ALTER TABLE parceiro ALTER COLUMN complemento VARCHAR(255); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20250401_262 .SQL b/Codemerx/Gestor.Application.Migration.Files.20250401_262 .SQL new file mode 100644 index 0000000..d8f9b23 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20250401_262 .SQL @@ -0,0 +1,11 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 257) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (257, N'MOB'); +END + + +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 258) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (258, N'MOTOCHEFE'); + +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20250423_263.SQL b/Codemerx/Gestor.Application.Migration.Files.20250423_263.SQL new file mode 100644 index 0000000..f77d11e --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20250423_263.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 259) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (259, N'TURISCAR'); +END diff --git a/Codemerx/Gestor.Application.Migration.Files.20250424_264.SQL b/Codemerx/Gestor.Application.Migration.Files.20250424_264.SQL new file mode 100644 index 0000000..f4227a6 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20250424_264.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM CODIGOBANCO WHERE IDCODIGOBANCO = 134) +BEGIN + INSERT INTO codigobanco (IDCODIGOBANCO,CODIGO,NOMEBANCO) VALUES (134, 197, N'STONE PAGAMENTOS S.A.'); +END diff --git a/Codemerx/Gestor.Application.Migration.Files.20250425_265.SQL b/Codemerx/Gestor.Application.Migration.Files.20250425_265.SQL new file mode 100644 index 0000000..7633b72 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20250425_265.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM CODIGOBANCO WHERE IDCODIGOBANCO = 135) +BEGIN + INSERT INTO codigobanco (IDCODIGOBANCO,CODIGO,NOMEBANCO) VALUES (135, 133, N'CRESOL CONFEDERAÇÃO'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20250523_266.SQL b/Codemerx/Gestor.Application.Migration.Files.20250523_266.SQL new file mode 100644 index 0000000..f9ab813 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20250523_266.SQL @@ -0,0 +1,6 @@ +CREATE TABLE ImportacaoJsonPdf ( +[Id] INT IDENTITY(1,1) PRIMARY KEY, +[JsonPdf] VARCHAR(MAX), +[AzureGuid] [uniqueidentifier] NULL, +[AzureStorage] [varchar](100) NULL +); \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20250625_267.SQL b/Codemerx/Gestor.Application.Migration.Files.20250625_267.SQL new file mode 100644 index 0000000..1adc7dd --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20250625_267.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 260) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (260, N'OMODA'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20250625_268.SQL b/Codemerx/Gestor.Application.Migration.Files.20250625_268.SQL new file mode 100644 index 0000000..9ea15d6 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20250625_268.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 261) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (261, N'JAECOO'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20250728_269.SQL b/Codemerx/Gestor.Application.Migration.Files.20250728_269.SQL new file mode 100644 index 0000000..9729a63 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20250728_269.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 262) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (262, N'GAC'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20250815_270.SQL b/Codemerx/Gestor.Application.Migration.Files.20250815_270.SQL new file mode 100644 index 0000000..9f398a4 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20250815_270.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 263) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (263, N'NANJING XCMG'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20250905_271.SQL b/Codemerx/Gestor.Application.Migration.Files.20250905_271.SQL new file mode 100644 index 0000000..c05aa5c --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20250905_271.SQL @@ -0,0 +1,9 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 264) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (264, N'VESPA'); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 265) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (265, N'LEVA MOTORS'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20250908_272.SQL b/Codemerx/Gestor.Application.Migration.Files.20250908_272.SQL new file mode 100644 index 0000000..68e2f0e --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20250908_272.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 266) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (266, N'DUOS'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20250909_273.SQL b/Codemerx/Gestor.Application.Migration.Files.20250909_273.SQL new file mode 100644 index 0000000..8c94f69 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20250909_273.SQL @@ -0,0 +1,14 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 267) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (267, N'LIBRELATO S.A. IMPLEMENTOS RODOVIARIOS'); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 268) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (268, N'ZEEKR PARTICIPACOES LTDA'); +END + +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 269) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (269, N'CONDUZZA AUTOPROPELIDOS CURITIBA LTDA'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20250919_274.SQL b/Codemerx/Gestor.Application.Migration.Files.20250919_274.SQL new file mode 100644 index 0000000..786640c --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20250919_274.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 270) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (270, N'CARVALHO CARRETAS RODOVIÁRIAS'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20250926_275.SQL b/Codemerx/Gestor.Application.Migration.Files.20250926_275.SQL new file mode 100644 index 0000000..018c54f --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20250926_275.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 271) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (271, N'RDK'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20251002_276.SQL b/Codemerx/Gestor.Application.Migration.Files.20251002_276.SQL new file mode 100644 index 0000000..4370186 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20251002_276.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 272) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (272, N'SUDU'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20251010_277.SQL b/Codemerx/Gestor.Application.Migration.Files.20251010_277.SQL new file mode 100644 index 0000000..67d9a12 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20251010_277.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM CODIGOBANCO WHERE IDCODIGOBANCO = 136) +BEGIN + INSERT INTO codigobanco (IDCODIGOBANCO,CODIGO,NOMEBANCO) VALUES (136, 323, N'MERCADO PAGO'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20251014_278.SQL b/Codemerx/Gestor.Application.Migration.Files.20251014_278.SQL new file mode 100644 index 0000000..7b6f6b4 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20251014_278.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[fabricante] WHERE [idfabricante] = 273) +BEGIN + INSERT INTO [dbo].[fabricante] ([idfabricante],[descricao]) VALUES (273, N'FERCAR'); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.Migration.Files.20251030_279.SQL b/Codemerx/Gestor.Application.Migration.Files.20251030_279.SQL new file mode 100644 index 0000000..cda3cb6 --- /dev/null +++ b/Codemerx/Gestor.Application.Migration.Files.20251030_279.SQL @@ -0,0 +1,4 @@ +IF NOT EXISTS(SELECT 1 FROM [dbo].[ramo] WHERE [IDRAMO] = 71) +BEGIN + INSERT INTO [dbo].[ramo] ([IDRAMO],[NOME],[IOF],[FATURA],[ATIVO]) VALUES (71, N'PECUÁRIO SEM FESR',0.00,1,1); +END \ No newline at end of file diff --git a/Codemerx/Gestor.Application.csproj b/Codemerx/Gestor.Application.csproj new file mode 100644 index 0000000..00bcbae --- /dev/null +++ b/Codemerx/Gestor.Application.csproj @@ -0,0 +1,2140 @@ + + + + {923EA83B-1027-436B-ACE0-661F786E5162} + Debug + x86 + Gestor.Application + WinExe + v4.8 + true + + + bin\Debug\ + true + DEBUG;TRACE + false + 4 + full + prompt + x86 + + + bin\Release\ + false + TRACE + true + 4 + pdbonly + prompt + x86 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Codemerx/Gestor.Application.sln b/Codemerx/Gestor.Application.sln new file mode 100644 index 0000000..b05dcf8 --- /dev/null +++ b/Codemerx/Gestor.Application.sln @@ -0,0 +1,21 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29728.190 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Gestor.Application", "Gestor.Application.csproj", "{923EA83B-1027-436B-ACE0-661F786E5162}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x86 = Debug|x86 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {923EA83B-1027-436B-ACE0-661F786E5162}.Debug|x86.ActiveCfg = Debug|x86 + {923EA83B-1027-436B-ACE0-661F786E5162}.Debug|x86.Build.0 = Debug|x86 + {923EA83B-1027-436B-ACE0-661F786E5162}.Release|x86.ActiveCfg = Release|x86 + {923EA83B-1027-436B-ACE0-661F786E5162}.Release|x86.Build.0 = Release|x86 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Codemerx/Gestor.Application/Actions/Actions.cs b/Codemerx/Gestor.Application/Actions/Actions.cs new file mode 100644 index 0000000..2d3a5a2 --- /dev/null +++ b/Codemerx/Gestor.Application/Actions/Actions.cs @@ -0,0 +1,222 @@ +using Assinador.Model.Common; +using Gestor.Model.Common; +using Gestor.Model.Domain.Seguros; +using System; +using System.Runtime.CompilerServices; +using System.Windows; + +namespace Gestor.Application.Actions +{ + public static class Actions + { + public static Action AcessarHoster + { + get; + set; + } + + public static Action AcessaTela + { + get; + set; + } + + public static Action AcessoApolice + { + get; + set; + } + + public static Action AcionarSnackbar + { + get; + set; + } + + public static Action AtualizaBadges + { + get; + set; + } + + public static Action AtualizaContatos + { + get; + set; + } + + public static Action AtualizaTrilhas + { + get; + set; + } + + public static Action AtualizaUsuario + { + get; + set; + } + + public static Action CloseHoster + { + get; + set; + } + + public static Action EnableDocumento + { + get; + set; + } + + public static Action EnableItens + { + get; + set; + } + + public static Action EnableMainMenu + { + get; + set; + } + + public static Action EnableMenu + { + get; + set; + } + + public static Action EnablePesquisarClientes + { + get; + set; + } + + public static Action IniciarAggilizador + { + get; + set; + } + + public static Action LimparCliente + { + get; + set; + } + + public static Action ManterItem + { + get; + set; + } + + public static Action NomeTela + { + get; + set; + } + + public static Action OcultarTogglesArquivoDigital + { + get; + set; + } + + public static Action OcultarTogglesFerramentas + { + get; + set; + } + + public static Action OcultarTogglesSeguros + { + get; + set; + } + + public static Action RecarregarDocumentos + { + get; + set; + } + + public static Action RecarregarParcelas + { + get; + set; + } + + public static Action RecarregarRelatorios + { + get; + set; + } + + public static Action Redimencionar + { + get; + set; + } + + public static Action Resize + { + get; + set; + } + + public static Action SaveSortLancamentos + { + get; + set; + } + + public static Action ScrollDocumento + { + get; + set; + } + + public static Action ScrollToItem + { + get; + set; + } + + public static Action SelectCliente + { + get; + set; + } + + public static Action SortLancamentos + { + get; + set; + } + + public static Action SubstituirItem + { + get; + set; + } + + public static Action UpdateDocumento + { + get; + set; + } + + public static Action UpdateItem + { + get; + set; + } + + public static Action UpdateRadioApolice + { + get; + set; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/App.cs b/Codemerx/Gestor.Application/App.cs new file mode 100644 index 0000000..d996857 --- /dev/null +++ b/Codemerx/Gestor.Application/App.cs @@ -0,0 +1,276 @@ +using Agger.Registro; +using Gestor.Application.Helpers; +using Gestor.Application.Views; +using Gestor.Common.Validation; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.API; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using MaterialDesignThemes.Wpf; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Globalization; +using System.Linq; +using System.Net; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Forms; +using System.Windows.Markup; +using System.Windows.Threading; +using Xceed.Wpf.AvalonDock.Controls; + +namespace Gestor.Application +{ + [Serializable] + public class App : System.Windows.Application, IStyleConnector + { + private bool _contentLoaded; + + public static Grid ProgressRing + { + get; + set; + } + + public static Snackbar SnackBar + { + get; + set; + } + + public App() + { + } + + public void Close() + { + System.Windows.Application.Current.Shutdown(); + } + + public void CloseToolTip_Click(object sender, RoutedEventArgs e) + { + System.Windows.Controls.ToolTip toolTip = Extentions.FindVisualAncestor((System.Windows.Controls.Button)sender); + if (toolTip != null) + { + toolTip.IsOpen = false; + } + } + + public Task ConnectionRetry() + { + return base.Dispatcher.Invoke>(async () => { + UnitOfWork unitOfWOrk; + ConnectionRetryView connectionRetryView = ViewHelper.Window(); + if (connectionRetryView == null) + { + ConnectionRetryView connectionRetryView1 = new ConnectionRetryView(); + connectionRetryView1.ShowDialog(); + unitOfWOrk = connectionRetryView1.UnitOfWOrk; + } + else + { + await connectionRetryView.CloseTask.Task; + unitOfWOrk = Instancia.Commited; + } + return unitOfWOrk; + }); + } + + private void DispatcherUnhandled(DispatcherUnhandledExceptionEventArgs exception) + { + this.Registrar(exception.Exception, 1000); + COMException cOMException = exception.Exception as COMException; + if (cOMException != null && cOMException.ErrorCode == -2147221040) + { + exception.Handled = true; + } + Instancia.ExcluirCfg(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/app.xaml", UriKind.Relative)); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + [STAThread] + public static void Main() + { + App app = new App(); + app.InitializeComponent(); + app.Run(); + } + + protected override void OnStartup(StartupEventArgs e) + { + string str; + App.SetLanguage(); + this.RegisterLogException(); + Instancia.App = this; + Recursos.Parametros = e.Args.ToList(); + string str1 = Recursos.Parametros.Find((string x) => x.Contains("REGISTRAR_")); + if (str1 != null) + { + str = str1.Replace("REGISTRAR_", ""); + } + else + { + str = null; + } + Recursos.Registrar = str; + if (!string.IsNullOrWhiteSpace(Recursos.Registrar)) + { + Recursos.Parametros.Remove(Recursos.Parametros.Find((string x) => x.Contains("REGISTRAR_"))); + } + if (Recursos.Parametros.Count > 2) + { + ApplicationHelper.Subkey = ((new RegistryHelper(Recursos.Parametros[2])).get_Registrado() ? Recursos.Parametros[2] : string.Empty); + } + Recursos.Host = Dns.GetHostEntry(Dns.GetHostName()); + ApplicationHelper.Conectado = Recursos.Parametros.Contains("CONECTADO"); + if (!Recursos.Parametros.Contains("INICIAR")) + { + return; + } + base.StartupUri = new Uri("pack://application:,,,/Views/LoginWindow.xaml"); + base.OnStartup(e); + } + + private void RegisterLogException() + { + AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler((object s, UnhandledExceptionEventArgs exception) => this.Registrar((Exception)exception.ExceptionObject, 1000)); + base.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler((object s, DispatcherUnhandledExceptionEventArgs exception) => this.DispatcherUnhandled(exception)); + TaskScheduler.UnobservedTaskException += new EventHandler((object s, UnobservedTaskExceptionEventArgs exception) => this.Registrar(exception.Exception, 1000)); + } + + private void Registrar(Exception e, TipoErro erro) + { + string nome; + string str; + long id; + string str1; + LogError logError = new LogError(); + logError.set_IdFornecedor(ApplicationHelper.IdFornecedor); + Empresa empresa = Recursos.Empresa; + if (empresa != null) + { + nome = empresa.get_Nome(); + } + else + { + nome = null; + } + logError.set_Fornecedor(nome); + Usuario usuario = Recursos.Usuario; + if (usuario != null) + { + str = usuario.get_Nome(); + } + else + { + str = null; + } + logError.set_UsuarioLogado(str); + Usuario usuario1 = Recursos.Usuario; + if (usuario1 != null) + { + id = usuario1.get_Id(); + } + else + { + id = (long)0; + } + logError.set_IdUsuarioLogado(id); + logError.set_Versao(ApplicationHelper.Versao.ToString()); + logError.set_Data(Funcoes.GetNetworkTime()); + logError.set_IdErro(erro); + logError.set_Erro(Gestor.Common.Validation.ValidationHelper.GetDescription(erro)); + logError.set_HResult(e.HResult); + if (e != null) + { + Exception innerException = e.InnerException; + if (innerException != null) + { + str1 = innerException.ToString(); + } + else + { + str1 = null; + } + } + else + { + str1 = null; + } + logError.set_InnerException(str1); + logError.set_HelpLink(e.HelpLink); + logError.set_Message(e.Message); + logError.set_Source(e.Source); + logError.set_StackTrace(e.StackTrace); + logError.set_Maquina(Environment.MachineName); + logError.set_UsuarioMaquina(Environment.UserName); + Erro.RegistrarErro(logError, true); + } + + public void Restart() + { + System.Windows.Forms.Application.Restart(); + System.Windows.Application.Current.Shutdown(); + } + + private static void SetLanguage() + { + XmlLanguage language = XmlLanguage.GetLanguage(CultureInfo.GetCultureInfo("pt-BR").IetfLanguageTag); + FrameworkElement.LanguageProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata(language)); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((System.Windows.Controls.Button)target).Click += new RoutedEventHandler(this.CloseToolTip_Click); + return; + } + case 2: + { + ((System.Windows.Controls.Button)target).Click += new RoutedEventHandler(this.CloseToolTip_Click); + return; + } + case 3: + { + ((System.Windows.Controls.Button)target).Click += new RoutedEventHandler(this.CloseToolTip_Click); + return; + } + case 4: + { + ((System.Windows.Controls.Button)target).Click += new RoutedEventHandler(this.CloseToolTip_Click); + return; + } + default: + { + return; + } + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/CalculoControl.cs b/Codemerx/Gestor.Application/Componentes/CalculoControl.cs new file mode 100644 index 0000000..5f2776d --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/CalculoControl.cs @@ -0,0 +1,680 @@ +using Agger.Registro; +using CsQuery.ExtensionMethods.Internal; +using Gestor.Application.Actions; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.CalculoWeb; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.License; +using Microsoft.CSharp.RuntimeBinder; +using Newtonsoft.Json.Linq; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Linq.Expressions; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Markup; + +namespace Gestor.Application.Componentes +{ + public class CalculoControl : UserControl, IComponentConnector + { + public readonly static DependencyProperty DocumentoIdProperty; + + public readonly static DependencyProperty ClienteIdProperty; + + public readonly static DependencyProperty RamoIdProperty; + + public readonly static DependencyProperty DocumentoProperty; + + private string _messageAggilizadorWeb = string.Concat("CRIADO COM SUCESSO!", Environment.NewLine, "DESEJA ACESSAR A PAGINA DO AGGILIZADOR AGORA?"); + + private string MessageAggilizador = string.Concat("NÃO FOI POSSÍVEL INICIAR A FUNÇÃO NO AGGILIZADOR DE CÁLCULOS.", Environment.NewLine, "CERTIFIQUE-SE QUE O AGGILIZADOR ESTÁ DEVIDAMENTE ATUALIZADO ANTES DE TENTAR NOVAMENTE."); + + internal Grid LayoutRoot; + + internal Button CalculoButton; + + private bool _contentLoaded; + + public object ClienteId + { + get + { + return base.GetValue(CalculoControl.ClienteIdProperty); + } + set + { + base.SetValue(CalculoControl.ClienteIdProperty, value); + } + } + + public string Documento + { + get + { + return (string)base.GetValue(CalculoControl.DocumentoProperty); + } + set + { + base.SetValue(CalculoControl.DocumentoProperty, value); + } + } + + public object DocumentoId + { + get + { + return base.GetValue(CalculoControl.DocumentoIdProperty); + } + set + { + base.SetValue(CalculoControl.DocumentoIdProperty, value); + } + } + + public object RamoId + { + get + { + return base.GetValue(CalculoControl.RamoIdProperty); + } + set + { + base.SetValue(CalculoControl.RamoIdProperty, value); + } + } + + static CalculoControl() + { + CalculoControl.DocumentoIdProperty = DependencyProperty.Register("DocumentoId", typeof(object), typeof(CalculoControl), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); + CalculoControl.ClienteIdProperty = DependencyProperty.Register("ClienteId", typeof(object), typeof(CalculoControl), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); + CalculoControl.RamoIdProperty = DependencyProperty.Register("RamoId", typeof(object), typeof(CalculoControl), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); + CalculoControl.DocumentoProperty = DependencyProperty.Register("Documento", typeof(object), typeof(CalculoControl), new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); + } + + public CalculoControl() + { + this.InitializeComponent(); + this.LayoutRoot.DataContext = this; + } + + private async Task AutoCalculo(Gestor.Model.Domain.Seguros.Documento doc) + { + // + // Current member / type: System.Threading.Tasks.Task`1 Gestor.Application.Componentes.CalculoControl::AutoCalculo(Gestor.Model.Domain.Seguros.Documento) + // File path: C:\AggerSeguros\Gestor.Application.exe + // + // Product version: 0.0.0.0 + // Exception in: System.Threading.Tasks.Task AutoCalculo(Gestor.Model.Domain.Seguros.Documento) + // + // Object reference not set to an instance of an object. + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.FindLowestCommonAncestor(ICollection`1 typeNodes) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 515 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.MergeWithLowestCommonAncestor() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 459 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.ProcessSingleConstraints() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 378 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.InferTypes() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 331 + // at Telerik.JustDecompiler.Decompiler.ExpressionDecompilerStep.Process(DecompilationContext theContext, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\ExpressionDecompilerStep.cs:line 104 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.Extensions.DecompileStateMachine(MethodBody body, DecompilationContext enclosingContext, BaseStateMachineRemoverStep removeStateMachineStep, Func`2 stateMachineDataSelector, DecompilationContext& decompilationContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 104 + // at Telerik.JustDecompiler.Decompiler.Extensions.DecompileAsyncStateMachine(MethodBody body, DecompilationContext enclosingContext, AsyncData& asyncData) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 150 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.GetMoveNextStatements() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 155 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.Match() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 60 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.Process(DecompilationContext context, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 31 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.Extensions.RunPipeline(DecompilationPipeline pipeline, ILanguage language, MethodBody body, DecompilationContext& context) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 95 + // at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61 + // at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 118 + // + // mailto: JustDecompilePublicFeedback@telerik.com + + } + + public static async Task BuscaClienteCompleto(long idCliente) + { + Cliente cliente = await (new ClienteServico()).BuscarCliente(idCliente); + ObservableCollection observableCollection = await (new ClienteServico()).BuscarTelefonesAsync(idCliente); + ObservableCollection observableCollection1 = await (new ClienteServico()).BuscarEmailsAsync(idCliente); + ObservableCollection observableCollection2 = await (new ClienteServico()).BuscarEnderecosAsync(idCliente); + cliente.set_Telefones(new ObservableCollection(observableCollection)); + cliente.set_Emails(new ObservableCollection(observableCollection1)); + cliente.set_Enderecos(new ObservableCollection(observableCollection2)); + Cliente cliente1 = cliente; + cliente = null; + observableCollection = null; + observableCollection1 = null; + return cliente1; + } + + private async void Calcular_OnClick(object sender, RoutedEventArgs e) + { + long? nullable; + long? nullable1; + if (await this.VerificarPermissao()) + { + if (this.DocumentoId != null) + { + List produtos = LicenseHelper.Produtos; + if (!produtos.Any((Licenca produto) => produto.get_Produto() == 91)) + { + await this.Iniciar(true); + Gestor.Model.Domain.Seguros.Documento documento = await (new ApoliceServico()).BuscarApoliceAsync(long.Parse(this.DocumentoId.ToString()), true, false); + long id = documento.get_Controle().get_Cliente().get_Id(); + long num = documento.get_Id(); + long id1 = documento.get_Controle().get_Id(); + List itensAtivo = documento.get_ItensAtivo(); + if (itensAtivo != null) + { + Item item = itensAtivo.FirstOrDefault(); + if (item != null) + { + nullable1 = new long?(item.get_Id()); + } + else + { + nullable = null; + nullable1 = nullable; + } + } + else + { + nullable = null; + nullable1 = nullable; + } + dynamic variable = new { ClientId = id, DocumentId = num, ControlId = id1, ItemId = nullable1, Branch = documento.get_Controle().get_Ramo().get_Id() }; + this.IniciarPipe(variable); + } + else if (!string.IsNullOrEmpty(Recursos.Usuario.get_Email())) + { + string str = await this.CalculoWeb(this.DocumentoId.ToString()); + if (!ExtensionMethods.IsNullOrEmpty(str)) + { + if (await (new DashboardViewModel()).ShowMessage(this._messageAggilizadorWeb, "SIM", "NÃO", false)) + { + int num1 = 0; + try + { + ProcessStartInfo processStartInfo = new ProcessStartInfo(str) + { + UseShellExecute = true + }; + Process.Start(processStartInfo); + } + catch + { + num1 = 1; + } + if (num1 == 1) + { + await (new DashboardViewModel()).ShowMessage("ERRO AO ABRIR CALCULO", "OK", "", false); + } + } + } + } + else + { + await (new DashboardViewModel()).ShowMessage("USUÁRIO SEM E-MAIL CADASTRADO! O E-MAIL CADASTRADO DEVE SER O MESMO DO AGGILIZADOR.", "OK", "", false); + } + } + else + { + this.Prospectar(); + } + } + } + + private async Task CalculoWeb(string idDocumento) + { + // + // Current member / type: System.Threading.Tasks.Task`1 Gestor.Application.Componentes.CalculoControl::CalculoWeb(System.String) + // File path: C:\AggerSeguros\Gestor.Application.exe + // + // Product version: 0.0.0.0 + // Exception in: System.Threading.Tasks.Task CalculoWeb(System.String) + // + // Object reference not set to an instance of an object. + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.FindLowestCommonAncestor(ICollection`1 typeNodes) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 515 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.MergeWithLowestCommonAncestor() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 459 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.ProcessSingleConstraints() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 378 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.InferTypes() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 331 + // at Telerik.JustDecompiler.Decompiler.ExpressionDecompilerStep.Process(DecompilationContext theContext, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\ExpressionDecompilerStep.cs:line 104 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.Extensions.DecompileStateMachine(MethodBody body, DecompilationContext enclosingContext, BaseStateMachineRemoverStep removeStateMachineStep, Func`2 stateMachineDataSelector, DecompilationContext& decompilationContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 104 + // at Telerik.JustDecompiler.Decompiler.Extensions.DecompileAsyncStateMachine(MethodBody body, DecompilationContext enclosingContext, AsyncData& asyncData) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 150 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.GetMoveNextStatements() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 155 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.Match() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 60 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.Process(DecompilationContext context, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 31 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.Extensions.RunPipeline(DecompilationPipeline pipeline, ILanguage language, MethodBody body, DecompilationContext& context) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 95 + // at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61 + // at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 118 + // + // mailto: JustDecompilePublicFeedback@telerik.com + + } + + private async Task CallPipe(dynamic message) + { + dynamic obj; + int num = 7; + PipeClient pipeClient = new PipeClient("AggilizadorPIPE"); + dynamic obj1 = pipeClient.Send(message); + while (true) + { + dynamic obj2 = !obj1; + obj = (!obj2 ? obj2 : obj2 & num > 0); + if (!obj) + { + break; + } + await Task.Delay(2000); + obj1 = pipeClient.Send(message); + num--; + } + bool flag = (bool)obj1; + pipeClient = null; + return flag; + } + + private async Task CondominioCalculo(Gestor.Model.Domain.Seguros.Documento doc) + { + // + // Current member / type: System.Threading.Tasks.Task`1 Gestor.Application.Componentes.CalculoControl::CondominioCalculo(Gestor.Model.Domain.Seguros.Documento) + // File path: C:\AggerSeguros\Gestor.Application.exe + // + // Product version: 0.0.0.0 + // Exception in: System.Threading.Tasks.Task CondominioCalculo(Gestor.Model.Domain.Seguros.Documento) + // + // Object reference not set to an instance of an object. + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.FindLowestCommonAncestor(ICollection`1 typeNodes) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 515 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.MergeWithLowestCommonAncestor() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 459 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.ProcessSingleConstraints() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 378 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.InferTypes() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 331 + // at Telerik.JustDecompiler.Decompiler.ExpressionDecompilerStep.Process(DecompilationContext theContext, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\ExpressionDecompilerStep.cs:line 104 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.Extensions.DecompileStateMachine(MethodBody body, DecompilationContext enclosingContext, BaseStateMachineRemoverStep removeStateMachineStep, Func`2 stateMachineDataSelector, DecompilationContext& decompilationContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 104 + // at Telerik.JustDecompiler.Decompiler.Extensions.DecompileAsyncStateMachine(MethodBody body, DecompilationContext enclosingContext, AsyncData& asyncData) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 150 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.GetMoveNextStatements() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 155 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.Match() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 60 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.Process(DecompilationContext context, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 31 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.Extensions.RunPipeline(DecompilationPipeline pipeline, ILanguage language, MethodBody body, DecompilationContext& context) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 95 + // at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61 + // at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 118 + // + // mailto: JustDecompilePublicFeedback@telerik.com + + } + + private void DropContextMenu_OnClick(object sender, RoutedEventArgs e) + { + if (string.IsNullOrEmpty(this.Documento)) + { + this.Calcular_OnClick(sender, e); + return; + } + Button button = sender as Button; + System.Windows.Controls.ContextMenu contextMenu = button.ContextMenu; + contextMenu.PlacementTarget = button; + contextMenu.Placement = PlacementMode.Top; + contextMenu.IsOpen = true; + } + + private async Task EmpresaCalculo(Gestor.Model.Domain.Seguros.Documento doc) + { + // + // Current member / type: System.Threading.Tasks.Task`1 Gestor.Application.Componentes.CalculoControl::EmpresaCalculo(Gestor.Model.Domain.Seguros.Documento) + // File path: C:\AggerSeguros\Gestor.Application.exe + // + // Product version: 0.0.0.0 + // Exception in: System.Threading.Tasks.Task EmpresaCalculo(Gestor.Model.Domain.Seguros.Documento) + // + // Object reference not set to an instance of an object. + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.FindLowestCommonAncestor(ICollection`1 typeNodes) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 515 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.MergeWithLowestCommonAncestor() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 459 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.ProcessSingleConstraints() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 378 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.InferTypes() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 331 + // at Telerik.JustDecompiler.Decompiler.ExpressionDecompilerStep.Process(DecompilationContext theContext, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\ExpressionDecompilerStep.cs:line 104 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.Extensions.DecompileStateMachine(MethodBody body, DecompilationContext enclosingContext, BaseStateMachineRemoverStep removeStateMachineStep, Func`2 stateMachineDataSelector, DecompilationContext& decompilationContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 104 + // at Telerik.JustDecompiler.Decompiler.Extensions.DecompileAsyncStateMachine(MethodBody body, DecompilationContext enclosingContext, AsyncData& asyncData) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 150 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.GetMoveNextStatements() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 155 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.Match() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 60 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.Process(DecompilationContext context, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 31 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.Extensions.RunPipeline(DecompilationPipeline pipeline, ILanguage language, MethodBody body, DecompilationContext& context) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 95 + // at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61 + // at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 118 + // + // mailto: JustDecompilePublicFeedback@telerik.com + + } + + public static async Task EnviaCalculoWeb(string body) + { + string empty; + string str; + try + { + using (HttpClient httpClient = new HttpClient()) + { + string str1 = "qN7vHy58kLTm4PXEbUgfzMAKrZye2GVn3sdJx9oRWcl71tbvQMF3cU6A8xn5"; + Uri apiCalculoWeb = Address.ApiCalculoWeb; + string[] strArrays = new string[] { "calculo" }; + Uri uri = apiCalculoWeb.Append(strArrays); + string[] strArrays1 = new string[] { "negocio" }; + Uri uri1 = uri.Append(strArrays1); + string[] strArrays2 = new string[] { "integracao" }; + Uri uri2 = uri1.Append(strArrays2); + httpClient.get_DefaultRequestHeaders().Clear(); + httpClient.get_DefaultRequestHeaders().Add("Authorization", str1); + StringContent stringContent = new StringContent(body, null, "application/json"); + HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(uri2, stringContent); + if (httpResponseMessage.get_StatusCode() != HttpStatusCode.Unauthorized) + { + string str2 = await httpResponseMessage.get_Content().ReadAsStringAsync(); + JObject jObject = JObject.Parse(str2); + if (!str2.Contains("erro")) + { + JToken item = jObject.get_Item("url"); + if (item != null) + { + str = item.ToString(); + } + else + { + str = null; + } + empty = str; + } + else + { + empty = ""; + } + } + else + { + await (new DashboardViewModel()).ShowMessage("O E-MAIL CADASTRADO NO GESTOR É DIFERENTE DO E-MAIL CADASTRADO NO AGGILIZADOR!", "OK", "", false); + empty = string.Empty; + } + } + } + catch + { + empty = ""; + } + return empty; + } + + private async Task Iniciar(bool trazerParaFrente = false) + { + if (!"Aggilizador.Application".ProgramaEmExecucao()) + { + Action iniciarAggilizador = Gestor.Application.Actions.Actions.IniciarAggilizador; + if (iniciarAggilizador != null) + { + iniciarAggilizador(); + } + else + { + } + await Task.Delay(8000); + } + if (trazerParaFrente) + { + "Aggilizador.Application".BringToFront(); + } + } + + private async void IniciarPipe(dynamic message) + { + CalculoControl.u003cIniciarPipeu003ed__29 variable = new CalculoControl.u003cIniciarPipeu003ed__29(); + variable.u003cu003et__builder = AsyncVoidMethodBuilder.Create(); + variable.u003cu003e4__this = this; + variable.message = message; + variable.u003cu003e1__state = -1; + variable.u003cu003et__builder.Start(ref variable); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/calculocontrol.xaml", UriKind.Relative)); + } + + private async void Prospectar() + { + if (this.ClienteId != null && this.RamoId != null) + { + await this.Iniciar(true); + dynamic variable = new { ClientId = long.Parse(this.ClienteId.ToString()), DocumentId = 0, ControlId = 0, ItemId = 0, Branch = long.Parse(this.RamoId.ToString()) }; + this.IniciarPipe(variable); + } + } + + private async Task ResidenciaCalculo(Gestor.Model.Domain.Seguros.Documento doc) + { + // + // Current member / type: System.Threading.Tasks.Task`1 Gestor.Application.Componentes.CalculoControl::ResidenciaCalculo(Gestor.Model.Domain.Seguros.Documento) + // File path: C:\AggerSeguros\Gestor.Application.exe + // + // Product version: 0.0.0.0 + // Exception in: System.Threading.Tasks.Task ResidenciaCalculo(Gestor.Model.Domain.Seguros.Documento) + // + // Object reference not set to an instance of an object. + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.FindLowestCommonAncestor(ICollection`1 typeNodes) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 515 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.MergeWithLowestCommonAncestor() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 459 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.ProcessSingleConstraints() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 378 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.InferTypes() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 331 + // at Telerik.JustDecompiler.Decompiler.ExpressionDecompilerStep.Process(DecompilationContext theContext, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\ExpressionDecompilerStep.cs:line 104 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.Extensions.DecompileStateMachine(MethodBody body, DecompilationContext enclosingContext, BaseStateMachineRemoverStep removeStateMachineStep, Func`2 stateMachineDataSelector, DecompilationContext& decompilationContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 104 + // at Telerik.JustDecompiler.Decompiler.Extensions.DecompileAsyncStateMachine(MethodBody body, DecompilationContext enclosingContext, AsyncData& asyncData) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 150 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.GetMoveNextStatements() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 155 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.Match() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 60 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.Process(DecompilationContext context, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 31 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.Extensions.RunPipeline(DecompilationPipeline pipeline, ILanguage language, MethodBody body, DecompilationContext& context) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 95 + // at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61 + // at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 118 + // + // mailto: JustDecompilePublicFeedback@telerik.com + + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.LayoutRoot = (Grid)target; + return; + } + case 2: + { + this.CalculoButton = (Button)target; + this.CalculoButton.Click += new RoutedEventHandler(this.DropContextMenu_OnClick); + return; + } + case 3: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Calcular_OnClick); + return; + } + case 4: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.VisualizarCalculos_OnClick); + return; + } + } + this._contentLoaded = true; + } + + private async Task VerificarPermissao() + { + bool flag; + if (Recursos.Usuario.get_PermissaoAggilizador().HasValue) + { + List produtos = LicenseHelper.Produtos; + if (!produtos.All((Licenca x) => { + if (x.get_Produto() == 79 || x.get_Produto() == 81) + { + return false; + } + return x.get_Produto() != 91; + })) + { + flag = true; + } + else + { + await (new DashboardViewModel()).ShowMessage("VOCÊ AINDA NÃO POSSUI AGGILIZADOR DE CÁLCULOS, ENTRE EM CONTATO COM comercial@agger.com.br PARA SABER MAIS", "OK", "", false); + flag = false; + } + } + else + { + await (new DashboardViewModel()).ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR O AGGILIZADOR", "OK", "", false); + flag = false; + } + return flag; + } + + private async Task VidaGlobalCalculo(Gestor.Model.Domain.Seguros.Documento doc) + { + // + // Current member / type: System.Threading.Tasks.Task`1 Gestor.Application.Componentes.CalculoControl::VidaGlobalCalculo(Gestor.Model.Domain.Seguros.Documento) + // File path: C:\AggerSeguros\Gestor.Application.exe + // + // Product version: 0.0.0.0 + // Exception in: System.Threading.Tasks.Task VidaGlobalCalculo(Gestor.Model.Domain.Seguros.Documento) + // + // Object reference not set to an instance of an object. + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.FindLowestCommonAncestor(ICollection`1 typeNodes) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 515 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.MergeWithLowestCommonAncestor() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 459 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.ProcessSingleConstraints() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 378 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.InferTypes() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 331 + // at Telerik.JustDecompiler.Decompiler.ExpressionDecompilerStep.Process(DecompilationContext theContext, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\ExpressionDecompilerStep.cs:line 104 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.Extensions.DecompileStateMachine(MethodBody body, DecompilationContext enclosingContext, BaseStateMachineRemoverStep removeStateMachineStep, Func`2 stateMachineDataSelector, DecompilationContext& decompilationContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 104 + // at Telerik.JustDecompiler.Decompiler.Extensions.DecompileAsyncStateMachine(MethodBody body, DecompilationContext enclosingContext, AsyncData& asyncData) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 150 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.GetMoveNextStatements() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 155 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.Match() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 60 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.Process(DecompilationContext context, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 31 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.Extensions.RunPipeline(DecompilationPipeline pipeline, ILanguage language, MethodBody body, DecompilationContext& context) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 95 + // at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61 + // at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 118 + // + // mailto: JustDecompilePublicFeedback@telerik.com + + } + + private async Task VidaIndividualCalculo(Gestor.Model.Domain.Seguros.Documento doc) + { + // + // Current member / type: System.Threading.Tasks.Task`1 Gestor.Application.Componentes.CalculoControl::VidaIndividualCalculo(Gestor.Model.Domain.Seguros.Documento) + // File path: C:\AggerSeguros\Gestor.Application.exe + // + // Product version: 0.0.0.0 + // Exception in: System.Threading.Tasks.Task VidaIndividualCalculo(Gestor.Model.Domain.Seguros.Documento) + // + // Object reference not set to an instance of an object. + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.FindLowestCommonAncestor(ICollection`1 typeNodes) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 515 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.MergeWithLowestCommonAncestor() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 459 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.ProcessSingleConstraints() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 378 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.InferTypes() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 331 + // at Telerik.JustDecompiler.Decompiler.ExpressionDecompilerStep.Process(DecompilationContext theContext, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\ExpressionDecompilerStep.cs:line 104 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.Extensions.DecompileStateMachine(MethodBody body, DecompilationContext enclosingContext, BaseStateMachineRemoverStep removeStateMachineStep, Func`2 stateMachineDataSelector, DecompilationContext& decompilationContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 104 + // at Telerik.JustDecompiler.Decompiler.Extensions.DecompileAsyncStateMachine(MethodBody body, DecompilationContext enclosingContext, AsyncData& asyncData) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 150 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.GetMoveNextStatements() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 155 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.Match() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 60 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.Process(DecompilationContext context, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 31 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.Extensions.RunPipeline(DecompilationPipeline pipeline, ILanguage language, MethodBody body, DecompilationContext& context) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 95 + // at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61 + // at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 118 + // + // mailto: JustDecompilePublicFeedback@telerik.com + + } + + private async void VisualizarCalculos_OnClick(object sender, RoutedEventArgs e) + { + string str; + string str1; + if (await this.VerificarPermissao()) + { + if (!string.IsNullOrEmpty(this.Documento)) + { + Gestor.Model.Domain.Seguros.Documento documento = await (new ApoliceServico()).BuscarApoliceAsync(long.Parse(this.DocumentoId.ToString()), true, false); + str1 = null; + if (this.RamoId != null && long.Parse(this.RamoId.ToString()) == (long)5) + { + if (documento.get_ItensAtivo() == null || documento.get_ItensAtivo().Count <= 0) + { + str = null; + } + else + { + str = await (new AutoServico()).BuscarChassi(documento.get_ItensAtivo().First().get_Id()); + } + str1 = str; + } + await this.Iniciar(false); + dynamic variable = new { CpfCnpj = this.Documento.Clear() }; + if (this.RamoId != null) + { + variable = new { CpfCnpj = this.Documento.Clear(), Branch = long.Parse(this.RamoId.ToString()) }; + } + if (str1 != null && this.RamoId != null) + { + variable = new { CpfCnpj = this.Documento.Clear(), Branch = long.Parse(this.RamoId.ToString()), Chassi = str1 }; + } + this.IniciarPipe(variable); + } + } + str1 = null; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/CoberturaView.cs b/Codemerx/Gestor.Application/Componentes/CoberturaView.cs new file mode 100644 index 0000000..1aca48f --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/CoberturaView.cs @@ -0,0 +1,139 @@ +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Markup; + +namespace Gestor.Application.Componentes +{ + public class CoberturaView : BaseUserControl, IComponentConnector, IStyleConnector + { + internal DataGrid CoberturaGrid; + + private bool _contentLoaded; + + public CoberturaViewModel ViewModel + { + get; + set; + } + + public CoberturaView(CoberturaViewModel viewModel) + { + this.ViewModel = viewModel ?? new CoberturaViewModel(null, null); + this.InitializeComponent(); + this.CoberturaGrid.DataContext = this.ViewModel; + } + + private void AdicionaCobertura_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AdicionaCobertura(); + } + + private void AutoCompleteBox_Populating(object sender, PopulatingEventArgs e) + { + if (!this.ViewModel.IsEnabled || e.get_Parameter().Trim().Length < 3) + { + return; + } + e.set_Cancel(true); + this.ViewModel.BuscarCobertura(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void ExcluirCobertura_OnClick(object sender, RoutedEventArgs e) + { + bool selectedIndex; + object item; + DataGrid coberturaGrid = this.CoberturaGrid; + if (coberturaGrid != null) + { + selectedIndex = coberturaGrid.SelectedIndex < 0; + } + else + { + selectedIndex = false; + } + if (selectedIndex) + { + return; + } + CoberturaViewModel viewModel = this.ViewModel; + DataGrid dataGrid = this.CoberturaGrid; + if (dataGrid != null) + { + item = dataGrid.Items[this.CoberturaGrid.SelectedIndex]; + } + else + { + item = null; + } + viewModel.ExcluirCobertura((Cobertura)item); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/coberturaview.xaml", UriKind.Relative)); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + if (connectionId == 1) + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AdicionaCobertura_OnClick); + return; + } + if (connectionId != 2) + { + this._contentLoaded = true; + return; + } + this.CoberturaGrid = (DataGrid)target; + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + if (connectionId == 3) + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, CoberturaView.AutoCompleteBox_Populating)); + return; + } + if (connectionId != 4) + { + return; + } + ((Button)target).Click += new RoutedEventHandler(this.ExcluirCobertura_OnClick); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/ContasDialog.cs b/Codemerx/Gestor.Application/Componentes/ContasDialog.cs new file mode 100644 index 0000000..8d09b79 --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/ContasDialog.cs @@ -0,0 +1,73 @@ +using Gestor.Application.ViewModels.Financeiro; +using Gestor.Model.Domain.Financeiro; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Markup; + +namespace Gestor.Application.Componentes +{ + public class ContasDialog : UserControl, IComponentConnector + { + internal Button ImportarButton; + + internal Button CancelarButton; + + private bool _contentLoaded; + + private ContasDialogModel ViewModel + { + get; + set; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public ContasDialog(List contas) + { + this.ViewModel = new ContasDialogModel(contas); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/contasdialog.xaml", UriKind.Relative)); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + if (connectionId == 1) + { + this.ImportarButton = (Button)target; + return; + } + if (connectionId != 2) + { + this._contentLoaded = true; + return; + } + this.CancelarButton = (Button)target; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/CustomIsReadOnlyControl.cs b/Codemerx/Gestor.Application/Componentes/CustomIsReadOnlyControl.cs new file mode 100644 index 0000000..988f8fc --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/CustomIsReadOnlyControl.cs @@ -0,0 +1,76 @@ +using System; +using System.Windows; + +namespace Gestor.Application.Componentes +{ + public class CustomIsReadOnlyControl : CustomItemControl + { + public readonly static DependencyProperty IsReadOnlyProperty; + + public readonly static DependencyProperty HasValidationProperty; + + public readonly static DependencyProperty TextProperty; + + public readonly static DependencyProperty TextAlignmentProperty; + + public bool HasValidation + { + get + { + return (bool)base.GetValue(CustomIsReadOnlyControl.HasValidationProperty); + } + set + { + base.SetValue(CustomIsReadOnlyControl.HasValidationProperty, value); + } + } + + public bool IsReadOnly + { + get + { + return (bool)base.GetValue(CustomIsReadOnlyControl.IsReadOnlyProperty); + } + set + { + base.SetValue(CustomIsReadOnlyControl.IsReadOnlyProperty, value); + } + } + + public string Text + { + get + { + return (string)base.GetValue(CustomIsReadOnlyControl.TextProperty); + } + set + { + base.SetValue(CustomIsReadOnlyControl.TextProperty, value); + } + } + + public System.Windows.TextAlignment TextAlignment + { + get + { + return (System.Windows.TextAlignment)base.GetValue(CustomIsReadOnlyControl.TextAlignmentProperty); + } + set + { + base.SetValue(CustomIsReadOnlyControl.TextAlignmentProperty, value); + } + } + + static CustomIsReadOnlyControl() + { + CustomIsReadOnlyControl.IsReadOnlyProperty = DependencyProperty.Register("IsReadOnly", typeof(bool), typeof(CustomIsReadOnlyControl), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); + CustomIsReadOnlyControl.HasValidationProperty = DependencyProperty.Register("HasValidation", typeof(bool), typeof(CustomIsReadOnlyControl), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); + CustomIsReadOnlyControl.TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(CustomIsReadOnlyControl), new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); + CustomIsReadOnlyControl.TextAlignmentProperty = DependencyProperty.Register("TextAlignment", typeof(System.Windows.TextAlignment), typeof(CustomIsReadOnlyControl), new FrameworkPropertyMetadata((object)System.Windows.TextAlignment.Left, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); + } + + public CustomIsReadOnlyControl() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/CustomItemControl.cs b/Codemerx/Gestor.Application/Componentes/CustomItemControl.cs new file mode 100644 index 0000000..7f5cbeb --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/CustomItemControl.cs @@ -0,0 +1,54 @@ +using System; +using System.Runtime.CompilerServices; +using System.Windows; +using System.Windows.Controls; + +namespace Gestor.Application.Componentes +{ + public class CustomItemControl : ItemsControl + { + public readonly static DependencyProperty LabelProperty; + + public readonly static DependencyProperty LabelVisibilityProperty; + + public bool Entered + { + get; + set; + } + + public string Label + { + get + { + return (string)base.GetValue(CustomItemControl.LabelProperty); + } + set + { + base.SetValue(CustomItemControl.LabelProperty, value); + } + } + + public System.Windows.Visibility LabelVisibility + { + get + { + return (System.Windows.Visibility)base.GetValue(CustomItemControl.LabelVisibilityProperty); + } + set + { + base.SetValue(CustomItemControl.LabelVisibilityProperty, value); + } + } + + static CustomItemControl() + { + CustomItemControl.LabelProperty = DependencyProperty.Register("Label", typeof(string), typeof(CustomItemControl), new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); + CustomItemControl.LabelVisibilityProperty = DependencyProperty.Register("LabelVisibility", typeof(System.Windows.Visibility), typeof(CustomItemControl), new FrameworkPropertyMetadata((object)System.Windows.Visibility.Visible, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); + } + + public CustomItemControl() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/CustomItemValidation.cs b/Codemerx/Gestor.Application/Componentes/CustomItemValidation.cs new file mode 100644 index 0000000..760f804 --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/CustomItemValidation.cs @@ -0,0 +1,11 @@ +using System; + +namespace Gestor.Application.Componentes +{ + public class CustomItemValidation : CustomItemControl + { + public CustomItemValidation() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/CustomLegendChart.cs b/Codemerx/Gestor.Application/Componentes/CustomLegendChart.cs new file mode 100644 index 0000000..ddbff3c --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/CustomLegendChart.cs @@ -0,0 +1,140 @@ +using LiveCharts.Definitions.Series; +using LiveCharts.Wpf; +using LiveCharts.Wpf.Charts.Base; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Markup; +using System.Windows.Media; + +namespace Gestor.Application.Componentes +{ + public class CustomLegendChart : UserControl, IChartLegend, INotifyPropertyChanged, IComponentConnector + { + public readonly static DependencyProperty OrientationProperty; + + internal ItemsControl itemsControl; + + private bool _contentLoaded; + + public ObservableCollection LegendEntries { get; } = new ObservableCollection(); + + public System.Windows.Controls.Orientation Orientation + { + get + { + return (System.Windows.Controls.Orientation)base.GetValue(CustomLegendChart.OrientationProperty); + } + set + { + base.SetValue(CustomLegendChart.OrientationProperty, value); + } + } + + public List Series + { + get + { + return ( + from x in this.LegendEntries + select x.SeriesViewModel).ToList(); + } + set + { + Chart ownerChart = this.GetOwnerChart(); + foreach (CustomSeriesViewModel list in ( + from x in this.LegendEntries + where !ownerChart.get_Series().Any((ISeriesView s) => (object)s == (object)x.View) + select x).ToList()) + { + this.LegendEntries.Remove(list); + } + foreach (SeriesViewModel seriesViewModel in value) + { + if (!this.LegendEntries.All((CustomSeriesViewModel x) => x.Title != seriesViewModel.get_Title())) + { + continue; + } + ISeriesView seriesView = ownerChart.get_Series().FirstOrDefault((ISeriesView x) => x.get_Title() == seriesViewModel.get_Title()); + this.LegendEntries.Add(new CustomSeriesViewModel(seriesViewModel, seriesView)); + } + this.OnPropertyChanged("Series"); + } + } + + static CustomLegendChart() + { + CustomLegendChart.OrientationProperty = DependencyProperty.Register("Orientation", typeof(System.Windows.Controls.Orientation), typeof(CustomLegendChart), new PropertyMetadata((object)System.Windows.Controls.Orientation.Horizontal)); + } + + public CustomLegendChart() + { + this.InitializeComponent(); + this.itemsControl.DataContext = this; + } + + public static T FindParent(DependencyObject child) + where T : DependencyObject + { + DependencyObject parent = VisualTreeHelper.GetParent(child); + if (parent == null) + { + return default(T); + } + T t = (T)(parent as T); + if (t != null) + { + return t; + } + return CustomLegendChart.FindParent(parent); + } + + private Chart GetOwnerChart() + { + return CustomLegendChart.FindParent(this); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/customlegendchart.xaml", UriKind.Relative)); + } + + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = "") + { + if (this.PropertyChanged != null) + { + this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + if (connectionId != 1) + { + this._contentLoaded = true; + return; + } + this.itemsControl = (ItemsControl)target; + } + + public event PropertyChangedEventHandler PropertyChanged; + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/CustomPasswordBox.cs b/Codemerx/Gestor.Application/Componentes/CustomPasswordBox.cs new file mode 100644 index 0000000..9b1c76d --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/CustomPasswordBox.cs @@ -0,0 +1,203 @@ +using System; +using System.CodeDom.Compiler; +using System.ComponentModel; +using System.Diagnostics; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Markup; + +namespace Gestor.Application.Componentes +{ + public class CustomPasswordBox : UserControl, IComponentConnector + { + public readonly static DependencyProperty IsReadOnlyProperty; + + public readonly static DependencyProperty TextProperty; + + public readonly static DependencyProperty PasswordViewProperty; + + private bool _typing; + + internal Grid LayoutRoot; + + internal TextBox TextRead; + + internal TextBox TextMask; + + internal System.Windows.Controls.PasswordBox PasswordBox; + + private bool _contentLoaded; + + public bool IsReadOnly + { + get + { + return (bool)base.GetValue(CustomPasswordBox.IsReadOnlyProperty); + } + set + { + base.SetValue(CustomPasswordBox.IsReadOnlyProperty, value); + } + } + + public bool PasswordView + { + get + { + return (bool)base.GetValue(CustomPasswordBox.PasswordViewProperty); + } + set + { + base.SetValue(CustomPasswordBox.PasswordViewProperty, value); + } + } + + public string Text + { + get + { + return (string)base.GetValue(CustomPasswordBox.TextProperty); + } + set + { + base.SetValue(CustomPasswordBox.TextProperty, value); + } + } + + static CustomPasswordBox() + { + CustomPasswordBox.IsReadOnlyProperty = DependencyProperty.Register("IsReadOnly", typeof(bool), typeof(CustomPasswordBox), new PropertyMetadata(false, new PropertyChangedCallback(CustomPasswordBox.OnBoundIsReadOnlyChanged))); + CustomPasswordBox.TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(CustomPasswordBox), new PropertyMetadata(string.Empty, new PropertyChangedCallback(CustomPasswordBox.OnBoundPasswordChanged))); + CustomPasswordBox.PasswordViewProperty = DependencyProperty.Register("PasswordViewProperty", typeof(bool), typeof(CustomPasswordBox), new PropertyMetadata(false, new PropertyChangedCallback(CustomPasswordBox.OnBoundPasswordViewChanged))); + } + + public CustomPasswordBox() + { + this.InitializeComponent(); + this.LayoutRoot.DataContext = this; + this.PasswordView = false; + } + + private void Eye_Click(object sender, RoutedEventArgs e) + { + if (this.IsReadOnly) + { + return; + } + this.PasswordView = !this.PasswordView; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/custompasswordbox.xaml", UriKind.Relative)); + } + + private static void OnBoundIsReadOnlyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + CustomPasswordBox customPasswordBox = d as CustomPasswordBox; + if (d == null || customPasswordBox == null) + { + return; + } + bool newValue = (bool)e.NewValue; + customPasswordBox.PasswordBox.Visibility = (newValue ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible); + customPasswordBox.TextRead.Visibility = (newValue ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + customPasswordBox.TextMask.Visibility = (newValue ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + } + + private static void OnBoundPasswordChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + CustomPasswordBox customPasswordBox = d as CustomPasswordBox; + if (d == null || customPasswordBox == null) + { + return; + } + string newValue = (string)e.NewValue ?? ""; + if (customPasswordBox._typing) + { + return; + } + customPasswordBox.TextMask.Text = "".PadLeft(newValue.Length, '•'); + customPasswordBox.PasswordBox.Password = newValue; + } + + private static void OnBoundPasswordViewChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + CustomPasswordBox text = d as CustomPasswordBox; + if (d == null || text == null) + { + return; + } + bool newValue = (bool)e.NewValue; + if (!newValue) + { + text.PasswordBox.Password = text.TextRead.Text; + } + else + { + text.TextRead.Text = text.PasswordBox.Password; + } + text.PasswordBox.Visibility = (newValue ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible); + text.TextRead.Visibility = (newValue ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + text.TextMask.Visibility = text.PasswordBox.Visibility; + } + + private void PasswordBox_PasswordChanged(object sender, RoutedEventArgs e) + { + this._typing = true; + this.Text = this.PasswordBox.Password; + this._typing = false; + this.TextMask.Text = "".PadLeft(this.PasswordBox.Password.Length, '•'); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.LayoutRoot = (Grid)target; + return; + } + case 2: + { + this.TextRead = (TextBox)target; + this.TextRead.TextChanged += new TextChangedEventHandler(this.TextRead_PasswordChanged); + return; + } + case 3: + { + this.TextMask = (TextBox)target; + return; + } + case 4: + { + this.PasswordBox = (System.Windows.Controls.PasswordBox)target; + this.PasswordBox.PasswordChanged += new RoutedEventHandler(this.PasswordBox_PasswordChanged); + return; + } + case 5: + { + ((Button)target).Click += new RoutedEventHandler(this.Eye_Click); + return; + } + } + this._contentLoaded = true; + } + + private void TextRead_PasswordChanged(object sender, TextChangedEventArgs e) + { + this.Text = this.TextRead.Text; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/CustomSenhaLoginBox.cs b/Codemerx/Gestor.Application/Componentes/CustomSenhaLoginBox.cs new file mode 100644 index 0000000..ce1a278 --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/CustomSenhaLoginBox.cs @@ -0,0 +1,338 @@ +using ControlzEx; +using MaterialDesignThemes.Wpf; +using System; +using System.CodeDom.Compiler; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Markup; +using System.Windows.Media; + +namespace Gestor.Application.Componentes +{ + public class CustomSenhaLoginBox : UserControl, IComponentConnector + { + public readonly static DependencyProperty TextProperty; + + public readonly static DependencyProperty IsReadOnlyProperty; + + public readonly static DependencyProperty PlaceHolderProperty; + + public readonly static DependencyProperty BackgroundProperty; + + public readonly static DependencyProperty ForegroundProperty; + + public readonly static DependencyProperty CaretBrushProperty; + + public readonly static DependencyProperty FontFamilyProperty; + + public readonly static DependencyProperty FontSizeProperty; + + public readonly static DependencyProperty BorderThicknessProperty; + + internal Grid LayoutRoot; + + internal TextBox TextRead; + + internal System.Windows.Controls.PasswordBox PasswordBox; + + internal Button ButtonEye; + + private bool _contentLoaded; + + private static bool _typing + { + get; + set; + } + + public new Brush Background + { + get + { + return (Brush)base.GetValue(CustomSenhaLoginBox.BackgroundProperty); + } + set + { + base.SetValue(CustomSenhaLoginBox.BackgroundProperty, value); + } + } + + public new Thickness BorderThickness + { + get + { + return (Thickness)base.GetValue(CustomSenhaLoginBox.BorderThicknessProperty); + } + set + { + base.SetValue(CustomSenhaLoginBox.BorderThicknessProperty, value); + } + } + + public Brush CaretBrush + { + get + { + return (Brush)base.GetValue(CustomSenhaLoginBox.CaretBrushProperty); + } + set + { + base.SetValue(CustomSenhaLoginBox.CaretBrushProperty, value); + } + } + + public new System.Windows.Media.FontFamily FontFamily + { + get + { + return (System.Windows.Media.FontFamily)base.GetValue(CustomSenhaLoginBox.FontFamilyProperty); + } + set + { + base.SetValue(CustomSenhaLoginBox.FontFamilyProperty, value); + } + } + + public new int FontSize + { + get + { + return (int)base.GetValue(CustomSenhaLoginBox.FontSizeProperty); + } + set + { + base.SetValue(CustomSenhaLoginBox.FontSizeProperty, value); + } + } + + public new Brush Foreground + { + get + { + return (Brush)base.GetValue(CustomSenhaLoginBox.ForegroundProperty); + } + set + { + base.SetValue(CustomSenhaLoginBox.ForegroundProperty, value); + } + } + + public bool IsReadOnly + { + get + { + return (bool)base.GetValue(CustomSenhaLoginBox.IsReadOnlyProperty); + } + set + { + base.SetValue(CustomSenhaLoginBox.IsReadOnlyProperty, value); + } + } + + public string PlaceHolder + { + get + { + return (string)base.GetValue(CustomSenhaLoginBox.PlaceHolderProperty); + } + set + { + base.SetValue(CustomSenhaLoginBox.PlaceHolderProperty, value); + } + } + + public string Text + { + get + { + return (string)base.GetValue(CustomSenhaLoginBox.TextProperty); + } + set + { + base.SetValue(CustomSenhaLoginBox.TextProperty, value); + } + } + + static CustomSenhaLoginBox() + { + CustomSenhaLoginBox.TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(CustomSenhaLoginBox), new PropertyMetadata(string.Empty, new PropertyChangedCallback(CustomSenhaLoginBox.OnBoundPasswordChanged))); + CustomSenhaLoginBox.IsReadOnlyProperty = DependencyProperty.Register("IsReadOnly", typeof(bool), typeof(CustomSenhaLoginBox), new PropertyMetadata(false, new PropertyChangedCallback(CustomSenhaLoginBox.OnBoundIsReadOnlyChanged))); + CustomSenhaLoginBox.PlaceHolderProperty = DependencyProperty.Register("PlaceHolder", typeof(string), typeof(CustomSenhaLoginBox), new FrameworkPropertyMetadata("SENHA", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); + CustomSenhaLoginBox.BackgroundProperty = DependencyProperty.Register("Background", typeof(Brush), typeof(CustomSenhaLoginBox), new PropertyMetadata(null, new PropertyChangedCallback(CustomSenhaLoginBox.OnBackgroundChanged))); + CustomSenhaLoginBox.ForegroundProperty = DependencyProperty.Register("Foreground", typeof(Brush), typeof(CustomSenhaLoginBox), new PropertyMetadata(null, new PropertyChangedCallback(CustomSenhaLoginBox.OnForegroundChanged))); + CustomSenhaLoginBox.CaretBrushProperty = DependencyProperty.Register("CaretBrush", typeof(Brush), typeof(CustomSenhaLoginBox), new PropertyMetadata(null, new PropertyChangedCallback(CustomSenhaLoginBox.OnCaretBrushChanged))); + CustomSenhaLoginBox.FontFamilyProperty = DependencyProperty.Register("FontFamily", typeof(System.Windows.Media.FontFamily), typeof(CustomSenhaLoginBox), new PropertyMetadata(null, new PropertyChangedCallback(CustomSenhaLoginBox.OnFontFamilyChanged))); + CustomSenhaLoginBox.FontSizeProperty = DependencyProperty.Register("FontSize", typeof(int), typeof(CustomSenhaLoginBox), new PropertyMetadata((object)10, new PropertyChangedCallback(CustomSenhaLoginBox.OnFontSizeChanged))); + CustomSenhaLoginBox.BorderThicknessProperty = DependencyProperty.Register("BorderThickness", typeof(Thickness), typeof(CustomSenhaLoginBox), new PropertyMetadata((object)(new Thickness(1)), new PropertyChangedCallback(CustomSenhaLoginBox.OnBorderThicknessChanged))); + } + + public CustomSenhaLoginBox() + { + this.InitializeComponent(); + this.LayoutRoot.DataContext = this; + } + + private void Eye_Click(object sender, RoutedEventArgs e) + { + if (this.IsReadOnly) + { + return; + } + Button button = sender as Button; + this.TextRead.Visibility = (this.TextRead.Visibility == System.Windows.Visibility.Collapsed ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.PasswordBox.Visibility = (this.TextRead.Visibility == System.Windows.Visibility.Collapsed ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + if (button != null && button.Content != null) + { + ((PackIcon)button.Content).set_Kind((this.TextRead.Visibility == System.Windows.Visibility.Collapsed ? 1492 : 1497)); + } + if (this.PasswordBox.Visibility != System.Windows.Visibility.Visible) + { + return; + } + this.PasswordBox.Focus(); + this.PasswordBox.SelectAll(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/customsenhaloginbox.xaml", UriKind.Relative)); + } + + private static void OnBackgroundChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + CustomSenhaLoginBox newValue = d as CustomSenhaLoginBox; + if (d == null || newValue == null) + { + return; + } + newValue.Background = (Brush)e.NewValue; + } + + private static void OnBorderThicknessChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + CustomSenhaLoginBox newValue = d as CustomSenhaLoginBox; + if (d == null || newValue == null) + { + return; + } + newValue.BorderThickness = (Thickness)e.NewValue; + } + + private static void OnBoundIsReadOnlyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + CustomPasswordBox customPasswordBox = d as CustomPasswordBox; + if (d == null || customPasswordBox == null) + { + return; + } + bool newValue = (bool)e.NewValue; + customPasswordBox.PasswordBox.Visibility = (newValue ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible); + customPasswordBox.TextRead.Visibility = (newValue ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + } + + private static void OnBoundPasswordChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + CustomSenhaLoginBox customSenhaLoginBox = d as CustomSenhaLoginBox; + if (d == null || customSenhaLoginBox == null) + { + return; + } + string newValue = (string)e.NewValue ?? ""; + if (CustomSenhaLoginBox._typing) + { + return; + } + customSenhaLoginBox.PasswordBox.Password = newValue; + } + + private static void OnCaretBrushChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + CustomSenhaLoginBox newValue = d as CustomSenhaLoginBox; + if (d == null || newValue == null) + { + return; + } + newValue.CaretBrush = (Brush)e.NewValue; + } + + private static void OnFontFamilyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + CustomSenhaLoginBox newValue = d as CustomSenhaLoginBox; + if (d == null || newValue == null) + { + return; + } + newValue.FontFamily = (System.Windows.Media.FontFamily)e.NewValue; + } + + private static void OnFontSizeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + CustomSenhaLoginBox newValue = d as CustomSenhaLoginBox; + if (d == null || newValue == null) + { + return; + } + newValue.FontSize = (int)e.NewValue; + } + + private static void OnForegroundChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + CustomSenhaLoginBox newValue = d as CustomSenhaLoginBox; + if (d == null || newValue == null) + { + return; + } + newValue.Foreground = (Brush)e.NewValue; + } + + private void PasswordBox_PasswordChanged(object sender, RoutedEventArgs e) + { + CustomSenhaLoginBox._typing = true; + this.Text = this.PasswordBox.Password; + CustomSenhaLoginBox._typing = false; + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.LayoutRoot = (Grid)target; + return; + } + case 2: + { + this.TextRead = (TextBox)target; + return; + } + case 3: + { + this.PasswordBox = (System.Windows.Controls.PasswordBox)target; + this.PasswordBox.PasswordChanged += new RoutedEventHandler(this.PasswordBox_PasswordChanged); + return; + } + case 4: + { + this.ButtonEye = (Button)target; + this.ButtonEye.Click += new RoutedEventHandler(this.Eye_Click); + return; + } + } + this._contentLoaded = true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/CustomSeriesViewModel.cs b/Codemerx/Gestor.Application/Componentes/CustomSeriesViewModel.cs new file mode 100644 index 0000000..7c4a6cf --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/CustomSeriesViewModel.cs @@ -0,0 +1,72 @@ +using LiveCharts.Definitions.Series; +using LiveCharts.Wpf; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Windows; +using System.Windows.Media; + +namespace Gestor.Application.Componentes +{ + public class CustomSeriesViewModel : INotifyPropertyChanged + { + public Brush Fill + { + get + { + return this.SeriesViewModel.get_Fill() ?? this.SeriesViewModel.get_Stroke(); + } + } + + public bool IsVisible + { + get + { + return ((UIElement)this.View).Visibility == Visibility.Visible; + } + set + { + if (this.IsVisible != value) + { + ((UIElement)this.View).Visibility = (value ? Visibility.Visible : Visibility.Hidden); + this.OnPropertyChanged("IsVisible"); + } + } + } + + public LiveCharts.Wpf.SeriesViewModel SeriesViewModel + { + get; + } + + public string Title + { + get + { + return this.SeriesViewModel.get_Title(); + } + } + + public ISeriesView View + { + get; + } + + public CustomSeriesViewModel(LiveCharts.Wpf.SeriesViewModel svm, ISeriesView view) + { + this.SeriesViewModel = svm; + this.View = view; + } + + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = "") + { + if (this.PropertyChanged != null) + { + this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + + public event PropertyChangedEventHandler PropertyChanged; + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/DefaultDialog.cs b/Codemerx/Gestor.Application/Componentes/DefaultDialog.cs new file mode 100644 index 0000000..5ff7c1e --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/DefaultDialog.cs @@ -0,0 +1,40 @@ +using Gestor.Application.Views.Generic; +using System; +using System.CodeDom.Compiler; +using System.ComponentModel; +using System.Diagnostics; +using System.Windows; +using System.Windows.Markup; + +namespace Gestor.Application.Componentes +{ + public class DefaultDialog : BaseUserControl, IComponentConnector + { + private bool _contentLoaded; + + public DefaultDialog() + { + this.InitializeComponent(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/defaultdialog.xaml", UriKind.Relative)); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + this._contentLoaded = true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/DialogAdvertising.cs b/Codemerx/Gestor.Application/Componentes/DialogAdvertising.cs new file mode 100644 index 0000000..dfff6b4 --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/DialogAdvertising.cs @@ -0,0 +1,101 @@ +using Gestor.Application.ViewModels.Generic; +using MaterialDesignThemes.Wpf; +using Newtonsoft.Json.Linq; +using System; +using System.CodeDom.Compiler; +using System.ComponentModel; +using System.Diagnostics; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Markup; + +namespace Gestor.Application.Componentes +{ + public class DialogAdvertising : UserControl, IComponentConnector + { + private DialogAdvertisingViewModel ViewModel; + + private readonly bool _isPromocao; + + internal Label Titulo; + + private bool _contentLoaded; + + public DialogAdvertising(JObject jsonAd, bool isPromo = true) + { + this.ViewModel = new DialogAdvertisingViewModel(jsonAd, isPromo); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + } + + private void CloseOnClick(object sender, RoutedEventArgs e) + { + DialogHost.CloseDialogCommand.Execute(null, null); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/dialogadvertising.xaml", UriKind.Relative)); + } + + private void Lido_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.SalvaEditarArquivoConfig(true); + DialogHost.CloseDialogCommand.Execute(null, null); + } + + private void LinkImage_MouseDown(object sender, MouseButtonEventArgs e) + { + try + { + if (!this._isPromocao) + { + this.ViewModel.EnviarPesquisa(); + } + Process.Start(this.ViewModel.Url); + } + catch + { + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.Titulo = (Label)target; + return; + } + case 2: + { + ((Button)target).Click += new RoutedEventHandler(this.CloseOnClick); + return; + } + case 3: + { + ((Image)target).MouseDown += new MouseButtonEventHandler(this.LinkImage_MouseDown); + return; + } + case 4: + { + ((Button)target).Click += new RoutedEventHandler(this.Lido_OnClick); + return; + } + } + this._contentLoaded = true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/DialogAnaliticoBi.cs b/Codemerx/Gestor.Application/Componentes/DialogAnaliticoBi.cs new file mode 100644 index 0000000..61adc39 --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/DialogAnaliticoBi.cs @@ -0,0 +1,387 @@ +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Ferramentas; +using Gestor.Application.Views.Generic; +using Gestor.Application.Views.Seguros; +using Gestor.Model.Attributes; +using Gestor.Model.Domain.BI; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.MalaDireta; +using Gestor.Model.Domain.Relatorios.ClientesAtivosInativos; +using Gestor.Model.Domain.Seguros; +using MaterialDesignThemes.Wpf; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Data; +using System.Windows.Input; +using System.Windows.Markup; + +namespace Gestor.Application.Componentes +{ + public class DialogAnaliticoBi : BaseUserControl, IComponentConnector, IStyleConnector + { + internal AnaliticoViewModel ViewModel; + + internal System.Windows.Controls.Grid MainGrid; + + internal DataGrid Grid; + + internal DataGridTemplateColumn InfoButton; + + internal TextBlock Totalizacao; + + private bool _contentLoaded; + + public List Campos + { + get; + set; + } + + public List Lista + { + get; + set; + } + + public DialogAnaliticoBi(string titulo, List analitico, string tipo, List campos) + { + this.ViewModel = new AnaliticoViewModel(tipo); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + this.ViewModel.Head = titulo; + this.Lista = analitico; + this.Campos = campos; + this.ConstruirLista(); + } + + private async Task AbrirTarefa(Tarefa data) + { + // + // Current member / type: System.Threading.Tasks.Task Gestor.Application.Componentes.DialogAnaliticoBi::AbrirTarefa(Gestor.Model.Domain.Ferramentas.Tarefa) + // File path: C:\AggerSeguros\Gestor.Application.exe + // + // Product version: 0.0.0.0 + // Exception in: System.Threading.Tasks.Task AbrirTarefa(Gestor.Model.Domain.Ferramentas.Tarefa) + // + // Collection was modified; enumeration operation may not execute. + // at System.Collections.Generic.List`1.Enumerator.MoveNextRare() + // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.Visit(IEnumerable collection) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 384 + // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.VisitBlockStatement(BlockStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 33 + // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.Process(DecompilationContext context, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 21 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.Extensions.RunPipeline(DecompilationPipeline pipeline, ILanguage language, MethodBody body, DecompilationContext& context) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 95 + // at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61 + // at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 118 + // + // mailto: JustDecompilePublicFeedback@telerik.com + + } + + private void CheckBox_Checked(object sender, RoutedEventArgs e) + { + this.Lista.ForEach((Analitico x) => x.set_Selecionado(!x.get_Selecionado())); + this.Grid.ItemsSource = null; + this.Grid.ItemsSource = this.Lista; + } + + private void ConstruirLista() + { + this.ViewModel.Loading(true); + PropertyInfo[] properties = this.Lista.First().GetType().GetProperties(); + this.Campos.ForEach((string x) => { + PropertyInfo propertyInfo = properties.FirstOrDefault((PropertyInfo p) => p.Name == x); + if (propertyInfo == null) + { + return; + } + object obj = propertyInfo.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault(); + string upper = propertyInfo.Name.ToUpper(); + if (obj != null) + { + upper = ((DescriptionAttribute)obj).Description; + } + object obj1 = propertyInfo.GetCustomAttributes(typeof(TipoAttribute), true).FirstOrDefault(); + string description = ""; + if (obj1 != null) + { + description = ((TipoAttribute)obj1).get_Description(); + } + string str = ""; + System.Windows.Style item = (System.Windows.Style)System.Windows.Application.Current.Resources["VerticalCenterStyle3"]; + System.Windows.Style style = (System.Windows.Style)System.Windows.Application.Current.Resources["MaterialDesignDataGridColumnHeader"]; + if (description == "DATA" || description == "DATA?") + { + str = "d"; + item = (System.Windows.Style)System.Windows.Application.Current.Resources["HorizontalCenterStyle2"]; + style = (System.Windows.Style)System.Windows.Application.Current.Resources["HorizontalCenterHeaderStyle"]; + } + else if (description == "PERCENTUAL") + { + str = "{0:0.00}%"; + item = (System.Windows.Style)System.Windows.Application.Current.Resources["HorizontalRightStyle"]; + style = (System.Windows.Style)System.Windows.Application.Current.Resources["HorizontalRightHeaderStyle"]; + } + else if (description == "VALOR" || description == "VALOR?") + { + str = "c"; + item = (System.Windows.Style)System.Windows.Application.Current.Resources["HorizontalRightStyle"]; + style = (System.Windows.Style)System.Windows.Application.Current.Resources["HorizontalRightHeaderStyle"]; + } + else if (description == "QUANTIDADE") + { + item = (System.Windows.Style)System.Windows.Application.Current.Resources["HorizontalCenterStyle2"]; + style = (System.Windows.Style)System.Windows.Application.Current.Resources["HorizontalCenterHeaderStyle"]; + } + this.Grid.Columns.Add(new MaterialDataGridTextColumn() + { + IsReadOnly = true, + Header = upper, + Binding = new Binding() + { + Path = new PropertyPath(propertyInfo.Name, Array.Empty()), + StringFormat = str, + UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged + }, + ElementStyle = item, + HeaderStyle = style + }); + }); + this.Grid.ItemsSource = this.Lista; + this.Totalizar(); + this.ViewModel.Loading(false); + } + + private async void Email_OnClick(object sender, RoutedEventArgs e) + { + List lista = this.Lista; + if (lista.Any((Analitico x) => x.get_Selecionado())) + { + if (Funcoes.IsWindowOpen("ENVIO DE E-MAIL")) + { + Funcoes.Destroy("ENVIO DE E-MAIL"); + } + List analiticos = this.Lista; + (new HosterWindow(new MalaDiretaView(( + from x in analiticos + where x.get_Selecionado() + select x).Select((Analitico x) => { + MalaDireta malaDiretum = new MalaDireta(); + Cliente cliente = new Cliente(); + cliente.set_Id(x.get_Cliente().get_Id()); + cliente.set_Nome(x.get_Cliente().get_Nome()); + cliente.set_Nascimento(x.get_Cliente().get_Nascimento()); + cliente.set_VencimentoHabilitacao(x.get_Cliente().get_VencimentoCnh()); + malaDiretum.set_Cliente(cliente); + malaDiretum.set_Apolice(x.get_Documento()); + malaDiretum.set_Parcela(x.get_Parcela()); + malaDiretum.set_Tela(this.ViewModel.Tela); + return malaDiretum; + }).ToList(), null, null, null), "ENVIO DE E-MAIL", new double?((double)1200), new double?((double)600), true)).Show(); + } + else + { + await this.ViewModel.ShowMessage("NECESSÁRIO SELECIONAR AO MENOS UM CLIENTE PARA PROSSEGUIR", "OK", "", false); + } + } + + private async void Grid_OnMouseDoubleClick(object sender, MouseButtonEventArgs e) + { + double? nullable; + if (this.Grid.SelectedItem != null && (!(this.ViewModel.Tipo == "PARCELAS") || !(this.ViewModel.Tipo == "APOLICES"))) + { + if (this.ViewModel.Tipo != "CLIENTES") + { + Analitico selectedItem = (Analitico)this.Grid.SelectedItem; + nullable = null; + double? nullable1 = nullable; + nullable = null; + (new HosterWindow(new ApoliceView(selectedItem.get_Documento(), true, false, 0, (long)0, false), string.Concat("CADASTRO DE APÓLICES - ", selectedItem.get_Cliente().get_Nome()), nullable1, nullable, false)).Show(); + } + else + { + Analitico analitico = (Analitico)this.Grid.SelectedItem; + Cliente cliente = await this.ViewModel.CarregaCliente(analitico.get_Cliente().get_Id()); + nullable = null; + double? nullable2 = nullable; + nullable = null; + (new HosterWindow(new ClienteView(cliente, true, null), string.Concat("CADASTRO DE CLIENTE - ", cliente.get_Nome()), nullable2, nullable, false)).Show(); + } + } + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/dialoganaliticobi.xaml", UriKind.Relative)); + } + + private async void Open_OnClick(object sender, RoutedEventArgs e) + { + double? nullable; + if (this.Grid.SelectedItem != null && (!(this.ViewModel.Tipo == "PARCELAS") || !(this.ViewModel.Tipo == "APOLICES"))) + { + if (this.ViewModel.Tipo != "CLIENTES") + { + Analitico selectedItem = (Analitico)this.Grid.SelectedItem; + nullable = null; + double? nullable1 = nullable; + nullable = null; + (new HosterWindow(new ApoliceView(selectedItem.get_Documento(), true, false, 0, (long)0, false), string.Concat("CADASTRO DE APÓLICES - ", selectedItem.get_Cliente().get_Nome()), nullable1, nullable, false)).Show(); + } + else + { + Analitico analitico = (Analitico)this.Grid.SelectedItem; + Cliente cliente = await this.ViewModel.CarregaCliente(analitico.get_Cliente().get_Id()); + nullable = null; + double? nullable2 = nullable; + nullable = null; + (new HosterWindow(new ClienteView(cliente, true, null), string.Concat("CADASTRO DE CLIENTE - ", cliente.get_Nome()), nullable2, nullable, false)).Show(); + } + } + } + + private async void Print_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Loading(true); + await this.ViewModel.Print(this.Grid); + this.ViewModel.Loading(false); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.MainGrid = (System.Windows.Controls.Grid)target; + return; + } + case 2: + { + this.Grid = (DataGrid)target; + this.Grid.MouseDoubleClick += new MouseButtonEventHandler(this.Grid_OnMouseDoubleClick); + return; + } + case 3: + case 5: + { + this._contentLoaded = true; + return; + } + case 4: + { + this.InfoButton = (DataGridTemplateColumn)target; + return; + } + case 6: + { + this.Totalizacao = (TextBlock)target; + return; + } + case 7: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Tarefas_OnClick); + return; + } + case 8: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Email_OnClick); + return; + } + case 9: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Print_OnClick); + return; + } + default: + { + this._contentLoaded = true; + return; + } + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + if (connectionId != 3) + { + if (connectionId != 5) + { + return; + } + ((Button)target).Click += new RoutedEventHandler(this.Open_OnClick); + return; + } + ((CheckBox)target).Checked += new RoutedEventHandler(this.CheckBox_Checked); + ((CheckBox)target).Unchecked += new RoutedEventHandler(this.CheckBox_Checked); + } + + private async void Tarefas_OnClick(object sender, RoutedEventArgs e) + { + Tarefa tarefa = new Tarefa(); + tarefa.set_Entidade(1); + tarefa.set_Titulo(this.ViewModel.Head); + tarefa.set_Usuario(Recursos.Usuario); + tarefa.set_Agendamento(Funcoes.GetNetworkTime()); + await this.AbrirTarefa(tarefa); + List lista = this.Lista; + List list = ( + from x in lista + where x.get_Selecionado() + select x).ToList(); + this.Lista = this.Lista.Except(list).ToList(); + this.Grid.ItemsSource = null; + this.Grid.ItemsSource = this.Lista; + this.Totalizar(); + } + + private void Totalizar() + { + string tipo = this.ViewModel.Tipo; + if (tipo == "CLIENTES") + { + this.Totalizacao.Text = string.Format("TOTAL DE {0} CLIENTES", this.Lista.Count); + return; + } + if (tipo == "PARCELAS") + { + this.Totalizacao.Text = string.Format("TOTAL DE {0} SEGUROS SOMANDO O VALOR DE {1:c}", this.Lista.Count, this.Lista.Sum((Analitico x) => x.get_Valor())); + return; + } + if (tipo == "COMISSÃO") + { + this.Totalizacao.Text = string.Format("TOTAL DE {0} SEGUROS SOMANDO O VALOR DE COMISSÃO RECEBIDA DE {1:c}", this.Lista.Count, this.Lista.Sum((Analitico x) => x.get_ValorComissao())); + return; + } + this.Totalizacao.Text = string.Format("TOTAL DE {0} SEGUROS SOMANDO O VALOR DE {1:c}", this.Lista.Count, this.Lista.Sum((Analitico x) => x.get_PremioLiquido())); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/DialogAnexar.cs b/Codemerx/Gestor.Application/Componentes/DialogAnexar.cs new file mode 100644 index 0000000..3b87c6d --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/DialogAnexar.cs @@ -0,0 +1,98 @@ +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.Common; +using MaterialDesignThemes.Wpf; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Markup; + +namespace Gestor.Application.Componentes +{ + public class DialogAnexar : UserControl, IComponentConnector, IStyleConnector + { + private DialogAnexarViewModel ViewModel; + + internal Button SalvarButton; + + internal Button CancelarButton; + + private bool _contentLoaded; + + public DialogAnexar(List arquivos) + { + this.ViewModel = new DialogAnexarViewModel(arquivos); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + } + + private void CancelarButton_OnClick(object sender, RoutedEventArgs e) + { + DialogHost.CloseDialogCommand.Execute(null, this.CancelarButton); + } + + private void Excluir_OnClick(object sender, RoutedEventArgs e) + { + Button button = (Button)sender; + if (button == null || button.DataContext == null) + { + return; + } + ArquivoDigital dataContext = (ArquivoDigital)button.DataContext; + this.ViewModel.Remover(dataContext); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/dialoganexar.xaml", UriKind.Relative)); + } + + private void SalvarButton_OnClick(object sender, RoutedEventArgs e) + { + DialogHost.CloseDialogCommand.Execute(this.ViewModel.Arquivos.ToList(), this.SalvarButton); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + if (connectionId == 2) + { + this.SalvarButton = (Button)target; + this.SalvarButton.Click += new RoutedEventHandler(this.SalvarButton_OnClick); + return; + } + if (connectionId != 3) + { + this._contentLoaded = true; + return; + } + this.CancelarButton = (Button)target; + this.CancelarButton.Click += new RoutedEventHandler(this.CancelarButton_OnClick); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + if (connectionId == 1) + { + ((Button)target).Click += new RoutedEventHandler(this.Excluir_OnClick); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/DialogCopia.cs b/Codemerx/Gestor.Application/Componentes/DialogCopia.cs new file mode 100644 index 0000000..f72933f --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/DialogCopia.cs @@ -0,0 +1,160 @@ +using Gestor.Application; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.MalaDireta; +using MaterialDesignThemes.Wpf; +using System; +using System.CodeDom.Compiler; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Componentes +{ + public class DialogCopia : UserControl, IComponentConnector, IStyleConnector + { + internal TextBox CopiaBox; + + internal MaterialDesignThemes.Wpf.Snackbar Snackbar; + + private bool _contentLoaded; + + public DialogCopiaViewModel ViewModel + { + get; + set; + } + + public DialogCopia(Copia copia) + { + this.ViewModel = new DialogCopiaViewModel(copia); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + } + + private void AdicionarCopia(object sender, RoutedEventArgs e) + { + this.ViewModel.AdicionarCopia(); + this.ToggleSnackBar(this.ViewModel.Erro, true); + } + + private void CloseSlackBar() + { + Thread.Sleep(3000); + System.Windows.Threading.Dispatcher dispatcher = App.ProgressRing.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => this.ToggleSnackBar("", false))); + } + + private void ExcluirComum_OnDeleteClick(object sender, RoutedEventArgs e) + { + Chip chip = (Chip)sender; + this.ViewModel.ExcluirCopia("CÓPIA COMUM", (string)chip.DataContext); + } + + private void ExcluirOculta_OnDeleteClick(object sender, RoutedEventArgs e) + { + Chip chip = (Chip)sender; + this.ViewModel.ExcluirCopia("CÓPIA OCULTA", (string)chip.DataContext); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/dialogcopia.xaml", UriKind.Relative)); + } + + private void SnackbarMessage_ActionClick(object sender, RoutedEventArgs e) + { + this.Snackbar.set_IsActive(false); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.CopiaBox = (TextBox)target; + return; + } + case 2: + { + ((Button)target).Click += new RoutedEventHandler(this.AdicionarCopia); + return; + } + case 3: + case 4: + { + this._contentLoaded = true; + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AdicionarCopia); + return; + } + case 6: + { + this.Snackbar = (MaterialDesignThemes.Wpf.Snackbar)target; + return; + } + case 7: + { + ((SnackbarMessage)target).add_ActionClick(new RoutedEventHandler(this.SnackbarMessage_ActionClick)); + return; + } + default: + { + this._contentLoaded = true; + return; + } + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + if (connectionId == 3) + { + ((Chip)target).add_DeleteClick(new RoutedEventHandler(this.ExcluirComum_OnDeleteClick)); + return; + } + if (connectionId != 4) + { + return; + } + ((Chip)target).add_DeleteClick(new RoutedEventHandler(this.ExcluirOculta_OnDeleteClick)); + } + + public void ToggleSnackBar(string message, bool active = true) + { + this.Snackbar.get_Message().Content = message; + this.Snackbar.set_IsActive(active); + if (!active) + { + return; + } + Task.Factory.StartNew(new Action(this.CloseSlackBar)); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/DialogCopiarCliente.cs b/Codemerx/Gestor.Application/Componentes/DialogCopiarCliente.cs new file mode 100644 index 0000000..bb3abfe --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/DialogCopiarCliente.cs @@ -0,0 +1,92 @@ +using Gestor.Application.ViewModels.Financeiro; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Markup; + +namespace Gestor.Application.Componentes +{ + public class DialogCopiarCliente : UserControl, IComponentConnector + { + internal CopiarClienteViewModel ViewModel; + + internal AutoCompleteBox PesquisaCliente; + + internal Loading LoadingAutoComplete; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public DialogCopiarCliente() + { + this.InitializeComponent(); + this.ViewModel = new CopiarClienteViewModel(); + base.DataContext = this.ViewModel; + } + + private void AutoCompleteBox_Populating(object sender, PopulatingEventArgs e) + { + if (e.get_Parameter().Trim().Length < 3) + { + return; + } + e.set_Cancel(true); + this.LoadingAutoComplete.Visibility = System.Windows.Visibility.Visible; + this.ViewModel.BuscarCliente(e.get_Parameter().Trim(), null, 2).ContinueWith((Task> searchResult) => { + this.LoadingAutoComplete.Visibility = System.Windows.Visibility.Collapsed; + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/dialogcopiarcliente.xaml", UriKind.Relative)); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + if (connectionId == 1) + { + this.PesquisaCliente = (AutoCompleteBox)target; + this.PesquisaCliente.add_Populating(new PopulatingEventHandler(this, DialogCopiarCliente.AutoCompleteBox_Populating)); + return; + } + if (connectionId != 2) + { + this._contentLoaded = true; + return; + } + this.LoadingAutoComplete = (Loading)target; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/DialogCopiarPermissao.cs b/Codemerx/Gestor.Application/Componentes/DialogCopiarPermissao.cs new file mode 100644 index 0000000..9ac6592 --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/DialogCopiarPermissao.cs @@ -0,0 +1,73 @@ +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Markup; + +namespace Gestor.Application.Componentes +{ + public class DialogCopiarPermissao : UserControl, IComponentConnector + { + public DialogCopiarPermissaoViewModel ViewModel; + + private bool _contentLoaded; + + public DialogCopiarPermissao(DialogCopiarPermissaoViewModel viewModel) + { + this.ViewModel = viewModel; + base.DataContext = this.ViewModel; + this.InitializeComponent(); + } + + private void AutoCompleteBox_Populating(object sender, PopulatingEventArgs e) + { + if (e.get_Parameter().Length < 3) + { + return; + } + e.set_Cancel(true); + this.ViewModel.BuscarUsuario(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/dialogcopiarpermissao.xaml", UriKind.Relative)); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + if (connectionId != 1) + { + this._contentLoaded = true; + return; + } + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, DialogCopiarPermissao.AutoCompleteBox_Populating)); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/DialogDetalheExtrato.cs b/Codemerx/Gestor.Application/Componentes/DialogDetalheExtrato.cs new file mode 100644 index 0000000..e6d2a01 --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/DialogDetalheExtrato.cs @@ -0,0 +1,119 @@ +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels.Comissao; +using Gestor.Application.Views.Generic; +using Gestor.Application.Views.Seguros; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Markup; + +namespace Gestor.Application.Componentes +{ + public class DialogDetalheExtrato : UserControl, IComponentConnector, IStyleConnector + { + internal DataGrid DetalhesGrid; + + private bool _contentLoaded; + + public ComissaoViewModel ViewModel + { + get; + set; + } + + public DialogDetalheExtrato(List detalhes) + { + this.InitializeComponent(); + this.DetalhesGrid.ItemsSource = detalhes; + } + + private async void AcessarApolice_OnClick(object sender, RoutedEventArgs e) + { + long? parcela; + Documento documento; + bool flag; + bool flag1; + DetalheExtrato dataContext = (DetalheExtrato)((Button)sender).DataContext; + flag = (dataContext != null ? !dataContext.get_Documento().HasValue : true); + if (flag) + { + flag1 = (dataContext != null ? !dataContext.get_Parcela().HasValue : true); + if (flag1) + { + return; + } + } + if (dataContext.get_Parcela().HasValue) + { + if (!dataContext.get_Documento().HasValue) + { + ParcelaServico parcelaServico = new ParcelaServico(); + parcela = dataContext.get_Parcela(); + documento = await parcelaServico.BuscarApolice(parcela.Value); + } + else + { + ApoliceServico apoliceServico = new ApoliceServico(); + parcela = dataContext.get_Documento(); + documento = await apoliceServico.BuscarApoliceAsync(parcela.Value, false, false); + } + Documento documento1 = documento; + if (documento1 != null) + { + double? nullable = null; + double? nullable1 = nullable; + nullable = null; + (new HosterWindow(new ApoliceView(documento1, true, false, 0, (long)0, false), string.Concat("CADASTRO DE APÓLICE - ", documento1.get_Controle().get_Cliente().get_Nome(), " - ", documento1.get_Apolice()), nullable1, nullable, false)).Show(); + } + else + { + return; + } + } + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/dialogdetalheextrato.xaml", UriKind.Relative)); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + if (connectionId != 1) + { + this._contentLoaded = true; + return; + } + this.DetalhesGrid = (DataGrid)target; + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + if (connectionId == 2) + { + ((Button)target).Click += new RoutedEventHandler(this.AcessarApolice_OnClick); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/DialogEditarParcelas.cs b/Codemerx/Gestor.Application/Componentes/DialogEditarParcelas.cs new file mode 100644 index 0000000..3a4a496 --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/DialogEditarParcelas.cs @@ -0,0 +1,170 @@ +using Gestor.Application.Actions; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Seguros; +using MaterialDesignThemes.Wpf; +using System; +using System.CodeDom.Compiler; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Input; +using System.Windows.Markup; + +namespace Gestor.Application.Componentes +{ + public class DialogEditarParcelas : UserControl, IComponentConnector + { + internal MaterialDesignThemes.Wpf.Snackbar Snackbar; + + internal DataGrid ParcelaGrid; + + internal DataGridTextColumn ParcelaColumn; + + internal Label LabelStatus; + + internal Button SalvarButton; + + internal Button FecharButton; + + private bool _contentLoaded; + + public DialogEditarParcelasViewModel ViewModel + { + get; + set; + } + + public DialogEditarParcelas(Documento documento) + { + this.ViewModel = new DialogEditarParcelasViewModel(documento); + base.DataContext = this.ViewModel; + Gestor.Application.Actions.Actions.AcionarSnackbar = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.AcionarSnackbar, new Action(this.AcionarSnackBar)); + Gestor.Application.Actions.Actions.AcionarSnackbar = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.AcionarSnackbar, new Action(this.AcionarSnackBar)); + this.InitializeComponent(); + } + + private void AcionarSnackBar(string message) + { + this.Snackbar.set_IsActive(true); + this.Snackbar.get_Message().Content = message; + } + + private void FecharButton_OnClick(object sender, RoutedEventArgs e) + { + DialogHost.CloseDialogCommand.Execute(null, this.SalvarButton); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/dialogeditarparcelas.xaml", UriKind.Relative)); + } + + private void ParcelaGrid_OnCellEditEnding(object sender, DataGridCellEditEndingEventArgs e) + { + DateTime dateTime; + if (!(e.EditingElement is TextBox)) + { + return; + } + Parcela dataContext = (Parcela)e.Row.DataContext; + TextBox editingElement = e.EditingElement as TextBox; + if (editingElement == null) + { + return; + } + if (e.Column.ClipboardContentBinding.StringFormat == "d") + { + editingElement.Text = ValidationHelper.FormatDate(editingElement.Text); + if (e.Column.Header.ToString() == "VENCIMENTO") + { + dataContext.set_Vencimento((string.IsNullOrWhiteSpace(editingElement.Text) || !DateTime.TryParse(editingElement.Text, out dateTime) ? DateTime.MinValue : DateTime.Parse(editingElement.Text))); + } + } + string str = e.Column.Header.ToString(); + if (str == "VALOR") + { + this.ViewModel.AlterandoValor(); + return; + } + if (str != "VENCIMENTO") + { + return; + } + this.ViewModel.AlterandoVencimento((Parcela)e.Row.DataContext); + } + + private async void SalvarButton_OnClick(object sender, RoutedEventArgs e) + { + if (await this.ViewModel.SalvarParcelas()) + { + DialogHost.CloseDialogCommand.Execute(null, this.SalvarButton); + } + } + + private void SnackbarMessage_ActionClick(object sender, RoutedEventArgs e) + { + this.Snackbar.set_IsActive(false); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.Snackbar = (MaterialDesignThemes.Wpf.Snackbar)target; + return; + } + case 2: + { + ((SnackbarMessage)target).add_ActionClick(new RoutedEventHandler(this.SnackbarMessage_ActionClick)); + return; + } + case 3: + { + this.ParcelaGrid = (DataGrid)target; + this.ParcelaGrid.CellEditEnding += new EventHandler(this.ParcelaGrid_OnCellEditEnding); + return; + } + case 4: + { + this.ParcelaColumn = (DataGridTextColumn)target; + return; + } + case 5: + { + this.LabelStatus = (Label)target; + return; + } + case 6: + { + this.SalvarButton = (Button)target; + this.SalvarButton.Click += new RoutedEventHandler(this.SalvarButton_OnClick); + return; + } + case 7: + { + this.FecharButton = (Button)target; + this.FecharButton.Click += new RoutedEventHandler(this.FecharButton_OnClick); + return; + } + } + this._contentLoaded = true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/DialogEnviarEmails.cs b/Codemerx/Gestor.Application/Componentes/DialogEnviarEmails.cs new file mode 100644 index 0000000..cc4a048 --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/DialogEnviarEmails.cs @@ -0,0 +1,62 @@ +using Gestor.Application.ViewModels.Generic; +using System; +using System.CodeDom.Compiler; +using System.ComponentModel; +using System.Diagnostics; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Markup; + +namespace Gestor.Application.Componentes +{ + public class DialogEnviarEmails : UserControl, IComponentConnector + { + public DialogEnviarEmailsViewModel ViewModel; + + internal System.Windows.Controls.ProgressBar ProgressBar; + + private bool _contentLoaded; + + public DialogEnviarEmails(DialogEnviarEmailsViewModel viewModel) + { + this.ViewModel = viewModel; + base.DataContext = this.ViewModel; + this.InitializeComponent(); + } + + private void Enviar_Click(object sender, RoutedEventArgs e) + { + this.ViewModel.Enviar(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/dialogenviaremails.xaml", UriKind.Relative)); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + if (connectionId == 1) + { + this.ProgressBar = (System.Windows.Controls.ProgressBar)target; + return; + } + if (connectionId != 2) + { + this._contentLoaded = true; + return; + } + ((MenuItem)target).Click += new RoutedEventHandler(this.Enviar_Click); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/DialogExportarPermissao.cs b/Codemerx/Gestor.Application/Componentes/DialogExportarPermissao.cs new file mode 100644 index 0000000..aa934dd --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/DialogExportarPermissao.cs @@ -0,0 +1,103 @@ +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Markup; + +namespace Gestor.Application.Componentes +{ + public class DialogExportarPermissao : UserControl, IComponentConnector, IStyleConnector + { + public DialogExportarPermissaoViewModel ViewModel; + + internal DataGrid UsuarioGrid; + + private bool _contentLoaded; + + public DialogExportarPermissao(DialogExportarPermissaoViewModel viewModel) + { + this.ViewModel = viewModel; + base.DataContext = this.ViewModel; + this.InitializeComponent(); + } + + private void AutoCompleteBox_OnTextChanged(object sender, RoutedEventArgs e) + { + if (!string.IsNullOrWhiteSpace(((AutoCompleteBox)sender).get_Text())) + { + return; + } + this.ViewModel.FiltrarUsuario(""); + } + + private void AutoCompleteBoxUsuario_Populating(object sender, PopulatingEventArgs e) + { + e.set_Cancel(true); + this.ViewModel.Filtrar(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void CheckBox_Checked(object sender, RoutedEventArgs e) + { + this.ViewModel.Selecionar(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/dialogexportarpermissao.xaml", UriKind.Relative)); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + if (connectionId != 1) + { + if (connectionId != 2) + { + this._contentLoaded = true; + return; + } + this.UsuarioGrid = (DataGrid)target; + return; + } + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, DialogExportarPermissao.AutoCompleteBoxUsuario_Populating)); + ((AutoCompleteBox)target).add_TextChanged(new RoutedEventHandler(this.AutoCompleteBox_OnTextChanged)); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + if (connectionId == 3) + { + ((CheckBox)target).Checked += new RoutedEventHandler(this.CheckBox_Checked); + ((CheckBox)target).Unchecked += new RoutedEventHandler(this.CheckBox_Checked); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/DialogExtratoComissao.cs b/Codemerx/Gestor.Application/Componentes/DialogExtratoComissao.cs new file mode 100644 index 0000000..f408d36 --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/DialogExtratoComissao.cs @@ -0,0 +1,207 @@ +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Model.Domain.Seguros; +using MaterialDesignThemes.Wpf; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Componentes +{ + public class DialogExtratoComissao : BaseUserControl, IComponentConnector, IStyleConnector + { + public ExtratoComissaoViewModel ViewModel; + + internal ComboBox SeguradoraBox; + + internal ComboBox SeguradoraSocialBox; + + internal DatePicker InicioBox; + + internal DatePicker FimBox; + + internal System.Windows.Controls.ProgressBar ProgressBar; + + internal DataGrid ExtratoGrid; + + internal Button ImportarButton; + + internal Button FecharButton; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public DialogExtratoComissao(List seguradoras) + { + this.InitializeComponent(); + this.ViewModel = new ExtratoComissaoViewModel(seguradoras); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + + private async void CarregarExtratos() + { + if (this.SeguradoraBox.SelectedItem != null && this.InicioBox.SelectedDate.HasValue && this.FimBox.SelectedDate.HasValue) + { + this.ViewModel.IsEnabled = false; + this.ProgressBar.Visibility = System.Windows.Visibility.Visible; + ExtratoComissaoViewModel viewModel = this.ViewModel; + Seguradora selectedItem = (Seguradora)this.SeguradoraBox.SelectedItem; + DateTime value = this.InicioBox.SelectedDate.Value; + DateTime? selectedDate = this.FimBox.SelectedDate; + await viewModel.CarregarExtratos(selectedItem, value, selectedDate.Value); + this.ProgressBar.Visibility = System.Windows.Visibility.Collapsed; + this.ViewModel.IsEnabled = true; + } + } + + private void CheckBox_Checked(object sender, RoutedEventArgs e) + { + this.ViewModel.SelecionarTudo(); + } + + private void ContentLoad() + { + this.InicioBox.SelectedDateChanged += new EventHandler(this.DataBox_SelectedDateChanged); + this.FimBox.SelectedDateChanged += new EventHandler(this.DataBox_SelectedDateChanged); + this.SeguradoraBox.SelectionChanged += new SelectionChangedEventHandler(this.SeguradoraBox_SelectionChanged); + this.SeguradoraSocialBox.SelectionChanged += new SelectionChangedEventHandler(this.SeguradoraSicialBox_SelectionChanged); + } + + private void DataBox_SelectedDateChanged(object sender, SelectionChangedEventArgs e) + { + this.CarregarExtratos(); + } + + private void Fechar_OnClick(object sender, RoutedEventArgs e) + { + DialogHost.CloseDialogCommand.Execute(null, this.FecharButton); + } + + private void Importar_OnClick(object sender, RoutedEventArgs e) + { + DialogHost.CloseDialogCommand.Execute(this.ViewModel.Selecionar(), this.ImportarButton); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/dialogextratocomissao.xaml", UriKind.Relative)); + } + + private void SeguradoraBox_SelectionChanged(object sender, SelectionChangedEventArgs e) + { + this.CarregarExtratos(); + } + + private void SeguradoraSicialBox_SelectionChanged(object sender, SelectionChangedEventArgs e) + { + this.SeguradoraBox.SelectedItem = this.SeguradoraSocialBox.SelectedItem; + this.CarregarExtratos(); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.SeguradoraBox = (ComboBox)target; + return; + } + case 2: + { + this.SeguradoraSocialBox = (ComboBox)target; + return; + } + case 3: + { + this.InicioBox = (DatePicker)target; + this.InicioBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + return; + } + case 4: + { + this.FimBox = (DatePicker)target; + this.FimBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + return; + } + case 5: + { + this.ProgressBar = (System.Windows.Controls.ProgressBar)target; + return; + } + case 6: + { + this.ExtratoGrid = (DataGrid)target; + return; + } + case 7: + { + this._contentLoaded = true; + return; + } + case 8: + { + this.ImportarButton = (Button)target; + this.ImportarButton.Click += new RoutedEventHandler(this.Importar_OnClick); + return; + } + case 9: + { + this.FecharButton = (Button)target; + this.FecharButton.Click += new RoutedEventHandler(this.Fechar_OnClick); + return; + } + default: + { + this._contentLoaded = true; + return; + } + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + if (connectionId == 7) + { + ((CheckBox)target).Checked += new RoutedEventHandler(this.CheckBox_Checked); + ((CheckBox)target).Unchecked += new RoutedEventHandler(this.CheckBox_Checked); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/DialogGrafico.cs b/Codemerx/Gestor.Application/Componentes/DialogGrafico.cs new file mode 100644 index 0000000..4b06c7a --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/DialogGrafico.cs @@ -0,0 +1,47 @@ +using System; +using System.CodeDom.Compiler; +using System.ComponentModel; +using System.Diagnostics; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Markup; + +namespace Gestor.Application.Componentes +{ + public class DialogGrafico : UserControl, IComponentConnector + { + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public DialogGrafico() + { + this.InitializeComponent(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/dialoggrafico.xaml", UriKind.Relative)); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + this._contentLoaded = true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/DialogHoster.cs b/Codemerx/Gestor.Application/Componentes/DialogHoster.cs new file mode 100644 index 0000000..1fbd014 --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/DialogHoster.cs @@ -0,0 +1,73 @@ +using System; +using System.CodeDom.Compiler; +using System.ComponentModel; +using System.Diagnostics; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Media; + +namespace Gestor.Application.Componentes +{ + public class DialogHoster : UserControl, IComponentConnector + { + internal TextBlock Head; + + internal Button CloseButton; + + internal ContentControl Content; + + private bool _contentLoaded; + + public DialogHoster(object view, string head) + { + this.InitializeComponent(); + this.Content.Content = view; + this.Head.Text = head; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/dialoghoster.xaml", UriKind.Relative)); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.Head = (TextBlock)target; + return; + } + case 2: + { + this.CloseButton = (Button)target; + return; + } + case 3: + { + this.Content = (ContentControl)target; + return; + } + } + this._contentLoaded = true; + } + + private void TopControls_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e) + { + ((Button)sender).Background = (((Button)sender).Name == "CloseButton" ? new SolidColorBrush(Colors.Red) : new SolidColorBrush(Colors.DimGray)); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/DialogInstalacoes.cs b/Codemerx/Gestor.Application/Componentes/DialogInstalacoes.cs new file mode 100644 index 0000000..48ecc7e --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/DialogInstalacoes.cs @@ -0,0 +1,125 @@ +using Gestor.Model.License; +using MaterialDesignThemes.Wpf; +using System; +using System.CodeDom.Compiler; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; + +namespace Gestor.Application.Componentes +{ + public class DialogInstalacoes : UserControl, IComponentConnector + { + internal DataGrid InstalacoesView; + + internal Button ValidarButton; + + internal Button FecharButton; + + internal MaterialDesignThemes.Wpf.Snackbar Snackbar; + + private bool _contentLoaded; + + public DialogInstalacoes(List instalacoes) + { + IEnumerable list; + this.InitializeComponent(); + DataGrid instalacoesView = this.InstalacoesView; + IEnumerable instalacaos = + from i in instalacoes + where !string.IsNullOrEmpty(i.get_Gerenciador()) + select i; + if (instalacaos != null) + { + list = instalacaos.ToList(); + } + else + { + list = null; + } + instalacoesView.ItemsSource = list; + this.InstalacoesView.SelectedIndex = -1; + } + + private void FecharButton_OnClick(object sender, RoutedEventArgs e) + { + DialogHost.CloseDialogCommand.Execute(null, this.FecharButton); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/dialoginstalacoes.xaml", UriKind.Relative)); + } + + private void SnackbarMessage_ActionClick(object sender, RoutedEventArgs e) + { + this.Snackbar.get_Message().Content = ""; + this.Snackbar.set_IsActive(false); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.InstalacoesView = (DataGrid)target; + return; + } + case 2: + { + this.ValidarButton = (Button)target; + this.ValidarButton.Click += new RoutedEventHandler(this.ValidarButton_OnClick); + return; + } + case 3: + { + this.FecharButton = (Button)target; + this.FecharButton.Click += new RoutedEventHandler(this.FecharButton_OnClick); + return; + } + case 4: + { + this.Snackbar = (MaterialDesignThemes.Wpf.Snackbar)target; + return; + } + case 5: + { + ((SnackbarMessage)target).add_ActionClick(new RoutedEventHandler(this.SnackbarMessage_ActionClick)); + return; + } + } + this._contentLoaded = true; + } + + private void ValidarButton_OnClick(object sender, RoutedEventArgs e) + { + object selectedItem = this.InstalacoesView.SelectedItem; + if (selectedItem != null) + { + DialogHost.CloseDialogCommand.Execute((Instalacao)selectedItem, this.ValidarButton); + return; + } + this.Snackbar.get_Message().Content = "SELECIONE A INSTALAÇÃO A SER SUBSTITUÍDA"; + this.Snackbar.set_IsActive(true); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/DialogLogAcesso.cs b/Codemerx/Gestor.Application/Componentes/DialogLogAcesso.cs new file mode 100644 index 0000000..0878937 --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/DialogLogAcesso.cs @@ -0,0 +1,71 @@ +using Gestor.Application.ViewModels.Drawer; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Validation; +using System; +using System.CodeDom.Compiler; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Markup; + +namespace Gestor.Application.Componentes +{ + public class DialogLogAcesso : UserControl, IComponentConnector + { + internal System.Windows.Controls.ProgressBar ProgressBar; + + internal TextBlock TitleText; + + private bool _contentLoaded; + + public LogViewModel ViewModel + { + get; + set; + } + + public DialogLogAcesso(TipoTela tela, Usuario usuario) + { + this.ViewModel = new LogViewModel(tela, usuario.get_Id(), null, 0); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + this.ViewModel.RegistrarAcao(string.Format("ACESSOU LOG DE ACESSO DO USUÁRIO {0}, ID \"{1}\"", usuario.get_Nome(), usuario.get_Id()), usuario.get_Id(), new TipoTela?(tela), string.Format("ID ENTIDADE: {0}\nTIPO: {1}", usuario.get_Id(), Funcoes.GetDescription(tela))); + this.TitleText.Text = string.Format("LOG DE ACESSO DO USUARIO: {0}, ID {1}", usuario.get_Nome(), usuario.get_Id()); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/dialoglogacesso.xaml", UriKind.Relative)); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + if (connectionId == 1) + { + this.ProgressBar = (System.Windows.Controls.ProgressBar)target; + return; + } + if (connectionId != 2) + { + this._contentLoaded = true; + return; + } + this.TitleText = (TextBlock)target; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/DialogMedalha.cs b/Codemerx/Gestor.Application/Componentes/DialogMedalha.cs new file mode 100644 index 0000000..a24570a --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/DialogMedalha.cs @@ -0,0 +1,49 @@ +using Gestor.Application.ViewModels.Generic; +using System; +using System.CodeDom.Compiler; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Markup; + +namespace Gestor.Application.Componentes +{ + public class DialogMedalha : UserControl, IComponentConnector + { + private bool _contentLoaded; + + private DialogMedalhaViewModel ViewModel + { + get; + } + + public DialogMedalha(int liquido, int comissao, int resultado, int media) + { + this.ViewModel = new DialogMedalhaViewModel(liquido, comissao, resultado, media); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/dialogmedalha.xaml", UriKind.Relative)); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + this._contentLoaded = true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/DialogObservacao.cs b/Codemerx/Gestor.Application/Componentes/DialogObservacao.cs new file mode 100644 index 0000000..acca62f --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/DialogObservacao.cs @@ -0,0 +1,85 @@ +using MaterialDesignThemes.Wpf; +using System; +using System.CodeDom.Compiler; +using System.ComponentModel; +using System.Diagnostics; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Markup; + +namespace Gestor.Application.Componentes +{ + public class DialogObservacao : UserControl, IComponentConnector + { + internal System.Windows.Controls.TextBox TextBox; + + internal Button SalvarButton; + + internal Button CancelarButton; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public DialogObservacao() + { + this.InitializeComponent(); + } + + private void CancelarButton_OnClick(object sender, RoutedEventArgs e) + { + DialogHost.CloseDialogCommand.Execute(null, this.CancelarButton); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/dialogobservacao.xaml", UriKind.Relative)); + } + + private void SalvarButton_OnClick(object sender, RoutedEventArgs e) + { + DialogHost.CloseDialogCommand.Execute(this.TextBox.Text, this.SalvarButton); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.TextBox = (System.Windows.Controls.TextBox)target; + return; + } + case 2: + { + this.SalvarButton = (Button)target; + this.SalvarButton.Click += new RoutedEventHandler(this.SalvarButton_OnClick); + return; + } + case 3: + { + this.CancelarButton = (Button)target; + this.CancelarButton.Click += new RoutedEventHandler(this.CancelarButton_OnClick); + return; + } + } + this._contentLoaded = true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/DialogPesquisaAvancada.cs b/Codemerx/Gestor.Application/Componentes/DialogPesquisaAvancada.cs new file mode 100644 index 0000000..e57893e --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/DialogPesquisaAvancada.cs @@ -0,0 +1,129 @@ +using Gestor.Application; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using MaterialDesignThemes.Wpf; +using System; +using System.CodeDom.Compiler; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Componentes +{ + public class DialogPesquisaAvancada : UserControl, IComponentConnector + { + internal DataGrid Grid; + + internal MaterialDesignThemes.Wpf.Snackbar Snackbar; + + private bool _contentLoaded; + + public DialogPesquisaAvancadaViewModel ViewModel + { + get; + set; + } + + public DialogPesquisaAvancada(DialogPesquisaAvancadaViewModel viewModel) + { + this.ViewModel = viewModel; + base.DataContext = this.ViewModel; + this.InitializeComponent(); + this.ViewModel.GetTipoTela(); + this.ViewModel.HabilitarBusca(); + } + + private void CloseSlackBar() + { + Thread.Sleep(3000); + System.Windows.Threading.Dispatcher dispatcher = App.ProgressRing.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => this.ToggleSnackBar("", false))); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/dialogpesquisaavancada.xaml", UriKind.Relative)); + } + + private async void Pesquisar_OnClick(object sender, RoutedEventArgs e) + { + if (this.ViewModel.Pesquisa != null) + { + await this.ViewModel.Pesquisar(); + if (this.ViewModel.Pesquisas.Count == 0) + { + this.ToggleSnackBar("NÃO HÁ DOCUMENTOS ENCONTRADOS.", true); + } + } + else + { + this.ToggleSnackBar(string.Concat("INFORME QUAL ", ValidationHelper.GetDescription(this.ViewModel.Tipo), " DESEJA PROCURAR"), true); + } + } + + private void SnackbarMessage_ActionClick(object sender, RoutedEventArgs e) + { + this.Snackbar.set_IsActive(false); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Pesquisar_OnClick); + return; + } + case 2: + { + this.Grid = (DataGrid)target; + return; + } + case 3: + { + this.Snackbar = (MaterialDesignThemes.Wpf.Snackbar)target; + return; + } + case 4: + { + ((SnackbarMessage)target).add_ActionClick(new RoutedEventHandler(this.SnackbarMessage_ActionClick)); + return; + } + } + this._contentLoaded = true; + } + + public void ToggleSnackBar(string message, bool active = true) + { + this.Snackbar.get_Message().Content = message; + this.Snackbar.set_IsActive(active); + if (!active) + { + return; + } + Task.Factory.StartNew(new Action(this.CloseSlackBar)); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/DialogPrint.cs b/Codemerx/Gestor.Application/Componentes/DialogPrint.cs new file mode 100644 index 0000000..a084b74 --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/DialogPrint.cs @@ -0,0 +1,176 @@ +using Gestor.Application.ViewModels.Relatorios; +using Gestor.Model.Common; +using Gestor.Model.Domain.Relatorios; +using MaterialDesignThemes.Wpf; +using System; +using System.CodeDom.Compiler; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Componentes +{ + public class DialogPrint : UserControl, IComponentConnector, IStyleConnector + { + internal System.Windows.Controls.ProgressBar ProgressBar; + + internal CheckBox Landscape; + + internal CheckBox Portrait; + + internal Button ValidarButton; + + internal Button FecharButton; + + private bool _contentLoaded; + + public DialogPrintViewModel ViewModel + { + get; + set; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public DialogPrint(Relatorio relatorio, Type tipo) + { + this.ViewModel = new DialogPrintViewModel(relatorio, tipo); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + + private void CancelarButton_OnClick(object sender, RoutedEventArgs e) + { + DialogHost.CloseDialogCommand.Execute(null, this.FecharButton); + } + + private async void ContentLoad() + { + this.ViewModel.Carregando = true; + await this.ViewModel.Carregar(); + this.Landscape.IsChecked = new bool?(true); + this.ViewModel.Carregando = false; + } + + private void ImprimirButton_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Configuracoes.set_Campos(( + from x in this.ViewModel.Configuracoes.get_Campos() + where x.get_Selecionado() + select x).ToList()); + DialogHost.CloseDialogCommand.Execute(this.ViewModel.Configuracoes, this.ValidarButton); + this.ViewModel.Configuracoes.set_OrientacaoImpressao(new bool?(this.ViewModel.OrientacaoImpressao)); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/dialogprint.xaml", UriKind.Relative)); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.ProgressBar = (System.Windows.Controls.ProgressBar)target; + return; + } + case 2: + { + this._contentLoaded = true; + return; + } + case 3: + { + this.Landscape = (CheckBox)target; + this.Landscape.Checked += new RoutedEventHandler(this.ToggleButtonLandscape_OnChecked); + return; + } + case 4: + { + this.Portrait = (CheckBox)target; + this.Portrait.Checked += new RoutedEventHandler(this.ToggleButtonPortrait_OnChecked); + return; + } + case 5: + { + this.ValidarButton = (Button)target; + this.ValidarButton.Click += new RoutedEventHandler(this.ImprimirButton_OnClick); + return; + } + case 6: + { + this.FecharButton = (Button)target; + this.FecharButton.Click += new RoutedEventHandler(this.CancelarButton_OnClick); + return; + } + default: + { + this._contentLoaded = true; + return; + } + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + if (connectionId == 2) + { + ((CheckBox)target).Checked += new RoutedEventHandler(this.ToggleButton_OnChecked); + ((CheckBox)target).Unchecked += new RoutedEventHandler(this.ToggleButton_OnChecked); + } + } + + private void ToggleButton_OnChecked(object sender, RoutedEventArgs e) + { + this.ViewModel.Selecionar(); + } + + private void ToggleButtonLandscape_OnChecked(object sender, RoutedEventArgs e) + { + this.ViewModel.OrientacaoImpressao = false; + this.ViewModel.OrientacaoImpressaoPortrait = false; + this.Portrait.IsChecked = new bool?(false); + } + + private void ToggleButtonPortrait_OnChecked(object sender, RoutedEventArgs e) + { + this.ViewModel.OrientacaoImpressao = true; + this.ViewModel.OrientacaoImpressaoLandscape = false; + this.Landscape.IsChecked = new bool?(false); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/DialogProtocolo.cs b/Codemerx/Gestor.Application/Componentes/DialogProtocolo.cs new file mode 100644 index 0000000..0ecaaac --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/DialogProtocolo.cs @@ -0,0 +1,51 @@ +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Markup; + +namespace Gestor.Application.Componentes +{ + public class DialogProtocolo : UserControl, IComponentConnector + { + private bool _contentLoaded; + + private ProtocoloViewModel ViewModel + { + get; + } + + public DialogProtocolo(List itens) + { + this.ViewModel = new ProtocoloViewModel(itens); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/dialogprotocolo.xaml", UriKind.Relative)); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + this._contentLoaded = true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/DialogReordenarItens.cs b/Codemerx/Gestor.Application/Componentes/DialogReordenarItens.cs new file mode 100644 index 0000000..e378a0f --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/DialogReordenarItens.cs @@ -0,0 +1,67 @@ +using Gestor.Application.ViewModels.Generic; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Markup; + +namespace Gestor.Application.Componentes +{ + public class DialogReordenarItens : UserControl, IComponentConnector + { + internal ProgressBar ProgressRing; + + private bool _contentLoaded; + + private ReordenarItensViewModel ViewModel + { + get; + } + + public DialogReordenarItens(List ids) + { + this.ViewModel = new ReordenarItensViewModel(ids); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/dialogreordenaritens.xaml", UriKind.Relative)); + } + + private void ReordenarAutomaticamente_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.ReordenarAutomaticamente(); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + if (connectionId == 1) + { + ((Button)target).Click += new RoutedEventHandler(this.ReordenarAutomaticamente_OnClick); + return; + } + if (connectionId != 2) + { + this._contentLoaded = true; + return; + } + this.ProgressRing = (ProgressBar)target; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/DialogSelecionarItens.cs b/Codemerx/Gestor.Application/Componentes/DialogSelecionarItens.cs new file mode 100644 index 0000000..6955962 --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/DialogSelecionarItens.cs @@ -0,0 +1,49 @@ +using Gestor.Application.ViewModels.Generic; +using System; +using System.CodeDom.Compiler; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Markup; + +namespace Gestor.Application.Componentes +{ + public class DialogSelecionarItens : UserControl, IComponentConnector + { + private bool _contentLoaded; + + private SelecionarItensViewModel ViewModel + { + get; + } + + public DialogSelecionarItens(long id) + { + this.ViewModel = new SelecionarItensViewModel(id); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/dialogselecionaritens.xaml", UriKind.Relative)); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + this._contentLoaded = true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/DialogSenhaAdm.cs b/Codemerx/Gestor.Application/Componentes/DialogSenhaAdm.cs new file mode 100644 index 0000000..897c5ea --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/DialogSenhaAdm.cs @@ -0,0 +1,125 @@ +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Common.Helpers; +using MaterialDesignThemes.Wpf; +using System; +using System.CodeDom.Compiler; +using System.ComponentModel; +using System.Diagnostics; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Markup; + +namespace Gestor.Application.Componentes +{ + public class DialogSenhaAdm : UserControl, IComponentConnector + { + internal TextBlock MensagemBlock; + + internal CustomPasswordBox SenhaBox; + + internal TextBlock MensagemErro; + + internal Button ValidarButton; + + internal Button FecharButton; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public DialogSenhaAdm(string mensagem) + { + this.InitializeComponent(); + this.MensagemBlock.Text = mensagem; + } + + private void FecharButton_OnClick(object sender, RoutedEventArgs e) + { + DialogHost.CloseDialogCommand.Execute(null, this.FecharButton); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/dialogsenhaadm.xaml", UriKind.Relative)); + } + + private void PasswordBox_LostFocus(object sender, RoutedEventArgs e) + { + } + + private void PasswordBox_OnKeyDown(object sender, KeyEventArgs e) + { + if (e.Key != Key.Return) + { + return; + } + DialogHost.CloseDialogCommand.Execute(this.Validar(), this.ValidarButton); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.MensagemBlock = (TextBlock)target; + return; + } + case 2: + { + this.SenhaBox = (CustomPasswordBox)target; + return; + } + case 3: + { + this.MensagemErro = (TextBlock)target; + return; + } + case 4: + { + this.ValidarButton = (Button)target; + this.ValidarButton.Click += new RoutedEventHandler(this.ValidarButton_OnClick); + return; + } + case 5: + { + this.FecharButton = (Button)target; + this.FecharButton.Click += new RoutedEventHandler(this.FecharButton_OnClick); + return; + } + } + this._contentLoaded = true; + } + + private bool Validar() + { + return this.SenhaBox.Text == EncryptionHelper.Decrypt((new EmpresaServico()).BuscarSenhaAdm()); + } + + private void ValidarButton_OnClick(object sender, RoutedEventArgs e) + { + if (!this.Validar()) + { + this.MensagemErro.Visibility = System.Windows.Visibility.Visible; + return; + } + DialogHost.CloseDialogCommand.Execute(this.Validar(), this.ValidarButton); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/DialogTarefa.cs b/Codemerx/Gestor.Application/Componentes/DialogTarefa.cs new file mode 100644 index 0000000..a9dc309 --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/DialogTarefa.cs @@ -0,0 +1,391 @@ +using Gestor.Application; +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Application.Views.Seguros; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using MaterialDesignThemes.Wpf; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; +using Xceed.Wpf.AvalonDock.Controls; + +namespace Gestor.Application.Componentes +{ + public class DialogTarefa : UserControl, IComponentConnector, IStyleConnector + { + internal Button ClienteButton; + + internal Button ApoliceButton; + + internal Button SinistroButton; + + internal TextBox TituloBox; + + internal DatePicker AgendamentoBox; + + internal RadioButton AnotacoesButton; + + internal TextBox AnotacoesBox; + + internal ComboBox ResponsavelBox; + + internal DatePicker ConclusaoBox; + + internal MenuItem SalvarButton; + + internal MaterialDesignThemes.Wpf.Snackbar Snackbar; + + private bool _contentLoaded; + + private DialogTarefaViewModel ViewModel + { + get; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public DialogTarefa(Tarefa tarefa, List telefones, bool nota = false, bool agendamento = false) + { + this.ViewModel = new DialogTarefaViewModel(tarefa, telefones, nota, agendamento); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + + private async void AcessarApolice_OnClick(object sender, RoutedEventArgs e) + { + Documento documento; + documento = (this.ViewModel.Tarefa.get_Entidade() != 3 ? await this.ViewModel.CarregaApolice(this.ViewModel.Tarefa.get_IdEntidade()) : await this.ViewModel.CarregaApoliceParcela(this.ViewModel.Tarefa.get_IdEntidade())); + double? nullable = null; + double? nullable1 = nullable; + nullable = null; + (new HosterWindow(new ApoliceView(documento, true, false, 0, (long)0, false), string.Concat("CADASTRO DE APÓLICES - ", this.ViewModel.Tarefa.get_Cliente()), nullable1, nullable, false)).Show(); + } + + private async void AcessarCliente_OnClick(object sender, RoutedEventArgs e) + { + double? nullable = null; + double? nullable1 = nullable; + nullable = null; + (new HosterWindow(new ClienteView(await this.ViewModel.CarregaCliente(this.ViewModel.Tarefa.get_IdCliente()), true, null), string.Concat("CADASTRO DE CLIENTE - ", this.ViewModel.Tarefa.get_Cliente()), nullable1, nullable, false)).Show(); + } + + private async void AcessarSinistro_OnClick(object sender, RoutedEventArgs e) + { + Sinistro sinistro = await this.ViewModel.CarregaSinistroApolice(this.ViewModel.Tarefa.get_IdEntidade()); + double? nullable = null; + double? nullable1 = nullable; + nullable = null; + (new HosterWindow(new SinistroView(sinistro.get_ControleSinistro().get_Item(), false), string.Concat("CADASTRO DE SINISTRO - ", sinistro.get_ControleSinistro().get_Item().get_Descricao()), nullable1, nullable, false)).Show(); + } + + private void AdicionarResponsavel_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AdcionarResponsavel(); + } + + private void Anotacoes_OnChecked(object sender, RoutedEventArgs e) + { + this.ViewModel.IsAnotacoes = true; + } + + private void AnotacoesInternas_OnChecked(object sender, RoutedEventArgs e) + { + this.ViewModel.IsAnotacoes = false; + } + + private void CloseSlackBar() + { + Thread.Sleep(3000); + System.Windows.Threading.Dispatcher dispatcher = App.ProgressRing.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => this.ToggleSnackBar("", false))); + } + + private void ContentLoad() + { + this.AgendamentoBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.AgendamentoBox.PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + this.ViewModel.PermissaoWhatsapp = this.ViewModel.Restricao(32); + switch (this.ViewModel.Tarefa.get_Entidade()) + { + case 0: + { + this.ClienteButton.Visibility = System.Windows.Visibility.Visible; + this.ApoliceButton.Visibility = System.Windows.Visibility.Visible; + break; + } + case 2: + { + this.ClienteButton.Visibility = System.Windows.Visibility.Visible; + break; + } + case 3: + { + this.ClienteButton.Visibility = System.Windows.Visibility.Visible; + this.ApoliceButton.Visibility = System.Windows.Visibility.Visible; + break; + } + case 4: + { + this.ClienteButton.Visibility = System.Windows.Visibility.Visible; + this.SinistroButton.Visibility = System.Windows.Visibility.Visible; + break; + } + default: + { + this.ClienteButton.Visibility = System.Windows.Visibility.Collapsed; + this.ApoliceButton.Visibility = System.Windows.Visibility.Collapsed; + break; + } + } + this.AnotacoesButton.IsChecked = new bool?(this.ViewModel.IsAnotacoes); + this.AnotacoesButton.Checked += new RoutedEventHandler(this.Anotacoes_OnChecked); + } + + private void CopyTelefoneToClipBoard_Click(object sender, RoutedEventArgs e) + { + TelefoneBase dataContext = (TelefoneBase)((Button)sender).DataContext; + string.Concat(dataContext.get_Prefixo(), dataContext.get_Numero()).CopyToClipboard(); + this.ToggleSnackBar("NÚMERO COPIADO COM SUCESSO", true); + } + + private void DataAtual_OnDoubleClick(object sender, RoutedEventArgs e) + { + ((DatePicker)sender).SelectedDate = new DateTime?(Funcoes.GetNetworkTime().Date); + } + + private void DatePicker_OnLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) + { + DatePicker datePicker = (DatePicker)sender; + datePicker.Text = ValidationHelper.FormatDate(datePicker.Text); + } + + private void DatePicker_PreviewKeyDown(object sender, KeyEventArgs e) + { + if (e.Key != Key.Return) + { + return; + } + DatePicker str = (DatePicker)sender; + DateTime date = Funcoes.GetNetworkTime().Date; + str.Text = date.ToString("dd/MM/yyyy"); + } + + private void ExcluirResponsavel_OnClick(object sender, RoutedEventArgs e) + { + Chip chip = sender as Chip; + if (chip == null) + { + return; + } + ListBox listBox = Extentions.FindVisualAncestor(chip); + Usuario item = (Usuario)listBox.Items[listBox.Items.IndexOf(chip.DataContext)]; + if (item == null) + { + return; + } + this.ViewModel.RemoverResponsavel(item); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/dialogtarefa.xaml", UriKind.Relative)); + } + + private void MenuItem_OnClick(object sender, RoutedEventArgs e) + { + if (this.ViewModel.Tarefa.get_UsuariosVinculados() == null) + { + this.ViewModel.Tarefa.set_UsuariosVinculados(new List()); + } + DialogHost.CloseDialogCommand.Execute(this.ViewModel.Tarefa, this.SalvarButton); + } + + private void SnackbarMessage_ActionClick(object sender, RoutedEventArgs e) + { + this.Snackbar.set_IsActive(false); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.ClienteButton = (Button)target; + this.ClienteButton.Click += new RoutedEventHandler(this.AcessarCliente_OnClick); + return; + } + case 2: + { + this.ApoliceButton = (Button)target; + this.ApoliceButton.Click += new RoutedEventHandler(this.AcessarApolice_OnClick); + return; + } + case 3: + { + this.SinistroButton = (Button)target; + this.SinistroButton.Click += new RoutedEventHandler(this.AcessarSinistro_OnClick); + return; + } + case 4: + case 5: + case 12: + { + this._contentLoaded = true; + return; + } + case 6: + { + this.TituloBox = (TextBox)target; + return; + } + case 7: + { + this.AgendamentoBox = (DatePicker)target; + this.AgendamentoBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.AgendamentoBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 8: + { + this.AnotacoesButton = (RadioButton)target; + return; + } + case 9: + { + this.AnotacoesBox = (TextBox)target; + return; + } + case 10: + { + this.ResponsavelBox = (ComboBox)target; + return; + } + case 11: + { + ((Button)target).Click += new RoutedEventHandler(this.AdicionarResponsavel_OnClick); + return; + } + case 13: + { + this.ConclusaoBox = (DatePicker)target; + this.ConclusaoBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.ConclusaoBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 14: + { + this.SalvarButton = (MenuItem)target; + this.SalvarButton.Click += new RoutedEventHandler(this.MenuItem_OnClick); + return; + } + case 15: + { + this.Snackbar = (MaterialDesignThemes.Wpf.Snackbar)target; + return; + } + case 16: + { + ((SnackbarMessage)target).add_ActionClick(new RoutedEventHandler(this.SnackbarMessage_ActionClick)); + return; + } + default: + { + this._contentLoaded = true; + return; + } + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + if (connectionId == 4) + { + ((Button)target).Click += new RoutedEventHandler(this.CopyTelefoneToClipBoard_Click); + return; + } + if (connectionId == 5) + { + ((Button)target).Click += new RoutedEventHandler(this.WhatsAppMessage_Click); + return; + } + if (connectionId != 12) + { + return; + } + ((Chip)target).add_DeleteClick(new RoutedEventHandler(this.ExcluirResponsavel_OnClick)); + } + + private void TimePicker_OnLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) + { + TimePicker timePicker = (TimePicker)sender; + timePicker.TextBox.Text = ValidationHelper.FormatTime(timePicker.TextBox.Text); + } + + public void ToggleSnackBar(string message, bool active = true) + { + this.Snackbar.get_Message().Content = message; + this.Snackbar.set_IsActive(active); + if (!active) + { + return; + } + Task.Factory.StartNew(new Action(this.CloseSlackBar)); + } + + private async void WhatsAppMessage_Click(object sender, RoutedEventArgs e) + { + string str; + TelefoneBase dataContext = (TelefoneBase)((Button)sender).DataContext; + str = (!dataContext.get_Tipo().HasValue || dataContext.get_Tipo().GetValueOrDefault() != 8 ? string.Concat("55", dataContext.get_Prefixo(), dataContext.get_Numero().Clear()) : string.Concat(dataContext.get_Prefixo(), dataContext.get_Numero()).Clear()); + if (!str.EnviarWhatsapp(null)) + { + await this.ViewModel.ShowMessage("HOUVE UM PROBLEMA AO ABRIR LINK DO WHATSAPP, O LINK FOI COPIADO EM SUA MAQUINA, BASTA ABRIR O NAVEGADOR DE INTERNET E COLAR NA BARRA DE ENDEREÇOS", "OK", "", false); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/DialogTransferencia.cs b/Codemerx/Gestor.Application/Componentes/DialogTransferencia.cs new file mode 100644 index 0000000..30f31c5 --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/DialogTransferencia.cs @@ -0,0 +1,110 @@ +using Assinador.Infrastructure.Helpers; +using CurrencyTextBoxControl; +using Gestor.Application.ViewModels.Financeiro; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Financeiro; +using System; +using System.CodeDom.Compiler; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Markup; + +namespace Gestor.Application.Componentes +{ + public class DialogTransferencia : UserControl, IComponentConnector + { + internal ComboBox ContaOrigemBox; + + internal CurrencyTextBox ValorBox; + + internal DatePicker VencimentoBox; + + internal ComboBox ContaDestinoBox; + + private bool _contentLoaded; + + private TranferenciaViewModel ViewModel + { + get; + } + + public DialogTransferencia(Transferencia transferencia) + { + this.ViewModel = new TranferenciaViewModel(transferencia); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + } + + private void DataAtual_OnDoubleClick(object sender, RoutedEventArgs e) + { + ((DatePicker)sender).SelectedDate = new DateTime?(Functions.GetNetworkTime().Date); + } + + public void DatePicker_OnLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) + { + DatePicker datePicker = (DatePicker)sender; + datePicker.Text = ValidationHelper.FormatDate(datePicker.Text); + } + + public void DatePicker_PreviewKeyDown(object sender, KeyEventArgs e) + { + if (e.Key != Key.Return) + { + return; + } + DatePicker str = (DatePicker)sender; + DateTime date = Functions.GetNetworkTime().Date; + str.Text = date.ToString("dd/MM/yyyy"); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/dialogtransferencia.xaml", UriKind.Relative)); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.ContaOrigemBox = (ComboBox)target; + return; + } + case 2: + { + this.ValorBox = (CurrencyTextBox)target; + return; + } + case 3: + { + this.VencimentoBox = (DatePicker)target; + this.VencimentoBox.PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + this.VencimentoBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.VencimentoBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 4: + { + this.ContaDestinoBox = (ComboBox)target; + return; + } + } + this._contentLoaded = true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/DialogTrilha.cs b/Codemerx/Gestor.Application/Componentes/DialogTrilha.cs new file mode 100644 index 0000000..e4f3011 --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/DialogTrilha.cs @@ -0,0 +1,134 @@ +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.Ferramentas; +using System; +using System.CodeDom.Compiler; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Markup; +using System.Windows.Media; + +namespace Gestor.Application.Componentes +{ + public class DialogTrilha : UserControl, IComponentConnector, IStyleConnector + { + private bool _contentLoaded; + + public DialogTrilhaViewModel ViewModel + { + get; + set; + } + + public DialogTrilha(DialogTrilhaViewModel viewModel) + { + this.ViewModel = viewModel; + base.DataContext = this.ViewModel; + this.InitializeComponent(); + } + + private void AdicionarFase_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AdicionarFase(); + } + + private void ExcluirFase_OnClick(object sender, RoutedEventArgs e) + { + Fase dataContext = ((Button)sender).DataContext as Fase; + if (dataContext == null) + { + return; + } + this.ViewModel.ExcluirFase(dataContext); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/dialogtrilha.xaml", UriKind.Relative)); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + if (connectionId != 1) + { + this._contentLoaded = true; + return; + } + ((MenuItem)target).Click += new RoutedEventHandler(this.AdicionarFase_OnClick); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 2: + { + ((TextBox)target).GotFocus += new RoutedEventHandler(this.UIElement_OnGotFocus); + ((TextBox)target).LostFocus += new RoutedEventHandler(this.UIElement_OnLostFocus); + return; + } + case 3: + { + ((TextBox)target).GotFocus += new RoutedEventHandler(this.UIElement_OnGotFocus); + ((TextBox)target).LostFocus += new RoutedEventHandler(this.UIElement_OnLostFocus); + return; + } + case 4: + { + ((Button)target).Click += new RoutedEventHandler(this.ExcluirFase_OnClick); + return; + } + default: + { + return; + } + } + } + + private void UIElement_OnGotFocus(object sender, RoutedEventArgs e) + { + DependencyObject parent = VisualTreeHelper.GetParent((UIElement)sender); + while (!(parent is ListBoxItem)) + { + if (parent == null) + { + continue; + } + parent = VisualTreeHelper.GetParent(parent); + } + ListBoxItem listBoxItem = (ListBoxItem)parent; + if (!listBoxItem.IsSelected) + { + listBoxItem.IsSelected = true; + } + } + + private void UIElement_OnLostFocus(object sender, RoutedEventArgs e) + { + ListBox listBox = ViewHelper.FindAncestor((TextBox)sender).FirstOrDefault(); + if (listBox == null) + { + return; + } + this.ViewModel.UpdateFase(listBox.SelectedIndex); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/DialogVinculo.cs b/Codemerx/Gestor.Application/Componentes/DialogVinculo.cs new file mode 100644 index 0000000..b64f05e --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/DialogVinculo.cs @@ -0,0 +1,89 @@ +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Markup; + +namespace Gestor.Application.Componentes +{ + public class DialogVinculo : UserControl, IComponentConnector + { + internal TextBlock TitleBox; + + internal ComboBox TipoVendedorBox; + + internal ComboBox VendedorBox; + + internal ComboBox TipoVendedorVinculoBox; + + internal ComboBox RepasseVinculoBox; + + private bool _contentLoaded; + + private DialogVinculoViewModel ViewModel + { + get; + } + + public DialogVinculo(VinculoRepasse vinculo, List repasses, Repasse repasse) + { + this.ViewModel = new DialogVinculoViewModel(vinculo, repasses, repasse); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/dialogvinculo.xaml", UriKind.Relative)); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.TitleBox = (TextBlock)target; + return; + } + case 2: + { + this.TipoVendedorBox = (ComboBox)target; + return; + } + case 3: + { + this.VendedorBox = (ComboBox)target; + return; + } + case 4: + { + this.TipoVendedorVinculoBox = (ComboBox)target; + return; + } + case 5: + { + this.RepasseVinculoBox = (ComboBox)target; + return; + } + } + this._contentLoaded = true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/ErrorDialog.cs b/Codemerx/Gestor.Application/Componentes/ErrorDialog.cs new file mode 100644 index 0000000..90e3f63 --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/ErrorDialog.cs @@ -0,0 +1,40 @@ +using Gestor.Application.Views.Generic; +using System; +using System.CodeDom.Compiler; +using System.ComponentModel; +using System.Diagnostics; +using System.Windows; +using System.Windows.Markup; + +namespace Gestor.Application.Componentes +{ + public class ErrorDialog : BaseUserControl, IComponentConnector + { + private bool _contentLoaded; + + public ErrorDialog() + { + this.InitializeComponent(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/errordialog.xaml", UriKind.Relative)); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + this._contentLoaded = true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/GridRelatorio.cs b/Codemerx/Gestor.Application/Componentes/GridRelatorio.cs new file mode 100644 index 0000000..7673cf8 --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/GridRelatorio.cs @@ -0,0 +1,695 @@ +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Relatorios; +using Gestor.Application.Views.Generic; +using Gestor.Application.Views.Seguros; +using Gestor.Application.Views.Seguros.Itens; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios.ApolicePendente; +using Gestor.Model.Domain.Relatorios.Log; +using Gestor.Model.Domain.Relatorios.LogsEnvio; +using Gestor.Model.Domain.Relatorios.Sinistro; +using Gestor.Model.Domain.Relatorios.Tarefa; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Markup; + +namespace Gestor.Application.Componentes +{ + public class GridRelatorio : UserControl, IComponentConnector, IStyleConnector + { + internal Grid LayoutRoot; + + internal System.Windows.Controls.DataGrid DataGrid; + + internal DataGridTemplateColumn InfoButton; + + internal DataGridTemplateColumn ArquivoButton; + + internal DataGridTemplateColumn VinculoButton; + + internal DataGridTemplateColumn CalculoButton; + + internal DataGridTemplateColumn AssinaturaButton; + + internal Expander Totalizacao; + + internal ItemsControl SinteticoGrid; + + private bool _contentLoaded; + + private int _index { get; set; } = -1; + + private ListSortDirection _sortDirection + { + get; + set; + } + + private RelatorioViewModel ViewModel + { + get; + } + + public GridRelatorio(RelatorioViewModel viewModel) + { + this.ViewModel = viewModel; + base.DataContext = this.ViewModel; + this.ViewModel.Totalizacao = true; + this.InitializeComponent(); + this.LayoutRoot.DataContext = this; + this.TipoRelatorio(); + } + + private async void ArquivoDigital_OnClick(object sender, RoutedEventArgs e) + { + Button button = (Button)sender; + object dataContext = button.DataContext; + FiltroArquivoDigital filtroArquivoDigital = null; + string tipo = ValidationHelper.GetTipo(this.ViewModel.Relatorio); + if (tipo == "CLIENTE") + { + if (!(new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 1).get_Consultar()) + { + await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", ValidationHelper.GetDescription((TipoArquivoDigital)1), "."), "OK", "", false); + return; + } + else if (this.ViewModel.Relatorio != 17) + { + Cliente valueFromType = dataContext.GetValueFromType(); + if (valueFromType != null) + { + FiltroArquivoDigital filtroArquivoDigital1 = new FiltroArquivoDigital(); + filtroArquivoDigital1.set_Id(valueFromType.get_Id()); + filtroArquivoDigital1.set_Tipo(1); + filtroArquivoDigital1.set_Parente(valueFromType); + filtroArquivoDigital = filtroArquivoDigital1; + } + else + { + return; + } + } + else + { + Item item = dataContext.GetValueFromType(); + Documento documento = button.DataContext.GetValueFromType(); + if (item != null) + { + documento = await (new ApoliceServico()).BuscarApoliceAsync(documento.get_Id(), false, false); + item.set_Documento(documento); + FiltroArquivoDigital filtroArquivoDigital2 = new FiltroArquivoDigital(); + filtroArquivoDigital2.set_Id(item.get_Id()); + filtroArquivoDigital2.set_Tipo(4); + filtroArquivoDigital2.set_Parente(item); + filtroArquivoDigital = filtroArquivoDigital2; + item = null; + } + else + { + return; + } + } + } + else if (tipo == "FECHAMENTO" || tipo == "DOCUMENTO") + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 2).get_Consultar()) + { + Documento valueFromType1 = dataContext.GetValueFromType(); + if (valueFromType1 != null) + { + FiltroArquivoDigital filtroArquivoDigital3 = new FiltroArquivoDigital(); + filtroArquivoDigital3.set_Id(valueFromType1.get_Id()); + filtroArquivoDigital3.set_Tipo(2); + filtroArquivoDigital3.set_Parente(valueFromType1); + filtroArquivoDigital = filtroArquivoDigital3; + } + else + { + return; + } + } + else + { + await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", ValidationHelper.GetDescription((TipoArquivoDigital)2), "."), "OK", "", false); + return; + } + } + else if (tipo == "PARCELA") + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 3).get_Consultar()) + { + Parcela parcela = dataContext.GetValueFromType(); + if (parcela != null) + { + FiltroArquivoDigital filtroArquivoDigital4 = new FiltroArquivoDigital(); + filtroArquivoDigital4.set_Id(parcela.get_Id()); + filtroArquivoDigital4.set_IdApolice(parcela.get_Documento().get_Id()); + filtroArquivoDigital4.set_Tipo(3); + filtroArquivoDigital4.set_Parente(parcela); + filtroArquivoDigital = filtroArquivoDigital4; + } + else + { + return; + } + } + else + { + await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", ValidationHelper.GetDescription((TipoArquivoDigital)3), "."), "OK", "", false); + return; + } + } + else if (tipo != "SINISTRO") + { + if (tipo == "EXTRATO") + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 7).get_Consultar()) + { + Extrato extrato = dataContext.GetValueFromType(); + if (extrato != null) + { + FiltroArquivoDigital filtroArquivoDigital5 = new FiltroArquivoDigital(); + filtroArquivoDigital5.set_Id(extrato.get_Id()); + filtroArquivoDigital5.set_Tipo(7); + filtroArquivoDigital5.set_Parente(extrato); + filtroArquivoDigital = filtroArquivoDigital5; + } + else + { + return; + } + } + else + { + await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", ValidationHelper.GetDescription((TipoArquivoDigital)7), "."), "OK", "", false); + return; + } + } + } + else if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 5).get_Consultar()) + { + Gestor.Model.Domain.Seguros.Sinistro sinistro = dataContext.GetValueFromType(); + if (sinistro != null) + { + FiltroArquivoDigital filtroArquivoDigital6 = new FiltroArquivoDigital(); + filtroArquivoDigital6.set_Id(sinistro.get_Id()); + filtroArquivoDigital6.set_IdApolice(sinistro.get_ControleSinistro().get_Item().get_Documento().get_Id()); + filtroArquivoDigital6.set_Tipo(5); + filtroArquivoDigital6.set_Parente(sinistro); + filtroArquivoDigital = filtroArquivoDigital6; + } + else + { + return; + } + } + else + { + await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", ValidationHelper.GetDescription((TipoArquivoDigital)5), "."), "OK", "", false); + return; + } + if (filtroArquivoDigital != null) + { + (new BaseSegurosViewModel()).ShowDrawer(new ArquivoDigitalDrawer(filtroArquivoDigital), 0, false); + } + else + { + await this.ViewModel.ShowMessage("ESSE TIPO DE RELATÓRIO NÃO POSSUI ARQUIVO DIGITAL", "OK", "", false); + } + } + + private async void CheckBox_Checked(object sender, RoutedEventArgs e) + { + this.ViewModel.Carregando = true; + this.ViewModel.IsEnabled = false; + await this.ViewModel.Selecionar(); + this.ViewModel.IsEnabled = true; + this.ViewModel.Carregando = false; + } + + private void Grid_Sorting(object sender, DataGridSortingEventArgs e) + { + this._index = e.Column.DisplayIndex; + ListSortDirection? sortDirection = e.Column.SortDirection; + this._sortDirection = (!(sortDirection.GetValueOrDefault() == ListSortDirection.Ascending & sortDirection.HasValue) ? ListSortDirection.Ascending : ListSortDirection.Descending); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/gridrelatorio.xaml", UriKind.Relative)); + } + + private async void MaisInformacoes_OnClick(object sender, RoutedEventArgs e) + { + double? nullable; + Gestor.Model.Domain.Relatorios.Sinistro.Sinistro dataContext; + Button button = (Button)sender; + if (button.DataContext != null) + { + string tipo = ValidationHelper.GetTipo(this.ViewModel.Relatorio); + if (this.ViewModel.Relatorio == 17) + { + Item valueFromType = button.DataContext.GetValueFromType(); + Documento documento = button.DataContext.GetValueFromType(); + if (valueFromType != null) + { + valueFromType.set_Documento(documento); + nullable = null; + double? nullable1 = nullable; + nullable = null; + (new HosterWindow(new AutoView(null, true, false, null, valueFromType, documento.get_Controle().get_Ramo(), false), string.Concat("CADASTRO DE ITENS DO CLIENTE - ", documento.get_Controle().get_Cliente().get_Nome()), nullable1, nullable, false)).ShowDialog(); + } + } + else if (this.ViewModel.Relatorio != 4 || button.DataContext.GetValueFromType() == null) + { + if (tipo != null) + { + switch (tipo.Length) + { + case 4: + { + if (tipo != "LOGS") + { + goto Label1; + } + else if (!(button.DataContext is LogAcaoRelatorio)) + { + LogsEnvio logsEnvio = (LogsEnvio)button.DataContext; + this.ViewModel.ShowDrawer(new LogEmailDrawer(17, logsEnvio.get_Id(), true), 0, false); + goto Label1; + } + else + { + this.ViewModel.ShowDrawer(new LogUtilizacaoDrawer(((LogAcaoRelatorio)button.DataContext).get_RegistroEntity(), this.ViewModel.Relatorio), 0, false); + return; + } + } + case 6: + { + if (tipo == "TAREFA") + { + Gestor.Model.Domain.Relatorios.Tarefa.Tarefa tarefa = (Gestor.Model.Domain.Relatorios.Tarefa.Tarefa)button.DataContext; + Gestor.Model.Domain.Ferramentas.Tarefa tarefa1 = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa1.set_Id(tarefa.get_Id()); + tarefa1.set_IdCliente(tarefa.get_IdCliente()); + tarefa1.set_Cliente(tarefa.get_Cliente()); + tarefa1.set_IdEntidade(tarefa.get_IdEntidade()); + tarefa1.set_Entidade(tarefa.get_Entidade()); + tarefa1.set_Conclusao(tarefa.get_Conclusao()); + Gestor.Model.Domain.Ferramentas.Tarefa tarefa2 = tarefa1; + this.ViewModel.ShowDrawer(new TarefaDrawer(tarefa2, false), 0, false); + goto Label1; + } + else + { + goto Label1; + } + } + case 7: + { + char chr = tipo[0]; + if (chr == 'C') + { + if (tipo == "CLIENTE") + { + Cliente cliente = button.DataContext.GetValueFromType(); + if (cliente != null) + { + cliente = await (new ClienteServico()).BuscarClienteAsync(cliente.get_Id()); + nullable = null; + double? nullable2 = nullable; + nullable = null; + (new HosterWindow(new ClienteView(cliente, true, null), string.Concat("CADASTRO DE CLIENTES - ", cliente.get_Nome()), nullable2, nullable, false)).ShowDialog(); + goto Label1; + } + else + { + return; + } + } + else + { + goto Label1; + } + } + else if (chr != 'P') + { + goto Label1; + } + else if (tipo == "PARCELA") + { + Documento valueFromType1 = button.DataContext.GetValueFromType(); + if (valueFromType1 != null) + { + Parcela parcela = button.DataContext.GetValueFromType(); + if (parcela != null) + { + nullable = null; + double? nullable3 = nullable; + nullable = null; + (new HosterWindow(new ApoliceView(valueFromType1, true, false, 1, parcela.get_Id(), false), string.Concat("CADASTRO DE APÓLICES - ", valueFromType1.get_Controle().get_Cliente().get_Nome()), nullable3, nullable, false)).Show(); + goto Label1; + } + else + { + return; + } + } + else + { + return; + } + } + else + { + goto Label1; + } + } + case 8: + { + if (tipo == "SINISTRO") + { + dataContext = (Gestor.Model.Domain.Relatorios.Sinistro.Sinistro)button.DataContext; + Gestor.Model.Domain.Seguros.Sinistro sinistro = button.DataContext.GetValueFromType(); + if (sinistro != null) + { + sinistro = await this.ViewModel.CarregaSinistroApolice(sinistro.get_Id()); + SinistroView sinistroView = new SinistroView(sinistro.get_ControleSinistro().get_Item(), false); + string[] nome = new string[] { "CADASTRO DE SINISTROS - ", dataContext.get_Nome(), " - ", dataContext.get_Apolice(), " ", dataContext.get_Endosso() }; + nullable = null; + double? nullable4 = nullable; + nullable = null; + (new HosterWindow(sinistroView, string.Concat(nome), nullable4, nullable, false)).Show(); + goto Label1; + } + else + { + return; + } + } + else + { + goto Label1; + } + } + case 9: + { + if (tipo == "DOCUMENTO") + { + break; + } + goto Label1; + } + case 10: + { + if (tipo == "FECHAMENTO") + { + break; + } + goto Label1; + } + default: + { + goto Label1; + } + } + Documento documento1 = button.DataContext.GetValueFromType(); + if (documento1 != null) + { + documento1 = await (new ApoliceServico()).BuscarApoliceAsync(documento1.get_Id(), false, false); + nullable = null; + double? nullable5 = nullable; + nullable = null; + (new HosterWindow(new ApoliceView(documento1, true, false, 0, (long)0, false), string.Concat("CADASTRO DE APÓLICES - ", documento1.get_Controle().get_Cliente().get_Nome()), nullable5, nullable, false)).Show(); + } + else + { + return; + } + } + Label1: + dataContext = null; + } + else if (button.DataContext.GetValueFromType().ToString() != "PROSPECÇÃO") + { + Prospeccao prospeccao = await this.ViewModel.ShowProspeccaoDialog(button.DataContext.GetValueFromType()); + if (prospeccao != null) + { + List> keyValuePairs = await this.ViewModel.SalvarProspeccao(prospeccao); + if (keyValuePairs != null && keyValuePairs.Count >= 1) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + } + } + } + } + + public void SortDataGrid() + { + DataGridColumn item = this.DataGrid.Columns[this._index]; + this.DataGrid.Items.SortDescriptions.Clear(); + this.DataGrid.Items.SortDescriptions.Add(new SortDescription(item.SortMemberPath, this._sortDirection)); + foreach (DataGridColumn column in this.DataGrid.Columns) + { + column.SortDirection = null; + } + item.SortDirection = new ListSortDirection?(this._sortDirection); + this.DataGrid.Items.Refresh(); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.LayoutRoot = (Grid)target; + return; + } + case 2: + { + this.DataGrid = (System.Windows.Controls.DataGrid)target; + this.DataGrid.Sorting += new DataGridSortingEventHandler(this.Grid_Sorting); + return; + } + case 3: + case 5: + case 7: + case 9: + { + this._contentLoaded = true; + return; + } + case 4: + { + this.InfoButton = (DataGridTemplateColumn)target; + return; + } + case 6: + { + this.ArquivoButton = (DataGridTemplateColumn)target; + return; + } + case 8: + { + this.VinculoButton = (DataGridTemplateColumn)target; + return; + } + case 10: + { + this.CalculoButton = (DataGridTemplateColumn)target; + return; + } + case 11: + { + this.AssinaturaButton = (DataGridTemplateColumn)target; + return; + } + case 12: + { + this.Totalizacao = (Expander)target; + this.Totalizacao.Collapsed += new RoutedEventHandler(this.Totalizacao_OnCollapsedExpanded); + this.Totalizacao.Expanded += new RoutedEventHandler(this.Totalizacao_OnCollapsedExpanded); + return; + } + case 13: + { + this.SinteticoGrid = (ItemsControl)target; + return; + } + default: + { + this._contentLoaded = true; + return; + } + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 3: + { + ((CheckBox)target).Checked += new RoutedEventHandler(this.CheckBox_Checked); + ((CheckBox)target).Unchecked += new RoutedEventHandler(this.CheckBox_Checked); + return; + } + case 4: + case 6: + case 8: + { + return; + } + case 5: + { + ((Button)target).Click += new RoutedEventHandler(this.MaisInformacoes_OnClick); + return; + } + case 7: + { + ((Button)target).Click += new RoutedEventHandler(this.ArquivoDigital_OnClick); + return; + } + case 9: + { + ((Button)target).Click += new RoutedEventHandler(this.Vinculo_OnClick); + return; + } + default: + { + return; + } + } + } + + private void TipoRelatorio() + { + Expander totalizacao; + System.Windows.Visibility visibility; + this.AssinaturaButton.Visibility = (this.ViewModel.Relatorio == 2 ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.VinculoButton.Visibility = (this.ViewModel.Relatorio == 3 ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.CalculoButton.Visibility = (this.ViewModel.Relatorio == 4 ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + string tipo = ValidationHelper.GetTipo(this.ViewModel.Relatorio); + if (tipo == "FECHAMENTO" || tipo == "NOTA FISCAL") + { + this.InfoButton.Visibility = System.Windows.Visibility.Collapsed; + this.ArquivoButton.Visibility = System.Windows.Visibility.Collapsed; + } + else if (tipo == "TAREFA") + { + this.InfoButton.Visibility = System.Windows.Visibility.Visible; + this.ArquivoButton.Visibility = System.Windows.Visibility.Collapsed; + } + else if (tipo == "EXTRATO") + { + this.InfoButton.Visibility = System.Windows.Visibility.Collapsed; + this.ArquivoButton.Visibility = System.Windows.Visibility.Visible; + } + else + { + this.InfoButton.Visibility = System.Windows.Visibility.Visible; + this.ArquivoButton.Visibility = System.Windows.Visibility.Visible; + } + Relatorio relatorio = this.ViewModel.Relatorio; + if (relatorio <= 15) + { + if (relatorio == 8) + { + this.InfoButton.Visibility = System.Windows.Visibility.Visible; + this.ArquivoButton.Visibility = System.Windows.Visibility.Visible; + } + else if (relatorio - 14 <= 1) + { + this.InfoButton.Visibility = System.Windows.Visibility.Collapsed; + this.ArquivoButton.Visibility = System.Windows.Visibility.Collapsed; + totalizacao = this.Totalizacao; + visibility = (this.ViewModel.Totais ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + totalizacao.Visibility = visibility; + if (!string.IsNullOrWhiteSpace(tipo)) + { + return; + } + this.InfoButton.Visibility = System.Windows.Visibility.Collapsed; + this.ArquivoButton.Visibility = System.Windows.Visibility.Collapsed; + return; + } + } + else if (relatorio - 24 <= 1) + { + this.InfoButton.Visibility = System.Windows.Visibility.Visible; + this.ArquivoButton.Visibility = System.Windows.Visibility.Collapsed; + } + else if (relatorio == 26) + { + this.InfoButton.Visibility = System.Windows.Visibility.Collapsed; + this.ArquivoButton.Visibility = System.Windows.Visibility.Collapsed; + totalizacao = this.Totalizacao; + visibility = (this.ViewModel.Totais ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + totalizacao.Visibility = visibility; + if (!string.IsNullOrWhiteSpace(tipo)) + { + return; + } + this.InfoButton.Visibility = System.Windows.Visibility.Collapsed; + this.ArquivoButton.Visibility = System.Windows.Visibility.Collapsed; + return; + } + totalizacao = this.Totalizacao; + visibility = (this.ViewModel.Totais ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + totalizacao.Visibility = visibility; + if (!string.IsNullOrWhiteSpace(tipo)) + { + return; + } + this.InfoButton.Visibility = System.Windows.Visibility.Collapsed; + this.ArquivoButton.Visibility = System.Windows.Visibility.Collapsed; + } + + private void Totalizacao_OnCollapsedExpanded(object sender, RoutedEventArgs e) + { + this.ViewModel.Totalizacao = this.Totalizacao.IsExpanded; + } + + private async void Vinculo_OnClick(object sender, RoutedEventArgs e) + { + Button button = (Button)sender; + if (button.DataContext != null) + { + ApolicePendente dataContext = (ApolicePendente)button.DataContext; + await this.ViewModel.RemoverVinculo(dataContext); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/Loading.cs b/Codemerx/Gestor.Application/Componentes/Loading.cs new file mode 100644 index 0000000..0c53d3b --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/Loading.cs @@ -0,0 +1,40 @@ +using System; +using System.CodeDom.Compiler; +using System.ComponentModel; +using System.Diagnostics; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Markup; + +namespace Gestor.Application.Componentes +{ + public class Loading : UserControl, IComponentConnector + { + private bool _contentLoaded; + + public Loading() + { + this.InitializeComponent(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/loading.xaml", UriKind.Relative)); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + this._contentLoaded = true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/NRecoHtmlToPdfConverter.cs b/Codemerx/Gestor.Application/Componentes/NRecoHtmlToPdfConverter.cs new file mode 100644 index 0000000..ca6a2c4 --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/NRecoHtmlToPdfConverter.cs @@ -0,0 +1,13 @@ +using NReco.PdfGenerator; +using System; + +namespace Gestor.Application.Componentes +{ + public class NRecoHtmlToPdfConverter : HtmlToPdfConverter + { + public NRecoHtmlToPdfConverter() + { + base.get_License().SetLicenseKey("PDF_Generator_Src_Examples_Pack_255474111334", "UN0G/w7zqQQlt19OtYHW14aK3o8N3sZ5gRq2SELQQjGKYV3luQETgIdsDxPl8e9ZYkRKlglzhNvxi7abVpvWeNYrTp45eL2lRgSIhMhV9Atpy1C12yBt/zG7141kzYD7hT9dmayX5d98MB0DPPlFL3A8b15f6w1qZ9ZVqBFE0w0="); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/PassBox.cs b/Codemerx/Gestor.Application/Componentes/PassBox.cs new file mode 100644 index 0000000..9ca18aa --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/PassBox.cs @@ -0,0 +1,213 @@ +using Gestor.Common.Validation; +using System; +using System.CodeDom.Compiler; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Markup; + +namespace Gestor.Application.Componentes +{ + public class PassBox : UserControl, IComponentConnector + { + public readonly static DependencyProperty ValueProperty; + + public readonly static DependencyProperty HintProperty; + + public readonly static DependencyProperty PasswordWidthProperty; + + private bool _hidePasswordView; + + internal Grid LayoutRoot; + + internal Button ShowHidePassword; + + internal PasswordBox TextPassword; + + internal TextBox TextPasswordVisible; + + private bool _contentLoaded; + + public bool HidePasswordView + { + get + { + return this._hidePasswordView; + } + set + { + if (value) + { + this.HidePassword(); + } + } + } + + public string Hint + { + get + { + return (string)base.GetValue(PassBox.HintProperty); + } + set + { + base.SetValue(PassBox.HintProperty, value); + } + } + + public string PasswordWidth + { + get + { + return (string)base.GetValue(PassBox.PasswordWidthProperty); + } + set + { + base.SetValue(PassBox.PasswordWidthProperty, value); + } + } + + public string Value + { + get + { + return (string)base.GetValue(PassBox.ValueProperty); + } + set + { + base.SetValue(PassBox.ValueProperty, value); + } + } + + public bool Visible + { + get; + set; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + static PassBox() + { + PassBox.ValueProperty = DependencyProperty.Register("Value", typeof(string), typeof(PassBox), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); + PassBox.HintProperty = DependencyProperty.Register("Hint", typeof(string), typeof(PassBox), new FrameworkPropertyMetadata("SENHA", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); + PassBox.PasswordWidthProperty = DependencyProperty.Register("PasswordWidth", typeof(string), typeof(PassBox), new PropertyMetadata(null, new PropertyChangedCallback(PassBox.OnBoundWidthChanged))); + } + + public PassBox() + { + this.InitializeComponent(); + this.LayoutRoot.DataContext = this; + } + + public void HidePassword() + { + this.TextPasswordVisible.Visibility = System.Windows.Visibility.Hidden; + this.TextPassword.Visibility = System.Windows.Visibility.Visible; + this.TextPassword.Focus(); + this.Visible = false; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/passbox.xaml", UriKind.Relative)); + } + + private static void OnBoundWidthChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + PassBox passBox = d as PassBox; + if (d == null || passBox == null) + { + return; + } + string newValue = (string)e.NewValue; + if (!ValidationHelper.ValidateDouble(newValue)) + { + return; + } + passBox.TextPassword.MinWidth = double.Parse(newValue); + passBox.TextPasswordVisible.MinWidth = double.Parse(newValue); + } + + private void ShowHidePassword_OnClick(object sender, RoutedEventArgs e) + { + if (this.Visible) + { + this.HidePassword(); + return; + } + this.ShowPassword(); + } + + private void ShowHidePassword_OnMouseDown(object sender, MouseButtonEventArgs e) + { + this.ShowPassword(); + } + + private void ShowHidePassword_OnMouseUp(object sender, MouseButtonEventArgs e) + { + this.HidePassword(); + } + + public void ShowPassword() + { + this.TextPasswordVisible.Visibility = System.Windows.Visibility.Visible; + this.TextPassword.Visibility = System.Windows.Visibility.Hidden; + this.TextPasswordVisible.Focus(); + this.Visible = true; + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.LayoutRoot = (Grid)target; + return; + } + case 2: + { + this.ShowHidePassword = (Button)target; + this.ShowHidePassword.PreviewMouseDown += new MouseButtonEventHandler(this.ShowHidePassword_OnMouseDown); + this.ShowHidePassword.PreviewMouseUp += new MouseButtonEventHandler(this.ShowHidePassword_OnMouseUp); + return; + } + case 3: + { + this.TextPassword = (PasswordBox)target; + this.TextPassword.PasswordChanged += new RoutedEventHandler(this.TextPassword_PasswordChanged); + return; + } + case 4: + { + this.TextPasswordVisible = (TextBox)target; + return; + } + } + this._contentLoaded = true; + } + + private void TextPassword_PasswordChanged(object sender, RoutedEventArgs e) + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/ProgressDialog.cs b/Codemerx/Gestor.Application/Componentes/ProgressDialog.cs new file mode 100644 index 0000000..847fe51 --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/ProgressDialog.cs @@ -0,0 +1,40 @@ +using Gestor.Application.Views.Generic; +using System; +using System.CodeDom.Compiler; +using System.ComponentModel; +using System.Diagnostics; +using System.Windows; +using System.Windows.Markup; + +namespace Gestor.Application.Componentes +{ + public class ProgressDialog : BaseUserControl, IComponentConnector + { + private bool _contentLoaded; + + public ProgressDialog() + { + this.InitializeComponent(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/progressdialog.xaml", UriKind.Relative)); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + this._contentLoaded = true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/ProspeccaoDialog.cs b/Codemerx/Gestor.Application/Componentes/ProspeccaoDialog.cs new file mode 100644 index 0000000..151bc2a --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/ProspeccaoDialog.cs @@ -0,0 +1,398 @@ +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using MaterialDesignThemes.Wpf; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Markup; +using Xceed.Wpf.AvalonDock.Controls; + +namespace Gestor.Application.Componentes +{ + public class ProspeccaoDialog : BaseUserControl, IComponentConnector, IStyleConnector + { + public DialogProspeccaoViewModel ViewModel; + + internal TextBox DocumentoBox; + + internal DatePicker NascimentoBox; + + internal TextBox Prefixo1Box; + + internal TextBox Telefone1Box; + + internal TextBox Prefixo2Box; + + internal TextBox Telefone2Box; + + internal TextBox EmailBox; + + internal MenuItem SalvarButton; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public ProspeccaoDialog(Prospeccao prospeccao) + { + this.ViewModel = new DialogProspeccaoViewModel(prospeccao); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + } + + private void AnexarArquivos_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Anexar(); + } + + private async void AutoCompleteBox_LostFocus(object sender, RoutedEventArgs e) + { + bool count; + ClienteTelefone item; + bool flag; + ClienteTelefone clienteTelefone; + bool email; + string str; + string numero; + string prefixo; + string numero1; + string prefixo1; + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + if (autoCompleteBox.get_SelectedItem() != null) + { + Cliente cliente = await this.ViewModel.BuscarInfoCliente((Cliente)autoCompleteBox.get_SelectedItem()); + this.DocumentoBox.Text = cliente.get_Documento(); + this.NascimentoBox.SelectedDate = cliente.get_Nascimento(); + ObservableCollection telefones = cliente.get_Telefones(); + if (telefones != null) + { + count = telefones.Count > 0; + } + else + { + count = false; + } + if (count) + { + item = cliente.get_Telefones()[0]; + } + else + { + item = null; + } + ClienteTelefone clienteTelefone1 = item; + if (clienteTelefone1 != null && clienteTelefone1.get_Prefixo() != null) + { + TextBox prefixo1Box = this.Prefixo1Box; + if (clienteTelefone1 != null) + { + prefixo1 = clienteTelefone1.get_Prefixo(); + } + else + { + prefixo1 = null; + } + prefixo1Box.Text = prefixo1; + } + if (clienteTelefone1 != null && clienteTelefone1.get_Numero() != null) + { + TextBox telefone1Box = this.Telefone1Box; + if (clienteTelefone1 != null) + { + numero1 = clienteTelefone1.get_Numero(); + } + else + { + numero1 = null; + } + telefone1Box.Text = numero1; + } + ObservableCollection observableCollection = cliente.get_Telefones(); + if (observableCollection != null) + { + flag = observableCollection.Count > 1; + } + else + { + flag = false; + } + if (flag) + { + clienteTelefone = cliente.get_Telefones()[1]; + } + else + { + clienteTelefone = null; + } + ClienteTelefone clienteTelefone2 = clienteTelefone; + if (clienteTelefone2 != null && clienteTelefone2.get_Prefixo() != null) + { + TextBox prefixo2Box = this.Prefixo2Box; + if (clienteTelefone2 != null) + { + prefixo = clienteTelefone2.get_Prefixo(); + } + else + { + prefixo = null; + } + prefixo2Box.Text = prefixo; + } + if (clienteTelefone2 != null && clienteTelefone2.get_Numero() != null) + { + TextBox telefone2Box = this.Telefone2Box; + if (clienteTelefone2 != null) + { + numero = clienteTelefone2.get_Numero(); + } + else + { + numero = null; + } + telefone2Box.Text = numero; + } + ObservableCollection emails = cliente.get_Emails(); + if (emails != null) + { + ClienteEmail clienteEmail = emails.FirstOrDefault(); + if (clienteEmail != null) + { + email = clienteEmail.get_Email(); + } + else + { + email = false; + } + } + else + { + email = false; + } + if (email) + { + TextBox emailBox = this.EmailBox; + ObservableCollection emails1 = cliente.get_Emails(); + if (emails1 != null) + { + ClienteEmail clienteEmail1 = emails1.FirstOrDefault(); + if (clienteEmail1 != null) + { + str = clienteEmail1.get_Email(); + } + else + { + str = null; + } + } + else + { + str = null; + } + emailBox.Text = str; + } + } + } + + private void AutoCompleteBox_Populating(object sender, PopulatingEventArgs e) + { + if (e.get_Parameter().Trim().Length < 3) + { + return; + } + e.set_Cancel(true); + this.ViewModel.BuscarCliente(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim()), null, 2).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void DeleteArquivo_OnDeleteClick(object sender, RoutedEventArgs e) + { + Chip chip = sender as Chip; + if (chip == null) + { + return; + } + ListBox listBox = Extentions.FindVisualAncestor(chip); + ArquivoDigital item = (ArquivoDigital)listBox.Items[listBox.Items.IndexOf(chip.DataContext)]; + if (item == null) + { + return; + } + this.ViewModel.Delete(item); + } + + private void DocumentoBox_OnLostFocus(object sender, RoutedEventArgs e) + { + TextBox textBox = (TextBox)sender; + textBox.Text = ValidationHelper.FormatDocument(textBox.Text); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/prospeccaodialog.xaml", UriKind.Relative)); + } + + private void SalvarButton_OnClick(object sender, RoutedEventArgs e) + { + List list; + Prospeccao selectedProspeccao = this.ViewModel.SelectedProspeccao; + ObservableCollection arquivosAnexados = this.ViewModel.ArquivosAnexados; + if (arquivosAnexados != null) + { + list = arquivosAnexados.ToList(); + } + else + { + list = null; + } + selectedProspeccao.set_Anexos(list); + DialogHost.CloseDialogCommand.Execute(this.ViewModel.SelectedProspeccao, this.SalvarButton); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, ProspeccaoDialog.AutoCompleteBox_Populating)); + ((AutoCompleteBox)target).LostFocus += new RoutedEventHandler(this.AutoCompleteBox_LostFocus); + return; + } + case 2: + { + this.DocumentoBox = (TextBox)target; + ProspeccaoDialog prospeccaoDialog = this; + this.DocumentoBox.PreviewTextInput += new TextCompositionEventHandler(prospeccaoDialog.SomenteNumeros); + this.DocumentoBox.LostFocus += new RoutedEventHandler(this.DocumentoBox_OnLostFocus); + return; + } + case 3: + { + this.NascimentoBox = (DatePicker)target; + this.NascimentoBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.NascimentoBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + this.NascimentoBox.PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + return; + } + case 4: + { + this.Prefixo1Box = (TextBox)target; + ProspeccaoDialog prospeccaoDialog1 = this; + this.Prefixo1Box.PreviewTextInput += new TextCompositionEventHandler(prospeccaoDialog1.SomenteNumeros); + return; + } + case 5: + { + this.Telefone1Box = (TextBox)target; + ProspeccaoDialog prospeccaoDialog2 = this; + this.Telefone1Box.LostFocus += new RoutedEventHandler(prospeccaoDialog2.FormatarTelefone); + ProspeccaoDialog prospeccaoDialog3 = this; + this.Telefone1Box.PreviewTextInput += new TextCompositionEventHandler(prospeccaoDialog3.SomenteNumeros); + return; + } + case 6: + { + this.Prefixo2Box = (TextBox)target; + ProspeccaoDialog prospeccaoDialog4 = this; + this.Prefixo2Box.PreviewTextInput += new TextCompositionEventHandler(prospeccaoDialog4.SomenteNumeros); + return; + } + case 7: + { + this.Telefone2Box = (TextBox)target; + ProspeccaoDialog prospeccaoDialog5 = this; + this.Telefone2Box.LostFocus += new RoutedEventHandler(prospeccaoDialog5.FormatarTelefone); + ProspeccaoDialog prospeccaoDialog6 = this; + this.Telefone2Box.PreviewTextInput += new TextCompositionEventHandler(prospeccaoDialog6.SomenteNumeros); + return; + } + case 8: + { + this.EmailBox = (TextBox)target; + return; + } + case 9: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + return; + } + case 10: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + return; + } + case 11: + { + this._contentLoaded = true; + return; + } + case 12: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AnexarArquivos_OnClick); + return; + } + case 13: + { + this.SalvarButton = (MenuItem)target; + this.SalvarButton.Click += new RoutedEventHandler(this.SalvarButton_OnClick); + return; + } + default: + { + this._contentLoaded = true; + return; + } + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + if (connectionId == 11) + { + ((Chip)target).add_DeleteClick(new RoutedEventHandler(this.DeleteArquivo_OnDeleteClick)); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/VincularLancamentoDialog.cs b/Codemerx/Gestor.Application/Componentes/VincularLancamentoDialog.cs new file mode 100644 index 0000000..98db83a --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/VincularLancamentoDialog.cs @@ -0,0 +1,82 @@ +using Gestor.Application.ViewModels.Financeiro; +using MaterialDesignThemes.Wpf; +using System; +using System.CodeDom.Compiler; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Markup; + +namespace Gestor.Application.Componentes +{ + public class VincularLancamentoDialog : UserControl, IComponentConnector, IStyleConnector + { + internal DataGrid LancamentoGrid; + + internal Button CancelarButton; + + private bool _contentLoaded; + + public FinanceiroViewModel ViewModel + { + get; + set; + } + + public VincularLancamentoDialog(FinanceiroViewModel viewModel) + { + this.ViewModel = viewModel; + base.DataContext = this.ViewModel; + this.InitializeComponent(); + } + + private void Button_Click(object sender, RoutedEventArgs e) + { + DialogHost.CloseDialogCommand.Execute(this.ViewModel.LancamentoVinculo, this.CancelarButton); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/vincularlancamentodialog.xaml", UriKind.Relative)); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + if (connectionId == 1) + { + this.LancamentoGrid = (DataGrid)target; + return; + } + if (connectionId != 3) + { + this._contentLoaded = true; + return; + } + this.CancelarButton = (Button)target; + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + if (connectionId == 2) + { + ((Button)target).Click += new RoutedEventHandler(this.Button_Click); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/WebBrowser.cs b/Codemerx/Gestor.Application/Componentes/WebBrowser.cs new file mode 100644 index 0000000..35327bc --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/WebBrowser.cs @@ -0,0 +1,197 @@ +using Gestor.Application.Properties; +using HtmlAgilityPack; +using mshtml; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Net; +using System.Reflection; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Interop; +using System.Windows.Markup; +using System.Windows.Navigation; +using System.Windows.Threading; + +namespace Gestor.Application.Componentes +{ + public class WebBrowser : UserControl, IComponentConnector + { + public HTMLDocument HtmlDocument; + + public System.Windows.Controls.WebBrowser Browser; + + public readonly static DependencyProperty IsReadOnlyProperty; + + internal Grid GridWebBrowser; + + private bool _contentLoaded; + + public bool IsReadOnly + { + get + { + return (bool)base.GetValue(Gestor.Application.Componentes.WebBrowser.IsReadOnlyProperty); + } + set + { + base.SetValue(Gestor.Application.Componentes.WebBrowser.IsReadOnlyProperty, value); + } + } + + static WebBrowser() + { + Gestor.Application.Componentes.WebBrowser.IsReadOnlyProperty = DependencyProperty.Register("IsReadOnly", typeof(bool), typeof(Gestor.Application.Componentes.WebBrowser), new PropertyMetadata(false)); + } + + public WebBrowser() + { + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + + private void Browser_PreviewKeyDown(object sender, KeyEventArgs e) + { + if (this.IsReadOnly) + { + e.Handled = true; + } + } + + private void Completed(object sender, NavigationEventArgs e) + { + this.HtmlDocument = this.Browser.Document as HTMLDocument; + if (this.HtmlDocument == null) + { + return; + } + this.HtmlDocument.designMode = "On"; + } + + private void ContentLoad() + { + base.PreviewKeyDown += new KeyEventHandler(this.Browser_PreviewKeyDown); + } + + private static void EncodeNode(HtmlNode node) + { + if (node.get_HasChildNodes()) + { + foreach (HtmlNode childNode in node.get_ChildNodes()) + { + if (childNode.get_NodeType() != 3) + { + Gestor.Application.Componentes.WebBrowser.EncodeNode(childNode); + } + else + { + childNode.set_InnerHtml(WebUtility.HtmlEncode(childNode.get_InnerHtml())); + } + } + } + else if (node.get_NodeType() == 3) + { + node.set_InnerHtml(WebUtility.HtmlEncode(node.get_InnerHtml())); + } + } + + private void HideScriptErrors() + { + FieldInfo field = typeof(Gestor.Application.Componentes.WebBrowser).GetField("_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic); + if (field == null) + { + return; + } + object value = field.GetValue(this.Browser); + if (value != null) + { + value.GetType().InvokeMember("Silent", BindingFlags.SetProperty, null, value, new object[] { true }); + } + } + + public static string HtmlEncode(string html) + { + if (html == null) + { + return null; + } + HtmlAgilityPack.HtmlDocument htmlDocument = new HtmlAgilityPack.HtmlDocument(); + htmlDocument.LoadHtml(html); + htmlDocument.OptionWriteEmptyNodes = true; + Gestor.Application.Componentes.WebBrowser.EncodeNode(htmlDocument.get_DocumentNode()); + return htmlDocument.get_DocumentNode().get_InnerHtml(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/webbrowser.xaml", UriKind.Relative)); + } + + public void InstanciateNew(string htmlData = null) + { + if (this.Browser != null) + { + this.Browser.LoadCompleted -= new LoadCompletedEventHandler(this.Completed); + this.Browser.Dispose(); + this.GridWebBrowser.Children.Remove(this.Browser); + } + HTMLDocument htmlDocument = this.HtmlDocument; + if (htmlDocument != null) + { + htmlDocument.clear(); + } + else + { + } + this.Browser = new System.Windows.Controls.WebBrowser() + { + IsEnabled = true + }; + this.Browser.LoadCompleted += new LoadCompletedEventHandler(this.Completed); + this.GridWebBrowser.Children.Add(this.Browser); + this.HideScriptErrors(); + htmlData = Gestor.Application.Componentes.WebBrowser.HtmlEncode(htmlData); + this.Browser.NavigateToString((string.IsNullOrEmpty(htmlData) ? Gestor.Application.Properties.Resources.New : htmlData)); + this.HtmlDocument = this.Browser.Document as HTMLDocument; + if (this.HtmlDocument == null) + { + return; + } + this.HtmlDocument.charset = "ISO-8859-1"; + this.HtmlDocument.designMode = "On"; + } + + public void ReadOnly(bool isReadOnly) + { + this.IsReadOnly = isReadOnly; + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + if (connectionId != 1) + { + this._contentLoaded = true; + return; + } + this.GridWebBrowser = (Grid)target; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Componentes/WebEditor.cs b/Codemerx/Gestor.Application/Componentes/WebEditor.cs new file mode 100644 index 0000000..9e0cd81 --- /dev/null +++ b/Codemerx/Gestor.Application/Componentes/WebEditor.cs @@ -0,0 +1,704 @@ +using HtmlAgilityPack; +using Microsoft.Win32; +using mshtml; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Drawing; +using System.IO; +using System.Net; +using System.Runtime.CompilerServices; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Forms; +using System.Windows.Markup; +using System.Windows.Media; + +namespace Gestor.Application.Componentes +{ + public class WebEditor : System.Windows.Controls.UserControl, IComponentConnector + { + private System.Windows.Forms.ColorDialog ColorDialog; + + public readonly static DependencyProperty ImageVisibilityProperty; + + public readonly static DependencyProperty BarVisibilityProperty; + + public readonly static DependencyProperty BodyProperty; + + public readonly static DependencyProperty IsReadOnlyProperty; + + internal WrapPanel PanelControls; + + internal System.Windows.Controls.ComboBox ComboTextFormat; + + internal System.Windows.Controls.ComboBox ComboFontFamily; + + internal System.Windows.Controls.ComboBox ComboFontSize; + + internal System.Windows.Controls.Button SettingsBold; + + internal System.Windows.Controls.Button SettingsItalic; + + internal System.Windows.Controls.Button SettingsUnderLine; + + internal System.Windows.Controls.Button SettingsFontColor; + + internal System.Windows.Controls.Button SettingsBullets; + + internal System.Windows.Controls.Button SettingsNumbered; + + internal System.Windows.Controls.Button SettingsLeftAlign; + + internal System.Windows.Controls.Button SettingsCenter; + + internal System.Windows.Controls.Button SettingsRightAlign; + + internal System.Windows.Controls.Button SettingsJustifyFull; + + internal System.Windows.Controls.Button SettingsLink; + + internal System.Windows.Controls.TextBox ImagemLink; + + internal Gestor.Application.Componentes.WebBrowser WebBrowserEditor; + + internal ItemsControl LinkPanel; + + internal System.Windows.Controls.TextBox HrefLink; + + internal CustomItemControl DescricaoBox; + + internal System.Windows.Controls.TextBox DescricaoLink; + + private bool _contentLoaded; + + public System.Windows.Visibility BarVisibility + { + get + { + return (System.Windows.Visibility)base.GetValue(WebEditor.BarVisibilityProperty); + } + set + { + base.SetValue(WebEditor.BarVisibilityProperty, value); + } + } + + public string Body + { + get + { + return (string)base.GetValue(WebEditor.BodyProperty); + } + set + { + base.SetValue(WebEditor.BodyProperty, value); + } + } + + public System.Windows.Visibility ImageVisibility + { + get + { + return (System.Windows.Visibility)base.GetValue(WebEditor.ImageVisibilityProperty); + } + set + { + base.SetValue(WebEditor.ImageVisibilityProperty, value); + } + } + + public bool IsReadOnly + { + get + { + return (bool)base.GetValue(WebEditor.IsReadOnlyProperty); + } + set + { + base.SetValue(WebEditor.IsReadOnlyProperty, value); + } + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + static WebEditor() + { + WebEditor.ImageVisibilityProperty = DependencyProperty.Register("ImageVisibility", typeof(System.Windows.Visibility), typeof(WebEditor), new FrameworkPropertyMetadata((object)System.Windows.Visibility.Collapsed, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); + WebEditor.BarVisibilityProperty = DependencyProperty.Register("BarVisibility", typeof(System.Windows.Visibility), typeof(WebEditor), new FrameworkPropertyMetadata((object)System.Windows.Visibility.Visible, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); + WebEditor.BodyProperty = DependencyProperty.Register("Body", typeof(string), typeof(WebEditor), new FrameworkPropertyMetadata(string.Empty, new PropertyChangedCallback(WebEditor.OnBoundBodyChanged))); + WebEditor.IsReadOnlyProperty = DependencyProperty.Register("IsReadOnly", typeof(bool), typeof(WebEditor), new FrameworkPropertyMetadata(false, new PropertyChangedCallback(WebEditor.OnBoundReadOnlyChanged))); + } + + public WebEditor() + { + this.InitializeComponent(); + this.ColorDialog = new System.Windows.Forms.ColorDialog(); + } + + private void CancelLink_OnClick(object sender, RoutedEventArgs e) + { + this.LinkPanel.Visibility = System.Windows.Visibility.Collapsed; + this.WebBrowserEditor.Visibility = System.Windows.Visibility.Visible; + } + + private void ComboFontFamily_SelectionChanged(object sender, SelectionChangedEventArgs e) + { + this.WebBrowserEditor.HtmlDocument = this.WebBrowserEditor.Browser.Document as HTMLDocument; + string str = this.ComboFontFamily.SelectedItem.ToString(); + HTMLDocument htmlDocument = this.WebBrowserEditor.HtmlDocument; + if (htmlDocument == null) + { + return; + } + htmlDocument.execCommand("FontName", false, str); + } + + private void ComboFontSize_SelectionChanged(object sender, SelectionChangedEventArgs e) + { + this.WebBrowserEditor.HtmlDocument = this.WebBrowserEditor.Browser.Document as HTMLDocument; + HTMLDocument htmlDocument = this.WebBrowserEditor.HtmlDocument; + if (htmlDocument == null) + { + return; + } + htmlDocument.execCommand("FontSize", false, this.ComboFontSize.SelectedItem); + } + + private void ComboTextFormat_SelectionChanged(object sender, SelectionChangedEventArgs e) + { + string str = this.ComboTextFormat.SelectedValue.ToString(); + this.WebBrowserEditor.HtmlDocument = this.WebBrowserEditor.Browser.Document as HTMLDocument; + HTMLDocument htmlDocument = this.WebBrowserEditor.HtmlDocument; + if (htmlDocument == null) + { + return; + } + htmlDocument.execCommand("FormatBlock", false, str); + } + + private void DecodeNode(HtmlNode node) + { + if (node.get_HasChildNodes()) + { + foreach (HtmlNode childNode in node.get_ChildNodes()) + { + if (childNode.get_NodeType() != 3) + { + this.DecodeNode(childNode); + } + else + { + childNode.set_InnerHtml(WebUtility.HtmlDecode(childNode.get_InnerHtml())); + } + } + } + else if (node.get_NodeType() == 3) + { + node.set_InnerHtml(WebUtility.HtmlDecode(node.get_InnerHtml())); + } + } + + private void FontFamilyInitialize() + { + this.ComboFontFamily.ItemsSource = Fonts.SystemFontFamilies; + this.ComboFontFamily.Text = "Times New Roman"; + } + + private void FontFormatInitialize() + { + this.ComboTextFormat.ItemsSource = new List>() + { + new KeyValuePair("

", "Parágrafo"), + new KeyValuePair("

", "Título 1"), + new KeyValuePair("

", "Título 2"), + new KeyValuePair("

", "Título 3"), + new KeyValuePair("

", "Título 4"), + new KeyValuePair("
", "Título 5"), + new KeyValuePair("
", "Título 6"), + new KeyValuePair("
", "Endereço"), + new KeyValuePair("
", "Pré-formatação")
+			};
+			this.ComboTextFormat.SelectedValuePath = "Key";
+			this.ComboTextFormat.DisplayMemberPath = "Value";
+			this.ComboTextFormat.SelectedIndex = 0;
+		}
+
+		private void FontSizeInitialize()
+		{
+			List strs = new List();
+			for (int i = 1; i <= 7; i++)
+			{
+				strs.Add(i.ToString());
+			}
+			this.ComboFontSize.ItemsSource = strs;
+			this.ComboFontSize.Text = "3";
+		}
+
+		public string GetHtml()
+		{
+			string htmlDocument = this.WebBrowserEditor.HtmlDocument.documentElement.innerHTML;
+			return this.HtmlDecode(htmlDocument.Replace("about:", string.Empty));
+		}
+
+		public string GetText()
+		{
+			if (this.WebBrowserEditor.HtmlDocument.documentElement.innerText.Trim() == "new")
+			{
+				return "";
+			}
+			return this.WebBrowserEditor.HtmlDocument.documentElement.innerText;
+		}
+
+		public string HtmlDecode(string html)
+		{
+			if (html == null)
+			{
+				return null;
+			}
+			HtmlAgilityPack.HtmlDocument htmlDocument = new HtmlAgilityPack.HtmlDocument();
+			htmlDocument.LoadHtml(html);
+			htmlDocument.OptionWriteEmptyNodes = true;
+			this.DecodeNode(htmlDocument.get_DocumentNode());
+			return htmlDocument.get_DocumentNode().get_InnerHtml();
+		}
+
+		public void Initialize(string htmlData = null)
+		{
+			this.WebBrowserEditor.InstanciateNew(htmlData);
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		public void InitializeComponent()
+		{
+			if (this._contentLoaded)
+			{
+				return;
+			}
+			this._contentLoaded = true;
+			System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/componentes/webeditor.xaml", UriKind.Relative));
+		}
+
+		private void InsertLink_OnClick(object sender, RoutedEventArgs e)
+		{
+			if (string.IsNullOrWhiteSpace(this.HrefLink.Text))
+			{
+				return;
+			}
+			IHTMLSelectionObject htmlDocument = this.WebBrowserEditor.HtmlDocument.selection;
+			if (htmlDocument != null)
+			{
+				IHTMLTxtRange variable = htmlDocument.createRange() as IHTMLTxtRange;
+				if (variable != null)
+				{
+					if (string.IsNullOrEmpty(variable.htmlText))
+					{
+						variable.pasteHTML(string.Concat(new string[] { "", this.DescricaoLink.Text, "" }));
+					}
+					else
+					{
+						variable.pasteHTML(string.Concat(new string[] { "", variable.htmlText, "" }));
+					}
+				}
+			}
+			this.LinkPanel.Visibility = System.Windows.Visibility.Collapsed;
+			this.WebBrowserEditor.Visibility = System.Windows.Visibility.Visible;
+		}
+
+		public void InsertText(string textToInsert)
+		{
+			object obj;
+			HTMLDocument htmlDocument = this.WebBrowserEditor.HtmlDocument;
+			if (htmlDocument != null)
+			{
+				IHTMLSelectionObject variable = htmlDocument.selection;
+				obj = (variable != null ? variable.createRange() : null);
+			}
+			else
+			{
+				obj = null;
+			}
+			dynamic obj1 = obj;
+			if (obj1 != null)
+			{
+				obj1.pasteHTML(textToInsert);
+			}
+		}
+
+		private static void OnBoundBodyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
+		{
+			string newValue = (string)e.NewValue;
+			if (d != null)
+			{
+				WebEditor webEditor = d as WebEditor;
+				if (webEditor != null)
+				{
+					webEditor.WebBrowserEditor.InstanciateNew(newValue);
+					return;
+				}
+			}
+		}
+
+		private static void OnBoundReadOnlyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
+		{
+			bool newValue = (bool)e.NewValue;
+			if (d != null)
+			{
+				WebEditor webEditor = d as WebEditor;
+				if (webEditor != null)
+				{
+					webEditor.WebBrowserEditor.ReadOnly(newValue);
+					webEditor.PanelControls.IsEnabled = !newValue;
+					return;
+				}
+			}
+		}
+
+		public System.Windows.Media.Color Pick()
+		{
+			System.Windows.Media.Color a = new System.Windows.Media.Color();
+			this.ColorDialog.AllowFullOpen = true;
+			this.ColorDialog.FullOpen = true;
+			if (this.ColorDialog.ShowDialog() != DialogResult.OK)
+			{
+				return a;
+			}
+			System.Drawing.Color color = this.ColorDialog.Color;
+			a.A = color.A;
+			color = this.ColorDialog.Color;
+			a.B = color.B;
+			color = this.ColorDialog.Color;
+			a.G = color.G;
+			color = this.ColorDialog.Color;
+			a.R = color.R;
+			return a;
+		}
+
+		private void SettingsBold_Click(object sender, RoutedEventArgs e)
+		{
+			HTMLDocument htmlDocument = this.WebBrowserEditor.HtmlDocument;
+			if (htmlDocument == null)
+			{
+				return;
+			}
+			htmlDocument.execCommand("Bold", false, Type.Missing);
+		}
+
+		private void SettingsBullets_Click(object sender, RoutedEventArgs e)
+		{
+			HTMLDocument htmlDocument = this.WebBrowserEditor.HtmlDocument;
+			if (htmlDocument == null)
+			{
+				return;
+			}
+			htmlDocument.execCommand("InsertUnorderedList", false, Type.Missing);
+		}
+
+		private void SettingsCenter_Click(object sender, RoutedEventArgs e)
+		{
+			HTMLDocument htmlDocument = this.WebBrowserEditor.HtmlDocument;
+			if (htmlDocument == null)
+			{
+				return;
+			}
+			htmlDocument.execCommand("JustifyCenter", false, Type.Missing);
+		}
+
+		private void SettingsFontColor_Click(object sender, RoutedEventArgs e)
+		{
+			this.WebBrowserEditor.HtmlDocument = this.WebBrowserEditor.Browser.Document as HTMLDocument;
+			if (this.WebBrowserEditor.HtmlDocument == null)
+			{
+				return;
+			}
+			System.Windows.Media.Color color = this.Pick();
+			string str = string.Format("#{0:X2}{1:X2}{2:X2}", color.R, color.G, color.B);
+			this.WebBrowserEditor.HtmlDocument.execCommand("ForeColor", false, str);
+		}
+
+		private void SettingsImage_Click(object sender, RoutedEventArgs e)
+		{
+			object obj;
+			Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog()
+			{
+				Title = "Selecione a imagem",
+				Filter = "Todos os formatos|*.jpg;*.jpeg;*.png|JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|Portable Network Graphic (*.png)|*.png"
+			};
+			if (!openFileDialog.ShowDialog().GetValueOrDefault())
+			{
+				return;
+			}
+			string str = Path.GetExtension(openFileDialog.FileName).ToLower().Substring(1);
+			string base64String = Convert.ToBase64String(File.ReadAllBytes(openFileDialog.FileName));
+			string str1 = string.Concat("data:image/", str, ";base64,", base64String);
+			HTMLDocument htmlDocument = this.WebBrowserEditor.HtmlDocument;
+			if (htmlDocument != null)
+			{
+				IHTMLSelectionObject variable = htmlDocument.selection;
+				obj = (variable != null ? variable.createRange() : null);
+			}
+			else
+			{
+				obj = null;
+			}
+			object obj1 = obj;
+			string str2 = string.Concat("\"Imagem\"");
+			if (!string.IsNullOrEmpty(this.ImagemLink.Text.Trim()))
+			{
+				str2 = string.Concat(new string[] { "", str2, "" });
+			}
+			dynamic obj2 = obj1;
+			if (obj2 != null)
+			{
+				obj2.pasteHTML(str2);
+			}
+		}
+
+		private void SettingsInsertOrderedList_Click(object sender, RoutedEventArgs e)
+		{
+			HTMLDocument htmlDocument = this.WebBrowserEditor.HtmlDocument;
+			if (htmlDocument == null)
+			{
+				return;
+			}
+			htmlDocument.execCommand("InsertOrderedList", false, Type.Missing);
+		}
+
+		private void SettingsItalic_Click(object sender, RoutedEventArgs e)
+		{
+			HTMLDocument htmlDocument = this.WebBrowserEditor.HtmlDocument;
+			if (htmlDocument == null)
+			{
+				return;
+			}
+			htmlDocument.execCommand("Italic", false, Type.Missing);
+		}
+
+		private void SettingsJustifyFull_Click(object sender, RoutedEventArgs e)
+		{
+			HTMLDocument htmlDocument = this.WebBrowserEditor.HtmlDocument;
+			if (htmlDocument == null)
+			{
+				return;
+			}
+			htmlDocument.execCommand("JustifyFull", false, Type.Missing);
+		}
+
+		private void SettingsLeftAlign_Click(object sender, RoutedEventArgs e)
+		{
+			HTMLDocument htmlDocument = this.WebBrowserEditor.HtmlDocument;
+			if (htmlDocument == null)
+			{
+				return;
+			}
+			htmlDocument.execCommand("JustifyLeft", false, Type.Missing);
+		}
+
+		private void SettingsLink_OnClick(object sender, RoutedEventArgs e)
+		{
+			HTMLDocument htmlDocument = this.WebBrowserEditor.HtmlDocument;
+			this.DescricaoBox.Visibility = System.Windows.Visibility.Visible;
+			IHTMLSelectionObject variable = htmlDocument.selection;
+			if (variable != null)
+			{
+				IHTMLTxtRange variable1 = variable.createRange() as IHTMLTxtRange;
+				if (variable1 != null)
+				{
+					this.DescricaoBox.Visibility = (!string.IsNullOrEmpty(variable1.htmlText) ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible);
+				}
+			}
+			this.LinkPanel.Visibility = System.Windows.Visibility.Visible;
+			this.WebBrowserEditor.Visibility = System.Windows.Visibility.Hidden;
+		}
+
+		private void SettingsRightAlign_Click(object sender, RoutedEventArgs e)
+		{
+			HTMLDocument htmlDocument = this.WebBrowserEditor.HtmlDocument;
+			if (htmlDocument == null)
+			{
+				return;
+			}
+			htmlDocument.execCommand("JustifyRight", false, Type.Missing);
+		}
+
+		private void SettingsUnderLine_Click(object sender, RoutedEventArgs e)
+		{
+			HTMLDocument htmlDocument = this.WebBrowserEditor.HtmlDocument;
+			if (htmlDocument == null)
+			{
+				return;
+			}
+			htmlDocument.execCommand("Underline", false, Type.Missing);
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target)
+		{
+			switch (connectionId)
+			{
+				case 1:
+				{
+					((WebEditor)target).Loaded += new RoutedEventHandler(this.Window_Loaded);
+					return;
+				}
+				case 2:
+				{
+					this.PanelControls = (WrapPanel)target;
+					return;
+				}
+				case 3:
+				{
+					this.ComboTextFormat = (System.Windows.Controls.ComboBox)target;
+					this.ComboTextFormat.SelectionChanged += new SelectionChangedEventHandler(this.ComboTextFormat_SelectionChanged);
+					return;
+				}
+				case 4:
+				{
+					this.ComboFontFamily = (System.Windows.Controls.ComboBox)target;
+					this.ComboFontFamily.SelectionChanged += new SelectionChangedEventHandler(this.ComboFontFamily_SelectionChanged);
+					return;
+				}
+				case 5:
+				{
+					this.ComboFontSize = (System.Windows.Controls.ComboBox)target;
+					this.ComboFontSize.SelectionChanged += new SelectionChangedEventHandler(this.ComboFontSize_SelectionChanged);
+					return;
+				}
+				case 6:
+				{
+					this.SettingsBold = (System.Windows.Controls.Button)target;
+					this.SettingsBold.Click += new RoutedEventHandler(this.SettingsBold_Click);
+					return;
+				}
+				case 7:
+				{
+					this.SettingsItalic = (System.Windows.Controls.Button)target;
+					this.SettingsItalic.Click += new RoutedEventHandler(this.SettingsItalic_Click);
+					return;
+				}
+				case 8:
+				{
+					this.SettingsUnderLine = (System.Windows.Controls.Button)target;
+					this.SettingsUnderLine.Click += new RoutedEventHandler(this.SettingsUnderLine_Click);
+					return;
+				}
+				case 9:
+				{
+					this.SettingsFontColor = (System.Windows.Controls.Button)target;
+					this.SettingsFontColor.Click += new RoutedEventHandler(this.SettingsFontColor_Click);
+					return;
+				}
+				case 10:
+				{
+					this.SettingsBullets = (System.Windows.Controls.Button)target;
+					this.SettingsBullets.Click += new RoutedEventHandler(this.SettingsBullets_Click);
+					return;
+				}
+				case 11:
+				{
+					this.SettingsNumbered = (System.Windows.Controls.Button)target;
+					this.SettingsNumbered.Click += new RoutedEventHandler(this.SettingsInsertOrderedList_Click);
+					return;
+				}
+				case 12:
+				{
+					this.SettingsLeftAlign = (System.Windows.Controls.Button)target;
+					this.SettingsLeftAlign.Click += new RoutedEventHandler(this.SettingsLeftAlign_Click);
+					return;
+				}
+				case 13:
+				{
+					this.SettingsCenter = (System.Windows.Controls.Button)target;
+					this.SettingsCenter.Click += new RoutedEventHandler(this.SettingsCenter_Click);
+					return;
+				}
+				case 14:
+				{
+					this.SettingsRightAlign = (System.Windows.Controls.Button)target;
+					this.SettingsRightAlign.Click += new RoutedEventHandler(this.SettingsRightAlign_Click);
+					return;
+				}
+				case 15:
+				{
+					this.SettingsJustifyFull = (System.Windows.Controls.Button)target;
+					this.SettingsJustifyFull.Click += new RoutedEventHandler(this.SettingsJustifyFull_Click);
+					return;
+				}
+				case 16:
+				{
+					this.SettingsLink = (System.Windows.Controls.Button)target;
+					this.SettingsLink.Click += new RoutedEventHandler(this.SettingsLink_OnClick);
+					return;
+				}
+				case 17:
+				{
+					this.ImagemLink = (System.Windows.Controls.TextBox)target;
+					return;
+				}
+				case 18:
+				{
+					((System.Windows.Controls.MenuItem)target).Click += new RoutedEventHandler(this.SettingsImage_Click);
+					return;
+				}
+				case 19:
+				{
+					this.WebBrowserEditor = (Gestor.Application.Componentes.WebBrowser)target;
+					return;
+				}
+				case 20:
+				{
+					this.LinkPanel = (ItemsControl)target;
+					return;
+				}
+				case 21:
+				{
+					((System.Windows.Controls.Button)target).Click += new RoutedEventHandler(this.CancelLink_OnClick);
+					return;
+				}
+				case 22:
+				{
+					this.HrefLink = (System.Windows.Controls.TextBox)target;
+					return;
+				}
+				case 23:
+				{
+					this.DescricaoBox = (CustomItemControl)target;
+					return;
+				}
+				case 24:
+				{
+					this.DescricaoLink = (System.Windows.Controls.TextBox)target;
+					return;
+				}
+				case 25:
+				{
+					((System.Windows.Controls.Button)target).Click += new RoutedEventHandler(this.InsertLink_OnClick);
+					return;
+				}
+			}
+			this._contentLoaded = true;
+		}
+
+		private void Window_Loaded(object sender, RoutedEventArgs e)
+		{
+			if (this.WebBrowserEditor.Browser == null)
+			{
+				this.WebBrowserEditor.InstanciateNew(null);
+			}
+			this.FontFamilyInitialize();
+			this.FontSizeInitialize();
+			this.FontFormatInitialize();
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/ActualHeightConverter.cs b/Codemerx/Gestor.Application/Converters/ActualHeightConverter.cs
new file mode 100644
index 0000000..1d521c9
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/ActualHeightConverter.cs
@@ -0,0 +1,33 @@
+using System;
+using System.Globalization;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class ActualHeightConverter : MarkupExtension, IValueConverter
+	{
+		public ActualHeightConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value == null)
+			{
+				return 0;
+			}
+			return (double)value - 20;
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/ArquivoDigitalVisibilityConverter.cs b/Codemerx/Gestor.Application/Converters/ArquivoDigitalVisibilityConverter.cs
new file mode 100644
index 0000000..61b456a
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/ArquivoDigitalVisibilityConverter.cs
@@ -0,0 +1,30 @@
+using System;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class ArquivoDigitalVisibilityConverter : MarkupExtension, IValueConverter
+	{
+		public ArquivoDigitalVisibilityConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return (value == null ? Visibility.Collapsed : Visibility.Visible);
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/AssinaturasVisibilityConverter.cs b/Codemerx/Gestor.Application/Converters/AssinaturasVisibilityConverter.cs
new file mode 100644
index 0000000..b32db66
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/AssinaturasVisibilityConverter.cs
@@ -0,0 +1,32 @@
+using Gestor.Model.Common;
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class AssinaturasVisibilityConverter : MarkupExtension, IValueConverter
+	{
+		public AssinaturasVisibilityConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return (value == null || ((List)value).Count == 0 ? Visibility.Collapsed : Visibility.Visible);
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/AssistenciaVisibilityConverter.cs b/Codemerx/Gestor.Application/Converters/AssistenciaVisibilityConverter.cs
new file mode 100644
index 0000000..6268f3d
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/AssistenciaVisibilityConverter.cs
@@ -0,0 +1,35 @@
+using Gestor.Model.Common;
+using System;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class AssistenciaVisibilityConverter : MarkupExtension, IValueConverter
+	{
+		public AssistenciaVisibilityConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value == null)
+			{
+				return Visibility.Collapsed;
+			}
+			return ((TipoContatoSeguradora)value == 1 ? Visibility.Visible : Visibility.Collapsed);
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/AtivoToColorConverter.cs b/Codemerx/Gestor.Application/Converters/AtivoToColorConverter.cs
new file mode 100644
index 0000000..b258583
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/AtivoToColorConverter.cs
@@ -0,0 +1,35 @@
+using System;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Data;
+using System.Windows.Markup;
+using System.Windows.Media;
+
+namespace Gestor.Application.Converters
+{
+	public class AtivoToColorConverter : MarkupExtension, IValueConverter
+	{
+		public AtivoToColorConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (((bool?)value).GetValueOrDefault(true))
+			{
+				return new SolidColorBrush(Colors.Red);
+			}
+			return new SolidColorBrush((Color)System.Windows.Application.Current.Resources["AggerBlue"]);
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/AtivoToStringConverter.cs b/Codemerx/Gestor.Application/Converters/AtivoToStringConverter.cs
new file mode 100644
index 0000000..f59b507
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/AtivoToStringConverter.cs
@@ -0,0 +1,33 @@
+using System;
+using System.Globalization;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class AtivoToStringConverter : MarkupExtension, IValueConverter
+	{
+		public AtivoToStringConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (!((bool?)value).GetValueOrDefault(true))
+			{
+				return "ATIVAR";
+			}
+			return "INATIVAR";
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/BaixarVisibilityConverter.cs b/Codemerx/Gestor.Application/Converters/BaixarVisibilityConverter.cs
new file mode 100644
index 0000000..7939567
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/BaixarVisibilityConverter.cs
@@ -0,0 +1,41 @@
+using Gestor.Model.Common;
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class BaixarVisibilityConverter : MarkupExtension, IValueConverter
+	{
+		public BaixarVisibilityConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value == null)
+			{
+				return Visibility.Collapsed;
+			}
+			return ((new List()
+			{
+				1,
+				13,
+				10
+			}).Contains((StatusParcela)value) ? Visibility.Collapsed : Visibility.Visible);
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/BoletosNotasConverter.cs b/Codemerx/Gestor.Application/Converters/BoletosNotasConverter.cs
new file mode 100644
index 0000000..e1830a0
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/BoletosNotasConverter.cs
@@ -0,0 +1,31 @@
+using Gestor.Application.Model.Ajuda;
+using System;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class BoletosNotasConverter : MarkupExtension, IValueConverter
+	{
+		public BoletosNotasConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return (string.IsNullOrEmpty(((Boleto)value).Nota) ? Visibility.Hidden : Visibility.Visible);
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/BoolToGridHeightOneStarConverter.cs b/Codemerx/Gestor.Application/Converters/BoolToGridHeightOneStarConverter.cs
new file mode 100644
index 0000000..636dc5e
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/BoolToGridHeightOneStarConverter.cs
@@ -0,0 +1,40 @@
+using System;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class BoolToGridHeightOneStarConverter : MarkupExtension, IValueConverter
+	{
+		public BoolToGridHeightOneStarConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			int num;
+			int num1 = 1;
+			if (parameter != null && int.TryParse(parameter.ToString(), out num))
+			{
+				num1 = num;
+			}
+			if (value != null && (bool)value && num1 == 1000)
+			{
+				return new GridLength(1, GridUnitType.Auto);
+			}
+			return (value == null || !(bool)value ? new GridLength(0) : new GridLength((double)num1, GridUnitType.Star));
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/CalculoIconConverter.cs b/Codemerx/Gestor.Application/Converters/CalculoIconConverter.cs
new file mode 100644
index 0000000..e7bb148
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/CalculoIconConverter.cs
@@ -0,0 +1,42 @@
+using Gestor.Model.Domain.Aggilizador;
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class CalculoIconConverter : MarkupExtension, IValueConverter
+	{
+		public CalculoIconConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			Uri uri = new Uri("pack://application:,,,Gestor.Application;component/Assets/Images/CalculoIcon.png");
+			if (value == null)
+			{
+				return uri;
+			}
+			if (!((List)value).Any((Calculo x) => x.get_Status() == 2))
+			{
+				return new Uri("pack://application:,,,Gestor.Application;component/Assets/Images/CalculoIcon.png");
+			}
+			return new Uri("pack://application:,,,Gestor.Application;component/Assets/Images/CalculoIconOk.png");
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return value;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/ColorStatusConverter.cs b/Codemerx/Gestor.Application/Converters/ColorStatusConverter.cs
new file mode 100644
index 0000000..b7cc4f9
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/ColorStatusConverter.cs
@@ -0,0 +1,75 @@
+using Gestor.Model.Common;
+using Gestor.Model.Validation;
+using System;
+using System.Globalization;
+using System.Windows.Data;
+using System.Windows.Media;
+
+namespace Gestor.Application.Converters
+{
+	public class ColorStatusConverter : IMultiValueConverter
+	{
+		public ColorStatusConverter()
+		{
+		}
+
+		public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (values[2] != null && values[2] is bool && (bool)values[2])
+			{
+				return new SolidColorBrush(Colors.Red);
+			}
+			object obj = values[0];
+			if (obj == null)
+			{
+				return new SolidColorBrush(Colors.White);
+			}
+			if (!(obj is TipoSeguro))
+			{
+				return new SolidColorBrush(Colors.White);
+			}
+			switch ((TipoSeguro)values[0])
+			{
+				case 3:
+				{
+					return new SolidColorBrush(Colors.Red);
+				}
+				case 5:
+				{
+					return new SolidColorBrush(Colors.DarkBlue);
+				}
+				case 6:
+				{
+					return new SolidColorBrush(Colors.Gray);
+				}
+				case 7:
+				{
+					return new SolidColorBrush(Colors.DimGray);
+				}
+				default:
+				{
+					if (values[1] == null)
+					{
+						return new SolidColorBrush(Colors.Green);
+					}
+					else
+					{
+						break;
+					}
+				}
+			}
+			DateTime? nullable = (DateTime?)values[1];
+			DateTime dateTime = Funcoes.GetNetworkTime().Date.AddDays(-6);
+			if ((nullable.HasValue ? nullable.GetValueOrDefault() < dateTime : true))
+			{
+				return new SolidColorBrush(Colors.Goldenrod);
+			}
+			return new SolidColorBrush(Colors.Green);
+		}
+
+		public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/ContatoSeguradoraVisibiltyConverter.cs b/Codemerx/Gestor.Application/Converters/ContatoSeguradoraVisibiltyConverter.cs
new file mode 100644
index 0000000..4bdffcf
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/ContatoSeguradoraVisibiltyConverter.cs
@@ -0,0 +1,35 @@
+using Gestor.Model.Common;
+using System;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class ContatoSeguradoraVisibiltyConverter : MarkupExtension, IValueConverter
+	{
+		public ContatoSeguradoraVisibiltyConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value == null)
+			{
+				return Visibility.Visible;
+			}
+			return ((TipoContatoSeguradora)value == 1 ? Visibility.Collapsed : Visibility.Visible);
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/DesconsiderarVisibilityConverter.cs b/Codemerx/Gestor.Application/Converters/DesconsiderarVisibilityConverter.cs
new file mode 100644
index 0000000..8a3c13e
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/DesconsiderarVisibilityConverter.cs
@@ -0,0 +1,43 @@
+using Gestor.Model.Common;
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class DesconsiderarVisibilityConverter : MarkupExtension, IValueConverter
+	{
+		public DesconsiderarVisibilityConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value == null)
+			{
+				return Visibility.Collapsed;
+			}
+			return ((new List()
+			{
+				8,
+				6,
+				1,
+				13,
+				10
+			}).Contains((StatusParcela)value) ? Visibility.Collapsed : Visibility.Visible);
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/DiasPentendesConverter.cs b/Codemerx/Gestor.Application/Converters/DiasPentendesConverter.cs
new file mode 100644
index 0000000..c684fe8
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/DiasPentendesConverter.cs
@@ -0,0 +1,33 @@
+using System;
+using System.Globalization;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class DiasPentendesConverter : MarkupExtension, IValueConverter
+	{
+		public DiasPentendesConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value == null)
+			{
+				return "";
+			}
+			return string.Format("{0} DIAS", value);
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/DocumentoEtiquetaConverter.cs b/Codemerx/Gestor.Application/Converters/DocumentoEtiquetaConverter.cs
new file mode 100644
index 0000000..e1defd3
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/DocumentoEtiquetaConverter.cs
@@ -0,0 +1,49 @@
+using Gestor.Model.Common;
+using System;
+using System.Globalization;
+using System.Windows.Data;
+
+namespace Gestor.Application.Converters
+{
+	public class DocumentoEtiquetaConverter : IMultiValueConverter
+	{
+		public DocumentoEtiquetaConverter()
+		{
+		}
+
+		public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
+		{
+			object obj;
+			object obj1;
+			try
+			{
+				if (values != null)
+				{
+					if ((TipoProtocoloEtiqueta)values[0] == 1)
+					{
+						obj1 = " - ";
+					}
+					else
+					{
+						obj1 = values[1];
+					}
+					obj = obj1;
+				}
+				else
+				{
+					obj = "";
+				}
+			}
+			catch
+			{
+				obj = "";
+			}
+			return obj;
+		}
+
+		public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/EmpresaNomeConverter.cs b/Codemerx/Gestor.Application/Converters/EmpresaNomeConverter.cs
new file mode 100644
index 0000000..54ceb4c
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/EmpresaNomeConverter.cs
@@ -0,0 +1,38 @@
+using Gestor.Application.Helpers;
+using Gestor.Model.Domain.Common;
+using Gestor.Model.Domain.Generic;
+using System;
+using System.Globalization;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class EmpresaNomeConverter : MarkupExtension, IValueConverter
+	{
+		public EmpresaNomeConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value != null && (long)value != 0)
+			{
+				return Recursos.Empresas.First((Empresa x) => x.get_Id() == (long)value).get_Nome();
+			}
+			return Recursos.Empresas.First((Empresa x) => x.get_Id() == (long)1).get_Nome();
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/EnderecoConverter.cs b/Codemerx/Gestor.Application/Converters/EnderecoConverter.cs
new file mode 100644
index 0000000..d31f10e
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/EnderecoConverter.cs
@@ -0,0 +1,191 @@
+using Gestor.Model.Domain.Generic;
+using Gestor.Model.Domain.Seguros;
+using System;
+using System.Collections.ObjectModel;
+using System.Globalization;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class EnderecoConverter : MarkupExtension, IValueConverter
+	{
+		public EnderecoConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			string str;
+			string str1;
+			string str2;
+			string str3;
+			string str4;
+			string str5;
+			string str6;
+			string str7;
+			string str8;
+			string str9;
+			string str10;
+			string str11;
+			if (value == null)
+			{
+				return "";
+			}
+			if (!(value is ObservableCollection))
+			{
+				return "";
+			}
+			ObservableCollection observableCollection = (ObservableCollection)value;
+			if (string.IsNullOrWhiteSpace(observableCollection[0].get_Complemento()))
+			{
+				string[] strArrays = new string[11];
+				string endereco = observableCollection[0].get_Endereco();
+				if (endereco != null)
+				{
+					str = endereco.Trim();
+				}
+				else
+				{
+					str = null;
+				}
+				strArrays[0] = str;
+				strArrays[1] = ", ";
+				string numero = observableCollection[0].get_Numero();
+				if (numero != null)
+				{
+					str1 = numero.Trim();
+				}
+				else
+				{
+					str1 = null;
+				}
+				strArrays[2] = str1;
+				strArrays[3] = ", ";
+				string bairro = observableCollection[0].get_Bairro();
+				if (bairro != null)
+				{
+					str2 = bairro.Trim();
+				}
+				else
+				{
+					str2 = null;
+				}
+				strArrays[4] = str2;
+				strArrays[5] = " - ";
+				string cidade = observableCollection[0].get_Cidade();
+				if (cidade != null)
+				{
+					str3 = cidade.Trim();
+				}
+				else
+				{
+					str3 = null;
+				}
+				strArrays[6] = str3;
+				strArrays[7] = "/";
+				string estado = observableCollection[0].get_Estado();
+				if (estado != null)
+				{
+					str4 = estado.Trim();
+				}
+				else
+				{
+					str4 = null;
+				}
+				strArrays[8] = str4;
+				strArrays[9] = " - ";
+				string cep = observableCollection[0].get_Cep();
+				if (cep != null)
+				{
+					str5 = cep.Trim();
+				}
+				else
+				{
+					str5 = null;
+				}
+				strArrays[10] = str5;
+				return string.Concat(strArrays);
+			}
+			string[] strArrays1 = new string[13];
+			string endereco1 = observableCollection[0].get_Endereco();
+			if (endereco1 != null)
+			{
+				str6 = endereco1.Trim();
+			}
+			else
+			{
+				str6 = null;
+			}
+			strArrays1[0] = str6;
+			strArrays1[1] = ", ";
+			string numero1 = observableCollection[0].get_Numero();
+			if (numero1 != null)
+			{
+				str7 = numero1.Trim();
+			}
+			else
+			{
+				str7 = null;
+			}
+			strArrays1[2] = str7;
+			strArrays1[3] = ", ";
+			strArrays1[4] = observableCollection[0].get_Complemento().Trim();
+			strArrays1[5] = ", ";
+			string bairro1 = observableCollection[0].get_Bairro();
+			if (bairro1 != null)
+			{
+				str8 = bairro1.Trim();
+			}
+			else
+			{
+				str8 = null;
+			}
+			strArrays1[6] = str8;
+			strArrays1[7] = " - ";
+			string cidade1 = observableCollection[0].get_Cidade();
+			if (cidade1 != null)
+			{
+				str9 = cidade1.Trim();
+			}
+			else
+			{
+				str9 = null;
+			}
+			strArrays1[8] = str9;
+			strArrays1[9] = "/";
+			string estado1 = observableCollection[0].get_Estado();
+			if (estado1 != null)
+			{
+				str10 = estado1.Trim();
+			}
+			else
+			{
+				str10 = null;
+			}
+			strArrays1[10] = str10;
+			strArrays1[11] = " - ";
+			string cep1 = observableCollection[0].get_Cep();
+			if (cep1 != null)
+			{
+				str11 = cep1.Trim();
+			}
+			else
+			{
+				str11 = null;
+			}
+			strArrays1[12] = str11;
+			return string.Concat(strArrays1);
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/EnviadoColorConverter.cs b/Codemerx/Gestor.Application/Converters/EnviadoColorConverter.cs
new file mode 100644
index 0000000..7e56ca0
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/EnviadoColorConverter.cs
@@ -0,0 +1,69 @@
+using Gestor.Model.Common;
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Windows;
+using System.Windows.Data;
+using System.Windows.Markup;
+using System.Windows.Media;
+
+namespace Gestor.Application.Converters
+{
+	public class EnviadoColorConverter : MarkupExtension, IValueConverter
+	{
+		public EnviadoColorConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value == null || !(value is List))
+			{
+				return new SolidColorBrush(Colors.IndianRed);
+			}
+			List statusDocumentoAssinados = (List)value;
+			int num = statusDocumentoAssinados.Count((StatusDocumentoAssinado x) => {
+				if (x.get_Status() == 1)
+				{
+					return true;
+				}
+				return x.get_Status() == 4;
+			});
+			int num1 = statusDocumentoAssinados.Count((StatusDocumentoAssinado x) => x.get_Status() == 0);
+			int num2 = statusDocumentoAssinados.Count((StatusDocumentoAssinado x) => x.get_Status() == 2);
+			if (statusDocumentoAssinados.All((StatusDocumentoAssinado x) => x.get_Status() == 3))
+			{
+				return new SolidColorBrush(Colors.IndianRed);
+			}
+			if (num2 > 0)
+			{
+				return new SolidColorBrush(Colors.Red);
+			}
+			if (num > 0 && num1 == 0 && num2 == 0)
+			{
+				return new SolidColorBrush(Colors.ForestGreen);
+			}
+			if (num == 0 && num1 > 0 && num2 == 0)
+			{
+				return new SolidColorBrush((Color)System.Windows.Application.Current.Resources["AggerBlue"]);
+			}
+			if (num <= 0 || num1 <= 0 || num2 != 0)
+			{
+				return new SolidColorBrush(Colors.IndianRed);
+			}
+			return new SolidColorBrush((Color)System.Windows.Application.Current.Resources["AggerYellow100"]);
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/EnviadoConverter.cs b/Codemerx/Gestor.Application/Converters/EnviadoConverter.cs
new file mode 100644
index 0000000..9fe764f
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/EnviadoConverter.cs
@@ -0,0 +1,39 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Windows;
+using System.Windows.Data;
+
+namespace Gestor.Application.Converters
+{
+	public class EnviadoConverter : IMultiValueConverter
+	{
+		public EnviadoConverter()
+		{
+		}
+
+		public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (((IEnumerable)values).Any((object x) => x == null))
+			{
+				return Visibility.Collapsed;
+			}
+			if (values[0] is bool && (bool)values[0])
+			{
+				return Visibility.Collapsed;
+			}
+			if (values[1] is bool && (bool)values[1])
+			{
+				return Visibility.Visible;
+			}
+			return Visibility.Collapsed;
+		}
+
+		public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
+		{
+			throw new NotImplementedException();
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/EnviadoIconConverter.cs b/Codemerx/Gestor.Application/Converters/EnviadoIconConverter.cs
new file mode 100644
index 0000000..a29e631
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/EnviadoIconConverter.cs
@@ -0,0 +1,65 @@
+using ControlzEx;
+using Gestor.Model.Common;
+using MaterialDesignThemes.Wpf;
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class EnviadoIconConverter : MarkupExtension, IValueConverter
+	{
+		public EnviadoIconConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			PackIcon packIcon = new PackIcon();
+			if (value == null || !(value is List))
+			{
+				packIcon.set_Kind(2689);
+				return packIcon;
+			}
+			List statusDocumentoAssinados = (List)value;
+			int num = statusDocumentoAssinados.Count((StatusDocumentoAssinado x) => x.get_Status() == 1);
+			int num1 = statusDocumentoAssinados.Count((StatusDocumentoAssinado x) => x.get_Status() == 0);
+			int num2 = statusDocumentoAssinados.Count((StatusDocumentoAssinado x) => x.get_Status() == 2);
+			if (statusDocumentoAssinados.All((StatusDocumentoAssinado x) => x.get_Status() == 3))
+			{
+				packIcon.set_Kind(2689);
+			}
+			if (num2 > 0)
+			{
+				packIcon.set_Kind(789);
+			}
+			if (num > 0 && num1 == 0 && num2 == 0)
+			{
+				packIcon.set_Kind(2685);
+			}
+			if (num == 0 && num1 > 0 && num2 == 0)
+			{
+				packIcon.set_Kind(2685);
+			}
+			if (num > 0 && num1 > 0 && num2 == 0)
+			{
+				packIcon.set_Kind(95);
+			}
+			return packIcon;
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/EnviadoTooTipConverter.cs b/Codemerx/Gestor.Application/Converters/EnviadoTooTipConverter.cs
new file mode 100644
index 0000000..e2f4b00
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/EnviadoTooTipConverter.cs
@@ -0,0 +1,67 @@
+using Gestor.Model.Common;
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class EnviadoTooTipConverter : MarkupExtension, IValueConverter
+	{
+		public EnviadoTooTipConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value == null || !(value is List))
+			{
+				return "";
+			}
+			List statusDocumentoAssinados = (List)value;
+			int num = statusDocumentoAssinados.Count((StatusDocumentoAssinado x) => {
+				if (x.get_Status() == 1)
+				{
+					return true;
+				}
+				return x.get_Status() == 4;
+			});
+			int num1 = statusDocumentoAssinados.Count((StatusDocumentoAssinado x) => x.get_Status() == 0);
+			int num2 = statusDocumentoAssinados.Count((StatusDocumentoAssinado x) => x.get_Status() == 2);
+			if (statusDocumentoAssinados.All((StatusDocumentoAssinado x) => x.get_Status() == 3))
+			{
+				return "ASSINAR SELECIONADOS";
+			}
+			if (num2 > 0)
+			{
+				return "HÁ ASSINATURAS REJEITADAS PARA ESSE DOCUMENTO";
+			}
+			if (num > 0 && num1 == 0 && num2 == 0)
+			{
+				return "DOCUMENTO ASSINADO";
+			}
+			if (num == 0 && num1 > 0 && num2 == 0)
+			{
+				return "ASSINATURA PENDENTE";
+			}
+			if (num > 0 && num1 > 0 && num2 == 0)
+			{
+				return "CLIQUE PARA VERIFICAR O STATUS DAS ASSINATURAS";
+			}
+			return "ASSINAR DOCUMENTOS";
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/EqualToCollapsedConverter.cs b/Codemerx/Gestor.Application/Converters/EqualToCollapsedConverter.cs
new file mode 100644
index 0000000..a254e8c
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/EqualToCollapsedConverter.cs
@@ -0,0 +1,47 @@
+using System;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Data;
+
+namespace Gestor.Application.Converters
+{
+	public class EqualToCollapsedConverter : IMultiValueConverter
+	{
+		public EqualToCollapsedConverter()
+		{
+		}
+
+		public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
+		{
+			Visibility visibility;
+			object obj = values[0];
+			if (obj is long)
+			{
+				long num = (long)obj;
+				obj = values[1];
+				if (!(obj is long))
+				{
+					visibility = Visibility.Visible;
+					return visibility;
+				}
+				if (num == (long)obj)
+				{
+					visibility = Visibility.Collapsed;
+					return visibility;
+				}
+				else
+				{
+					visibility = Visibility.Visible;
+					return visibility;
+				}
+			}
+			visibility = Visibility.Visible;
+			return visibility;
+		}
+
+		public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/ExcluidoStringConverter.cs b/Codemerx/Gestor.Application/Converters/ExcluidoStringConverter.cs
new file mode 100644
index 0000000..e02410e
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/ExcluidoStringConverter.cs
@@ -0,0 +1,33 @@
+using System;
+using System.Globalization;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class ExcluidoStringConverter : MarkupExtension, IValueConverter
+	{
+		public ExcluidoStringConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value is bool && (bool)value)
+			{
+				return "EXCLUÍDO";
+			}
+			return "";
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/ExcluirVendedorLabelConverter.cs b/Codemerx/Gestor.Application/Converters/ExcluirVendedorLabelConverter.cs
new file mode 100644
index 0000000..e665326
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/ExcluirVendedorLabelConverter.cs
@@ -0,0 +1,33 @@
+using System;
+using System.Globalization;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class ExcluirVendedorLabelConverter : MarkupExtension, IValueConverter
+	{
+		public ExcluirVendedorLabelConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (((DateTime?)value).HasValue)
+			{
+				return "EXCLUIR PAGAMENTO";
+			}
+			return "EXCLUIR VENDEDOR";
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/ExpanderHeaderConverter.cs b/Codemerx/Gestor.Application/Converters/ExpanderHeaderConverter.cs
new file mode 100644
index 0000000..66c167b
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/ExpanderHeaderConverter.cs
@@ -0,0 +1,41 @@
+using System;
+using System.Globalization;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class ExpanderHeaderConverter : MarkupExtension, IValueConverter
+	{
+		public ExpanderHeaderConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value == null)
+			{
+				return "";
+			}
+			if (!(value is bool))
+			{
+				return "";
+			}
+			if (!(bool)value)
+			{
+				return string.Format("MOSTRAR {0}", parameter);
+			}
+			return string.Format("OCULTAR {0}", parameter);
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/ExtensaoVisibilityConverter.cs b/Codemerx/Gestor.Application/Converters/ExtensaoVisibilityConverter.cs
new file mode 100644
index 0000000..6114950
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/ExtensaoVisibilityConverter.cs
@@ -0,0 +1,57 @@
+using System;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Data;
+
+namespace Gestor.Application.Converters
+{
+	public class ExtensaoVisibilityConverter : IMultiValueConverter
+	{
+		public ExtensaoVisibilityConverter()
+		{
+		}
+
+		public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
+		{
+			object obj;
+			try
+			{
+				if (values[0] == null || values[1] == null)
+				{
+					obj = Visibility.Collapsed;
+				}
+				else if (values[0] == null || (long)values[0] <= (long)0)
+				{
+					obj = (values[1].ToString().ToLower() == ".pdf" ? Visibility.Visible : Visibility.Collapsed);
+				}
+				else
+				{
+					obj = Visibility.Collapsed;
+				}
+			}
+			catch (Exception exception)
+			{
+				obj = Visibility.Collapsed;
+			}
+			return obj;
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value == null)
+			{
+				return Visibility.Collapsed;
+			}
+			if (value.ToString().ToLower() != ".pdf")
+			{
+				return Visibility.Collapsed;
+			}
+			return Visibility.Visible;
+		}
+
+		public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/FaturaVisibilityConverter.cs b/Codemerx/Gestor.Application/Converters/FaturaVisibilityConverter.cs
new file mode 100644
index 0000000..7bf7182
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/FaturaVisibilityConverter.cs
@@ -0,0 +1,31 @@
+using Gestor.Model.Common;
+using System;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class FaturaVisibilityConverter : MarkupExtension, IValueConverter
+	{
+		public FaturaVisibilityConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return (value == null || (TipoRecebimento)value != 1 ? Visibility.Visible : Visibility.Collapsed);
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/FilialStringConverter.cs b/Codemerx/Gestor.Application/Converters/FilialStringConverter.cs
new file mode 100644
index 0000000..587602f
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/FilialStringConverter.cs
@@ -0,0 +1,33 @@
+using System;
+using System.Globalization;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class FilialStringConverter : MarkupExtension, IValueConverter
+	{
+		public FilialStringConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value is long && (long)value == (long)1)
+			{
+				return "";
+			}
+			return string.Format("FILIAL {0}", value);
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/IdVisibilityConverter.cs b/Codemerx/Gestor.Application/Converters/IdVisibilityConverter.cs
new file mode 100644
index 0000000..5e30bb6
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/IdVisibilityConverter.cs
@@ -0,0 +1,30 @@
+using System;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class IdVisibilityConverter : MarkupExtension, IValueConverter
+	{
+		public IdVisibilityConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return (value == null || (long)value == 0 ? Visibility.Collapsed : Visibility.Visible);
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/IncluirApoliceEnabledConverter.cs b/Codemerx/Gestor.Application/Converters/IncluirApoliceEnabledConverter.cs
new file mode 100644
index 0000000..ca7628a
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/IncluirApoliceEnabledConverter.cs
@@ -0,0 +1,37 @@
+using System;
+using System.Globalization;
+using System.Windows.Data;
+
+namespace Gestor.Application.Converters
+{
+	public class IncluirApoliceEnabledConverter : IMultiValueConverter
+	{
+		public IncluirApoliceEnabledConverter()
+		{
+		}
+
+		public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (values[0] == null || values[1] == null)
+			{
+				return false;
+			}
+			object obj = values[0];
+			if (obj is bool && !(bool)obj)
+			{
+				return false;
+			}
+			obj = values[1];
+			if (!(obj is bool))
+			{
+				return false;
+			}
+			return (bool)obj;
+		}
+
+		public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/IntToMedalConverter.cs b/Codemerx/Gestor.Application/Converters/IntToMedalConverter.cs
new file mode 100644
index 0000000..f716c62
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/IntToMedalConverter.cs
@@ -0,0 +1,55 @@
+using System;
+using System.Globalization;
+using System.Windows.Data;
+using System.Windows.Markup;
+using System.Windows.Media;
+
+namespace Gestor.Application.Converters
+{
+	public class IntToMedalConverter : MarkupExtension, IValueConverter
+	{
+		public IntToMedalConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value != null)
+			{
+				switch ((int)value)
+				{
+					case 1:
+					{
+						return new SolidColorBrush(Colors.SaddleBrown);
+					}
+					case 2:
+					{
+						return new SolidColorBrush(Colors.Silver);
+					}
+					case 3:
+					{
+						return new SolidColorBrush(Colors.Gold);
+					}
+				}
+			}
+			Color color = new Color()
+			{
+				A = 64,
+				R = 200,
+				G = 200,
+				B = 200
+			};
+			return new SolidColorBrush(color);
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return value;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/IntToMedalTextConverter.cs b/Codemerx/Gestor.Application/Converters/IntToMedalTextConverter.cs
new file mode 100644
index 0000000..71ef1a5
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/IntToMedalTextConverter.cs
@@ -0,0 +1,47 @@
+using System;
+using System.Globalization;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class IntToMedalTextConverter : MarkupExtension, IValueConverter
+	{
+		public IntToMedalTextConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value != null)
+			{
+				switch ((int)value)
+				{
+					case 1:
+					{
+						return "BRONZE";
+					}
+					case 2:
+					{
+						return "PRATA";
+					}
+					case 3:
+					{
+						return "OURO";
+					}
+				}
+			}
+			return "SEM QUALIFICAÇÃO";
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return value;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/IntToVisibilityConverter.cs b/Codemerx/Gestor.Application/Converters/IntToVisibilityConverter.cs
new file mode 100644
index 0000000..a09c136
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/IntToVisibilityConverter.cs
@@ -0,0 +1,35 @@
+using System;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class IntToVisibilityConverter : MarkupExtension, IValueConverter
+	{
+		public IntToVisibilityConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			int num;
+			if (value != null && (!int.TryParse(value.ToString(), out num) || num != 0))
+			{
+				return Visibility.Visible;
+			}
+			return Visibility.Collapsed;
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return value;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/InvertedBoolToGridHeightOneStarConverter.cs b/Codemerx/Gestor.Application/Converters/InvertedBoolToGridHeightOneStarConverter.cs
new file mode 100644
index 0000000..66e7098
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/InvertedBoolToGridHeightOneStarConverter.cs
@@ -0,0 +1,30 @@
+using System;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class InvertedBoolToGridHeightOneStarConverter : MarkupExtension, IValueConverter
+	{
+		public InvertedBoolToGridHeightOneStarConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return (value == null || (bool)value ? new GridLength(0) : new GridLength(1, GridUnitType.Star));
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/IsNamedObjectVisibilityConverter.cs b/Codemerx/Gestor.Application/Converters/IsNamedObjectVisibilityConverter.cs
new file mode 100644
index 0000000..c5ef7b7
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/IsNamedObjectVisibilityConverter.cs
@@ -0,0 +1,77 @@
+using Gestor.Model.Common;
+using Gestor.Model.Domain.Seguros;
+using System;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class IsNamedObjectVisibilityConverter : MarkupExtension, IValueConverter
+	{
+		private static int column;
+
+		private static TipoTela tela;
+
+		public IsNamedObjectVisibilityConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			PermissaoUsuario permissaoUsuario = (PermissaoUsuario)value;
+			Visibility visibility = Visibility.Visible;
+			if (permissaoUsuario.get_Tela() != IsNamedObjectVisibilityConverter.tela)
+			{
+				IsNamedObjectVisibilityConverter.tela = permissaoUsuario.get_Tela();
+				IsNamedObjectVisibilityConverter.column = 1;
+			}
+			TipoTela tela = permissaoUsuario.get_Tela();
+			if (tela != 10)
+			{
+				if (tela - 12 > 1)
+				{
+					if (tela == 18)
+					{
+						if (IsNamedObjectVisibilityConverter.column == 3)
+						{
+							visibility = Visibility.Hidden;
+						}
+						IsNamedObjectVisibilityConverter.column++;
+						return visibility;
+					}
+					IsNamedObjectVisibilityConverter.column++;
+					return visibility;
+				}
+				else if (IsNamedObjectVisibilityConverter.column == 1 || IsNamedObjectVisibilityConverter.column == 3)
+				{
+					visibility = Visibility.Hidden;
+					IsNamedObjectVisibilityConverter.column++;
+					return visibility;
+				}
+				else
+				{
+					IsNamedObjectVisibilityConverter.column++;
+					return visibility;
+				}
+			}
+			if (IsNamedObjectVisibilityConverter.column == 3)
+			{
+				visibility = Visibility.Hidden;
+			}
+			IsNamedObjectVisibilityConverter.column++;
+			return visibility;
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/ManutencaoPagamentoGroupHeaderConverter.cs b/Codemerx/Gestor.Application/Converters/ManutencaoPagamentoGroupHeaderConverter.cs
new file mode 100644
index 0000000..107633f
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/ManutencaoPagamentoGroupHeaderConverter.cs
@@ -0,0 +1,41 @@
+using Gestor.Model.Domain.Ferramentas;
+using System;
+using System.Globalization;
+using System.Reflection;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class ManutencaoPagamentoGroupHeaderConverter : MarkupExtension, IValueConverter
+	{
+		public ManutencaoPagamentoGroupHeaderConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value == null || parameter == null)
+			{
+				return null;
+			}
+			if (!(parameter is string))
+			{
+				return null;
+			}
+			string str = parameter.ToString();
+			ManutencaoPagamentos manutencaoPagamento = (ManutencaoPagamentos)value;
+			return manutencaoPagamento.GetType().GetProperty(str).GetValue(manutencaoPagamento, null);
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/MenosZeroVirgulaZeroUmConverter.cs b/Codemerx/Gestor.Application/Converters/MenosZeroVirgulaZeroUmConverter.cs
new file mode 100644
index 0000000..f230613
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/MenosZeroVirgulaZeroUmConverter.cs
@@ -0,0 +1,57 @@
+using System;
+using System.Globalization;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class MenosZeroVirgulaZeroUmConverter : MarkupExtension, IValueConverter
+	{
+		public MenosZeroVirgulaZeroUmConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			decimal? nullable;
+			decimal? nullable1;
+			decimal? nullable2 = (decimal?)value;
+			decimal num = new decimal(1, 0, 0, false, 2);
+			if (nullable2.HasValue)
+			{
+				nullable1 = new decimal?(nullable2.GetValueOrDefault() - num);
+			}
+			else
+			{
+				nullable = null;
+				nullable1 = nullable;
+			}
+			nullable = nullable1;
+			return nullable.GetValueOrDefault();
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			decimal? nullable;
+			decimal? nullable1;
+			decimal? nullable2 = (decimal?)value;
+			decimal num = new decimal(1, 0, 0, false, 2);
+			if (nullable2.HasValue)
+			{
+				nullable1 = new decimal?(nullable2.GetValueOrDefault() + num);
+			}
+			else
+			{
+				nullable = null;
+				nullable1 = nullable;
+			}
+			nullable = nullable1;
+			return nullable.GetValueOrDefault();
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/MimeIconConverter.cs b/Codemerx/Gestor.Application/Converters/MimeIconConverter.cs
new file mode 100644
index 0000000..a3f0efd
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/MimeIconConverter.cs
@@ -0,0 +1,267 @@
+using ControlzEx;
+using MaterialDesignThemes.Wpf;
+using System;
+using System.Globalization;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class MimeIconConverter : MarkupExtension, IValueConverter
+	{
+		public MimeIconConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			char chr;
+			PackIcon packIcon;
+			PackIcon packIcon1;
+			PackIcon packIcon2;
+			PackIcon packIcon3;
+			PackIcon packIcon4;
+			if (value == null)
+			{
+				PackIcon packIcon5 = new PackIcon();
+				packIcon5.set_Kind(1529);
+				return packIcon5;
+			}
+			string lower = value.ToString().ToLower();
+			if (lower != null)
+			{
+				int length = lower.Length;
+				if (length == 4)
+				{
+					chr = lower[2];
+					if (chr == 'a')
+					{
+						if (lower == ".rar")
+						{
+							packIcon1 = new PackIcon();
+							packIcon1.set_Kind(301);
+							return packIcon1;
+						}
+						packIcon = new PackIcon();
+						packIcon.set_Kind(1529);
+						return packIcon;
+					}
+					else
+					{
+						switch (chr)
+						{
+							case 'd':
+							{
+								if (lower == ".pdf")
+								{
+									PackIcon packIcon6 = new PackIcon();
+									packIcon6.set_Kind(1580);
+									return packIcon6;
+								}
+								packIcon = new PackIcon();
+								packIcon.set_Kind(1529);
+								return packIcon;
+							}
+							case 'e':
+							case 'f':
+							case 'g':
+							case 'h':
+							case 'j':
+							case 'k':
+							{
+								packIcon = new PackIcon();
+								packIcon.set_Kind(1529);
+								return packIcon;
+							}
+							case 'i':
+							{
+								if (lower == ".zip")
+								{
+									break;
+								}
+								packIcon = new PackIcon();
+								packIcon.set_Kind(1529);
+								return packIcon;
+							}
+							case 'l':
+							{
+								if (lower == ".xls")
+								{
+									packIcon2 = new PackIcon();
+									packIcon2.set_Kind(1563);
+									return packIcon2;
+								}
+								packIcon = new PackIcon();
+								packIcon.set_Kind(1529);
+								return packIcon;
+							}
+							case 'm':
+							{
+								if (lower == ".bmp")
+								{
+									packIcon3 = new PackIcon();
+									packIcon3.set_Kind(2102);
+									return packIcon3;
+								}
+								packIcon = new PackIcon();
+								packIcon.set_Kind(1529);
+								return packIcon;
+							}
+							case 'n':
+							{
+								if (lower == ".png")
+								{
+									packIcon3 = new PackIcon();
+									packIcon3.set_Kind(2102);
+									return packIcon3;
+								}
+								packIcon = new PackIcon();
+								packIcon.set_Kind(1529);
+								return packIcon;
+							}
+							case 'o':
+							{
+								if (lower == ".doc")
+								{
+									packIcon4 = new PackIcon();
+									packIcon4.set_Kind(1605);
+									return packIcon4;
+								}
+								packIcon = new PackIcon();
+								packIcon.set_Kind(1529);
+								return packIcon;
+							}
+							case 'p':
+							{
+								if (lower == ".jpg")
+								{
+									packIcon3 = new PackIcon();
+									packIcon3.set_Kind(2102);
+									return packIcon3;
+								}
+								packIcon = new PackIcon();
+								packIcon.set_Kind(1529);
+								return packIcon;
+							}
+							default:
+							{
+								if (chr == 'x')
+								{
+									if (lower == ".txt")
+									{
+										PackIcon packIcon7 = new PackIcon();
+										packIcon7.set_Kind(3399);
+										return packIcon7;
+									}
+									packIcon = new PackIcon();
+									packIcon.set_Kind(1529);
+									return packIcon;
+								}
+								else
+								{
+									packIcon = new PackIcon();
+									packIcon.set_Kind(1529);
+									return packIcon;
+								}
+							}
+						}
+					}
+					packIcon1 = new PackIcon();
+					packIcon1.set_Kind(301);
+					return packIcon1;
+				}
+				else if (length == 5)
+				{
+					chr = lower[2];
+					switch (chr)
+					{
+						case 'l':
+						{
+							if (lower == ".xlsx")
+							{
+								packIcon2 = new PackIcon();
+								packIcon2.set_Kind(1563);
+								return packIcon2;
+							}
+							packIcon = new PackIcon();
+							packIcon.set_Kind(1529);
+							return packIcon;
+						}
+						case 'm':
+						case 'n':
+						{
+							packIcon = new PackIcon();
+							packIcon.set_Kind(1529);
+							return packIcon;
+						}
+						case 'o':
+						{
+							if (lower == ".docx")
+							{
+								packIcon4 = new PackIcon();
+								packIcon4.set_Kind(1605);
+								return packIcon4;
+							}
+							packIcon = new PackIcon();
+							packIcon.set_Kind(1529);
+							return packIcon;
+						}
+						case 'p':
+						{
+							if (lower == ".jpge")
+							{
+								break;
+							}
+							packIcon = new PackIcon();
+							packIcon.set_Kind(1529);
+							return packIcon;
+						}
+						default:
+						{
+							if (chr == 's')
+							{
+								if (lower != ".json")
+								{
+									packIcon = new PackIcon();
+									packIcon.set_Kind(1529);
+									return packIcon;
+								}
+								PackIcon packIcon8 = new PackIcon();
+								packIcon8.set_Kind(2156);
+								return packIcon8;
+							}
+							else
+							{
+								packIcon = new PackIcon();
+								packIcon.set_Kind(1529);
+								return packIcon;
+							}
+						}
+					}
+				}
+				else
+				{
+					packIcon = new PackIcon();
+					packIcon.set_Kind(1529);
+					return packIcon;
+				}
+				packIcon3 = new PackIcon();
+				packIcon3.set_Kind(2102);
+				return packIcon3;
+			}
+			packIcon = new PackIcon();
+			packIcon.set_Kind(1529);
+			return packIcon;
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/ModeloExisteTooltipConverter.cs b/Codemerx/Gestor.Application/Converters/ModeloExisteTooltipConverter.cs
new file mode 100644
index 0000000..01d12cb
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/ModeloExisteTooltipConverter.cs
@@ -0,0 +1,37 @@
+using System;
+using System.Globalization;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class ModeloExisteTooltipConverter : MarkupExtension, IValueConverter
+	{
+		public ModeloExisteTooltipConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value == null)
+			{
+				return "NEM TODOS OS DOCUMENTOS SELECIONADOS\nPARA ENVIO POSSUEM AS VARIÁVEIS DESSE MODELO";
+			}
+			if (!(bool)value)
+			{
+				return "TODOS OS DOCUMENTOS SELECIONADOS PARA\nENVIO POSSUEM AS VARIÁVEIS DESSE MODELO";
+			}
+			return "NEM TODOS OS DOCUMENTOS SELECIONADOS\nPARA ENVIO POSSUEM AS VARIÁVEIS DESSE MODELO";
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/MultiBoolReadOnly.cs b/Codemerx/Gestor.Application/Converters/MultiBoolReadOnly.cs
new file mode 100644
index 0000000..3bd7f40
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/MultiBoolReadOnly.cs
@@ -0,0 +1,35 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Windows.Data;
+
+namespace Gestor.Application.Converters
+{
+	public class MultiBoolReadOnly : IMultiValueConverter
+	{
+		public MultiBoolReadOnly()
+		{
+		}
+
+		public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
+		{
+			object obj;
+			try
+			{
+				obj = !((IEnumerable)values).All((object value) => (bool)value);
+			}
+			catch
+			{
+				obj = false;
+			}
+			return obj;
+		}
+
+		public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/MultiBoolToVisibilityConverter.cs b/Codemerx/Gestor.Application/Converters/MultiBoolToVisibilityConverter.cs
new file mode 100644
index 0000000..710de71
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/MultiBoolToVisibilityConverter.cs
@@ -0,0 +1,36 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Windows;
+using System.Windows.Data;
+
+namespace Gestor.Application.Converters
+{
+	public class MultiBoolToVisibilityConverter : IMultiValueConverter
+	{
+		public MultiBoolToVisibilityConverter()
+		{
+		}
+
+		public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
+		{
+			object obj;
+			try
+			{
+				obj = (((IEnumerable)values).All((object value) => (bool)value) ? Visibility.Visible : Visibility.Collapsed);
+			}
+			catch
+			{
+				obj = false;
+			}
+			return obj;
+		}
+
+		public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/MultiVisibilityConverter.cs b/Codemerx/Gestor.Application/Converters/MultiVisibilityConverter.cs
new file mode 100644
index 0000000..1e5f09b
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/MultiVisibilityConverter.cs
@@ -0,0 +1,36 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Windows;
+using System.Windows.Data;
+
+namespace Gestor.Application.Converters
+{
+	public class MultiVisibilityConverter : IMultiValueConverter
+	{
+		public MultiVisibilityConverter()
+		{
+		}
+
+		public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
+		{
+			object obj;
+			try
+			{
+				obj = (((IEnumerable)values).All((object value) => (Visibility)value == Visibility.Visible) ? Visibility.Visible : Visibility.Collapsed);
+			}
+			catch
+			{
+				obj = false;
+			}
+			return obj;
+		}
+
+		public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/NullToFalseConverter.cs b/Codemerx/Gestor.Application/Converters/NullToFalseConverter.cs
new file mode 100644
index 0000000..23186f6
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/NullToFalseConverter.cs
@@ -0,0 +1,33 @@
+using System;
+using System.Globalization;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class NullToFalseConverter : MarkupExtension, IValueConverter
+	{
+		public NullToFalseConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value == null)
+			{
+				return false;
+			}
+			return true;
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return value;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/NullToTrueConverter.cs b/Codemerx/Gestor.Application/Converters/NullToTrueConverter.cs
new file mode 100644
index 0000000..c75c2d5
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/NullToTrueConverter.cs
@@ -0,0 +1,37 @@
+using System;
+using System.Globalization;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class NullToTrueConverter : MarkupExtension, IValueConverter
+	{
+		public NullToTrueConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value == null)
+			{
+				return true;
+			}
+			return (bool)value;
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value == null)
+			{
+				return true;
+			}
+			return (bool)value;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/PackIconToImage.cs b/Codemerx/Gestor.Application/Converters/PackIconToImage.cs
new file mode 100644
index 0000000..ffccc97
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/PackIconToImage.cs
@@ -0,0 +1,41 @@
+using ControlzEx;
+using MaterialDesignThemes.Wpf;
+using System;
+using System.Windows.Media;
+
+namespace Gestor.Application.Converters
+{
+	public class PackIconToImage
+	{
+		public PackIconToImage()
+		{
+		}
+
+		public static ImageSource CreateImageSource(object value, Brush foregroundBrush, double penThickness)
+		{
+			PackIcon packIcon;
+			if (value.GetType() == typeof(PackIconKind))
+			{
+				packIcon = new PackIcon();
+				packIcon.set_Kind((PackIconKind)value);
+			}
+			else
+			{
+				packIcon = (PackIcon)value;
+			}
+			PackIcon packIcon1 = packIcon;
+			GeometryDrawing geometryDrawing = new GeometryDrawing()
+			{
+				Geometry = Geometry.Parse(packIcon1.get_Data()),
+				Brush = foregroundBrush,
+				Pen = new Pen(foregroundBrush, penThickness)
+			};
+			DrawingGroup drawingGroup = new DrawingGroup();
+			drawingGroup.Children.Add(geometryDrawing);
+			return new DrawingImage()
+			{
+				Drawing = drawingGroup
+			};
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/PackIconToImageConverter.cs b/Codemerx/Gestor.Application/Converters/PackIconToImageConverter.cs
new file mode 100644
index 0000000..4ded51c
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/PackIconToImageConverter.cs
@@ -0,0 +1,39 @@
+using System;
+using System.Globalization;
+using System.Runtime.CompilerServices;
+using System.Windows.Data;
+using System.Windows.Markup;
+using System.Windows.Media;
+
+namespace Gestor.Application.Converters
+{
+	public class PackIconToImageConverter : MarkupExtension, IValueConverter
+	{
+		public System.Windows.Media.Brush Brush { get; set; } = Brushes.White;
+
+		public double Thickness { get; set; } = 0.25;
+
+		public PackIconToImageConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value == null)
+			{
+				return null;
+			}
+			return PackIconToImage.CreateImageSource(value, this.Brush, this.Thickness);
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/RamoToImageConverter.cs b/Codemerx/Gestor.Application/Converters/RamoToImageConverter.cs
new file mode 100644
index 0000000..1fca8b2
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/RamoToImageConverter.cs
@@ -0,0 +1,214 @@
+using MaterialDesignThemes.Wpf;
+using System;
+using System.Globalization;
+using System.Runtime.CompilerServices;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class RamoToImageConverter : MarkupExtension, IValueConverter
+	{
+		public double Thickness { get; set; } = 0.25;
+
+		public RamoToImageConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value == null)
+			{
+				return null;
+			}
+			long num = (long)value - (long)1;
+			if (num <= (long)61)
+			{
+				switch ((uint)num)
+				{
+					case 0:
+					case 2:
+					case 14:
+					case 17:
+					{
+						return (PackIconKind)2040;
+					}
+					case 1:
+					{
+						return (PackIconKind)1515;
+					}
+					case 4:
+					{
+						return (PackIconKind)794;
+					}
+					case 5:
+					case 8:
+					case 60:
+					{
+						return (PackIconKind)2010;
+					}
+					case 6:
+					case 9:
+					case 11:
+					case 52:
+					{
+						return (PackIconKind)33;
+					}
+					case 7:
+					case 15:
+					case 48:
+					{
+						return (PackIconKind)3514;
+					}
+					case 10:
+					case 31:
+					{
+						return (PackIconKind)25;
+					}
+					case 12:
+					case 22:
+					{
+						return (PackIconKind)77;
+					}
+					case 13:
+					{
+						return (PackIconKind)3;
+					}
+					case 16:
+					{
+						return (PackIconKind)3012;
+					}
+					case 18:
+					case 26:
+					case 28:
+					case 30:
+					case 40:
+					case 58:
+					{
+						return (PackIconKind)4;
+					}
+					case 19:
+					{
+						return (PackIconKind)3694;
+					}
+					case 20:
+					case 21:
+					case 41:
+					{
+						return (PackIconKind)859;
+					}
+					case 23:
+					{
+						return (PackIconKind)720;
+					}
+					case 24:
+					{
+						return (PackIconKind)844;
+					}
+					case 25:
+					{
+						return (PackIconKind)1528;
+					}
+					case 27:
+					case 55:
+					{
+						return (PackIconKind)3762;
+					}
+					case 29:
+					{
+						return (PackIconKind)2756;
+					}
+					case 32:
+					case 43:
+					case 53:
+					{
+						return (PackIconKind)3248;
+					}
+					case 33:
+					{
+						return (PackIconKind)2680;
+					}
+					case 34:
+					{
+						return (PackIconKind)1616;
+					}
+					case 35:
+					{
+						return (PackIconKind)41;
+					}
+					case 36:
+					{
+						return (PackIconKind)705;
+					}
+					case 37:
+					{
+						return (PackIconKind)920;
+					}
+					case 38:
+					{
+						return (PackIconKind)1462;
+					}
+					case 39:
+					{
+						return (PackIconKind)1013;
+					}
+					case 42:
+					{
+						return (PackIconKind)3372;
+					}
+					case 44:
+					{
+						return (PackIconKind)88;
+					}
+					case 45:
+					{
+						return (PackIconKind)3464;
+					}
+					case 46:
+					{
+						return (PackIconKind)3465;
+					}
+					case 47:
+					case 56:
+					{
+						return (PackIconKind)870;
+					}
+					case 50:
+					{
+						return (PackIconKind)3040;
+					}
+					case 51:
+					{
+						return (PackIconKind)2433;
+					}
+					case 54:
+					{
+						return (PackIconKind)2719;
+					}
+					case 57:
+					{
+						return (PackIconKind)1101;
+					}
+					case 61:
+					{
+						return (PackIconKind)450;
+					}
+				}
+			}
+			else
+			{
+			}
+			return (PackIconKind)196;
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/ResultadoToBoolConverter.cs b/Codemerx/Gestor.Application/Converters/ResultadoToBoolConverter.cs
new file mode 100644
index 0000000..4f25d95
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/ResultadoToBoolConverter.cs
@@ -0,0 +1,35 @@
+using Gestor.Model.Domain.Common;
+using System;
+using System.Globalization;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class ResultadoToBoolConverter : MarkupExtension, IValueConverter
+	{
+		public ResultadoToBoolConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value == null)
+			{
+				return false;
+			}
+			PesquisaAvancada pesquisaAvancada = (PesquisaAvancada)value;
+			return (pesquisaAvancada.get_IdCliente() != 0 || pesquisaAvancada.get_IdDocumento() != 0 || pesquisaAvancada.get_IdItem() != 0 || pesquisaAvancada.get_IdSinistro() != 0 || !string.IsNullOrWhiteSpace(pesquisaAvancada.get_Nome()) ? true : !string.IsNullOrWhiteSpace(pesquisaAvancada.get_Pesquisa()));
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return value;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/StatusComissaoAutomaticaTooltipConverter.cs b/Codemerx/Gestor.Application/Converters/StatusComissaoAutomaticaTooltipConverter.cs
new file mode 100644
index 0000000..67b2207
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/StatusComissaoAutomaticaTooltipConverter.cs
@@ -0,0 +1,115 @@
+using Gestor.Model.Common;
+using System;
+using System.Globalization;
+using System.Windows.Data;
+
+namespace Gestor.Application.Converters
+{
+	public class StatusComissaoAutomaticaTooltipConverter : IValueConverter
+	{
+		public StatusComissaoAutomaticaTooltipConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (!(value is StatusParcela))
+			{
+				return null;
+			}
+			switch ((StatusParcela)value)
+			{
+				case 1:
+				{
+					return "";
+				}
+				case 2:
+				{
+					return "CLIENTE NÃO CADASTRADO NO SISTEMA OU DIVERGÊNCIA NO NÚMERO DA APÓLICE";
+				}
+				case 3:
+				{
+					return "O NÚMERO DA PARCELA NÃO FOI LOCALIZADO NO SISTEMA";
+				}
+				case 4:
+				{
+					return "OCORRE ANTES DE BAIXAR O EXTRATO, QUANDO O PERCENTUAL DE COMISSÃO CADASTRADO NA APÓLICE É DIFERENTE DO INFORMADO NO EXTRATO";
+				}
+				case 5:
+				{
+					return "A PARCELA JÁ FOI BAIXADA MANUALMENTE; O SISTEMA CONFERE A DATA DE RECEBIMENTO";
+				}
+				case 6:
+				{
+					return "O USUÁRIO OPTOU POR NÃO REALIZAR MANUTENÇÃO";
+				}
+				case 7:
+				{
+					return "É NECESSÁRIO FAZER MANUTENÇÃO NAS PARCELAS ANTERIORES";
+				}
+				case 8:
+				{
+					return "O SISTEMA DESCONSIDERA QUANDO NÃO EXISTE VALOR DE COMISSÃO NA PARCELA";
+				}
+				case 9:
+				{
+					return "NÃO HÁ MANUTENÇÃO PENDENTE, APENAS REALIZAR A BAIXA";
+				}
+				case 10:
+				{
+					return "OCORRE APÓS A BAIXA DO EXTRATO, MESMO HAVENDO DIFERENÇA NO PERCENTUAL DE COMISSÃO";
+				}
+				case 11:
+				{
+					return "APÓLICES COM NÚMEROS SIMILARES LOCALIZADAS NO SISTEMA";
+				}
+				case 12:
+				{
+					return "INDICA QUE O EXTRATO FOI BAIXADO MANUALMENTE NO SISTEMA";
+				}
+				case 13:
+				{
+					return "FOI NECESSÁRIO LOCALIZAR O CLIENTE OU DOCUMENTO POR MEIO DA CRÍTICA PARA REALIZAR A BAIXA DA PARCELA";
+				}
+				case 14:
+				{
+					return "";
+				}
+				case 15:
+				{
+					return "O NÚMERO DA FATURA NÃO FOI LOCALIZADO NO SISTEMA";
+				}
+				case 16:
+				{
+					return "O SISTEMA TENTARÁ REALIZAR A BAIXA POR APROXIMAÇÃO, ATRAVÉS DO N° DA APÓLICE";
+				}
+				case 17:
+				{
+					return "HÁ PARCELA NO EXTRATO SEM VÍNCULO; IRÁ SER CRIADA AUTOMATICAMENTE";
+				}
+				case 18:
+				{
+					return "";
+				}
+				case 19:
+				{
+					return "O CAMPO DE COMISSÃO ESTÁ EM BRANCO";
+				}
+				case 20:
+				{
+					return "A FATURA CRIADA POSSUI O CAMPO DE COMISSÃO EM BRANCO";
+				}
+				case 21:
+				{
+					return "INDICA QUE A PARCELA ESPECIAL CRIADA JÁ HAVIA SIDO BAIXADA ANTERIORMENTE";
+				}
+			}
+			return "";
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return Binding.DoNothing;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/StatusIconConverter.cs b/Codemerx/Gestor.Application/Converters/StatusIconConverter.cs
new file mode 100644
index 0000000..9717cea
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/StatusIconConverter.cs
@@ -0,0 +1,80 @@
+using Gestor.Model.Common;
+using Gestor.Model.Validation;
+using MaterialDesignThemes.Wpf;
+using System;
+using System.Globalization;
+using System.Windows.Data;
+using System.Windows.Media;
+
+namespace Gestor.Application.Converters
+{
+	public class StatusIconConverter : IMultiValueConverter
+	{
+		public StatusIconConverter()
+		{
+		}
+
+		public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
+		{
+			PackIconKind packIconKind;
+			if (values[2] != null && values[2] is bool && (bool)values[2])
+			{
+				return (PackIconKind)1280;
+			}
+			object obj = values[0];
+			if (obj == null)
+			{
+				return (PackIconKind)1543;
+			}
+			if (!(obj is TipoSeguro))
+			{
+				return new SolidColorBrush(Colors.White);
+			}
+			switch ((TipoSeguro)values[0])
+			{
+				case 3:
+				{
+					return (PackIconKind)1058;
+				}
+				case 5:
+				{
+					return (PackIconKind)2901;
+				}
+				case 6:
+				{
+					return (PackIconKind)1554;
+				}
+				case 7:
+				{
+					return (PackIconKind)789;
+				}
+				default:
+				{
+					if (values[1] == null)
+					{
+						packIconKind = 1545;
+						return packIconKind;
+					}
+					else
+					{
+						break;
+					}
+				}
+			}
+			DateTime? nullable = (DateTime?)values[1];
+			DateTime dateTime = Funcoes.GetNetworkTime().Date.AddDays(-6);
+			if ((nullable.HasValue ? nullable.GetValueOrDefault() < dateTime : true))
+			{
+				packIconKind = 1044;
+				return packIconKind;
+			}
+			packIconKind = 1545;
+			return packIconKind;
+		}
+
+		public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/StatusPagamentoColorConverter.cs b/Codemerx/Gestor.Application/Converters/StatusPagamentoColorConverter.cs
new file mode 100644
index 0000000..92ab9ba
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/StatusPagamentoColorConverter.cs
@@ -0,0 +1,40 @@
+using Gestor.Model.Common;
+using System;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Data;
+using System.Windows.Markup;
+using System.Windows.Media;
+
+namespace Gestor.Application.Converters
+{
+	public class StatusPagamentoColorConverter : MarkupExtension, IValueConverter
+	{
+		public StatusPagamentoColorConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value == null || (StatusPagamento)value == null)
+			{
+				return new SolidColorBrush(Colors.Gray);
+			}
+			if ((StatusPagamento)value != 2)
+			{
+				return new SolidColorBrush(Colors.Red);
+			}
+			return new SolidColorBrush((Color)System.Windows.Application.Current.Resources["AggerBlue"]);
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/StatusPagamentoVisibilityConverter.cs b/Codemerx/Gestor.Application/Converters/StatusPagamentoVisibilityConverter.cs
new file mode 100644
index 0000000..7b17fdd
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/StatusPagamentoVisibilityConverter.cs
@@ -0,0 +1,35 @@
+using Gestor.Model.Common;
+using System;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class StatusPagamentoVisibilityConverter : MarkupExtension, IValueConverter
+	{
+		public StatusPagamentoVisibilityConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value == null)
+			{
+				return Visibility.Collapsed;
+			}
+			return ((StatusPagamento)value == null ? Visibility.Collapsed : Visibility.Visible);
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/StringToFontWeightConverter.cs b/Codemerx/Gestor.Application/Converters/StringToFontWeightConverter.cs
new file mode 100644
index 0000000..40ca721
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/StringToFontWeightConverter.cs
@@ -0,0 +1,34 @@
+using System;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class StringToFontWeightConverter : MarkupExtension, IValueConverter
+	{
+		public StringToFontWeightConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value != null && ((string)value).Contains("$"))
+			{
+				return FontWeights.Bold;
+			}
+			return FontWeights.SemiBold;
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return value;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/StringToStringFontWeightCleanConverter.cs b/Codemerx/Gestor.Application/Converters/StringToStringFontWeightCleanConverter.cs
new file mode 100644
index 0000000..c738ba9
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/StringToStringFontWeightCleanConverter.cs
@@ -0,0 +1,33 @@
+using System;
+using System.Globalization;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class StringToStringFontWeightCleanConverter : MarkupExtension, IValueConverter
+	{
+		public StringToStringFontWeightCleanConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value == null || !((string)value).Contains("$"))
+			{
+				return (string)value;
+			}
+			return ((string)value).Replace("$", "");
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return value;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/SubTipoEnableConverter.cs b/Codemerx/Gestor.Application/Converters/SubTipoEnableConverter.cs
new file mode 100644
index 0000000..53d4698
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/SubTipoEnableConverter.cs
@@ -0,0 +1,30 @@
+using Gestor.Model.Common;
+using System;
+using System.Globalization;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class SubTipoEnableConverter : MarkupExtension, IValueConverter
+	{
+		public SubTipoEnableConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return (value == null ? false : (SubTipo)value != 1);
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return value;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/TelaRelatorioConverter.cs b/Codemerx/Gestor.Application/Converters/TelaRelatorioConverter.cs
new file mode 100644
index 0000000..0104b98
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/TelaRelatorioConverter.cs
@@ -0,0 +1,41 @@
+using Gestor.Common.Validation;
+using Gestor.Model.Common;
+using System;
+using System.Globalization;
+using System.Windows.Data;
+
+namespace Gestor.Application.Converters
+{
+	public class TelaRelatorioConverter : IMultiValueConverter
+	{
+		public TelaRelatorioConverter()
+		{
+		}
+
+		public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
+		{
+			object obj;
+			try
+			{
+				if (values != null)
+				{
+					obj = (values[0] == null ? ValidationHelper.GetDescription((Relatorio)values[1]) : ValidationHelper.GetDescription((TipoTela)values[0]));
+				}
+				else
+				{
+					obj = "";
+				}
+			}
+			catch
+			{
+				obj = "";
+			}
+			return obj;
+		}
+
+		public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/TelefoneToVisibilityConverter.cs b/Codemerx/Gestor.Application/Converters/TelefoneToVisibilityConverter.cs
new file mode 100644
index 0000000..5eeca33
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/TelefoneToVisibilityConverter.cs
@@ -0,0 +1,35 @@
+using System;
+using System.Globalization;
+using System.Text.RegularExpressions;
+using System.Windows;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class TelefoneToVisibilityConverter : MarkupExtension, IValueConverter
+	{
+		public TelefoneToVisibilityConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value == null || (string)value == "")
+			{
+				return Visibility.Visible;
+			}
+			return (Regex.Match((string)value, "^[0-9]{4} [0-9]{3} [0-9]{4}$").Success ? Visibility.Collapsed : Visibility.Visible);
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return value;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/TextInputToVisibilityConverter.cs b/Codemerx/Gestor.Application/Converters/TextInputToVisibilityConverter.cs
new file mode 100644
index 0000000..820e24a
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/TextInputToVisibilityConverter.cs
@@ -0,0 +1,36 @@
+using System;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Data;
+
+namespace Gestor.Application.Converters
+{
+	public class TextInputToVisibilityConverter : IMultiValueConverter
+	{
+		public TextInputToVisibilityConverter()
+		{
+		}
+
+		public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (values[0] == null && values[1] is bool && (bool)values[1])
+			{
+				return Visibility.Collapsed;
+			}
+			if (values[0] is string && values[1] is bool)
+			{
+				bool flag = !string.IsNullOrEmpty((string)values[0]);
+				if ((bool)values[1] | flag)
+				{
+					return Visibility.Collapsed;
+				}
+			}
+			return Visibility.Visible;
+		}
+
+		public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
+		{
+			throw new NotImplementedException();
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/TipoDependenteToVisibilityConverter.cs b/Codemerx/Gestor.Application/Converters/TipoDependenteToVisibilityConverter.cs
new file mode 100644
index 0000000..3039f18
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/TipoDependenteToVisibilityConverter.cs
@@ -0,0 +1,35 @@
+using Gestor.Model.Common;
+using System;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class TipoDependenteToVisibilityConverter : MarkupExtension, IValueConverter
+	{
+		public TipoDependenteToVisibilityConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value == null)
+			{
+				return Visibility.Collapsed;
+			}
+			return ((TipoTitular)value == 2 ? Visibility.Visible : Visibility.Collapsed);
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return value;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/TipoEmailVisibilityConverter.cs b/Codemerx/Gestor.Application/Converters/TipoEmailVisibilityConverter.cs
new file mode 100644
index 0000000..b382d5e
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/TipoEmailVisibilityConverter.cs
@@ -0,0 +1,31 @@
+using Gestor.Model.Common;
+using System;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class TipoEmailVisibilityConverter : MarkupExtension, IValueConverter
+	{
+		public TipoEmailVisibilityConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return (value == null || (TipoEmail)value == null ? Visibility.Visible : Visibility.Collapsed);
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/TipoRepasseGlobalFilterConverter.cs b/Codemerx/Gestor.Application/Converters/TipoRepasseGlobalFilterConverter.cs
new file mode 100644
index 0000000..37e73c5
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/TipoRepasseGlobalFilterConverter.cs
@@ -0,0 +1,41 @@
+using Gestor.Application.Helpers;
+using Gestor.Model.Attributes;
+using Gestor.Model.Common;
+using Gestor.Model.Domain.Configuracoes;
+using System;
+using System.Globalization;
+using System.Linq;
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Windows.Data;
+
+namespace Gestor.Application.Converters
+{
+	public class TipoRepasseGlobalFilterConverter : IValueConverter
+	{
+		public TipoRepasseGlobalFilterConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			bool flag = Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 56);
+			return Enum.GetValues(typeof(TipoRepasse)).Cast().Where((TipoRepasse tipo) => {
+				object obj;
+				FieldInfo field = typeof(TipoRepasse).GetField(tipo.ToString());
+				obj = (field != null ? field.GetCustomAttributes(typeof(TipoAttribute), false).FirstOrDefault() : null);
+				TipoAttribute tipoAttribute = obj as TipoAttribute;
+				if ((tipoAttribute != null ? tipoAttribute.get_Tipo() : null) == "0")
+				{
+					return true;
+				}
+				return ((tipoAttribute != null ? tipoAttribute.get_Tipo() : null) == "1") & flag;
+			}).ToList();
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			throw new NotImplementedException();
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/TipoRepasseVendedorVisibilityConverter.cs b/Codemerx/Gestor.Application/Converters/TipoRepasseVendedorVisibilityConverter.cs
new file mode 100644
index 0000000..fc9fc1c
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/TipoRepasseVendedorVisibilityConverter.cs
@@ -0,0 +1,152 @@
+using Gestor.Application.Helpers;
+using Gestor.Model.Domain.Configuracoes;
+using System;
+using System.Globalization;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Windows;
+using System.Windows.Data;
+
+namespace Gestor.Application.Converters
+{
+	public class TipoRepasseVendedorVisibilityConverter : IMultiValueConverter
+	{
+		public TipoRepasseVendedorVisibilityConverter()
+		{
+		}
+
+		public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
+		{
+			char chr;
+			object obj;
+			Visibility visibility;
+			if (parameter == null || values == null)
+			{
+				return Visibility.Collapsed;
+			}
+			string lower = parameter.ToString().ToLower();
+			if (values.Count() != 0)
+			{
+				obj = values[0];
+			}
+			else
+			{
+				obj = false;
+			}
+			object obj1 = obj;
+			if (lower != null)
+			{
+				int length = lower.Length;
+				switch (length)
+				{
+					case 15:
+					{
+						chr = lower[0];
+						switch (chr)
+						{
+							case 'r':
+							{
+								if (lower == "repassevendedor")
+								{
+									visibility = (!(obj1 is bool) || !(bool)obj1 ? Visibility.Visible : Visibility.Collapsed);
+									return visibility;
+								}
+								return Visibility.Visible;
+							}
+							case 's':
+							case 'u':
+							{
+								return Visibility.Visible;
+							}
+							case 't':
+							{
+								if (lower == "tipovendedorbox")
+								{
+									visibility = (!(obj1 is bool) || !(bool)obj1 ? Visibility.Visible : Visibility.Collapsed);
+									return visibility;
+								}
+								return Visibility.Visible;
+							}
+							case 'v':
+							{
+								if (lower == "valorrepassebox")
+								{
+									visibility = (!(obj1 is bool) || !(bool)obj1 ? Visibility.Visible : Visibility.Collapsed);
+									return visibility;
+								}
+								return Visibility.Visible;
+							}
+							default:
+							{
+								return Visibility.Visible;
+							}
+						}
+						break;
+					}
+					case 16:
+					{
+						if (lower == "formarecebidabox")
+						{
+							break;
+						}
+						else
+						{
+							return Visibility.Visible;
+						}
+					}
+					case 17:
+					{
+						return Visibility.Visible;
+					}
+					case 18:
+					{
+						chr = lower[0];
+						if (chr == 'c')
+						{
+							if (lower == "cocorretagemtoogle")
+							{
+								return (Recursos.Configuracoes.Any((ConfiguracaoSistema config) => config.get_Configuracao() == 56) ? Visibility.Visible : Visibility.Collapsed);
+							}
+							return Visibility.Visible;
+						}
+						else if (chr == 'f')
+						{
+							if (lower == "formaincidenciabox")
+							{
+								break;
+							}
+							return Visibility.Visible;
+						}
+						else
+						{
+							return Visibility.Visible;
+						}
+					}
+					default:
+					{
+						if (length == 25)
+						{
+							if (lower == "comissaorenovacaocombobox")
+							{
+								break;
+							}
+							return Visibility.Visible;
+						}
+						else
+						{
+							return Visibility.Visible;
+						}
+					}
+				}
+				visibility = (!(obj1 is bool) || !(bool)obj1 ? Visibility.Visible : Visibility.Collapsed);
+				return visibility;
+			}
+			return Visibility.Visible;
+		}
+
+		public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/TipoRepasseVisibilityConverter.cs b/Codemerx/Gestor.Application/Converters/TipoRepasseVisibilityConverter.cs
new file mode 100644
index 0000000..4df37ee
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/TipoRepasseVisibilityConverter.cs
@@ -0,0 +1,56 @@
+using Gestor.Model.Common;
+using System;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Data;
+
+namespace Gestor.Application.Converters
+{
+	public class TipoRepasseVisibilityConverter : IMultiValueConverter
+	{
+		public TipoRepasseVisibilityConverter()
+		{
+		}
+
+		public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (parameter == null || values == null)
+			{
+				return Visibility.Collapsed;
+			}
+			TipoRepasse tipoRepasse = (TipoRepasse)values[0];
+			FormaRepasse formaRepasse = (FormaRepasse)values[1];
+			string lower = parameter.ToString().ToLower();
+			if (lower == "incidenciabox")
+			{
+				return (tipoRepasse == 2 ? Visibility.Visible : Visibility.Collapsed);
+			}
+			if (lower == "basepagtobox")
+			{
+				return ((tipoRepasse != 1 || formaRepasse == 1) && formaRepasse != 2 && formaRepasse != 3 || tipoRepasse == 3 ? Visibility.Collapsed : Visibility.Visible);
+			}
+			if (lower == "formapagtobox")
+			{
+				return (tipoRepasse == 3 ? Visibility.Collapsed : Visibility.Visible);
+			}
+			if (lower == "valorbox")
+			{
+				return (tipoRepasse == 3 ? Visibility.Collapsed : Visibility.Visible);
+			}
+			if (lower == "renovacoesbox")
+			{
+				return (tipoRepasse == 3 ? Visibility.Collapsed : Visibility.Visible);
+			}
+			if (lower != "cocorretagembox")
+			{
+				return Visibility.Visible;
+			}
+			return (tipoRepasse == 3 ? Visibility.Visible : Visibility.Collapsed);
+		}
+
+		public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/TipoSinistroConverter.cs b/Codemerx/Gestor.Application/Converters/TipoSinistroConverter.cs
new file mode 100644
index 0000000..c965cdc
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/TipoSinistroConverter.cs
@@ -0,0 +1,30 @@
+using Gestor.Model.Common;
+using System;
+using System.Globalization;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class TipoSinistroConverter : MarkupExtension, IValueConverter
+	{
+		public TipoSinistroConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return (value == null ? true : (TipoSinistro)value != 0);
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/TipoTelefoneVisibilityConverter.cs b/Codemerx/Gestor.Application/Converters/TipoTelefoneVisibilityConverter.cs
new file mode 100644
index 0000000..795bec4
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/TipoTelefoneVisibilityConverter.cs
@@ -0,0 +1,35 @@
+using Gestor.Model.Common;
+using System;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class TipoTelefoneVisibilityConverter : MarkupExtension, IValueConverter
+	{
+		public TipoTelefoneVisibilityConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value != null && ((TipoTelefone)value == 9 || (TipoTelefone)value == 3 || (TipoTelefone)value == 2 || (TipoTelefone)value == 5 || (TipoTelefone)value == 1))
+			{
+				return Visibility.Visible;
+			}
+			return Visibility.Collapsed;
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/TootipStatusConverter.cs b/Codemerx/Gestor.Application/Converters/TootipStatusConverter.cs
new file mode 100644
index 0000000..63a9bba
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/TootipStatusConverter.cs
@@ -0,0 +1,75 @@
+using Gestor.Model.Common;
+using Gestor.Model.Validation;
+using System;
+using System.Globalization;
+using System.Windows.Data;
+using System.Windows.Media;
+
+namespace Gestor.Application.Converters
+{
+	public class TootipStatusConverter : IMultiValueConverter
+	{
+		public TootipStatusConverter()
+		{
+		}
+
+		public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (values[2] != null && values[2] is bool && (bool)values[2])
+			{
+				return "DOCUMENTO EXCLUÍDO";
+			}
+			object obj = values[0];
+			if (obj == null)
+			{
+				return "";
+			}
+			if (!(obj is TipoSeguro))
+			{
+				return new SolidColorBrush(Colors.White);
+			}
+			switch ((TipoSeguro)values[0])
+			{
+				case 3:
+				{
+					return "DOCUMENTO CANCELADO";
+				}
+				case 5:
+				{
+					return "DOCUMENTO RENOVADO";
+				}
+				case 6:
+				{
+					return "DOCUMENTO PERDIDO";
+				}
+				case 7:
+				{
+					return "DOCUMENTO RECUSADO";
+				}
+				default:
+				{
+					if (values[1] == null)
+					{
+						return "DOCUMENTO VIGENTE";
+					}
+					else
+					{
+						break;
+					}
+				}
+			}
+			DateTime? nullable = (DateTime?)values[1];
+			DateTime dateTime = Funcoes.GetNetworkTime().Date.AddDays(-6);
+			if ((nullable.HasValue ? nullable.GetValueOrDefault() < dateTime : true))
+			{
+				return "DOCUMENTO VENCIDO";
+			}
+			return "DOCUMENTO VIGENTE";
+		}
+
+		public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/TypeVisibilityConverter.cs b/Codemerx/Gestor.Application/Converters/TypeVisibilityConverter.cs
new file mode 100644
index 0000000..5ba5b06
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/TypeVisibilityConverter.cs
@@ -0,0 +1,33 @@
+using System;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Data;
+
+namespace Gestor.Application.Converters
+{
+	public class TypeVisibilityConverter : IMultiValueConverter
+	{
+		public TypeVisibilityConverter()
+		{
+		}
+
+		public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
+		{
+			object obj;
+			try
+			{
+				obj = (values[0] == null || values[1] == null ? Visibility.Collapsed : ((Type)values[0] == (Type)values[1] ? Visibility.Visible : Visibility.Collapsed));
+			}
+			catch (Exception exception)
+			{
+				obj = Visibility.Collapsed;
+			}
+			return obj;
+		}
+
+		public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/ValorTipoConverter.cs b/Codemerx/Gestor.Application/Converters/ValorTipoConverter.cs
new file mode 100644
index 0000000..3566d8f
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/ValorTipoConverter.cs
@@ -0,0 +1,47 @@
+using System;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class ValorTipoConverter : MarkupExtension, IMultiValueConverter
+	{
+		public ValorTipoConverter()
+		{
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+
+		object System.Windows.Data.IMultiValueConverter.Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (values == null || values[1] == null || values[0] == DependencyProperty.UnsetValue)
+			{
+				return null;
+			}
+			if (values[0] == null)
+			{
+				return values[1].ToString();
+			}
+			string str = values[0].ToString();
+			if (str == "VALOR")
+			{
+				return ((decimal)values[1]).ToString("c2");
+			}
+			if (str != "PERCENTUAL")
+			{
+				return values[1].ToString();
+			}
+			return ((decimal)values[1]).ToString("p2");
+		}
+
+		object[] System.Windows.Data.IMultiValueConverter.ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
+		{
+			throw new NotImplementedException();
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/VariavelExisteColorConverter.cs b/Codemerx/Gestor.Application/Converters/VariavelExisteColorConverter.cs
new file mode 100644
index 0000000..8f7510c
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/VariavelExisteColorConverter.cs
@@ -0,0 +1,38 @@
+using System;
+using System.Globalization;
+using System.Windows.Data;
+using System.Windows.Markup;
+using System.Windows.Media;
+
+namespace Gestor.Application.Converters
+{
+	public class VariavelExisteColorConverter : MarkupExtension, IValueConverter
+	{
+		public VariavelExisteColorConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value == null)
+			{
+				return new SolidColorBrush(Colors.Red);
+			}
+			if (!(bool)value)
+			{
+				return new SolidColorBrush(Colors.Black);
+			}
+			return new SolidColorBrush(Colors.Red);
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/VariavelExisteTooltipConverter.cs b/Codemerx/Gestor.Application/Converters/VariavelExisteTooltipConverter.cs
new file mode 100644
index 0000000..e0328f2
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/VariavelExisteTooltipConverter.cs
@@ -0,0 +1,37 @@
+using System;
+using System.Globalization;
+using System.Windows.Data;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Converters
+{
+	public class VariavelExisteTooltipConverter : MarkupExtension, IValueConverter
+	{
+		public VariavelExisteTooltipConverter()
+		{
+		}
+
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value == null)
+			{
+				return "CAMPO FALTANDO EM, PELO MENOS, UM\nDOS DOCUMENTOS SELECIONADOS PARA ENVIO";
+			}
+			if (!(bool)value)
+			{
+				return "CAMPO PRESENTE EM TODOS\nOS DOCUMENTOS SELECIONADOS PARA ENVIO";
+			}
+			return "CAMPO FALTANDO EM, PELO MENOS, UM\nDOS DOCUMENTOS SELECIONADOS PARA ENVIO";
+		}
+
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+
+		public override object ProvideValue(IServiceProvider serviceProvider)
+		{
+			return this;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Converters/VerApoliceComissaoConverter.cs b/Codemerx/Gestor.Application/Converters/VerApoliceComissaoConverter.cs
new file mode 100644
index 0000000..4048ab5
--- /dev/null
+++ b/Codemerx/Gestor.Application/Converters/VerApoliceComissaoConverter.cs
@@ -0,0 +1,52 @@
+using System;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Data;
+
+namespace Gestor.Application.Converters
+{
+	public class VerApoliceComissaoConverter : IMultiValueConverter
+	{
+		public VerApoliceComissaoConverter()
+		{
+		}
+
+		public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
+		{
+			object obj;
+			try
+			{
+				if (values[0] != null || values[1] != null)
+				{
+					long? nullable = (long?)values[0];
+					long num = (long)0;
+					if (nullable.GetValueOrDefault() == num & nullable.HasValue)
+					{
+						nullable = (long?)values[1];
+						num = (long)0;
+						if (nullable.GetValueOrDefault() == num & nullable.HasValue)
+						{
+							obj = Visibility.Collapsed;
+							return obj;
+						}
+					}
+					obj = Visibility.Visible;
+				}
+				else
+				{
+					obj = Visibility.Collapsed;
+				}
+			}
+			catch (Exception exception)
+			{
+				obj = Visibility.Collapsed;
+			}
+			return obj;
+		}
+
+		public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Drawers/AdiantamentoDrawerView.cs b/Codemerx/Gestor.Application/Drawers/AdiantamentoDrawerView.cs
new file mode 100644
index 0000000..46e4dde
--- /dev/null
+++ b/Codemerx/Gestor.Application/Drawers/AdiantamentoDrawerView.cs
@@ -0,0 +1,243 @@
+using CurrencyTextBoxControl;
+using Gestor.Application.Helpers;
+using Gestor.Application.ViewModels.Drawer;
+using Gestor.Application.ViewModels.Generic;
+using Gestor.Application.Views.Generic;
+using Gestor.Model.Domain.Generic;
+using Gestor.Model.Domain.Seguros;
+using MaterialDesignThemes.Wpf;
+using System;
+using System.CodeDom.Compiler;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Controls.Primitives;
+using System.Windows.Data;
+using System.Windows.Input;
+using System.Windows.Markup;
+using System.Windows.Threading;
+
+namespace Gestor.Application.Drawers
+{
+	public class AdiantamentoDrawerView : BaseUserControl, IComponentConnector
+	{
+		internal System.Windows.Controls.ProgressBar ProgressBar;
+
+		internal DataGrid AdiantamentoGrid;
+
+		internal CurrencyTextBox RendaMensalBox;
+
+		internal MaterialDesignThemes.Wpf.Snackbar Snackbar;
+
+		private bool _contentLoaded;
+
+		public AdiantamentoViewModel ViewModel
+		{
+			get;
+			set;
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		internal Delegate _CreateDelegate(Type delegateType, string handler)
+		{
+			return Delegate.CreateDelegate(delegateType, this, handler);
+		}
+
+		public AdiantamentoDrawerView(Vendedor vendedor)
+		{
+			this.ViewModel = new AdiantamentoViewModel(vendedor);
+			base.DataContext = this.ViewModel;
+			this.InitializeComponent();
+		}
+
+		private void AbrirLog_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.AbrirLog(36, this.ViewModel.SelectedAdiantamento.get_Id());
+		}
+
+		private void Alterar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.Alterar(true);
+		}
+
+		private void Cancelar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.CancelarAlteracao();
+		}
+
+		private void CloseSlackBar()
+		{
+			Thread.Sleep(5000);
+			System.Windows.Threading.Dispatcher dispatcher = this.ProgressBar.Dispatcher;
+			if (dispatcher == null)
+			{
+				return;
+			}
+			dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => this.ToggleSnackBar("", false)));
+		}
+
+		private async void Excluir_OnClick(object sender, RoutedEventArgs e)
+		{
+			if (await this.ViewModel.Excluir())
+			{
+				this.ToggleSnackBar("ADIANTAMENTO EXCLUÍDO COM SUCESSO", true);
+			}
+		}
+
+		private void Fechar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.CloseDrawer();
+		}
+
+		private void Incluir_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.Incluir();
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		public void InitializeComponent()
+		{
+			if (this._contentLoaded)
+			{
+				return;
+			}
+			this._contentLoaded = true;
+			System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/drawers/adiantamentodrawerview.xaml", UriKind.Relative));
+		}
+
+		private async void MenuList_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
+		{
+			ListBox listBox = (ListBox)sender;
+			if (listBox.SelectedItem != null)
+			{
+				await this.ViewModel.CarregarAdiantamento(listBox.SelectedIndex);
+			}
+		}
+
+		private async void Salvar_OnClick(object sender, RoutedEventArgs e)
+		{
+			bool flag;
+			this.ViewModel.Carregando = true;
+			List> keyValuePairs = await this.ViewModel.Salvar();
+			this.ValidateFields(keyValuePairs, true);
+			flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0);
+			this.AdiantamentoGrid.Items.Refresh();
+			this.ViewModel.Carregando = false;
+			this.ViewModel.Loading(false);
+			if (!flag)
+			{
+				await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", "");
+			}
+			else
+			{
+				this.ToggleSnackBar("ADIANTAMENTO SALVO COM SUCESSO", true);
+			}
+		}
+
+		private void SnackbarMessage_ActionClick(object sender, RoutedEventArgs e)
+		{
+			this.Snackbar.set_IsActive(false);
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target)
+		{
+			switch (connectionId)
+			{
+				case 1:
+				{
+					this.ProgressBar = (System.Windows.Controls.ProgressBar)target;
+					return;
+				}
+				case 2:
+				{
+					((ListBox)target).SelectionChanged += new SelectionChangedEventHandler(this.MenuList_OnSelectionChanged);
+					return;
+				}
+				case 3:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.Fechar_OnClick);
+					return;
+				}
+				case 4:
+				{
+					this.AdiantamentoGrid = (DataGrid)target;
+					return;
+				}
+				case 5:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Incluir_OnClick);
+					return;
+				}
+				case 6:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick);
+					return;
+				}
+				case 7:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick);
+					return;
+				}
+				case 8:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick);
+					return;
+				}
+				case 9:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Excluir_OnClick);
+					return;
+				}
+				case 10:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick);
+					return;
+				}
+				case 11:
+				{
+					((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus);
+					((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick);
+					((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown);
+					return;
+				}
+				case 12:
+				{
+					this.RendaMensalBox = (CurrencyTextBox)target;
+					return;
+				}
+				case 13:
+				{
+					this.Snackbar = (MaterialDesignThemes.Wpf.Snackbar)target;
+					return;
+				}
+				case 14:
+				{
+					((SnackbarMessage)target).add_ActionClick(new RoutedEventHandler(this.SnackbarMessage_ActionClick));
+					return;
+				}
+			}
+			this._contentLoaded = true;
+		}
+
+		public void ToggleSnackBar(string message, bool active = true)
+		{
+			this.Snackbar.get_Message().Content = message;
+			this.Snackbar.set_IsActive(active);
+			if (!active)
+			{
+				return;
+			}
+			Task.Factory.StartNew(new Action(this.CloseSlackBar));
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Drawers/AgendaDrawer.cs b/Codemerx/Gestor.Application/Drawers/AgendaDrawer.cs
new file mode 100644
index 0000000..d60001d
--- /dev/null
+++ b/Codemerx/Gestor.Application/Drawers/AgendaDrawer.cs
@@ -0,0 +1,563 @@
+using Gestor.Application.Componentes;
+using Gestor.Application.Helpers;
+using Gestor.Application.ViewModels.Drawer;
+using Gestor.Application.ViewModels.Generic;
+using Gestor.Application.Views.Generic;
+using Gestor.Common.Helpers;
+using Gestor.Common.Validation;
+using Gestor.Model.Common;
+using Gestor.Model.Domain.Ferramentas;
+using Gestor.Model.Domain.Generic;
+using MaterialDesignThemes.Wpf;
+using System;
+using System.CodeDom.Compiler;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Controls.Primitives;
+using System.Windows.Input;
+using System.Windows.Markup;
+using System.Windows.Threading;
+using Xceed.Wpf.AvalonDock.Controls;
+
+namespace Gestor.Application.Drawers
+{
+	public class AgendaDrawer : BaseUserControl, IComponentConnector, IStyleConnector
+	{
+		internal System.Windows.Controls.ProgressBar ProgressBar;
+
+		internal DataGrid AgendaGrid;
+
+		internal MenuItem MaisOpcoesButton;
+
+		internal TextBox NomeBox;
+
+		internal TextBox CepBox;
+
+		internal System.Windows.Controls.ProgressBar ProgressCep;
+
+		internal TextBox EnderecoBox;
+
+		internal TextBox BairroBox;
+
+		internal TextBox CidadeBox;
+
+		internal TextBox EstadoBox;
+
+		internal TextBox ObsBox;
+
+		internal ListBox TelefoneListBox;
+
+		internal ListBox EmailListBox;
+
+		internal MaterialDesignThemes.Wpf.Snackbar Snackbar;
+
+		private bool _contentLoaded;
+
+		private AgendaViewModel ViewModel
+		{
+			get;
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		internal Delegate _CreateDelegate(Type delegateType, string handler)
+		{
+			return Delegate.CreateDelegate(delegateType, this, handler);
+		}
+
+		public AgendaDrawer()
+		{
+			this.ViewModel = new AgendaViewModel();
+			base.DataContext = this.ViewModel;
+			this.InitializeComponent();
+			System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher;
+			if (dispatcher == null)
+			{
+				return;
+			}
+			dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad));
+		}
+
+		private void AbrirLog_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.AbrirLog(34, this.ViewModel.SelectedAgenda.get_Id());
+		}
+
+		private async void AgendaGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
+		{
+			object obj;
+			DataGrid dataGrid = (DataGrid)sender;
+			if (dataGrid == null || dataGrid.SelectedIndex >= 0)
+			{
+				AgendaViewModel viewModel = this.ViewModel;
+				obj = (dataGrid != null ? dataGrid.Items[dataGrid.SelectedIndex] : null);
+				await viewModel.SelecionaAgenda((Agenda)obj);
+			}
+		}
+
+		private void Alterar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.CancelAgenda = (Agenda)this.ViewModel.SelectedAgenda.Clone();
+			this.ViewModel.Alterar(true);
+		}
+
+		private void AutoCompleteBox_OnTextChanged(object sender, RoutedEventArgs e)
+		{
+			if (!string.IsNullOrWhiteSpace(((AutoCompleteBox)sender).get_Text()))
+			{
+				return;
+			}
+			this.ViewModel.FiltrarAgenda("");
+		}
+
+		private void AutoCompleteBox_Populating(object sender, PopulatingEventArgs e)
+		{
+			if (e.get_Parameter().Length < 3)
+			{
+				return;
+			}
+			e.set_Cancel(true);
+			this.ViewModel.Filtrar(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => {
+				if (searchResult.Result == null)
+				{
+					return;
+				}
+				AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender;
+				autoCompleteBox.set_ItemsSource(searchResult.Result);
+				autoCompleteBox.PopulateComplete();
+			}, TaskScheduler.FromCurrentSynchronizationContext());
+		}
+
+		private void Cancelar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.CancelarAlteracao();
+		}
+
+		private void CloseSlackBar()
+		{
+			Thread.Sleep(5000);
+			System.Windows.Threading.Dispatcher dispatcher = this.ProgressBar.Dispatcher;
+			if (dispatcher == null)
+			{
+				return;
+			}
+			dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => this.ToggleSnackBar("", false)));
+		}
+
+		private void ContentLoad()
+		{
+			this.AgendaGrid.SelectedIndex = 0;
+			this.AgendaGrid.SelectionChanged += new SelectionChangedEventHandler(this.AgendaGrid_OnSelectionChanged);
+			this.AgendaGrid.MouseDoubleClick += new MouseButtonEventHandler((object sender, MouseButtonEventArgs args) => {
+			});
+			this.ViewModel.PermissaoWhatsapp = this.ViewModel.Restricao(32);
+		}
+
+		private void CopyEmailToClipBoard_Click(object sender, RoutedEventArgs e)
+		{
+			Button button = (Button)sender;
+			ListBox listBox = Extentions.FindVisualAncestor(button);
+			EmailBase item = (EmailBase)listBox.Items[listBox.Items.IndexOf(button.DataContext)];
+			item.get_Email().CopyToClipboard();
+			this.ToggleSnackBar(string.Concat("COPIADO - ", item.get_Email()), true);
+		}
+
+		private void CopyTelefoneToClipBoard_Click(object sender, RoutedEventArgs e)
+		{
+			Button button = (Button)sender;
+			ListBox listBox = Extentions.FindVisualAncestor(button);
+			TelefoneBase item = (TelefoneBase)listBox.Items[listBox.Items.IndexOf(button.DataContext)];
+			string.Concat(item.get_Prefixo(), ValidationHelper.OnlyNumber(item.get_Numero())).CopyToClipboard();
+			this.ToggleSnackBar(string.Concat("COPIADO - ", item.get_Prefixo(), ValidationHelper.OnlyNumber(item.get_Numero())), true);
+		}
+
+		private async void Excluir_OnClick(object sender, RoutedEventArgs e)
+		{
+			if (await this.ViewModel.Excluir())
+			{
+				this.ToggleSnackBar("AGENDA EXCLUÍDA COM SUCESSO", true);
+			}
+		}
+
+		private void ExcluirEmail_OnClick(object sender, RoutedEventArgs e)
+		{
+			Button button = sender as Button;
+			if (button == null)
+			{
+				return;
+			}
+			ListBox listBox = Extentions.FindVisualAncestor(button);
+			AgendaEmail item = (AgendaEmail)listBox.Items[listBox.Items.IndexOf(button.DataContext)];
+			this.ViewModel.ExcluirEmail(item);
+		}
+
+		private void ExcluirTelefone_OnClick(object sender, RoutedEventArgs e)
+		{
+			Button button = sender as Button;
+			if (button == null)
+			{
+				return;
+			}
+			ListBox listBox = Extentions.FindVisualAncestor(button);
+			AgendaTelefone item = (AgendaTelefone)listBox.Items[listBox.Items.IndexOf(button.DataContext)];
+			this.ViewModel.ExcluirTelefone(item);
+		}
+
+		private void Fechar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.CloseDrawer();
+		}
+
+		private void Incluir_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.Incluir();
+			List> keyValuePairs = this.ViewModel.SelectedAgenda.Validate();
+			this.ValidateFields(keyValuePairs, true);
+		}
+
+		private void IncluirEmail_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.IncluirEmail();
+		}
+
+		private void IncluirTelefone_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.IncluirTelefone();
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		public void InitializeComponent()
+		{
+			if (this._contentLoaded)
+			{
+				return;
+			}
+			this._contentLoaded = true;
+			System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/drawers/agendadrawer.xaml", UriKind.Relative));
+		}
+
+		private async void PostcodeBox_OnLostFocus(object sender, RoutedEventArgs e)
+		{
+			string str = ValidationHelper.FormatPostCode(((TextBox)sender).Text);
+			this.CepBox.Text = str;
+			if (ValidationHelper.ValidatePostCode(str))
+			{
+				EnderecoBase enderecoBase = await this.ViewModel.BuscaCep(str);
+				if (enderecoBase != null)
+				{
+					this.EnderecoBox.Text = enderecoBase.get_Endereco();
+					this.CidadeBox.Text = enderecoBase.get_Cidade();
+					this.EstadoBox.Text = enderecoBase.get_Estado();
+					this.BairroBox.Text = enderecoBase.get_Bairro();
+				}
+			}
+		}
+
+		private async void Salvar_OnClick(object sender, RoutedEventArgs e)
+		{
+			bool flag;
+			this.ViewModel.Carregando = true;
+			List> keyValuePairs = await this.ViewModel.Salvar();
+			this.ValidateFields(keyValuePairs, true);
+			flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0);
+			this.ViewModel.Carregando = false;
+			if (!flag)
+			{
+				await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", "");
+			}
+			else
+			{
+				this.ToggleSnackBar("AGENDA SALVA COM SUCESSO", true);
+			}
+		}
+
+		private void SnackbarMessage_ActionClick(object sender, RoutedEventArgs e)
+		{
+			this.Snackbar.set_IsActive(false);
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target)
+		{
+			switch (connectionId)
+			{
+				case 1:
+				{
+					this.ProgressBar = (System.Windows.Controls.ProgressBar)target;
+					return;
+				}
+				case 2:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.Fechar_OnClick);
+					return;
+				}
+				case 3:
+				{
+					((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, AgendaDrawer.AutoCompleteBox_Populating));
+					((AutoCompleteBox)target).add_TextChanged(new RoutedEventHandler(this.AutoCompleteBox_OnTextChanged));
+					return;
+				}
+				case 4:
+				{
+					this.AgendaGrid = (DataGrid)target;
+					return;
+				}
+				case 5:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Incluir_OnClick);
+					return;
+				}
+				case 6:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick);
+					return;
+				}
+				case 7:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick);
+					return;
+				}
+				case 8:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick);
+					return;
+				}
+				case 9:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Excluir_OnClick);
+					return;
+				}
+				case 10:
+				{
+					this.MaisOpcoesButton = (MenuItem)target;
+					return;
+				}
+				case 11:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick);
+					return;
+				}
+				case 12:
+				{
+					this.NomeBox = (TextBox)target;
+					return;
+				}
+				case 13:
+				{
+					this.CepBox = (TextBox)target;
+					this.CepBox.LostFocus += new RoutedEventHandler(this.PostcodeBox_OnLostFocus);
+					AgendaDrawer agendaDrawer = this;
+					this.CepBox.PreviewTextInput += new TextCompositionEventHandler(agendaDrawer.SomenteNumeros);
+					return;
+				}
+				case 14:
+				{
+					this.ProgressCep = (System.Windows.Controls.ProgressBar)target;
+					return;
+				}
+				case 15:
+				{
+					this.EnderecoBox = (TextBox)target;
+					return;
+				}
+				case 16:
+				{
+					this.BairroBox = (TextBox)target;
+					return;
+				}
+				case 17:
+				{
+					this.CidadeBox = (TextBox)target;
+					return;
+				}
+				case 18:
+				{
+					this.EstadoBox = (TextBox)target;
+					return;
+				}
+				case 19:
+				{
+					this.ObsBox = (TextBox)target;
+					return;
+				}
+				case 20:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.IncluirTelefone_OnClick);
+					return;
+				}
+				case 21:
+				{
+					this.TelefoneListBox = (ListBox)target;
+					return;
+				}
+				case 22:
+				case 23:
+				case 24:
+				case 25:
+				case 26:
+				case 27:
+				case 30:
+				case 31:
+				{
+					this._contentLoaded = true;
+					return;
+				}
+				case 28:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.IncluirEmail_OnClick);
+					return;
+				}
+				case 29:
+				{
+					this.EmailListBox = (ListBox)target;
+					return;
+				}
+				case 32:
+				{
+					this.Snackbar = (MaterialDesignThemes.Wpf.Snackbar)target;
+					return;
+				}
+				case 33:
+				{
+					((SnackbarMessage)target).add_ActionClick(new RoutedEventHandler(this.SnackbarMessage_ActionClick));
+					return;
+				}
+				default:
+				{
+					this._contentLoaded = true;
+					return;
+				}
+			}
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target)
+		{
+			switch (connectionId)
+			{
+				case 22:
+				{
+					((ComboBox)target).SelectionChanged += new SelectionChangedEventHandler(this.TipoComboBox_OnSelectionChanged);
+					return;
+				}
+				case 23:
+				{
+					AgendaDrawer agendaDrawer = this;
+					((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(agendaDrawer.SomenteNumeros);
+					return;
+				}
+				case 24:
+				{
+					AgendaDrawer agendaDrawer1 = this;
+					((TextBox)target).LostFocus += new RoutedEventHandler(agendaDrawer1.FormatarTelefone);
+					AgendaDrawer agendaDrawer2 = this;
+					((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(agendaDrawer2.SomenteNumeros);
+					return;
+				}
+				case 25:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.ExcluirTelefone_OnClick);
+					return;
+				}
+				case 26:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.CopyTelefoneToClipBoard_Click);
+					return;
+				}
+				case 27:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.WhatsAppMessage_Click);
+					return;
+				}
+				case 28:
+				case 29:
+				{
+					return;
+				}
+				case 30:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.ExcluirEmail_OnClick);
+					return;
+				}
+				case 31:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.CopyEmailToClipBoard_Click);
+					return;
+				}
+				default:
+				{
+					return;
+				}
+			}
+		}
+
+		private void TipoComboBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
+		{
+			int num;
+			ComboBox comboBox = (ComboBox)sender;
+			CustomIsReadOnlyControl customIsReadOnlyControl = Extentions.FindVisualAncestor(comboBox);
+			if (customIsReadOnlyControl == null)
+			{
+				return;
+			}
+			WrapPanel wrapPanel = Extentions.FindVisualAncestor(customIsReadOnlyControl);
+			ListBox listBox = Extentions.FindVisualAncestor(wrapPanel);
+			ContentPresenter contentPresenter = FindVisualChild.Find((ListBoxItem)listBox.ItemContainerGenerator.ContainerFromIndex(listBox.Items.IndexOf(wrapPanel.DataContext)));
+			DataTemplate contentTemplate = contentPresenter.ContentTemplate;
+			CustomItemValidation customItemValidation = (CustomItemValidation)contentTemplate.FindName("Prefixo", contentPresenter);
+			CustomItemValidation customItemValidation1 = (CustomItemValidation)contentTemplate.FindName("Telefone", contentPresenter);
+			TextBox textBox = ViewHelper.FindChildren(customItemValidation).FirstOrDefault();
+			TextBox textBox1 = ViewHelper.FindChildren(customItemValidation1).FirstOrDefault();
+			if (textBox == null || textBox1 == null)
+			{
+				return;
+			}
+			if ((TipoTelefone)comboBox.SelectedValue == 8)
+			{
+				customItemValidation.Visibility = System.Windows.Visibility.Collapsed;
+				textBox1.MaxLength = 20;
+				return;
+			}
+			customItemValidation.Visibility = System.Windows.Visibility.Visible;
+			textBox1.MaxLength = 10;
+			num = (textBox1.Text.Length >= 10 ? 10 : textBox1.Text.Length);
+			textBox1.Text = textBox1.Text.Substring(0, num);
+		}
+
+		public void ToggleSnackBar(string message, bool active = true)
+		{
+			this.Snackbar.get_Message().Content = message;
+			this.Snackbar.set_IsActive(active);
+			if (!active)
+			{
+				return;
+			}
+			Task.Factory.StartNew(new Action(this.CloseSlackBar));
+		}
+
+		private async void WhatsAppMessage_Click(object sender, RoutedEventArgs e)
+		{
+			string str;
+			Button button = (Button)sender;
+			ListBox listBox = Extentions.FindVisualAncestor(button);
+			TelefoneBase item = (TelefoneBase)listBox.Items[listBox.Items.IndexOf(button.DataContext)];
+			str = (!item.get_Tipo().HasValue || item.get_Tipo().GetValueOrDefault() != 8 ? string.Concat("55", item.get_Prefixo(), item.get_Numero().Clear()) : string.Concat(item.get_Prefixo(), item.get_Numero()).Clear());
+			if (!str.EnviarWhatsapp(null))
+			{
+				await this.ViewModel.ShowMessage("HOUVE UM PROBLEMA AO ABRIR LINK DO WHATSAPP, O LINK FOI COPIADO EM SUA MAQUINA, BASTA ABRIR O NAVEGADOR DE INTERNET E COLAR NA BARRA DE ENDEREÇOS", "OK", "", false);
+			}
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Drawers/Ajuda/BoletosNotasDrawerView.cs b/Codemerx/Gestor.Application/Drawers/Ajuda/BoletosNotasDrawerView.cs
new file mode 100644
index 0000000..5426bb0
--- /dev/null
+++ b/Codemerx/Gestor.Application/Drawers/Ajuda/BoletosNotasDrawerView.cs
@@ -0,0 +1,174 @@
+using Agger.Registro;
+using Gestor.Application.Helpers;
+using Gestor.Application.Model.Ajuda;
+using Gestor.Application.ViewModels.Drawer.Ajuda;
+using Gestor.Application.ViewModels.Generic;
+using Gestor.Application.Views.Generic;
+using System;
+using System.CodeDom.Compiler;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Controls.Primitives;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Drawers.Ajuda
+{
+	public class BoletosNotasDrawerView : BaseUserControl, IComponentConnector, IStyleConnector
+	{
+		internal System.Windows.Controls.ProgressBar ProgressBar;
+
+		internal ComboBox StatusCbo;
+
+		internal DataGrid BoletosGrid;
+
+		internal DataGridTemplateColumn BaixarBoletoColumn;
+
+		internal DataGridTextColumn PagamentoColumn;
+
+		internal ItemsControl BoletoDisponivel;
+
+		internal TextBlock TxtBoletoDisponivel;
+
+		private bool _contentLoaded;
+
+		public BoletosNotasViewModel ViewModel
+		{
+			get;
+			set;
+		}
+
+		public BoletosNotasDrawerView()
+		{
+			this.ViewModel = new BoletosNotasViewModel();
+			base.DataContext = this.ViewModel;
+			this.InitializeComponent();
+			this.StatusCbo.SelectedIndex = 0;
+		}
+
+		private void ExibirBoleto_OnClick(object sender, RoutedEventArgs e)
+		{
+			Boleto selectedItem = (Boleto)this.BoletosGrid.SelectedItem;
+			if ((selectedItem.Vencimento - Funcoes.GetNetworkTime()).TotalDays > 10)
+			{
+				return;
+			}
+			Process.Start(string.Format("{0}billet/id/{1}", Address.get_ApiBoletoAgger(), selectedItem.IdBoleto));
+		}
+
+		private void ExibirNota_OnClick(object sender, RoutedEventArgs e)
+		{
+			Process.Start(((Boleto)this.BoletosGrid.SelectedItem).Nota ?? "");
+		}
+
+		private void Fechar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.CloseDrawer();
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		public void InitializeComponent()
+		{
+			if (this._contentLoaded)
+			{
+				return;
+			}
+			this._contentLoaded = true;
+			System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/drawers/ajuda/boletosnotasdrawerview.xaml", UriKind.Relative));
+		}
+
+		private void SelectedStatus_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
+		{
+			if (this.StatusCbo.SelectedItem == null)
+			{
+				return;
+			}
+			this.ViewModel.WorkOnSelectedStatus(this.StatusCbo.SelectedItem.ToString());
+			this.PagamentoColumn.Visibility = (this.StatusCbo.SelectedItem.ToString() == "PENDENTES" ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible);
+			this.BaixarBoletoColumn.Visibility = (this.StatusCbo.SelectedItem.ToString() == "PENDENTES" ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed);
+			this.BoletoDisponivel.Visibility = (this.StatusCbo.SelectedItem.ToString() == "PENDENTES" ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed);
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target)
+		{
+			switch (connectionId)
+			{
+				case 1:
+				{
+					this.ProgressBar = (System.Windows.Controls.ProgressBar)target;
+					return;
+				}
+				case 2:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.Fechar_OnClick);
+					return;
+				}
+				case 3:
+				{
+					this.StatusCbo = (ComboBox)target;
+					this.StatusCbo.SelectionChanged += new SelectionChangedEventHandler(this.SelectedStatus_OnSelectionChanged);
+					return;
+				}
+				case 4:
+				{
+					this.BoletosGrid = (DataGrid)target;
+					return;
+				}
+				case 5:
+				{
+					this.BaixarBoletoColumn = (DataGridTemplateColumn)target;
+					return;
+				}
+				case 6:
+				case 7:
+				{
+					this._contentLoaded = true;
+					return;
+				}
+				case 8:
+				{
+					this.PagamentoColumn = (DataGridTextColumn)target;
+					return;
+				}
+				case 9:
+				{
+					this.BoletoDisponivel = (ItemsControl)target;
+					return;
+				}
+				case 10:
+				{
+					this.TxtBoletoDisponivel = (TextBlock)target;
+					return;
+				}
+				default:
+				{
+					this._contentLoaded = true;
+					return;
+				}
+			}
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target)
+		{
+			if (connectionId == 6)
+			{
+				((Button)target).Click += new RoutedEventHandler(this.ExibirBoleto_OnClick);
+				return;
+			}
+			if (connectionId != 7)
+			{
+				return;
+			}
+			((Button)target).Click += new RoutedEventHandler(this.ExibirNota_OnClick);
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Drawers/Ajuda/ContratosDrawerView.cs b/Codemerx/Gestor.Application/Drawers/Ajuda/ContratosDrawerView.cs
new file mode 100644
index 0000000..3a3c153
--- /dev/null
+++ b/Codemerx/Gestor.Application/Drawers/Ajuda/ContratosDrawerView.cs
@@ -0,0 +1,69 @@
+using Gestor.Application.ViewModels.Drawer.Ajuda;
+using Gestor.Application.ViewModels.Generic;
+using Gestor.Application.Views.Generic;
+using System;
+using System.CodeDom.Compiler;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Drawers.Ajuda
+{
+	public class ContratosDrawerView : BaseUserControl, IComponentConnector
+	{
+		internal DataGrid ContratosGrid;
+
+		private bool _contentLoaded;
+
+		public ContratosViewModel ViewModel
+		{
+			get;
+			set;
+		}
+
+		public ContratosDrawerView()
+		{
+			this.ViewModel = new ContratosViewModel();
+			base.DataContext = this.ViewModel;
+			this.InitializeComponent();
+		}
+
+		private void Fechar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.CloseDrawer();
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		public void InitializeComponent()
+		{
+			if (this._contentLoaded)
+			{
+				return;
+			}
+			this._contentLoaded = true;
+			System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/drawers/ajuda/contratosdrawerview.xaml", UriKind.Relative));
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target)
+		{
+			if (connectionId == 1)
+			{
+				((Button)target).Click += new RoutedEventHandler(this.Fechar_OnClick);
+				return;
+			}
+			if (connectionId != 2)
+			{
+				this._contentLoaded = true;
+				return;
+			}
+			this.ContratosGrid = (DataGrid)target;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Drawers/Ajuda/InstalacaoDrawerView.cs b/Codemerx/Gestor.Application/Drawers/Ajuda/InstalacaoDrawerView.cs
new file mode 100644
index 0000000..9721288
--- /dev/null
+++ b/Codemerx/Gestor.Application/Drawers/Ajuda/InstalacaoDrawerView.cs
@@ -0,0 +1,181 @@
+using Gestor.Application.Model.Ajuda;
+using Gestor.Application.ViewModels.Drawer.Ajuda;
+using Gestor.Application.ViewModels.Generic;
+using Gestor.Application.Views.Generic;
+using Gestor.Common.Validation;
+using System;
+using System.CodeDom.Compiler;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Controls.Primitives;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Drawers.Ajuda
+{
+	public class InstalacaoDrawerView : BaseUserControl, IComponentConnector, IStyleConnector
+	{
+		internal System.Windows.Controls.ProgressBar ProgressBar;
+
+		internal DataGrid GestorGrid;
+
+		internal DataGrid AggilizadorGrid;
+
+		private bool _contentLoaded;
+
+		public InstalacaoViewModel ViewModel
+		{
+			get;
+			set;
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		internal Delegate _CreateDelegate(Type delegateType, string handler)
+		{
+			return Delegate.CreateDelegate(delegateType, this, handler);
+		}
+
+		public InstalacaoDrawerView()
+		{
+			this.ViewModel = new InstalacaoViewModel();
+			base.DataContext = this.ViewModel;
+			this.InitializeComponent();
+		}
+
+		private void AutoCompleteBox_OnTextChanged(object sender, RoutedEventArgs e)
+		{
+			if (!string.IsNullOrWhiteSpace(((AutoCompleteBox)sender).get_Text()))
+			{
+				return;
+			}
+			this.ViewModel.FiltrarInstalacao("");
+		}
+
+		private void AutoCompleteBox_Populating(object sender, PopulatingEventArgs e)
+		{
+			e.set_Cancel(true);
+			this.ViewModel.Filtrar(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => {
+				if (searchResult.Result == null)
+				{
+					return;
+				}
+				AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender;
+				autoCompleteBox.set_ItemsSource(searchResult.Result);
+				autoCompleteBox.PopulateComplete();
+			}, TaskScheduler.FromCurrentSynchronizationContext());
+		}
+
+		private async void ExcluirInstalacaoAggilizadorGrid_OnClick(object sender, RoutedEventArgs e)
+		{
+			Instalacao selectedItem;
+			if (this.AggilizadorGrid.SelectedItem != null)
+			{
+				selectedItem = (Instalacao)this.AggilizadorGrid.SelectedItem;
+				if (await this.ViewModel.ShowMessage(string.Concat("DESEJA REALMENTE EXCLUIR A INSTALAÇÃO DA MÁQUINA ", selectedItem.Maquina.ToUpper()), "SIM", "NÃO", false))
+				{
+					this.ViewModel.Excluir(selectedItem.Id);
+				}
+			}
+			selectedItem = null;
+		}
+
+		private async void ExcluirInstalacaoGestorGrid_OnClick(object sender, RoutedEventArgs e)
+		{
+			Instalacao selectedItem;
+			if (this.GestorGrid.SelectedItem != null)
+			{
+				selectedItem = (Instalacao)this.GestorGrid.SelectedItem;
+				if (await this.ViewModel.ShowMessage(string.Concat("DESEJA REALMENTE EXCLUIR A INSTALAÇÃO DA MÁQUINA ", selectedItem.Maquina.ToUpper()), "SIM", "NÃO", false))
+				{
+					this.ViewModel.Excluir(selectedItem.Id);
+				}
+			}
+			selectedItem = null;
+		}
+
+		private void Fechar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.CloseDrawer();
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		public void InitializeComponent()
+		{
+			if (this._contentLoaded)
+			{
+				return;
+			}
+			this._contentLoaded = true;
+			System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/drawers/ajuda/instalacaodrawerview.xaml", UriKind.Relative));
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target)
+		{
+			switch (connectionId)
+			{
+				case 1:
+				{
+					this.ProgressBar = (System.Windows.Controls.ProgressBar)target;
+					return;
+				}
+				case 2:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.Fechar_OnClick);
+					return;
+				}
+				case 3:
+				{
+					((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, InstalacaoDrawerView.AutoCompleteBox_Populating));
+					((AutoCompleteBox)target).add_TextChanged(new RoutedEventHandler(this.AutoCompleteBox_OnTextChanged));
+					return;
+				}
+				case 4:
+				{
+					this.GestorGrid = (DataGrid)target;
+					return;
+				}
+				case 5:
+				{
+					this._contentLoaded = true;
+					return;
+				}
+				case 6:
+				{
+					this.AggilizadorGrid = (DataGrid)target;
+					return;
+				}
+				default:
+				{
+					this._contentLoaded = true;
+					return;
+				}
+			}
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target)
+		{
+			if (connectionId == 5)
+			{
+				((Button)target).Click += new RoutedEventHandler(this.ExcluirInstalacaoGestorGrid_OnClick);
+				return;
+			}
+			if (connectionId != 7)
+			{
+				return;
+			}
+			((Button)target).Click += new RoutedEventHandler(this.ExcluirInstalacaoAggilizadorGrid_OnClick);
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Drawers/ArquivoDigitalDrawer.cs b/Codemerx/Gestor.Application/Drawers/ArquivoDigitalDrawer.cs
new file mode 100644
index 0000000..04ffb9a
--- /dev/null
+++ b/Codemerx/Gestor.Application/Drawers/ArquivoDigitalDrawer.cs
@@ -0,0 +1,835 @@
+using Gestor.Application;
+using Gestor.Application.Helpers;
+using Gestor.Application.ViewModels.Drawer;
+using Gestor.Application.ViewModels.Generic;
+using Gestor.Application.Views.Ferramentas;
+using Gestor.Application.Views.Generic;
+using Gestor.Common.Security;
+using Gestor.Common.Validation;
+using Gestor.Model.API;
+using Gestor.Model.Common;
+using Gestor.Model.Domain.Common;
+using Gestor.Model.Domain.Generic;
+using Gestor.Model.Domain.MalaDireta;
+using Gestor.Model.Domain.Seguros;
+using Gestor.Model.License;
+using MaterialDesignThemes.Wpf;
+using System;
+using System.CodeDom.Compiler;
+using System.Collections;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Text;
+using System.Text.RegularExpressions;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Input;
+using System.Windows.Markup;
+using System.Windows.Threading;
+using Xceed.Wpf.AvalonDock.Controls;
+
+namespace Gestor.Application.Drawers
+{
+	public class ArquivoDigitalDrawer : UserControl, IComponentConnector, IStyleConnector
+	{
+		internal System.Windows.Controls.ProgressBar ProgressBar;
+
+		internal TextBlock TitleBox;
+
+		internal DataGrid ArquivoGrid;
+
+		internal TextBox DocumentoBox;
+
+		internal Snackbar SnackbarArquivoDigital;
+
+		private bool _contentLoaded;
+
+		private FiltroArquivoDigital Filtro
+		{
+			get;
+		}
+
+		public ArquivoDigitalViewModel ViewModel
+		{
+			get;
+			set;
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		internal Delegate _CreateDelegate(Type delegateType, string handler)
+		{
+			return Delegate.CreateDelegate(delegateType, this, handler);
+		}
+
+		public ArquivoDigitalDrawer(FiltroArquivoDigital filtro)
+		{
+			long? nullable;
+			long? nullable1;
+			string description;
+			string str;
+			long? nullable2;
+			string description1;
+			string str1;
+			long num;
+			this.ViewModel = new ArquivoDigitalViewModel(filtro);
+			this.Filtro = filtro;
+			base.DataContext = this.ViewModel;
+			this.InitializeComponent();
+			System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher;
+			if (dispatcher != null)
+			{
+				dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad));
+			}
+			else
+			{
+			}
+			ArquivoDigitalViewModel viewModel = this.ViewModel;
+			if (filtro != null)
+			{
+				description = ValidationHelper.GetDescription(filtro.get_Tipo());
+			}
+			else
+			{
+				description = null;
+			}
+			if ((filtro != null ? filtro.get_Id() != (long)0 : true))
+			{
+				if (filtro != null)
+				{
+					nullable1 = new long?(filtro.get_Id());
+				}
+				else
+				{
+					nullable = null;
+					nullable1 = nullable;
+				}
+				str = string.Format(" DO DOCUMENTO DE ID \"{0}\"", nullable1);
+			}
+			else
+			{
+				str = "";
+			}
+			string str2 = string.Concat("ACESSOU ARQUIVO DIGITAL DE ", description, str);
+			num = (filtro != null ? filtro.get_Id() : (long)0);
+			TipoTela? nullable3 = new TipoTela?(6);
+			if (filtro != null)
+			{
+				description1 = ValidationHelper.GetDescription(filtro.get_Tipo());
+			}
+			else
+			{
+				description1 = null;
+			}
+			if ((filtro != null ? filtro.get_Id() != (long)0 : true))
+			{
+				if (filtro != null)
+				{
+					nullable2 = new long?(filtro.get_Id());
+				}
+				else
+				{
+					nullable = null;
+					nullable2 = nullable;
+				}
+				str1 = string.Format("\nID APÓLICE: {0}", nullable2);
+			}
+			else
+			{
+				str1 = "";
+			}
+			viewModel.RegistrarAcao(str2, num, nullable3, string.Concat("TIPO: ", description1, str1));
+		}
+
+		private void Abrir_OnClick(object sender, RoutedEventArgs e)
+		{
+			Button button = sender as Button;
+			if (button == null)
+			{
+				return;
+			}
+			this.ViewModel.Activated = false;
+			DataGrid dataGrid = Extentions.FindVisualAncestor(button);
+			IndiceArquivoDigital item = (IndiceArquivoDigital)dataGrid.Items[dataGrid.Items.IndexOf(button.DataContext)];
+			this.ViewModel.Baixar(item, true);
+			this.ViewModel.Activated = true;
+		}
+
+		private void AlteraEventoAssinarOnClick(Button assinarButton, bool adiciona = true)
+		{
+			if (adiciona)
+			{
+				assinarButton.Click += new RoutedEventHandler(this.Assinar_OnClick);
+				return;
+			}
+			assinarButton.Click -= new RoutedEventHandler(this.Assinar_OnClick);
+		}
+
+		private void AlteraEventoEnviarOnClick(MenuItem enviarMenu, bool adiciona = true)
+		{
+			if (adiciona)
+			{
+				enviarMenu.Click += new RoutedEventHandler(this.Enviar_OnClick);
+				return;
+			}
+			enviarMenu.Click -= new RoutedEventHandler(this.Enviar_OnClick);
+		}
+
+		private void AnexarArquivos_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.Anexar();
+		}
+
+		private void ArquivoGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
+		{
+			string path;
+			if (e.EditAction != DataGridEditAction.Commit)
+			{
+				return;
+			}
+			DataGridBoundColumn column = e.Column as DataGridBoundColumn;
+			if (column == null)
+			{
+				return;
+			}
+			Binding binding = column.Binding as Binding;
+			if (binding != null)
+			{
+				path = binding.Path.Path;
+			}
+			else
+			{
+				path = null;
+			}
+			if (path != "Descricao")
+			{
+				return;
+			}
+			int index = e.Row.GetIndex();
+			TextBox editingElement = e.EditingElement as TextBox;
+			if (editingElement == null)
+			{
+				return;
+			}
+			editingElement.Text = editingElement.Text.ToUpper();
+			IndiceArquivoDigital item = (IndiceArquivoDigital)this.ArquivoGrid.Items[index];
+			if (item.get_Descricao() == editingElement.Text)
+			{
+				return;
+			}
+			item.Initialize();
+			item.set_Descricao(editingElement.Text);
+			this.ViewModel.Editar(item);
+		}
+
+		private async void Assinar_OnClick(object sender, RoutedEventArgs e)
+		{
+			object obj;
+			Button button = (Button)sender;
+			this.AlteraEventoAssinarOnClick(button, false);
+			if (!this.ViewModel.Restricao(60))
+			{
+				List produtos = LicenseHelper.Produtos;
+				if (!produtos.All((Licenca x) => x.get_Produto() != 86))
+				{
+					await this.ViewModel.EnviarParaAssinatura();
+					this.AlteraEventoAssinarOnClick(button, true);
+				}
+				else
+				{
+					Token token = new Token();
+					object[] numeroSerial = new object[] { ApplicationHelper.NumeroSerial, ApplicationHelper.IdFornecedor, Recursos.Usuario.get_Id(), null };
+					obj = (ApplicationHelper.Beta ? "1" : "0");
+					numeroSerial[3] = obj;
+					string str = token.Encrypt(string.Format("{0}:{1}:{2}:{3}", numeroSerial));
+					Parameters parameter = new Parameters();
+					parameter.set_Beta(ApplicationHelper.Beta);
+					parameter.set_Type(8);
+					parameter.set_Application("Assinador.Application.exe");
+					parameter.set_Directory("Assinador.Application");
+					parameter.set_Arguments(str);
+					parameter.set_Run(true);
+					(new DownloadWindow(parameter)).Show();
+					this.AlteraEventoAssinarOnClick(button, true);
+				}
+			}
+			else
+			{
+				await this.ViewModel.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA ASSINATURA.", "OK", "", false);
+				this.AlteraEventoAssinarOnClick(button, true);
+			}
+			button = null;
+		}
+
+		private void Baixar_OnClick(object sender, RoutedEventArgs e)
+		{
+			Button button = sender as Button;
+			if (button == null)
+			{
+				return;
+			}
+			DataGrid dataGrid = Extentions.FindVisualAncestor(button);
+			IndiceArquivoDigital item = (IndiceArquivoDigital)dataGrid.Items[dataGrid.Items.IndexOf(button.DataContext)];
+			this.ViewModel.Baixar(item, false);
+		}
+
+		private async void BaixarTodos_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.Activated = false;
+			if (await this.ViewModel.BaixarTodos())
+			{
+				await this.ViewModel.ShowMessage("ARQUIVOS BAIXADOS COM SUCESSO!", "OK", "", false);
+			}
+			this.ViewModel.Activated = true;
+		}
+
+		private void CloseSlackBar()
+		{
+			Thread.Sleep(5000);
+			System.Windows.Threading.Dispatcher dispatcher = App.ProgressRing.Dispatcher;
+			if (dispatcher == null)
+			{
+				return;
+			}
+			dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => this.Toggle("", false)));
+		}
+
+		private void ContentLoad()
+		{
+			this.ArquivoGrid.CellEditEnding += new EventHandler(this.ArquivoGrid_CellEditEnding);
+			this.DocumentoBox.LostFocus += new RoutedEventHandler(ArquivoDigitalDrawer.DocumentBox_OnLostFocus);
+			this.DocumentoBox.PreviewTextInput += new TextCompositionEventHandler(ArquivoDigitalDrawer.SomenteNumeros);
+		}
+
+		private void CopiarLinkAssinatura_OnClick(object sender, RoutedEventArgs e)
+		{
+			IndiceArquivoDigital dataContext = (IndiceArquivoDigital)((Button)sender).DataContext;
+			if (dataContext == null || string.IsNullOrWhiteSpace(dataContext.get_UrlAssinatura()))
+			{
+				return;
+			}
+			dataContext.get_UrlAssinatura().CopyToClipboard();
+			this.Toggle(string.Concat("LINK COPIADO - ", dataContext.get_UrlAssinatura()), true);
+		}
+
+		private void CopyTelefoneToClipBoard_Click(object sender, RoutedEventArgs e)
+		{
+			Button button = (Button)sender;
+			ListBox listBox = Extentions.FindVisualAncestor(button);
+			ClienteTelefone item = (ClienteTelefone)listBox.Items[listBox.Items.IndexOf(button.DataContext)];
+			string.Concat(item.get_Prefixo(), item.get_Numero()).CopyToClipboard();
+			this.Toggle(string.Concat("COPIADO - ", item.get_Prefixo(), ValidationHelper.OnlyNumber(item.get_Numero())), true);
+		}
+
+		private async Task CreateWhatsappMessage(IndiceArquivoDigital indice)
+		{
+			string str;
+			string str1;
+			Uri uri = await this.ViewModel.CreateLink(indice);
+			StringBuilder stringBuilder = new StringBuilder(uri.ToString());
+			if (indice.get_Assinado())
+			{
+				str = "";
+			}
+			else if (indice.get_EnviadoAssinatura())
+			{
+				string[] newLine = new string[] { "LINK PARA ASSINATURA", Environment.NewLine, indice.get_UrlAssinatura(), Environment.NewLine, Environment.NewLine };
+				str = string.Concat(newLine);
+			}
+			else
+			{
+				str = "";
+			}
+			StringBuilder stringBuilder1 = new StringBuilder(str);
+			foreach (IndiceArquivoDigital arquivo in this.ViewModel.Arquivos)
+			{
+				if (arquivo.get_Selecionado() && arquivo.get_IdArquivoDigital() != indice.get_IdArquivoDigital())
+				{
+					if (stringBuilder.Length > 0)
+					{
+						stringBuilder.AppendLine("\r\n");
+						stringBuilder1.AppendLine();
+					}
+					StringBuilder stringBuilder2 = stringBuilder;
+					uri = await this.ViewModel.CreateLink(arquivo);
+					stringBuilder2.AppendLine(uri.ToString());
+					stringBuilder2 = null;
+					StringBuilder stringBuilder3 = stringBuilder1;
+					if (arquivo.get_Assinado())
+					{
+						str1 = "";
+					}
+					else if (arquivo.get_EnviadoAssinatura())
+					{
+						string[] strArrays = new string[] { "LINK PARA ASSINATURA", Environment.NewLine, arquivo.get_UrlAssinatura(), Environment.NewLine, Environment.NewLine };
+						str1 = string.Concat(strArrays);
+					}
+					else
+					{
+						str1 = "";
+					}
+					stringBuilder3.AppendLine(str1);
+				}
+			}
+			string str2 = this.ViewModel.CarregarMensagem().Replace("[*LINK*]", string.Format("LINK(S) PARA BAIXAR O(S) DOCUMENTO(S) (VÁLIDO(S) POR 7 DIAS){0}{1}", Environment.NewLine, stringBuilder)).Replace("<|LINKASSINATURA|>", stringBuilder1.ToString());
+			stringBuilder = null;
+			stringBuilder1 = null;
+			return str2;
+		}
+
+		private void DeleteArquivo_OnDeleteClick(object sender, RoutedEventArgs e)
+		{
+			Chip chip = sender as Chip;
+			if (chip == null)
+			{
+				return;
+			}
+			ListBox listBox = Extentions.FindVisualAncestor(chip);
+			Gestor.Model.Domain.Common.ArquivoDigital item = (Gestor.Model.Domain.Common.ArquivoDigital)listBox.Items[listBox.Items.IndexOf(chip.DataContext)];
+			if (item == null)
+			{
+				return;
+			}
+			this.ViewModel.Delete(item);
+		}
+
+		private static void DocumentBox_OnLostFocus(object sender, RoutedEventArgs e)
+		{
+			TextBox textBox = (TextBox)sender;
+			if (textBox.Text == string.Empty)
+			{
+				return;
+			}
+			textBox.Text = ValidationHelper.FormatDocument(textBox.Text);
+		}
+
+		private async void Enviar_OnClick(object sender, RoutedEventArgs e)
+		{
+			object obj;
+			MenuItem menuItem = (MenuItem)sender;
+			this.AlteraEventoEnviarOnClick(menuItem, false);
+			if (!this.ViewModel.Restricao(60))
+			{
+				ObservableCollection arquivosTela = this.ViewModel.ArquivosTela;
+				if (arquivosTela.Any((IndiceArquivoDigital x) => x.get_Assinar()))
+				{
+					List produtos = LicenseHelper.Produtos;
+					if (produtos.All((Licenca x) => x.get_Produto() != 86))
+					{
+						Token token = new Token();
+						object[] numeroSerial = new object[] { ApplicationHelper.NumeroSerial, ApplicationHelper.IdFornecedor, Recursos.Usuario.get_Id(), null };
+						obj = (ApplicationHelper.Beta ? "1" : "0");
+						numeroSerial[3] = obj;
+						string str = token.Encrypt(string.Format("{0}:{1}:{2}:{3}", numeroSerial));
+						Parameters parameter = new Parameters();
+						parameter.set_Beta(ApplicationHelper.Beta);
+						parameter.set_Type(8);
+						parameter.set_Application("Assinador.Application.exe");
+						parameter.set_Directory("Assinador.Application");
+						parameter.set_Arguments(str);
+						parameter.set_Run(true);
+						(new DownloadWindow(parameter)).Show();
+						this.AlteraEventoEnviarOnClick(menuItem, true);
+						menuItem = null;
+						return;
+					}
+					else if (!await this.ViewModel.EnviarParaAssinatura())
+					{
+						this.AlteraEventoEnviarOnClick(menuItem, true);
+						menuItem = null;
+						return;
+					}
+				}
+			}
+			else
+			{
+				await this.ViewModel.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA ASSINATURA.\nCONTINUANDO COM O ENVIO APENAS.", "OK", "", false);
+			}
+			MalaDireta malaDiretum = await this.ViewModel.PrepararEnvio();
+			if (malaDiretum != null)
+			{
+				if (Funcoes.IsWindowOpen("ENVIO DE E-MAIL"))
+				{
+					Funcoes.Destroy("ENVIO DE E-MAIL");
+				}
+				List malaDiretas = new List()
+				{
+					malaDiretum
+				};
+				(new HosterWindow(new MalaDiretaView(malaDiretas, this.ViewModel.Assunto, this.ViewModel.Corpo, this.Filtro), "ENVIO DE E-MAIL", new double?((double)1200), new double?((double)600), true)).Show();
+				this.AlteraEventoEnviarOnClick(menuItem, true);
+			}
+			else
+			{
+				this.AlteraEventoEnviarOnClick(menuItem, true);
+			}
+			menuItem = null;
+		}
+
+		private async void EnviarPorWhatsApp_OnClick(object sender, RoutedEventArgs e)
+		{
+			string str;
+			if (!this.ViewModel.Restricao(32))
+			{
+				Button button = (Button)sender;
+				if (button.DataContext != null)
+				{
+					ClienteTelefone dataContext = button.DataContext as ClienteTelefone;
+					if (dataContext != null)
+					{
+						str = (!dataContext.get_Tipo().HasValue || dataContext.get_Tipo().GetValueOrDefault() != 8 ? string.Concat("55", dataContext.get_Prefixo(), dataContext.get_Numero().Clear()) : string.Concat(dataContext.get_Prefixo(), dataContext.get_Numero()).Clear());
+						if (!str.EnviarWhatsapp(this.ViewModel.Anotacoes))
+						{
+							await this.ViewModel.ShowMessage("HOUVE UM PROBLEMA AO ABRIR LINK DO WHATSAPP, O LINK FOI COPIADO EM SUA MAQUINA, BASTA ABRIR O NAVEGADOR DE INTERNET E COLAR NA BARRA DE ENDEREÇOS", "OK", "", false);
+						}
+						return;
+					}
+				}
+			}
+			else
+			{
+				await this.ViewModel.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR O WHATSAPP", "OK", "", false);
+			}
+		}
+
+		private async void Excluir_OnClick(object sender, RoutedEventArgs e)
+		{
+			IndiceArquivoDigital item;
+			Button button = sender as Button;
+			if (button != null)
+			{
+				DataGrid dataGrid = Extentions.FindVisualAncestor(button);
+				item = (IndiceArquivoDigital)dataGrid.Items[dataGrid.Items.IndexOf(button.DataContext)];
+				if (item != null)
+				{
+					this.ViewModel.VerificarEnables(new long?(item.get_Id()));
+					if (!this.ViewModel.EnableExcluir)
+					{
+						await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO TEM PERMISSÃO PARA EXCLUIR ARQUIVO DIGITAL DO TIPO ", ValidationHelper.GetDescription(this.Filtro.get_Tipo()), "!"), "OK", "", false);
+					}
+					else if (item.get_NaoExcluir())
+					{
+						await this.ViewModel.ShowMessage(string.Concat("O ARQUIVO ", item.get_Descricao(), " NÃO PODE SER EXCLUÍDO!"), "OK", "", false);
+					}
+					else if (await this.ViewModel.ShowMessage(string.Concat("DESEJA REALMENTE EXCLUIR O ARQUIVO ", item.get_Descricao()), "SIM", "NÃO", false))
+					{
+						await this.ViewModel.Excluir(item);
+					}
+				}
+			}
+			item = null;
+		}
+
+		private void Fechar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.CloseDrawer();
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		public void InitializeComponent()
+		{
+			if (this._contentLoaded)
+			{
+				return;
+			}
+			this._contentLoaded = true;
+			System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/drawers/arquivodigitaldrawer.xaml", UriKind.Relative));
+		}
+
+		private void LimparLista_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.LimparAnexos();
+		}
+
+		private void Log_OnClick(object sender, RoutedEventArgs e)
+		{
+			Button button = sender as Button;
+			if (button == null)
+			{
+				return;
+			}
+			IndiceArquivoDigital dataContext = (IndiceArquivoDigital)button.DataContext;
+			if (dataContext != null && dataContext.get_Id() != 0)
+			{
+				this.ViewModel.AbrirLog(6, dataContext.get_Id());
+			}
+		}
+
+		private async void PopupBox_OnOpened(object sender, RoutedEventArgs e)
+		{
+			if (this.ViewModel.Telefones.Count == 0)
+			{
+				ObservableCollection telefones = this.ViewModel.Telefones;
+				ClienteTelefone clienteTelefone = new ClienteTelefone();
+				clienteTelefone.set_Prefixo(Recursos.Empresa.get_PrimeiroPrefixo());
+				clienteTelefone.set_Numero(Recursos.Empresa.get_PrimeiroTelefone());
+				telefones.Add(clienteTelefone);
+			}
+			IndiceArquivoDigital dataContext = (IndiceArquivoDigital)((PopupBox)sender).DataContext;
+			ArquivoDigitalViewModel viewModel = this.ViewModel;
+			viewModel.Anotacoes = await this.CreateWhatsappMessage(dataContext);
+			viewModel = null;
+		}
+
+		private async void SalvarAnexos_OnClick(object sender, RoutedEventArgs e)
+		{
+			await this.ViewModel.SalvarAnexos();
+		}
+
+		public void ScrollViewer_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
+		{
+			ScrollViewer scrollViewer = (ScrollViewer)sender;
+			scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset - (double)e.Delta);
+			e.Handled = true;
+		}
+
+		private void SnackbarMessage_ActionClick(object sender, RoutedEventArgs e)
+		{
+			this.SnackbarArquivoDigital.set_IsActive(false);
+		}
+
+		private static void SomenteNumeros(object sender, TextCompositionEventArgs e)
+		{
+			Regex regex = new Regex("[^0-9]+");
+			e.Handled = regex.IsMatch(e.Text);
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target)
+		{
+			switch (connectionId)
+			{
+				case 1:
+				{
+					((ScrollViewer)target).PreviewMouseWheel += new MouseWheelEventHandler(this.ScrollViewer_PreviewMouseWheel);
+					return;
+				}
+				case 2:
+				{
+					this.ProgressBar = (System.Windows.Controls.ProgressBar)target;
+					return;
+				}
+				case 3:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.Fechar_OnClick);
+					return;
+				}
+				case 4:
+				{
+					this.TitleBox = (TextBlock)target;
+					return;
+				}
+				case 5:
+				case 6:
+				case 9:
+				case 10:
+				case 11:
+				case 12:
+				case 13:
+				case 14:
+				case 15:
+				case 21:
+				{
+					this._contentLoaded = true;
+					return;
+				}
+				case 7:
+				{
+					((TextBox)target).TextChanged += new TextChangedEventHandler(this.TextBoxBase_OnTextChanged);
+					return;
+				}
+				case 8:
+				{
+					this.ArquivoGrid = (DataGrid)target;
+					return;
+				}
+				case 16:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.AnexarArquivos_OnClick);
+					return;
+				}
+				case 17:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.BaixarTodos_OnClick);
+					return;
+				}
+				case 18:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Enviar_OnClick);
+					return;
+				}
+				case 19:
+				{
+					this.DocumentoBox = (TextBox)target;
+					return;
+				}
+				case 20:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.Assinar_OnClick);
+					return;
+				}
+				case 22:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.SalvarAnexos_OnClick);
+					return;
+				}
+				case 23:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.LimparLista_OnClick);
+					return;
+				}
+				case 24:
+				{
+					this.SnackbarArquivoDigital = (Snackbar)target;
+					return;
+				}
+				case 25:
+				{
+					((SnackbarMessage)target).add_ActionClick(new RoutedEventHandler(this.SnackbarMessage_ActionClick));
+					return;
+				}
+				default:
+				{
+					this._contentLoaded = true;
+					return;
+				}
+			}
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target)
+		{
+			switch (connectionId)
+			{
+				case 5:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.CopyTelefoneToClipBoard_Click);
+					return;
+				}
+				case 6:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.WhatsAppMessage_Click);
+					return;
+				}
+				case 7:
+				case 8:
+				case 16:
+				case 17:
+				case 18:
+				case 19:
+				case 20:
+				{
+					return;
+				}
+				case 9:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.CopiarLinkAssinatura_OnClick);
+					return;
+				}
+				case 10:
+				{
+					((PopupBox)target).add_Opened(new RoutedEventHandler(this.PopupBox_OnOpened));
+					return;
+				}
+				case 11:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.EnviarPorWhatsApp_OnClick);
+					return;
+				}
+				case 12:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.Abrir_OnClick);
+					return;
+				}
+				case 13:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.Baixar_OnClick);
+					return;
+				}
+				case 14:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.Log_OnClick);
+					return;
+				}
+				case 15:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.Excluir_OnClick);
+					return;
+				}
+				case 21:
+				{
+					((Chip)target).add_DeleteClick(new RoutedEventHandler(this.DeleteArquivo_OnDeleteClick));
+					return;
+				}
+				default:
+				{
+					return;
+				}
+			}
+		}
+
+		private void TextBoxBase_OnTextChanged(object sender, TextChangedEventArgs e)
+		{
+			string text = ((TextBox)sender).Text;
+			if (text.Length < 3)
+			{
+				this.ViewModel.ArquivosTela = this.ViewModel.Arquivos;
+				return;
+			}
+			List list = (
+				from x in this.ViewModel.Arquivos
+				where x.get_Descricao().Contains(text)
+				select x).ToList();
+			if (list.Count <= 0)
+			{
+				this.ViewModel.ArquivosTela = new ObservableCollection();
+				return;
+			}
+			this.ViewModel.ArquivosTela = new ObservableCollection();
+			list.ForEach((IndiceArquivoDigital x) => this.ViewModel.ArquivosTela.Add(x));
+		}
+
+		public void Toggle(string message, bool active = true)
+		{
+			this.SnackbarArquivoDigital.get_Message().Content = message;
+			this.SnackbarArquivoDigital.set_IsActive(active);
+			if (!active)
+			{
+				return;
+			}
+			Task.Factory.StartNew(new Action(this.CloseSlackBar));
+		}
+
+		private async void WhatsAppMessage_Click(object sender, RoutedEventArgs e)
+		{
+			string str;
+			if (!this.ViewModel.Restricao(32))
+			{
+				Button button = (Button)sender;
+				ListBox listBox = Extentions.FindVisualAncestor(button);
+				ClienteTelefone item = (ClienteTelefone)listBox.Items[listBox.Items.IndexOf(button.DataContext)];
+				str = (!item.get_Tipo().HasValue || item.get_Tipo().GetValueOrDefault() != 8 ? string.Concat("55", item.get_Prefixo(), item.get_Numero().Clear()) : string.Concat(item.get_Prefixo(), item.get_Numero()).Clear());
+				if (!str.EnviarWhatsapp(null))
+				{
+					await this.ViewModel.ShowMessage("HOUVE UM PROBLEMA AO ABRIR LINK DO WHATSAPP, O LINK FOI COPIADO EM SUA MAQUINA, BASTA ABRIR O NAVEGADOR DE INTERNET E COLAR NA BARRA DE ENDEREÇOS", "OK", "", false);
+				}
+			}
+			else
+			{
+				await this.ViewModel.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA ESSE MENU.", "OK", "", false);
+			}
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Drawers/Configuracoes/ConfiguracoesDrawer.cs b/Codemerx/Gestor.Application/Drawers/Configuracoes/ConfiguracoesDrawer.cs
new file mode 100644
index 0000000..84a2223
--- /dev/null
+++ b/Codemerx/Gestor.Application/Drawers/Configuracoes/ConfiguracoesDrawer.cs
@@ -0,0 +1,159 @@
+using Gestor.Application.ViewModels.Configuracoes;
+using Gestor.Application.ViewModels.Generic;
+using Gestor.Model.Domain.Configuracoes;
+using System;
+using System.CodeDom.Compiler;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Markup;
+using System.Windows.Threading;
+
+namespace Gestor.Application.Drawers.Configuracoes
+{
+	public class ConfiguracoesDrawer : UserControl, IComponentConnector, IStyleConnector
+	{
+		internal System.Windows.Controls.ProgressBar ProgressBar;
+
+		internal DataGrid VendedorGrid;
+
+		private bool _contentLoaded;
+
+		private ConfiguracoesViewModel ViewModel
+		{
+			get;
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		internal Delegate _CreateDelegate(Type delegateType, string handler)
+		{
+			return Delegate.CreateDelegate(delegateType, this, handler);
+		}
+
+		public ConfiguracoesDrawer()
+		{
+			this.ViewModel = new ConfiguracoesViewModel();
+			base.DataContext = this.ViewModel;
+			this.InitializeComponent();
+			System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher;
+			if (dispatcher == null)
+			{
+				return;
+			}
+			dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad));
+		}
+
+		private void AbrirLog_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.AbrirLog(50, (long)0);
+		}
+
+		private async void AdicionarConfiguracao_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.Carregando = true;
+			if (this.ViewModel.SelectedConfiguracao == 15 || this.ViewModel.SelectedConfiguracao == 26 || this.ViewModel.SelectedConfiguracao == 34 || this.ViewModel.SelectedConfiguracao == 53)
+			{
+				bool? nullable = await this.ViewModel.ShowSenha("OPÇÃO RESTRITA A ADMINISTRADORES DO SISTEMA, PREENCHA A SENHA ADM PARA PROSSEGUIR.");
+				if (!nullable.HasValue)
+				{
+					this.ViewModel.Carregando = false;
+					return;
+				}
+				else if (!nullable.GetValueOrDefault())
+				{
+					await this.ViewModel.ShowMessage("SENHA INVÁLIDA", "OK", "", false);
+					this.ViewModel.Carregando = false;
+					return;
+				}
+			}
+			await this.ViewModel.Salvar();
+			this.ViewModel.Carregando = false;
+		}
+
+		private async void ContentLoad()
+		{
+			this.ViewModel.Carregando = true;
+			await this.ViewModel.BuscarConfiguracoes();
+			this.ViewModel.Carregando = false;
+		}
+
+		private async void ExcluirConfiguracao_OnClick(object sender, RoutedEventArgs e)
+		{
+			Button button = (Button)sender;
+			if (button != null && button.DataContext != null)
+			{
+				this.ViewModel.Carregando = true;
+				await this.ViewModel.Excluir((ConfiguracaoSistema)button.DataContext);
+				this.ViewModel.Carregando = false;
+			}
+		}
+
+		private void Fechar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.CloseDrawer();
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		public void InitializeComponent()
+		{
+			if (this._contentLoaded)
+			{
+				return;
+			}
+			this._contentLoaded = true;
+			System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/drawers/configuracoes/configuracoesdrawer.xaml", UriKind.Relative));
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target)
+		{
+			switch (connectionId)
+			{
+				case 1:
+				{
+					this.ProgressBar = (System.Windows.Controls.ProgressBar)target;
+					return;
+				}
+				case 2:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.Fechar_OnClick);
+					return;
+				}
+				case 3:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick);
+					return;
+				}
+				case 4:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.AdicionarConfiguracao_OnClick);
+					return;
+				}
+				case 5:
+				{
+					this.VendedorGrid = (DataGrid)target;
+					return;
+				}
+			}
+			this._contentLoaded = true;
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target)
+		{
+			if (connectionId == 6)
+			{
+				((Button)target).Click += new RoutedEventHandler(this.ExcluirConfiguracao_OnClick);
+			}
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Drawers/ExpedicaoDrawer.cs b/Codemerx/Gestor.Application/Drawers/ExpedicaoDrawer.cs
new file mode 100644
index 0000000..50ab8e8
--- /dev/null
+++ b/Codemerx/Gestor.Application/Drawers/ExpedicaoDrawer.cs
@@ -0,0 +1,265 @@
+using Gestor.Application.ViewModels.Drawer;
+using Gestor.Application.ViewModels.Generic;
+using Gestor.Application.Views.Generic;
+using Gestor.Model.Domain.Generic;
+using Gestor.Model.Domain.Seguros;
+using MaterialDesignThemes.Wpf;
+using System;
+using System.CodeDom.Compiler;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Input;
+using System.Windows.Markup;
+using System.Windows.Threading;
+
+namespace Gestor.Application.Drawers
+{
+	public class ExpedicaoDrawer : BaseUserControl, IComponentConnector
+	{
+		internal System.Windows.Controls.ProgressBar ProgressBar;
+
+		internal TextBox DocumentoBox;
+
+		internal TextBox DestinoBox;
+
+		internal DatePicker EnvioBox;
+
+		internal DatePicker RecebimentoBox;
+
+		internal TextBox ResponsavelBox;
+
+		internal DataGrid ExpedicaoGrid;
+
+		internal MaterialDesignThemes.Wpf.Snackbar Snackbar;
+
+		private bool _contentLoaded;
+
+		public ExpedicaoViewModel ViewModel
+		{
+			get;
+			set;
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		internal Delegate _CreateDelegate(Type delegateType, string handler)
+		{
+			return Delegate.CreateDelegate(delegateType, this, handler);
+		}
+
+		public ExpedicaoDrawer(Documento documento)
+		{
+			this.ViewModel = new ExpedicaoViewModel(documento);
+			base.DataContext = this.ViewModel;
+			this.InitializeComponent();
+			System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher;
+			if (dispatcher == null)
+			{
+				return;
+			}
+			dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad));
+		}
+
+		private void Alterar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.Alterar(true);
+		}
+
+		private void Cancelar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.CancelarAlteracao();
+		}
+
+		private void CloseSlackBar()
+		{
+			Thread.Sleep(5000);
+			System.Windows.Threading.Dispatcher dispatcher = this.ProgressBar.Dispatcher;
+			if (dispatcher == null)
+			{
+				return;
+			}
+			dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => this.ToggleSnackBar("", false)));
+		}
+
+		private void ContentLoad()
+		{
+			this.EnvioBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus);
+			this.EnvioBox.PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown);
+			this.RecebimentoBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus);
+			this.RecebimentoBox.PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown);
+		}
+
+		private async void Excluir_OnClick(object sender, RoutedEventArgs e)
+		{
+			if (await this.ViewModel.Excluir())
+			{
+				this.ToggleSnackBar("EXPEDIÇÃO EXCLUÍDA COM SUCESSO", true);
+			}
+		}
+
+		private void Fechar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.CloseDrawer();
+		}
+
+		private void Incluir_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.Incluir();
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		public void InitializeComponent()
+		{
+			if (this._contentLoaded)
+			{
+				return;
+			}
+			this._contentLoaded = true;
+			System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/drawers/expedicaodrawer.xaml", UriKind.Relative));
+		}
+
+		private void Log_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.AbrirLog(46, this.ViewModel.SelectedExpedicao.get_Id());
+		}
+
+		private async void Salvar_OnClick(object sender, RoutedEventArgs e)
+		{
+			bool flag;
+			this.ViewModel.Carregando = true;
+			List> keyValuePairs = await this.ViewModel.Salvar();
+			this.ExpedicaoGrid.Items.Refresh();
+			flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0);
+			this.ViewModel.Carregando = false;
+			if (!flag)
+			{
+				await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", "");
+			}
+			else
+			{
+				this.ToggleSnackBar("EXPEDIÇÃO SALVA COM SUCESSO", true);
+			}
+		}
+
+		private void SnackbarMessage_ActionClick(object sender, RoutedEventArgs e)
+		{
+			this.Snackbar.set_IsActive(false);
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target)
+		{
+			switch (connectionId)
+			{
+				case 1:
+				{
+					this.ProgressBar = (System.Windows.Controls.ProgressBar)target;
+					return;
+				}
+				case 2:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.Fechar_OnClick);
+					return;
+				}
+				case 3:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Incluir_OnClick);
+					return;
+				}
+				case 4:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick);
+					return;
+				}
+				case 5:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick);
+					return;
+				}
+				case 6:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick);
+					return;
+				}
+				case 7:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Excluir_OnClick);
+					return;
+				}
+				case 8:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Log_OnClick);
+					return;
+				}
+				case 9:
+				{
+					this.DocumentoBox = (TextBox)target;
+					return;
+				}
+				case 10:
+				{
+					this.DestinoBox = (TextBox)target;
+					return;
+				}
+				case 11:
+				{
+					this.EnvioBox = (DatePicker)target;
+					this.EnvioBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus);
+					this.EnvioBox.PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown);
+					this.EnvioBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick);
+					return;
+				}
+				case 12:
+				{
+					this.RecebimentoBox = (DatePicker)target;
+					this.RecebimentoBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus);
+					this.RecebimentoBox.PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown);
+					this.RecebimentoBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick);
+					return;
+				}
+				case 13:
+				{
+					this.ResponsavelBox = (TextBox)target;
+					return;
+				}
+				case 14:
+				{
+					this.ExpedicaoGrid = (DataGrid)target;
+					return;
+				}
+				case 15:
+				{
+					this.Snackbar = (MaterialDesignThemes.Wpf.Snackbar)target;
+					return;
+				}
+				case 16:
+				{
+					((SnackbarMessage)target).add_ActionClick(new RoutedEventHandler(this.SnackbarMessage_ActionClick));
+					return;
+				}
+			}
+			this._contentLoaded = true;
+		}
+
+		public void ToggleSnackBar(string message, bool active = true)
+		{
+			this.Snackbar.get_Message().Content = message;
+			this.Snackbar.set_IsActive(active);
+			if (!active)
+			{
+				return;
+			}
+			Task.Factory.StartNew(new Action(this.CloseSlackBar));
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Drawers/ExtratosDrawer.cs b/Codemerx/Gestor.Application/Drawers/ExtratosDrawer.cs
new file mode 100644
index 0000000..890eaec
--- /dev/null
+++ b/Codemerx/Gestor.Application/Drawers/ExtratosDrawer.cs
@@ -0,0 +1,281 @@
+using Gestor.Application.ViewModels.Drawer;
+using Gestor.Application.ViewModels.Generic;
+using Gestor.Application.Views.Generic;
+using Gestor.Model.Common;
+using Gestor.Model.Domain.Relatorios.ClientesAtivosInativos;
+using Gestor.Model.Domain.Seguros;
+using MaterialDesignThemes.Wpf;
+using System;
+using System.CodeDom.Compiler;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Controls.Primitives;
+using System.Windows.Input;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Drawers
+{
+	public class ExtratosDrawer : BaseUserControl, IComponentConnector
+	{
+		internal System.Windows.Controls.ProgressBar ProgressBar;
+
+		internal StackPanel Tipo;
+
+		internal StackPanel Cliente;
+
+		internal ToggleButton ClienteToggle;
+
+		internal StackPanel Documento;
+
+		internal StackPanel Endosso;
+
+		internal StackPanel Item;
+
+		internal StackPanel Perfil;
+
+		internal MaterialDesignThemes.Wpf.Snackbar Snackbar;
+
+		private bool _contentLoaded;
+
+		private static List Clientes
+		{
+			get;
+			set;
+		}
+
+		private static List Documentos
+		{
+			get;
+			set;
+		}
+
+		private static List Prospeccoes
+		{
+			get;
+			set;
+		}
+
+		private static List Selecionados
+		{
+			get;
+			set;
+		}
+
+		private static List SelecionadosPros
+		{
+			get;
+			set;
+		}
+
+		private static Relatorio? TipoRelatorio
+		{
+			get;
+			set;
+		}
+
+		public ExtratosViewModel ViewModel
+		{
+			get;
+			set;
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		internal Delegate _CreateDelegate(Type delegateType, string handler)
+		{
+			return Delegate.CreateDelegate(delegateType, this, handler);
+		}
+
+		public ExtratosDrawer(List clientes = null, List documentos = null, Relatorio? tipoRelatorio = null, List selecionados = null, List selecionadosPros = null, List prospeccaos = null)
+		{
+			ExtratosDrawer.Documentos = documentos;
+			ExtratosDrawer.Prospeccoes = prospeccaos;
+			ExtratosDrawer.Selecionados = selecionados;
+			ExtratosDrawer.Clientes = clientes;
+			ExtratosDrawer.TipoRelatorio = tipoRelatorio;
+			ExtratosDrawer.SelecionadosPros = selecionadosPros;
+			this.ViewModel = new ExtratosViewModel()
+			{
+				TipoDeRelatorio = tipoRelatorio
+			};
+			if (!tipoRelatorio.HasValue)
+			{
+				this.ViewModel.TipoExtratoEnabled = true;
+				this.ViewModel.ClientePorPaginaVisibility = System.Windows.Visibility.Collapsed;
+			}
+			else
+			{
+				switch (tipoRelatorio.GetValueOrDefault())
+				{
+					case 0:
+					{
+						this.ViewModel.TipoExtratoEnabled = false;
+						this.ViewModel.SelectedTipoExtrato = 0;
+						this.ViewModel.SelecionarItensVisibility = System.Windows.Visibility.Collapsed;
+						break;
+					}
+					case 1:
+					case 3:
+					{
+						this.ViewModel.SelectedTipoExtrato = 1;
+						this.ViewModel.SelecionarItensVisibility = System.Windows.Visibility.Collapsed;
+						this.ViewModel.SelecionarItensVisibility = System.Windows.Visibility.Collapsed;
+						break;
+					}
+					case 2:
+					case 4:
+					{
+						this.ViewModel.TipoExtratoEnabled = false;
+						this.ViewModel.SelectedTipoExtrato = 1;
+						this.ViewModel.ClientePorPaginaVisibility = System.Windows.Visibility.Visible;
+						this.ViewModel.SelecionarItensVisibility = System.Windows.Visibility.Collapsed;
+						break;
+					}
+					default:
+					{
+						goto case 3;
+					}
+				}
+			}
+			if (this.ViewModel.SelectedTipoExtrato == null)
+			{
+				this.ViewModel.EsconderResumido = true;
+				this.ViewModel.ClienteVisibility = true;
+			}
+			base.DataContext = this.ViewModel;
+			this.InitializeComponent();
+		}
+
+		private void Fechar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.CloseDrawer();
+		}
+
+		private async void Gerar_OnClick(object sender, RoutedEventArgs e)
+		{
+			if (ExtratosDrawer.Clientes != null)
+			{
+				await this.ViewModel.PrepararExtrato(ExtratosDrawer.Clientes, null, null, ExtratosDrawer.TipoRelatorio, null, null, false);
+			}
+			else if (ExtratosDrawer.Documentos != null || ExtratosDrawer.Prospeccoes != null)
+			{
+				await this.ViewModel.PrepararExtrato(null, ExtratosDrawer.Documentos, ExtratosDrawer.Prospeccoes, ExtratosDrawer.TipoRelatorio, ExtratosDrawer.Selecionados, ExtratosDrawer.SelecionadosPros, false);
+			}
+		}
+
+		private async void GerarPDF_OnClick(object sender, RoutedEventArgs e)
+		{
+			if (ExtratosDrawer.Clientes != null)
+			{
+				await this.ViewModel.PrepararExtrato(ExtratosDrawer.Clientes, null, null, ExtratosDrawer.TipoRelatorio, null, null, true);
+			}
+			else if (ExtratosDrawer.Documentos != null || ExtratosDrawer.Prospeccoes != null)
+			{
+				await this.ViewModel.PrepararExtrato(null, ExtratosDrawer.Documentos, ExtratosDrawer.Prospeccoes, ExtratosDrawer.TipoRelatorio, ExtratosDrawer.Selecionados, ExtratosDrawer.SelecionadosPros, true);
+			}
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		public void InitializeComponent()
+		{
+			if (this._contentLoaded)
+			{
+				return;
+			}
+			this._contentLoaded = true;
+			System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/drawers/extratosdrawer.xaml", UriKind.Relative));
+		}
+
+		private void SnackbarMessage_ActionClick(object sender, RoutedEventArgs e)
+		{
+			this.Snackbar.set_IsActive(false);
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target)
+		{
+			switch (connectionId)
+			{
+				case 1:
+				{
+					((ScrollViewer)target).PreviewMouseWheel += new MouseWheelEventHandler(this.ScrollViewer_PreviewMouseWheel);
+					return;
+				}
+				case 2:
+				{
+					this.ProgressBar = (System.Windows.Controls.ProgressBar)target;
+					return;
+				}
+				case 3:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.Fechar_OnClick);
+					return;
+				}
+				case 4:
+				{
+					this.Tipo = (StackPanel)target;
+					return;
+				}
+				case 5:
+				{
+					this.Cliente = (StackPanel)target;
+					return;
+				}
+				case 6:
+				{
+					this.ClienteToggle = (ToggleButton)target;
+					return;
+				}
+				case 7:
+				{
+					this.Documento = (StackPanel)target;
+					return;
+				}
+				case 8:
+				{
+					this.Endosso = (StackPanel)target;
+					return;
+				}
+				case 9:
+				{
+					this.Item = (StackPanel)target;
+					return;
+				}
+				case 10:
+				{
+					this.Perfil = (StackPanel)target;
+					return;
+				}
+				case 11:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Gerar_OnClick);
+					return;
+				}
+				case 12:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.GerarPDF_OnClick);
+					return;
+				}
+				case 13:
+				{
+					this.Snackbar = (MaterialDesignThemes.Wpf.Snackbar)target;
+					return;
+				}
+				case 14:
+				{
+					((SnackbarMessage)target).add_ActionClick(new RoutedEventHandler(this.SnackbarMessage_ActionClick));
+					return;
+				}
+			}
+			this._contentLoaded = true;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Drawers/ImpostoDrawer.cs b/Codemerx/Gestor.Application/Drawers/ImpostoDrawer.cs
new file mode 100644
index 0000000..648e160
--- /dev/null
+++ b/Codemerx/Gestor.Application/Drawers/ImpostoDrawer.cs
@@ -0,0 +1,296 @@
+using Gestor.Application;
+using Gestor.Application.Helpers;
+using Gestor.Application.ViewModels.Drawer;
+using Gestor.Application.ViewModels.Generic;
+using Gestor.Model.Domain.Generic;
+using MaterialDesignThemes.Wpf;
+using System;
+using System.CodeDom.Compiler;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Controls.Primitives;
+using System.Windows.Markup;
+using System.Windows.Threading;
+
+namespace Gestor.Application.Drawers
+{
+	public class ImpostoDrawer : UserControl, IComponentConnector
+	{
+		private readonly int _tipo;
+
+		private readonly long _id;
+
+		internal System.Windows.Controls.ProgressBar ProgressBar;
+
+		internal TextBlock TitleBox;
+
+		internal ComboBox SeguradoraBox;
+
+		internal ComboBox SeguradoraAlternativaBox;
+
+		internal ComboBox RamoBox;
+
+		internal DataGrid ArquivoGrid;
+
+		internal Snackbar SnackbarImposto;
+
+		private bool _contentLoaded;
+
+		public ImpostoViewModel ViewModel
+		{
+			get;
+			set;
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		internal Delegate _CreateDelegate(Type delegateType, string handler)
+		{
+			return Delegate.CreateDelegate(delegateType, this, handler);
+		}
+
+		public ImpostoDrawer(int tipo, long id)
+		{
+			this._tipo = tipo;
+			this._id = id;
+			this.ViewModel = new ImpostoViewModel();
+			base.DataContext = this.ViewModel;
+			this.InitializeComponent();
+			System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher;
+			if (dispatcher == null)
+			{
+				return;
+			}
+			dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad));
+		}
+
+		private void Alterar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.AlterarImposto();
+		}
+
+		private async void Cancelar_OnClick(object sender, RoutedEventArgs e)
+		{
+			await this.ViewModel.Cancelar();
+		}
+
+		private void CloseSlackBar()
+		{
+			Thread.Sleep(5000);
+			System.Windows.Threading.Dispatcher dispatcher = App.ProgressRing.Dispatcher;
+			if (dispatcher == null)
+			{
+				return;
+			}
+			dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => this.Toggle("", false)));
+		}
+
+		private async void ContentLoad()
+		{
+			this.ViewModel.Carregando = true;
+			await this.ViewModel.Carregar(this._tipo, this._id);
+			this.SeguradoraBox.SelectionChanged += new SelectionChangedEventHandler(this.Indice_OnSelectionChanged);
+			this.SeguradoraAlternativaBox.SelectionChanged += new SelectionChangedEventHandler(this.Indice_OnSelectionChanged);
+			this.RamoBox.SelectionChanged += new SelectionChangedEventHandler(this.Indice_OnSelectionChanged);
+			this.ViewModel.Carregando = false;
+		}
+
+		private void Fechar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.CloseDrawer();
+		}
+
+		private void Incluir_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.Incluir();
+		}
+
+		private async void Indice_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
+		{
+			if (!this.ViewModel.Carregando)
+			{
+				this.ViewModel.Carregando = true;
+				await this.ViewModel.Carregar((long)0);
+				this.ViewModel.Carregando = false;
+			}
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		public void InitializeComponent()
+		{
+			if (this._contentLoaded)
+			{
+				return;
+			}
+			this._contentLoaded = true;
+			System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/drawers/impostodrawer.xaml", UriKind.Relative));
+		}
+
+		private void Log_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.AbrirLog(56, this.ViewModel.SelectedImposto.get_Id());
+		}
+
+		private async void Salvar_OnClick(object sender, RoutedEventArgs e)
+		{
+			bool flag;
+			this.ViewModel.Carregando = true;
+			List> keyValuePairs = await this.ViewModel.Salvar();
+			this.ValidateFields(keyValuePairs, true);
+			flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0);
+			this.ViewModel.Carregando = false;
+			if (!flag)
+			{
+				await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", "");
+			}
+			else
+			{
+				this.Toggle("PARÂMETRO SALVO COM SUCESSO.", true);
+			}
+		}
+
+		private void SnackbarMessage_ActionClick(object sender, RoutedEventArgs e)
+		{
+			this.SnackbarImposto.set_IsActive(false);
+		}
+
+		private async void Status_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
+		{
+			bool? nullable;
+			string str;
+			ListBox listBox = (ListBox)sender;
+			if (listBox.SelectedItem != null)
+			{
+				ImpostoViewModel viewModel = this.ViewModel;
+				if (listBox.SelectedIndex == 0)
+				{
+					nullable = new bool?(true);
+				}
+				else if (listBox.SelectedIndex == 1)
+				{
+					nullable = new bool?(false);
+				}
+				else
+				{
+					nullable = null;
+				}
+				viewModel.Ativo = nullable;
+				TextBlock titleBox = this.TitleBox;
+				if (listBox.SelectedIndex == 0)
+				{
+					str = "IMPOSTOS ATIVOS";
+				}
+				else
+				{
+					str = (listBox.SelectedIndex == 1 ? "IMPOSTOS INATIVOS" : "TODOS IMPOSTOS");
+				}
+				titleBox.Text = str;
+				await this.ViewModel.Carregar((long)0);
+			}
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target)
+		{
+			switch (connectionId)
+			{
+				case 1:
+				{
+					this.ProgressBar = (System.Windows.Controls.ProgressBar)target;
+					return;
+				}
+				case 2:
+				{
+					((ListBox)target).SelectionChanged += new SelectionChangedEventHandler(this.Status_OnSelectionChanged);
+					return;
+				}
+				case 3:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.Fechar_OnClick);
+					return;
+				}
+				case 4:
+				{
+					this.TitleBox = (TextBlock)target;
+					return;
+				}
+				case 5:
+				{
+					this.SeguradoraBox = (ComboBox)target;
+					return;
+				}
+				case 6:
+				{
+					this.SeguradoraAlternativaBox = (ComboBox)target;
+					return;
+				}
+				case 7:
+				{
+					this.RamoBox = (ComboBox)target;
+					return;
+				}
+				case 8:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Incluir_OnClick);
+					return;
+				}
+				case 9:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick);
+					return;
+				}
+				case 10:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick);
+					return;
+				}
+				case 11:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick);
+					return;
+				}
+				case 12:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Log_OnClick);
+					return;
+				}
+				case 13:
+				{
+					this.ArquivoGrid = (DataGrid)target;
+					return;
+				}
+				case 14:
+				{
+					this.SnackbarImposto = (Snackbar)target;
+					return;
+				}
+				case 15:
+				{
+					((SnackbarMessage)target).add_ActionClick(new RoutedEventHandler(this.SnackbarMessage_ActionClick));
+					return;
+				}
+			}
+			this._contentLoaded = true;
+		}
+
+		public void Toggle(string message, bool active = true)
+		{
+			this.SnackbarImposto.get_Message().Content = message;
+			this.SnackbarImposto.set_IsActive(active);
+			if (!active)
+			{
+				return;
+			}
+			Task.Factory.StartNew(new Action(this.CloseSlackBar));
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Drawers/InclusaoArquivoDigitalDrawer.cs b/Codemerx/Gestor.Application/Drawers/InclusaoArquivoDigitalDrawer.cs
new file mode 100644
index 0000000..e8013e2
--- /dev/null
+++ b/Codemerx/Gestor.Application/Drawers/InclusaoArquivoDigitalDrawer.cs
@@ -0,0 +1,186 @@
+using Gestor.Application;
+using Gestor.Application.ViewModels.Drawer;
+using Gestor.Application.ViewModels.Generic;
+using Gestor.Model.Common;
+using Gestor.Model.Domain.Common;
+using MaterialDesignThemes.Wpf;
+using System;
+using System.CodeDom.Compiler;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Markup;
+using System.Windows.Threading;
+using Xceed.Wpf.AvalonDock.Controls;
+
+namespace Gestor.Application.Drawers
+{
+	public class InclusaoArquivoDigitalDrawer : UserControl, IComponentConnector, IStyleConnector
+	{
+		internal System.Windows.Controls.ProgressBar ProgressBar;
+
+		internal Snackbar SnackbarArquivoDigital;
+
+		private bool _contentLoaded;
+
+		public TarefaDrawerViewModel ViewModel
+		{
+			get;
+			set;
+		}
+
+		public InclusaoArquivoDigitalDrawer(TarefaDrawerViewModel viewModel)
+		{
+			this.ViewModel = viewModel;
+			base.DataContext = this.ViewModel;
+			this.InitializeComponent();
+			this.ViewModel.RegistrarAcao("ACESSOU ANEXO ARQUIVO DIGITAL", (long)0, new TipoTela?(6), null);
+		}
+
+		private void AnexarArquivos_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.Anexar();
+		}
+
+		private void CloseSlackBar()
+		{
+			Thread.Sleep(5000);
+			System.Windows.Threading.Dispatcher dispatcher = App.ProgressRing.Dispatcher;
+			if (dispatcher == null)
+			{
+				return;
+			}
+			dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => this.Toggle("", false)));
+		}
+
+		private void DeleteArquivo_OnDeleteClick(object sender, RoutedEventArgs e)
+		{
+			Chip chip = sender as Chip;
+			if (chip == null)
+			{
+				return;
+			}
+			ListBox listBox = Extentions.FindVisualAncestor(chip);
+			ArquivoDigital item = (ArquivoDigital)listBox.Items[listBox.Items.IndexOf(chip.DataContext)];
+			if (item == null)
+			{
+				return;
+			}
+			this.ViewModel.Delete(item);
+		}
+
+		private void Fechar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.CloseDrawer();
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		public void InitializeComponent()
+		{
+			if (this._contentLoaded)
+			{
+				return;
+			}
+			this._contentLoaded = true;
+			System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/drawers/inclusaoarquivodigitaldrawer.xaml", UriKind.Relative));
+		}
+
+		private void LimparLista_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.LimparAnexos();
+		}
+
+		private void SalvarAnexos_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.SalvarAnexos();
+			this.ViewModel.CloseDrawer();
+		}
+
+		private void SnackbarMessage_ActionClick(object sender, RoutedEventArgs e)
+		{
+			this.SnackbarArquivoDigital.set_IsActive(false);
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target)
+		{
+			switch (connectionId)
+			{
+				case 1:
+				{
+					this.ProgressBar = (System.Windows.Controls.ProgressBar)target;
+					return;
+				}
+				case 2:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.Fechar_OnClick);
+					return;
+				}
+				case 3:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.AnexarArquivos_OnClick);
+					return;
+				}
+				case 4:
+				{
+					this._contentLoaded = true;
+					return;
+				}
+				case 5:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.SalvarAnexos_OnClick);
+					return;
+				}
+				case 6:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.LimparLista_OnClick);
+					return;
+				}
+				case 7:
+				{
+					this.SnackbarArquivoDigital = (Snackbar)target;
+					return;
+				}
+				case 8:
+				{
+					((SnackbarMessage)target).add_ActionClick(new RoutedEventHandler(this.SnackbarMessage_ActionClick));
+					return;
+				}
+				default:
+				{
+					this._contentLoaded = true;
+					return;
+				}
+			}
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target)
+		{
+			if (connectionId == 4)
+			{
+				((Chip)target).add_DeleteClick(new RoutedEventHandler(this.DeleteArquivo_OnDeleteClick));
+			}
+		}
+
+		public void Toggle(string message, bool active = true)
+		{
+			this.SnackbarArquivoDigital.get_Message().Content = message;
+			this.SnackbarArquivoDigital.set_IsActive(active);
+			if (!active)
+			{
+				return;
+			}
+			Task.Factory.StartNew(new Action(this.CloseSlackBar));
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Drawers/InfoDrawer.cs b/Codemerx/Gestor.Application/Drawers/InfoDrawer.cs
new file mode 100644
index 0000000..f21deb5
--- /dev/null
+++ b/Codemerx/Gestor.Application/Drawers/InfoDrawer.cs
@@ -0,0 +1,219 @@
+using Gestor.Application.Helpers;
+using Gestor.Application.ViewModels.Drawer;
+using Gestor.Application.ViewModels.Generic;
+using Gestor.Application.Views.Generic;
+using Gestor.Model.Common;
+using Gestor.Model.Domain.Common;
+using Gestor.Model.Domain.Generic;
+using Gestor.Model.Domain.Seguros;
+using MaterialDesignThemes.Wpf;
+using System;
+using System.CodeDom.Compiler;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Markup;
+using Xceed.Wpf.AvalonDock.Controls;
+
+namespace Gestor.Application.Drawers
+{
+	public class InfoDrawer : BaseUserControl, IComponentConnector, IStyleConnector
+	{
+		internal System.Windows.Controls.ProgressBar ProgressBar;
+
+		internal DataGrid ParcelaGrid;
+
+		internal DataGridTextColumn ParcelasValorColumn;
+
+		internal DataGridTextColumn ParcelasRealizadoColumn;
+
+		internal DataGridTextColumn ParcelasComissaoColumn;
+
+		internal DataGridTextColumn ParcelasReciboColumn;
+
+		internal DataGrid ItemGrid;
+
+		internal MaterialDesignThemes.Wpf.Snackbar Snackbar;
+
+		private bool _contentLoaded;
+
+		public InfoViewModel ViewModel
+		{
+			get;
+			set;
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		internal Delegate _CreateDelegate(Type delegateType, string handler)
+		{
+			return Delegate.CreateDelegate(delegateType, this, handler);
+		}
+
+		public InfoDrawer(Documento documento, bool ocultarInfos = false)
+		{
+			long? nullable;
+			string str;
+			this.ViewModel = new InfoViewModel(documento, ocultarInfos);
+			base.DataContext = this.ViewModel;
+			this.InitializeComponent();
+			InfoViewModel viewModel = this.ViewModel;
+			if ((documento != null ? documento.get_Id() != (long)0 : true))
+			{
+				if (documento != null)
+				{
+					nullable = new long?(documento.get_Id());
+				}
+				else
+				{
+					nullable = null;
+				}
+				str = string.Format(" DO DOCUMENTO DE ID \"{0}\"", nullable);
+			}
+			else
+			{
+				str = "";
+			}
+			viewModel.RegistrarAcao(string.Concat("ACESSOU INFORMAÇÕES", str), (documento != null ? documento.get_Id() : (long)0), new TipoTela?(2), this.ViewModel.GerarObs(documento));
+		}
+
+		private void CopyTelefoneToClipBoard_Click(object sender, RoutedEventArgs e)
+		{
+			Button button = (Button)sender;
+			ListBox listBox = Extentions.FindVisualAncestor(button);
+			Contato item = (Contato)listBox.Items[listBox.Items.IndexOf(button.DataContext)];
+			item.get_Numero().CopyToClipboard();
+			this.ViewModel.ToggleSnackBar(string.Concat("COPIADO - ", item.get_Numero()), true);
+		}
+
+		private void Fechar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.CloseDrawer();
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		public void InitializeComponent()
+		{
+			if (this._contentLoaded)
+			{
+				return;
+			}
+			this._contentLoaded = true;
+			System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/drawers/infodrawer.xaml", UriKind.Relative));
+		}
+
+		private void SnackbarMessage_ActionClick(object sender, RoutedEventArgs e)
+		{
+			this.Snackbar.set_IsActive(false);
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target)
+		{
+			switch (connectionId)
+			{
+				case 1:
+				{
+					this.ProgressBar = (System.Windows.Controls.ProgressBar)target;
+					return;
+				}
+				case 2:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.Fechar_OnClick);
+					return;
+				}
+				case 3:
+				case 4:
+				{
+					this._contentLoaded = true;
+					return;
+				}
+				case 5:
+				{
+					this.ParcelaGrid = (DataGrid)target;
+					return;
+				}
+				case 6:
+				{
+					this.ParcelasValorColumn = (DataGridTextColumn)target;
+					return;
+				}
+				case 7:
+				{
+					this.ParcelasRealizadoColumn = (DataGridTextColumn)target;
+					return;
+				}
+				case 8:
+				{
+					this.ParcelasComissaoColumn = (DataGridTextColumn)target;
+					return;
+				}
+				case 9:
+				{
+					this.ParcelasReciboColumn = (DataGridTextColumn)target;
+					return;
+				}
+				case 10:
+				{
+					this.ItemGrid = (DataGrid)target;
+					return;
+				}
+				case 11:
+				{
+					this.Snackbar = (MaterialDesignThemes.Wpf.Snackbar)target;
+					return;
+				}
+				case 12:
+				{
+					((SnackbarMessage)target).add_ActionClick(new RoutedEventHandler(this.SnackbarMessage_ActionClick));
+					return;
+				}
+				default:
+				{
+					this._contentLoaded = true;
+					return;
+				}
+			}
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target)
+		{
+			if (connectionId == 3)
+			{
+				((Button)target).Click += new RoutedEventHandler(this.CopyTelefoneToClipBoard_Click);
+				return;
+			}
+			if (connectionId != 4)
+			{
+				return;
+			}
+			((Button)target).Click += new RoutedEventHandler(this.WhatsAppMessage_Click);
+		}
+
+		private async void WhatsAppMessage_Click(object sender, RoutedEventArgs e)
+		{
+			if (!this.ViewModel.Restricao(32))
+			{
+				Button button = (Button)sender;
+				ListBox listBox = Extentions.FindVisualAncestor(button);
+				if (!string.Concat("55", ((Contato)listBox.Items[listBox.Items.IndexOf(button.DataContext)]).get_Numero().Clear()).EnviarWhatsapp(null))
+				{
+					await this.ViewModel.ShowMessage("HOUVE UM PROBLEMA AO ABRIR LINK DO WHATSAPP, O LINK FOI COPIADO EM SUA MAQUINA, BASTA ABRIR O NAVEGADOR DE INTERNET E COLAR NA BARRA DE ENDEREÇOS", "OK", "", false);
+				}
+			}
+			else
+			{
+				await this.ViewModel.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR O WHATSAPP", "OK", "", false);
+			}
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Drawers/LogDrawer.cs b/Codemerx/Gestor.Application/Drawers/LogDrawer.cs
new file mode 100644
index 0000000..5e1cec9
--- /dev/null
+++ b/Codemerx/Gestor.Application/Drawers/LogDrawer.cs
@@ -0,0 +1,90 @@
+using Assinador.Infrastructure.Helpers;
+using Gestor.Application.ViewModels.Drawer;
+using Gestor.Application.ViewModels.Generic;
+using Gestor.Application.Views.Generic;
+using Gestor.Model.Common;
+using System;
+using System.CodeDom.Compiler;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Drawers
+{
+	public class LogDrawer : BaseUserControl, IComponentConnector
+	{
+		private bool _contentLoaded;
+
+		public LogViewModel ViewModel
+		{
+			get;
+			set;
+		}
+
+		public LogDrawer(TipoTela tela, long id, List parcelas = null, int numParcela = 0)
+		{
+			this.ViewModel = new LogViewModel(tela, id, parcelas, numParcela);
+			base.DataContext = this.ViewModel;
+			this.InitializeComponent();
+			string description = Functions.GetDescription(tela);
+			this.ViewModel.RegistrarAcao(string.Format("ACESSOU LOG DE ALTERAÇÕES DE {0} DO ID \"{1}\"", description, id), id, new TipoTela?(tela), string.Format("ID ENTIDADE: {0}\nTIPO: {1}", id, description));
+		}
+
+		private void Fechar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.CloseDrawer();
+		}
+
+		private void Imprimir_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.Imprimir();
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		public void InitializeComponent()
+		{
+			if (this._contentLoaded)
+			{
+				return;
+			}
+			this._contentLoaded = true;
+			System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/drawers/logdrawer.xaml", UriKind.Relative));
+		}
+
+		private void MostrarCampos_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.MostrarCampos();
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target)
+		{
+			switch (connectionId)
+			{
+				case 1:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.Fechar_OnClick);
+					return;
+				}
+				case 2:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.Imprimir_OnClick);
+					return;
+				}
+				case 3:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.MostrarCampos_OnClick);
+					return;
+				}
+			}
+			this._contentLoaded = true;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Drawers/LogEmailDrawer.cs b/Codemerx/Gestor.Application/Drawers/LogEmailDrawer.cs
new file mode 100644
index 0000000..5dd6981
--- /dev/null
+++ b/Codemerx/Gestor.Application/Drawers/LogEmailDrawer.cs
@@ -0,0 +1,75 @@
+using Assinador.Infrastructure.Helpers;
+using Gestor.Application.ViewModels.Drawer;
+using Gestor.Application.ViewModels.Generic;
+using Gestor.Application.Views.Generic;
+using Gestor.Model.Common;
+using System;
+using System.CodeDom.Compiler;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Drawers
+{
+	public class LogEmailDrawer : BaseUserControl, IComponentConnector
+	{
+		private bool _contentLoaded;
+
+		public LogEmailViewModel ViewModel
+		{
+			get;
+			set;
+		}
+
+		public LogEmailDrawer(TipoTela tela, long id, bool singleMode = false)
+		{
+			this.ViewModel = new LogEmailViewModel(tela, id, singleMode);
+			base.DataContext = this.ViewModel;
+			this.InitializeComponent();
+			this.ViewModel.RegistrarAcao(string.Format("ACESSOU LOG DE E-MAIL DE {0} DO ID \"{1}\"", Functions.GetDescription(tela), id), id, new TipoTela?(tela), string.Format("ID ENTIDADE: {0}\nTIPO: {1}", id, Functions.GetDescription(tela)));
+		}
+
+		private void Fechar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.CloseDrawer();
+		}
+
+		private void Imprimir_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.Imprimir();
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		public void InitializeComponent()
+		{
+			if (this._contentLoaded)
+			{
+				return;
+			}
+			this._contentLoaded = true;
+			System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/drawers/logemaildrawer.xaml", UriKind.Relative));
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target)
+		{
+			if (connectionId == 1)
+			{
+				((Button)target).Click += new RoutedEventHandler(this.Fechar_OnClick);
+				return;
+			}
+			if (connectionId != 2)
+			{
+				this._contentLoaded = true;
+				return;
+			}
+			((Button)target).Click += new RoutedEventHandler(this.Imprimir_OnClick);
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Drawers/LogSistemaAntigo.cs b/Codemerx/Gestor.Application/Drawers/LogSistemaAntigo.cs
new file mode 100644
index 0000000..051493e
--- /dev/null
+++ b/Codemerx/Gestor.Application/Drawers/LogSistemaAntigo.cs
@@ -0,0 +1,67 @@
+using Gestor.Application.ViewModels.Drawer;
+using Gestor.Application.ViewModels.Generic;
+using Gestor.Model.Common;
+using System;
+using System.CodeDom.Compiler;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Drawers
+{
+	public class LogSistemaAntigo : UserControl, IComponentConnector
+	{
+		private readonly LogSistemaAntigoViewModel _viewModel;
+
+		private bool _contentLoaded;
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		internal Delegate _CreateDelegate(Type delegateType, string handler)
+		{
+			return Delegate.CreateDelegate(delegateType, this, handler);
+		}
+
+		public LogSistemaAntigo(long id, string log)
+		{
+			this._viewModel = new LogSistemaAntigoViewModel();
+			base.DataContext = this._viewModel;
+			this.InitializeComponent();
+			this._viewModel.Descricao = string.Format("LOG DO DOCUMENTO {0}", id);
+			this._viewModel.Log = log;
+			this._viewModel.RegistrarAcao(string.Format("ACESSOU LOG DO SISTEMA ANTIGO DO ID \"{0}\"", id), id, new TipoTela?(2), string.Format("ID ENTIDADE: {0}", id));
+		}
+
+		private void Fechar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this._viewModel.CloseDrawer();
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		public void InitializeComponent()
+		{
+			if (this._contentLoaded)
+			{
+				return;
+			}
+			this._contentLoaded = true;
+			System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/drawers/logsistemaantigo.xaml", UriKind.Relative));
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target)
+		{
+			if (connectionId != 1)
+			{
+				this._contentLoaded = true;
+				return;
+			}
+			((Button)target).Click += new RoutedEventHandler(this.Fechar_OnClick);
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Drawers/LogUtilizacaoDrawer.cs b/Codemerx/Gestor.Application/Drawers/LogUtilizacaoDrawer.cs
new file mode 100644
index 0000000..6fc62db
--- /dev/null
+++ b/Codemerx/Gestor.Application/Drawers/LogUtilizacaoDrawer.cs
@@ -0,0 +1,65 @@
+using Gestor.Application.ViewModels.Drawer;
+using Gestor.Application.ViewModels.Generic;
+using Gestor.Model.Common;
+using Gestor.Model.Domain.Common;
+using System;
+using System.CodeDom.Compiler;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Drawers
+{
+	public class LogUtilizacaoDrawer : UserControl, IComponentConnector
+	{
+		private readonly LogAcaoViewModel _viewModel;
+
+		private bool _contentLoaded;
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		internal Delegate _CreateDelegate(Type delegateType, string handler)
+		{
+			return Delegate.CreateDelegate(delegateType, this, handler);
+		}
+
+		public LogUtilizacaoDrawer(RegistroAcao registro, Relatorio relatorio)
+		{
+			this._viewModel = new LogAcaoViewModel(registro, relatorio);
+			base.DataContext = this._viewModel;
+			this.InitializeComponent();
+		}
+
+		private void Fechar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this._viewModel.CloseDrawer();
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		public void InitializeComponent()
+		{
+			if (this._contentLoaded)
+			{
+				return;
+			}
+			this._contentLoaded = true;
+			System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/drawers/logutilizacaodrawer.xaml", UriKind.Relative));
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target)
+		{
+			if (connectionId != 1)
+			{
+				this._contentLoaded = true;
+				return;
+			}
+			((Button)target).Click += new RoutedEventHandler(this.Fechar_OnClick);
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Drawers/MetaSeguradoraView.cs b/Codemerx/Gestor.Application/Drawers/MetaSeguradoraView.cs
new file mode 100644
index 0000000..b8e8a21
--- /dev/null
+++ b/Codemerx/Gestor.Application/Drawers/MetaSeguradoraView.cs
@@ -0,0 +1,224 @@
+using Gestor.Application.Componentes;
+using Gestor.Application.Helpers;
+using Gestor.Application.ViewModels.Drawer;
+using Gestor.Application.ViewModels.Generic;
+using Gestor.Application.Views.Generic;
+using Gestor.Model.Common;
+using Gestor.Model.Domain.Generic;
+using Gestor.Model.Domain.Seguros;
+using MaterialDesignThemes.Wpf;
+using System;
+using System.CodeDom.Compiler;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Markup;
+using System.Windows.Threading;
+
+namespace Gestor.Application.Drawers
+{
+	public class MetaSeguradoraView : BaseUserControl, IComponentConnector
+	{
+		internal System.Windows.Controls.ProgressBar ProgressBar;
+
+		internal CustomItemValidation FaturaField;
+
+		internal DataGrid MetasGrid;
+
+		internal MaterialDesignThemes.Wpf.Snackbar Snackbar;
+
+		private bool _contentLoaded;
+
+		public MetaSeguradoraViewModel ViewModel
+		{
+			get;
+			set;
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		internal Delegate _CreateDelegate(Type delegateType, string handler)
+		{
+			return Delegate.CreateDelegate(delegateType, this, handler);
+		}
+
+		public MetaSeguradoraView(Seguradora seguradora)
+		{
+			this.ViewModel = new MetaSeguradoraViewModel(seguradora);
+			base.DataContext = this.ViewModel;
+			this.InitializeComponent();
+			this.ViewModel.RegistrarAcao(string.Concat("ACESSOU METAS DE VENDA DA SEGURADORA \"", seguradora.get_Nome(), "\""), seguradora.get_Id(), new TipoTela?(31), string.Format("ID: {0}", seguradora.get_Id()));
+		}
+
+		private void Alterar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.Alterar(true);
+		}
+
+		private void Cancelar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.CancelarAlteracao();
+		}
+
+		private void CloseSlackBar()
+		{
+			Thread.Sleep(5000);
+			System.Windows.Threading.Dispatcher dispatcher = this.ProgressBar.Dispatcher;
+			if (dispatcher == null)
+			{
+				return;
+			}
+			dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => this.ToggleSnackBar("", false)));
+		}
+
+		private async void Excluir_OnClick(object sender, RoutedEventArgs e)
+		{
+			if (await this.ViewModel.Excluir())
+			{
+				this.ToggleSnackBar("META DE VENDA EXCLUÍDA COM SUCESSO", true);
+			}
+		}
+
+		private void Fechar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.CloseDrawer();
+		}
+
+		private void Incluir_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.Incluir();
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		public void InitializeComponent()
+		{
+			if (this._contentLoaded)
+			{
+				return;
+			}
+			this._contentLoaded = true;
+			System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/drawers/metaseguradoraview.xaml", UriKind.Relative));
+		}
+
+		private void Log_OnClick(object sender, RoutedEventArgs e)
+		{
+			if (this.ViewModel.SelectedMetaSeguradora != null)
+			{
+				this.ViewModel.AbrirLog(31, this.ViewModel.SelectedMetaSeguradora.get_Id());
+			}
+		}
+
+		private async void Salvar_OnClick(object sender, RoutedEventArgs e)
+		{
+			bool flag;
+			this.ViewModel.Carregando = true;
+			List> keyValuePairs = await this.ViewModel.Salvar();
+			this.MetasGrid.Items.Refresh();
+			this.ValidateFields(keyValuePairs, true);
+			flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0);
+			this.ViewModel.Carregando = false;
+			if (!flag)
+			{
+				await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", "");
+			}
+			else
+			{
+				this.ToggleSnackBar("META DE VENDA SALVA COM SUCESSO", true);
+			}
+		}
+
+		private void SnackbarMessage_ActionClick(object sender, RoutedEventArgs e)
+		{
+			this.Snackbar.set_IsActive(false);
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target)
+		{
+			switch (connectionId)
+			{
+				case 1:
+				{
+					this.ProgressBar = (System.Windows.Controls.ProgressBar)target;
+					return;
+				}
+				case 2:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.Fechar_OnClick);
+					return;
+				}
+				case 3:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Incluir_OnClick);
+					return;
+				}
+				case 4:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick);
+					return;
+				}
+				case 5:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick);
+					return;
+				}
+				case 6:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick);
+					return;
+				}
+				case 7:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Excluir_OnClick);
+					return;
+				}
+				case 8:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Log_OnClick);
+					return;
+				}
+				case 9:
+				{
+					this.FaturaField = (CustomItemValidation)target;
+					return;
+				}
+				case 10:
+				{
+					this.MetasGrid = (DataGrid)target;
+					return;
+				}
+				case 11:
+				{
+					this.Snackbar = (MaterialDesignThemes.Wpf.Snackbar)target;
+					return;
+				}
+				case 12:
+				{
+					((SnackbarMessage)target).add_ActionClick(new RoutedEventHandler(this.SnackbarMessage_ActionClick));
+					return;
+				}
+			}
+			this._contentLoaded = true;
+		}
+
+		public void ToggleSnackBar(string message, bool active = true)
+		{
+			this.Snackbar.get_Message().Content = message;
+			this.Snackbar.set_IsActive(active);
+			if (!active)
+			{
+				return;
+			}
+			Task.Factory.StartNew(new Action(this.CloseSlackBar));
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Drawers/MetaVendedorView.cs b/Codemerx/Gestor.Application/Drawers/MetaVendedorView.cs
new file mode 100644
index 0000000..da25374
--- /dev/null
+++ b/Codemerx/Gestor.Application/Drawers/MetaVendedorView.cs
@@ -0,0 +1,226 @@
+using CurrencyTextBoxControl;
+using Gestor.Application.Helpers;
+using Gestor.Application.ViewModels.Drawer;
+using Gestor.Application.ViewModels.Generic;
+using Gestor.Application.Views.Generic;
+using Gestor.Model.Domain.Generic;
+using Gestor.Model.Domain.Seguros;
+using MaterialDesignThemes.Wpf;
+using System;
+using System.CodeDom.Compiler;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Markup;
+using System.Windows.Threading;
+
+namespace Gestor.Application.Drawers
+{
+	public class MetaVendedorView : BaseUserControl, IComponentConnector
+	{
+		internal System.Windows.Controls.ProgressBar ProgressBar;
+
+		internal CurrencyTextBox ValorMetaBox;
+
+		internal TextBox AnoBox;
+
+		internal DataGrid MetasGrid;
+
+		internal MaterialDesignThemes.Wpf.Snackbar Snackbar;
+
+		private bool _contentLoaded;
+
+		public MetaVendedorViewModel ViewModel
+		{
+			get;
+			set;
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		internal Delegate _CreateDelegate(Type delegateType, string handler)
+		{
+			return Delegate.CreateDelegate(delegateType, this, handler);
+		}
+
+		public MetaVendedorView(Vendedor vendedor)
+		{
+			this.ViewModel = new MetaVendedorViewModel(vendedor);
+			base.DataContext = this.ViewModel;
+			this.InitializeComponent();
+		}
+
+		private void Alterar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.Alterar(true);
+		}
+
+		private void Cancelar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.CancelarAlteracao();
+		}
+
+		private void CloseSlackBar()
+		{
+			Thread.Sleep(5000);
+			System.Windows.Threading.Dispatcher dispatcher = this.ProgressBar.Dispatcher;
+			if (dispatcher == null)
+			{
+				return;
+			}
+			dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => this.ToggleSnackBar("", false)));
+		}
+
+		private async void Excluir_OnClick(object sender, RoutedEventArgs e)
+		{
+			if (await this.ViewModel.Excluir())
+			{
+				this.ToggleSnackBar("META DE VENDA EXCLUÍDA COM SUCESSO", true);
+			}
+		}
+
+		private void Fechar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.CloseDrawer();
+		}
+
+		private void Incluir_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.Incluir();
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		public void InitializeComponent()
+		{
+			if (this._contentLoaded)
+			{
+				return;
+			}
+			this._contentLoaded = true;
+			System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/drawers/metavendedorview.xaml", UriKind.Relative));
+		}
+
+		private void Log_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.AbrirLog(30, this.ViewModel.SelectedMetaVendedor.get_Id());
+		}
+
+		private async void Salvar_OnClick(object sender, RoutedEventArgs e)
+		{
+			bool flag;
+			this.ViewModel.Carregando = true;
+			List> keyValuePairs = await this.ViewModel.Salvar();
+			this.MetasGrid.Items.Refresh();
+			this.ValidateFields(keyValuePairs, true);
+			flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0);
+			this.ViewModel.Carregando = false;
+			if (!flag)
+			{
+				await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", "");
+			}
+			else
+			{
+				this.ToggleSnackBar("META DE VENDA SALVA COM SUCESSO", true);
+			}
+		}
+
+		private void SnackbarMessage_ActionClick(object sender, RoutedEventArgs e)
+		{
+			this.Snackbar.set_IsActive(false);
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target)
+		{
+			switch (connectionId)
+			{
+				case 1:
+				{
+					this.ProgressBar = (System.Windows.Controls.ProgressBar)target;
+					return;
+				}
+				case 2:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.Fechar_OnClick);
+					return;
+				}
+				case 3:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Incluir_OnClick);
+					return;
+				}
+				case 4:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick);
+					return;
+				}
+				case 5:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick);
+					return;
+				}
+				case 6:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick);
+					return;
+				}
+				case 7:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Excluir_OnClick);
+					return;
+				}
+				case 8:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Log_OnClick);
+					return;
+				}
+				case 9:
+				{
+					this.ValorMetaBox = (CurrencyTextBox)target;
+					return;
+				}
+				case 10:
+				{
+					this.AnoBox = (TextBox)target;
+					return;
+				}
+				case 11:
+				{
+					this.MetasGrid = (DataGrid)target;
+					return;
+				}
+				case 12:
+				{
+					this.Snackbar = (MaterialDesignThemes.Wpf.Snackbar)target;
+					return;
+				}
+				case 13:
+				{
+					((SnackbarMessage)target).add_ActionClick(new RoutedEventHandler(this.SnackbarMessage_ActionClick));
+					return;
+				}
+			}
+			this._contentLoaded = true;
+		}
+
+		public void ToggleSnackBar(string message, bool active = true)
+		{
+			this.Snackbar.get_Message().Content = message;
+			this.Snackbar.set_IsActive(active);
+			if (!active)
+			{
+				return;
+			}
+			Task.Factory.StartNew(new Action(this.CloseSlackBar));
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Drawers/ObservacoesDrawer.cs b/Codemerx/Gestor.Application/Drawers/ObservacoesDrawer.cs
new file mode 100644
index 0000000..7c47563
--- /dev/null
+++ b/Codemerx/Gestor.Application/Drawers/ObservacoesDrawer.cs
@@ -0,0 +1,265 @@
+using Gestor.Application.Helpers;
+using Gestor.Application.Servicos;
+using Gestor.Application.Servicos.Generic;
+using Gestor.Application.Servicos.Seguros;
+using Gestor.Application.ViewModels.Generic;
+using Gestor.Model.Common;
+using Gestor.Model.Domain.Generic;
+using Gestor.Model.Domain.Seguros;
+using System;
+using System.CodeDom.Compiler;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Markup;
+using System.Windows.Threading;
+
+namespace Gestor.Application.Drawers
+{
+	public class ObservacoesDrawer : UserControl, IComponentConnector
+	{
+		private readonly BaseSegurosViewModel _viewModel;
+
+		private readonly long _id;
+
+		private TipoTela _tipo;
+
+		private ApoliceServico _apoliceServico;
+
+		private ParcelaServico _parcelaServico;
+
+		private ClienteServico _clienteServico;
+
+		internal Grid GridMainObservacao;
+
+		internal TextBlock Observacaotxt;
+
+		internal TextBox ObservacaoBox;
+
+		private bool _contentLoaded;
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		internal Delegate _CreateDelegate(Type delegateType, string handler)
+		{
+			return Delegate.CreateDelegate(delegateType, this, handler);
+		}
+
+		public ObservacoesDrawer(long id, TipoTela tipo)
+		{
+			this._apoliceServico = new ApoliceServico();
+			this._parcelaServico = new ParcelaServico();
+			this._clienteServico = new ClienteServico();
+			this._viewModel = new BaseSegurosViewModel();
+			base.DataContext = this._viewModel;
+			this.InitializeComponent();
+			this._id = id;
+			this._tipo = tipo;
+			double windowHeight = this._viewModel.GetWindowHeight();
+			this.GridMainObservacao.Height = windowHeight;
+			System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher;
+			if (dispatcher == null)
+			{
+				return;
+			}
+			dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad));
+		}
+
+		private void Alterar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this._viewModel.Alterar(true);
+		}
+
+		private void Cancelar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this._viewModel.Alterar(false);
+			this._viewModel.Anotacoes = string.Empty;
+		}
+
+		private async void ContentLoad()
+		{
+			await this.LoadObservacao(this._id, this._tipo, false);
+		}
+
+		private void Fechar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this._viewModel.CloseDrawer();
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		public void InitializeComponent()
+		{
+			if (this._contentLoaded)
+			{
+				return;
+			}
+			this._contentLoaded = true;
+			System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/drawers/observacoesdrawer.xaml", UriKind.Relative));
+		}
+
+		private async Task LoadObservacao(long id, TipoTela tipo, bool salvar)
+		{
+			string str;
+			TextBox observacaoBox;
+			object[] nome = new object[] { Recursos.Usuario.get_Nome(), Recursos.Usuario.get_Id(), Funcoes.GetNetworkTime(), Environment.NewLine, this._viewModel.Anotacoes, Environment.NewLine, Environment.NewLine, this.ObservacaoBox.Text };
+			string str1 = string.Format("{0}, ID: {1}, {2:g}{3}{4}{5}{6}{7}", nome);
+			this._viewModel.VerificarEnables(new long?(id));
+			switch (tipo)
+			{
+				case 1:
+				{
+					this.Observacaotxt.Text = "OBSERVAÇÃO CLIENTE";
+					if (salvar)
+					{
+						observacaoBox = this.ObservacaoBox;
+						str = await this._clienteServico.SalvarObservacoes(this._id, str1);
+						observacaoBox.Text = str;
+						observacaoBox = null;
+						if (!this._clienteServico.Sucesso)
+						{
+							goto case 4;
+						}
+						this.ObservacaoBox.Text = str1;
+						goto case 4;
+					}
+					else
+					{
+						observacaoBox = this.ObservacaoBox;
+						Cliente cliente = await this._clienteServico.BuscarClienteAsync(id);
+						observacaoBox.Text = cliente.get_Observacao();
+						observacaoBox = null;
+						goto case 4;
+					}
+				}
+				case 2:
+				{
+					this.Observacaotxt.Text = "OBSERVAÇÃO APÓLICE";
+					if (salvar)
+					{
+						str1 = await this._apoliceServico.Save(this._id, str1);
+						if (!this._apoliceServico.Sucesso)
+						{
+							goto case 4;
+						}
+						this.ObservacaoBox.Text = str1;
+						goto case 4;
+					}
+					else
+					{
+						observacaoBox = this.ObservacaoBox;
+						Documento documento = await this._apoliceServico.BuscarApoliceAsync(id, false, false);
+						observacaoBox.Text = documento.get_Observacao();
+						observacaoBox = null;
+						goto case 4;
+					}
+				}
+				case 3:
+				case 4:
+				{
+					break;
+				}
+				case 5:
+				{
+					this.Observacaotxt.Text = "OBSERVAÇÃO PARCELA";
+					if (salvar)
+					{
+						observacaoBox = this.ObservacaoBox;
+						str = await this._parcelaServico.SalvarObservacoes(this._id, str1);
+						observacaoBox.Text = str;
+						observacaoBox = null;
+						if (!this._parcelaServico.Sucesso)
+						{
+							goto case 4;
+						}
+						this.ObservacaoBox.Text = str1;
+						goto case 4;
+					}
+					else
+					{
+						observacaoBox = this.ObservacaoBox;
+						Parcela parcela = await this._parcelaServico.BuscarParcela(id);
+						observacaoBox.Text = parcela.get_Observacao();
+						observacaoBox = null;
+						goto case 4;
+					}
+				}
+				default:
+				{
+					goto case 4;
+				}
+			}
+			str1 = null;
+		}
+
+		private async void ObservacoesDrawer_OnLoaded(object sender, RoutedEventArgs e)
+		{
+			await this._viewModel.PermissaoTela(2);
+			this._viewModel.Alterar(false);
+		}
+
+		private async void Salvar_OnClick(object sender, RoutedEventArgs e)
+		{
+			if (!string.IsNullOrWhiteSpace(this._viewModel.Anotacoes))
+			{
+				await this.LoadObservacao(this._id, this._tipo, true);
+				this._viewModel.Anotacoes = string.Empty;
+				this._viewModel.Alterar(false);
+			}
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target)
+		{
+			switch (connectionId)
+			{
+				case 1:
+				{
+					((ObservacoesDrawer)target).Loaded += new RoutedEventHandler(this.ObservacoesDrawer_OnLoaded);
+					return;
+				}
+				case 2:
+				{
+					this.GridMainObservacao = (Grid)target;
+					return;
+				}
+				case 3:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.Fechar_OnClick);
+					return;
+				}
+				case 4:
+				{
+					this.Observacaotxt = (TextBlock)target;
+					return;
+				}
+				case 5:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick);
+					return;
+				}
+				case 6:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick);
+					return;
+				}
+				case 7:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick);
+					return;
+				}
+				case 8:
+				{
+					this.ObservacaoBox = (TextBox)target;
+					return;
+				}
+			}
+			this._contentLoaded = true;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Drawers/PermissaoUsuarioDrawer.cs b/Codemerx/Gestor.Application/Drawers/PermissaoUsuarioDrawer.cs
new file mode 100644
index 0000000..859aa9d
--- /dev/null
+++ b/Codemerx/Gestor.Application/Drawers/PermissaoUsuarioDrawer.cs
@@ -0,0 +1,672 @@
+using Gestor.Application.Actions;
+using Gestor.Application.Helpers;
+using Gestor.Application.ViewModels.Drawer;
+using Gestor.Application.ViewModels.Generic;
+using Gestor.Application.Views.Generic;
+using Gestor.Common.Validation;
+using Gestor.Model.Domain.Generic;
+using Gestor.Model.Domain.Seguros;
+using MaterialDesignThemes.Wpf;
+using System;
+using System.CodeDom.Compiler;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Controls.Primitives;
+using System.Windows.Data;
+using System.Windows.Input;
+using System.Windows.Markup;
+using System.Windows.Threading;
+
+namespace Gestor.Application.Drawers
+{
+	public class PermissaoUsuarioDrawer : BaseUserControl, IComponentConnector, IStyleConnector
+	{
+		public PermissaoUsuarioViewModel ViewModel;
+
+		private bool _filtrado;
+
+		internal System.Windows.Controls.ProgressBar ProgressBar;
+
+		internal ToggleButton AtivoBox;
+
+		internal ScrollViewer ScrollPermissoes;
+
+		internal MenuItem DesativarPermissoes;
+
+		internal MenuItem AtivarPermissoes;
+
+		internal MenuItem MaisOpcoesButton;
+
+		internal DataGrid SegurosGrid;
+
+		internal DataGrid FerramentasGrid;
+
+		internal DataGrid ArquivoDigitalGrid;
+
+		internal MenuItem AtivarRestricoes;
+
+		internal MenuItem DesativarRestricoes;
+
+		internal DataGrid RestricoesBiGrid;
+
+		internal DataGrid RestricoesSegurosGrid;
+
+		internal DataGrid RestricoesRelatoriosGrid;
+
+		internal DataGrid RestricoesCamposRelatoriosGrid;
+
+		internal DataGrid RestricoesTotalizacoesRelatoriosGrid;
+
+		internal DataGrid RestricoesFinanceiroGrid;
+
+		internal DataGrid RestricoesFerramentasGrid;
+
+		internal DataGrid RestricoesAjudaGrid;
+
+		internal MaterialDesignThemes.Wpf.Snackbar Snackbar;
+
+		private bool _contentLoaded;
+
+		public PermissaoUsuarioDrawer(Usuario usuario)
+		{
+			this.ViewModel = new PermissaoUsuarioViewModel(usuario);
+			base.DataContext = this.ViewModel;
+			this.InitializeComponent();
+			Gestor.Application.Actions.Actions.OcultarTogglesSeguros = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.OcultarTogglesSeguros, new Action(this.OcultarTogglesSeguros));
+			Gestor.Application.Actions.Actions.OcultarTogglesFerramentas = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.OcultarTogglesFerramentas, new Action(this.OcultarTogglesFerramentas));
+			Gestor.Application.Actions.Actions.OcultarTogglesArquivoDigital = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.OcultarTogglesArquivoDigital, new Action(PermissaoUsuarioDrawer.OcultarTogglesArquivoDigital));
+		}
+
+		private async Task AbrirCopiarPermiss()
+		{
+			Tuple, Usuario, List, List, List> tuple;
+			do
+			{
+				tuple = await this.ViewModel.ShowCopiarPermissaoDialog();
+				if (tuple != null)
+				{
+					continue;
+				}
+				return;
+			}
+			while (!this.ViewModel.CopiarPermissoes(tuple));
+			this.SegurosGrid.Items.Refresh();
+			this.FerramentasGrid.Items.Refresh();
+			this.ArquivoDigitalGrid.Items.Refresh();
+			this.RestricoesBiGrid.Items.Refresh();
+			this.RestricoesSegurosGrid.Items.Refresh();
+			this.RestricoesFinanceiroGrid.Items.Refresh();
+			this.RestricoesFerramentasGrid.Items.Refresh();
+			this.RestricoesRelatoriosGrid.Items.Refresh();
+			this.RestricoesTotalizacoesRelatoriosGrid.Items.Refresh();
+			this.RestricoesCamposRelatoriosGrid.Items.Refresh();
+			this.FerramentasGrid.EsconderToggles(18, TipoToggle.Incluir | TipoToggle.Excluir);
+			this.FerramentasGrid.EsconderToggles(10, TipoToggle.Excluir);
+			this.FerramentasGrid.EsconderToggles(12, TipoToggle.Incluir | TipoToggle.Excluir);
+			this.FerramentasGrid.EsconderToggles(13, TipoToggle.Incluir | TipoToggle.Excluir);
+			this.SegurosGrid.EsconderToggles(21, TipoToggle.Incluir | TipoToggle.Alterar | TipoToggle.Excluir);
+			this.SegurosGrid.EsconderToggles(5, TipoToggle.Consultar);
+		}
+
+		private async Task AbrirExportarPermiss()
+		{
+			bool flag;
+			do
+			{
+				List usuarios = await this.ViewModel.ShowExportarPermissaoDialog(this.ViewModel.SelectedUsuario.get_Id());
+				if (usuarios != null)
+				{
+					this.ViewModel.Carregando = true;
+					flag = await this.ViewModel.ExportarPermissoes(usuarios);
+					this.ViewModel.Carregando = false;
+				}
+				else
+				{
+					return;
+				}
+			}
+			while (!flag);
+			this.ToggleSnackBar("PERMISSÕES/RESTRIÇÕES EXPORTADAS COM SUCESSO.", true);
+		}
+
+		private void AbrirLogPermissoes_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.AbrirLog(43, this.ViewModel.SelectedUsuario.get_Id());
+		}
+
+		private void AtivarDesativarPermissoes_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.AtivarDesativarPermissoes(this.ViewModel.AtivarDesativarPermissoesBool);
+		}
+
+		private void AtivarDesativarRestricoes_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.AtivarDesativarRestricoes(this.ViewModel.AtivarDesativarRestricoesBool);
+		}
+
+		private void AutoCompleteBox_OnTextChanged(object sender, RoutedEventArgs e)
+		{
+			if (((AutoCompleteBox)sender).get_Text().Length >= 3 || !this._filtrado)
+			{
+				return;
+			}
+			this._filtrado = false;
+			this.ViewModel.FiltrarRestricoesBis("");
+			this.ViewModel.FiltrarRestricoesSeguros("");
+			this.ViewModel.FiltrarRestricoesRelatorios("");
+			this.ViewModel.FiltrarRestricoesTotalizacoesRelatorios("");
+			this.ViewModel.FiltrarRestricoesCamposRelatorios("");
+			this.ViewModel.FiltrarRestricoesFinanceiros("");
+			this.ViewModel.FiltrarRestricoesFerramentas("");
+			this.ViewModel.FiltrarRestricoesAjudas("");
+		}
+
+		private void AutoCompleteBox_Populating(object sender, PopulatingEventArgs e)
+		{
+			if (e.get_Parameter().Length < 3)
+			{
+				return;
+			}
+			this._filtrado = true;
+			e.set_Cancel(true);
+			this.ViewModel.FiltrarRestricoesBi(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => ((AutoCompleteBox)sender).PopulateComplete(), TaskScheduler.FromCurrentSynchronizationContext());
+			this.ViewModel.FiltrarRestricoesSeguro(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => ((AutoCompleteBox)sender).PopulateComplete(), TaskScheduler.FromCurrentSynchronizationContext());
+			this.ViewModel.FiltrarRestricoesRelatorio(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => ((AutoCompleteBox)sender).PopulateComplete(), TaskScheduler.FromCurrentSynchronizationContext());
+			this.ViewModel.FiltrarRestricoesTotalizacoesRelatorio(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => ((AutoCompleteBox)sender).PopulateComplete(), TaskScheduler.FromCurrentSynchronizationContext());
+			this.ViewModel.FiltrarRestricoesCamposRelatorio(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => ((AutoCompleteBox)sender).PopulateComplete(), TaskScheduler.FromCurrentSynchronizationContext());
+			this.ViewModel.FiltrarRestricoesFinanceiro(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => ((AutoCompleteBox)sender).PopulateComplete(), TaskScheduler.FromCurrentSynchronizationContext());
+			this.ViewModel.FiltrarRestricoesFerramenta(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => ((AutoCompleteBox)sender).PopulateComplete(), TaskScheduler.FromCurrentSynchronizationContext());
+			this.ViewModel.FiltrarRestricoesAjuda(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => ((AutoCompleteBox)sender).PopulateComplete(), TaskScheduler.FromCurrentSynchronizationContext());
+		}
+
+		private void CloseSlackBar()
+		{
+			Thread.Sleep(5000);
+			System.Windows.Threading.Dispatcher dispatcher = this.ProgressBar.Dispatcher;
+			if (dispatcher == null)
+			{
+				return;
+			}
+			dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => this.ToggleSnackBar("", false)));
+		}
+
+		private async void CopiarUsuario_OnClick(object sender, RoutedEventArgs e)
+		{
+			await this.AbrirCopiarPermiss();
+		}
+
+		private async void ExportarUsuario_OnClick(object sender, RoutedEventArgs e)
+		{
+			await this.AbrirExportarPermiss();
+		}
+
+		private void Fechar_OnClick(object sender, RoutedEventArgs e)
+		{
+			Action atualizaUsuario = Gestor.Application.Actions.Actions.AtualizaUsuario;
+			if (atualizaUsuario != null)
+			{
+				atualizaUsuario();
+			}
+			else
+			{
+			}
+			this.ViewModel.CloseDrawer();
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		public void InitializeComponent()
+		{
+			if (this._contentLoaded)
+			{
+				return;
+			}
+			this._contentLoaded = true;
+			System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/drawers/permissaousuariodrawer.xaml", UriKind.Relative));
+		}
+
+		private static void OcultarTogglesArquivoDigital()
+		{
+		}
+
+		private void OcultarTogglesFerramentas()
+		{
+			this.FerramentasGrid.EsconderToggles(18, TipoToggle.Incluir | TipoToggle.Excluir);
+			this.FerramentasGrid.EsconderToggles(10, TipoToggle.Excluir);
+			this.FerramentasGrid.EsconderToggles(12, TipoToggle.Incluir | TipoToggle.Excluir);
+			this.FerramentasGrid.EsconderToggles(13, TipoToggle.Excluir);
+		}
+
+		private void OcultarTogglesSeguros()
+		{
+			this.SegurosGrid.EsconderToggles(21, TipoToggle.Incluir | TipoToggle.Alterar | TipoToggle.Excluir);
+			this.SegurosGrid.EsconderToggles(5, TipoToggle.Consultar);
+		}
+
+		private void PermissoesGrid_OnPreviewMouseWheel(object sender, MouseWheelEventArgs e)
+		{
+			this.ScrollPermissoes.ScrollToVerticalOffset(this.ScrollPermissoes.VerticalOffset - (double)e.Delta);
+		}
+
+		private async void SalvarPermissoes_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.Carregando = true;
+			if (await this.ViewModel.Salvar(null, true))
+			{
+				this.ToggleSnackBar("PERMISSÕES/RESTRIÇÕES SALVAS COM SUCESSO.", true);
+			}
+			this.ViewModel.Carregando = false;
+		}
+
+		private void SnackbarMessage_ActionClick(object sender, RoutedEventArgs e)
+		{
+			this.Snackbar.set_IsActive(false);
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target)
+		{
+			switch (connectionId)
+			{
+				case 1:
+				{
+					this.ProgressBar = (System.Windows.Controls.ProgressBar)target;
+					return;
+				}
+				case 2:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.Fechar_OnClick);
+					return;
+				}
+				case 3:
+				{
+					this.AtivoBox = (ToggleButton)target;
+					return;
+				}
+				case 4:
+				{
+					this.ScrollPermissoes = (ScrollViewer)target;
+					return;
+				}
+				case 5:
+				{
+					this.DesativarPermissoes = (MenuItem)target;
+					this.DesativarPermissoes.Click += new RoutedEventHandler(this.AtivarDesativarPermissoes_OnClick);
+					return;
+				}
+				case 6:
+				{
+					this.AtivarPermissoes = (MenuItem)target;
+					this.AtivarPermissoes.Click += new RoutedEventHandler(this.AtivarDesativarPermissoes_OnClick);
+					return;
+				}
+				case 7:
+				{
+					this.MaisOpcoesButton = (MenuItem)target;
+					return;
+				}
+				case 8:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLogPermissoes_OnClick);
+					return;
+				}
+				case 9:
+				{
+					this.SegurosGrid = (DataGrid)target;
+					this.SegurosGrid.PreviewMouseWheel += new MouseWheelEventHandler(this.PermissoesGrid_OnPreviewMouseWheel);
+					return;
+				}
+				case 10:
+				case 11:
+				case 12:
+				case 13:
+				case 15:
+				case 16:
+				case 17:
+				case 18:
+				case 20:
+				case 21:
+				case 22:
+				{
+					this._contentLoaded = true;
+					return;
+				}
+				case 14:
+				{
+					this.FerramentasGrid = (DataGrid)target;
+					this.FerramentasGrid.PreviewMouseWheel += new MouseWheelEventHandler(this.PermissoesGrid_OnPreviewMouseWheel);
+					return;
+				}
+				case 19:
+				{
+					this.ArquivoDigitalGrid = (DataGrid)target;
+					this.ArquivoDigitalGrid.PreviewMouseWheel += new MouseWheelEventHandler(this.PermissoesGrid_OnPreviewMouseWheel);
+					return;
+				}
+				case 23:
+				{
+					((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, PermissaoUsuarioDrawer.AutoCompleteBox_Populating));
+					((AutoCompleteBox)target).add_TextChanged(new RoutedEventHandler(this.AutoCompleteBox_OnTextChanged));
+					return;
+				}
+				case 24:
+				{
+					this.AtivarRestricoes = (MenuItem)target;
+					this.AtivarRestricoes.Click += new RoutedEventHandler(this.AtivarDesativarRestricoes_OnClick);
+					return;
+				}
+				case 25:
+				{
+					this.DesativarRestricoes = (MenuItem)target;
+					this.DesativarRestricoes.Click += new RoutedEventHandler(this.AtivarDesativarRestricoes_OnClick);
+					return;
+				}
+				case 26:
+				{
+					this.RestricoesBiGrid = (DataGrid)target;
+					return;
+				}
+				case 27:
+				{
+					this.RestricoesSegurosGrid = (DataGrid)target;
+					return;
+				}
+				case 28:
+				{
+					this.RestricoesRelatoriosGrid = (DataGrid)target;
+					return;
+				}
+				case 29:
+				{
+					this.RestricoesCamposRelatoriosGrid = (DataGrid)target;
+					this.RestricoesCamposRelatoriosGrid.PreviewMouseWheel += new MouseWheelEventHandler(this.PermissoesGrid_OnPreviewMouseWheel);
+					return;
+				}
+				case 30:
+				{
+					this.RestricoesTotalizacoesRelatoriosGrid = (DataGrid)target;
+					return;
+				}
+				case 31:
+				{
+					this.RestricoesFinanceiroGrid = (DataGrid)target;
+					return;
+				}
+				case 32:
+				{
+					this.RestricoesFerramentasGrid = (DataGrid)target;
+					return;
+				}
+				case 33:
+				{
+					this.RestricoesAjudaGrid = (DataGrid)target;
+					return;
+				}
+				case 34:
+				{
+					this.Snackbar = (MaterialDesignThemes.Wpf.Snackbar)target;
+					return;
+				}
+				case 35:
+				{
+					((SnackbarMessage)target).add_ActionClick(new RoutedEventHandler(this.SnackbarMessage_ActionClick));
+					return;
+				}
+				case 36:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.SalvarPermissoes_OnClick);
+					return;
+				}
+				case 37:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.CopiarUsuario_OnClick);
+					return;
+				}
+				case 38:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.ExportarUsuario_OnClick);
+					return;
+				}
+				default:
+				{
+					this._contentLoaded = true;
+					return;
+				}
+			}
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target)
+		{
+			EventSetter eventSetter;
+			switch (connectionId)
+			{
+				case 10:
+				{
+					eventSetter = new EventSetter()
+					{
+						Event = ToggleButton.UncheckedEvent,
+						Handler = new RoutedEventHandler(this.UnToggleSeguros_OnChecked)
+					};
+					((System.Windows.Style)target).Setters.Add(eventSetter);
+					return;
+				}
+				case 11:
+				{
+					eventSetter = new EventSetter()
+					{
+						Event = ToggleButton.CheckedEvent,
+						Handler = new RoutedEventHandler(this.ToggleSeguros_OnChecked)
+					};
+					((System.Windows.Style)target).Setters.Add(eventSetter);
+					return;
+				}
+				case 12:
+				{
+					eventSetter = new EventSetter()
+					{
+						Event = ToggleButton.CheckedEvent,
+						Handler = new RoutedEventHandler(this.ToggleSeguros_OnChecked)
+					};
+					((System.Windows.Style)target).Setters.Add(eventSetter);
+					return;
+				}
+				case 13:
+				{
+					eventSetter = new EventSetter()
+					{
+						Event = ToggleButton.CheckedEvent,
+						Handler = new RoutedEventHandler(this.ToggleSeguros_OnChecked)
+					};
+					((System.Windows.Style)target).Setters.Add(eventSetter);
+					return;
+				}
+				case 14:
+				case 19:
+				{
+					return;
+				}
+				case 15:
+				{
+					eventSetter = new EventSetter()
+					{
+						Event = ToggleButton.UncheckedEvent,
+						Handler = new RoutedEventHandler(this.UnToggleFerramentas_OnChecked)
+					};
+					((System.Windows.Style)target).Setters.Add(eventSetter);
+					return;
+				}
+				case 16:
+				{
+					eventSetter = new EventSetter()
+					{
+						Event = ToggleButton.CheckedEvent,
+						Handler = new RoutedEventHandler(this.ToggleFerramentas_OnChecked)
+					};
+					((System.Windows.Style)target).Setters.Add(eventSetter);
+					return;
+				}
+				case 17:
+				{
+					eventSetter = new EventSetter()
+					{
+						Event = ToggleButton.CheckedEvent,
+						Handler = new RoutedEventHandler(this.ToggleFerramentas_OnChecked)
+					};
+					((System.Windows.Style)target).Setters.Add(eventSetter);
+					return;
+				}
+				case 18:
+				{
+					eventSetter = new EventSetter()
+					{
+						Event = ToggleButton.CheckedEvent,
+						Handler = new RoutedEventHandler(this.ToggleFerramentas_OnChecked)
+					};
+					((System.Windows.Style)target).Setters.Add(eventSetter);
+					return;
+				}
+				case 20:
+				{
+					eventSetter = new EventSetter()
+					{
+						Event = ToggleButton.UncheckedEvent,
+						Handler = new RoutedEventHandler(this.UnToggleArquivosDigitais_OnChecked)
+					};
+					((System.Windows.Style)target).Setters.Add(eventSetter);
+					return;
+				}
+				case 21:
+				{
+					eventSetter = new EventSetter()
+					{
+						Event = ToggleButton.CheckedEvent,
+						Handler = new RoutedEventHandler(this.ToggleArquivosDigitais_OnChecked)
+					};
+					((System.Windows.Style)target).Setters.Add(eventSetter);
+					return;
+				}
+				case 22:
+				{
+					eventSetter = new EventSetter()
+					{
+						Event = ToggleButton.CheckedEvent,
+						Handler = new RoutedEventHandler(this.ToggleArquivosDigitais_OnChecked)
+					};
+					((System.Windows.Style)target).Setters.Add(eventSetter);
+					return;
+				}
+				default:
+				{
+					return;
+				}
+			}
+		}
+
+		private void ToggleArquivosDigitais_OnChecked(object sender, RoutedEventArgs e)
+		{
+			if (!this.ViewModel.Carregado)
+			{
+				return;
+			}
+			DataGridCell dataGridCell = (DataGridCell)sender;
+			if (dataGridCell == null)
+			{
+				return;
+			}
+			this.ViewModel.HabilitarArquivoDigital((PermissaoArquivoDigital)dataGridCell.DataContext);
+		}
+
+		private void ToggleFerramentas_OnChecked(object sender, RoutedEventArgs e)
+		{
+			if (!this.ViewModel.Carregado)
+			{
+				return;
+			}
+			DataGridCell dataGridCell = (DataGridCell)sender;
+			if (dataGridCell == null)
+			{
+				return;
+			}
+			this.ViewModel.HabilitarConsulta((PermissaoUsuario)dataGridCell.DataContext, "Ferramentas");
+		}
+
+		private void ToggleSeguros_OnChecked(object sender, RoutedEventArgs e)
+		{
+			if (!this.ViewModel.Carregado)
+			{
+				return;
+			}
+			DataGridCell dataGridCell = (DataGridCell)sender;
+			if (dataGridCell == null)
+			{
+				return;
+			}
+			this.ViewModel.HabilitarConsulta((PermissaoUsuario)dataGridCell.DataContext, "Seguros");
+		}
+
+		public void ToggleSnackBar(string message, bool active = true)
+		{
+			this.Snackbar.get_Message().Content = message;
+			this.Snackbar.set_IsActive(active);
+			if (!active)
+			{
+				return;
+			}
+			Task.Factory.StartNew(new Action(this.CloseSlackBar));
+		}
+
+		private void UnToggleArquivosDigitais_OnChecked(object sender, RoutedEventArgs e)
+		{
+			if (!this.ViewModel.Carregado)
+			{
+				return;
+			}
+			DataGridCell dataGridCell = (DataGridCell)sender;
+			if (dataGridCell == null)
+			{
+				return;
+			}
+			this.ViewModel.DesabilitarArquivoDigital((PermissaoArquivoDigital)dataGridCell.DataContext);
+		}
+
+		private void UnToggleFerramentas_OnChecked(object sender, RoutedEventArgs e)
+		{
+			if (!this.ViewModel.Carregado)
+			{
+				return;
+			}
+			DataGridCell dataGridCell = (DataGridCell)sender;
+			if (dataGridCell == null)
+			{
+				return;
+			}
+			this.ViewModel.DesabilitarConsulta((PermissaoUsuario)dataGridCell.DataContext, "Ferramentas");
+		}
+
+		private void UnToggleSeguros_OnChecked(object sender, RoutedEventArgs e)
+		{
+			if (!this.ViewModel.Carregado)
+			{
+				return;
+			}
+			DataGridCell dataGridCell = (DataGridCell)sender;
+			if (dataGridCell == null)
+			{
+				return;
+			}
+			this.ViewModel.DesabilitarConsulta((PermissaoUsuario)dataGridCell.DataContext, "Seguros");
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Drawers/Relatorios/ConfiguracaoRelatorio.cs b/Codemerx/Gestor.Application/Drawers/Relatorios/ConfiguracaoRelatorio.cs
new file mode 100644
index 0000000..acd3f1f
--- /dev/null
+++ b/Codemerx/Gestor.Application/Drawers/Relatorios/ConfiguracaoRelatorio.cs
@@ -0,0 +1,421 @@
+using Gestor.Application;
+using Gestor.Application.ViewModels.Generic;
+using Gestor.Application.ViewModels.Relatorios;
+using Gestor.Model.Domain.Relatorios;
+using MaterialDesignThemes.Wpf;
+using System;
+using System.CodeDom.Compiler;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Controls.Primitives;
+using System.Windows.Markup;
+using System.Windows.Threading;
+
+namespace Gestor.Application.Drawers.Relatorios
+{
+	public class ConfiguracaoRelatorio : UserControl, IComponentConnector, IStyleConnector
+	{
+		internal System.Windows.Controls.ProgressBar ProgressBar;
+
+		internal RadioButton CampoButton;
+
+		internal RadioButton TotalizacaoButton;
+
+		internal ComboBox CampoComboBox;
+
+		internal ComboBox TotalizacaoComboBox;
+
+		internal DataGrid ParametrosGrid;
+
+		internal DataGrid TotalizacaoGrid;
+
+		internal Snackbar SnackbarArquivoDigital;
+
+		private bool _contentLoaded;
+
+		public RelatorioViewModel ViewModel
+		{
+			get;
+			set;
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		internal Delegate _CreateDelegate(Type delegateType, string handler)
+		{
+			return Delegate.CreateDelegate(delegateType, this, handler);
+		}
+
+		public ConfiguracaoRelatorio(RelatorioViewModel viewModel)
+		{
+			this.ViewModel = viewModel;
+			base.DataContext = this.ViewModel;
+			this.InitializeComponent();
+			System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher;
+			if (dispatcher == null)
+			{
+				return;
+			}
+			dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad));
+		}
+
+		private void AdicionarParametro_OnClick(object sender, RoutedEventArgs e)
+		{
+			object item;
+			RelatorioViewModel viewModel = this.ViewModel;
+			ComboBox campoComboBox = this.CampoComboBox;
+			if (campoComboBox != null)
+			{
+				item = campoComboBox.Items[this.CampoComboBox.SelectedIndex];
+			}
+			else
+			{
+				item = null;
+			}
+			viewModel.AdicionarParametro((ParametrosRelatorio)item);
+		}
+
+		private void AdicionarTotalizacao_OnClick(object sender, RoutedEventArgs e)
+		{
+			object item;
+			RelatorioViewModel viewModel = this.ViewModel;
+			ComboBox totalizacaoComboBox = this.TotalizacaoComboBox;
+			if (totalizacaoComboBox != null)
+			{
+				item = totalizacaoComboBox.Items[this.TotalizacaoComboBox.SelectedIndex];
+			}
+			else
+			{
+				item = null;
+			}
+			viewModel.AdicionarTotalizacao((ParametrosTotalizacao)item);
+		}
+
+		private void Campo_OnChecked(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.IsCampo = true;
+		}
+
+		private void CloseSlackBar()
+		{
+			Thread.Sleep(5000);
+			System.Windows.Threading.Dispatcher dispatcher = App.ProgressRing.Dispatcher;
+			if (dispatcher == null)
+			{
+				return;
+			}
+			dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => this.Toggle("", false)));
+		}
+
+		private async void ContentLoad()
+		{
+			this.CampoButton.IsChecked = new bool?(this.ViewModel.IsCampo);
+			this.TotalizacaoButton.IsChecked = new bool?(!this.ViewModel.IsCampo);
+			this.CampoButton.Checked += new RoutedEventHandler(this.Campo_OnChecked);
+			this.TotalizacaoButton.Checked += new RoutedEventHandler(this.Totalizacao_OnChecked);
+			this.ViewModel.IsEnabled = false;
+			await this.ViewModel.CarregarConfiguracoes();
+			this.ViewModel.IsEnabled = true;
+		}
+
+		private void DescerParametro_OnClick(object sender, RoutedEventArgs e)
+		{
+			bool selectedIndex;
+			object item;
+			DataGrid parametrosGrid = this.ParametrosGrid;
+			if (parametrosGrid != null)
+			{
+				selectedIndex = parametrosGrid.SelectedIndex < 0;
+			}
+			else
+			{
+				selectedIndex = false;
+			}
+			if (selectedIndex)
+			{
+				return;
+			}
+			RelatorioViewModel viewModel = this.ViewModel;
+			DataGrid dataGrid = this.ParametrosGrid;
+			if (dataGrid != null)
+			{
+				item = dataGrid.Items[this.ParametrosGrid.SelectedIndex];
+			}
+			else
+			{
+				item = null;
+			}
+			viewModel.DescerParametro((ParametrosRelatorio)item);
+		}
+
+		private void ExcluirParametro_OnClick(object sender, RoutedEventArgs e)
+		{
+			bool selectedIndex;
+			object item;
+			DataGrid parametrosGrid = this.ParametrosGrid;
+			if (parametrosGrid != null)
+			{
+				selectedIndex = parametrosGrid.SelectedIndex < 0;
+			}
+			else
+			{
+				selectedIndex = false;
+			}
+			if (selectedIndex)
+			{
+				return;
+			}
+			RelatorioViewModel viewModel = this.ViewModel;
+			DataGrid dataGrid = this.ParametrosGrid;
+			if (dataGrid != null)
+			{
+				item = dataGrid.Items[this.ParametrosGrid.SelectedIndex];
+			}
+			else
+			{
+				item = null;
+			}
+			viewModel.ExcluirParametro((ParametrosRelatorio)item);
+		}
+
+		private void ExcluirTotalizacao_OnClick(object sender, RoutedEventArgs e)
+		{
+			bool selectedIndex;
+			object item;
+			DataGrid totalizacaoGrid = this.TotalizacaoGrid;
+			if (totalizacaoGrid != null)
+			{
+				selectedIndex = totalizacaoGrid.SelectedIndex < 0;
+			}
+			else
+			{
+				selectedIndex = false;
+			}
+			if (selectedIndex)
+			{
+				return;
+			}
+			RelatorioViewModel viewModel = this.ViewModel;
+			DataGrid dataGrid = this.TotalizacaoGrid;
+			if (dataGrid != null)
+			{
+				item = dataGrid.Items[this.TotalizacaoGrid.SelectedIndex];
+			}
+			else
+			{
+				item = null;
+			}
+			viewModel.ExcluirTotalizacao((ParametrosTotalizacao)item);
+		}
+
+		private void Fechar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.CloseDrawer();
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		public void InitializeComponent()
+		{
+			if (this._contentLoaded)
+			{
+				return;
+			}
+			this._contentLoaded = true;
+			System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/drawers/relatorios/configuracaorelatorio.xaml", UriKind.Relative));
+		}
+
+		private async void Salvar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.IsEnabled = false;
+			bool flag = await this.ViewModel.SalvarParametros();
+			this.ViewModel.IsEnabled = true;
+			if (flag)
+			{
+				this.Toggle("CONFIGURAÇÕES SALVAS.", true);
+			}
+		}
+
+		private void SnackbarMessage_ActionClick(object sender, RoutedEventArgs e)
+		{
+			this.SnackbarArquivoDigital.set_IsActive(false);
+		}
+
+		private void SubirParametro_OnClick(object sender, RoutedEventArgs e)
+		{
+			bool selectedIndex;
+			object item;
+			DataGrid parametrosGrid = this.ParametrosGrid;
+			if (parametrosGrid != null)
+			{
+				selectedIndex = parametrosGrid.SelectedIndex < 0;
+			}
+			else
+			{
+				selectedIndex = false;
+			}
+			if (selectedIndex)
+			{
+				return;
+			}
+			RelatorioViewModel viewModel = this.ViewModel;
+			DataGrid dataGrid = this.ParametrosGrid;
+			if (dataGrid != null)
+			{
+				item = dataGrid.Items[this.ParametrosGrid.SelectedIndex];
+			}
+			else
+			{
+				item = null;
+			}
+			viewModel.SubirParametro((ParametrosRelatorio)item);
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target)
+		{
+			switch (connectionId)
+			{
+				case 1:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.Fechar_OnClick);
+					return;
+				}
+				case 2:
+				{
+					this.ProgressBar = (System.Windows.Controls.ProgressBar)target;
+					return;
+				}
+				case 3:
+				{
+					this.CampoButton = (RadioButton)target;
+					return;
+				}
+				case 4:
+				{
+					this.TotalizacaoButton = (RadioButton)target;
+					return;
+				}
+				case 5:
+				{
+					this.CampoComboBox = (ComboBox)target;
+					return;
+				}
+				case 6:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.AdicionarParametro_OnClick);
+					return;
+				}
+				case 7:
+				{
+					this.TotalizacaoComboBox = (ComboBox)target;
+					return;
+				}
+				case 8:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.AdicionarTotalizacao_OnClick);
+					return;
+				}
+				case 9:
+				{
+					this.ParametrosGrid = (DataGrid)target;
+					return;
+				}
+				case 10:
+				case 11:
+				case 12:
+				case 14:
+				{
+					this._contentLoaded = true;
+					return;
+				}
+				case 13:
+				{
+					this.TotalizacaoGrid = (DataGrid)target;
+					return;
+				}
+				case 15:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick);
+					return;
+				}
+				case 16:
+				{
+					this.SnackbarArquivoDigital = (Snackbar)target;
+					return;
+				}
+				case 17:
+				{
+					((SnackbarMessage)target).add_ActionClick(new RoutedEventHandler(this.SnackbarMessage_ActionClick));
+					return;
+				}
+				default:
+				{
+					this._contentLoaded = true;
+					return;
+				}
+			}
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target)
+		{
+			switch (connectionId)
+			{
+				case 10:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.SubirParametro_OnClick);
+					return;
+				}
+				case 11:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.DescerParametro_OnClick);
+					return;
+				}
+				case 12:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.ExcluirParametro_OnClick);
+					return;
+				}
+				case 13:
+				{
+					return;
+				}
+				case 14:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.ExcluirTotalizacao_OnClick);
+					return;
+				}
+				default:
+				{
+					return;
+				}
+			}
+		}
+
+		public void Toggle(string message, bool active = true)
+		{
+			this.SnackbarArquivoDigital.get_Message().Content = message;
+			this.SnackbarArquivoDigital.set_IsActive(active);
+			if (!active)
+			{
+				return;
+			}
+			Task.Factory.StartNew(new Action(this.CloseSlackBar));
+		}
+
+		private void Totalizacao_OnChecked(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.IsCampo = false;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Drawers/Relatorios/FiltroRelatorio.cs b/Codemerx/Gestor.Application/Drawers/Relatorios/FiltroRelatorio.cs
new file mode 100644
index 0000000..4c1f2a2
--- /dev/null
+++ b/Codemerx/Gestor.Application/Drawers/Relatorios/FiltroRelatorio.cs
@@ -0,0 +1,152 @@
+using Gestor.Application.ViewModels.Generic;
+using Gestor.Application.ViewModels.Relatorios;
+using Gestor.Model.Common;
+using MaterialDesignThemes.Wpf;
+using System;
+using System.CodeDom.Compiler;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Drawers.Relatorios
+{
+	public class FiltroRelatorio : UserControl, IComponentConnector
+	{
+		private RelatorioViewModel ViewModel;
+
+		internal MaterialDataGridTextColumn IdField;
+
+		internal MaterialDataGridTextColumn NomeField;
+
+		internal MaterialDataGridTextColumn ApelidoField;
+
+		internal DataGrid RamosGrid;
+
+		internal DataGrid VendedorGrid;
+
+		internal DataGrid TipoSeguroGrid;
+
+		internal DataGrid TipoVendedorGrid;
+
+		internal DataGrid NegocioGrid;
+
+		internal DataGrid ProdutoGrid;
+
+		internal DataGrid EstipulanteGrid;
+
+		private bool _contentLoaded;
+
+		public FiltroRelatorio(RelatorioViewModel viewModel, Relatorio relatorio)
+		{
+			this.ViewModel = viewModel;
+			base.DataContext = this.ViewModel;
+			this.InitializeComponent();
+			viewModel.ReloadVendedores();
+			this.VendedorGrid.Visibility = (viewModel.Vendedores.Count > 0 ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed);
+			this.EstipulanteGrid.Visibility = (viewModel.Estipulantes.Count > 0 ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed);
+			this.ProdutoGrid.Visibility = (viewModel.Produtos.Count > 0 ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed);
+			this.IdField.Visibility = (this.ViewModel.Apelido ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible);
+			this.NomeField.Visibility = (this.ViewModel.Apelido ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible);
+			this.ApelidoField.Visibility = (!this.ViewModel.Apelido ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible);
+			if (relatorio == 19)
+			{
+				this.RamosGrid.Visibility = System.Windows.Visibility.Collapsed;
+				this.TipoSeguroGrid.Visibility = System.Windows.Visibility.Collapsed;
+				this.VendedorGrid.Visibility = System.Windows.Visibility.Collapsed;
+				this.EstipulanteGrid.Visibility = System.Windows.Visibility.Collapsed;
+				this.ProdutoGrid.Visibility = System.Windows.Visibility.Collapsed;
+				this.TipoVendedorGrid.Visibility = System.Windows.Visibility.Collapsed;
+				this.NegocioGrid.Visibility = System.Windows.Visibility.Collapsed;
+			}
+			this.ViewModel.EnableMenu = true;
+		}
+
+		private void Fechar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.Filtro = "";
+			this.ViewModel.AdicionarFiltros();
+			this.ViewModel.CloseDrawer();
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		public void InitializeComponent()
+		{
+			if (this._contentLoaded)
+			{
+				return;
+			}
+			this._contentLoaded = true;
+			System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/drawers/relatorios/filtrorelatorio.xaml", UriKind.Relative));
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target)
+		{
+			switch (connectionId)
+			{
+				case 1:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.Fechar_OnClick);
+					return;
+				}
+				case 2:
+				{
+					this.IdField = (MaterialDataGridTextColumn)target;
+					return;
+				}
+				case 3:
+				{
+					this.NomeField = (MaterialDataGridTextColumn)target;
+					return;
+				}
+				case 4:
+				{
+					this.ApelidoField = (MaterialDataGridTextColumn)target;
+					return;
+				}
+				case 5:
+				{
+					this.RamosGrid = (DataGrid)target;
+					return;
+				}
+				case 6:
+				{
+					this.VendedorGrid = (DataGrid)target;
+					return;
+				}
+				case 7:
+				{
+					this.TipoSeguroGrid = (DataGrid)target;
+					return;
+				}
+				case 8:
+				{
+					this.TipoVendedorGrid = (DataGrid)target;
+					return;
+				}
+				case 9:
+				{
+					this.NegocioGrid = (DataGrid)target;
+					return;
+				}
+				case 10:
+				{
+					this.ProdutoGrid = (DataGrid)target;
+					return;
+				}
+				case 11:
+				{
+					this.EstipulanteGrid = (DataGrid)target;
+					return;
+				}
+			}
+			this._contentLoaded = true;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Drawers/TarefaDrawer.cs b/Codemerx/Gestor.Application/Drawers/TarefaDrawer.cs
new file mode 100644
index 0000000..13b9bac
--- /dev/null
+++ b/Codemerx/Gestor.Application/Drawers/TarefaDrawer.cs
@@ -0,0 +1,631 @@
+using Gestor.Application.Componentes;
+using Gestor.Application.Helpers;
+using Gestor.Application.Servicos;
+using Gestor.Application.ViewModels.Drawer;
+using Gestor.Application.ViewModels.Generic;
+using Gestor.Common.Validation;
+using Gestor.Model.Common;
+using Gestor.Model.Domain.Common;
+using Gestor.Model.Domain.Configuracoes;
+using Gestor.Model.Domain.Ferramentas;
+using Gestor.Model.Domain.Generic;
+using Gestor.Model.Domain.Seguros;
+using MaterialDesignThemes.Wpf;
+using System;
+using System.CodeDom.Compiler;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Controls.Primitives;
+using System.Windows.Input;
+using System.Windows.Markup;
+using System.Windows.Threading;
+using Xceed.Wpf.AvalonDock.Controls;
+
+namespace Gestor.Application.Drawers
+{
+	public class TarefaDrawer : UserControl, IComponentConnector, IStyleConnector
+	{
+		internal System.Windows.Controls.ProgressBar ProgressBar;
+
+		internal TextBlock TitleBox;
+
+		internal DatePicker AgendamentoBox;
+
+		internal ToggleButton AtivoBox;
+
+		internal RadioButton AnotacoesButton;
+
+		internal RadioButton AnotacoesInternasButton;
+
+		internal WebEditor Anotacoes;
+
+		internal WebEditor Historico;
+
+		internal WebEditor AnotacoesInternas;
+
+		internal WebEditor HistoricoInterno;
+
+		internal DatePicker ConclusaoBox;
+
+		internal ComboBox CboResponsavel;
+
+		internal MaterialDesignThemes.Wpf.Snackbar Snackbar;
+
+		private bool _contentLoaded;
+
+		private TarefaDrawerViewModel ViewModel
+		{
+			get;
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		internal Delegate _CreateDelegate(Type delegateType, string handler)
+		{
+			return Delegate.CreateDelegate(delegateType, this, handler);
+		}
+
+		public TarefaDrawer(Tarefa tarefa, bool enableMenu = true)
+		{
+			long? nullable;
+			long? nullable1;
+			object description;
+			long? nullable2;
+			long? nullable3;
+			object obj;
+			object obj1;
+			long num;
+			this.ViewModel = new TarefaDrawerViewModel(tarefa, enableMenu);
+			base.DataContext = this.ViewModel;
+			this.InitializeComponent();
+			System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher;
+			if (dispatcher != null)
+			{
+				dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad));
+			}
+			else
+			{
+			}
+			TarefaDrawerViewModel viewModel = this.ViewModel;
+			if (tarefa != null)
+			{
+				description = ValidationHelper.GetDescription(tarefa.get_Entidade());
+			}
+			else
+			{
+				description = null;
+			}
+			if (tarefa != null)
+			{
+				nullable1 = new long?(tarefa.get_IdEntidade());
+			}
+			else
+			{
+				nullable = null;
+				nullable1 = nullable;
+			}
+			string str = string.Format("ACESSOU TAREFA DE {0} DO DOCUMENTO DE ID \"{1}\"", description, nullable1);
+			num = (tarefa != null ? tarefa.get_IdEntidade() : (long)0);
+			TipoTela? nullable4 = new TipoTela?(38);
+			if (tarefa != null)
+			{
+				obj = ValidationHelper.GetDescription(tarefa.get_Entidade());
+			}
+			else
+			{
+				obj = null;
+			}
+			if ((tarefa != null ? tarefa.get_IdCliente() != (long)0 : true))
+			{
+				if (tarefa != null)
+				{
+					nullable2 = new long?(tarefa.get_IdCliente());
+				}
+				else
+				{
+					nullable = null;
+					nullable2 = nullable;
+				}
+				obj1 = string.Format("\nID CLIENTE: {0}", nullable2);
+			}
+			else
+			{
+				obj1 = "";
+			}
+			if (tarefa != null)
+			{
+				nullable3 = new long?(tarefa.get_IdEntidade());
+			}
+			else
+			{
+				nullable = null;
+				nullable3 = nullable;
+			}
+			viewModel.RegistrarAcao(str, num, nullable4, string.Format("TIPO DE TAREFA: {0}{1}\nID DOCUMENTO: {2}", obj, obj1, nullable3));
+		}
+
+		private void AdicionarResponsavel_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.AdcionarResponsavel();
+		}
+
+		private void Alterar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.AlterarTarefa();
+			this.Anotacoes.Initialize(null);
+			this.Validar();
+		}
+
+		private async void AnexoTarefa_OnClick(object sender, RoutedEventArgs e)
+		{
+			if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 15).get_Consultar())
+			{
+				Button button = (Button)sender;
+				if (button.DataContext != null)
+				{
+					Tarefa dataContext = (Tarefa)button.DataContext;
+					FiltroArquivoDigital filtroArquivoDigital = new FiltroArquivoDigital();
+					filtroArquivoDigital.set_Id(dataContext.get_Id());
+					filtroArquivoDigital.set_Tipo(15);
+					filtroArquivoDigital.set_Parente(dataContext);
+					this.ViewModel.ShowDrawer(new ArquivoDigitalDrawer(filtroArquivoDigital), 0, false);
+				}
+			}
+			else
+			{
+				await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", ValidationHelper.GetDescription((TipoArquivoDigital)15), "."), "OK", "", false);
+			}
+		}
+
+		private void Anotacoes_OnChecked(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.IsAnotacoes = true;
+		}
+
+		private void AnotacoesInternas_OnChecked(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.IsAnotacoes = false;
+		}
+
+		private async void Cancelar_OnClick(object sender, RoutedEventArgs e)
+		{
+			await this.ViewModel.Cancelar();
+			this.Anotacoes.Initialize(null);
+			this.AnotacoesInternas.Initialize(null);
+		}
+
+		private void CloseSlackBar()
+		{
+			Thread.Sleep(5000);
+			System.Windows.Threading.Dispatcher dispatcher = this.ProgressBar.Dispatcher;
+			if (dispatcher == null)
+			{
+				return;
+			}
+			dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => this.ToggleSnackBar("", false)));
+		}
+
+		private void ContentLoad()
+		{
+			this.AnotacoesButton.IsChecked = new bool?(this.ViewModel.IsAnotacoes);
+			this.AnotacoesInternasButton.IsChecked = new bool?(!this.ViewModel.IsAnotacoes);
+			this.AnotacoesButton.Checked += new RoutedEventHandler(this.Anotacoes_OnChecked);
+			this.AnotacoesInternasButton.Checked += new RoutedEventHandler(this.AnotacoesInternas_OnChecked);
+		}
+
+		private void CopyTelefoneToClipBoard_Click(object sender, RoutedEventArgs e)
+		{
+			Button button = (Button)sender;
+			if (button.DataContext != null)
+			{
+				TelefoneBase dataContext = button.DataContext as TelefoneBase;
+				if (dataContext != null)
+				{
+					string.Concat(dataContext.get_Prefixo(), ValidationHelper.OnlyNumber(dataContext.get_Numero())).CopyToClipboard();
+					this.ToggleSnackBar(string.Concat("COPIADO - ", dataContext.get_Prefixo(), ValidationHelper.OnlyNumber(dataContext.get_Numero())), true);
+					return;
+				}
+			}
+		}
+
+		private void DataAtual_OnDoubleClick(object sender, RoutedEventArgs e)
+		{
+			((DatePicker)sender).SelectedDate = new DateTime?(Funcoes.GetNetworkTime().Date);
+		}
+
+		private void DatePicker_OnLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
+		{
+			DatePicker datePicker = (DatePicker)sender;
+			datePicker.Text = ValidationHelper.FormatDate(datePicker.Text);
+		}
+
+		private async void ExcluirResponsavel_OnClick(object sender, RoutedEventArgs e)
+		{
+			Chip chip = sender as Chip;
+			if (chip != null)
+			{
+				if (await this.ViewModel.ValidaPermissaoParaEditarTarefa())
+				{
+					ResponsavelTarefa dataContext = (ResponsavelTarefa)chip.DataContext;
+					if (dataContext != null)
+					{
+						this.ViewModel.Responsaveis.Remove(dataContext);
+						this.ViewModel.Usuarios.Add(dataContext.get_Usuario());
+						TarefaDrawerViewModel viewModel = this.ViewModel;
+						ObservableCollection usuarios = this.ViewModel.Usuarios;
+						viewModel.Usuarios = new ObservableCollection(
+							from x in usuarios
+							orderby x.get_Nome()
+							select x);
+					}
+				}
+				else
+				{
+					await this.ViewModel.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA EXCLUIR RESPONSÁVEL.", "OK", "", false);
+				}
+			}
+			chip = null;
+		}
+
+		private async void ExcluirTarefa_OnClick(object sender, RoutedEventArgs e)
+		{
+			Grid grid = Extentions.FindVisualAncestor((Button)sender);
+			ListBox listBox = Extentions.FindVisualAncestor(grid);
+			Tarefa item = (Tarefa)listBox.Items[listBox.Items.IndexOf(grid.DataContext)];
+			if (!await this.ViewModel.ValidaPermissaoParaExcluirTarefa(item))
+			{
+				await this.ViewModel.ShowMessage("VOCÊ NÃO TEM PERMISSÃO PARA EXCLUIR ESSA TAREFA", "OK", "", false);
+			}
+			else if (await this.ViewModel.Excluir(item))
+			{
+				this.ToggleSnackBar("TAREFA EXCLUÍDA COM SUCESSO.", true);
+			}
+			item = null;
+		}
+
+		private void Fechar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.CloseDrawer();
+		}
+
+		private void Imprimir_OnClick(object sender, RoutedEventArgs e)
+		{
+			Button button = (Button)sender;
+			if (button.DataContext == null)
+			{
+				return;
+			}
+			Tarefa dataContext = (Tarefa)button.DataContext;
+			if (dataContext.get_Id() == 0)
+			{
+				return;
+			}
+			this.ViewModel.SelectedTarefa = dataContext;
+			this.ViewModel.Print();
+		}
+
+		private void IncluirTarefa_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.AnotacoesButton.IsChecked = new bool?(true);
+			this.Anotacoes.Initialize(null);
+			this.AnotacoesInternas.Initialize(null);
+			this.ViewModel.Incluir();
+			this.Validar();
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		public void InitializeComponent()
+		{
+			if (this._contentLoaded)
+			{
+				return;
+			}
+			this._contentLoaded = true;
+			System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/drawers/tarefadrawer.xaml", UriKind.Relative));
+		}
+
+		private void InxlusaoAnexoTarefa_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.ArquivosAnexados = new ObservableCollection(this.ViewModel.ArquivosFinais);
+			this.ViewModel.ShowDrawer(new InclusaoArquivoDigitalDrawer(this.ViewModel), 0, false);
+		}
+
+		private async void MenuList_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
+		{
+			ListBox listBox = (ListBox)sender;
+			if (listBox.SelectedItem != null)
+			{
+				this.ViewModel.TituloTarefas = listBox.SelectedItem.ToString().Replace("System.Windows.Controls.ListBoxItem: ", "");
+				await this.ViewModel.CarregarTarefas(listBox.SelectedIndex);
+			}
+		}
+
+		private async void SalvarTarefa_OnClick(object sender, RoutedEventArgs e)
+		{
+			bool flag;
+			this.ViewModel.Carregando = true;
+			this.ViewModel.SelectedTarefa.set_Anotacoes(this.Anotacoes.GetHtml());
+			this.ViewModel.SelectedTarefa.set_AnotacoesInternas(this.AnotacoesInternas.GetHtml());
+			List> keyValuePairs = await this.ViewModel.Salvar(this.Anotacoes.GetText(), this.AnotacoesInternas.GetText());
+			flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0);
+			this.ViewModel.Carregando = false;
+			if (!flag)
+			{
+				await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", "");
+			}
+			else
+			{
+				this.ToggleSnackBar("TAREFA SALVA COM SUCESSO.", true);
+				this.ViewModel.Alterar(false);
+				this.Anotacoes.Initialize(null);
+				this.AnotacoesInternas.Initialize(null);
+			}
+		}
+
+		private void SnackbarMessage_ActionClick(object sender, RoutedEventArgs e)
+		{
+			this.Snackbar.set_IsActive(false);
+		}
+
+		private void Status_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
+		{
+			ComboBox comboBox = (ComboBox)sender;
+			if (comboBox == null || comboBox.SelectedItem == null)
+			{
+				return;
+			}
+			this.ViewModel.Concluido = (StatusTarefa)comboBox.SelectedItem == 2;
+			if ((StatusTarefa)comboBox.SelectedItem == 2)
+			{
+				DatePicker conclusaoBox = this.ConclusaoBox;
+				DateTime? conclusao = this.ViewModel.SelectedTarefa.get_Conclusao();
+				conclusaoBox.SelectedDate = new DateTime?((conclusao.HasValue ? conclusao.GetValueOrDefault() : Funcoes.GetNetworkTime()));
+			}
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target)
+		{
+			switch (connectionId)
+			{
+				case 1:
+				{
+					this.ProgressBar = (System.Windows.Controls.ProgressBar)target;
+					return;
+				}
+				case 2:
+				{
+					((ListBox)target).SelectionChanged += new SelectionChangedEventHandler(this.MenuList_OnSelectionChanged);
+					return;
+				}
+				case 3:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.Fechar_OnClick);
+					return;
+				}
+				case 4:
+				{
+					this.TitleBox = (TextBlock)target;
+					return;
+				}
+				case 5:
+				case 6:
+				case 12:
+				case 13:
+				case 14:
+				case 27:
+				{
+					this._contentLoaded = true;
+					return;
+				}
+				case 7:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.IncluirTarefa_OnClick);
+					return;
+				}
+				case 8:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick);
+					return;
+				}
+				case 9:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.SalvarTarefa_OnClick);
+					return;
+				}
+				case 10:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick);
+					return;
+				}
+				case 11:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.InxlusaoAnexoTarefa_OnClick);
+					return;
+				}
+				case 15:
+				{
+					this.AgendamentoBox = (DatePicker)target;
+					this.AgendamentoBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus);
+					this.AgendamentoBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick);
+					return;
+				}
+				case 16:
+				{
+					this.AtivoBox = (ToggleButton)target;
+					return;
+				}
+				case 17:
+				{
+					this.AnotacoesButton = (RadioButton)target;
+					return;
+				}
+				case 18:
+				{
+					this.AnotacoesInternasButton = (RadioButton)target;
+					return;
+				}
+				case 19:
+				{
+					this.Anotacoes = (WebEditor)target;
+					return;
+				}
+				case 20:
+				{
+					this.Historico = (WebEditor)target;
+					return;
+				}
+				case 21:
+				{
+					this.AnotacoesInternas = (WebEditor)target;
+					return;
+				}
+				case 22:
+				{
+					this.HistoricoInterno = (WebEditor)target;
+					return;
+				}
+				case 23:
+				{
+					((ComboBox)target).SelectionChanged += new SelectionChangedEventHandler(this.Status_OnSelectionChanged);
+					return;
+				}
+				case 24:
+				{
+					this.ConclusaoBox = (DatePicker)target;
+					this.ConclusaoBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus);
+					this.ConclusaoBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick);
+					return;
+				}
+				case 25:
+				{
+					this.CboResponsavel = (ComboBox)target;
+					return;
+				}
+				case 26:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.AdicionarResponsavel_OnClick);
+					return;
+				}
+				case 28:
+				{
+					this.Snackbar = (MaterialDesignThemes.Wpf.Snackbar)target;
+					return;
+				}
+				case 29:
+				{
+					((SnackbarMessage)target).add_ActionClick(new RoutedEventHandler(this.SnackbarMessage_ActionClick));
+					return;
+				}
+				default:
+				{
+					this._contentLoaded = true;
+					return;
+				}
+			}
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target)
+		{
+			if (connectionId <= 6)
+			{
+				if (connectionId == 5)
+				{
+					((Button)target).Click += new RoutedEventHandler(this.CopyTelefoneToClipBoard_Click);
+					return;
+				}
+				if (connectionId != 6)
+				{
+					return;
+				}
+				((Button)target).Click += new RoutedEventHandler(this.WhatsAppMessage_Click);
+				return;
+			}
+			switch (connectionId)
+			{
+				case 12:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.ExcluirTarefa_OnClick);
+					return;
+				}
+				case 13:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.AnexoTarefa_OnClick);
+					return;
+				}
+				case 14:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.Imprimir_OnClick);
+					return;
+				}
+				default:
+				{
+					if (connectionId == 27)
+					{
+						break;
+					}
+					else
+					{
+						return;
+					}
+				}
+			}
+			((Chip)target).add_DeleteClick(new RoutedEventHandler(this.ExcluirResponsavel_OnClick));
+		}
+
+		public void ToggleSnackBar(string message, bool active = true)
+		{
+			this.Snackbar.get_Message().Content = message;
+			this.Snackbar.set_IsActive(active);
+			if (!active)
+			{
+				return;
+			}
+			Task.Factory.StartNew(new Action(this.CloseSlackBar));
+		}
+
+		private void Validar()
+		{
+			if (this.ViewModel.SelectedTarefa == null)
+			{
+				return;
+			}
+			this.ViewModel.SelectedTarefa.set_AgendamentoRetroativo(Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 45));
+			List> keyValuePairs = this.ViewModel.SelectedTarefa.Validate();
+			this.ValidateFields(keyValuePairs, false);
+		}
+
+		private async void WhatsAppMessage_Click(object sender, RoutedEventArgs e)
+		{
+			string str;
+			Button button = (Button)sender;
+			if (button.DataContext != null)
+			{
+				TelefoneBase dataContext = button.DataContext as TelefoneBase;
+				if (dataContext != null)
+				{
+					str = (!dataContext.get_Tipo().HasValue || dataContext.get_Tipo().GetValueOrDefault() != 8 ? string.Concat("55", dataContext.get_Prefixo(), dataContext.get_Numero().Clear()) : string.Concat(dataContext.get_Prefixo(), dataContext.get_Numero()).Clear());
+					if (!str.EnviarWhatsapp(null))
+					{
+						await this.ViewModel.ShowMessage("HOUVE UM PROBLEMA AO ABRIR LINK DO WHATSAPP, O LINK FOI COPIADO EM SUA MAQUINA, BASTA ABRIR O NAVEGADOR DE INTERNET E COLAR NA BARRA DE ENDEREÇOS", "OK", "", false);
+					}
+					return;
+				}
+			}
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Drawers/ValoresApoliceDrawer.cs b/Codemerx/Gestor.Application/Drawers/ValoresApoliceDrawer.cs
new file mode 100644
index 0000000..f11ad64
--- /dev/null
+++ b/Codemerx/Gestor.Application/Drawers/ValoresApoliceDrawer.cs
@@ -0,0 +1,63 @@
+using Gestor.Application.ViewModels.Drawer;
+using Gestor.Application.ViewModels.Generic;
+using Gestor.Application.Views.Generic;
+using Gestor.Model.Domain.Seguros;
+using System;
+using System.CodeDom.Compiler;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Drawers
+{
+	public class ValoresApoliceDrawer : BaseUserControl, IComponentConnector
+	{
+		private bool _contentLoaded;
+
+		public ValoresApoliceViewModel ViewModel
+		{
+			get;
+			set;
+		}
+
+		public ValoresApoliceDrawer(Documento documento)
+		{
+			this.ViewModel = new ValoresApoliceViewModel(documento);
+			base.DataContext = this.ViewModel;
+			this.InitializeComponent();
+		}
+
+		private void Fechar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.CloseDrawer();
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		public void InitializeComponent()
+		{
+			if (this._contentLoaded)
+			{
+				return;
+			}
+			this._contentLoaded = true;
+			System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/drawers/valoresapolicedrawer.xaml", UriKind.Relative));
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target)
+		{
+			if (connectionId != 1)
+			{
+				this._contentLoaded = true;
+				return;
+			}
+			((Button)target).Click += new RoutedEventHandler(this.Fechar_OnClick);
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Drawers/ValoresParcelaDrawer.cs b/Codemerx/Gestor.Application/Drawers/ValoresParcelaDrawer.cs
new file mode 100644
index 0000000..2e5979d
--- /dev/null
+++ b/Codemerx/Gestor.Application/Drawers/ValoresParcelaDrawer.cs
@@ -0,0 +1,70 @@
+using Gestor.Application.ViewModels.Drawer;
+using Gestor.Application.ViewModels.Generic;
+using Gestor.Application.Views.Generic;
+using Gestor.Model.Domain.Seguros;
+using System;
+using System.CodeDom.Compiler;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Drawers
+{
+	public class ValoresParcelaDrawer : BaseUserControl, IComponentConnector
+	{
+		internal DockPanel pnlStatusParcelaExtrato;
+
+		private bool _contentLoaded;
+
+		public ValoresParcelaViewModel ViewModel
+		{
+			get;
+			set;
+		}
+
+		public ValoresParcelaDrawer(Parcela parcela, Documento documento)
+		{
+			this.ViewModel = new ValoresParcelaViewModel(parcela, documento);
+			base.DataContext = this.ViewModel;
+			this.InitializeComponent();
+		}
+
+		private void Fechar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.CloseDrawer();
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		public void InitializeComponent()
+		{
+			if (this._contentLoaded)
+			{
+				return;
+			}
+			this._contentLoaded = true;
+			System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/drawers/valoresparceladrawer.xaml", UriKind.Relative));
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target)
+		{
+			if (connectionId == 1)
+			{
+				((Button)target).Click += new RoutedEventHandler(this.Fechar_OnClick);
+				return;
+			}
+			if (connectionId != 2)
+			{
+				this._contentLoaded = true;
+				return;
+			}
+			this.pnlStatusParcelaExtrato = (DockPanel)target;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Drawers/VinculoVendedorDrawer.cs b/Codemerx/Gestor.Application/Drawers/VinculoVendedorDrawer.cs
new file mode 100644
index 0000000..9b03e23
--- /dev/null
+++ b/Codemerx/Gestor.Application/Drawers/VinculoVendedorDrawer.cs
@@ -0,0 +1,124 @@
+using Gestor.Application.ViewModels.Drawer;
+using Gestor.Application.ViewModels.Generic;
+using Gestor.Application.Views.Generic;
+using Gestor.Common.Validation;
+using Gestor.Model.Domain.Generic;
+using Gestor.Model.Domain.Seguros;
+using System;
+using System.CodeDom.Compiler;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Markup;
+
+namespace Gestor.Application.Drawers
+{
+	public class VinculoVendedorDrawer : BaseUserControl, IComponentConnector
+	{
+		public VinculoVendedorViewModel ViewModel;
+
+		internal DataGrid VendedorGrid;
+
+		internal DataGrid VinculadoGrid;
+
+		private bool _contentLoaded;
+
+		public VinculoVendedorDrawer(Usuario usuario)
+		{
+			this.ViewModel = new VinculoVendedorViewModel(usuario);
+			base.DataContext = this.ViewModel;
+			this.InitializeComponent();
+		}
+
+		private void AbrirLog_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.AbrirLog(45, this.ViewModel.SelectedUsuario.get_Id());
+		}
+
+		private async void AutoCompleteBox_OnTextChanged(object sender, RoutedEventArgs e)
+		{
+			if (((AutoCompleteBox)sender).get_Text() == string.Empty)
+			{
+				await this.ViewModel.BuscarVinculoVendedor("");
+			}
+		}
+
+		private void AutoCompleteBox_Populating(object sender, PopulatingEventArgs e)
+		{
+			if (e.get_Parameter().Length < 3)
+			{
+				return;
+			}
+			e.set_Cancel(true);
+			this.ViewModel.BuscarVinculoVendedor(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task searchResult) => ((AutoCompleteBox)sender).PopulateComplete(), TaskScheduler.FromCurrentSynchronizationContext());
+		}
+
+		private void Fechar_OnClick(object sender, RoutedEventArgs e)
+		{
+			this.ViewModel.CloseDrawer();
+		}
+
+		[DebuggerNonUserCode]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		public void InitializeComponent()
+		{
+			if (this._contentLoaded)
+			{
+				return;
+			}
+			this._contentLoaded = true;
+			System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/drawers/vinculovendedordrawer.xaml", UriKind.Relative));
+		}
+
+		private async void SalvarVinculo_OnClick(object sender, RoutedEventArgs e)
+		{
+			await this.ViewModel.Salvar();
+			this.ViewModel.ToggleSnackBar("VÍNCULO DE USUÁRIO SALVO COM SUCESSO.", true);
+		}
+
+		[DebuggerNonUserCode]
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
+		void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target)
+		{
+			switch (connectionId)
+			{
+				case 1:
+				{
+					((Button)target).Click += new RoutedEventHandler(this.Fechar_OnClick);
+					return;
+				}
+				case 2:
+				{
+					((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, VinculoVendedorDrawer.AutoCompleteBox_Populating));
+					((AutoCompleteBox)target).add_TextChanged(new RoutedEventHandler(this.AutoCompleteBox_OnTextChanged));
+					return;
+				}
+				case 3:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick);
+					return;
+				}
+				case 4:
+				{
+					this.VendedorGrid = (DataGrid)target;
+					return;
+				}
+				case 5:
+				{
+					this.VinculadoGrid = (DataGrid)target;
+					return;
+				}
+				case 6:
+				{
+					((MenuItem)target).Click += new RoutedEventHandler(this.SalvarVinculo_OnClick);
+					return;
+				}
+			}
+			this._contentLoaded = true;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Helpers/ApplicationHelper.cs b/Codemerx/Gestor.Application/Helpers/ApplicationHelper.cs
new file mode 100644
index 0000000..1250a2e
--- /dev/null
+++ b/Codemerx/Gestor.Application/Helpers/ApplicationHelper.cs
@@ -0,0 +1,98 @@
+using Agger.Registro;
+using Gestor.Common.Helpers;
+using System;
+using System.Runtime.CompilerServices;
+
+namespace Gestor.Application.Helpers
+{
+	public class ApplicationHelper
+	{
+		private static string _numeroSerial;
+
+		private const string ChaveSerial = "NS";
+
+		public static bool Beta
+		{
+			get;
+			set;
+		}
+
+		public static DateTime ChecagemVersao
+		{
+			get;
+			set;
+		}
+
+		public static bool Conectado
+		{
+			get;
+			set;
+		}
+
+		public static long IdFornecedor
+		{
+			get;
+			set;
+		}
+
+		public static string NumeroSerial
+		{
+			get
+			{
+				return ApplicationHelper._numeroSerial ?? ApplicationHelper.GetSerialNumber();
+			}
+			set
+			{
+				ApplicationHelper._numeroSerial = value;
+			}
+		}
+
+		public static string Subkey
+		{
+			get;
+			set;
+		}
+
+		public static Version Versao
+		{
+			get;
+			set;
+		}
+
+		static ApplicationHelper()
+		{
+			ApplicationHelper.Conectado = true;
+			ApplicationHelper.Beta = false;
+			ApplicationHelper.ChecagemVersao = Funcoes.GetNetworkTime();
+		}
+
+		public ApplicationHelper()
+		{
+		}
+
+		internal static string GetSerialNumber()
+		{
+			string numeroSerial;
+			string str;
+			try
+			{
+				string str1 = (new RegistryHelper(ApplicationHelper.Subkey)).Read("NS", true);
+				if (string.IsNullOrEmpty(str1))
+				{
+					str = null;
+				}
+				else
+				{
+					str = EncryptionHelper.Decrypt(str1);
+				}
+				ApplicationHelper.NumeroSerial = str;
+				numeroSerial = ApplicationHelper.NumeroSerial;
+			}
+			catch (Exception exception)
+			{
+				numeroSerial = null;
+			}
+			return numeroSerial;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Helpers/ArquivoDigital.cs b/Codemerx/Gestor.Application/Helpers/ArquivoDigital.cs
new file mode 100644
index 0000000..c140906
--- /dev/null
+++ b/Codemerx/Gestor.Application/Helpers/ArquivoDigital.cs
@@ -0,0 +1,65 @@
+using ArquivoDigital.Infrastructure.UnitOfWork.Logic;
+using Gestor.Application.Servicos.Generic;
+using Gestor.Model.Domain.Common;
+using System;
+using System.Runtime.CompilerServices;
+using System.Threading.Tasks;
+
+namespace Gestor.Application.Helpers
+{
+	public static class ArquivoDigital
+	{
+		public static string ConexaoAd;
+
+		public static string Banco
+		{
+			get;
+			set;
+		}
+
+		public static UnitOfWork Commited
+		{
+			get
+			{
+				return Gestor.Application.Helpers.ArquivoDigital.UnitOfWork(true, false);
+			}
+		}
+
+		public static UnitOfWork Read
+		{
+			get
+			{
+				return Gestor.Application.Helpers.ArquivoDigital.UnitOfWork(false, false);
+			}
+		}
+
+		public static string Tabela
+		{
+			get;
+			set;
+		}
+
+		static ArquivoDigital()
+		{
+			Gestor.Application.Helpers.ArquivoDigital.ConexaoAd = null;
+			Gestor.Application.Helpers.ArquivoDigital.Tabela = "arquivodigital";
+		}
+
+		public static void SetConnection(string banco = "")
+		{
+			ControleArquivoDigital controleArquivoDigital = (string.IsNullOrEmpty(banco) ? (new BaseServico()).ArquivoDigital().Result : (new BaseServico()).ArquivoDigital(banco).Result);
+			Gestor.Application.Helpers.ArquivoDigital.Banco = controleArquivoDigital.get_Catalogo();
+			Gestor.Application.Helpers.ArquivoDigital.Tabela = (string.IsNullOrWhiteSpace(controleArquivoDigital.get_Tabela()) ? "arquivodigital" : controleArquivoDigital.get_Tabela());
+			Gestor.Application.Helpers.ArquivoDigital.ConexaoAd = string.Concat(new string[] { "Server=", Connection.Server, ";initial catalog=", controleArquivoDigital.get_Catalogo(), ";user=", Connection.User, ";password=", Connection.Password, ";" });
+		}
+
+		private static UnitOfWork UnitOfWork(bool withTransaction = true, bool reconect = false)
+		{
+			if (Gestor.Application.Helpers.ArquivoDigital.ConexaoAd == null)
+			{
+				Gestor.Application.Helpers.ArquivoDigital.SetConnection("");
+			}
+			return new UnitOfWork(Gestor.Application.Helpers.ArquivoDigital.ConexaoAd, Gestor.Application.Helpers.ArquivoDigital.Tabela, withTransaction);
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Helpers/AssinadorHelper.cs b/Codemerx/Gestor.Application/Helpers/AssinadorHelper.cs
new file mode 100644
index 0000000..2a6939d
--- /dev/null
+++ b/Codemerx/Gestor.Application/Helpers/AssinadorHelper.cs
@@ -0,0 +1,211 @@
+using Agger.Registro;
+using Assinador.Model.Domain;
+using Newtonsoft.Json;
+using Sign.Modelos;
+using System;
+using System.Diagnostics;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Runtime.CompilerServices;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Gestor.Application.Helpers
+{
+	public static class AssinadorHelper
+	{
+		private static ParametrosAssinaturaAssinador _parametros;
+
+		public const string Authorization = "Authorization";
+
+		public const string Server = "Server";
+
+		public const string Contrato = "Purchase";
+
+		public const string Adquirir = "Purchase/BuyPackage";
+
+		public const string Disponiveis = "Sign/Availble";
+
+		public const string Contratadas = "Sign/Purchased";
+
+		private static string ApiKey
+		{
+			get;
+			set;
+		}
+
+		public static ParametrosAssinaturaAssinador Parametros
+		{
+			get
+			{
+				return AssinadorHelper._parametros;
+			}
+			set
+			{
+				AssinadorHelper._parametros = value;
+				if (value == null)
+				{
+					return;
+				}
+				Sign.Modelos.Remetente remetente = new Sign.Modelos.Remetente();
+				remetente.set_Id(ApplicationHelper.IdFornecedor);
+				remetente.set_Documento(value.get_Documento());
+				remetente.set_Email(value.get_Email());
+				remetente.set_Nome(value.get_Nome());
+				remetente.set_Serial(ApplicationHelper.NumeroSerial);
+				AssinadorHelper.Remetente = remetente;
+			}
+		}
+
+		public static Sign.Modelos.Remetente Remetente
+		{
+			get;
+			set;
+		}
+
+		private static string Base64EncodeBasic(string plainText)
+		{
+			return Convert.ToBase64String(Encoding.UTF8.GetBytes(plainText));
+		}
+
+		public static string BasicKey(this string serial)
+		{
+			DateTime universalTime = Funcoes.GetNetworkTime().ToUniversalTime();
+			return AssinadorHelper.Base64EncodeBasic(string.Format("{0}:{1}", serial, universalTime.Ticks));
+		}
+
+		public static async Task Contratado(long id)
+		{
+			bool flag = await AssinadorHelper.Get(string.Format("{0}{1}/{2}/86", Address.GestorApi(), "Purchase", id), ApplicationHelper.NumeroSerial.BasicKey(), true) == "true";
+			return flag;
+		}
+
+		public static async Task Get(string command, string token = null, bool basic = false)
+		{
+			HttpStatusCode statusCode;
+			HttpResponseMessage httpResponseMessage;
+			string str = (basic ? "Basic" : "Token");
+			Uri uri = new Uri(Address.GestorApi(), command);
+			HttpClient httpClient = new HttpClient();
+			if (!string.IsNullOrWhiteSpace(token))
+			{
+				httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue(str, token));
+			}
+			ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+			try
+			{
+				ConfiguredTaskAwaitable configuredTaskAwaitable = httpClient.GetAsync(uri).ConfigureAwait(false);
+				httpResponseMessage = await configuredTaskAwaitable;
+			}
+			catch (Exception exception)
+			{
+				statusCode = HttpStatusCode.InternalServerError;
+				return statusCode;
+			}
+			statusCode = httpResponseMessage.get_StatusCode();
+			return statusCode;
+		}
+
+		internal static async Task Get(string command, string token = null, bool basic = false)
+		where T : class
+		{
+			T t;
+			HttpResponseMessage httpResponseMessage;
+			string str = (basic ? "Basic" : "Token");
+			Uri uri = new Uri(command);
+			HttpClient httpClient = new HttpClient();
+			if (!string.IsNullOrWhiteSpace(token))
+			{
+				httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue(str, token));
+			}
+			ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+			try
+			{
+				ConfiguredTaskAwaitable configuredTaskAwaitable = httpClient.GetAsync(uri).ConfigureAwait(false);
+				httpResponseMessage = await configuredTaskAwaitable;
+			}
+			catch (Exception exception)
+			{
+				t = default(T);
+				return t;
+			}
+			if (httpResponseMessage.get_StatusCode() == HttpStatusCode.OK)
+			{
+				string result = httpResponseMessage.get_Content().ReadAsStringAsync().Result;
+				t = JsonConvert.DeserializeObject(httpResponseMessage.get_Content().ReadAsStringAsync().Result);
+			}
+			else
+			{
+				t = default(T);
+			}
+			return t;
+		}
+
+		public static async Task Key()
+		{
+			string str = null;
+			try
+			{
+				str = await AssinadorHelper.Get(string.Format("{0}{1}/86", Address.AssinadorApi(), "Authorization"), ApplicationHelper.NumeroSerial.BasicKey(), true);
+			}
+			catch (Exception exception)
+			{
+			}
+			string str1 = str;
+			str = null;
+			return str1;
+		}
+
+		public static async Task Licencas(string key)
+		{
+			int num;
+			if (key != null)
+			{
+				int num1 = 0;
+				try
+				{
+					string str = await AssinadorHelper.Get(string.Format("{0}{1}/{2}", Address.AssinadorApi(), "Sign/Availble", ApplicationHelper.IdFornecedor), key, false);
+					num1 = int.Parse(str);
+				}
+				catch (Exception exception)
+				{
+				}
+				num = num1;
+			}
+			else
+			{
+				num = 0;
+			}
+			return num;
+		}
+
+		internal static async Task Put(string command, T keyValues, string token = null, bool basic = false)
+		where T : class
+		{
+			T t;
+			string str = (basic ? "Basic" : "Token");
+			Uri uri = new Uri(command);
+			object obj = keyValues;
+			JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings();
+			jsonSerializerSetting.set_ReferenceLoopHandling(1);
+			StringContent stringContent = new StringContent(JsonConvert.SerializeObject(obj, 1, jsonSerializerSetting), Encoding.UTF8, "application/json");
+			HttpClient httpClient = new HttpClient();
+			ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+			if (!string.IsNullOrWhiteSpace(token))
+			{
+				httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue(str, token));
+			}
+			HttpResponseMessage httpResponseMessage = await httpClient.PutAsync(uri, stringContent);
+			if (httpResponseMessage.get_StatusCode() == HttpStatusCode.OK || httpResponseMessage.get_StatusCode() == HttpStatusCode.NoContent)
+			{
+				t = (httpResponseMessage.get_StatusCode() != HttpStatusCode.NoContent ? JsonConvert.DeserializeObject(httpResponseMessage.get_Content().ReadAsStringAsync().Result) : default(T));
+			}
+			else
+			{
+				t = default(T);
+			}
+			return t;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Helpers/BindingEnumHelper.cs b/Codemerx/Gestor.Application/Helpers/BindingEnumHelper.cs
new file mode 100644
index 0000000..54e9330
--- /dev/null
+++ b/Codemerx/Gestor.Application/Helpers/BindingEnumHelper.cs
@@ -0,0 +1,56 @@
+using System;
+using System.ComponentModel;
+using System.Reflection;
+using System.Text;
+
+namespace Gestor.Application.Helpers
+{
+	public class BindingEnumHelper
+	{
+		public BindingEnumHelper()
+		{
+		}
+
+		public static string ConcatenarDescricoesEnum(string valores)
+		where TEnum : Enum
+		{
+			if (valores == null)
+			{
+				return null;
+			}
+			return BindingEnumHelper.ConcatenarDescricoesEnum(Array.ConvertAll(valores.Split(new char[] { ',' }), new Converter(int.Parse)));
+		}
+
+		private static string ConcatenarDescricoesEnum(int[] valores)
+		where TEnum : Enum
+		{
+			StringBuilder stringBuilder = new StringBuilder();
+			int[] numArray = valores;
+			for (int i = 0; i < (int)numArray.Length; i++)
+			{
+				int num = numArray[i];
+				if (!Enum.IsDefined(typeof(TEnum), num))
+				{
+					stringBuilder.Append("Valor desconhecido, ");
+				}
+				else
+				{
+					string str = BindingEnumHelper.ObterDescricaoEnum((TEnum)Enum.ToObject(typeof(TEnum), num));
+					stringBuilder.Append(string.Concat(str, ", "));
+				}
+			}
+			return stringBuilder.ToString().TrimEnd(new char[] { ',', ' ' });
+		}
+
+		private static string ObterDescricaoEnum(TEnum valor)
+		where TEnum : Enum
+		{
+			DescriptionAttribute[] customAttributes = (DescriptionAttribute[])valor.GetType().GetField(valor.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
+			if (customAttributes == null || customAttributes.Length == 0)
+			{
+				return valor.ToString();
+			}
+			return customAttributes[0].Description;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Helpers/BindingHelper.cs b/Codemerx/Gestor.Application/Helpers/BindingHelper.cs
new file mode 100644
index 0000000..3c9d76e
--- /dev/null
+++ b/Codemerx/Gestor.Application/Helpers/BindingHelper.cs
@@ -0,0 +1,239 @@
+using CurrencyTextBoxControl;
+using Gestor.Common.Helpers;
+using Gestor.Model.Helper;
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Linq;
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Controls.Primitives;
+using System.Windows.Data;
+
+namespace Gestor.Application.Helpers
+{
+	public static class BindingHelper
+	{
+		public static void AddBinding(object control, string path, ValidationRule rule = null)
+		{
+			Type type = control.GetType();
+			Binding binding = new Binding()
+			{
+				Mode = BindingMode.TwoWay,
+				UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
+				Path = new PropertyPath(path, Array.Empty())
+			};
+			if (rule != null)
+			{
+				binding.ValidationRules.Add(rule);
+				binding.ValidationRules[0].ValidatesOnTargetUpdated = true;
+			}
+			string name = type.Name;
+			if (name == "TextBox")
+			{
+				((TextBox)control).SetBinding(TextBox.TextProperty, binding);
+				return;
+			}
+			if (name == "DatePicker")
+			{
+				((DatePicker)control).SetBinding(DatePicker.SelectedDateProperty, binding);
+				return;
+			}
+			if (name != "CurrencyTextBox")
+			{
+				return;
+			}
+			((CurrencyTextBox)control).SetBinding(CurrencyTextBox.NumberProperty, binding);
+		}
+
+		public static void AddValidationRule(object control, ValidationRule rule = null)
+		{
+			// 
+			// Current member / type: System.Void Gestor.Application.Helpers.BindingHelper::AddValidationRule(System.Object,System.Windows.Controls.ValidationRule)
+			// File path: C:\AggerSeguros\Gestor.Application.exe
+			// 
+			// Product version: 0.0.0.0
+			// Exception in: System.Void AddValidationRule(System.Object,System.Windows.Controls.ValidationRule)
+			// 
+			// Object reference not set to an instance of an object.
+			//    at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.FindLowestCommonAncestor(ICollection`1 typeNodes) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 515
+			//    at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.MergeWithLowestCommonAncestor() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 459
+			//    at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.ProcessSingleConstraints() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 378
+			//    at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.InferTypes() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 331
+			//    at Telerik.JustDecompiler.Decompiler.ExpressionDecompilerStep.Process(DecompilationContext theContext, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\ExpressionDecompilerStep.cs:line 104
+			//    at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100
+			//    at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72
+			//    at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61
+			//    at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 133
+			// 
+			// mailto: JustDecompilePublicFeedback@telerik.com
+
+		}
+
+		private static List> AfterTreatment(bool withSelect, bool orderByLabel, List> comboData, List> comboValues, bool orderbyAttr = false)
+		{
+			List> list = comboData;
+			if (!withSelect)
+			{
+				list.RemoveAt(0);
+			}
+			list.AddRange(comboValues);
+			if (orderbyAttr)
+			{
+				Type type = typeof(T);
+				list = list.OrderBy, int?>((KeyValuePair s) => {
+					if (s.Key == string.Empty)
+					{
+						return new int?(0);
+					}
+					return EnumHelper.GetOrder((T)Enum.Parse(type, s.Key));
+				}).ToList>();
+				return list;
+			}
+			if (!orderByLabel)
+			{
+				return list;
+			}
+			list = (
+				from  in list
+				orderby Math.Sign(ValidationHelper.ToFloat(x.Key)), Math.Abs(ValidationHelper.ToFloat(x.Key))
+				select ).ToList>();
+			list = (
+				from  in list
+				orderby list.IndexOf(s) != 0, s.Value
+				select ).ToList>();
+			return list;
+		}
+
+		private static List> BeforeTreatment(string defaultValue, string defaultText)
+		{
+			defaultText = (defaultText == string.Empty ? "Selecione" : defaultText);
+			return new List>()
+			{
+				new KeyValuePair(defaultValue, defaultText)
+			};
+		}
+
+		public static List> BindingData(bool withSelect = true, bool enumDefault = true, string defaultValue = "", string defaultText = "", bool orderByLabel = false, bool showAll = false, bool orderbyAttr = false)
+		{
+			List> keyValuePairs = BindingHelper.BeforeTreatment(defaultValue, defaultText);
+			Type type = typeof(T);
+			List> list = Enum.GetNames(type).AsEnumerable().Where((string x) => {
+				if (showAll)
+				{
+					return true;
+				}
+				T t = (T)Enum.Parse(type, x);
+				bool? @default = EnumHelper.GetDefault(t);
+				bool hidden = EnumHelper.GetHidden(t);
+				if (@default.HasValue && @default.Value != enumDefault)
+				{
+					return false;
+				}
+				return !hidden;
+			}).Select>((string x) => {
+				T t = (T)Enum.Parse(type, x);
+				return new KeyValuePair(EnumHelper.Value(t), EnumHelper.GetDescription(t));
+			}).ToList>();
+			return BindingHelper.AfterTreatment(withSelect, orderByLabel, keyValuePairs, list, orderbyAttr);
+		}
+
+		public static void DeleteValidationRule(object control)
+		{
+			Binding binding;
+			string name = control.GetType().Name;
+			if (name == "TextBox")
+			{
+				binding = BindingOperations.GetBinding((TextBox)control, TextBox.TextProperty) ?? new Binding()
+				{
+					Mode = BindingMode.TwoWay,
+					UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
+				};
+				binding.ValidationRules.Clear();
+				((TextBox)control).SetBinding(TextBox.TextProperty, binding);
+				return;
+			}
+			if (name == "DatePicker")
+			{
+				binding = BindingOperations.GetBinding((DatePicker)control, DatePicker.SelectedDateProperty) ?? new Binding()
+				{
+					Mode = BindingMode.TwoWay,
+					UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
+				};
+				binding.ValidationRules.Clear();
+				((DatePicker)control).SetBinding(DatePicker.SelectedDateProperty, binding);
+				return;
+			}
+			if (name != "CurrencyTextBox")
+			{
+				return;
+			}
+			binding = BindingOperations.GetBinding((CurrencyTextBox)control, CurrencyTextBox.NumberProperty) ?? new Binding()
+			{
+				Mode = BindingMode.TwoWay,
+				UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
+			};
+			binding.ValidationRules.Clear();
+			((CurrencyTextBox)control).SetBinding(CurrencyTextBox.NumberProperty, binding);
+		}
+
+		public static string GetPath(object control)
+		{
+			Binding binding;
+			PropertyPath path;
+			string name = control.GetType().Name;
+			if (name == "TextBox")
+			{
+				binding = BindingOperations.GetBinding((TextBox)control, TextBox.TextProperty);
+				if (binding == null)
+				{
+					return "";
+				}
+				path = binding.Path;
+			}
+			else if (name == "DatePicker")
+			{
+				binding = BindingOperations.GetBinding((DatePicker)control, DatePicker.SelectedDateProperty);
+				if (binding == null)
+				{
+					return "";
+				}
+				path = binding.Path;
+			}
+			else if (name == "CurrencyTextBox")
+			{
+				binding = BindingOperations.GetBinding((CurrencyTextBox)control, CurrencyTextBox.NumberProperty);
+				if (binding == null)
+				{
+					return "";
+				}
+				path = binding.Path;
+			}
+			else if (name == "ComboBox")
+			{
+				binding = BindingOperations.GetBinding((ComboBox)control, Selector.SelectedItemProperty);
+				if (binding == null)
+				{
+					return "";
+				}
+				path = binding.Path;
+			}
+			else
+			{
+				if (name != "AutoCompleteBox")
+				{
+					return "";
+				}
+				binding = BindingOperations.GetBinding((AutoCompleteBox)control, AutoCompleteBox.SelectedItemProperty);
+				if (binding == null)
+				{
+					return "";
+				}
+				path = binding.Path;
+			}
+			return path.Path;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Helpers/Connection.cs b/Codemerx/Gestor.Application/Helpers/Connection.cs
new file mode 100644
index 0000000..7458e99
--- /dev/null
+++ b/Codemerx/Gestor.Application/Helpers/Connection.cs
@@ -0,0 +1,632 @@
+using Agger.Registro;
+using Gestor.Common.Security;
+using Gestor.Common.Validation;
+using Gestor.Model.API;
+using Newtonsoft.Json;
+using System;
+using System.Collections.Generic;
+using System.Data.SqlClient;
+using System.Diagnostics;
+using System.IO;
+using System.Linq;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Runtime.CompilerServices;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Gestor.Application.Helpers
+{
+	public static class Connection
+	{
+		private const bool defaultUsaAzureStorage = false;
+
+		private const string defaultAzureStorage = "ad1";
+
+		public static string Server;
+
+		public static string Catalog;
+
+		public static string User;
+
+		public static string Password;
+
+		public static string Pool;
+
+		public static string Type;
+
+		public static Gestor.Model.API.ConnectionAddress ConnectionAddress
+		{
+			get;
+			set;
+		}
+
+		public static string LinkAggilizador
+		{
+			get;
+			set;
+		}
+
+		public static string UrlCentralSegurado
+		{
+			get;
+			set;
+		}
+
+		private static string AdApiV2(string storage)
+		{
+			if (Address.get_ApiAD().ToString().Contains("/api/v1"))
+			{
+				return string.Empty;
+			}
+			return storage;
+		}
+
+		internal static Uri Append(this Uri uri, params string[] paths)
+		{
+			return new Uri(paths.Aggregate(uri.AbsoluteUri, (string current, string path) => string.Concat(current.TrimEnd(new char[] { '/' }), "/", path.TrimStart(new char[] { '/' }))));
+		}
+
+		public static string Base64Encode(this string plainText)
+		{
+			return (new Token()).Encrypt(plainText);
+		}
+
+		public static string BasicKey()
+		{
+			string numeroSerial = ApplicationHelper.NumeroSerial;
+			DateTime universalTime = Funcoes.GetNetworkTime().ToUniversalTime();
+			return string.Format("{0}:{1}", numeroSerial, universalTime.Ticks).Base64Encode();
+		}
+
+		public static async Task Delete(string command)
+		{
+			Uri uri = new Uri(Address.GestorApi(), command);
+			HttpClient httpClient = new HttpClient();
+			ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+			httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue("Token", Gestor.Application.Helpers.Connection.BasicKey()));
+			if (await httpClient.DeleteAsync(uri).get_StatusCode() != HttpStatusCode.OK)
+			{
+				throw new Exception(string.Concat("Api connection Error ", Environment.NewLine, " ", command), null);
+			}
+			return true;
+		}
+
+		internal static async Task DeleteFile(string azureStorage, int ano, Guid id, string extensao, string path = "ad")
+		{
+			bool flag;
+			string str;
+			bool flag1;
+			str = (string.IsNullOrEmpty(azureStorage) ? "ad1" : azureStorage);
+			azureStorage = str;
+			Uri apiAD = Address.get_ApiAD();
+			string[] strArrays = new string[] { Gestor.Application.Helpers.Connection.AdApiV2(azureStorage) };
+			Uri uri = apiAD.Append(strArrays);
+			string[] strArrays1 = new string[] { path };
+			Uri uri1 = uri.Append(strArrays1);
+			string[] str1 = new string[] { ano.ToString() };
+			Uri uri2 = uri1.Append(str1);
+			string[] str2 = new string[] { id.ToString() };
+			Uri uri3 = uri2.Append(str2);
+			string[] strArrays2 = new string[] { extensao.Replace(".", string.Empty) };
+			Uri uri4 = uri3.Append(strArrays2);
+			try
+			{
+				using (HttpClient httpClient = new HttpClient())
+				{
+					ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
+					httpClient.get_DefaultRequestHeaders().Clear();
+					httpClient.get_DefaultRequestHeaders().Add("Authorization", string.Concat("Token ", Gestor.Application.Helpers.Connection.BasicKey()));
+					HttpResponseMessage httpResponseMessage = await httpClient.DeleteAsync(uri4);
+					flag1 = (!httpResponseMessage.get_IsSuccessStatusCode() ? false : httpResponseMessage.get_StatusCode() != HttpStatusCode.NoContent);
+					flag = flag1;
+					return flag;
+				}
+			}
+			catch
+			{
+			}
+			flag = false;
+			return flag;
+		}
+
+		internal static async Task DownloadFile(string azureStorage, int ano, Guid id, string extensao, string path = "ad", bool forceDownload = false)
+		{
+			byte[] numArray;
+			string str;
+			str = (string.IsNullOrEmpty(azureStorage) ? "ad1" : azureStorage);
+			azureStorage = str;
+			Uri apiAD = Address.get_ApiAD();
+			string[] strArrays = new string[] { Gestor.Application.Helpers.Connection.AdApiV2(azureStorage) };
+			Uri uri = apiAD.Append(strArrays);
+			string[] strArrays1 = new string[] { path };
+			Uri uri1 = uri.Append(strArrays1);
+			string[] str1 = new string[] { ano.ToString() };
+			Uri uri2 = uri1.Append(str1);
+			string[] str2 = new string[] { id.ToString() };
+			Uri uri3 = uri2.Append(str2);
+			string[] strArrays2 = new string[] { extensao.Replace(".", string.Empty) };
+			Uri uri4 = uri3.Append(strArrays2);
+			try
+			{
+				string str3 = string.Format("{0}{1}{2}", Path.GetTempPath(), id, extensao);
+				if (forceDownload || !File.Exists(str3))
+				{
+					using (HttpClient httpClient = new HttpClient())
+					{
+						ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
+						httpClient.get_DefaultRequestHeaders().Clear();
+						httpClient.get_DefaultRequestHeaders().Add("Authorization", string.Concat("Token ", Gestor.Application.Helpers.Connection.BasicKey()));
+						HttpResponseMessage async = await httpClient.GetAsync(uri4);
+						if (async.get_IsSuccessStatusCode() && async.get_StatusCode() != HttpStatusCode.NotFound)
+						{
+							numArray = await async.get_Content().ReadAsByteArrayAsync();
+							return numArray;
+						}
+					}
+					httpClient = null;
+				}
+				else
+				{
+					numArray = File.ReadAllBytes(str3);
+					return numArray;
+				}
+			}
+			catch
+			{
+			}
+			numArray = null;
+			return numArray;
+		}
+
+		public static string EncodeBase64(this string plainText)
+		{
+			string base64String;
+			try
+			{
+				base64String = Convert.ToBase64String(Encoding.UTF8.GetBytes(plainText));
+			}
+			catch
+			{
+				return string.Empty;
+			}
+			return base64String;
+		}
+
+		internal static async Task EspacoUsadoAzureInBytes(string path = "")
+		{
+			double num;
+			Uri apiAD = Address.get_ApiAD();
+			string[] strArrays = new string[] { Gestor.Application.Helpers.Connection.AdApiV2(Gestor.Application.Helpers.Connection.ConnectionAddress.get_AzureStorage()) };
+			Uri uri = apiAD.Append(strArrays);
+			string[] strArrays1 = new string[] { "tamanho" };
+			Uri uri1 = uri.Append(strArrays1);
+			if (!string.IsNullOrEmpty(path))
+			{
+				string[] strArrays2 = new string[] { path };
+				uri1.Append(strArrays2);
+			}
+			try
+			{
+				using (HttpClient httpClient = new HttpClient())
+				{
+					ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
+					httpClient.get_DefaultRequestHeaders().Clear();
+					httpClient.get_DefaultRequestHeaders().Add("Authorization", string.Concat("Token ", Gestor.Application.Helpers.Connection.BasicKey()));
+					HttpResponseMessage async = await httpClient.GetAsync(uri1);
+					if (async.get_IsSuccessStatusCode() && async.get_StatusCode() != HttpStatusCode.NoContent)
+					{
+						num = double.Parse(await async.get_Content().ReadAsStringAsync());
+						return num;
+					}
+				}
+				httpClient = null;
+			}
+			catch
+			{
+			}
+			num = 0;
+			return num;
+		}
+
+		public static async Task Get(string command, bool autorizar = true, bool verificarConexao = false)
+		where T : class
+		{
+			Gestor.Application.Helpers.T t;
+			HttpResponseMessage httpResponseMessage;
+			Uri uri = new Uri(Address.GestorApi(), command);
+			HttpClient httpClient = new HttpClient();
+			if (autorizar)
+			{
+				httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue("Token", Gestor.Application.Helpers.Connection.BasicKey()));
+			}
+			ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+			try
+			{
+				ConfiguredTaskAwaitable configuredTaskAwaitable = httpClient.GetAsync(uri).ConfigureAwait(false);
+				httpResponseMessage = await configuredTaskAwaitable;
+			}
+			catch (Exception exception)
+			{
+				ApplicationHelper.Conectado = false;
+				t = default(Gestor.Application.Helpers.T);
+				return t;
+			}
+			if (verificarConexao)
+			{
+				ApplicationHelper.Conectado = true;
+			}
+			if (httpResponseMessage.get_StatusCode() != HttpStatusCode.NoContent)
+			{
+				if (httpResponseMessage.get_StatusCode() != HttpStatusCode.OK)
+				{
+					throw new Exception(string.Concat("Api connection Error ", Environment.NewLine, " ", command), null);
+				}
+				t = JsonConvert.DeserializeObject(httpResponseMessage.get_Content().ReadAsStringAsync().Result);
+			}
+			else
+			{
+				t = default(Gestor.Application.Helpers.T);
+			}
+			return t;
+		}
+
+		public static async Task Get(string command, bool autorizar = true)
+		{
+			HttpStatusCode statusCode;
+			HttpResponseMessage httpResponseMessage;
+			Uri uri = new Uri(Address.GestorApi(), command);
+			HttpClient httpClient = new HttpClient();
+			if (autorizar)
+			{
+				httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue("Token", Gestor.Application.Helpers.Connection.BasicKey()));
+			}
+			ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+			try
+			{
+				ConfiguredTaskAwaitable configuredTaskAwaitable = httpClient.GetAsync(uri).ConfigureAwait(false);
+				httpResponseMessage = await configuredTaskAwaitable;
+			}
+			catch (Exception exception)
+			{
+				statusCode = HttpStatusCode.InternalServerError;
+				return statusCode;
+			}
+			statusCode = httpResponseMessage.get_StatusCode();
+			return statusCode;
+		}
+
+		public static string GetAdConnection(string serial)
+		{
+			ApplicationHelper.NumeroSerial = serial;
+			if (string.IsNullOrWhiteSpace(Gestor.Application.Helpers.Connection.Server))
+			{
+				Gestor.Application.Helpers.Connection.GetAdConnection(serial);
+			}
+			return string.Concat(new string[] { "Server=", Gestor.Application.Helpers.Connection.Server, ";initial catalog=", Gestor.Application.Helpers.Connection.Catalog, "AD;user=", Gestor.Application.Helpers.Connection.User, ";password=", Gestor.Application.Helpers.Connection.Password, ";" });
+		}
+
+		public static string GetConnection(bool tryconnect = true)
+		{
+			string str;
+			string aggilizador;
+			string urlCentralSegurado;
+			try
+			{
+				Token token = new Token();
+				RegistryHelper registryHelper = new RegistryHelper(ApplicationHelper.Subkey);
+				bool usaAzureStorage = false;
+				string str1 = "ad1";
+				if (ApplicationHelper.Conectado)
+				{
+					List result = Gestor.Application.Helpers.Connection.Get>(string.Format("Server/{0}", ApplicationHelper.IdFornecedor), true, false).Result;
+					for (int i = 0; i < result.Count; i++)
+					{
+						string str2 = token.AggerEncrypt(token.Decrypt(result[i].get_Server()));
+						string str3 = token.AggerEncrypt(token.Decrypt(result[i].get_Catalog()));
+						string str4 = token.AggerEncrypt(token.Decrypt(result[i].get_User()));
+						string str5 = token.AggerEncrypt(token.Decrypt(result[i].get_Password()));
+						string str6 = token.AggerEncrypt(token.Decrypt(result[i].get_Pool()));
+						string str7 = result[i].get_Type().ToString();
+						if (string.IsNullOrEmpty(result[i].get_Aggilizador()))
+						{
+							aggilizador = null;
+						}
+						else
+						{
+							aggilizador = result[i].get_Aggilizador();
+						}
+						Gestor.Application.Helpers.Connection.LinkAggilizador = aggilizador;
+						if (string.IsNullOrEmpty(result[i].get_UrlCentralSegurado()))
+						{
+							urlCentralSegurado = null;
+						}
+						else
+						{
+							urlCentralSegurado = result[0].get_UrlCentralSegurado();
+						}
+						Gestor.Application.Helpers.Connection.UrlCentralSegurado = urlCentralSegurado;
+						usaAzureStorage = result[i].get_UsaAzureStorage();
+						str1 = (string.IsNullOrEmpty(result[i].get_AzureStorage()) ? "ad1" : token.Decrypt(result[i].get_AzureStorage()));
+						registryHelper.Write(string.Format("SERVER{0}", i + 1), str2, true);
+						registryHelper.Write(string.Format("DB{0}", i + 1), str3, true);
+						registryHelper.Write(string.Format("USER{0}", i + 1), str4, true);
+						registryHelper.Write(string.Format("PASSWORD{0}", i + 1), str5, true);
+						registryHelper.Write(string.Format("POOL{0}", i + 1), str6, true);
+						registryHelper.Write(string.Format("TYPE{0}", i + 1), str7, true);
+					}
+				}
+				string str8 = "";
+				for (int j = 0; j < 3 && registryHelper.Read(string.Format("SERVER{0}", j + 1), true) != null; j++)
+				{
+					if (registryHelper.Read(string.Format("TYPE{0}", j + 1), true) != "4")
+					{
+						Gestor.Application.Helpers.Connection.Server = token.AggerDecrypt(registryHelper.Read(string.Format("SERVER{0}", j + 1), true));
+						Gestor.Application.Helpers.Connection.Catalog = token.AggerDecrypt(registryHelper.Read(string.Format("DB{0}", j + 1), true));
+						Gestor.Application.Helpers.Connection.User = token.AggerDecrypt(registryHelper.Read(string.Format("USER{0}", j + 1), true));
+						Gestor.Application.Helpers.Connection.Password = token.AggerDecrypt(registryHelper.Read(string.Format("PASSWORD{0}", j + 1), true));
+						Gestor.Application.Helpers.Connection.Pool = token.AggerDecrypt(registryHelper.Read(string.Format("POOL{0}", j + 1), true));
+						Gestor.Application.Helpers.Connection.Type = registryHelper.Read(string.Format("TYPE{0}", j + 1), true);
+						if (!usaAzureStorage)
+						{
+							usaAzureStorage = Task.Run(async () => await Gestor.Application.Helpers.Connection.SaveInAzureStorage()).Result;
+						}
+						Gestor.Model.API.ConnectionAddress connectionAddress = new Gestor.Model.API.ConnectionAddress();
+						connectionAddress.set_Server(Gestor.Application.Helpers.Connection.Server);
+						connectionAddress.set_Catalog(Gestor.Application.Helpers.Connection.Catalog);
+						connectionAddress.set_User(Gestor.Application.Helpers.Connection.User);
+						connectionAddress.set_Password(Gestor.Application.Helpers.Connection.Password);
+						connectionAddress.set_Pool(Gestor.Application.Helpers.Connection.Pool);
+						connectionAddress.set_Aggilizador(Gestor.Application.Helpers.Connection.LinkAggilizador);
+						connectionAddress.set_UrlCentralSegurado(Gestor.Application.Helpers.Connection.UrlCentralSegurado);
+						connectionAddress.set_UsaAzureStorage(usaAzureStorage);
+						connectionAddress.set_AzureStorage(str1);
+						connectionAddress.set_Type(int.Parse((Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(Gestor.Application.Helpers.Connection.Type) ? "0" : Gestor.Application.Helpers.Connection.Type)));
+						Gestor.Application.Helpers.Connection.ConnectionAddress = connectionAddress;
+						string connectionString = Gestor.Application.Helpers.Connection.GetConnectionString();
+						if (!tryconnect || Gestor.Application.Helpers.Connection.TryConnect(connectionString, 1))
+						{
+							str8 = connectionString;
+							break;
+						}
+					}
+				}
+				str = str8;
+			}
+			catch (Exception exception)
+			{
+				str = null;
+			}
+			return str;
+		}
+
+		public static string GetConnectionString()
+		{
+			return string.Concat(new string[] { "Server=", Gestor.Application.Helpers.Connection.Server, ";initial catalog=", Gestor.Application.Helpers.Connection.Catalog, ";user=", Gestor.Application.Helpers.Connection.User, ";password=", Gestor.Application.Helpers.Connection.Password, ";" });
+		}
+
+		public static async Task GetPool()
+		{
+			string pool;
+			Gestor.Model.API.ConnectionAddress connectionAddress = await Gestor.Application.Helpers.Connection.Get("Server/Pool", true, false);
+			if (connectionAddress != null)
+			{
+				Gestor.Application.Helpers.Connection.Pool = (new Token()).Decrypt(connectionAddress.get_Pool());
+				pool = Gestor.Application.Helpers.Connection.Pool;
+			}
+			else
+			{
+				pool = "";
+			}
+			return pool;
+		}
+
+		public static async Task Post(string command, T keyValues)
+		where T : class
+		{
+			Gestor.Application.Helpers.T t;
+			Uri uri = new Uri(Address.GestorApi(), command);
+			object obj = keyValues;
+			JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings();
+			jsonSerializerSetting.set_ReferenceLoopHandling(1);
+			jsonSerializerSetting.set_MissingMemberHandling(0);
+			StringContent stringContent = new StringContent(JsonConvert.SerializeObject(obj, 1, jsonSerializerSetting), Encoding.UTF8, "application/json");
+			HttpClient httpClient = new HttpClient();
+			httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue("Token", Gestor.Application.Helpers.Connection.BasicKey()));
+			ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+			HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(uri, stringContent);
+			if (httpResponseMessage.get_StatusCode() != HttpStatusCode.NoContent)
+			{
+				if (httpResponseMessage.get_StatusCode() != HttpStatusCode.OK)
+				{
+					throw new Exception(string.Concat("Api connection Error ", Environment.NewLine, " ", command), null);
+				}
+				t = JsonConvert.DeserializeObject(httpResponseMessage.get_Content().ReadAsStringAsync().Result);
+			}
+			else
+			{
+				t = default(Gestor.Application.Helpers.T);
+			}
+			return t;
+		}
+
+		public static async Task Post(string command, object keyValues)
+		where T : class
+		{
+			Gestor.Application.Helpers.T t;
+			Uri uri = new Uri(Address.GestorApi(), command);
+			object obj = keyValues;
+			JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings();
+			jsonSerializerSetting.set_ReferenceLoopHandling(1);
+			jsonSerializerSetting.set_MissingMemberHandling(0);
+			StringContent stringContent = new StringContent(JsonConvert.SerializeObject(obj, 1, jsonSerializerSetting), Encoding.UTF8, "application/json");
+			HttpClient httpClient = new HttpClient();
+			httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue("Token", Gestor.Application.Helpers.Connection.BasicKey()));
+			ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+			HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(uri, stringContent);
+			if (httpResponseMessage.get_StatusCode() != HttpStatusCode.NoContent)
+			{
+				if (httpResponseMessage.get_StatusCode() != HttpStatusCode.OK)
+				{
+					throw new Exception(string.Concat("Api connection Error ", Environment.NewLine, " ", command), null);
+				}
+				t = JsonConvert.DeserializeObject(httpResponseMessage.get_Content().ReadAsStringAsync().Result);
+			}
+			else
+			{
+				t = default(Gestor.Application.Helpers.T);
+			}
+			return t;
+		}
+
+		public static async Task Put(string command, T keyValues)
+		where T : class
+		{
+			Uri uri = new Uri(Address.GestorApi(), command);
+			object obj = keyValues;
+			JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings();
+			jsonSerializerSetting.set_ReferenceLoopHandling(1);
+			StringContent stringContent = new StringContent(JsonConvert.SerializeObject(obj, 1, jsonSerializerSetting), Encoding.UTF8, "application/json");
+			HttpClient httpClient = new HttpClient();
+			ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+			httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue("Token", Gestor.Application.Helpers.Connection.BasicKey()));
+			HttpResponseMessage httpResponseMessage = await httpClient.PutAsync(uri, stringContent);
+			if (httpResponseMessage.get_StatusCode() != HttpStatusCode.OK)
+			{
+				throw new Exception(string.Concat("Api connection Error ", Environment.NewLine, " ", command), null);
+			}
+			Gestor.Application.Helpers.T t = JsonConvert.DeserializeObject(httpResponseMessage.get_Content().ReadAsStringAsync().Result);
+			return t;
+		}
+
+		public static async Task Put(string command, object keyValues)
+		where T : class
+		{
+			Gestor.Application.Helpers.T t;
+			Uri uri = new Uri(Address.GestorApi(), command);
+			object obj = keyValues;
+			JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings();
+			jsonSerializerSetting.set_ReferenceLoopHandling(1);
+			StringContent stringContent = new StringContent(JsonConvert.SerializeObject(obj, 1, jsonSerializerSetting), Encoding.UTF8, "application/json");
+			HttpClient httpClient = new HttpClient();
+			ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+			httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue("Token", Gestor.Application.Helpers.Connection.BasicKey()));
+			HttpResponseMessage httpResponseMessage = await httpClient.PutAsync(uri, stringContent);
+			if (httpResponseMessage.get_StatusCode() != HttpStatusCode.NoContent)
+			{
+				if (httpResponseMessage.get_StatusCode() != HttpStatusCode.OK)
+				{
+					throw new Exception(string.Concat("Api connection Error ", Environment.NewLine, " ", command), null);
+				}
+				t = JsonConvert.DeserializeObject(httpResponseMessage.get_Content().ReadAsStringAsync().Result);
+			}
+			else
+			{
+				t = default(Gestor.Application.Helpers.T);
+			}
+			return t;
+		}
+
+		public static async void PutError(T keyValues)
+		where T : class
+		{
+			Uri uri = new Uri(Address.GestorApi(), "Error/Objeto");
+			object obj = keyValues;
+			JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings();
+			jsonSerializerSetting.set_ReferenceLoopHandling(1);
+			StringContent stringContent = new StringContent(JsonConvert.SerializeObject(obj, 1, jsonSerializerSetting), Encoding.UTF8, "application/json");
+			HttpClient httpClient = new HttpClient();
+			ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+			httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue("Token", Gestor.Application.Helpers.Connection.BasicKey()));
+			if (await httpClient.PutAsync(uri, stringContent).get_StatusCode() != HttpStatusCode.NoContent)
+			{
+				throw new Exception(string.Concat("Api connection Error ", Environment.NewLine, " Error"), null);
+			}
+		}
+
+		internal static async Task SaveInAzureStorage()
+		{
+			bool flag;
+			string str = string.Format("{0}Data", Address.GestorApi());
+			try
+			{
+				using (HttpClient httpClient = new HttpClient())
+				{
+					httpClient.get_DefaultRequestHeaders().Clear();
+					httpClient.get_DefaultRequestHeaders().Add("Authorization", string.Concat("Token ", Gestor.Application.Helpers.Connection.BasicKey()));
+					HttpResponseMessage async = await httpClient.GetAsync(str);
+					if (async.get_IsSuccessStatusCode())
+					{
+						flag = await async.get_Content().ReadAsStringAsync() == "true";
+						return flag;
+					}
+				}
+				httpClient = null;
+			}
+			catch
+			{
+			}
+			flag = false;
+			return flag;
+		}
+
+		internal static bool TryConnect(string connectionString, int retryCount = 1)
+		{
+			bool flag;
+			List exceptions = new List();
+			int num = 0;
+		Label1:
+			while (num < retryCount)
+			{
+				try
+				{
+					using (SqlConnection sqlConnection = new SqlConnection(connectionString))
+					{
+						sqlConnection.Open();
+					}
+					flag = true;
+				}
+				catch (Exception exception)
+				{
+					exceptions.Add(exception);
+					goto Label0;
+				}
+				return flag;
+			}
+			return exceptions.Count == 0;
+		Label0:
+			num++;
+			goto Label1;
+		}
+
+		internal static async Task UploadFile(UploadFile upload, string path = "ad")
+		{
+			bool flag;
+			bool flag1;
+			Uri apiAD = Address.get_ApiAD();
+			string[] strArrays = new string[] { Gestor.Application.Helpers.Connection.AdApiV2(Gestor.Application.Helpers.Connection.ConnectionAddress.get_AzureStorage()) };
+			Uri uri = apiAD.Append(strArrays);
+			string[] strArrays1 = new string[] { path };
+			Uri uri1 = uri.Append(strArrays1);
+			try
+			{
+				using (HttpClient httpClient = new HttpClient())
+				{
+					ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
+					httpClient.get_DefaultRequestHeaders().Clear();
+					httpClient.get_DefaultRequestHeaders().Add("Authorization", string.Concat("Token ", Gestor.Application.Helpers.Connection.BasicKey()));
+					HttpResponseMessage httpResponseMessage = await httpClient.PutAsync(uri1, new StringContent(JsonConvert.SerializeObject(upload), Encoding.UTF8, "application/json"));
+					flag1 = (!httpResponseMessage.get_IsSuccessStatusCode() ? false : httpResponseMessage.get_StatusCode() != HttpStatusCode.NoContent);
+					flag = flag1;
+					return flag;
+				}
+			}
+			catch
+			{
+			}
+			flag = false;
+			return flag;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Helpers/ConnectionHelper.cs b/Codemerx/Gestor.Application/Helpers/ConnectionHelper.cs
new file mode 100644
index 0000000..1b364ca
--- /dev/null
+++ b/Codemerx/Gestor.Application/Helpers/ConnectionHelper.cs
@@ -0,0 +1,521 @@
+using Agger.Registro;
+using Gestor.Application.Migration;
+using Gestor.Common.Exceptions;
+using Gestor.Model.API;
+using System;
+using System.Collections.Generic;
+using System.Data.SqlClient;
+using System.Diagnostics;
+using System.IO;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Runtime.CompilerServices;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace Gestor.Application.Helpers
+{
+	public class ConnectionHelper
+	{
+		public static bool BancoAtualizado
+		{
+			get;
+			set;
+		}
+
+		public ConnectionHelper()
+		{
+		}
+
+		public async Task AtualizarBanco()
+		{
+			string str;
+			bool flag = await (new Migrator()).Execute();
+			ConnectionHelper.BancoAtualizado = flag;
+			if (flag)
+			{
+				str = null;
+			}
+			else
+			{
+				str = "HOUVE UM PROBLEMA AO ATUALIZAR O BANCO DE DADOS.";
+			}
+			return str;
+		}
+
+		public bool BDConvertido()
+		{
+			bool flag;
+			try
+			{
+				using (SqlConnection sqlConnection = new SqlConnection(Gestor.Application.Helpers.Connection.GetConnection(false)))
+				{
+					sqlConnection.Open();
+					using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
+					{
+						sqlCommand.CommandText = "SELECT OBJECT_ID('dbo.AtualizacaoDados', 'U')";
+						if (sqlCommand.ExecuteScalar() == DBNull.Value)
+						{
+							flag = true;
+							return flag;
+						}
+					}
+					using (SqlCommand sqlCommand1 = sqlConnection.CreateCommand())
+					{
+						sqlCommand1.CommandText = "SELECT COUNT(IdArquivo) FROM AtualizacaoDados";
+						flag = (int)sqlCommand1.ExecuteScalar() == 0;
+					}
+				}
+			}
+			catch
+			{
+				return true;
+			}
+			return flag;
+		}
+
+		public static async Task CheckDatabase()
+		{
+			string message;
+			string str;
+			try
+			{
+				bool flag = await ConnectionHelper.DatabaseExists();
+				bool flag1 = await ConnectionHelper.LoginExists();
+				bool flag2 = await ConnectionHelper.UserExists();
+				bool flag3 = false;
+				if (!(flag & flag1 & flag2))
+				{
+					if (!flag)
+					{
+						flag = await ConnectionHelper.CreateDatabase();
+					}
+					if (flag)
+					{
+						if (!flag1)
+						{
+							bool flag4 = await ConnectionHelper.CreateLogin();
+							bool flag5 = flag4;
+							flag3 = flag4;
+							flag1 = flag5;
+						}
+						if (flag1)
+						{
+							if (!flag2)
+							{
+								flag2 = await ConnectionHelper.CreateUser();
+							}
+							if (flag3)
+							{
+								int num = 10;
+								while (num > 1)
+								{
+									try
+									{
+										using (SqlConnection sqlConnection = new SqlConnection(Gestor.Application.Helpers.Connection.GetConnection(true)))
+										{
+											sqlConnection.Open();
+											break;
+										}
+									}
+									catch
+									{
+										Thread.Sleep(10000);
+										num--;
+									}
+								}
+							}
+							if (!flag2)
+							{
+								str = "ERRO AO CRIAR USUÁRIO";
+							}
+							else
+							{
+								str = null;
+							}
+							message = str;
+						}
+						else
+						{
+							message = "ERRO AO CRIAR LOGIN";
+						}
+					}
+					else
+					{
+						message = "ERRO AO CRIAR BANCO DE DADOS";
+					}
+				}
+				else
+				{
+					message = null;
+				}
+			}
+			catch (ValidationException validationException)
+			{
+				message = validationException.Message;
+			}
+			catch (Exception exception)
+			{
+				message = "ERRO AO CRIAR BANCO DE DADOS";
+			}
+			return message;
+		}
+
+		private static async Task CreateDatabase()
+		{
+			bool flag;
+			bool i;
+			string str = Uri.EscapeDataString(ApplicationHelper.NumeroSerial);
+			if (await ConnectionHelper.Post(string.Concat("Data/CreateData?token=", str)) != "ERRO INTERNO")
+			{
+				int num = 0;
+				for (i = false; num < 24 && !i; i = await ConnectionHelper.DatabaseExists())
+				{
+					await Task.Delay(5000);
+					num++;
+				}
+				flag = i;
+			}
+			else
+			{
+				flag = false;
+			}
+			return flag;
+		}
+
+		private static async Task CreateLogin()
+		{
+			bool flag;
+			bool i;
+			if (await ConnectionHelper.Post("Data/CreateLogin") != "ERRO INTERNO")
+			{
+				int num = 0;
+				for (i = false; num < 24 && !i; i = await ConnectionHelper.Get("Data/ServerLoginExists", true) == null)
+				{
+					await Task.Delay(5000);
+					num++;
+				}
+				flag = i;
+			}
+			else
+			{
+				flag = false;
+			}
+			return flag;
+		}
+
+		private static async Task CreateUser()
+		{
+			bool flag;
+			bool i;
+			if (await ConnectionHelper.Post("Data/CreateUser") != "ERRO INTERNO")
+			{
+				int num = 0;
+				for (i = false; num < 24 && !i; i = await ConnectionHelper.Get("Data/UserExists", true) == null)
+				{
+					await Task.Delay(5000);
+					num++;
+				}
+				flag = i;
+			}
+			else
+			{
+				flag = false;
+			}
+			return flag;
+		}
+
+		private static async Task DatabaseExists()
+		{
+			return await ConnectionHelper.Get("Data/DataExists", true) == null;
+		}
+
+		private static async Task DatabaseTest()
+		{
+			return await ConnectionHelper.Get("Data/Verify", true);
+		}
+
+		public bool ExisteEmpresa()
+		{
+			bool flag;
+			try
+			{
+				using (SqlConnection sqlConnection = new SqlConnection(Gestor.Application.Helpers.Connection.GetConnection(false)))
+				{
+					sqlConnection.Open();
+					using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
+					{
+						sqlCommand.CommandText = "SELECT OBJECT_ID (N'empresa', N'U')";
+						if (sqlCommand.ExecuteScalar() == DBNull.Value)
+						{
+							flag = false;
+							return flag;
+						}
+					}
+					using (SqlCommand sqlCommand1 = sqlConnection.CreateCommand())
+					{
+						sqlCommand1.CommandText = "SELECT COUNT(idempresa) FROM empresa WHERE idempresa = 1";
+						flag = (int)sqlCommand1.ExecuteScalar() > 0;
+					}
+				}
+			}
+			catch
+			{
+				return true;
+			}
+			return flag;
+		}
+
+		private static async Task Get(string command, bool autorizar = true)
+		{
+			string str;
+			Uri uri = new Uri(Address.GestorApi(), command);
+			HttpClient httpClient = new HttpClient();
+			httpClient.set_Timeout(new TimeSpan(0, 2, 0));
+			HttpClient httpClient1 = httpClient;
+			if (autorizar)
+			{
+				httpClient1.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue("Token", Gestor.Application.Helpers.Connection.BasicKey()));
+			}
+			ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+			try
+			{
+				ConfiguredTaskAwaitable configuredTaskAwaitable = httpClient1.GetAsync(uri).ConfigureAwait(false);
+				HttpResponseMessage httpResponseMessage = await configuredTaskAwaitable;
+				if (httpResponseMessage.get_StatusCode() == HttpStatusCode.OK)
+				{
+					str = null;
+				}
+				else
+				{
+					str = await httpResponseMessage.get_Content().ReadAsStringAsync();
+				}
+			}
+			catch (Exception exception)
+			{
+				str = "ERRO INTERNO";
+			}
+			return str;
+		}
+
+		internal static async Task HasLogin(string connectionString)
+		{
+			bool flag1 = await Task.Run(() => {
+				bool flag;
+				List exceptions = new List();
+				try
+				{
+					using (SqlConnection sqlConnection = new SqlConnection(connectionString))
+					{
+						sqlConnection.Open();
+						using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
+						{
+							sqlCommand.CommandText = "SELECT 1 FROM [dbo].[usuario] WHERE [removido] IS NULL OR [removido] = '0'";
+							SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
+							if (sqlDataReader.HasRows)
+							{
+								sqlDataReader.Close();
+								sqlCommand.CommandText = "SELECT 1 FROM [dbo].[empresa] WHERE [idempresa] = 1";
+								sqlDataReader = sqlCommand.ExecuteReader();
+								if (sqlDataReader.HasRows)
+								{
+									sqlDataReader.Close();
+									sqlCommand.CommandText = "SELECT 1 FROM [dbo].[vendedor] WHERE [corretora] = '1'";
+									sqlDataReader = sqlCommand.ExecuteReader();
+									if (sqlDataReader.HasRows)
+									{
+										sqlDataReader.Close();
+										flag = true;
+									}
+									else
+									{
+										flag = false;
+									}
+								}
+								else
+								{
+									flag = false;
+								}
+							}
+							else
+							{
+								flag = false;
+							}
+						}
+					}
+				}
+				catch (Exception exception)
+				{
+					exceptions.Add(exception);
+					return exceptions.Count == 0;
+				}
+				return flag;
+			});
+			return flag1;
+		}
+
+		private static async Task LoginExists()
+		{
+			return await ConnectionHelper.Get("Data/ServerLoginExists", true) == null;
+		}
+
+		private static async Task Post(string command)
+		{
+			string str;
+			Uri uri = new Uri(Address.GestorApi(), command);
+			HttpClient httpClient = new HttpClient();
+			httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue("Token", Gestor.Application.Helpers.Connection.BasicKey()));
+			ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+			try
+			{
+				HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(uri, null);
+				if (httpResponseMessage.get_StatusCode() == HttpStatusCode.OK)
+				{
+					str = null;
+				}
+				else
+				{
+					str = await httpResponseMessage.get_Content().ReadAsStringAsync();
+				}
+			}
+			catch (Exception exception)
+			{
+				str = "ERRO INTERNO";
+			}
+			return str;
+		}
+
+		public async Task> PrimeiroAcesso()
+		{
+			Tuple tuple;
+			Tuple tuple1;
+			string connection = Gestor.Application.Helpers.Connection.GetConnection(false);
+			if (!await ConnectionHelper.TryConnect(connection, 1))
+			{
+				if (await ConnectionHelper.DatabaseExists())
+				{
+					bool flag = !await ConnectionHelper.LoginExists();
+					if (flag)
+					{
+						flag = !await ConnectionHelper.CreateLogin();
+					}
+					if (!flag)
+					{
+						flag = !await ConnectionHelper.UserExists();
+						if (flag)
+						{
+							flag = !await ConnectionHelper.CreateUser();
+						}
+						if (flag)
+						{
+							tuple = new Tuple(false, false);
+							connection = null;
+							return tuple;
+						}
+					}
+					else
+					{
+						tuple = new Tuple(false, false);
+						connection = null;
+						return tuple;
+					}
+				}
+				else
+				{
+					tuple = new Tuple(false, false);
+					connection = null;
+					return tuple;
+				}
+			}
+			tuple1 = (!await ConnectionHelper.HasLogin(connection) ? new Tuple(true, false) : new Tuple(true, true));
+			tuple = tuple1;
+			connection = null;
+			return tuple;
+		}
+
+		internal static async Task TryConnect(string connectionString, int retryCount = 1)
+		{
+			bool flag1 = await Task.Run(() => {
+				bool flag;
+				List exceptions = new List();
+				int num = 0;
+			Label1:
+				while (num < retryCount)
+				{
+					try
+					{
+						using (SqlConnection sqlConnection = new SqlConnection(string.Concat(connectionString, "Connection Timeout=5")))
+						{
+							sqlConnection.Open();
+						}
+						flag = true;
+					}
+					catch (Exception exception)
+					{
+						exceptions.Add(exception);
+						goto Label0;
+					}
+					return flag;
+				}
+				return exceptions.Count == 0;
+			Label0:
+				num++;
+				goto Label1;
+			});
+			return flag1;
+		}
+
+		private static async Task UserExists()
+		{
+			return await ConnectionHelper.Get("Data/UserExists", true) == null;
+		}
+
+		public async Task VerifyConnection()
+		{
+			string str;
+			try
+			{
+				if (!await ConnectionHelper.TryConnect(Gestor.Application.Helpers.Connection.GetConnection(false), 1))
+				{
+					string str1 = await ConnectionHelper.DatabaseTest();
+					if (str1 == null)
+					{
+						string str2 = string.Concat(Gestor.Application.Helpers.Connection.ConnectionAddress.get_Catalog(), ".cfg");
+						string str3 = string.Concat(AppDomain.CurrentDomain.BaseDirectory, "Data_", str2);
+						string str4 = string.Concat(AppDomain.CurrentDomain.BaseDirectory, "Files_", str2);
+						string str5 = string.Concat(AppDomain.CurrentDomain.BaseDirectory, "Sign_", str2);
+						if (File.Exists(str3))
+						{
+							File.Delete(str3);
+						}
+						if (File.Exists(str4))
+						{
+							File.Delete(str4);
+						}
+						if (File.Exists(str5))
+						{
+							File.Delete(str5);
+						}
+						string str6 = await ConnectionHelper.CheckDatabase();
+						await Task.Delay(2000);
+						str = str6;
+					}
+					else
+					{
+						str = str1;
+					}
+				}
+				else
+				{
+					str = null;
+				}
+			}
+			catch (Exception exception)
+			{
+				str = "ERRO AO CONECTAR NO BANCO DE DADOS DA CORRETORA";
+			}
+			return str;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Helpers/CustomLinq.cs b/Codemerx/Gestor.Application/Helpers/CustomLinq.cs
new file mode 100644
index 0000000..2900b2e
--- /dev/null
+++ b/Codemerx/Gestor.Application/Helpers/CustomLinq.cs
@@ -0,0 +1,421 @@
+using Gestor.Common.Validation;
+using Gestor.Model.Domain.Relatorios;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Reflection;
+using System.Runtime.CompilerServices;
+
+namespace Gestor.Application.Helpers
+{
+	public static class CustomLinq
+	{
+		public static List CustomNot(this List list, List property)
+		where T : class
+		{
+			if (property == null || property.Count == 0)
+			{
+				return list;
+			}
+			return list.Where((T x) => {
+				Func func8 = null;
+				Func func9 = null;
+				Func func10 = null;
+				Func func11 = null;
+				Func func12 = null;
+				Func func13 = null;
+				Func func14 = null;
+				List filtroPersonalizados = property;
+				Func u003cu003e9_21 = CustomLinq.u003cu003ec__2.u003cu003e9__2_1;
+				if (u003cu003e9_21 == null)
+				{
+					u003cu003e9_21 = (FiltroPersonalizado p) => p.get_Propriedade();
+					CustomLinq.u003cu003ec__2.u003cu003e9__2_1 = u003cu003e9_21;
+				}
+				return filtroPersonalizados.GroupBy(u003cu003e9_21).ToList>().All>((IGrouping p) => {
+					Func func;
+					IGrouping strs = p;
+					Func u003cu003e9_23 = CustomLinq.u003cu003ec__2.u003cu003e9__2_3;
+					if (u003cu003e9_23 == null)
+					{
+						u003cu003e9_23 = (FiltroPersonalizado s) => s.get_SemValor();
+						CustomLinq.u003cu003ec__2.u003cu003e9__2_3 = u003cu003e9_23;
+					}
+					if (strs.Any(u003cu003e9_23))
+					{
+						IGrouping strs1 = p;
+						Func u003cu003e9_4 = func8;
+						if (u003cu003e9_4 == null)
+						{
+							Func func1 = (FiltroPersonalizado v) => {
+								bool value;
+								string str;
+								PropertyInfo propertyInfo1 = typeof(T).GetProperty(v.get_Propriedade());
+								value = (propertyInfo1 != null ? propertyInfo1.GetValue(x) : false);
+								if (!value)
+								{
+									return true;
+								}
+								PropertyInfo propertyInfo = typeof(T).GetProperty(v.get_Propriedade());
+								str = (propertyInfo != null ? propertyInfo.GetValue(x).ToString() : null);
+								return string.IsNullOrWhiteSpace(str);
+							};
+							func = func1;
+							func8 = func1;
+							u003cu003e9_4 = func;
+						}
+						return strs1.All(u003cu003e9_4);
+					}
+					if (p.First().get_Tipo() == typeof(DateTime))
+					{
+						IGrouping strs2 = p;
+						Func u003cu003e9_5 = func9;
+						if (u003cu003e9_5 == null)
+						{
+							Func func2 = (FiltroPersonalizado v) => {
+								bool value;
+								PropertyInfo propertyInfo2 = typeof(T).GetProperty(v.get_Propriedade());
+								value = (propertyInfo2 != null ? propertyInfo2.GetValue(x) : false);
+								if (!value)
+								{
+									return false;
+								}
+								return (DateTime)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x) != DateTime.Parse(v.get_ValorIncial());
+							};
+							func = func2;
+							func9 = func2;
+							u003cu003e9_5 = func;
+						}
+						return strs2.All(u003cu003e9_5);
+					}
+					if (p.First().get_Tipo() == typeof(long))
+					{
+						IGrouping strs3 = p;
+						Func u003cu003e9_6 = func10;
+						if (u003cu003e9_6 == null)
+						{
+							Func func3 = (FiltroPersonalizado v) => {
+								bool value;
+								PropertyInfo propertyInfo3 = typeof(T).GetProperty(v.get_Propriedade());
+								value = (propertyInfo3 != null ? propertyInfo3.GetValue(x) : false);
+								if (!value)
+								{
+									return false;
+								}
+								return (long)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x) != long.Parse(v.get_ValorIncial());
+							};
+							func = func3;
+							func10 = func3;
+							u003cu003e9_6 = func;
+						}
+						return strs3.All(u003cu003e9_6);
+					}
+					if (p.First().get_Tipo() == typeof(int))
+					{
+						IGrouping strs4 = p;
+						Func u003cu003e9_7 = func11;
+						if (u003cu003e9_7 == null)
+						{
+							Func func4 = (FiltroPersonalizado v) => {
+								bool value;
+								PropertyInfo propertyInfo4 = typeof(T).GetProperty(v.get_Propriedade());
+								value = (propertyInfo4 != null ? propertyInfo4.GetValue(x) : false);
+								if (!value)
+								{
+									return false;
+								}
+								return (int)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x) != int.Parse(v.get_ValorIncial());
+							};
+							func = func4;
+							func11 = func4;
+							u003cu003e9_7 = func;
+						}
+						return strs4.All(u003cu003e9_7);
+					}
+					if (p.First().get_Tipo() == typeof(decimal))
+					{
+						IGrouping strs5 = p;
+						Func u003cu003e9_8 = func12;
+						if (u003cu003e9_8 == null)
+						{
+							Func func5 = (FiltroPersonalizado v) => {
+								bool value;
+								PropertyInfo propertyInfo5 = typeof(T).GetProperty(v.get_Propriedade());
+								value = (propertyInfo5 != null ? propertyInfo5.GetValue(x) : false);
+								if (!value)
+								{
+									return false;
+								}
+								return (decimal)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x) != decimal.Parse(v.get_ValorIncial());
+							};
+							func = func5;
+							func12 = func5;
+							u003cu003e9_8 = func;
+						}
+						return strs5.All(u003cu003e9_8);
+					}
+					if (p.First().get_Tipo() != typeof(Enum))
+					{
+						IGrouping strs6 = p;
+						Func u003cu003e9_10 = func14;
+						if (u003cu003e9_10 == null)
+						{
+							Func func6 = (FiltroPersonalizado v) => {
+								bool value;
+								PropertyInfo propertyInfo6 = typeof(T).GetProperty(v.get_Propriedade());
+								value = (propertyInfo6 != null ? propertyInfo6.GetValue(x) : false);
+								if (!value)
+								{
+									return false;
+								}
+								return !ValidationHelper.AlphanumericAndSpace(typeof(T).GetProperty(v.get_Propriedade()).GetValue(x).ToString().ToLower().Trim()).Contains(ValidationHelper.AlphanumericAndSpace(v.get_ValorIncial().ToLower().Trim()));
+							};
+							func = func6;
+							func14 = func6;
+							u003cu003e9_10 = func;
+						}
+						return strs6.All(u003cu003e9_10);
+					}
+					IGrouping strs7 = p;
+					Func u003cu003e9_9 = func13;
+					if (u003cu003e9_9 == null)
+					{
+						Func func7 = (FiltroPersonalizado v) => {
+							bool value;
+							PropertyInfo propertyInfo7 = typeof(T).GetProperty(v.get_Propriedade());
+							value = (propertyInfo7 != null ? propertyInfo7.GetValue(x) : false);
+							if (!value)
+							{
+								return false;
+							}
+							return !ValidationHelper.GetDescription((Enum)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x)).ToLower().Contains(v.get_ValorIncial().ToLower());
+						};
+						func = func7;
+						func13 = func7;
+						u003cu003e9_9 = func;
+					}
+					return strs7.All(u003cu003e9_9);
+				});
+			}).ToList();
+		}
+
+		public static List CustomWhere(this List list, string propertyName, string query)
+		where T : class
+		{
+			PropertyInfo property = typeof(T).GetProperty(propertyName);
+			return (
+				from  in list
+				where property.GetValue(x).ToString().ToLower().Contains(query.ToLower())
+				select ).ToList();
+		}
+
+		public static List CustomWhere(this List list, List property, bool buscaIgual = false)
+		where T : class
+		{
+			if (property == null || property.Count == 0)
+			{
+				return list;
+			}
+			return list.Where((T x) => {
+				Func func7 = null;
+				Func func8 = null;
+				Func func9 = null;
+				Func func10 = null;
+				Func func11 = null;
+				Func func12 = null;
+				Func func13 = null;
+				List filtroPersonalizados = property;
+				Func u003cu003e9_11 = CustomLinq.u003cu003ec__1.u003cu003e9__1_1;
+				if (u003cu003e9_11 == null)
+				{
+					u003cu003e9_11 = (FiltroPersonalizado p) => p.get_Propriedade();
+					CustomLinq.u003cu003ec__1.u003cu003e9__1_1 = u003cu003e9_11;
+				}
+				return filtroPersonalizados.GroupBy(u003cu003e9_11).ToList>().All>((IGrouping p) => {
+					Func func;
+					IGrouping strs = p;
+					Func u003cu003e9_13 = CustomLinq.u003cu003ec__1.u003cu003e9__1_3;
+					if (u003cu003e9_13 == null)
+					{
+						u003cu003e9_13 = (FiltroPersonalizado s) => s.get_SemValor();
+						CustomLinq.u003cu003ec__1.u003cu003e9__1_3 = u003cu003e9_13;
+					}
+					if (strs.Any(u003cu003e9_13))
+					{
+						IGrouping strs1 = p;
+						Func u003cu003e9_4 = func7;
+						if (u003cu003e9_4 == null)
+						{
+							Func func1 = (FiltroPersonalizado v) => {
+								bool value;
+								string str;
+								string str1;
+								PropertyInfo propertyInfo1 = typeof(T).GetProperty(v.get_Propriedade());
+								value = (propertyInfo1 != null ? propertyInfo1.GetValue(x) : false);
+								if (value)
+								{
+									PropertyInfo propertyInfo = typeof(T).GetProperty(v.get_Propriedade());
+									str = (propertyInfo != null ? propertyInfo.GetValue(x).ToString() : null);
+									if (!string.IsNullOrWhiteSpace(str))
+									{
+										PropertyInfo property1 = typeof(T).GetProperty(v.get_Propriedade());
+										str1 = (property1 != null ? property1.GetValue(x).ToString() : null);
+										return string.IsNullOrEmpty(str1);
+									}
+								}
+								return true;
+							};
+							func = func1;
+							func7 = func1;
+							u003cu003e9_4 = func;
+						}
+						return strs1.Any(u003cu003e9_4);
+					}
+					if (p.First().get_Tipo() == typeof(DateTime))
+					{
+						IGrouping strs2 = p;
+						Func u003cu003e9_5 = func8;
+						if (u003cu003e9_5 == null)
+						{
+							Func func2 = (FiltroPersonalizado v) => {
+								bool value;
+								PropertyInfo propertyInfo2 = typeof(T).GetProperty(v.get_Propriedade());
+								value = (propertyInfo2 != null ? propertyInfo2.GetValue(x) : false);
+								if (!value || !((DateTime)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x) >= DateTime.Parse(v.get_ValorIncial())))
+								{
+									return false;
+								}
+								DateTime dateTime = (DateTime)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x);
+								DateTime dateTime1 = DateTime.Parse(v.get_ValorFinal());
+								dateTime1 = dateTime1.AddDays(1);
+								return dateTime <= dateTime1.AddSeconds(-1);
+							};
+							func = func2;
+							func8 = func2;
+							u003cu003e9_5 = func;
+						}
+						return strs2.Any(u003cu003e9_5);
+					}
+					if (p.First().get_Tipo() == typeof(long))
+					{
+						IGrouping strs3 = p;
+						Func u003cu003e9_6 = func9;
+						if (u003cu003e9_6 == null)
+						{
+							Func func3 = (FiltroPersonalizado v) => {
+								bool value;
+								PropertyInfo propertyInfo3 = typeof(T).GetProperty(v.get_Propriedade());
+								value = (propertyInfo3 != null ? propertyInfo3.GetValue(x) : false);
+								if (!value || (long)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x) < long.Parse(v.get_ValorIncial()))
+								{
+									return false;
+								}
+								return (long)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x) <= long.Parse(v.get_ValorFinal());
+							};
+							func = func3;
+							func9 = func3;
+							u003cu003e9_6 = func;
+						}
+						return strs3.Any(u003cu003e9_6);
+					}
+					if (p.First().get_Tipo() == typeof(int))
+					{
+						IGrouping strs4 = p;
+						Func u003cu003e9_7 = func10;
+						if (u003cu003e9_7 == null)
+						{
+							Func func4 = (FiltroPersonalizado v) => {
+								bool value;
+								PropertyInfo propertyInfo4 = typeof(T).GetProperty(v.get_Propriedade());
+								value = (propertyInfo4 != null ? propertyInfo4.GetValue(x) : false);
+								if (!value || (int)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x) < int.Parse(v.get_ValorIncial()))
+								{
+									return false;
+								}
+								return (int)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x) <= int.Parse(v.get_ValorFinal());
+							};
+							func = func4;
+							func10 = func4;
+							u003cu003e9_7 = func;
+						}
+						return strs4.Any(u003cu003e9_7);
+					}
+					if (p.First().get_Tipo() == typeof(decimal))
+					{
+						IGrouping strs5 = p;
+						Func u003cu003e9_8 = func11;
+						if (u003cu003e9_8 == null)
+						{
+							Func func5 = (FiltroPersonalizado v) => {
+								bool value;
+								PropertyInfo propertyInfo5 = typeof(T).GetProperty(v.get_Propriedade());
+								value = (propertyInfo5 != null ? propertyInfo5.GetValue(x) : false);
+								if (!value || !((decimal)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x) >= decimal.Parse(v.get_ValorIncial())))
+								{
+									return false;
+								}
+								return (decimal)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x) <= decimal.Parse(v.get_ValorFinal());
+							};
+							func = func5;
+							func11 = func5;
+							u003cu003e9_8 = func;
+						}
+						return strs5.Any(u003cu003e9_8);
+					}
+					if (p.First().get_Tipo() != typeof(Enum))
+					{
+						IGrouping strs6 = p;
+						Func u003cu003e9_10 = func13;
+						if (u003cu003e9_10 == null)
+						{
+							Func cSu0024u003cu003e8_locals1 = (FiltroPersonalizado v) => {
+								bool value;
+								bool flag;
+								if (!buscaIgual)
+								{
+									PropertyInfo propertyInfo6 = typeof(T).GetProperty(v.get_Propriedade());
+									flag = (propertyInfo6 != null ? propertyInfo6.GetValue(x) : false);
+									if (!flag)
+									{
+										return false;
+									}
+									return ValidationHelper.AlphanumericAndSpace(typeof(T).GetProperty(v.get_Propriedade()).GetValue(x).ToString().ToLower().Trim()).Contains(ValidationHelper.AlphanumericAndSpace(v.get_ValorIncial().ToLower().Trim()));
+								}
+								PropertyInfo propertyInfo = typeof(T).GetProperty(v.get_Propriedade());
+								value = (propertyInfo != null ? propertyInfo.GetValue(x) : false);
+								if (!value)
+								{
+									return false;
+								}
+								return ValidationHelper.AlphanumericAndSpace(typeof(T).GetProperty(v.get_Propriedade()).GetValue(x).ToString().ToLower().Trim()).Equals(ValidationHelper.AlphanumericAndSpace(v.get_ValorIncial().ToLower().Trim()));
+							};
+							func = cSu0024u003cu003e8_locals1;
+							func13 = cSu0024u003cu003e8_locals1;
+							u003cu003e9_10 = func;
+						}
+						return strs6.Any(u003cu003e9_10);
+					}
+					IGrouping strs7 = p;
+					Func u003cu003e9_9 = func12;
+					if (u003cu003e9_9 == null)
+					{
+						Func func6 = (FiltroPersonalizado v) => {
+							bool value;
+							PropertyInfo propertyInfo7 = typeof(T).GetProperty(v.get_Propriedade());
+							value = (propertyInfo7 != null ? propertyInfo7.GetValue(x) : false);
+							if (!value)
+							{
+								return false;
+							}
+							return ValidationHelper.GetDescription((Enum)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x)).ToLower().Equals(v.get_ValorIncial().ToLower());
+						};
+						func = func6;
+						func12 = func6;
+						u003cu003e9_9 = func;
+					}
+					return strs7.Any(u003cu003e9_9);
+				});
+			}).ToList();
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Helpers/DataGridExtensions.cs b/Codemerx/Gestor.Application/Helpers/DataGridExtensions.cs
new file mode 100644
index 0000000..acffb1d
--- /dev/null
+++ b/Codemerx/Gestor.Application/Helpers/DataGridExtensions.cs
@@ -0,0 +1,83 @@
+using Gestor.Common.Validation;
+using Gestor.Model.Common;
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Runtime.CompilerServices;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Controls.Primitives;
+using System.Windows.Media;
+
+namespace Gestor.Application.Helpers
+{
+	public static class DataGridExtensions
+	{
+		public static void EsconderToggles(this DataGrid grid, TipoTela tela, TipoToggle toggles)
+		{
+			try
+			{
+				foreach (object item in grid.ItemContainerGenerator.Items)
+				{
+					grid.ScrollIntoView(item, grid.Columns[0]);
+					grid.UpdateLayout();
+					DataGridRow dataGridRow = (DataGridRow)grid.ItemContainerGenerator.ContainerFromItem(item);
+					if (dataGridRow == null)
+					{
+						continue;
+					}
+					grid.ScrollIntoView(dataGridRow, grid.Columns[4]);
+					grid.UpdateLayout();
+					DataGridCellsPresenter visualChild = DataGridExtensions.GetVisualChild(dataGridRow);
+					DataGridCell dataGridCell = (DataGridCell)visualChild.ItemContainerGenerator.ContainerFromIndex(0);
+					if (dataGridCell == null || !dataGridCell.ToString().Contains(ValidationHelper.GetDescription(tela)))
+					{
+						continue;
+					}
+					if (toggles.HasFlag(TipoToggle.Consultar))
+					{
+						((DataGridCell)visualChild.ItemContainerGenerator.ContainerFromIndex(1)).Visibility = Visibility.Hidden;
+					}
+					if (toggles.HasFlag(TipoToggle.Incluir))
+					{
+						((DataGridCell)visualChild.ItemContainerGenerator.ContainerFromIndex(2)).Visibility = Visibility.Hidden;
+					}
+					if (toggles.HasFlag(TipoToggle.Alterar))
+					{
+						((DataGridCell)visualChild.ItemContainerGenerator.ContainerFromIndex(3)).Visibility = Visibility.Hidden;
+					}
+					if (toggles.HasFlag(TipoToggle.Excluir))
+					{
+						((DataGridCell)visualChild.ItemContainerGenerator.ContainerFromIndex(4)).Visibility = Visibility.Hidden;
+					}
+					return;
+				}
+			}
+			catch (Exception exception)
+			{
+			}
+		}
+
+		public static T GetVisualChild(Visual parent)
+		where T : Visual
+		{
+			T t = default(T);
+			int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
+			for (int i = 0; i < childrenCount; i++)
+			{
+				Visual child = (Visual)VisualTreeHelper.GetChild(parent, i);
+				T visualChild = (T)(child as T);
+				if (visualChild == null)
+				{
+					visualChild = DataGridExtensions.GetVisualChild(child);
+				}
+				t = visualChild;
+				if (t != null)
+				{
+					break;
+				}
+			}
+			return t;
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Helpers/Erro.cs b/Codemerx/Gestor.Application/Helpers/Erro.cs
new file mode 100644
index 0000000..52f70f5
--- /dev/null
+++ b/Codemerx/Gestor.Application/Helpers/Erro.cs
@@ -0,0 +1,24 @@
+using Gestor.Application.Views.Generic;
+using Gestor.Model.API;
+using System;
+using System.IO;
+using System.Runtime.CompilerServices;
+using System.Windows;
+using System.Windows.Threading;
+
+namespace Gestor.Application.Helpers
+{
+	public static class Erro
+	{
+		public static void RegistrarErro(LogError log, bool abrirTela = true)
+		{
+			string str = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Gestor.Exceptions.log");
+			File.AppendAllText(str, string.Format("CORRETORA: {1} - {2}{0} USUÁRIO LOGADO: {3}{0} VERSÃO: {4}{0} DATA: {5}{0} ERRO: {6} - {7}{0} HRESULT: {8}{0} HELPLINK: {9}{0}  MESSAGE: {10}{0} SOURCE: {11}{0} STACKTRACE: {12}{0} MAQUINA: {13}{0} USUARIO MAQUINA: {14}{0} LINHA: {15}{0} OBJETO: {16}{0} {0}", new object[] { Environment.NewLine, log.get_IdFornecedor(), log.get_Fornecedor(), log.get_UsuarioLogado(), log.get_Versao(), log.get_Data(), log.get_IdErro(), log.get_Erro(), log.get_HResult(), log.get_HelpLink(), log.get_Message(), log.get_Source(), log.get_StackTrace(), log.get_Maquina(), log.get_UsuarioMaquina(), log.get_Linha(), log.get_Objeto() }));
+			if (!abrirTela)
+			{
+				return;
+			}
+			System.Windows.Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => (new ErrorWindow(log.get_IdErro(), false)).ShowDialog()));
+		}
+	}
+}
\ No newline at end of file
diff --git a/Codemerx/Gestor.Application/Helpers/Funcoes.cs b/Codemerx/Gestor.Application/Helpers/Funcoes.cs
new file mode 100644
index 0000000..786f217
--- /dev/null
+++ b/Codemerx/Gestor.Application/Helpers/Funcoes.cs
@@ -0,0 +1,6825 @@
+using Agger.Registro;
+using ClosedXML.Excel;
+using CsQuery.ExtensionMethods;
+using Gestor.Application;
+using Gestor.Application.Actions;
+using Gestor.Application.Properties;
+using Gestor.Application.Servicos;
+using Gestor.Application.Servicos.Configuracoes;
+using Gestor.Application.Servicos.Ferramentas;
+using Gestor.Application.Servicos.Generic;
+using Gestor.Application.Servicos.Seguros;
+using Gestor.Application.Servicos.Seguros.Itens;
+using Gestor.Application.ViewModels.Generic;
+using Gestor.Application.Views.Generic;
+using Gestor.Common.Validation;
+using Gestor.Infrastructure.Repository.Interface;
+using Gestor.Infrastructure.UnitOfWork.Generic;
+using Gestor.Infrastructure.UnitOfWork.Logic;
+using Gestor.Model.API;
+using Gestor.Model.Attributes;
+using Gestor.Model.Common;
+using Gestor.Model.Domain.Card;
+using Gestor.Model.Domain.Common;
+using Gestor.Model.Domain.Configuracoes;
+using Gestor.Model.Domain.Generic;
+using Gestor.Model.Domain.MalaDireta;
+using Gestor.Model.Domain.Relatorios;
+using Gestor.Model.Domain.Seguros;
+using HtmlAgilityPack;
+using MaterialDesignThemes.Wpf;
+using Newtonsoft.Json;
+using OfxSharpLib;
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Globalization;
+using System.Linq;
+using System.Net;
+using System.Net.Sockets;
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Text;
+using System.Text.RegularExpressions;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Web;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Input;
+using System.Windows.Threading;
+using Xceed.Wpf.AvalonDock.Controls;
+
+namespace Gestor.Application.Helpers
+{
+	public static class Funcoes
+	{
+		public static System.Diagnostics.Stopwatch Stopwatch;
+
+		public static DateTime? StartTime;
+
+		public static string AdicionarLog(string html)
+		{
+			string innerHtml;
+			HtmlDocument htmlDocument = new HtmlDocument();
+			htmlDocument.LoadHtml(html);
+			DateTime networkTime = Funcoes.GetNetworkTime();
+			using (IEnumerator enumerator = htmlDocument.get_DocumentNode().get_ChildNodes().GetEnumerator())
+			{
+				while (enumerator.MoveNext())
+				{
+					HtmlNode current = enumerator.Current;
+					if (current.get_Name() != "body")
+					{
+						continue;
+					}
+					current.set_InnerHtml(string.Format("

{0} ID-{1} {2:g}

{3}
", new object[] { Recursos.Usuario.get_Nome(), Recursos.Usuario.get_Id(), networkTime, current.get_InnerHtml() })); + innerHtml = current.get_InnerHtml(); + return innerHtml; + } + return ""; + } + return innerHtml; + } + + public static async Task AtualizarAssistencia(Assistance assistance, string id) + { + string str; + if (await Gestor.Application.Helpers.Connection.Put(string.Concat("Assistance/", id), assistance) == null) + { + str = id; + } + else + { + str = null; + } + return str; + } + + public static async Task AtualizarCartao(Gestor.Model.Domain.Card.Card card, string id) + { + string str; + if (await Gestor.Application.Helpers.Connection.Put(string.Concat("Card/", id), card) == null) + { + str = id; + } + else + { + str = null; + } + return str; + } + + public static async Task Atualizarlogo(Logo logo, string id) + { + string str = await Gestor.Application.Helpers.Connection.Put(string.Concat("Card/Logo/", id), logo); + return str; + } + + public static async Task AtualizarSeguradora(AssistenciaCia cia, string id) + { + string str = await Gestor.Application.Helpers.Connection.Put(string.Concat("Assistance/Seguradora/", id), cia); + return str; + } + + public static async Task BaixarComissao(Parcela parcela, List parcelas, List repasses, [DecimalConstant(0, 0, 0, 0, 2)] decimal tolerancia = default(decimal), bool comissaoAuto = false) + { + Parcela parcela1; + long? nullable1; + Parcela parcela2; + decimal num1; + decimal num2; + bool flag; + object nome; + object apolice; + long? nullable2; + bool flag1; + object empty; + string str; + string proposta; + Funcoes.u003cu003ec__DisplayClass2_0 variable; + Parcela parcela3 = parcela; + ParcelaServico parcelaServico = new ParcelaServico(); + Parcela parcela4 = parcela3; + num1 = (!(parcela3.get_ValorComDesconto() == decimal.Zero) || !(Math.Abs(parcela3.get_ValorComDesconto()) < Math.Abs(parcela3.get_ValorComissao())) ? parcela3.get_ValorComDesconto() : parcela3.get_ValorComissao()); + parcela4.set_ValorComDesconto(num1); + List vendedorParcelas = repasses; + var groupings = + from x in vendedorParcelas + group x by new { Id = x.get_Parcela().get_Id(), vendedor = x.get_Vendedor().get_Id(), tipovendedor = x.get_TipoVendedor().get_Id() }; + BaseDialogViewModel baseDialogViewModel = new BaseDialogViewModel(); + if (!groupings.Any((g) => g.Count() > 1)) + { + DateTime networkTime = Funcoes.GetNetworkTime(); + if (parcela3.get_SubTipo() != 1 || parcela3.get_Documento().get_TipoRecebimento().GetValueOrDefault() != 1) + { + List vendedorParcelas1 = repasses.Where((VendedorParcela x) => { + FormaRepasse? nullable; + FormaRepasse? forma; + if (x.get_Parcela().get_Id() != parcela3.get_Id() || x.get_DataPagamento().HasValue) + { + return false; + } + if (x == null) + { + return false; + } + Repasse repasse = x.get_Repasse(); + if (repasse != null) + { + forma = repasse.get_Forma(); + } + else + { + nullable = null; + forma = nullable; + } + nullable = forma; + return nullable.GetValueOrDefault() == 1; + }).ToList(); + vendedorParcelas1.ForEach((VendedorParcela x) => { + x.set_DataPrePagamento(parcela3.get_DataRecebimento()); + x.set_ValorRepasse(new decimal?(Funcoes.CalculaRepasse(x.get_Repasse(), parcela3, false))); + }); + parcela2 = await parcelaServico.Save(parcela3, parcelas, vendedorParcelas1, false); + parcela3 = parcela2; + if (!parcelaServico.Sucesso) + { + await Funcoes.MostrarErro(24); + parcela1 = parcela3; + variable = null; + parcelaServico = null; + baseDialogViewModel = null; + return parcela1; + } + } + else + { + num2 = (parcela3.get_Documento().get_AdicionalComiss() ? parcela3.get_Documento().get_PremioLiquido() + parcela3.get_Documento().get_PremioAdicional() : parcela3.get_Documento().get_PremioLiquido()); + decimal num3 = num2; + decimal comissao = (num3 * parcela3.get_Documento().get_Comissao()) * new decimal(1, 0, 0, false, 2); + List parcelas1 = parcelas; + IEnumerable parcelas2 = parcelas1.Where((Parcela x) => { + if (x.get_SubTipo() != 1) + { + return false; + } + return x.get_DataRecebimento().HasValue; + }); + decimal num4 = parcelas2.Sum((Parcela x) => x.get_ValorComissao()); + decimal num5 = Math.Abs(comissao) - Math.Abs(num4); + flag = (num5 <= tolerancia ? true : num5 < new decimal(1, 0, 0, false, 2)); + bool flag2 = flag; + TipoRecebimento? tipoRecebimento = parcela3.get_Documento().get_TipoRecebimento(); + bool flag3 = tipoRecebimento.GetValueOrDefault() == 1 & flag2; + bool flag4 = true; + if (flag3) + { + List configuracoes = Recursos.Configuracoes; + if (configuracoes.Any((ConfiguracaoSistema c) => c.get_Configuracao() == 54)) + { + Parcela parcela5 = parcela3; + if (parcela5 != null) + { + Documento documento = parcela5.get_Documento(); + if (documento != null) + { + Controle controle = documento.get_Controle(); + if (controle != null) + { + Cliente cliente = controle.get_Cliente(); + if (cliente != null) + { + nome = cliente.get_Nome(); + } + else + { + nome = null; + } + } + else + { + nome = null; + } + } + else + { + nome = null; + } + } + else + { + nome = null; + } + if (nome == null) + { + nome = string.Empty; + } + string str1 = (string)nome; + if (string.IsNullOrEmpty(str1)) + { + Documento documento1 = parcela3.get_Documento(); + if (documento1 != null) + { + Controle controle1 = documento1.get_Controle(); + if (controle1 != null) + { + Cliente cliente1 = controle1.get_Cliente(); + if (cliente1 != null) + { + nullable2 = new long?(cliente1.get_Id()); + } + else + { + nullable1 = null; + nullable2 = nullable1; + } + } + else + { + nullable1 = null; + nullable2 = nullable1; + } + long? nullable3 = nullable2; + long num6 = (long)0; + flag1 = nullable3.GetValueOrDefault() > num6 & nullable3.HasValue; + } + else + { + flag1 = false; + } + if (flag1) + { + Cliente cliente2 = await (new ClienteServico()).BuscarClienteAsync(parcela3.get_Documento().get_Controle().get_Cliente().get_Id()); + if (cliente2 != null) + { + empty = cliente2.get_Nome(); + } + else + { + empty = null; + } + if (empty == null) + { + empty = string.Empty; + } + str1 = (string)empty; + } + } + if (!string.IsNullOrEmpty(str1)) + { + str1 = string.Concat(", DO CLIENTE ", str1); + } + Parcela parcela6 = parcela3; + if (parcela6 != null) + { + Documento documento2 = parcela6.get_Documento(); + if (documento2 != null) + { + apolice = documento2.get_Apolice(); + } + else + { + apolice = null; + } + } + else + { + apolice = null; + } + if (apolice == null) + { + apolice = string.Empty; + } + string str2 = (string)apolice; + if (!string.IsNullOrEmpty(str2)) + { + str2 = string.Concat(" - APÓLICE ", str2); + } + if (parcela3.get_Documento().get_NumeroParcelas() != parcela3.get_NumeroParcela()) + { + bool flag5 = await baseDialogViewModel.ShowMessage(string.Format("AINDA RESTA {0:c}{1}{2} QUE NÃO SERÁ REPASSADO, CONTINUAR A BAIXA POR ESGOTAMENTO?", num5, str1, str2), "SIM, BAIXAR POR ESGOMENTO", "NÃO", false); + bool flag6 = flag5; + flag3 = flag5; + flag4 = flag6; + } + } + } + List vendedorParcelas2 = repasses.Where((VendedorParcela x) => { + bool valueOrDefault; + if (x.get_Parcela().get_Id() == this.parcela.get_Id()) + { + Repasse repasse = x.get_Repasse(); + valueOrDefault = (repasse != null ? repasse.get_Forma().GetValueOrDefault() == 1 : false); + if (valueOrDefault) + { + return !x.get_DataPagamento().HasValue; + } + } + return false; + }).ToList(); + List vendedorParcelas3 = new List(); + Parcela parcela7 = parcelas.FirstOrDefault((Parcela x) => { + if (x.get_SubTipo() != 1) + { + return false; + } + return x.get_NumeroParcela() == this.parcela.get_NumeroParcela() + 1; + }); + Parcela parcela8 = parcela3; + List vendedorParcelas4 = vendedorParcelas2; + ExtensionMethods.ForEach( + from g in vendedorParcelas4 + group g by new { Id = g.get_Parcela().get_Id(), vendedor = g.get_Vendedor().get_Id(), tipovendedor = g.get_TipoVendedor().get_Id() }, (x) => { + if (x.First().get_CoCorretagem()) + { + return; + } + decimal valueOrDefault = x.First().get_ValorRepasse().GetValueOrDefault(); + decimal num = Funcoes.CalculaPagamento(x.First(), parcela8, comissao); + x.First().set_ValorRepasse(new decimal?((Math.Abs(valueOrDefault) > Math.Abs(num) ? num : valueOrDefault))); + x.First().set_DataPrePagamento(parcela8.get_DataRecebimento()); + if (flag4 && (Math.Abs(comissao) - Math.Abs(num4)) <= Math.Abs(tolerancia) || parcela7 == null) + { + return; + } + VendedorParcela vendedorParcela = new VendedorParcela(); + vendedorParcela.set_Repasse(x.First().get_Repasse()); + vendedorParcela.set_Parcela(parcela7); + vendedorParcela.set_Documento(parcela8.get_Documento()); + vendedorParcela.set_ValorRepasse(new decimal?(valueOrDefault - num)); + vendedorParcela.set_Vendedor(x.First().get_Vendedor()); + vendedorParcela.set_ValorTotal(x.First().get_ValorTotal()); + vendedorParcela.set_PorcentagemRepasse(x.First().get_PorcentagemRepasse()); + vendedorParcela.set_TipoVendedor(x.First().get_TipoVendedor()); + vendedorParcela.set_CoCorretagem(x.First().get_CoCorretagem()); + vendedorParcelas3.Add(vendedorParcela); + }); + if (vendedorParcelas3.Count > 0) + { + vendedorParcelas2.AddRange(vendedorParcelas3); + } + if (await parcelaServico.SaveRange(vendedorParcelas2)) + { + parcela2 = await parcelaServico.Save(parcela3, parcelas, null, false); + parcela3 = parcela2; + if (parcelaServico.Sucesso) + { + if (flag3) + { + List parcelas3 = parcelas; + List parcelas4 = parcelas3.Where((Parcela x) => { + if (x.get_DataRecebimento().HasValue) + { + return false; + } + return x.get_SubTipo() == 1; + }).ToList(); + List vendedorParcelas5 = new List(); + parcelas4.ForEach((Parcela x) => { + x.set_Documento(parcela3.get_Documento()); + x.set_DataRecebimento(parcela3.get_DataRecebimento()); + x.set_DataCredito(parcela3.get_DataRecebimento()); + x.set_ValorRealizado(decimal.Zero); + x.set_ValorComissao(decimal.Zero); + x.set_ValorComDesconto(decimal.Zero); + x.set_Irr(decimal.Zero); + x.set_Iss(decimal.Zero); + List list = repasses.Where((VendedorParcela p) => { + bool valueOrDefault; + if (p.get_Parcela().get_Id() == x.get_Id()) + { + Repasse repasse = p.get_Repasse(); + valueOrDefault = (repasse != null ? repasse.get_Forma().GetValueOrDefault() == 1 : false); + if (valueOrDefault) + { + Repasse repasse1 = p.get_Repasse(); + if (repasse1 == null) + { + return true; + } + return repasse1.get_Tipo().GetValueOrDefault() != 3; + } + } + return false; + }).ToList(); + list.ForEach((VendedorParcela p) => { + decimal? nullable; + p.set_Parcela(x); + p.set_Documento(parcela3.get_Documento()); + p.set_DataPrePagamento(new DateTime?(networkTime)); + VendedorParcela vendedorParcela = p; + decimal? valorRepasse = p.get_ValorRepasse(); + decimal cSu0024u003cu003e8_locals1 = tolerancia; + if ((valorRepasse.GetValueOrDefault() > cSu0024u003cu003e8_locals1) & valorRepasse.HasValue) + { + cSu0024u003cu003e8_locals1 = new decimal(); + nullable = new decimal?(cSu0024u003cu003e8_locals1); + } + else + { + nullable = p.get_ValorRepasse(); + } + vendedorParcela.set_ValorRepasse(nullable); + }); + vendedorParcelas5.AddRange(list); + }); + await parcelaServico.SaveRange(parcelas); + if (!parcelaServico.Sucesso) + { + await Funcoes.MostrarErro(24); + parcela1 = parcela3; + variable = null; + parcelaServico = null; + baseDialogViewModel = null; + return parcela1; + } + else if (await parcelaServico.SaveRange(vendedorParcelas5)) + { + } + else + { + await Funcoes.MostrarErro(24); + parcela1 = parcela3; + variable = null; + parcelaServico = null; + baseDialogViewModel = null; + return parcela1; + } + } + } + else + { + await Funcoes.MostrarErro(24); + parcela1 = parcela3; + variable = null; + parcelaServico = null; + baseDialogViewModel = null; + return parcela1; + } + } + else + { + await Funcoes.MostrarErro(24); + parcela1 = parcela3; + variable = null; + parcelaServico = null; + baseDialogViewModel = null; + return parcela1; + } + } + if (!comissaoAuto) + { + Funcoes.RegistrarLogBaixa(parcela3.get_Documento().get_Id(), networkTime); + } + parcela1 = parcela3; + } + else + { + Documento documento3 = parcela3.get_Documento(); + if (documento3 != null) + { + str = documento3.get_Apolice(); + } + else + { + str = null; + } + if (string.IsNullOrWhiteSpace(str)) + { + Documento documento4 = parcela3.get_Documento(); + if (documento4 != null) + { + proposta = documento4.get_Apolice(); + } + else + { + proposta = null; + } + } + else + { + Documento documento5 = parcela3.get_Documento(); + if (documento5 != null) + { + proposta = documento5.get_Proposta(); + } + else + { + proposta = null; + } + } + string str3 = proposta; + await baseDialogViewModel.ShowMessage(string.Format("HÁ VENDEDORES DUPLICADOS PARA A PARCELA {0} DO DOCUMENTO {1}, BAIXA DE COMISSÃO INTERROMPIDA.{2}REALIZE A CORREÇÃO DOS VENDEDORES E TENTE NOVAMENTE.", parcela3.get_NumeroParcela(), str3, Environment.NewLine), "OK", "", false); + parcela3.set_DataRecebimento(null); + parcela3.set_ValorComissao(decimal.Zero); + parcela3.set_ValorComDesconto(decimal.Zero); + parcela3.set_Irr(decimal.Zero); + parcela3.set_Iss(decimal.Zero); + parcela3.set_Outros(decimal.Zero); + parcela3.set_Desconto(decimal.Zero); + parcela1 = parcela3; + } + variable = null; + parcelaServico = null; + baseDialogViewModel = null; + return parcela1; + } + + public static string BoolToString(this bool boolean) + { + if (!boolean) + { + return "0"; + } + return "1"; + } + + public static void BringToFront(this string programName) + { + try + { + Process[] processesByName = Process.GetProcessesByName(programName); + if (processesByName.Length != 0) + { + IntPtr mainWindowHandle = processesByName[0].MainWindowHandle; + Funcoes.ShowWindow(mainWindowHandle, 5); + Funcoes.ShowWindow(mainWindowHandle, 9); + Funcoes.SetForegroundWindow(mainWindowHandle); + } + } + catch (Exception exception) + { + } + } + + public static decimal CalculaPagamento(VendedorParcela pagamento, Parcela parcela, decimal comissaoPrevista) + { + TipoRepasse? tipo; + bool valueOrDefault; + bool flag; + bool valueOrDefault1; + bool flag1; + decimal num; + decimal num1 = pagamento.get_PorcentagemRepasse().GetValueOrDefault(); + decimal valueOrDefault2 = pagamento.get_ValorRepasse().GetValueOrDefault(); + decimal valorComDesconto = parcela.get_ValorComDesconto(); + Repasse repasse = pagamento.get_Repasse(); + if (repasse != null) + { + valueOrDefault = repasse.get_Incidencia().GetValueOrDefault() == 2; + } + else + { + valueOrDefault = false; + } + if (valueOrDefault) + { + decimal comissao = (parcela.get_Documento().get_Comissao() * parcela.get_Documento().get_PremioLiquido()) * new decimal(1, 0, 0, false, 2); + num = (parcela.get_ValorComissao() != decimal.Zero ? parcela.get_ValorComissao() / comissao : decimal.Zero); + valorComDesconto = parcela.get_Documento().get_PremioLiquido() * num; + } + Repasse repasse1 = pagamento.get_Repasse(); + if (repasse1 != null) + { + tipo = repasse1.get_Tipo(); + flag = tipo.GetValueOrDefault() != 1; + } + else + { + flag = true; + } + if (flag) + { + decimal? porcentagemRepasse = pagamento.get_PorcentagemRepasse(); + num1 = (valorComDesconto * porcentagemRepasse.GetValueOrDefault()) * new decimal(1, 0, 0, false, 2); + } + Repasse repasse2 = pagamento.get_Repasse(); + if (repasse2 != null) + { + tipo = repasse2.get_Tipo(); + valueOrDefault1 = tipo.GetValueOrDefault() == 1; + } + else + { + valueOrDefault1 = false; + } + if (valueOrDefault1) + { + Repasse repasse3 = pagamento.get_Repasse(); + if (repasse3 != null) + { + flag1 = repasse3.get_Forma().GetValueOrDefault() == 1; + } + else + { + flag1 = false; + } + if (flag1) + { + if (Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 25)) + { + num1 *= (comissaoPrevista == decimal.Zero ? decimal.One : parcela.get_ValorComissao() / comissaoPrevista); + } + } + } + if (Math.Abs(num1) <= Math.Abs(valueOrDefault2)) + { + return num1; + } + return valueOrDefault2; + } + + public static decimal CalculaRepasse(Repasse repasse, Parcela parcela, bool apolice = true) + { + decimal num; + decimal num1; + decimal num2; + decimal comissao; + decimal num3; + if (repasse == null) + { + return decimal.Zero; + } + NegocioCorretora? negocioCorretora = parcela.get_Documento().get_NegocioCorretora(); + bool valueOrDefault = negocioCorretora.GetValueOrDefault() == 1; + if (!apolice || parcela.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 2 || parcela.get_SubTipo() != 1) + { + decimal num4 = (parcela.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 2 ? parcela.get_ValorLiquidoFatura() : parcela.get_Valor()); + if (repasse.get_Incidencia().GetValueOrDefault() == 2) + { + num3 = num4; + } + else + { + num3 = (parcela.get_ValorComDesconto() == decimal.Zero ? num4 : parcela.get_ValorComDesconto()); + } + num1 = num3; + num2 = num1; + comissao = (parcela.get_ValorComDesconto() == decimal.Zero ? parcela.get_Comissao() * new decimal(1, 0, 0, false, 2) : decimal.One); + } + else + { + num1 = (parcela.get_Documento().get_AdicionalComiss() ? parcela.get_Documento().get_PremioLiquido() + parcela.get_Documento().get_PremioAdicional() : parcela.get_Documento().get_PremioLiquido()); + num2 = (parcela.get_Documento().get_AdicionalComiss() ? parcela.get_Documento().get_PremioLiquido() + parcela.get_Documento().get_PremioAdicional() : parcela.get_Documento().get_PremioLiquido()); + comissao = parcela.get_Documento().get_Comissao() * new decimal(1, 0, 0, false, 2); + } + num1 = (repasse.get_Incidencia().GetValueOrDefault() == 2 ? num1 : num1 * comissao); + num1 = (repasse.get_Tipo().GetValueOrDefault() == 1 ? num1 : (num1 * (valueOrDefault ? repasse.get_ValorRenovacao() : repasse.get_ValorNovo())) * new decimal(1, 0, 0, false, 2)); + decimal num5 = (repasse.get_Incidencia().GetValueOrDefault() == 2 ? num2 : num2 * comissao); + if (repasse.get_Tipo().GetValueOrDefault() != 1) + { + num = (num5 * (valueOrDefault ? repasse.get_ValorRenovacao() : repasse.get_ValorNovo())) * new decimal(1, 0, 0, false, 2); + } + else + { + num = (valueOrDefault ? repasse.get_ValorRenovacao() : repasse.get_ValorNovo()); + if (Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 24) && parcela.get_Valor() < decimal.Zero) + { + num = -num; + } + } + if (parcela.get_Documento().get_TipoRecebimento().GetValueOrDefault() != 2 && parcela.get_SubTipo() == 1 && parcela.get_Documento().get_TipoEndosso().GetValueOrDefault() != 2) + { + if (Math.Abs(num) > Math.Abs(num1)) + { + (new BaseDialogViewModel()).ShowMessage("OS VALORES DE REPASSE ULTRAPASSARAM O VALOR DE COMISSÃO FECHADA. REVEJA OS VALORES.", "OK", "", false); + } + if (Math.Abs(num) <= Math.Abs(num1)) + { + return num; + } + return num1; + } + if (parcela.get_ValorComDesconto() != decimal.Zero && Math.Abs(num) > Math.Abs(parcela.get_ValorComDesconto())) + { + if (Recursos.Configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 15)) + { + return parcela.get_ValorComDesconto(); + } + } + return num; + } + + public static string Clear(this string stringToClean) + { + if (stringToClean == null) + { + return null; + } + return Regex.Replace(stringToClean, "[^\\d]", string.Empty); + } + + private static void CloseSlackBar() + { + Thread.Sleep(5000); + Dispatcher dispatcher = App.ProgressRing.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => Funcoes.ToggleSnackBar("", false))); + } + + public static List ColunasRelatorio(Relatorio relatorio, List parametrosAdicionados) + { + long id; + int ordem; + List parametrosRelatorios = new List(); + foreach (PropertyInfo propertyInfo in + from in (IEnumerable)typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public) + orderby x.GetDescriptionAttribute() + select ) + { + if (propertyInfo.Name == "ValidationEvent" || propertyInfo.GetTypeAttribute() == "INVALID" || parametrosAdicionados.Any((ParametrosRelatorio x) => x.get_Campo() == propertyInfo.Name)) + { + continue; + } + ParametrosRelatorio parametrosRelatorio = new ParametrosRelatorio(); + ParametrosRelatorio parametrosRelatorio1 = parametrosAdicionados.FirstOrDefault((ParametrosRelatorio x) => { + if (x.get_IdUsuario() == 0) + { + return false; + } + return x.get_Campo() == propertyInfo.Name; + }); + if (parametrosRelatorio1 != null) + { + id = parametrosRelatorio1.get_Id(); + } + else + { + id = (long)0; + } + parametrosRelatorio.set_Id(id); + parametrosRelatorio.set_Campo(propertyInfo.Name); + parametrosRelatorio.set_Header(propertyInfo.GetDescriptionAttribute()); + parametrosRelatorio.set_IdUsuario(Recursos.Usuario.get_Id()); + parametrosRelatorio.set_Relatorio(relatorio); + parametrosRelatorio.set_Tipo(propertyInfo.GetTypeAttribute()); + parametrosRelatorio.set_Width(0); + ParametrosRelatorio parametrosRelatorio2 = parametrosAdicionados.FirstOrDefault((ParametrosRelatorio x) => x.get_Campo() == propertyInfo.Name); + if (parametrosRelatorio2 != null) + { + ordem = parametrosRelatorio2.get_Ordem(); + } + else + { + ordem = 0; + } + parametrosRelatorio.set_Ordem(ordem); + parametrosRelatorios.Add(parametrosRelatorio); + } + return parametrosRelatorios; + } + + public static List ConstruirSintetico(this List sintetico, Relatorio relatorio) + { + if (sintetico == null) + { + return null; + } + List sinteticModelLists = new List(); + typeof(Sintetico).GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList().ForEach((PropertyInfo props) => { + char chr; + if (props.GetValue(sintetico.First()) == null) + { + return; + } + string descriptionAttribute = props.GetDescriptionAttribute(); + TipoRestricao? nullable = null; + if (descriptionAttribute != null) + { + switch (descriptionAttribute.Length) + { + case 5: + { + if (descriptionAttribute == "VALOR") + { + nullable = new TipoRestricao?(100); + goto Label0; + } + else + { + goto Label0; + } + } + case 7: + { + if (descriptionAttribute == "REPASSE") + { + nullable = new TipoRestricao?(81); + goto Label0; + } + else + { + goto Label0; + } + } + case 8: + { + if (descriptionAttribute == "IMPOSTOS") + { + nullable = new TipoRestricao?(93); + goto Label0; + } + else + { + goto Label0; + } + } + case 10: + { + if (descriptionAttribute == "VALOR PAGO") + { + nullable = new TipoRestricao?(104); + goto Label0; + } + else + { + goto Label0; + } + } + case 11: + { + if (descriptionAttribute == "TOTAL GERAL") + { + nullable = new TipoRestricao?(75); + goto Label0; + } + else + { + goto Label0; + } + } + case 12: + { + chr = descriptionAttribute[0]; + if (chr == 'M') + { + if (descriptionAttribute == "META ATINGIR") + { + nullable = new TipoRestricao?(88); + goto Label0; + } + else + { + goto Label0; + } + } + else if (chr == 'P') + { + if (descriptionAttribute == "PRÊMIO TOTAL") + { + nullable = new TipoRestricao?(65); + goto Label0; + } + else + { + goto Label0; + } + } + else if (chr != 'V') + { + goto Label0; + } + else if (descriptionAttribute == "VALOR ORÇADO") + { + nullable = new TipoRestricao?(101); + goto Label0; + } + else + { + goto Label0; + } + } + case 13: + { + chr = descriptionAttribute[0]; + if (chr == 'M') + { + if (descriptionAttribute == "META CUMPRIDA") + { + nullable = new TipoRestricao?(89); + goto Label0; + } + else + { + goto Label0; + } + } + else if (chr != 'V') + { + goto Label0; + } + else if (descriptionAttribute == "VALOR SALVADO") + { + nullable = new TipoRestricao?(105); + goto Label0; + } + else + { + goto Label0; + } + } + case 14: + { + chr = descriptionAttribute[8]; + switch (chr) + { + case 'A': + { + if (descriptionAttribute == "VALOR FRANQUIA") + { + nullable = new TipoRestricao?(106); + goto Label0; + } + else + { + goto Label0; + } + } + case 'B': + { + if (descriptionAttribute == "VALOR LIBERADO") + { + nullable = new TipoRestricao?(103); + goto Label0; + } + else + { + goto Label0; + } + } + case 'C': + case 'D': + { + goto Label0; + } + case 'E': + { + if (descriptionAttribute == "TOTAL PREVISTO") + { + nullable = new TipoRestricao?(82); + goto Label0; + } + else + { + goto Label0; + } + } + default: + { + if (chr == 'R') + { + if (descriptionAttribute == "TOTAL PARCELAS") + { + nullable = new TipoRestricao?(102); + goto Label0; + } + else + { + goto Label0; + } + } + else if (chr != 'Í') + { + goto Label0; + } + else if (descriptionAttribute == "PRÊMIO LÍQUIDO") + { + nullable = new TipoRestricao?(67); + goto Label0; + } + else + { + goto Label0; + } + } + } + break; + } + case 15: + { + if (descriptionAttribute == "VALOR LIQUIDADO") + { + nullable = new TipoRestricao?(86); + goto Label0; + } + else + { + goto Label0; + } + } + case 16: + { + if (descriptionAttribute == "TOTAL DE LÍQUIDO") + { + nullable = new TipoRestricao?(76); + goto Label0; + } + else + { + goto Label0; + } + } + case 17: + { + chr = descriptionAttribute[10]; + if (chr == 'E') + { + if (descriptionAttribute == "COMISSÃO PENDENTE") + { + nullable = new TipoRestricao?(87); + goto Label0; + } + else + { + goto Label0; + } + } + else if (chr == 'L') + { + if (descriptionAttribute == "TOTAL DE CLIENTES") + { + goto Label1; + } + goto Label0; + } + else if (chr != 'R') + { + goto Label0; + } + else if (descriptionAttribute == "COMISSÃO PREVISTA") + { + nullable = new TipoRestricao?(80); + goto Label0; + } + else + { + goto Label0; + } + } + case 18: + { + if (descriptionAttribute == "TOTAL DE TERCEIROS") + { + nullable = new TipoRestricao?(83); + goto Label0; + } + else + { + goto Label0; + } + } + case 19: + { + if (descriptionAttribute == "QUANTIDADE PENDENTE") + { + nullable = new TipoRestricao?(85); + goto Label0; + } + else + { + goto Label0; + } + } + case 20: + { + if (descriptionAttribute == "QUANTIDADE LIQUIDADO") + { + nullable = new TipoRestricao?(84); + goto Label0; + } + else + { + goto Label0; + } + } + case 21: + { + if (descriptionAttribute == "QUANTIDADE DE FATURAS") + { + nullable = new TipoRestricao?(74); + goto Label0; + } + else + { + goto Label0; + } + } + case 22: + { + chr = descriptionAttribute[14]; + if (chr == 'A') + { + if (descriptionAttribute == "QUANTIDADE DE APÓLICES") + { + nullable = new TipoRestricao?(72); + goto Label0; + } + else + { + goto Label0; + } + } + else if (chr != 'E') + { + goto Label0; + } + else if (descriptionAttribute == "QUANTIDADE DE ENDOSSOS") + { + nullable = new TipoRestricao?(73); + goto Label0; + } + else + { + goto Label0; + } + } + case 23: + { + if (descriptionAttribute == "COMISSÃO RECEBIDA BRUTA") + { + nullable = new TipoRestricao?(79); + goto Label0; + } + else + { + goto Label0; + } + } + case 24: + { + chr = descriptionAttribute[0]; + if (chr == 'M') + { + if (descriptionAttribute == "MÉDIA DE COMISSÃO GERADA") + { + break; + } + goto Label0; + } + else if (chr == 'Q') + { + if (descriptionAttribute == "QUANTIDADE DE RENOVAÇÕES") + { + goto Label2; + } + goto Label0; + } + else if (chr == 'T') + { + if (descriptionAttribute == "TOTAL DE CLIENTES ATIVOS") + { + goto Label1; + } + if (descriptionAttribute == "TOTAL DE COMISSÃO GERADA") + { + nullable = new TipoRestricao?(78); + goto Label0; + } + else + { + goto Label0; + } + } + else + { + goto Label0; + } + } + case 25: + { + chr = descriptionAttribute[0]; + if (chr == 'C') + { + if (descriptionAttribute == "COMISSÃO RECEBIDA LÍQUIDA") + { + nullable = new TipoRestricao?(92); + goto Label0; + } + else + { + goto Label0; + } + } + else if (chr == 'M') + { + if (descriptionAttribute == "MÉDIA DE COMISSÃO FECHADA") + { + break; + } + goto Label0; + } + else if (chr != 'Q') + { + goto Label0; + } + else if (descriptionAttribute == "QUANTIDADE DE PROSPECÇÕES") + { + nullable = new TipoRestricao?(77); + goto Label0; + } + else + { + goto Label0; + } + } + case 26: + { + if (descriptionAttribute == "TOTAL DE CLIENTES INATIVOS") + { + goto Label1; + } + goto Label0; + } + case 27: + { + chr = descriptionAttribute[15]; + if (chr == 'A') + { + if (descriptionAttribute == "QUANTIDADE DE CANCELAMENTOS") + { + nullable = new TipoRestricao?(71); + goto Label0; + } + else + { + goto Label0; + } + } + else if (chr == 'E') + { + if (descriptionAttribute == "QUANTIDADE DE SEGUROS NOVOS") + { + goto Label2; + } + goto Label0; + } + else if (chr == 'Ã') + { + if (descriptionAttribute == "MÉDIA DE COMISSÃO PONDERADA") + { + break; + } + goto Label0; + } + else + { + goto Label0; + } + } + case 28: + { + if (descriptionAttribute == "QUANTIDADE DE NOVOS NEGÓCIOS") + { + goto Label3; + } + goto Label0; + } + case 31: + { + if (descriptionAttribute == "QUANTIDADE DE NEGÓCIOS PRÓPRIOS") + { + goto Label3; + } + goto Label0; + } + default: + { + goto Label0; + } + } + nullable = new TipoRestricao?(68); + } + Label0: + if (nullable.HasValue) + { + RestricaoUsuario restricaoUsuario = (new RestricaoUsuarioServico()).BuscarRestricao(Recursos.Usuario, nullable.Value); + if (restricaoUsuario != null && restricaoUsuario.get_Restricao()) + { + return; + } + } + List parametrosTotalizacaos = (new ConfuguracoesServico()).BuscarParametroTotalizacao(relatorio); + if (parametrosTotalizacaos != null && parametrosTotalizacaos.Count > 0 && parametrosTotalizacaos.All((ParametrosTotalizacao y) => y.get_Campo() != props.Name) && !props.Name.ToUpperInvariant().Contains("AGRUPAMENTO")) + { + return; + } + SinteticModelList sinteticModelList = new SinteticModelList(); + sinteticModelList.set_Hint(descriptionAttribute); + sinteticModelList.set_Value(new List()); + SinteticModelList sinteticModelList1 = sinteticModelList; + string typeAttribute = props.GetTypeAttribute(); + sintetico.ForEach((Sintetico s) => { + object obj; + DateTime? value; + DateTime valueOrDefault; + object str; + object str1; + string str2 = typeAttribute; + if (str2 == "DATA/TIME" || str2 == "DATA/TIME?") + { + value = (DateTime?)props.GetValue(s); + if (value.HasValue) + { + valueOrDefault = value.GetValueOrDefault(); + str = valueOrDefault.ToString("G"); + } + else + { + str = null; + } + obj = str; + } + else if (str2 == "DATA" || str2 == "DATA?") + { + value = (DateTime?)props.GetValue(s); + if (value.HasValue) + { + valueOrDefault = value.GetValueOrDefault(); + str1 = valueOrDefault.ToString("d"); + } + else + { + str1 = null; + } + obj = str1; + } + else + { + obj = (str2 == "PERCENTUAL" ? string.Format("{0:n2} %", props.GetValue(s)) : (str2 == "VALOR" ? ((decimal)props.GetValue(s)).ToString("c2") : string.Format("{0}", props.GetValue(s)))); + } + sinteticModelList1.get_Value().Add(obj); + }); + sinteticModelLists.Add(sinteticModelList1); + return; + Label1: + nullable = new TipoRestricao?(66); + goto Label0; + Label2: + nullable = new TipoRestricao?(70); + goto Label0; + Label3: + nullable = new TipoRestricao?(69); + goto Label0; + }); + return sinteticModelLists; + } + + public static List ConstruirSintetico(this Sintetico sintetico, Relatorio relatorio) + { + if (sintetico == null) + { + return null; + } + List sinteticModels = new List(); + typeof(Sintetico).GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList().ForEach((PropertyInfo x) => { + int length; + char chr; + DateTime? value; + DateTime valueOrDefault; + decimal num; + object str; + SinteticModel sinteticModel; + object obj; + if (x.GetValue(sintetico) == null) + { + return; + } + string descriptionAttribute = x.GetDescriptionAttribute(); + TipoRestricao? nullable = null; + string str1 = null; + if (descriptionAttribute != null) + { + length = descriptionAttribute.Length; + switch (length) + { + case 5: + { + if (descriptionAttribute == "VALOR") + { + nullable = new TipoRestricao?(100); + goto Label0; + } + else + { + goto Label0; + } + } + case 7: + { + if (descriptionAttribute == "REPASSE") + { + nullable = new TipoRestricao?(81); + goto Label0; + } + else + { + goto Label0; + } + } + case 8: + { + if (descriptionAttribute == "IMPOSTOS") + { + nullable = new TipoRestricao?(93); + goto Label0; + } + else + { + goto Label0; + } + } + case 10: + { + if (descriptionAttribute == "VALOR PAGO") + { + nullable = new TipoRestricao?(104); + goto Label0; + } + else + { + goto Label0; + } + } + case 11: + { + if (descriptionAttribute == "TOTAL GERAL") + { + nullable = new TipoRestricao?(75); + str1 = "CONTAGEM GERAL DE DOCUMENTOS"; + goto Label0; + } + else + { + goto Label0; + } + } + case 12: + { + chr = descriptionAttribute[0]; + if (chr == 'M') + { + if (descriptionAttribute == "META ATINGIR") + { + nullable = new TipoRestricao?(88); + goto Label0; + } + else + { + goto Label0; + } + } + else if (chr == 'P') + { + if (descriptionAttribute == "PRÊMIO TOTAL") + { + nullable = new TipoRestricao?(65); + goto Label0; + } + else + { + goto Label0; + } + } + else if (chr != 'V') + { + goto Label0; + } + else if (descriptionAttribute == "VALOR ORÇADO") + { + nullable = new TipoRestricao?(101); + goto Label0; + } + else + { + goto Label0; + } + } + case 13: + { + chr = descriptionAttribute[0]; + if (chr == 'M') + { + if (descriptionAttribute == "META CUMPRIDA") + { + nullable = new TipoRestricao?(89); + goto Label0; + } + else + { + goto Label0; + } + } + else if (chr != 'V') + { + goto Label0; + } + else if (descriptionAttribute == "VALOR SALVADO") + { + nullable = new TipoRestricao?(105); + goto Label0; + } + else + { + goto Label0; + } + } + case 14: + { + chr = descriptionAttribute[8]; + switch (chr) + { + case 'A': + { + if (descriptionAttribute == "VALOR FRANQUIA") + { + nullable = new TipoRestricao?(106); + goto Label0; + } + else + { + goto Label0; + } + } + case 'B': + { + if (descriptionAttribute == "VALOR LIBERADO") + { + nullable = new TipoRestricao?(103); + goto Label0; + } + else + { + goto Label0; + } + } + case 'C': + case 'D': + { + goto Label0; + } + case 'E': + { + if (descriptionAttribute == "TOTAL PREVISTO") + { + nullable = new TipoRestricao?(82); + goto Label0; + } + else + { + goto Label0; + } + } + default: + { + if (chr == 'R') + { + if (descriptionAttribute == "TOTAL PARCELAS") + { + nullable = new TipoRestricao?(102); + goto Label0; + } + else + { + goto Label0; + } + } + else if (chr != 'Í') + { + goto Label0; + } + else if (descriptionAttribute == "PRÊMIO LÍQUIDO") + { + nullable = new TipoRestricao?(67); + goto Label0; + } + else + { + goto Label0; + } + } + } + break; + } + case 15: + { + if (descriptionAttribute == "VALOR LIQUIDADO") + { + nullable = new TipoRestricao?(86); + goto Label0; + } + else + { + goto Label0; + } + } + case 16: + { + if (descriptionAttribute == "TOTAL DE LÍQUIDO") + { + nullable = new TipoRestricao?(76); + str1 = "CONTAGEM GERAL DOS DOCUMENTOS ATIVOS"; + goto Label0; + } + else + { + goto Label0; + } + } + case 17: + { + chr = descriptionAttribute[10]; + if (chr == 'E') + { + if (descriptionAttribute == "COMISSÃO PENDENTE") + { + nullable = new TipoRestricao?(87); + goto Label0; + } + else + { + goto Label0; + } + } + else if (chr == 'L') + { + if (descriptionAttribute == "TOTAL DE CLIENTES") + { + goto Label1; + } + goto Label0; + } + else if (chr != 'R') + { + goto Label0; + } + else if (descriptionAttribute == "COMISSÃO PREVISTA") + { + nullable = new TipoRestricao?(80); + goto Label0; + } + else + { + goto Label0; + } + } + case 18: + { + if (descriptionAttribute == "TOTAL DE TERCEIROS") + { + nullable = new TipoRestricao?(83); + goto Label0; + } + else + { + goto Label0; + } + } + case 19: + { + if (descriptionAttribute == "QUANTIDADE PENDENTE") + { + nullable = new TipoRestricao?(85); + goto Label0; + } + else + { + goto Label0; + } + } + case 20: + { + if (descriptionAttribute == "QUANTIDADE LIQUIDADO") + { + nullable = new TipoRestricao?(84); + goto Label0; + } + else + { + goto Label0; + } + } + case 21: + { + if (descriptionAttribute == "QUANTIDADE DE FATURAS") + { + nullable = new TipoRestricao?(74); + goto Label0; + } + else + { + goto Label0; + } + } + case 22: + { + chr = descriptionAttribute[14]; + if (chr == 'A') + { + if (descriptionAttribute == "QUANTIDADE DE APÓLICES") + { + nullable = new TipoRestricao?(72); + goto Label0; + } + else + { + goto Label0; + } + } + else if (chr != 'E') + { + goto Label0; + } + else if (descriptionAttribute == "QUANTIDADE DE ENDOSSOS") + { + nullable = new TipoRestricao?(73); + goto Label0; + } + else + { + goto Label0; + } + } + case 23: + { + if (descriptionAttribute == "COMISSÃO RECEBIDA BRUTA") + { + nullable = new TipoRestricao?(79); + goto Label0; + } + else + { + goto Label0; + } + } + case 24: + { + chr = descriptionAttribute[0]; + if (chr == 'M') + { + if (descriptionAttribute == "MÉDIA DE COMISSÃO GERADA") + { + break; + } + goto Label0; + } + else if (chr == 'Q') + { + if (descriptionAttribute == "QUANTIDADE DE RENOVAÇÕES") + { + goto Label2; + } + goto Label0; + } + else if (chr == 'T') + { + if (descriptionAttribute == "TOTAL DE CLIENTES ATIVOS") + { + goto Label1; + } + if (descriptionAttribute == "TOTAL DE COMISSÃO GERADA") + { + nullable = new TipoRestricao?(78); + goto Label0; + } + else + { + goto Label0; + } + } + else + { + goto Label0; + } + } + case 25: + { + chr = descriptionAttribute[0]; + if (chr == 'C') + { + if (descriptionAttribute == "COMISSÃO RECEBIDA LÍQUIDA") + { + nullable = new TipoRestricao?(92); + goto Label0; + } + else + { + goto Label0; + } + } + else if (chr == 'M') + { + if (descriptionAttribute == "MÉDIA DE COMISSÃO FECHADA") + { + break; + } + goto Label0; + } + else if (chr != 'Q') + { + goto Label0; + } + else if (descriptionAttribute == "QUANTIDADE DE PROSPECÇÕES") + { + nullable = new TipoRestricao?(77); + goto Label0; + } + else + { + goto Label0; + } + } + case 26: + { + if (descriptionAttribute == "TOTAL DE CLIENTES INATIVOS") + { + goto Label1; + } + goto Label0; + } + case 27: + { + chr = descriptionAttribute[15]; + if (chr == 'A') + { + if (descriptionAttribute == "QUANTIDADE DE CANCELAMENTOS") + { + nullable = new TipoRestricao?(71); + goto Label0; + } + else + { + goto Label0; + } + } + else if (chr == 'E') + { + if (descriptionAttribute == "QUANTIDADE DE SEGUROS NOVOS") + { + goto Label2; + } + goto Label0; + } + else if (chr == 'Ã') + { + if (descriptionAttribute == "MÉDIA DE COMISSÃO PONDERADA") + { + break; + } + goto Label0; + } + else + { + goto Label0; + } + } + case 28: + { + if (descriptionAttribute == "QUANTIDADE DE NOVOS NEGÓCIOS") + { + goto Label3; + } + goto Label0; + } + case 31: + { + if (descriptionAttribute == "QUANTIDADE DE NEGÓCIOS PRÓPRIOS") + { + goto Label3; + } + goto Label0; + } + default: + { + goto Label0; + } + } + nullable = new TipoRestricao?(68); + } + Label0: + if (nullable.HasValue) + { + RestricaoUsuario restricaoUsuario = (new RestricaoUsuarioServico()).BuscarRestricao(Recursos.Usuario, nullable.Value); + if (restricaoUsuario != null && restricaoUsuario.get_Restricao()) + { + return; + } + } + List parametrosTotalizacaos = (new ConfuguracoesServico()).BuscarParametroTotalizacao(relatorio); + if (parametrosTotalizacaos != null && parametrosTotalizacaos.Count > 0 && parametrosTotalizacaos.All((ParametrosTotalizacao y) => y.get_Campo() != x.Name)) + { + return; + } + SinteticModel sinteticModel1 = new SinteticModel(); + sinteticModel1.set_Hint(descriptionAttribute); + sinteticModel1.set_DescriptionField(str1); + SinteticModel sinteticModel2 = sinteticModel1; + string typeAttribute = x.GetTypeAttribute(); + if (typeAttribute != null) + { + length = typeAttribute.Length; + switch (length) + { + case 4: + { + if (typeAttribute == "DATA") + { + break; + } + sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico))); + sinteticModels.Add(sinteticModel2); + return; + } + case 5: + { + chr = typeAttribute[0]; + if (chr == 'D') + { + if (typeAttribute == "DATA?") + { + break; + } + sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico))); + sinteticModels.Add(sinteticModel2); + return; + } + else if (chr != 'V') + { + sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico))); + sinteticModels.Add(sinteticModel2); + return; + } + else if (typeAttribute == "VALOR") + { + num = (decimal)x.GetValue(sintetico); + sinteticModel2.set_Value(num.ToString("c2")); + sinteticModels.Add(sinteticModel2); + return; + } + else + { + sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico))); + sinteticModels.Add(sinteticModel2); + return; + } + } + case 6: + case 7: + case 8: + { + sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico))); + sinteticModels.Add(sinteticModel2); + return; + } + case 9: + { + if (typeAttribute == "DATA/TIME") + { + sinteticModel = sinteticModel2; + value = (DateTime?)x.GetValue(sintetico); + if (value.HasValue) + { + valueOrDefault = value.GetValueOrDefault(); + obj = valueOrDefault.ToString("G"); + } + else + { + obj = null; + } + sinteticModel.set_Value(obj); + sinteticModels.Add(sinteticModel2); + return; + } + sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico))); + sinteticModels.Add(sinteticModel2); + return; + } + case 10: + { + chr = typeAttribute[0]; + if (chr == 'D') + { + if (typeAttribute == "DATA/TIME?") + { + sinteticModel = sinteticModel2; + value = (DateTime?)x.GetValue(sintetico); + if (value.HasValue) + { + valueOrDefault = value.GetValueOrDefault(); + obj = valueOrDefault.ToString("G"); + } + else + { + obj = null; + } + sinteticModel.set_Value(obj); + sinteticModels.Add(sinteticModel2); + return; + } + sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico))); + sinteticModels.Add(sinteticModel2); + return; + } + else if (chr != 'P') + { + sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico))); + sinteticModels.Add(sinteticModel2); + return; + } + else if (typeAttribute == "PERCENTUAL") + { + sinteticModel2.set_Value(string.Format("{0} %", x.GetValue(sintetico))); + sinteticModels.Add(sinteticModel2); + return; + } + else + { + sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico))); + sinteticModels.Add(sinteticModel2); + return; + } + } + default: + { + if (length == 13) + { + if (typeAttribute != "VALORDECIMAL2") + { + sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico))); + sinteticModels.Add(sinteticModel2); + return; + } + num = (decimal)x.GetValue(sintetico); + sinteticModel2.set_Value(num.ToString("n2")); + sinteticModels.Add(sinteticModel2); + return; + } + else + { + sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico))); + sinteticModels.Add(sinteticModel2); + return; + } + } + } + SinteticModel sinteticModel3 = sinteticModel2; + value = (DateTime?)x.GetValue(sintetico); + if (value.HasValue) + { + valueOrDefault = value.GetValueOrDefault(); + str = valueOrDefault.ToString("d"); + } + else + { + str = null; + } + sinteticModel3.set_Value(str); + sinteticModels.Add(sinteticModel2); + return; + } + sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico))); + sinteticModels.Add(sinteticModel2); + return; + Label1: + nullable = new TipoRestricao?(66); + goto Label0; + Label2: + nullable = new TipoRestricao?(70); + goto Label0; + Label3: + nullable = new TipoRestricao?(69); + goto Label0; + }); + return sinteticModels; + } + + public static async Task ContruirLista(DataGrid grid, Relatorio relatorio) + { + List list = await (new ConfuguracoesServico()).BuscarParametros(relatorio); + if (list == null || list.Count == 0) + { + list = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public).Select((PropertyInfo x) => { + ParametrosRelatorio parametrosRelatorio = new ParametrosRelatorio(); + parametrosRelatorio.set_Campo(x.Name); + parametrosRelatorio.set_Header(x.GetDescriptionAttribute()); + parametrosRelatorio.set_Tipo(x.GetTypeAttribute()); + parametrosRelatorio.set_Relatorio(relatorio); + parametrosRelatorio.set_Width(0); + parametrosRelatorio.set_Ordem(0); + return parametrosRelatorio; + }).ToList(); + } + if (!Recursos.Usuario.get_Administrador()) + { + list = await Funcoes.GetRestricoesColunas(list); + } + List parametrosRelatorios = list; + IOrderedEnumerable ordem = + from in parametrosRelatorios + orderby x.get_Ordem() + select ; + ordem.ThenBy((ParametrosRelatorio x) => x.get_Header()).ToList().ForEach((ParametrosRelatorio x) => { + char chr; + object upper; + if (x.get_Tipo() == "INVALID") + { + return; + } + if (x.get_Campo() == "DataControle" && !Recursos.Usuario.get_Administrador()) + { + List configuracoes = Recursos.Configuracoes; + Func u003cu003e9_324 = Funcoes.u003cu003ec__32.u003cu003e9__32_4; + if (u003cu003e9_324 == null) + { + u003cu003e9_324 = (ConfiguracaoSistema c) => c.get_Configuracao() == 33; + Funcoes.u003cu003ec__32.u003cu003e9__32_4 = u003cu003e9_324; + } + if (configuracoes.Any(u003cu003e9_324)) + { + return; + } + } + string str = ""; + Style item = (Style)System.Windows.Application.Current.Resources["VerticalCenterStyle3"]; + Style style = (Style)System.Windows.Application.Current.Resources["MaterialDesignDataGridColumnHeaderNew"]; + string tipo = x.get_Tipo(); + if (tipo != null) + { + int length = tipo.Length; + switch (length) + { + case 4: + { + if (tipo == "DATA") + { + break; + } + ObservableCollection columns = grid.Columns; + MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); + string header = x.get_Header(); + if (header != null) + { + upper = header.ToUpper(); + } + else + { + upper = null; + } + if (upper == null) + { + upper = x.get_Campo().ToUpper(); + } + materialDataGridTextColumn.Header = upper; + materialDataGridTextColumn.Binding = new Binding() + { + Path = new PropertyPath(x.get_Campo(), Array.Empty()), + StringFormat = str, + Mode = BindingMode.TwoWay, + UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged + }; + materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); + materialDataGridTextColumn.ElementStyle = item; + materialDataGridTextColumn.HeaderStyle = style; + columns.Add(materialDataGridTextColumn); + return; + } + case 5: + { + chr = tipo[0]; + if (chr == 'D') + { + if (tipo == "DATA?") + { + break; + } + ObservableCollection columns = grid.Columns; + MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); + string header = x.get_Header(); + if (header != null) + { + upper = header.ToUpper(); + } + else + { + upper = null; + } + if (upper == null) + { + upper = x.get_Campo().ToUpper(); + } + materialDataGridTextColumn.Header = upper; + materialDataGridTextColumn.Binding = new Binding() + { + Path = new PropertyPath(x.get_Campo(), Array.Empty()), + StringFormat = str, + Mode = BindingMode.TwoWay, + UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged + }; + materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); + materialDataGridTextColumn.ElementStyle = item; + materialDataGridTextColumn.HeaderStyle = style; + columns.Add(materialDataGridTextColumn); + return; + } + else if (chr != 'V') + { + ObservableCollection columns = grid.Columns; + MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); + string header = x.get_Header(); + if (header != null) + { + upper = header.ToUpper(); + } + else + { + upper = null; + } + if (upper == null) + { + upper = x.get_Campo().ToUpper(); + } + materialDataGridTextColumn.Header = upper; + materialDataGridTextColumn.Binding = new Binding() + { + Path = new PropertyPath(x.get_Campo(), Array.Empty()), + StringFormat = str, + Mode = BindingMode.TwoWay, + UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged + }; + materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); + materialDataGridTextColumn.ElementStyle = item; + materialDataGridTextColumn.HeaderStyle = style; + columns.Add(materialDataGridTextColumn); + return; + } + else if (tipo == "VALOR") + { + str = "c"; + item = (Style)System.Windows.Application.Current.Resources["HorizontalRightStyle"]; + style = (Style)System.Windows.Application.Current.Resources["HorizontalRightHeaderStyleNew"]; + ObservableCollection columns = grid.Columns; + MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); + string header = x.get_Header(); + if (header != null) + { + upper = header.ToUpper(); + } + else + { + upper = null; + } + if (upper == null) + { + upper = x.get_Campo().ToUpper(); + } + materialDataGridTextColumn.Header = upper; + materialDataGridTextColumn.Binding = new Binding() + { + Path = new PropertyPath(x.get_Campo(), Array.Empty()), + StringFormat = str, + Mode = BindingMode.TwoWay, + UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged + }; + materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); + materialDataGridTextColumn.ElementStyle = item; + materialDataGridTextColumn.HeaderStyle = style; + columns.Add(materialDataGridTextColumn); + return; + } + else + { + ObservableCollection columns = grid.Columns; + MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); + string header = x.get_Header(); + if (header != null) + { + upper = header.ToUpper(); + } + else + { + upper = null; + } + if (upper == null) + { + upper = x.get_Campo().ToUpper(); + } + materialDataGridTextColumn.Header = upper; + materialDataGridTextColumn.Binding = new Binding() + { + Path = new PropertyPath(x.get_Campo(), Array.Empty()), + StringFormat = str, + Mode = BindingMode.TwoWay, + UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged + }; + materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); + materialDataGridTextColumn.ElementStyle = item; + materialDataGridTextColumn.HeaderStyle = style; + columns.Add(materialDataGridTextColumn); + return; + } + } + case 6: + case 7: + case 8: + { + ObservableCollection columns = grid.Columns; + MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); + string header = x.get_Header(); + if (header != null) + { + upper = header.ToUpper(); + } + else + { + upper = null; + } + if (upper == null) + { + upper = x.get_Campo().ToUpper(); + } + materialDataGridTextColumn.Header = upper; + materialDataGridTextColumn.Binding = new Binding() + { + Path = new PropertyPath(x.get_Campo(), Array.Empty()), + StringFormat = str, + Mode = BindingMode.TwoWay, + UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged + }; + materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); + materialDataGridTextColumn.ElementStyle = item; + materialDataGridTextColumn.HeaderStyle = style; + columns.Add(materialDataGridTextColumn); + return; + } + case 9: + { + if (tipo == "DATA/TIME") + { + goto Label1; + } + ObservableCollection columns = grid.Columns; + MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); + string header = x.get_Header(); + if (header != null) + { + upper = header.ToUpper(); + } + else + { + upper = null; + } + if (upper == null) + { + upper = x.get_Campo().ToUpper(); + } + materialDataGridTextColumn.Header = upper; + materialDataGridTextColumn.Binding = new Binding() + { + Path = new PropertyPath(x.get_Campo(), Array.Empty()), + StringFormat = str, + Mode = BindingMode.TwoWay, + UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged + }; + materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); + materialDataGridTextColumn.ElementStyle = item; + materialDataGridTextColumn.HeaderStyle = style; + columns.Add(materialDataGridTextColumn); + return; + } + case 10: + { + chr = tipo[0]; + if (chr == 'D') + { + if (tipo == "DATA/TIME?") + { + goto Label1; + } + ObservableCollection columns = grid.Columns; + MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); + string header = x.get_Header(); + if (header != null) + { + upper = header.ToUpper(); + } + else + { + upper = null; + } + if (upper == null) + { + upper = x.get_Campo().ToUpper(); + } + materialDataGridTextColumn.Header = upper; + materialDataGridTextColumn.Binding = new Binding() + { + Path = new PropertyPath(x.get_Campo(), Array.Empty()), + StringFormat = str, + Mode = BindingMode.TwoWay, + UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged + }; + materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); + materialDataGridTextColumn.ElementStyle = item; + materialDataGridTextColumn.HeaderStyle = style; + columns.Add(materialDataGridTextColumn); + return; + } + else if (chr == 'P') + { + if (tipo == "PERCENTUAL") + { + str = "{0:0.00}%"; + item = (Style)System.Windows.Application.Current.Resources["HorizontalRightStyle"]; + style = (Style)System.Windows.Application.Current.Resources["HorizontalRightHeaderStyleNew"]; + ObservableCollection columns = grid.Columns; + MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); + string header = x.get_Header(); + if (header != null) + { + upper = header.ToUpper(); + } + else + { + upper = null; + } + if (upper == null) + { + upper = x.get_Campo().ToUpper(); + } + materialDataGridTextColumn.Header = upper; + materialDataGridTextColumn.Binding = new Binding() + { + Path = new PropertyPath(x.get_Campo(), Array.Empty()), + StringFormat = str, + Mode = BindingMode.TwoWay, + UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged + }; + materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); + materialDataGridTextColumn.ElementStyle = item; + materialDataGridTextColumn.HeaderStyle = style; + columns.Add(materialDataGridTextColumn); + return; + } + else + { + ObservableCollection columns = grid.Columns; + MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); + string header = x.get_Header(); + if (header != null) + { + upper = header.ToUpper(); + } + else + { + upper = null; + } + if (upper == null) + { + upper = x.get_Campo().ToUpper(); + } + materialDataGridTextColumn.Header = upper; + materialDataGridTextColumn.Binding = new Binding() + { + Path = new PropertyPath(x.get_Campo(), Array.Empty()), + StringFormat = str, + Mode = BindingMode.TwoWay, + UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged + }; + materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); + materialDataGridTextColumn.ElementStyle = item; + materialDataGridTextColumn.HeaderStyle = style; + columns.Add(materialDataGridTextColumn); + return; + } + } + else if (chr != 'Q') + { + ObservableCollection columns = grid.Columns; + MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); + string header = x.get_Header(); + if (header != null) + { + upper = header.ToUpper(); + } + else + { + upper = null; + } + if (upper == null) + { + upper = x.get_Campo().ToUpper(); + } + materialDataGridTextColumn.Header = upper; + materialDataGridTextColumn.Binding = new Binding() + { + Path = new PropertyPath(x.get_Campo(), Array.Empty()), + StringFormat = str, + Mode = BindingMode.TwoWay, + UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged + }; + materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); + materialDataGridTextColumn.ElementStyle = item; + materialDataGridTextColumn.HeaderStyle = style; + columns.Add(materialDataGridTextColumn); + return; + } + else if (tipo == "QUANTIDADE") + { + item = (Style)System.Windows.Application.Current.Resources["HorizontalCenterStyle2"]; + style = (Style)System.Windows.Application.Current.Resources["HorizontalCenterHeaderStyleNew"]; + ObservableCollection columns = grid.Columns; + MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); + string header = x.get_Header(); + if (header != null) + { + upper = header.ToUpper(); + } + else + { + upper = null; + } + if (upper == null) + { + upper = x.get_Campo().ToUpper(); + } + materialDataGridTextColumn.Header = upper; + materialDataGridTextColumn.Binding = new Binding() + { + Path = new PropertyPath(x.get_Campo(), Array.Empty()), + StringFormat = str, + Mode = BindingMode.TwoWay, + UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged + }; + materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); + materialDataGridTextColumn.ElementStyle = item; + materialDataGridTextColumn.HeaderStyle = style; + columns.Add(materialDataGridTextColumn); + return; + } + else + { + ObservableCollection columns = grid.Columns; + MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); + string header = x.get_Header(); + if (header != null) + { + upper = header.ToUpper(); + } + else + { + upper = null; + } + if (upper == null) + { + upper = x.get_Campo().ToUpper(); + } + materialDataGridTextColumn.Header = upper; + materialDataGridTextColumn.Binding = new Binding() + { + Path = new PropertyPath(x.get_Campo(), Array.Empty()), + StringFormat = str, + Mode = BindingMode.TwoWay, + UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged + }; + materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); + materialDataGridTextColumn.ElementStyle = item; + materialDataGridTextColumn.HeaderStyle = style; + columns.Add(materialDataGridTextColumn); + return; + } + } + default: + { + if (length != 13) + { + ObservableCollection columns = grid.Columns; + MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); + string header = x.get_Header(); + if (header != null) + { + upper = header.ToUpper(); + } + else + { + upper = null; + } + if (upper == null) + { + upper = x.get_Campo().ToUpper(); + } + materialDataGridTextColumn.Header = upper; + materialDataGridTextColumn.Binding = new Binding() + { + Path = new PropertyPath(x.get_Campo(), Array.Empty()), + StringFormat = str, + Mode = BindingMode.TwoWay, + UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged + }; + materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); + materialDataGridTextColumn.ElementStyle = item; + materialDataGridTextColumn.HeaderStyle = style; + columns.Add(materialDataGridTextColumn); + return; + } + else if (tipo == "VALORDECIMAL2") + { + str = "n2"; + item = (Style)System.Windows.Application.Current.Resources["HorizontalRightStyle"]; + style = (Style)System.Windows.Application.Current.Resources["HorizontalRightHeaderStyleNew"]; + ObservableCollection columns = grid.Columns; + MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); + string header = x.get_Header(); + if (header != null) + { + upper = header.ToUpper(); + } + else + { + upper = null; + } + if (upper == null) + { + upper = x.get_Campo().ToUpper(); + } + materialDataGridTextColumn.Header = upper; + materialDataGridTextColumn.Binding = new Binding() + { + Path = new PropertyPath(x.get_Campo(), Array.Empty()), + StringFormat = str, + Mode = BindingMode.TwoWay, + UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged + }; + materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); + materialDataGridTextColumn.ElementStyle = item; + materialDataGridTextColumn.HeaderStyle = style; + columns.Add(materialDataGridTextColumn); + return; + } + else + { + ObservableCollection columns = grid.Columns; + MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); + string header = x.get_Header(); + if (header != null) + { + upper = header.ToUpper(); + } + else + { + upper = null; + } + if (upper == null) + { + upper = x.get_Campo().ToUpper(); + } + materialDataGridTextColumn.Header = upper; + materialDataGridTextColumn.Binding = new Binding() + { + Path = new PropertyPath(x.get_Campo(), Array.Empty()), + StringFormat = str, + Mode = BindingMode.TwoWay, + UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged + }; + materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); + materialDataGridTextColumn.ElementStyle = item; + materialDataGridTextColumn.HeaderStyle = style; + columns.Add(materialDataGridTextColumn); + return; + } + } + } + str = "d"; + item = (Style)System.Windows.Application.Current.Resources["HorizontalCenterStyle2"]; + style = (Style)System.Windows.Application.Current.Resources["HorizontalCenterHeaderStyleNew"]; + } + ObservableCollection columns = grid.Columns; + MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); + string header = x.get_Header(); + if (header != null) + { + upper = header.ToUpper(); + } + else + { + upper = null; + } + if (upper == null) + { + upper = x.get_Campo().ToUpper(); + } + materialDataGridTextColumn.Header = upper; + materialDataGridTextColumn.Binding = new Binding() + { + Path = new PropertyPath(x.get_Campo(), Array.Empty()), + StringFormat = str, + Mode = BindingMode.TwoWay, + UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged + }; + materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); + materialDataGridTextColumn.ElementStyle = item; + materialDataGridTextColumn.HeaderStyle = style; + columns.Add(materialDataGridTextColumn); + return; + Label1: + str = "G"; + item = (Style)System.Windows.Application.Current.Resources["HorizontalCenterStyle2"]; + style = (Style)System.Windows.Application.Current.Resources["HorizontalCenterHeaderStyleNew"]; + ObservableCollection columns = grid.Columns; + MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); + string header = x.get_Header(); + if (header != null) + { + upper = header.ToUpper(); + } + else + { + upper = null; + } + if (upper == null) + { + upper = x.get_Campo().ToUpper(); + } + materialDataGridTextColumn.Header = upper; + materialDataGridTextColumn.Binding = new Binding() + { + Path = new PropertyPath(x.get_Campo(), Array.Empty()), + StringFormat = str, + Mode = BindingMode.TwoWay, + UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged + }; + materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); + materialDataGridTextColumn.ElementStyle = item; + materialDataGridTextColumn.HeaderStyle = style; + columns.Add(materialDataGridTextColumn); + return; + }); + } + + public static string ConvertGaragemTrabalhoEstudoCalculo(this GaragemTrabalhoEstudo garagemTrabalhoEstudo) + { + switch (garagemTrabalhoEstudo) + { + case 0: + { + return "0"; + } + case 1: + { + return "1"; + } + case 2: + { + return "2"; + } + case 3: + { + return string.Empty; + } + case 4: + case 5: + { + return "3"; + } + default: + { + return string.Empty; + } + } + } + + public static TipoTela? ConvertTela(string name) + { + return new TipoTela?(((TipoTela[])Enum.GetValues(typeof(TipoTela))).ToList().FirstOrDefault((TipoTela x) => Gestor.Common.Validation.ValidationHelper.GetEntity(x) == name)); + } + + public static TempoHabilitacao ConvertTempoHabilitacao(int tempoHabilitacao = 0) + { + if (tempoHabilitacao == 1) + { + return 0; + } + if (tempoHabilitacao == 2) + { + return 1; + } + if (tempoHabilitacao == 3) + { + return 2; + } + if (tempoHabilitacao == 4) + { + return 3; + } + if (tempoHabilitacao == 5) + { + return 4; + } + if (tempoHabilitacao == 6) + { + return 5; + } + if (tempoHabilitacao == 7) + { + return 6; + } + if (tempoHabilitacao == 8) + { + return 7; + } + if (tempoHabilitacao == 9) + { + return 8; + } + if (tempoHabilitacao == 10) + { + return 9; + } + if (tempoHabilitacao >= 11) + { + return 10; + } + return 0; + } + + public static string ConvertTempoHabilitacaoCalculo(this DateTime tempoHabilitacao) + { + if (tempoHabilitacao == DateTime.MinValue) + { + return "0"; + } + int year = DateTime.Now.Year - tempoHabilitacao.Year; + if (year >= 11) + { + return "11"; + } + return year.ToString(); + } + + public static string ConvertTipoSeguroCalculo(this TipoSeguro tipoSeguro) + { + if (tipoSeguro - 1 <= 1) + { + return "1"; + } + return "0"; + } + + public static void CopyToClipboard(this string text) + { + try + { + Clipboard.SetText(text); + } + catch (Exception exception) + { + } + } + + public static string CreateCard(string title, string body, bool pageBreak = false) + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append((pageBreak ? "
" : "
")); + stringBuilder.Append("
"); + stringBuilder.Append(string.Concat("
", title, "
")); + stringBuilder.Append(body); + stringBuilder.Append("
"); + stringBuilder.Append("
"); + return stringBuilder.ToString(); + } + + public static async Task CriarAssistencia(Assistance assistance) + { + return await Gestor.Application.Helpers.Connection.Post("Assistance", assistance); + } + + public static async Task CriarCartao(Gestor.Model.Domain.Card.Card card) + { + return await Gestor.Application.Helpers.Connection.Post("Card", card); + } + + public static async Task Criarlogo(Logo logo) + { + return await Gestor.Application.Helpers.Connection.Post("Card/Logo", logo); + } + + public static string CriarRecibo(Vendedor vendedor, decimal valor, Filtros filtro, bool segundavia) + { + string str = (segundavia ? " acima listados" : string.Format(" no periodo de {0:d} até {1:d}", filtro.get_Inicio(), filtro.get_Fim())); + string str1 = "CPF"; + if (vendedor.get_Documento() != null && Gestor.Common.Validation.ValidationHelper.OnlyNumber(vendedor.get_Documento()).Length > 12) + { + str1 = "CNPJ"; + } + object[] nome = new object[] { vendedor.get_Nome(), str1, vendedor.get_Documento(), Recursos.Empresa.get_Nome(), valor, str, null }; + nome[6] = Funcoes.GetNetworkTime().Date; + return string.Format("
\r\n
RECIBO DE PAGAMENTO
\r\n
\r\n
Declaração de recebimento de Comissão
\r\n

Eu {0}, portador(a) do {1} {2} declaro que recebi de {3} o valor de {4:c} referente a comissão dos seguros{5}.

\r\n\r\n

Para maior clareza firmo(a) o presente recibo para que produza os seus efeitos, dando plena, rasa e irrevogável quitação, pelo valor recebido.

\r\n\r\n

_____________________________________________________________
{6:d}

\r\n
\r\n
", nome); + } + + public static async Task CriarSeguradora(AssistenciaCia cia) + { + return await Gestor.Application.Helpers.Connection.Post("Assistance/Seguradora", cia); + } + + public static void DatePicker_OnLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) + { + DatePicker datePicker = (DatePicker)sender; + datePicker.Text = Gestor.Common.Validation.ValidationHelper.FormatDate(datePicker.Text); + } + + public static void DatePicker_PreviewKeyDown(object sender, KeyEventArgs e) + { + if (e.Key != Key.Return) + { + return; + } + DatePicker str = (DatePicker)sender; + DateTime date = Funcoes.GetNetworkTime().Date; + str.Text = date.ToString("dd/MM/yyyy"); + } + + public static void Destroy() + where T : Window + { + object obj = System.Windows.Application.Current.Windows.OfType().FirstOrDefault(); + if (obj == null) + { + return; + } + ((Window)obj).Close(); + } + + public static void Destroy(string title) + where T : Window + { + object obj = System.Windows.Application.Current.Windows.OfType().FirstOrDefault((T x) => x.Title == title); + if (obj == null) + { + return; + } + ((Window)obj).Close(); + } + + public static string DiaDaSemana(this int? dia) + { + if (!dia.HasValue) + { + return ""; + } + switch (dia.Value) + { + case 0: + { + return "DOMINGO"; + } + case 1: + { + return "SEGUNDA-FEIRA"; + } + case 2: + { + return "TERÇA-FEIRA"; + } + case 3: + { + return "QUARTA-FEIRA"; + } + case 4: + { + return "QUINTA-FEIRA"; + } + case 5: + { + return "SEXTA-FEIRA"; + } + case 6: + { + return "SABADO"; + } + } + return ""; + } + + public static IEnumerable DistinctBy(IEnumerable source, Func keySelector) + { + HashSet tKeys = new HashSet(); + foreach (TSource tSource in source) + { + if (!tKeys.Add(keySelector(tSource))) + { + continue; + } + yield return tSource; + } + } + + public static bool EnviarWhatsapp(this string numero, string anotacoes = null) + { + bool flag; + Uri uri = (string.IsNullOrEmpty(anotacoes) ? Recursos.WhatsAppLink.SetQuery("phone", numero, true) : Recursos.WhatsAppLink.AddQuery("phone", numero).SetQuery("text", anotacoes, true)); + try + { + Process.Start(new ProcessStartInfo(uri.AbsoluteUri)); + flag = true; + } + catch (Exception exception) + { + uri.AbsoluteUri.CopyToClipboard(); + flag = false; + } + return flag; + } + + public static async Task ExcluirBaixa(Parcela parcela, List repasses, List parcelas = null) + { + Parcela parcela1; + string str; + decimal num1; + List parcelas1; + List parcelas2; + Funcoes.u003cu003ec__DisplayClass9_0 variable; + ParcelaServico parcelaServico; + VendedorServico vendedorServico; + Parcela parcela2 = parcela; + ParcelaServico parcelaServico1 = new ParcelaServico(); + if (parcela2.get_SubTipo() != 1 || parcela2.get_Documento().get_TipoRecebimento().GetValueOrDefault() != 1) + { + List list = repasses.Where((VendedorParcela x) => { + if (x.get_Parcela().get_Id() != parcela2.get_Id()) + { + return false; + } + return !x.get_DataPagamento().HasValue; + }).ToList(); + List vendedorParcelas1 = list; + vendedorParcelas1.ForEach((VendedorParcela x) => { + x.set_DataPrePagamento(null); + VendedorParcela vendedorParcela = x; + decimal? valorTotal = x.get_ValorTotal(); + vendedorParcela.set_ValorRepasse(new decimal?((valorTotal.HasValue ? valorTotal.GetValueOrDefault() : Funcoes.CalculaPagamento(x, x.get_Parcela(), decimal.Zero)))); + }); + parcela2.set_ValorComissao(decimal.Zero); + parcela2.set_ValorComDesconto(decimal.Zero); + DateTime? nullable1 = null; + parcela2.set_DataRecebimento(nullable1); + nullable1 = null; + parcela2.set_DataCredito(nullable1); + parcela2.set_ValorRealizado(decimal.Zero); + Parcela parcela3 = await parcelaServico1.Save(parcela2, parcelas, list, false); + parcela2 = parcela3; + if (!parcelaServico1.Sucesso) + { + await Funcoes.MostrarErro(191); + parcela1 = parcela2; + variable = null; + parcelaServico1 = null; + parcelaServico = null; + vendedorServico = null; + return parcela1; + } + } + else + { + List list1 = repasses.Where((VendedorParcela x) => { + bool valueOrDefault; + if (x.get_Parcela().get_SubTipo() == 1) + { + Repasse repasse = x.get_Repasse(); + valueOrDefault = (repasse != null ? repasse.get_Forma().GetValueOrDefault() == 1 : false); + if (valueOrDefault) + { + if (x.get_Parcela().get_Id() == this.parcela.get_Id()) + { + return true; + } + return !x.get_DataPrePagamento().HasValue; + } + } + return false; + }).ToList(); + decimal premioLiquido = parcela2.get_Documento().get_PremioLiquido(); + num1 = (parcela2.get_Documento().get_AdicionalComiss() ? parcela2.get_Documento().get_PremioAdicional() : decimal.Zero); + decimal comissao = ((premioLiquido + num1) * parcela2.get_Documento().get_Comissao()) * new decimal(1, 0, 0, false, 2); + List vendedorParcelas2 = list1; + List list2 = ( + from x in vendedorParcelas2 + group x by x.get_Vendedor().get_Id()).Select, VendedorParcela>((IGrouping x) => { + TipoRepasse? nullable; + decimal? valorTotal; + decimal num; + TipoRepasse? tipo; + bool valueOrDefault; + bool hasValue; + decimal? valorRepasse; + bool flag; + VendedorParcela vendedorParcela = new VendedorParcela(); + vendedorParcela.set_Repasse(x.First().get_Repasse()); + vendedorParcela.set_Parcela(parcela2); + vendedorParcela.set_Documento(parcela2.get_Documento()); + VendedorParcela vendedorParcela1 = x.First(); + if (vendedorParcela1 != null) + { + Repasse repasse = vendedorParcela1.get_Repasse(); + if (repasse != null) + { + tipo = repasse.get_Tipo(); + } + else + { + nullable = null; + tipo = nullable; + } + nullable = tipo; + valueOrDefault = nullable.GetValueOrDefault() != 3; + } + else + { + valueOrDefault = true; + } + if (valueOrDefault) + { + VendedorParcela vendedorParcela2 = x.First(); + if (vendedorParcela2 != null) + { + valorTotal = vendedorParcela2.get_ValorTotal(); + hasValue = valorTotal.HasValue; + } + else + { + hasValue = false; + } + if (hasValue) + { + VendedorParcela vendedorParcela3 = x.First(); + if (vendedorParcela3 != null) + { + valorTotal = vendedorParcela3.get_ValorTotal(); + num = new decimal(); + flag = !((valorTotal.GetValueOrDefault() == num) & valorTotal.HasValue); + } + else + { + flag = true; + } + if (!flag) + { + goto Label1; + } + VendedorParcela vendedorParcela4 = x.First(); + if (vendedorParcela4 != null) + { + valorRepasse = vendedorParcela4.get_ValorTotal(); + vendedorParcela.set_ValorTotal(valorRepasse); + vendedorParcela.set_Vendedor(x.First().get_Vendedor()); + vendedorParcela.set_PorcentagemRepasse(x.First().get_PorcentagemRepasse()); + vendedorParcela.set_TipoVendedor(x.First().get_TipoVendedor()); + vendedorParcela.set_CoCorretagem(x.First().get_CoCorretagem()); + return vendedorParcela; + } + else + { + valorTotal = null; + valorRepasse = valorTotal; + vendedorParcela.set_ValorTotal(valorRepasse); + vendedorParcela.set_Vendedor(x.First().get_Vendedor()); + vendedorParcela.set_PorcentagemRepasse(x.First().get_PorcentagemRepasse()); + vendedorParcela.set_TipoVendedor(x.First().get_TipoVendedor()); + vendedorParcela.set_CoCorretagem(x.First().get_CoCorretagem()); + return vendedorParcela; + } + } + Label1: + num = comissao; + valorTotal = x.First().get_PorcentagemRepasse(); + valorRepasse = (valorTotal.HasValue ? new decimal?((num * valorTotal.GetValueOrDefault()) * new decimal(1, 0, 0, false, 2)) : null); + } + else + { + valorRepasse = x.First().get_ValorRepasse(); + } + vendedorParcela.set_ValorTotal(valorRepasse); + vendedorParcela.set_Vendedor(x.First().get_Vendedor()); + vendedorParcela.set_PorcentagemRepasse(x.First().get_PorcentagemRepasse()); + vendedorParcela.set_TipoVendedor(x.First().get_TipoVendedor()); + vendedorParcela.set_CoCorretagem(x.First().get_CoCorretagem()); + return vendedorParcela; + }).ToList(); + parcelas1 = (parcelas != null ? parcelas.Where((Parcela x) => { + if (x.get_SubTipo() != 1) + { + return false; + } + return x.get_NumeroParcela() < this.parcela.get_NumeroParcela(); + }).ToList() : new List()); + List parcelas3 = parcelas1; + list2.ForEach((VendedorParcela y) => { + VendedorParcela vendedorParcela = y; + decimal? valorTotal = y.get_ValorTotal(); + IEnumerable vendedorParcelas = repasses.Where((VendedorParcela x) => { + bool valueOrDefault; + if (x.get_Parcela().get_SubTipo() == 1) + { + Repasse repasse = x.get_Repasse(); + valueOrDefault = (repasse != null ? repasse.get_Forma().GetValueOrDefault() == 1 : false); + if (valueOrDefault && x.get_Vendedor().get_Id() == y.get_Vendedor().get_Id()) + { + List cSu0024u003cu003e8_locals2 = parcelas3; + Func u003cu003e9_912 = Funcoes.u003cu003ec.u003cu003e9__9_12; + if (u003cu003e9_912 == null) + { + u003cu003e9_912 = (Parcela z) => z.get_Id(); + Funcoes.u003cu003ec.u003cu003e9__9_12 = u003cu003e9_912; + } + return cSu0024u003cu003e8_locals2.Select(u003cu003e9_912).ToList().Contains(x.get_Parcela().get_Id()); + } + } + return false; + }); + Func u003cu003e9_911 = Funcoes.u003cu003ec.u003cu003e9__9_11; + if (u003cu003e9_911 == null) + { + u003cu003e9_911 = (VendedorParcela x) => x.get_ValorRepasse(); + Funcoes.u003cu003ec.u003cu003e9__9_11 = u003cu003e9_911; + } + decimal? nullable = vendedorParcelas.Sum(u003cu003e9_911); + vendedorParcela.set_ValorRepasse((valorTotal.HasValue & nullable.HasValue ? new decimal?(valorTotal.GetValueOrDefault() - nullable.GetValueOrDefault()) : null)); + }); + parcelas2 = (parcelas != null ? parcelas.Where((Parcela x) => { + if (x.get_SubTipo() != 1) + { + return false; + } + return x.get_NumeroParcela() > this.parcela.get_NumeroParcela(); + }).ToList() : new List()); + List list3 = parcelas2; + list3.Add(parcela2); + List vendedorParcelas3 = repasses.Where((VendedorParcela x) => { + bool valueOrDefault; + if (x.get_Parcela().get_SubTipo() == 1) + { + Repasse repasse = x.get_Repasse(); + valueOrDefault = (repasse != null ? repasse.get_Forma().GetValueOrDefault() == 1 : false); + if (valueOrDefault) + { + if (x.get_Parcela().get_NumeroParcela() >= this.parcela.get_NumeroParcela()) + { + return true; + } + return !x.get_DataPrePagamento().HasValue; + } + } + return false; + }).ToList(); + if (!await parcelaServico1.DeletePagamentoRange(vendedorParcelas3)) + { + await Funcoes.MostrarErro(191); + parcela1 = parcela2; + variable = null; + parcelaServico1 = null; + parcelaServico = null; + vendedorServico = null; + return parcela1; + } + else if (await parcelaServico1.SaveRange(list2)) + { + List parcelas4 = list3; + list3 = parcelas4.Where((Parcela dParcela) => { + if (dParcela.get_ValorComissao() != decimal.Zero || dParcela.get_ValorComissao() != decimal.Zero || dParcela.get_DataRecebimento().HasValue || dParcela.get_DataCredito().HasValue) + { + return true; + } + return dParcela.get_ValorRealizado() != decimal.Zero; + }).ToList(); + if (list3 != null && list3.Count > 0) + { + list3.ForEach((Parcela dParcela) => { + dParcela.set_Documento(this.parcela.get_Documento()); + dParcela.set_ValorComissao(decimal.Zero); + dParcela.set_ValorComDesconto(decimal.Zero); + DateTime? nullable = null; + dParcela.set_DataRecebimento(nullable); + nullable = null; + dParcela.set_DataCredito(nullable); + dParcela.set_ValorRealizado(decimal.Zero); + }); + list3 = await parcelaServico1.UpdateRange(list3); + if (parcelaServico1.Sucesso) + { + parcela2 = list3.FirstOrDefault((Parcela x) => x.get_Id() == this.parcela.get_Id()); + } + else + { + await Funcoes.MostrarErro(191); + parcela1 = parcela2; + variable = null; + parcelaServico1 = null; + parcelaServico = null; + vendedorServico = null; + return parcela1; + } + } + list2 = null; + list3 = null; + } + else + { + await Funcoes.MostrarErro(191); + parcela1 = parcela2; + variable = null; + parcelaServico1 = null; + parcelaServico = null; + vendedorServico = null; + return parcela1; + } + } + ApoliceServico apoliceServico = new ApoliceServico(); + parcelaServico = new ParcelaServico(); + vendedorServico = new VendedorServico(); + if (parcela2 != null) + { + Documento documento = await apoliceServico.BuscarApoliceAsync(parcela2.get_Documento().get_Id(), false, false); + Documento documento1 = documento; + ObservableCollection observableCollection = await parcelaServico.BuscarParcelasAsync(documento.get_Id()); + documento1.set_Parcelas(observableCollection); + documento1 = null; + List vendedorParcelas4 = await vendedorServico.BuscaRepasse(documento.get_Id()); + foreach (Parcela parcela4 in documento.get_Parcelas()) + { + foreach (VendedorParcela vendedorParcela5 in vendedorParcelas4) + { + if (vendedorParcela5.get_Parcela().get_Id() != parcela4.get_Id()) + { + continue; + } + if (parcela4.get_Vendedores() == null) + { + parcela4.set_Vendedores(new ObservableCollection()); + } + parcela4.get_Vendedores().Add(vendedorParcela5); + } + } + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(2); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(Funcoes.GetNetworkTime()); + Documento documento2 = documento; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(documento2, jsonSerializerSetting)); + registroLog.set_EntidadeId(documento.get_Id()); + registroLog.set_Tela(2); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + RegistroLog registroLog1 = registroLog; + await Task.Run(() => { + using (UnitOfWork commited = Instancia.Commited) + { + commited.get_RegistroLogRepository().SaveOrUpdate(registroLog1); + commited.Commit(); + } + }); + documento = null; + } + parcela1 = parcela2; + variable = null; + parcelaServico1 = null; + parcelaServico = null; + vendedorServico = null; + return parcela1; + } + + public static async Task ExcluirPagamento(VendedorParcela pagamento) + { + pagamento.set_DataPagamento(null); + ParcelaServico parcelaServico = new ParcelaServico() + { + Sucesso = true + }; + await parcelaServico.Save(pagamento); + bool sucesso = parcelaServico.Sucesso; + parcelaServico = null; + return sucesso; + } + + public static string ExportarHtml(TipoRelatorio tipo, string dados, string porcentagem = "60", string orientation = "landscape", bool search = false, string grafico = "") + { + string str = string.Format("DATA DE EMISSÃO DO RELATÓRIO EM {0:G}", Funcoes.GetNetworkTime()); + if (tipo.get_Inicio() != DateTime.MinValue && tipo.get_Nome() != "RELATÓRIO DE CLIENTE") + { + str = string.Format("PERÍODO DE {0:d} ATÉ {1:d}. DATA DE EMISSÃO DO RELATÓRIO EM {2:G}", tipo.get_Inicio(), tipo.get_Fim(), Funcoes.GetNetworkTime()); + } + string str1 = (!search ? "" : ""); + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append(Resources.RelatorioTemplate.Replace("{style}", str1).Replace("Orientation", orientation).Replace("{NomeRelatorio}", string.Concat(Recursos.Empresa.get_NomeSocial(), " - ", tipo.get_Nome())).Replace("{EmissaoRelatorio}", str).Replace("{Grafico}", grafico).Replace("{DadosRelatorio}", dados)); + return stringBuilder.ToString(); + } + + public static string ExportarMultipleHtml(TipoRelatorio tipo, string dados, string porcentagem = "60", string orientation = "landscape", bool search = false, string grafico = "") + { + string str = string.Format("DATA DE EMISSÃO DO RELATÓRIO EM {0:G}", Funcoes.GetNetworkTime()); + if (tipo.get_Inicio() != DateTime.MinValue && tipo.get_Nome() != "RELATÓRIO DE CLIENTE") + { + str = string.Format("PERÍODO DE {0:d} ATÉ {1:d}. DATA DE EMISSÃO DO RELATÓRIO EM {2:G}", tipo.get_Inicio(), tipo.get_Fim(), Funcoes.GetNetworkTime()); + } + string str1 = (!search ? "" : ""); + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append(Resources.RelatorioMultipleTemplate.Replace("{style}", str1).Replace("Orientation", orientation).Replace("{NomeRelatorio}", string.Concat(Recursos.Empresa.get_NomeSocial(), " - ", tipo.get_Nome())).Replace("{EmissaoRelatorio}", str).Replace("{Grafico}", grafico).Replace("{DadosRelatorio}", dados)); + return stringBuilder.ToString(); + } + + public static async Task GenerateMultipleTable(List> analiticos, List colunasOcultas, bool grafico = false, bool propertyName = false, string footer = "", ConfiguracaoImpressao config = null) + { + string str4; + string str5; + Action action2 = null; + if (analiticos == null) + { + str4 = ""; + } + else if (analiticos.Count != 0) + { + int tamanhoFonte = 0; + if (config != null) + { + tamanhoFonte = config.get_TamanhoFonte(); + } + str5 = (tamanhoFonte == 0 ? "" : string.Format("fs-{0}'", tamanhoFonte)); + string str6 = str5; + str4 = await Task.Run(() => { + StringBuilder stringBuilder2 = new StringBuilder(); + int num = 0; + foreach (List analitico in analiticos) + { + StringBuilder stringBuilder3 = new StringBuilder(); + StringBuilder stringBuilder4 = new StringBuilder(); + StringBuilder stringBuilder5 = new StringBuilder(); + int num1 = 0; + stringBuilder4.Append(Resources.HeaderTemplate.Replace("{Align}", "text-start").Replace("{Size}", "").Replace("{FontWeight}", "fw-bold").Replace("{Content}", analitico[0].get_NomeRelatorio())); + stringBuilder3.Append(Resources.RowTemplate.Replace("{Content}", stringBuilder4.ToString()).Replace("{Color}", "")); + List listagems = analitico; + Action u003cu003e9_1 = action2; + if (u003cu003e9_1 == null) + { + Action action = (Listagem x) => { + Sinal sinal; + string str; + char chr; + string str1; + PropertyInfo[] properties = x.GetType().GetProperties(); + Func u003cu003e9_222 = Funcoes.u003cu003ec.u003cu003e9__22_2; + if (u003cu003e9_222 == null) + { + u003cu003e9_222 = (PropertyInfo b) => b.Name == "Bold"; + Funcoes.u003cu003ec.u003cu003e9__22_2 = u003cu003e9_222; + } + PropertyInfo propertyInfo = ((IEnumerable)properties).FirstOrDefault(u003cu003e9_222); + bool flag = (propertyInfo == null ? false : (bool)propertyInfo.GetValue(x)); + Func u003cu003e9_223 = Funcoes.u003cu003ec.u003cu003e9__22_3; + if (u003cu003e9_223 == null) + { + u003cu003e9_223 = (PropertyInfo b) => b.Name == "Sinal"; + Funcoes.u003cu003ec.u003cu003e9__22_3 = u003cu003e9_223; + } + PropertyInfo propertyInfo1 = ((IEnumerable)properties).FirstOrDefault(u003cu003e9_223); + string str2 = (!(propertyInfo1 != null) || propertyInfo1.GetValue(x) == null || !Enum.TryParse(propertyInfo1.GetValue(x).ToString(), true, out sinal) || sinal != 1 ? "color: black;" : "color: red;"); + if (flag) + { + string.Concat(""); + } + else + { + string.Concat(""); + } + StringBuilder stringBuilder = new StringBuilder(); + PropertyInfo[] propertyInfoArray = properties; + for (int i = 0; i < (int)propertyInfoArray.Length; i++) + { + PropertyInfo propertyInfo2 = propertyInfoArray[i]; + if (propertyInfo2.Name != "ValidationEvent") + { + object obj = propertyInfo2.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault(); + if (obj != null) + { + string description = ((DescriptionAttribute)obj).Description; + if ((!propertyName || !colunasOcultas.Contains(propertyInfo2.Name)) && (propertyName || !colunasOcultas.Contains(description))) + { + object obj1 = propertyInfo2.GetCustomAttributes(typeof(TipoAttribute), true).FirstOrDefault(); + string description1 = ""; + if (obj1 != null) + { + description1 = ((TipoAttribute)obj1).get_Description(); + } + string str3 = "text-start"; + if (description1 != null) + { + switch (description1.Length) + { + case 4: + { + chr = description1[0]; + if (chr == 'D') + { + if (description1 == "DATA") + { + str3 = "text-center"; + str = (propertyInfo2.GetValue(x) == null || (DateTime)propertyInfo2.GetValue(x) == DateTime.MinValue ? "" : string.Format("{0:d}", (DateTime)propertyInfo2.GetValue(x))); + goto Label0; + } + else + { + goto Label1; + } + } + else if (chr != 'E') + { + goto Label1; + } + else if (description1 == "ENUM") + { + str = (propertyInfo2.GetValue(x) != null ? Gestor.Common.Validation.ValidationHelper.GetDescription((Enum)propertyInfo2.GetValue(x)) ?? "" : ""); + goto Label0; + } + else + { + goto Label1; + } + } + case 5: + { + chr = description1[0]; + if (chr == 'D') + { + if (description1 == "DATA?") + { + str3 = "text-center"; + str = (propertyInfo2.GetValue(x) != null ? string.Format("{0:d}", (DateTime?)propertyInfo2.GetValue(x)) : ""); + goto Label0; + } + else + { + goto Label1; + } + } + else if (chr != 'V') + { + goto Label1; + } + else if (description1 == "VALOR") + { + str3 = "text-end"; + str = (propertyInfo2.GetValue(x) != null ? string.Format("{0:c2}", (decimal)propertyInfo2.GetValue(x)) : ""); + goto Label0; + } + else + { + goto Label1; + } + } + case 6: + { + if (description1 != "VALOR?") + { + goto Label1; + } + str3 = "text-end"; + str = (propertyInfo2.GetValue(x) != null ? string.Format("{0:c2}", (decimal?)propertyInfo2.GetValue(x)) : ""); + goto Label0; + } + case 9: + { + if (description1 == "DATA/TIME") + { + break; + } + goto Label1; + } + case 10: + { + chr = description1[0]; + if (chr == 'D') + { + if (description1 == "DATA/TIME?") + { + break; + } + goto Label1; + } + else if (chr == 'P') + { + if (description1 == "PERCENTUAL") + { + str3 = "text-end"; + str = (propertyInfo2.GetValue(x) != null ? string.Format("{0:p2}", (decimal)propertyInfo2.GetValue(x) * new decimal(1, 0, 0, false, 2)) : ""); + goto Label0; + } + else + { + goto Label1; + } + } + else if (chr != 'Q') + { + goto Label1; + } + else if (description1 == "QUANTIDADE") + { + str3 = "text-center"; + str = (propertyInfo2.GetValue(x) != null ? string.Format("{0}", propertyInfo2.GetValue(x)) : ""); + goto Label0; + } + else + { + goto Label1; + } + } + default: + { + goto Label1; + } + } + str3 = "text-center"; + str = (propertyInfo2.GetValue(x) != null ? string.Format("{0:G}", (DateTime?)propertyInfo2.GetValue(x)) : ""); + goto Label0; + } + Label1: + str1 = (propertyInfo2.GetValue(x) != null ? string.Format("{0}", propertyInfo2.GetValue(x)) : ""); + str = str1; + Label0: + StringBuilder stringBuilder1 = stringBuilder; + stringBuilder1.Append(Resources.ColumnTemplate.Replace("{Align}", str3).Replace("{Size}", str6).Replace("{FontWeight}", (flag ? "fw-bold" : "")).Replace("{Content}", str)); + } + } + } + } + }; + Action action1 = action; + action2 = action; + u003cu003e9_1 = action1; + } + listagems.ForEach(u003cu003e9_1); + StringBuilder stringBuilder6 = new StringBuilder(); + if (grafico) + { + stringBuilder5.Append(string.Format("
", num)); + } + num++; + stringBuilder6.Append(Resources.TableMultipleTemplate.Replace("{Head}", stringBuilder3.ToString()).Replace("{Body}", stringBuilder5.ToString()).Replace("{Footer}", (!string.IsNullOrEmpty(footer) ? Resources.FooterTemplate.Replace("{Content}", string.Format("{1}", num1, footer)) : ""))); + stringBuilder2.Append(stringBuilder6.ToString()); + } + return stringBuilder2.ToString(); + }); + } + else + { + str4 = ""; + } + return str4; + } + + public static async Task GenerateTable(List analitico, List colunasOcultas, bool grafico = false, bool propertyName = false, string footer = "", ConfiguracaoImpressao config = null) + { + string str7; + string str8; + if (analitico == null) + { + str7 = ""; + } + else if (analitico.Count != 0) + { + int tamanhoFonte = 0; + if (config != null) + { + tamanhoFonte = config.get_TamanhoFonte(); + } + str8 = (tamanhoFonte == 0 ? "" : string.Format("fs-{0}'", tamanhoFonte)); + string str9 = str8; + str7 = await Task.Run(() => { + StringBuilder stringBuilder2 = new StringBuilder(); + StringBuilder stringBuilder3 = new StringBuilder(); + StringBuilder stringBuilder4 = new StringBuilder(); + Type type = analitico[0].GetType(); + PropertyInfo[] properties = type.GetProperties(); + int num = 0; + PropertyInfo[] propertyInfoArray3 = properties; + for (int i1 = 0; i1 < (int)propertyInfoArray3.Length; i1++) + { + PropertyInfo propertyInfo3 = propertyInfoArray3[i1]; + if (propertyInfo3.Name != "ValidationEvent") + { + object obj2 = propertyInfo3.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault(); + if (obj2 != null) + { + string str4 = ((DescriptionAttribute)obj2).Description; + if ((!propertyName || !colunasOcultas.Contains(propertyInfo3.Name)) && (propertyName || !colunasOcultas.Contains(str4))) + { + object obj3 = propertyInfo3.GetCustomAttributes(typeof(TipoAttribute), true).FirstOrDefault(); + string str5 = ""; + if (obj3 != null) + { + str5 = ((TipoAttribute)obj3).get_Description(); + } + string str6 = "text-start"; + if (str5 == "PERCENTUAL" || str5 == "VALOR") + { + str6 = "text-center"; + } + else if (str5 == "QUANTIDADE" || str5 == "DATA") + { + str6 = "text-end"; + } + stringBuilder3.Append(Resources.HeaderTemplate.Replace("{Align}", str6).Replace("{Size}", str9).Replace("{FontWeight}", "fw-bold").Replace("{Content}", str4)); + num++; + } + } + } + } + stringBuilder2.Append(Resources.RowTemplate.Replace("{Content}", stringBuilder3.ToString()).Replace("{Color}", "")); + analitico.ForEach((T x) => { + Sinal sinal; + string str; + char chr; + string str1; + type = x.GetType(); + properties = type.GetProperties(); + PropertyInfo[] propertyInfoArray = properties; + Func u003cu003e9_212 = Funcoes.u003cu003ec__21.u003cu003e9__21_2; + if (u003cu003e9_212 == null) + { + u003cu003e9_212 = (PropertyInfo b) => b.Name == "Bold"; + Funcoes.u003cu003ec__21.u003cu003e9__21_2 = u003cu003e9_212; + } + PropertyInfo propertyInfo = ((IEnumerable)propertyInfoArray).FirstOrDefault(u003cu003e9_212); + bool flag = (propertyInfo == null ? false : (bool)propertyInfo.GetValue(x)); + PropertyInfo[] propertyInfoArray1 = properties; + Func u003cu003e9_213 = Funcoes.u003cu003ec__21.u003cu003e9__21_3; + if (u003cu003e9_213 == null) + { + u003cu003e9_213 = (PropertyInfo b) => b.Name == "Sinal"; + Funcoes.u003cu003ec__21.u003cu003e9__21_3 = u003cu003e9_213; + } + PropertyInfo propertyInfo1 = ((IEnumerable)propertyInfoArray1).FirstOrDefault(u003cu003e9_213); + string str2 = (!(propertyInfo1 != null) || propertyInfo1.GetValue(x) == null || !Enum.TryParse(propertyInfo1.GetValue(x).ToString(), true, out sinal) || sinal != 1 ? "color: black;" : "color: red;"); + if (flag) + { + string.Concat(""); + } + else + { + string.Concat(""); + } + StringBuilder stringBuilder = new StringBuilder(); + PropertyInfo[] propertyInfoArray2 = properties; + for (int i = 0; i < (int)propertyInfoArray2.Length; i++) + { + PropertyInfo propertyInfo2 = propertyInfoArray2[i]; + if (propertyInfo2.Name != "ValidationEvent") + { + object obj = propertyInfo2.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault(); + if (obj != null) + { + string description = ((DescriptionAttribute)obj).Description; + if ((!propertyName || !colunasOcultas.Contains(propertyInfo2.Name)) && (propertyName || !colunasOcultas.Contains(description))) + { + object obj1 = propertyInfo2.GetCustomAttributes(typeof(TipoAttribute), true).FirstOrDefault(); + string description1 = ""; + if (obj1 != null) + { + description1 = ((TipoAttribute)obj1).get_Description(); + } + string str3 = "text-start"; + if (description1 != null) + { + switch (description1.Length) + { + case 4: + { + chr = description1[0]; + if (chr == 'D') + { + if (description1 == "DATA") + { + str3 = "text-center"; + str = (propertyInfo2.GetValue(x) == null || (DateTime)propertyInfo2.GetValue(x) == DateTime.MinValue ? "" : string.Format("{0:d}", (DateTime)propertyInfo2.GetValue(x))); + goto Label0; + } + else + { + goto Label1; + } + } + else if (chr != 'E') + { + goto Label1; + } + else if (description1 == "ENUM") + { + str = (propertyInfo2.GetValue(x) != null ? Gestor.Common.Validation.ValidationHelper.GetDescription((Enum)propertyInfo2.GetValue(x)) ?? "" : ""); + goto Label0; + } + else + { + goto Label1; + } + } + case 5: + { + chr = description1[0]; + if (chr == 'D') + { + if (description1 == "DATA?") + { + str3 = "text-center"; + str = (propertyInfo2.GetValue(x) != null ? string.Format("{0:d}", (DateTime?)propertyInfo2.GetValue(x)) : ""); + goto Label0; + } + else + { + goto Label1; + } + } + else if (chr != 'V') + { + goto Label1; + } + else if (description1 == "VALOR") + { + str3 = "text-end"; + str = (propertyInfo2.GetValue(x) != null ? string.Format("{0:c2}", (decimal)propertyInfo2.GetValue(x)) : ""); + goto Label0; + } + else + { + goto Label1; + } + } + case 6: + { + if (description1 != "VALOR?") + { + goto Label1; + } + str3 = "text-end"; + str = (propertyInfo2.GetValue(x) != null ? string.Format("{0:c2}", (decimal?)propertyInfo2.GetValue(x)) : ""); + goto Label0; + } + case 9: + { + if (description1 == "DATA/TIME") + { + break; + } + goto Label1; + } + case 10: + { + chr = description1[0]; + if (chr == 'D') + { + if (description1 == "DATA/TIME?") + { + break; + } + goto Label1; + } + else if (chr == 'P') + { + if (description1 == "PERCENTUAL") + { + str3 = "text-end"; + str = (propertyInfo2.GetValue(x) != null ? string.Format("{0:p2}", (decimal)propertyInfo2.GetValue(x) * new decimal(1, 0, 0, false, 2)) : ""); + goto Label0; + } + else + { + goto Label1; + } + } + else if (chr != 'Q') + { + goto Label1; + } + else if (description1 == "QUANTIDADE") + { + str3 = "text-center"; + str = (propertyInfo2.GetValue(x) != null ? string.Format("{0}", propertyInfo2.GetValue(x)) : ""); + goto Label0; + } + else + { + goto Label1; + } + } + case 13: + { + if (description1 == "VALORDECIMAL2") + { + str3 = "text-end"; + str = (propertyInfo2.GetValue(x) != null ? string.Format("{0:n2}", (decimal)propertyInfo2.GetValue(x)) : ""); + goto Label0; + } + else + { + goto Label1; + } + } + default: + { + goto Label1; + } + } + str3 = "text-center"; + str = (propertyInfo2.GetValue(x) != null ? string.Format("{0:G}", (DateTime?)propertyInfo2.GetValue(x)) : ""); + goto Label0; + } + Label1: + str1 = (propertyInfo2.GetValue(x) != null ? string.Format("{0}", propertyInfo2.GetValue(x)) : ""); + str = str1; + Label0: + StringBuilder stringBuilder1 = stringBuilder; + stringBuilder1.Append(Resources.ColumnTemplate.Replace("{Align}", str3).Replace("{Size}", str9).Replace("{FontWeight}", (flag ? "fw-bold" : "")).Replace("{Content}", str)); + } + } + } + } + stringBuilder4.Append(Resources.RowTemplate.Replace("{Content}", stringBuilder.ToString()).Replace("{Color}", string.Concat("style='", str2, "'"))); + }); + StringBuilder stringBuilder5 = new StringBuilder(); + if (grafico) + { + stringBuilder4.Append(""); + stringBuilder4.Append("
"); + stringBuilder4.Append("
*VALORES NEGATIVOS NÃO SÃO REPRESENTADOS NO GRÁFICO DE PIZZA.
"); + stringBuilder4.Append(""); + } + stringBuilder5.Append(Resources.TableTemplate.Replace("{Head}", stringBuilder2.ToString()).Replace("{Body}", stringBuilder4.ToString()).Replace("{Footer}", (!string.IsNullOrEmpty(footer) ? Resources.FooterTemplate.Replace("{Content}", string.Format("{1}", num, footer)) : ""))); + return stringBuilder5.ToString(); + }); + } + else + { + str7 = ""; + } + return str7; + } + + public static async Task GenerateTable(List analitico, Relatorio relatorio, bool grafico = false, bool verificarColunas = true, string footer = "", ConfiguracaoImpressao config = null) + { + string str6; + List restricoesColunas; + string str7; + List campos; + int tamanhoFonte = 0; + if (config != null) + { + campos = config.get_Campos(); + tamanhoFonte = config.get_TamanhoFonte(); + } + else + { + if (!verificarColunas) + { + restricoesColunas = null; + } + else + { + restricoesColunas = await (new ConfuguracoesServico()).BuscarParametros(relatorio); + } + campos = restricoesColunas; + if (campos == null || campos.Count == 0) + { + PropertyInfo[] propertyInfoArray2 = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public); + campos = propertyInfoArray2.Select((PropertyInfo x) => { + ParametrosRelatorio parametrosRelatorio = new ParametrosRelatorio(); + parametrosRelatorio.set_Campo(x.Name); + parametrosRelatorio.set_Header(x.GetDescriptionAttribute()); + parametrosRelatorio.set_Tipo(x.GetTypeAttribute()); + parametrosRelatorio.set_Relatorio(relatorio); + parametrosRelatorio.set_Width(0); + parametrosRelatorio.set_Ordem(0); + return parametrosRelatorio; + }).ToList(); + } + } + str7 = (tamanhoFonte == 0 ? "" : string.Format("fs-{0}'", tamanhoFonte)); + string str8 = str7; + restricoesColunas = await Funcoes.GetRestricoesColunas(campos); + campos = restricoesColunas; + if (analitico == null) + { + str6 = ""; + } + else if (analitico.Count != 0) + { + str6 = await Task.Run(() => { + StringBuilder stringBuilder3 = new StringBuilder(); + StringBuilder stringBuilder4 = new StringBuilder(); + StringBuilder stringBuilder5 = new StringBuilder(); + Type type = analitico[0].GetType(); + PropertyInfo[] properties = type.GetProperties(); + int num = 0; + List parametrosRelatorios1 = campos; + Func u003cu003e9_242 = Funcoes.u003cu003ec__24.u003cu003e9__24_2; + if (u003cu003e9_242 == null) + { + u003cu003e9_242 = (ParametrosRelatorio x) => x.get_Ordem(); + Funcoes.u003cu003ec__24.u003cu003e9__24_2 = u003cu003e9_242; + } + IOrderedEnumerable parametrosRelatorios2 = parametrosRelatorios1.OrderBy(u003cu003e9_242); + Func u003cu003e9_243 = Funcoes.u003cu003ec__24.u003cu003e9__24_3; + if (u003cu003e9_243 == null) + { + u003cu003e9_243 = (ParametrosRelatorio x) => x.get_Header(); + Funcoes.u003cu003ec__24.u003cu003e9__24_3 = u003cu003e9_243; + } + ExtensionMethods.ForEach(parametrosRelatorios2.ThenBy(u003cu003e9_243), (ParametrosRelatorio x) => { + if (x.get_Tipo() == "INVALID") + { + return; + } + PropertyInfo propertyInfo = properties.FirstOrDefault((PropertyInfo p) => p.Name == x.get_Campo()); + if (propertyInfo == null) + { + return; + } + string descriptionAttribute = propertyInfo.GetDescriptionAttribute(); + string str = "text-start"; + string tipo = x.get_Tipo(); + if (tipo == "PERCENTUAL" || tipo == "VALOR") + { + str = "text-center"; + } + else if (tipo == "QUANTIDADE" || tipo == "DATA") + { + str = "text-end"; + } + stringBuilder4.Append(Resources.HeaderTemplate.Replace("{Align}", str).Replace("{Size}", str8).Replace("{FontWeight}", "fw-bold").Replace("{Content}", descriptionAttribute)); + num++; + }); + stringBuilder3.Append(Resources.RowTemplate.Replace("{Content}", stringBuilder4.ToString()).Replace("{Color}", "")); + analitico.ForEach((T a) => { + Sinal sinal; + StringBuilder stringBuilder2 = new StringBuilder(); + type = a.GetType(); + properties = type.GetProperties(); + PropertyInfo[] propertyInfoArray = properties; + Func u003cu003e9_247 = Funcoes.u003cu003ec__24.u003cu003e9__24_7; + if (u003cu003e9_247 == null) + { + u003cu003e9_247 = (PropertyInfo b) => b.Name == "Bold"; + Funcoes.u003cu003ec__24.u003cu003e9__24_7 = u003cu003e9_247; + } + PropertyInfo propertyInfo1 = ((IEnumerable)propertyInfoArray).FirstOrDefault(u003cu003e9_247); + bool flag = (propertyInfo1 == null ? false : (bool)propertyInfo1.GetValue(a)); + PropertyInfo[] propertyInfoArray1 = properties; + Func u003cu003e9_248 = Funcoes.u003cu003ec__24.u003cu003e9__24_8; + if (u003cu003e9_248 == null) + { + u003cu003e9_248 = (PropertyInfo b) => b.Name == "Sinal"; + Funcoes.u003cu003ec__24.u003cu003e9__24_8 = u003cu003e9_248; + } + PropertyInfo propertyInfo2 = ((IEnumerable)propertyInfoArray1).FirstOrDefault(u003cu003e9_248); + string str5 = (!(propertyInfo2 != null) || propertyInfo2.GetValue(a) == null || !Enum.TryParse(propertyInfo2.GetValue(a).ToString(), true, out sinal) || sinal != 1 ? "color: black;" : "color: red;"); + if (flag) + { + string.Concat(""); + } + else + { + string.Concat(""); + } + List cSu0024u003cu003e8_locals1 = campos; + Func u003cu003e9_249 = Funcoes.u003cu003ec__24.u003cu003e9__24_9; + if (u003cu003e9_249 == null) + { + u003cu003e9_249 = (ParametrosRelatorio x) => x.get_Ordem(); + Funcoes.u003cu003ec__24.u003cu003e9__24_9 = u003cu003e9_249; + } + IOrderedEnumerable parametrosRelatorios = cSu0024u003cu003e8_locals1.OrderBy(u003cu003e9_249); + Func u003cu003e9_2410 = Funcoes.u003cu003ec__24.u003cu003e9__24_10; + if (u003cu003e9_2410 == null) + { + u003cu003e9_2410 = (ParametrosRelatorio x) => x.get_Header(); + Funcoes.u003cu003ec__24.u003cu003e9__24_10 = u003cu003e9_2410; + } + ExtensionMethods.ForEach(parametrosRelatorios.ThenBy(u003cu003e9_2410), (ParametrosRelatorio x) => { + string str; + char chr; + string str1; + string str2; + string str3; + StringBuilder stringBuilder; + StringBuilder stringBuilder1; + if (x.get_Tipo() == "INVALID") + { + return; + } + PropertyInfo propertyInfo = properties.FirstOrDefault((PropertyInfo p) => p.Name == x.get_Campo()); + if (propertyInfo == null) + { + return; + } + string str4 = "text-start"; + string tipo = x.get_Tipo(); + if (tipo != null) + { + switch (tipo.Length) + { + case 4: + { + chr = tipo[0]; + if (chr == 'D') + { + if (tipo == "DATA") + { + str4 = "text-center"; + str = (propertyInfo.GetValue(a) == null || (DateTime)propertyInfo.GetValue(a) == DateTime.MinValue ? "" : string.Format("{0:d}", (DateTime)propertyInfo.GetValue(a))); + stringBuilder = stringBuilder2; + str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); + str3 = (flag ? "fw-bold" : ""); + stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); + return; + } + else + { + str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : ""); + str = str1; + stringBuilder = stringBuilder2; + str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); + str3 = (flag ? "fw-bold" : ""); + stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); + return; + } + } + else if (chr != 'E') + { + str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : ""); + str = str1; + stringBuilder = stringBuilder2; + str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); + str3 = (flag ? "fw-bold" : ""); + stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); + return; + } + else if (tipo == "ENUM") + { + str = (propertyInfo.GetValue(a) == null || Convert.ToInt32(propertyInfo.GetValue(a)) == 0 ? "" : Gestor.Common.Validation.ValidationHelper.GetDescription((Enum)propertyInfo.GetValue(a)) ?? ""); + stringBuilder = stringBuilder2; + str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); + str3 = (flag ? "fw-bold" : ""); + stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); + return; + } + else + { + str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : ""); + str = str1; + stringBuilder = stringBuilder2; + str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); + str3 = (flag ? "fw-bold" : ""); + stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); + return; + } + } + case 5: + { + chr = tipo[0]; + if (chr == 'D') + { + if (tipo == "DATA?") + { + str4 = "text-center"; + str = (propertyInfo.GetValue(a) != null ? string.Format("{0:d}", (DateTime?)propertyInfo.GetValue(a)) : ""); + stringBuilder = stringBuilder2; + str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); + str3 = (flag ? "fw-bold" : ""); + stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); + return; + } + else + { + str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : ""); + str = str1; + stringBuilder = stringBuilder2; + str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); + str3 = (flag ? "fw-bold" : ""); + stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); + return; + } + } + else if (chr != 'V') + { + str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : ""); + str = str1; + stringBuilder = stringBuilder2; + str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); + str3 = (flag ? "fw-bold" : ""); + stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); + return; + } + else if (tipo == "VALOR") + { + str4 = "text-end"; + str = (propertyInfo.GetValue(a) != null ? string.Format("{0:c2}", (decimal)propertyInfo.GetValue(a)) : ""); + stringBuilder = stringBuilder2; + str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); + str3 = (flag ? "fw-bold" : ""); + stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); + return; + } + else + { + str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : ""); + str = str1; + stringBuilder = stringBuilder2; + str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); + str3 = (flag ? "fw-bold" : ""); + stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); + return; + } + } + case 6: + { + if (tipo != "VALOR?") + { + str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : ""); + str = str1; + stringBuilder = stringBuilder2; + str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); + str3 = (flag ? "fw-bold" : ""); + stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); + return; + } + str4 = "text-end"; + str = (propertyInfo.GetValue(a) != null ? string.Format("{0:c2}", (decimal?)propertyInfo.GetValue(a)) : ""); + stringBuilder = stringBuilder2; + str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); + str3 = (flag ? "fw-bold" : ""); + stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); + return; + } + case 7: + case 8: + case 11: + case 12: + { + str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : ""); + str = str1; + stringBuilder = stringBuilder2; + str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); + str3 = (flag ? "fw-bold" : ""); + stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); + return; + } + case 9: + { + if (tipo == "DATA/TIME") + { + break; + } + str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : ""); + str = str1; + stringBuilder = stringBuilder2; + str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); + str3 = (flag ? "fw-bold" : ""); + stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); + return; + } + case 10: + { + chr = tipo[0]; + if (chr == 'D') + { + if (tipo == "DATA/TIME?") + { + break; + } + str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : ""); + str = str1; + stringBuilder = stringBuilder2; + str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); + str3 = (flag ? "fw-bold" : ""); + stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); + return; + } + else if (chr == 'P') + { + if (tipo == "PERCENTUAL") + { + str4 = "text-end"; + str = (propertyInfo.GetValue(a) != null ? string.Format("{0:p2}", (decimal)propertyInfo.GetValue(a) * new decimal(1, 0, 0, false, 2)) : ""); + stringBuilder = stringBuilder2; + str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); + str3 = (flag ? "fw-bold" : ""); + stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); + return; + } + else + { + str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : ""); + str = str1; + stringBuilder = stringBuilder2; + str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); + str3 = (flag ? "fw-bold" : ""); + stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); + return; + } + } + else if (chr != 'Q') + { + str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : ""); + str = str1; + stringBuilder = stringBuilder2; + str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); + str3 = (flag ? "fw-bold" : ""); + stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); + return; + } + else if (tipo == "QUANTIDADE") + { + str4 = "text-center"; + str = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : ""); + stringBuilder = stringBuilder2; + str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); + str3 = (flag ? "fw-bold" : ""); + stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); + return; + } + else + { + str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : ""); + str = str1; + stringBuilder = stringBuilder2; + str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); + str3 = (flag ? "fw-bold" : ""); + stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); + return; + } + } + case 13: + { + if (tipo == "VALORDECIMAL2") + { + str4 = "text-end"; + str = (propertyInfo.GetValue(a) != null ? string.Format("{0:n2}", (decimal)propertyInfo.GetValue(a)) : ""); + stringBuilder = stringBuilder2; + str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); + str3 = (flag ? "fw-bold" : ""); + stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); + return; + } + else + { + str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : ""); + str = str1; + stringBuilder = stringBuilder2; + str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); + str3 = (flag ? "fw-bold" : ""); + stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); + return; + } + } + default: + { + str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : ""); + str = str1; + stringBuilder = stringBuilder2; + str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); + str3 = (flag ? "fw-bold" : ""); + stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); + return; + } + } + str4 = "text-center"; + str = (propertyInfo.GetValue(a) != null ? string.Format("{0:G}", (DateTime?)propertyInfo.GetValue(a)) : ""); + stringBuilder = stringBuilder2; + str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); + str3 = (flag ? "fw-bold" : ""); + stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); + return; + } + str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : ""); + str = str1; + stringBuilder = stringBuilder2; + str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); + str3 = (flag ? "fw-bold" : ""); + stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); + }); + stringBuilder5.Append(Resources.RowTemplate.Replace("{Content}", stringBuilder2.ToString()).Replace("{Color}", string.Concat("style='", str5, "'"))); + }); + StringBuilder stringBuilder6 = new StringBuilder(); + stringBuilder6.Append(Resources.TableTemplate.Replace("{Head}", stringBuilder3.ToString()).Replace("{Body}", stringBuilder5.ToString()).Replace("{Footer}", (!string.IsNullOrEmpty(footer) ? Resources.FooterTemplate.Replace("{Content}", string.Format("{1}", num, footer)) : ""))); + return stringBuilder6.ToString(); + }); + } + else + { + str6 = ""; + } + return str6; + } + + public static async Task GenerateTableSintetic(List sintetic, int fontSize = 0) + { + string str; + string str1; + if (sintetic == null || sintetic.Count == 0) + { + str = ""; + } + else + { + str1 = (fontSize == 0 ? "" : string.Format("fs-{0}'", fontSize)); + string str2 = str1; + str = await Task.Run(() => { + StringBuilder stringBuilder = new StringBuilder(); + StringBuilder stringBuilder1 = new StringBuilder(); + StringBuilder stringBuilder2 = new StringBuilder(); + StringBuilder stringBuilder3 = new StringBuilder(); + StringBuilder stringBuilder4 = new StringBuilder(); + sintetic.ForEach((SinteticModel x) => { + stringBuilder2.Append(Resources.HeaderTemplate.Replace("{Align}", "text-center").Replace("{Size}", str2).Replace("{FontWeight}", "fw-bold").Replace("{Content}", x.get_Hint())); + stringBuilder4.Append(Resources.ColumnTemplate.Replace("{Align}", "text-center").Replace("{Size}", str2).Replace("{FontWeight}", "").Replace("{Content}", (x.get_Value() == null ? "" : x.get_Value().ToString()))); + }); + stringBuilder1.Append(Resources.RowTemplate.Replace("{Content}", stringBuilder2.ToString()).Replace("{Color}", "")); + stringBuilder3.Append(Resources.RowTemplate.Replace("{Content}", stringBuilder4.ToString()).Replace("{Color}", "")); + stringBuilder.Append(Resources.TableTemplate.Replace("{Head}", stringBuilder1.ToString()).Replace("{Body}", stringBuilder3.ToString()).Replace("{Footer}", "")); + return stringBuilder.ToString(); + }); + } + return str; + } + + public static async Task GenerateTableSintetic(List sintetic, int fontSize = 0) + { + string str; + string str1; + if (sintetic == null || sintetic.Count == 0) + { + str = ""; + } + else + { + str1 = (fontSize == 0 ? "" : string.Format("fs-{0}'", fontSize)); + string str2 = str1; + str = await Task.Run(() => { + StringBuilder stringBuilder = new StringBuilder(); + StringBuilder stringBuilder1 = new StringBuilder(); + StringBuilder stringBuilder2 = new StringBuilder(); + StringBuilder stringBuilder3 = new StringBuilder(); + sintetic.ForEach((SinteticModelList x) => stringBuilder2.Append(Resources.HeaderTemplate.Replace("{Align}", "text-center").Replace("{Size}", str2).Replace("{FontWeight}", "fw-bold").Replace("{Content}", x.get_Hint()))); + stringBuilder1.Append(Resources.RowTemplate.Replace("{Content}", stringBuilder2.ToString()).Replace("{Color}", "")); + for (int i = 0; i < sintetic.First().get_Value().Count; i++) + { + StringBuilder stringBuilder4 = new StringBuilder(); + bool flag = false; + foreach (SinteticModelList sinteticModelList in sintetic) + { + flag = (flag ? true : (sinteticModelList.get_Value()[0] == null ? false : sinteticModelList.get_Value()[i].ToString() == "TOTAL")); + stringBuilder4.Append(Resources.ColumnTemplate.Replace("{Align}", "text-center").Replace("{Size}", str2).Replace("{FontWeight}", (flag ? "fw-bold" : "")).Replace("{Content}", string.Format("{0}", sinteticModelList.get_Value()[i]))); + } + stringBuilder3.Append(Resources.RowTemplate.Replace("{Content}", stringBuilder4.ToString()).Replace("{Color}", "")); + } + stringBuilder.Append(Resources.TableTemplate.Replace("{Head}", stringBuilder1.ToString()).Replace("{Body}", stringBuilder3.ToString()).Replace("{Footer}", "")); + return stringBuilder.ToString(); + }); + } + return str; + } + + public static string GeraAssistencia(this long id) + { + string str; + try + { + DateTime now = DateTime.Now; + str = HttpUtility.UrlEncode(string.Format("{0}:{1}:A:{2}", now.Ticks, ApplicationHelper.IdFornecedor, id).Base64Encode()); + } + catch + { + return ""; + } + return str; + } + + public static string GeraCartaoVisita(this long id) + { + string str; + try + { + DateTime now = DateTime.Now; + str = HttpUtility.UrlEncode(string.Format("{0}:{1}:V:{2}", now.Ticks, ApplicationHelper.IdFornecedor, id).Base64Encode()); + } + catch + { + return ""; + } + return str; + } + + public static async Task GerarCsv(List Conteudo, IEnumerable colunasExportacao) + { + PropertyInfo[] array = ( + from in typeof(T).GetProperties() + where colunasExportacao.Contains(p.Name) + select ).ToArray(); + StringBuilder stringBuilder = new StringBuilder(); + StringBuilder stringBuilder1 = stringBuilder; + PropertyInfo[] propertyInfoArray = array; + stringBuilder1.AppendLine(string.Join(";", + from in (IEnumerable)propertyInfoArray + select p.Name)); + foreach (T conteudo in Conteudo) + { + IEnumerable strs = array.Select((PropertyInfo p) => { + object str; + object value = p.GetValue(conteudo, null); + if (value != null) + { + str = value.ToString(); + } + else + { + str = null; + } + if (str == null) + { + str = string.Empty; + } + return str; + }); + stringBuilder.AppendLine(string.Join(";", strs)); + } + return stringBuilder.ToString(); + } + + public static string GerarGrafico(List sinteticoLista) + { + string str = "['NOME', 'VALOR'], "; + sinteticoLista.ForEach((ValorSintetico x) => { + if (x.get_Indice() != "TOTAL" && x.get_Valor() > decimal.Zero) + { + string[] indice = new string[] { str, "[`", x.get_Indice(), " ", x.get_Porcentagem(), "`, ", null, null }; + indice[6] = x.get_Valor().ToString("F2", CultureInfo.InvariantCulture); + indice[7] = "], "; + str = string.Concat(indice); + } + }); + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append(""); + stringBuilder.Append(""); + return stringBuilder.ToString(); + } + + public static string GerarGraficoUnico(List> sinteticosListas) + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append(""); + stringBuilder.Append(""); + return stringBuilder.ToString(); + } + + public static async Task GerarXls(XLWorkbook xlWorkbook, string nome, List analitico, Relatorio relatorio, bool verificarColunas = true) + { + List restricoesColunas; + string str = nome; + str = str.ValidaNomePlanilha("", 0); + if (!verificarColunas) + { + restricoesColunas = null; + } + else + { + restricoesColunas = await (new ConfuguracoesServico()).BuscarParametros(relatorio); + } + List list = restricoesColunas; + if (list == null || list.Count == 0) + { + PropertyInfo[] propertyInfoArray = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public); + list = propertyInfoArray.Select((PropertyInfo x) => { + ParametrosRelatorio parametrosRelatorio = new ParametrosRelatorio(); + parametrosRelatorio.set_Campo(x.Name); + parametrosRelatorio.set_Header(x.GetDescriptionAttribute()); + parametrosRelatorio.set_Tipo(x.GetTypeAttribute()); + parametrosRelatorio.set_Relatorio(relatorio); + parametrosRelatorio.set_Width(0); + parametrosRelatorio.set_Ordem(0); + return parametrosRelatorio; + }).ToList(); + } + restricoesColunas = await Funcoes.GetRestricoesColunas(list); + list = restricoesColunas; + XLWorkbook xLWorkbook1 = await Task.Run(() => { + XLWorkbook xLWorkbook; + try + { + IXLWorksheet xLWorksheet = xlWorkbook.get_Worksheets().Add(str); + PropertyInfo[] properties = analitico[0].GetType().GetProperties(); + int num1 = 1; + List parametrosRelatorios1 = list; + Func u003cu003e9_252 = Funcoes.u003cu003ec__25.u003cu003e9__25_2; + if (u003cu003e9_252 == null) + { + u003cu003e9_252 = (ParametrosRelatorio x) => x.get_Ordem(); + Funcoes.u003cu003ec__25.u003cu003e9__25_2 = u003cu003e9_252; + } + IOrderedEnumerable parametrosRelatorios2 = parametrosRelatorios1.OrderBy(u003cu003e9_252); + Func u003cu003e9_253 = Funcoes.u003cu003ec__25.u003cu003e9__25_3; + if (u003cu003e9_253 == null) + { + u003cu003e9_253 = (ParametrosRelatorio x) => x.get_Header(); + Funcoes.u003cu003ec__25.u003cu003e9__25_3 = u003cu003e9_253; + } + ExtensionMethods.ForEach(parametrosRelatorios2.ThenBy(u003cu003e9_253), (ParametrosRelatorio x) => { + if (x.get_Tipo() == "INVALID") + { + return; + } + PropertyInfo propertyInfo = properties.FirstOrDefault((PropertyInfo p) => { + if (p.Name == x.get_Campo() || p.Name.ToUpper().Equals("NOME") && x.get_Campo().ToUpper().Equals("VENDEDOR") && str.Equals("SINTÉTICO POR VENDEDOR") && relatorio == 7 || p.Name.ToUpper().Equals("NOME") && x.get_Campo().ToUpper().Equals("SEGURADORA") && str.Equals("SINTÉTICO POR SEGURADORA") && relatorio == 7) + { + return true; + } + if (!p.Name.ToUpper().Equals("NOME") || !x.get_Campo().ToUpper().Equals("RAMO") || !str.Equals("SINTÉTICO POR RAMO")) + { + return false; + } + return relatorio == 7; + }); + if (propertyInfo == null) + { + return; + } + xLWorksheet.Cell(1, num1).set_Value(propertyInfo.GetDescriptionAttribute()); + num1++; + }); + int num2 = 2; + analitico.ForEach((T a) => { + num1 = 1; + int num = num2; + List cSu0024u003cu003e8_locals1 = list; + Func u003cu003e9_257 = Funcoes.u003cu003ec__25.u003cu003e9__25_7; + if (u003cu003e9_257 == null) + { + u003cu003e9_257 = (ParametrosRelatorio x) => x.get_Ordem(); + Funcoes.u003cu003ec__25.u003cu003e9__25_7 = u003cu003e9_257; + } + IOrderedEnumerable parametrosRelatorios = cSu0024u003cu003e8_locals1.OrderBy(u003cu003e9_257); + Func u003cu003e9_258 = Funcoes.u003cu003ec__25.u003cu003e9__25_8; + if (u003cu003e9_258 == null) + { + u003cu003e9_258 = (ParametrosRelatorio x) => x.get_Header(); + Funcoes.u003cu003ec__25.u003cu003e9__25_8 = u003cu003e9_258; + } + ExtensionMethods.ForEach(parametrosRelatorios.ThenBy(u003cu003e9_258), (ParametrosRelatorio x) => { + int cSu0024u003cu003e8_locals3; + char chr; + if (x.get_Tipo() == "INVALID") + { + return; + } + PropertyInfo propertyInfo = properties.FirstOrDefault((PropertyInfo p) => { + if (p.Name == x.get_Campo() || p.Name.ToUpper().Equals("NOME") && x.get_Campo().ToUpper().Equals("VENDEDOR") && str.Equals("SINTÉTICO POR VENDEDOR") && relatorio == 7 || p.Name.ToUpper().Equals("NOME") && x.get_Campo().ToUpper().Equals("SEGURADORA") && str.Equals("SINTÉTICO POR SEGURADORA") && relatorio == 7) + { + return true; + } + if (!p.Name.ToUpper().Equals("NOME") || !x.get_Campo().ToUpper().Equals("RAMO") || !str.Equals("SINTÉTICO POR RAMO")) + { + return false; + } + return relatorio == 7; + }); + if (propertyInfo == null) + { + return; + } + Regex regex = new Regex("\\<[^\\>]*\\>"); + object value = propertyInfo.GetValue(a); + if (value != null && value.ToString().Contains(">") && value.ToString().Contains("<")) + { + value = regex.Replace(value.ToString(), ""); + } + string tipo = x.get_Tipo(); + if (tipo != null) + { + switch (tipo.Length) + { + case 4: + { + if (tipo == "DATA") + { + break; + } + xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@"); + xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value)); + cSu0024u003cu003e8_locals3 = num1; + num1 = cSu0024u003cu003e8_locals3 + 1; + return; + } + case 5: + { + chr = tipo[0]; + if (chr == 'D') + { + if (tipo == "DATA?") + { + break; + } + xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@"); + xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value)); + cSu0024u003cu003e8_locals3 = num1; + num1 = cSu0024u003cu003e8_locals3 + 1; + return; + } + else if (chr == 'V') + { + if (tipo != "VALOR") + { + xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@"); + xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value)); + cSu0024u003cu003e8_locals3 = num1; + num1 = cSu0024u003cu003e8_locals3 + 1; + return; + } + xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().SetNumberFormatId(2); + xLWorksheet.Cell(num, num1).set_Value(((decimal?)value).GetValueOrDefault()); + cSu0024u003cu003e8_locals3 = num1; + num1 = cSu0024u003cu003e8_locals3 + 1; + return; + } + else + { + xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@"); + xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value)); + cSu0024u003cu003e8_locals3 = num1; + num1 = cSu0024u003cu003e8_locals3 + 1; + return; + } + } + case 6: + case 7: + case 8: + { + xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@"); + xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value)); + cSu0024u003cu003e8_locals3 = num1; + num1 = cSu0024u003cu003e8_locals3 + 1; + return; + } + case 9: + { + if (tipo == "DATA/TIME") + { + xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("dd/MM/yyyy HH:mm:ss"); + xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value)); + cSu0024u003cu003e8_locals3 = num1; + num1 = cSu0024u003cu003e8_locals3 + 1; + return; + } + xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@"); + xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value)); + cSu0024u003cu003e8_locals3 = num1; + num1 = cSu0024u003cu003e8_locals3 + 1; + return; + } + case 10: + { + chr = tipo[0]; + if (chr == 'D') + { + if (tipo == "DATA/TIME?") + { + xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("dd/MM/yyyy HH:mm:ss"); + xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value)); + cSu0024u003cu003e8_locals3 = num1; + num1 = cSu0024u003cu003e8_locals3 + 1; + return; + } + xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@"); + xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value)); + cSu0024u003cu003e8_locals3 = num1; + num1 = cSu0024u003cu003e8_locals3 + 1; + return; + } + else if (chr == 'P') + { + if (tipo == "PERCENTUAL") + { + xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().SetNumberFormatId(10); + xLWorksheet.Cell(num, num1).set_Value(((decimal?)value).GetValueOrDefault() * new decimal(1, 0, 0, false, 2)); + cSu0024u003cu003e8_locals3 = num1; + num1 = cSu0024u003cu003e8_locals3 + 1; + return; + } + else + { + xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@"); + xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value)); + cSu0024u003cu003e8_locals3 = num1; + num1 = cSu0024u003cu003e8_locals3 + 1; + return; + } + } + else if (chr != 'Q') + { + xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@"); + xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value)); + cSu0024u003cu003e8_locals3 = num1; + num1 = cSu0024u003cu003e8_locals3 + 1; + return; + } + else if (tipo == "QUANTIDADE") + { + xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().SetNumberFormatId(1); + xLWorksheet.Cell(num, num1).set_Value(value); + cSu0024u003cu003e8_locals3 = num1; + num1 = cSu0024u003cu003e8_locals3 + 1; + return; + } + else + { + xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@"); + xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value)); + cSu0024u003cu003e8_locals3 = num1; + num1 = cSu0024u003cu003e8_locals3 + 1; + return; + } + } + default: + { + xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@"); + xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value)); + cSu0024u003cu003e8_locals3 = num1; + num1 = cSu0024u003cu003e8_locals3 + 1; + return; + } + } + xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("dd/MM/yyyy"); + xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value)); + cSu0024u003cu003e8_locals3 = num1; + num1 = cSu0024u003cu003e8_locals3 + 1; + return; + } + xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@"); + xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value)); + cSu0024u003cu003e8_locals3 = num1; + num1 = cSu0024u003cu003e8_locals3 + 1; + }); + num2++; + }); + xLWorksheet.Row(1).get_Style().get_Font().set_Bold(true); + xLWorksheet.Columns().AdjustToContents(); + xLWorkbook = xlWorkbook; + } + catch (Exception exception) + { + xLWorkbook = null; + } + return xLWorkbook; + }); + return xLWorkbook1; + } + + public static async Task GerarXls(XLWorkbook xlWorkbook, string nome, List analitico, List colunasOcultas = null) + { + XLWorkbook xLWorkbook1 = await Task.Run(() => { + XLWorkbook xLWorkbook; + try + { + nome = nome.ValidaNomePlanilha("", 0); + IXLWorksheet xLWorksheet = xlWorkbook.get_Worksheets().Add(nome); + Type type = analitico[0].GetType(); + PropertyInfo[] properties = type.GetProperties(); + int num = 1; + PropertyInfo[] propertyInfoArray1 = properties; + for (int i1 = 0; i1 < (int)propertyInfoArray1.Length; i1++) + { + PropertyInfo propertyInfo1 = propertyInfoArray1[i1]; + if (propertyInfo1.Name != "ValidationEvent") + { + object obj1 = propertyInfo1.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault(); + if (obj1 != null) + { + string str = ((DescriptionAttribute)obj1).Description; + if (colunasOcultas == null || !colunasOcultas.Contains(str)) + { + xLWorksheet.Cell(1, num).set_Value(str); + num++; + } + } + } + } + int num1 = 2; + analitico.ForEach((T x) => { + int i; + num = 1; + type = x.GetType(); + properties = type.GetProperties(); + PropertyInfo[] propertyInfoArray = properties; + for (i = 0; i < (int)propertyInfoArray.Length; i++) + { + PropertyInfo propertyInfo = propertyInfoArray[i]; + if (propertyInfo.Name != "ValidationEvent") + { + object obj = propertyInfo.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault(); + if (obj != null) + { + string description = ((DescriptionAttribute)obj).Description; + if (colunasOcultas == null || !colunasOcultas.Contains(description)) + { + string name = propertyInfo.Name; + if (name.Contains("Fipe") || name == "NumeroProposta" || name == "NumeroApolice" || name == "NumeroPedidoEndosso") + { + xLWorksheet.Cell(num1, num).get_Style().get_NumberFormat().set_Format("@"); + } + xLWorksheet.Cell(num1, num).set_Value(propertyInfo.GetValue(x)); + num++; + } + } + } + } + i = num1; + num1 = i + 1; + }); + xLWorksheet.Row(1).get_Style().get_Font().set_Bold(true); + xLWorksheet.Columns().AdjustToContents(); + xLWorkbook = xlWorkbook; + } + catch (Exception exception) + { + xLWorkbook = null; + } + return xLWorkbook; + }); + return xLWorkbook1; + } + + public static async Task GerarXlsSintetico(XLWorkbook xlWorkbook, string nome, List sintetic) + { + XLWorkbook xLWorkbook1 = await Task.Run(() => { + XLWorkbook xLWorkbook; + try + { + nome = nome.ValidaNomePlanilha("", 0); + IXLWorksheet xLWorksheet = xlWorkbook.get_Worksheets().Add(nome); + int num = 1; + sintetic.ForEach((SinteticModel x) => { + xLWorksheet.Cell(1, num).set_Value(x.get_Hint()); + xLWorksheet.Cell(2, num).set_Value(x.get_Value()); + num++; + }); + xLWorksheet.Row(1).get_Style().get_Font().set_Bold(true); + xLWorksheet.Columns().AdjustToContents(); + xLWorkbook = xlWorkbook; + } + catch (Exception exception) + { + xLWorkbook = null; + } + return xLWorkbook; + }); + return xLWorkbook1; + } + + public static string GetBody(this string html) + { + HtmlDocument htmlDocument = new HtmlDocument(); + htmlDocument.LoadHtml(html); + HtmlNode htmlNode = htmlDocument.get_DocumentNode().SelectSingleNode("//body"); + if (htmlNode != null) + { + return htmlNode.get_InnerHtml(); + } + return null; + } + + public static Categoria? GetCategoria(string text) + { + Categoria categorium; + if (text.Contains("caminhao") || text.Contains("caminhão")) + { + return new Categoria?(4); + } + if (text.Contains("onibus") || text.Contains("ônibus")) + { + return new Categoria?(6); + } + if (text.Contains("utilitario") || text.Contains("utilitário")) + { + return new Categoria?(6); + } + if (text.Contains("moto")) + { + return new Categoria?(9); + } + if (!Enum.TryParse(text, true, out categorium)) + { + return null; + } + return new Categoria?((Categoria)Enum.Parse(typeof(Categoria), text, true)); + } + + public static Combustivel? GetCombustivel(string text) + { + Combustivel combustivel; + if (text.Contains("flex")) + { + return new Combustivel?(4); + } + if (text.Contains("gasolina") && (text.Contains("alcool") || text.Contains("álcool"))) + { + if (text.Contains("gnv")) + { + return new Combustivel?(8); + } + if (!text.Contains("eletrico") && !text.Contains("elétrico")) + { + return new Combustivel?(4); + } + return new Combustivel?(12); + } + if (text.Contains("gasolina") && text.Contains("gnv")) + { + return new Combustivel?(7); + } + if (text.Contains("gasolina") && (text.Contains("eletrico") || text.Contains("elétrico"))) + { + return new Combustivel?(9); + } + if (text.Contains("eletrico") || text.Contains("elétrico")) + { + return new Combustivel?(11); + } + if (text.Contains("alcool") || text.Contains("álcool")) + { + return new Combustivel?(1); + } + if (text.Contains("hibrido") || text.Contains("híbrido")) + { + return new Combustivel?(10); + } + if (text.Contains("outro")) + { + return new Combustivel?(6); + } + if (!Enum.TryParse(text, true, out combustivel)) + { + return null; + } + return new Combustivel?((Combustivel)Enum.Parse(typeof(Combustivel), text, true)); + } + + public static Cor? GetCor(string text) + { + Cor cor; + if (text.Contains("outro")) + { + return new Cor?(16); + } + if (!Enum.TryParse(text, true, out cor)) + { + return null; + } + return new Cor?((Cor)Enum.Parse(typeof(Cor), text, true)); + } + + public static Correcao? GetCorrecao(string text) + { + if (text.Contains("mercado")) + { + return new Correcao?(0); + } + if (text.Contains("determinado")) + { + return new Correcao?(1); + } + return null; + } + + public static string GetDescriptionAttribute(this PropertyInfo pi) + { + object obj = pi.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault(); + if (obj == null) + { + return pi.Name.ToUpper(); + } + return ((DescriptionAttribute)obj).Description; + } + + public static async Task GetFabricante(string text) + { + Fabricante fabricante; + List fabricantes = await (new BaseServico()).BuscarFabricante(text); + if (fabricantes.Count < 1) + { + fabricante = null; + } + else + { + fabricante = fabricantes.First(); + } + return fabricante; + } + + public static Isencao? GetIsencao(string text) + { + if (text.Contains("sem")) + { + return new Isencao?(0); + } + if (text.Contains("ipi") && text.Contains("icms")) + { + return new Isencao?(3); + } + if (text.Contains("ipi")) + { + return new Isencao?(2); + } + if (text.Contains("icms")) + { + return new Isencao?(1); + } + return null; + } + + public static DateTime GetNetworkTime() + { + DateTime value; + try + { + if (!Funcoes.StartTime.HasValue) + { + byte[] numArray = new byte[48]; + numArray[0] = 27; + IPEndPoint pEndPoint = new IPEndPoint(((IEnumerable)Dns.GetHostEntry("time.google.com").AddressList).First((IPAddress a) => a.AddressFamily == AddressFamily.InterNetwork), 123); + using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) + { + socket.Connect(pEndPoint); + socket.ReceiveTimeout = 3000; + socket.Send(numArray); + socket.Receive(numArray); + socket.Close(); + } + ulong num = (ulong)numArray[40] << 24 | (ulong)numArray[41] << 16 | (ulong)numArray[42] << 8 | (ulong)numArray[43]; + ulong num1 = (ulong)numArray[44] << 24 | (ulong)numArray[45] << 16 | (ulong)numArray[46] << 8 | (ulong)numArray[47]; + ulong num2 = num * (long)1000 + num1 * (long)1000 / 4294967296L; + DateTime dateTime = new DateTime(1900, 1, 1); + dateTime = dateTime.AddMilliseconds((double)num2); + Funcoes.StartTime = new DateTime?(dateTime.ToLocalTime()); + Funcoes.Stopwatch = System.Diagnostics.Stopwatch.StartNew(); + value = Funcoes.StartTime.Value; + } + else + { + value = Funcoes.StartTime.Value; + value = value.AddMilliseconds((double)Funcoes.Stopwatch.ElapsedMilliseconds); + } + } + catch (Exception exception) + { + Funcoes.StartTime = new DateTime?(DateTime.Now); + Funcoes.Stopwatch = System.Diagnostics.Stopwatch.StartNew(); + value = Funcoes.StartTime.Value; + } + return value; + } + + private static async Task> GetRestricoesColunas(List parametros) + { + List restricaoUsuarioCamposRelatorios = await (new RestricaoUsuarioServico()).BuscarRestricoesCamposRelatorios(Recursos.Usuario.get_Id()); + List list = restricaoUsuarioCamposRelatorios; + List restricaoUsuarioCamposRelatorios1 = list; + list = ( + from x in restricaoUsuarioCamposRelatorios1 + where x.get_Restricao() + select x).ToList(); + List parametrosRelatorios = ( + from x in parametros + where ( + from y in list + where x.get_Relatorio() == y.get_Relatorio() + select y).All((RestricaoUsuarioCamposRelatorios y) => x.get_Header() != y.get_Campo()) + select x).ToList(); + return parametrosRelatorios; + } + + public static TabelaReferencia? GetTabelaReferencia(string text) + { + TabelaReferencia tabelaReferencium; + if (!Enum.TryParse(text, true, out tabelaReferencium)) + { + return null; + } + return new TabelaReferencia?((TabelaReferencia)Enum.Parse(typeof(TabelaReferencia), text, true)); + } + + public static string GetText(string html) + { + HtmlDocument htmlDocument = new HtmlDocument(); + htmlDocument.LoadHtml(html); + return Funcoes.NodeText(htmlDocument.get_DocumentNode()); + } + + public static TipoCobertura? GetTipoCobertura(string text) + { + TipoCobertura tipoCobertura; + if (text.Contains("incendio") || text.Contains("incêndio")) + { + return new TipoCobertura?(2); + } + if (text.Contains("roubo") && text.Contains("furto")) + { + return new TipoCobertura?(5); + } + if (text.Contains("terceiros")) + { + return new TipoCobertura?(3); + } + if (text.Contains("compreensiva")) + { + return new TipoCobertura?(1); + } + if (!Enum.TryParse(text, true, out tipoCobertura)) + { + return null; + } + return new TipoCobertura?((TipoCobertura)Enum.Parse(typeof(TipoCobertura), text, true)); + } + + public static string GetTypeAttribute(this PropertyInfo pi) + { + object obj = pi.GetCustomAttributes(typeof(TipoAttribute), true).FirstOrDefault(); + if (obj == null) + { + return ""; + } + return ((TipoAttribute)obj).get_Description(); + } + + public static UsoVeiculo? GetUsoveiculo(string text) + { + UsoVeiculo usoVeiculo; + UsoVeiculo usoVeiculo1; + if (Enum.TryParse(text, true, out usoVeiculo)) + { + usoVeiculo1 = usoVeiculo; + } + else + { + usoVeiculo1 = 0; + } + return new UsoVeiculo?(usoVeiculo1); + } + + public static T GetValueFromType(this object objeto) + { + Type type = typeof(T); + PropertyInfo[] properties = objeto.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); + for (int i = 0; i < (int)properties.Length; i++) + { + PropertyInfo propertyInfo = properties[i]; + if (propertyInfo.PropertyType == type) + { + return (T)propertyInfo.GetValue(objeto); + } + } + return default(T); + } + + public static async Task InativarItens(long id, long ramo, bool delete = true) + { + bool sucesso; + ItemServico itemServico = new ItemServico(); + ObservableCollection observableCollection = await itemServico.BuscarItens(id); + ObservableCollection observableCollection1 = observableCollection; + IEnumerable hasValue = + from x in observableCollection1 + where x.get_Substituicao().HasValue + select x; + if (await Funcoes.ReativarItens(( + from x in hasValue + select x.get_Substituicao().Value).ToList())) + { + if (!delete) + { + List list = observableCollection.ToList(); + list.ForEach((Item x) => x.set_Cancelado(true)); + await itemServico.SaveRange(observableCollection.ToList()); + } + else + { + await itemServico.DeleteRange(observableCollection.ToList(), ramo); + } + sucesso = itemServico.Sucesso; + } + else + { + sucesso = false; + } + itemServico = null; + observableCollection = null; + return sucesso; + } + + public static bool IsEmpty(this string html) + { + int count = Regex.Matches(html, "").Count; + bool flag = true; + int num = 0; + for (int i = 0; i < count; i++) + { + int num1 = html.IndexOf("", num, StringComparison.Ordinal) + 6; + if (num1 == 5) + { + break; + } + int num2 = html.IndexOf("", num, StringComparison.Ordinal); + num = num2 + 7; + flag = string.IsNullOrWhiteSpace(html.Substring(num1, num2 - num1)); + if (!flag) + { + break; + } + } + return flag; + } + + public static Window IsHosterOpen(string name) + { + return System.Windows.Application.Current.Windows.OfType().ToList().FirstOrDefault((HosterWindow x) => { + string str; + ContentControl contentControl = Extentions.FindVisualChildren(x).FirstOrDefault(); + if (contentControl != null) + { + str = contentControl.Tag.ToString(); + } + else + { + str = null; + } + return str == name; + }); + } + + public static bool IsWindowOpen(string title) + where T : Window + { + return System.Windows.Application.Current.Windows.OfType().Any((T x) => x.Title == title); + } + + public static List LogList(this List valores, bool restricaoComissao = false) + { + List> tuples = new List>(); + valores.ForEach((ValorOriginal x) => { + if (restricaoComissao && x.get_Campo().ToUpper().Contains("COMISSÃO")) + { + return; + } + tuples.Add(new Tuple(x.get_Descricao(), (string.IsNullOrEmpty(x.get_ValorAtual()) ? "NÃO PREENCHIDO" : (x.get_ValorAtual() == "True" ? "SIM" : (x.get_ValorAtual() == "False" ? "NÃO" : x.get_ValorAtual()))), "")); + }); + List tupleLists = new List(); + TupleList tupleList = new TupleList(); + tupleList.set_Tuples(new ObservableCollection>(tuples)); + tupleLists.Add(tupleList); + return tupleLists; + } + + public static List LogList(this List valores, bool restricaoComissao = false) + { + List> tuples = new List>(); + valores.ForEach((Diferenca x) => { + if (restricaoComissao && x.get_Campo().ToUpper().Contains("COMISSÃO")) + { + return; + } + tuples.Add(new Tuple(x.get_Descricao(), (string.IsNullOrEmpty(x.get_ValorAtual()) ? "NÃO PREENCHIDO" : (x.get_ValorAtual() == "True" ? "SIM" : (x.get_ValorAtual() == "False" ? "NÃO" : x.get_ValorAtual()))), (string.IsNullOrEmpty(x.get_ValorAnterior()) ? "NÃO PREENCHIDO" : (x.get_ValorAnterior() == "True" ? "SIM" : (x.get_ValorAnterior() == "False" ? "NÃO" : x.get_ValorAnterior()))))); + }); + List tupleLists = new List(); + TupleList tupleList = new TupleList(); + tupleList.set_Tuples(new ObservableCollection>(tuples)); + tupleLists.Add(tupleList); + return tupleLists; + } + + public static async Task MostrarErro(TipoErro erro) + { + await System.Windows.Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => (new ErrorWindow(erro, true)).ShowDialog())); + } + + private static string NodeText(HtmlNode node) + { + string innerText = ""; + if (node.get_HasChildNodes()) + { + foreach (HtmlNode childNode in node.get_ChildNodes()) + { + innerText = string.Concat(innerText, (childNode.get_NodeType() == 3 ? childNode.get_InnerText() : Funcoes.NodeText(childNode))); + } + } + else if (node.get_NodeType() == 3) + { + innerText = node.get_InnerText(); + } + return innerText; + } + + public static async Task> OcultarColunas(Relatorio relatorio) + { + List strs; + List strs1 = new List(); + List restricoesColunas = await (new ConfuguracoesServico()).BuscarParametros(relatorio); + if (restricoesColunas == null || restricoesColunas.Count == 0) + { + strs = strs1; + } + else + { + restricoesColunas = await Funcoes.GetRestricoesColunas(restricoesColunas); + PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public); + for (int i = 0; i < (int)properties.Length; i++) + { + PropertyInfo propertyInfo = properties[i]; + object obj = propertyInfo.GetCustomAttributes(typeof(TipoAttribute), true).FirstOrDefault(); + string description = ""; + if (obj != null) + { + description = ((TipoAttribute)obj).get_Description(); + } + string descriptionAttribute = propertyInfo.GetDescriptionAttribute(); + if (description == "INVALID") + { + strs1.Add(descriptionAttribute); + } + if (!restricoesColunas.Any((ParametrosRelatorio x) => x.get_Campo() == propertyInfo.Name) && !(propertyInfo.Name == "ValidationEvent")) + { + strs1.Add(descriptionAttribute); + } + } + strs = strs1; + } + strs1 = null; + return strs; + } + + public static List OcultarColunasDescricao(Type type, string categoria) + { + List strs = new List(); + PropertyInfo[] properties = type.GetProperties(); + for (int i = 0; i < (int)properties.Length; i++) + { + PropertyInfo propertyInfo = properties[i]; + if (propertyInfo.Name != "ValidationEvent") + { + object obj = propertyInfo.GetCustomAttributes(typeof(CategoryAttribute), true).FirstOrDefault(); + if (obj != null && !(((CategoryAttribute)obj).Category == categoria)) + { + object obj1 = propertyInfo.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault(); + if (obj1 != null) + { + strs.Add(((DescriptionAttribute)obj1).Description); + } + } + } + } + return strs; + } + + public static async Task OrganizarDocumentos(long id) + { + ApoliceServico apoliceServico = new ApoliceServico(); + Controle controle = await apoliceServico.BuscarControleAsync(id); + int num = 1; + IList documentos = controle.get_Documentos(); + IEnumerable excluido = + from x in documentos + where !x.get_Excluido() + select x; + ( + from x in excluido + orderby x.get_Vigencia1() + select x).ToList().ForEach((Documento x) => { + if (x.get_Tipo() == 0) + { + x.set_Ordem(0); + return; + } + x.set_Ordem(num); + num++; + }); + await apoliceServico.UpdateRange(controle); + apoliceServico = null; + } + + public static ParentescoVinculo? ParentescoInverso(ParentescoVinculo? parentesco) + { + if (parentesco.HasValue) + { + switch (parentesco.GetValueOrDefault()) + { + case 0: + { + return new ParentescoVinculo?(1); + } + case 1: + { + return new ParentescoVinculo?(0); + } + case 3: + { + return new ParentescoVinculo?(4); + } + case 4: + { + return new ParentescoVinculo?(3); + } + case 5: + { + return new ParentescoVinculo?(6); + } + case 6: + { + return new ParentescoVinculo?(5); + } + case 7: + { + return new ParentescoVinculo?(8); + } + case 8: + { + return new ParentescoVinculo?(7); + } + case 10: + { + return new ParentescoVinculo?(11); + } + case 11: + { + return new ParentescoVinculo?(10); + } + case 13: + { + return new ParentescoVinculo?(14); + } + case 14: + { + return new ParentescoVinculo?(13); + } + case 19: + { + return new ParentescoVinculo?(20); + } + case 20: + { + return new ParentescoVinculo?(19); + } + case 21: + { + return new ParentescoVinculo?(22); + } + case 22: + { + return new ParentescoVinculo?(21); + } + } + } + return parentesco; + } + + public static TipoPagamento ParseTransactionType(this OfxTransactionType type) + { + switch (type) + { + case 0: + { + return 5; + } + case 1: + case 4: + { + return 7; + } + case 6: + case 13: + { + return 8; + } + case 7: + case 12: + { + return 10; + } + case 10: + { + return 4; + } + case 11: + { + return 15; + } + case 14: + { + return 6; + } + default: + { + return 12; + } + } + } + + public static string PlacaVencimento(string placa, Categoria? categoria) + { + if (string.IsNullOrEmpty(placa)) + { + return ""; + } + string str = placa.Substring(placa.Length - 1, 1); + if (str != null && str.Length == 1) + { + switch (str[0]) + { + case '0': + { + return "DEZEMBRO"; + } + case '1': + { + if (categoria.HasValue && categoria.GetValueOrDefault() == 4) + { + return "SETEMBRO"; + } + return "ABRIL"; + } + case '2': + { + if (categoria.HasValue && categoria.GetValueOrDefault() == 4) + { + return "SETEMBRO"; + } + return "MAIO"; + } + case '3': + { + if (categoria.HasValue && categoria.GetValueOrDefault() == 4) + { + return "OUTUBRO"; + } + return "JUNHO"; + } + case '4': + { + if (categoria.HasValue && categoria.GetValueOrDefault() == 4) + { + return "OUTUBRO"; + } + return "JULHO"; + } + case '5': + { + if (categoria.HasValue && categoria.GetValueOrDefault() == 4) + { + return "OUTUBRO"; + } + return "AGOSTO"; + } + case '6': + { + if (categoria.HasValue && categoria.GetValueOrDefault() == 4) + { + return "NOVEMBRO"; + } + return "AGOSTO"; + } + case '7': + { + if (categoria.HasValue && categoria.GetValueOrDefault() == 4) + { + return "NOVEMBRO"; + } + return "SETEMBRO"; + } + case '8': + { + if (categoria.HasValue && categoria.GetValueOrDefault() == 4) + { + return "NOVEMBRO"; + } + return "OUTUBRO"; + } + case '9': + { + if (categoria.HasValue && categoria.GetValueOrDefault() == 4) + { + return "DEZEMBRO"; + } + return "NOVEMBRO"; + } + } + } + return ""; + } + + public static List PopularFiltroFinanceiro() + { + List filtroPersonalizados = new List(); + FiltroPersonalizado filtroPersonalizado = new FiltroPersonalizado(); + filtroPersonalizado.set_Propriedade("Id"); + filtroPersonalizado.set_Nome("ID"); + filtroPersonalizado.set_Tipo(typeof(long)); + filtroPersonalizados.Add(filtroPersonalizado); + FiltroPersonalizado filtroPersonalizado1 = new FiltroPersonalizado(); + filtroPersonalizado1.set_Propriedade("Controle.Fornecedor.NomeSocial"); + filtroPersonalizado1.set_Nome("FORNECEDOR"); + filtroPersonalizado1.set_Tipo(typeof(string)); + filtroPersonalizados.Add(filtroPersonalizado1); + FiltroPersonalizado filtroPersonalizado2 = new FiltroPersonalizado(); + filtroPersonalizado2.set_Propriedade("Controle.Fornecedor.Ativo"); + filtroPersonalizado2.set_Nome("FORNECEDOR ATIVO"); + filtroPersonalizado2.set_Tipo(typeof(string)); + filtroPersonalizados.Add(filtroPersonalizado2); + FiltroPersonalizado filtroPersonalizado3 = new FiltroPersonalizado(); + filtroPersonalizado3.set_Propriedade("Historico"); + filtroPersonalizado3.set_Nome("HISTÓRICO"); + filtroPersonalizado3.set_Tipo(typeof(string)); + filtroPersonalizados.Add(filtroPersonalizado3); + FiltroPersonalizado filtroPersonalizado4 = new FiltroPersonalizado(); + filtroPersonalizado4.set_Propriedade("Parcela"); + filtroPersonalizado4.set_Nome("PARCELA"); + filtroPersonalizado4.set_Tipo(typeof(int)); + filtroPersonalizados.Add(filtroPersonalizado4); + FiltroPersonalizado filtroPersonalizado5 = new FiltroPersonalizado(); + filtroPersonalizado5.set_Propriedade("Documento"); + filtroPersonalizado5.set_Nome("DOCUMENTO"); + filtroPersonalizado5.set_Tipo(typeof(string)); + filtroPersonalizados.Add(filtroPersonalizado5); + FiltroPersonalizado filtroPersonalizado6 = new FiltroPersonalizado(); + filtroPersonalizado6.set_Propriedade("Competencia"); + filtroPersonalizado6.set_Nome("COMPETÊNCIA"); + filtroPersonalizado6.set_Tipo(typeof(string)); + filtroPersonalizados.Add(filtroPersonalizado6); + FiltroPersonalizado filtroPersonalizado7 = new FiltroPersonalizado(); + filtroPersonalizado7.set_Propriedade("Complemento"); + filtroPersonalizado7.set_Nome("COMPLEMENTO"); + filtroPersonalizado7.set_Tipo(typeof(string)); + filtroPersonalizados.Add(filtroPersonalizado7); + FiltroPersonalizado filtroPersonalizado8 = new FiltroPersonalizado(); + filtroPersonalizado8.set_Propriedade("Vencimento"); + filtroPersonalizado8.set_Nome("VENCIMENTO"); + filtroPersonalizado8.set_Tipo(typeof(DateTime)); + filtroPersonalizados.Add(filtroPersonalizado8); + FiltroPersonalizado filtroPersonalizado9 = new FiltroPersonalizado(); + filtroPersonalizado9.set_Propriedade("Valor"); + filtroPersonalizado9.set_Nome("VALOR"); + filtroPersonalizado9.set_Tipo(typeof(decimal)); + filtroPersonalizados.Add(filtroPersonalizado9); + FiltroPersonalizado filtroPersonalizado10 = new FiltroPersonalizado(); + filtroPersonalizado10.set_Propriedade("Baixa"); + filtroPersonalizado10.set_Nome("DATA BAIXA"); + filtroPersonalizado10.set_Tipo(typeof(DateTime)); + filtroPersonalizados.Add(filtroPersonalizado10); + FiltroPersonalizado filtroPersonalizado11 = new FiltroPersonalizado(); + filtroPersonalizado11.set_Propriedade("ValorPago"); + filtroPersonalizado11.set_Nome("VALOR PAGO"); + filtroPersonalizado11.set_Tipo(typeof(decimal)); + filtroPersonalizados.Add(filtroPersonalizado11); + FiltroPersonalizado filtroPersonalizado12 = new FiltroPersonalizado(); + filtroPersonalizado12.set_Propriedade("Pagamento"); + filtroPersonalizado12.set_Nome("PAGAMENTO"); + filtroPersonalizado12.set_Tipo(typeof(DateTime)); + filtroPersonalizados.Add(filtroPersonalizado12); + FiltroPersonalizado filtroPersonalizado13 = new FiltroPersonalizado(); + filtroPersonalizado13.set_Propriedade("Conta.Descricao"); + filtroPersonalizado13.set_Nome("CONTA"); + filtroPersonalizado13.set_Tipo(typeof(string)); + filtroPersonalizados.Add(filtroPersonalizado13); + FiltroPersonalizado filtroPersonalizado14 = new FiltroPersonalizado(); + filtroPersonalizado14.set_Propriedade("Controle.Plano.Descricao"); + filtroPersonalizado14.set_Nome("PLANO DE CONTAS"); + filtroPersonalizado14.set_Tipo(typeof(string)); + filtroPersonalizados.Add(filtroPersonalizado14); + FiltroPersonalizado filtroPersonalizado15 = new FiltroPersonalizado(); + filtroPersonalizado15.set_Propriedade("Controle.Centro.Descricao"); + filtroPersonalizado15.set_Nome("CENTRO DE CUSTO"); + filtroPersonalizado15.set_Tipo(typeof(string)); + filtroPersonalizados.Add(filtroPersonalizado15); + FiltroPersonalizado filtroPersonalizado16 = new FiltroPersonalizado(); + filtroPersonalizado16.set_Propriedade("Sinal"); + filtroPersonalizado16.set_Nome("SINAL"); + filtroPersonalizado16.set_Tipo(typeof(Enum)); + filtroPersonalizados.Add(filtroPersonalizado16); + FiltroPersonalizado filtroPersonalizado17 = new FiltroPersonalizado(); + filtroPersonalizado17.set_Propriedade("TipoPagamento"); + filtroPersonalizado17.set_Nome("FORMA PAGAMENTO"); + filtroPersonalizado17.set_Tipo(typeof(Enum)); + filtroPersonalizados.Add(filtroPersonalizado17); + FiltroPersonalizado filtroPersonalizado18 = new FiltroPersonalizado(); + filtroPersonalizado18.set_Propriedade("Observacao"); + filtroPersonalizado18.set_Nome("OBSERVAÇÃO"); + filtroPersonalizado18.set_Tipo(typeof(string)); + filtroPersonalizados.Add(filtroPersonalizado18); + FiltroPersonalizado filtroPersonalizado19 = new FiltroPersonalizado(); + filtroPersonalizado19.set_Propriedade("Controle.Plano.Nome"); + filtroPersonalizado19.set_Nome("PLANO"); + filtroPersonalizado19.set_Tipo(typeof(string)); + filtroPersonalizados.Add(filtroPersonalizado19); + return filtroPersonalizados; + } + + public static List PopularFiltroPersonalizado() + { + List filtroPersonalizados = new List(); + foreach (PropertyInfo propertyInfo in + from in (IEnumerable)typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public) + orderby Gestor.Common.Validation.ValidationHelper.DescriptionAttribute(x) + select ) + { + if (propertyInfo.Name == "ValidationEvent") + { + continue; + } + FiltroPersonalizado filtroPersonalizado = new FiltroPersonalizado(); + filtroPersonalizado.set_Propriedade(propertyInfo.Name); + filtroPersonalizado.set_Nome(propertyInfo.GetDescriptionAttribute()); + FiltroPersonalizado filtroPersonalizado1 = filtroPersonalizado; + if (propertyInfo.GetTypeAttribute() == "INVALID") + { + continue; + } + Type propertyType = propertyInfo.PropertyType; + if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) + { + propertyType = propertyType.GetGenericArguments()[0]; + } + filtroPersonalizado1.set_Tipo((propertyType.BaseType == typeof(Enum) ? propertyType.BaseType : propertyType)); + filtroPersonalizados.Add(filtroPersonalizado1); + } + return filtroPersonalizados; + } + + public static bool ProgramaEmExecucao(this string programName) + { + return Process.GetProcessesByName(programName).Length != 0; + } + + public static async Task ReativarItens(List ids) + { + ItemServico itemServico = new ItemServico(); + List items = await itemServico.BuscarItems(ids); + List items1 = items; + items1.ForEach((Item x) => { + x.set_Substituido(null); + x.set_Cancelado(false); + x.set_Status(x.get_StatusInclusao()); + }); + await itemServico.SaveRange(items); + bool sucesso = itemServico.Sucesso; + itemServico = null; + return sucesso; + } + + public static async Task RecusarApolice(Documento documento, string motivo, bool estorno) + { + bool flag; + string str; + NegocioCorretora negocioCorretora; + NegocioCorretora negocioCorretora1; + ApoliceServico apoliceServico = new ApoliceServico(); + CriticaApoliceServico criticaApoliceServico = new CriticaApoliceServico(); + if (documento.get_Tipo() != 0 || !string.IsNullOrEmpty(documento.get_Apolice())) + { + str = (documento.get_Tipo() != 0 || string.IsNullOrEmpty(documento.get_Apolice()) ? "ENDOSSO RECUSADO" : "APÓLICE RECUSADA"); + } + else + { + str = "PROPOSTA RECUSADA"; + } + string str1 = str; + if (!string.IsNullOrWhiteSpace(motivo)) + { + Documento documento1 = documento; + object[] nome = new object[] { Recursos.Usuario.get_Nome(), Recursos.Usuario.get_Id(), Funcoes.GetNetworkTime(), Environment.NewLine, motivo, Environment.NewLine, Environment.NewLine, documento.get_Observacao() }; + documento1.set_Observacao(string.Format("{0}, ID: {1}, {2:g}{3}RECUSA: {4}{5}{6}{7}", nome)); + } + if (documento.get_Tipo() != 0) + { + if (!documento.get_NegocioCorretora().HasValue) + { + Documento documento2 = documento; + negocioCorretora = (!documento.get_Negocio().HasValue || documento.get_Negocio().GetValueOrDefault() != 1 ? 0 : 1); + documento2.set_NegocioCorretora(new NegocioCorretora?(negocioCorretora)); + } + documento.set_Situacao(7); + documento.set_Apolice("RECUSADA"); + documento.set_Endosso("RECUSADA"); + flag = await apoliceServico.BaixarParcelasCancelamento(documento, estorno); + if (!flag) + { + Action acessaTela = Gestor.Application.Actions.Actions.AcessaTela; + if (acessaTela != null) + { + acessaTela(21, ""); + } + else + { + } + } + await apoliceServico.Save(documento, false, false); + if (!apoliceServico.Sucesso) + { + Action action = Gestor.Application.Actions.Actions.AcessaTela; + if (action != null) + { + action(21, ""); + } + else + { + } + } + if (!apoliceServico.Sucesso) + { + Action acessaTela1 = Gestor.Application.Actions.Actions.AcessaTela; + if (acessaTela1 != null) + { + acessaTela1(21, ""); + } + else + { + } + } + flag = await Funcoes.InativarItens(documento.get_Id(), documento.get_Controle().get_Ramo().get_Id(), false); + if (!flag) + { + Action action1 = Gestor.Application.Actions.Actions.AcessaTela; + if (action1 != null) + { + action1(21, ""); + } + else + { + } + } + } + else + { + await apoliceServico.Save(documento, false, false); + Controle controle = await apoliceServico.BuscarControleAsync(documento.get_Controle().get_Id()); + if (controle.get_Id() != 0) + { + foreach (Documento documento3 in controle.get_Documentos()) + { + if (!documento3.get_NegocioCorretora().HasValue) + { + Documento documento4 = documento3; + negocioCorretora1 = (!documento3.get_Negocio().HasValue || documento3.get_Negocio().GetValueOrDefault() != 1 ? 0 : 1); + documento4.set_NegocioCorretora(new NegocioCorretora?(negocioCorretora1)); + } + documento3.set_Situacao(7); + documento3.set_Apolice("RECUSADA"); + flag = await apoliceServico.BaixarParcelasCancelamento(documento3, estorno); + if (flag) + { + continue; + } + Action acessaTela2 = Gestor.Application.Actions.Actions.AcessaTela; + if (acessaTela2 != null) + { + acessaTela2(21, ""); + } + else + { + } + } + flag = await apoliceServico.UpdateRange(controle); + controle = null; + } + else + { + apoliceServico = null; + criticaApoliceServico = null; + str1 = null; + return; + } + } + if (!flag) + { + Action action2 = Gestor.Application.Actions.Actions.AcessaTela; + if (action2 != null) + { + action2(21, ""); + } + else + { + } + } + List criticaApolices = await criticaApoliceServico.BuscarCritica(documento.get_Id()); + if (criticaApolices != null) + { + foreach (CriticaApolice criticaApolouse in criticaApolices) + { + criticaApolouse.set_Critica(new bool?(true)); + await criticaApoliceServico.Save(criticaApolouse); + } + } + Action acessaTela3 = Gestor.Application.Actions.Actions.AcessaTela; + if (acessaTela3 != null) + { + acessaTela3(21, ""); + } + else + { + } + Funcoes.ToggleSnackBar(string.Concat(str1, " COM SUCESSO"), true); + apoliceServico = null; + criticaApoliceServico = null; + str1 = null; + } + + private static async void RegistrarLogBaixa(long id, DateTime now) + { + string str; + ApoliceServico apoliceServico = new ApoliceServico(); + ParcelaServico parcelaServico = new ParcelaServico(); + VendedorServico vendedorServico = new VendedorServico(); + Documento documento = await apoliceServico.BuscarApoliceAsync(id, false, false); + Documento documento1 = documento; + ObservableCollection observableCollection = await parcelaServico.BuscarParcelasAsync(documento.get_Id()); + documento1.set_Parcelas(observableCollection); + documento1 = null; + List vendedorParcelas = await vendedorServico.BuscaRepasse(documento.get_Id()); + foreach (Parcela parcela in documento.get_Parcelas()) + { + foreach (VendedorParcela vendedorParcela in vendedorParcelas) + { + if (vendedorParcela.get_Parcela().get_Id() != parcela.get_Id()) + { + continue; + } + if (parcela.get_Vendedores() == null) + { + parcela.set_Vendedores(new ObservableCollection()); + } + parcela.get_Vendedores().Add(vendedorParcela); + } + } + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(1); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(now); + Documento documento2 = documento; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(documento2, jsonSerializerSetting)); + registroLog.set_EntidadeId(documento.get_Id()); + registroLog.set_Tela(2); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + RegistroLog registroLog1 = registroLog; + using (UnitOfWork commited = Instancia.Commited) + { + commited.get_RegistroLogRepository().SaveOrUpdate(registroLog1); + commited.Commit(); + } + parcelaServico = null; + vendedorServico = null; + documento = null; + } + + public static string RemoverAcentos(string text) + { + string str = text.Normalize(NormalizationForm.FormD); + StringBuilder stringBuilder = new StringBuilder(); + foreach (char chr in + from c in str + let unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c) + where unicodeCategory != UnicodeCategory.NonSpacingMark + select c) + { + stringBuilder.Append(chr); + } + return stringBuilder.ToString().Normalize(NormalizationForm.FormC); + } + + [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false)] + private static extern bool SetForegroundWindow(IntPtr hWnd); + + [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false)] + private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); + + public static string SubstituirVariaveis(string corpo, MalaDireta envio) + { + DateTime? vigencia2; + DateTime vigencia1; + decimal valor; + decimal? nullable; + bool controle; + bool flag; + string str; + string str1; + string str2; + string str3; + object obj; + string str4; + string str5; + string description; + decimal? nullable1; + string str6; + decimal? nullable2; + string str7; + DateTime networkTime = Funcoes.GetNetworkTime(); + VariaveisMalaDireta[] values = (VariaveisMalaDireta[])Enum.GetValues(typeof(VariaveisMalaDireta)); + for (int i = 0; i < (int)values.Length; i++) + { + VariaveisMalaDireta variaveisMalaDiretum = values[i]; + switch (variaveisMalaDiretum) + { + case 0: + { + corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), networkTime.ToString(new CultureInfo("pt-BR"))); + break; + } + case 1: + { + corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), (Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(envio.get_Cliente().get_NomeSocialRg()) ? envio.get_Cliente().get_NomeSocialRg() : envio.get_Cliente().get_Nome())); + break; + } + case 2: + { + corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), envio.get_Cliente().get_Documento()); + break; + } + case 3: + { + if (envio.get_Apolice() == null) + { + break; + } + corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), envio.get_Apolice().get_Proposta()); + break; + } + case 4: + { + if (envio.get_Apolice() == null) + { + break; + } + corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), string.Concat(envio.get_Apolice().get_Apolice(), (envio.get_Apolice().get_Tipo() != 0 ? string.Concat(", endosso de número: ", envio.get_Apolice().get_Endosso()) : ""))); + break; + } + case 5: + { + Documento apolice = envio.get_Apolice(); + if (apolice != null) + { + controle = apolice.get_Controle(); + } + else + { + controle = false; + } + if (!controle) + { + break; + } + corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), envio.get_Apolice().get_Controle().get_Ramo().get_Nome()); + break; + } + case 6: + { + Documento documento = envio.get_Apolice(); + if (documento != null) + { + flag = documento.get_Controle(); + } + else + { + flag = false; + } + if (!flag) + { + break; + } + corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), envio.get_Apolice().get_Controle().get_Seguradora().get_Nome()); + break; + } + case 7: + { + if (envio.get_Apolice() == null) + { + break; + } + string entity = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum); + vigencia1 = envio.get_Apolice().get_Vigencia1(); + corpo = corpo.Replace(entity, vigencia1.ToString("d")); + break; + } + case 8: + { + if (envio.get_Apolice() == null) + { + break; + } + string str8 = corpo; + string entity1 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum); + vigencia2 = envio.get_Apolice().get_Vigencia2(); + if (vigencia2.HasValue) + { + vigencia1 = vigencia2.GetValueOrDefault(); + str = vigencia1.ToString("d"); + } + else + { + str = null; + } + corpo = str8.Replace(entity1, str); + break; + } + case 9: + { + if (envio.get_Parcela() == null) + { + break; + } + string entity2 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum); + vigencia1 = envio.get_Parcela().get_Vencimento(); + corpo = corpo.Replace(entity2, vigencia1.ToString("d")); + break; + } + case 10: + { + if (envio.get_Parcela() == null) + { + break; + } + string entity3 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum); + valor = envio.get_Parcela().get_Valor(); + corpo = corpo.Replace(entity3, valor.ToString("c2")); + break; + } + case 11: + { + if (envio.get_Item() == null) + { + break; + } + corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), envio.get_Item().get_Descricao()); + break; + } + case 12: + { + if (envio.get_Sinistro() == null) + { + break; + } + corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), envio.get_Sinistro().get_Numero()); + break; + } + case 13: + { + if (envio.get_Parcela() == null) + { + break; + } + string entity4 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum); + int numeroParcela = envio.get_Parcela().get_NumeroParcela(); + corpo = corpo.Replace(entity4, numeroParcela.ToString()); + break; + } + case 14: + { + vigencia2 = envio.get_Cliente().get_Nascimento(); + if (!vigencia2.HasValue) + { + break; + } + string str9 = corpo; + string entity5 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum); + vigencia2 = envio.get_Cliente().get_Nascimento(); + if (vigencia2.HasValue) + { + vigencia1 = vigencia2.GetValueOrDefault(); + str1 = vigencia1.ToString("dd/MM"); + } + else + { + str1 = null; + } + corpo = str9.Replace(entity5, str1); + break; + } + case 15: + { + vigencia2 = envio.get_Cliente().get_Nascimento(); + if (!vigencia2.HasValue) + { + break; + } + string str10 = corpo; + string entity6 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum); + vigencia2 = envio.get_Cliente().get_Nascimento(); + if (vigencia2.HasValue) + { + vigencia1 = vigencia2.GetValueOrDefault(); + str2 = vigencia1.ToString("d"); + } + else + { + str2 = null; + } + corpo = str10.Replace(entity6, str2); + break; + } + case 16: + { + string str11 = corpo; + string entity7 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum); + vigencia2 = envio.get_Cliente().get_VencimentoHabilitacao(); + if (vigencia2.HasValue) + { + vigencia1 = vigencia2.GetValueOrDefault(); + str3 = vigencia1.ToString("d"); + } + else + { + str3 = null; + } + corpo = str11.Replace(entity7, str3); + break; + } + case 17: + { + if (envio.get_ArquivoDigital() != null) + { + if (!envio.get_ArquivoDigital().All((IndiceArquivoDigital x) => string.IsNullOrWhiteSpace(x.get_UrlAssinatura()))) + { + string str12 = ""; + ( + from x in envio.get_ArquivoDigital() + where !string.IsNullOrWhiteSpace(x.get_UrlAssinatura()) + select x).ToList().ForEach((IndiceArquivoDigital x) => str12 = string.Concat(new string[] { str12, "" })); + str12 = string.Concat(str12, "
ABAIXO OS DOCUMENTOS PARA ASSINATURA
", x.get_Descricao(), "
"); + corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), str12); + break; + } + } + corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), string.Empty); + break; + } + case 18: + { + string str13 = string.Format("ABAIXO O LINK PARA MEU CARTÃO DE VISITA.
CARTÃO DE VISITA ELETRÔNICO", Address.get_Card(), Recursos.Usuario.get_Id().GeraCartaoVisita()); + corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), str13); + break; + } + case 19: + { + if (envio.get_Apolice() != null) + { + Uri assistance = Address.get_Assistance(); + if (envio != null) + { + Documento apolice1 = envio.get_Apolice(); + if (apolice1 != null) + { + obj = apolice1.get_Id().GeraAssistencia(); + } + else + { + obj = null; + } + } + else + { + obj = null; + } + string str14 = string.Format("ABAIXO O LINK PARA O SEU CARTÃO ASSISTÊNCIA.
CARTÃO ASSISTÊNCIA", assistance, obj); + corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), str14); + break; + } + else + { + corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), string.Empty); + break; + } + } + case 20: + { + string str15 = corpo; + string entity8 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum); + Documento documento1 = envio.get_Apolice(); + if (documento1 != null) + { + str4 = documento1.get_PremioLiquido().ToString("c"); + } + else + { + str4 = null; + } + corpo = str15.Replace(entity8, str4); + break; + } + case 21: + { + string str16 = corpo; + string entity9 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum); + Documento apolice2 = envio.get_Apolice(); + if (apolice2 != null) + { + str5 = apolice2.get_PremioTotal().ToString("c"); + } + else + { + str5 = null; + } + corpo = str16.Replace(entity9, str5); + break; + } + case 22: + { + string str17 = corpo; + string entity10 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum); + Documento documento2 = envio.get_Apolice(); + if (documento2 != null) + { + FormaPagamento? formaPagamento = documento2.get_FormaPagamento(); + if (formaPagamento.HasValue) + { + description = Gestor.Common.Validation.ValidationHelper.GetDescription(formaPagamento.GetValueOrDefault()); + } + else + { + description = null; + } + } + else + { + description = null; + } + corpo = str17.Replace(entity10, description); + break; + } + case 23: + { + string str18 = corpo; + string entity11 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum); + Documento apolice3 = envio.get_Apolice(); + if (apolice3 != null) + { + nullable1 = new decimal?(apolice3.get_NumeroParcelas()); + } + else + { + nullable = null; + nullable1 = nullable; + } + if (!nullable1.HasValue || envio.get_Apolice().get_TipoRecebimento().GetValueOrDefault() == 2) + { + str6 = "Indefinido"; + } + else + { + Documento documento3 = envio.get_Apolice(); + if (documento3 != null) + { + str6 = documento3.get_NumeroParcelas().ToString(); + } + else + { + str6 = null; + } + } + corpo = str18.Replace(entity11, str6); + break; + } + case 24: + { + string str19 = corpo; + string entity12 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum); + Documento apolice4 = envio.get_Apolice(); + if (apolice4 != null) + { + nullable2 = new decimal?(apolice4.get_NumeroParcelas()); + } + else + { + nullable = null; + nullable2 = nullable; + } + if (!nullable2.HasValue || envio.get_Apolice().get_NumeroParcelas() == decimal.Zero || envio.get_Apolice().get_TipoRecebimento().GetValueOrDefault() == 2) + { + str7 = "Verificar documento anexado"; + } + else + { + valor = envio.get_Apolice().get_PremioTotal() / envio.get_Apolice().get_NumeroParcelas(); + str7 = valor.ToString(); + } + corpo = str19.Replace(entity12, str7); + break; + } + } + } + return corpo; + } + + public static void ToggleSnackBar(string message, bool active = true) + { + App.SnackBar.get_Message().Content = message; + App.SnackBar.set_IsActive(active); + if (!active) + { + return; + } + Task.Factory.StartNew(new Action(Funcoes.CloseSlackBar)); + } + + public static List TotalizacoesRelatorio(Relatorio relatorio, List parametrosAdicionados) + { + long id; + List parametrosTotalizacaos = new List(); + List strs = new List(); + switch (relatorio) + { + case 2: + case 3: + { + strs.Add("PremioTotal"); + strs.Add("PremioLiquido"); + strs.Add("MediaComissao"); + strs.Add("ComissaoGerada"); + strs.Add("Cancelamentos"); + strs.Add("Novos"); + strs.Add("NegociosProprios"); + strs.Add("Renovacoes"); + strs.Add("SegurosNovos"); + strs.Add("Apolices"); + strs.Add("Endossos"); + strs.Add("Faturas"); + strs.Add("TotalGeral"); + strs.Add("MediaPonderada"); + goto case 15; + } + case 4: + { + strs.Add("Cancelamentos"); + strs.Add("Novos"); + strs.Add("Renovacoes"); + strs.Add("Apolices"); + strs.Add("Endossos"); + strs.Add("Faturas"); + strs.Add("TotalProspeccao"); + strs.Add("TotalGeral"); + strs.Add("PremioTotal"); + strs.Add("PremioLiquido"); + strs.Add("ComissaoGerada"); + goto case 15; + } + case 5: + { + strs.Add("ComissaoRecebidaBruta"); + strs.Add("ComissaoRecebidaLiquida"); + strs.Add("ComissaoPrevista"); + strs.Add("Repasse"); + strs.Add("Impostos"); + strs.Add("PremioTotal"); + strs.Add("PremioLiquido"); + goto case 15; + } + case 6: + case 16: + { + strs.Add("ComissaoPrevista"); + strs.Add("TotalPrevista"); + strs.Add("TotalGeral"); + strs.Add("TotalParcela"); + goto case 15; + } + case 7: + case 11: + case 12: + case 13: + case 14: + case 15: + { + PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public); + foreach (PropertyInfo propertyInfo in + from in (IEnumerable)properties + orderby x.GetDescriptionAttribute() + select ) + { + if (propertyInfo.Name == "ValidationEvent" || propertyInfo.GetTypeAttribute() == "INVALID" || !strs.Contains(propertyInfo.Name) || propertyInfo.Name == "Agrupamento" || parametrosAdicionados.Any((ParametrosTotalizacao x) => x.get_Campo() == propertyInfo.Name)) + { + continue; + } + ParametrosTotalizacao parametrosTotalizacao = new ParametrosTotalizacao(); + ParametrosTotalizacao parametrosTotalizacao1 = parametrosAdicionados.FirstOrDefault((ParametrosTotalizacao x) => { + if (x.get_IdUsuario() == 0) + { + return false; + } + return x.get_Campo() == propertyInfo.Name; + }); + if (parametrosTotalizacao1 != null) + { + id = parametrosTotalizacao1.get_Id(); + } + else + { + id = (long)0; + } + parametrosTotalizacao.set_Id(id); + parametrosTotalizacao.set_Campo(propertyInfo.Name); + parametrosTotalizacao.set_Header(propertyInfo.GetDescriptionAttribute()); + parametrosTotalizacao.set_IdUsuario(Recursos.Usuario.get_Id()); + parametrosTotalizacao.set_Relatorio(relatorio); + parametrosTotalizacaos.Add(parametrosTotalizacao); + } + return parametrosTotalizacaos; + } + case 8: + { + strs.Add("PremioTotal"); + strs.Add("PremioLiquido"); + strs.Add("ComissaoRecebidaBruta"); + strs.Add("MediaComissao"); + strs.Add("TotalPrevista"); + strs.Add("ComissaoGerada"); + strs.Add("Cancelamentos"); + strs.Add("Novos"); + strs.Add("Renovacoes"); + strs.Add("Apolices"); + strs.Add("Endossos"); + strs.Add("Faturas"); + strs.Add("TotalGeral"); + goto case 15; + } + case 9: + case 10: + { + strs.Add("Liquidado"); + strs.Add("ValorLiquidado"); + strs.Add("Pendente"); + strs.Add("TotalGeral"); + strs.Add("TotalClientes"); + strs.Add("TotalTerceiros"); + goto case 15; + } + default: + { + goto case 15; + } + } + } + + public static long UnixTimeStamp() + { + DateTime utcNow = DateTime.UtcNow; + TimeSpan timeSpan = utcNow.Subtract(new DateTime(1970, 1, 1)); + return (long)timeSpan.TotalSeconds; + } + + public static string ValidaNomePlanilha(this string nome, string agrupamento = "", int index = 0) + { + if (string.IsNullOrWhiteSpace(nome)) + { + nome = agrupamento; + } + nome = nome.Replace("/", "_").Replace(":", " ").Replace("*", " ").Replace("?", "").Trim(); + if (index > 0) + { + nome = string.Format("{0} {1}", index, nome); + } + if (nome.Length > 30) + { + nome = nome.Substring(0, 30); + } + return nome; + } + + public static async Task VerificarPagamento(long id) + { + bool[] flagArray = new bool[2]; + List parcelas = await (new ParcelaServico()).BuscarParcelas(id); + if (parcelas.Any((Parcela x) => x.get_DataRecebimento().HasValue)) + { + flagArray[0] = true; + } + List vendedorParcelas = await (new VendedorServico()).BuscaRepasse(id); + if (vendedorParcelas.Any((VendedorParcela x) => x.get_DataPagamento().HasValue)) + { + flagArray[1] = true; + } + bool[] flagArray1 = flagArray; + flagArray = null; + return flagArray1; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/HttpHelper.cs b/Codemerx/Gestor.Application/Helpers/HttpHelper.cs new file mode 100644 index 0000000..e042d1b --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/HttpHelper.cs @@ -0,0 +1,103 @@ +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Linq; +using System.Net.Http; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading.Tasks; + +namespace Gestor.Application.Helpers +{ + public static class HttpHelper + { + public static Uri AddQuery(this Uri uri, string name, T value) + { + // + // Current member / type: System.Uri Gestor.Application.Helpers.HttpHelper::AddQuery(System.Uri,System.String,T) + // File path: C:\AggerSeguros\Gestor.Application.exe + // + // Product version: 0.0.0.0 + // Exception in: System.Uri AddQuery(System.Uri,System.String,T) + // + // Managed pointer usage not in SSA + // at Telerik.JustDecompiler.Steps.ManagedPointersRemovalStep.CheckForAssignment(BinaryExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\ManagedPointersRemovalStep.cs:line 100 + // at Telerik.JustDecompiler.Steps.ManagedPointersRemovalStep.VisitBinaryExpression(BinaryExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\ManagedPointersRemovalStep.cs:line 80 + // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 351 + // at Telerik.JustDecompiler.Steps.ManagedPointersRemovalStep.VisitExpressions() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\ManagedPointersRemovalStep.cs:line 41 + // at Telerik.JustDecompiler.Steps.ManagedPointersRemovalStep.Process(DecompilationContext context, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\ManagedPointersRemovalStep.cs:line 29 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61 + // at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 133 + // + // mailto: JustDecompilePublicFeedback@telerik.com + + } + + public static Dictionary ParseQueryString(this Uri uri) + { + int num = uri.Query.IndexOf('?') + 1; + return ( + from o in uri.Query.Substring(num).Split(new char[] { '&' }) + select o.Split(new char[] { '=' }) into items + where (int)items.Length == 2 + select items).ToDictionary((string[] pair) => pair[0], (string[] pair) => pair[1]); + } + + public static Uri SetQuery(this Uri uri, string name, string value, bool escapeValue = true) + { + UriBuilder uriBuilder = new UriBuilder(uri); + Dictionary strs = uri.ParseQueryString(); + string str = (escapeValue ? Uri.EscapeDataString(value) : value); + if (strs.ContainsKey(name)) + { + strs.Remove(name); + } + strs.Add(name, str); + List list = ( + from x in strs + select string.Concat(x.Key, "=", x.Value)).ToList(); + uriBuilder.Query = string.Join("&", list); + return uriBuilder.Uri; + } + + public static string ToBase64BasicEncode(this string value) + { + return string.Concat("Basic ", Convert.ToBase64String(Encoding.UTF8.GetBytes(value))); + } + + public static StringContent ToHttpContent(this T content, Encoding encoding = null, string mediaType = "application/json") + { + return new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8, mediaType); + } + + public static JObject ToJObject(this string jsonString) + { + JObject jObject; + try + { + jObject = JObject.Parse(jsonString); + } + catch (Exception exception) + { + jObject = null; + } + return jObject; + } + + public static JObject ToJObject(this HttpContent content) + { + return content.ReadAsStringAsync().Result.ToJObject(); + } + + public static Uri ToUri(this string uri) + { + Uri uri1; + Uri.TryCreate(uri, UriKind.Absolute, out uri1); + return uri1; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/Instancia.cs b/Codemerx/Gestor.Application/Helpers/Instancia.cs new file mode 100644 index 0000000..5c68db1 --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/Instancia.cs @@ -0,0 +1,75 @@ +using Gestor.Application; +using Gestor.Common.Helpers; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using System; +using System.IO; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Helpers +{ + public class Instancia + { + public static string Conexao; + + public static Gestor.Application.App App + { + get; + set; + } + + public static UnitOfWork Commited + { + get + { + return Instancia.UnitOfWork(true); + } + } + + public static UnitOfWork Read + { + get + { + return Instancia.UnitOfWork(false); + } + } + + public Instancia() + { + } + + public static void DeleteCfg() + { + string str = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data"); + string str1 = string.Concat(Connection.Catalog, ".cfg"); + if (File.Exists(string.Concat(str, str1))) + { + File.Delete(string.Concat(str, str1)); + } + } + + public static void ExcluirCfg() + { + File.Delete(string.Concat("Data_", Connection.Catalog, ".cfg")); + File.Delete(string.Concat("File_", Connection.Catalog, ".cfg")); + File.Delete(string.Concat("Sign_", Connection.Catalog, ".cfg")); + } + + private static UnitOfWork UnitOfWork(bool withTransaction = true) + { + DataBaseParameters.set_NovoGestor(true); + Instancia.Conexao = Instancia.Conexao ?? Connection.GetConnection(true); + if (Instancia.Conexao == null) + { + return Instancia.App.ConnectionRetry().Result; + } + UnitOfWork unitOfWork = new UnitOfWork(Instancia.Conexao, withTransaction); + if (unitOfWork.get_HasSession()) + { + return unitOfWork; + } + return Instancia.App.ConnectionRetry().Result; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/InstanciaAssinador.cs b/Codemerx/Gestor.Application/Helpers/InstanciaAssinador.cs new file mode 100644 index 0000000..6241ae1 --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/InstanciaAssinador.cs @@ -0,0 +1,44 @@ +using Assinador.Infrastructure.UnitOfWork.Logic; +using Gestor.Application; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Application.Helpers +{ + public class InstanciaAssinador + { + public static string EnderecoConexao; + + public static Gestor.Application.App App + { + get; + set; + } + + public static UnitOfWork Commited + { + get + { + return InstanciaAssinador.UnitOfWork(true); + } + } + + public static UnitOfWork Read + { + get + { + return InstanciaAssinador.UnitOfWork(false); + } + } + + public InstanciaAssinador() + { + } + + private static UnitOfWork UnitOfWork(bool withTransaction = true) + { + InstanciaAssinador.EnderecoConexao = InstanciaAssinador.EnderecoConexao ?? Connection.GetConnection(true); + return new UnitOfWork(InstanciaAssinador.EnderecoConexao, withTransaction); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/LicenseHelper.cs b/Codemerx/Gestor.Application/Helpers/LicenseHelper.cs new file mode 100644 index 0000000..e82c145 --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/LicenseHelper.cs @@ -0,0 +1,572 @@ +using Agger.Registro; +using Gestor.Common.Helpers; +using Gestor.Common.Validation; +using Gestor.Model.API; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.License; +using Microsoft.Win32; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.NetworkInformation; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Helpers +{ + public class LicenseHelper + { + private string _guid + { + get; + set; + } + + public static DateTime DataAtual + { + get; + private set; + } + + public static int? DiasRestantes + { + get; + set; + } + + public static Gestor.Model.License.Instalacao Instalacao + { + get; + set; + } + + public static List Produtos + { + get; + set; + } + + public static StatusLicenca Status + { + get; + set; + } + + static LicenseHelper() + { + LicenseHelper.Status = 1; + } + + public LicenseHelper() + { + } + + public async Task FindKey() + { + string str; + string str1 = EncryptionHelper.Decrypt((new RegistryHelper(ApplicationHelper.Subkey)).ForceRead("MACHINEID", false)); + str = (string.IsNullOrEmpty(str1) ? string.Concat(this.GetMacAddress(), this.GetMachineSerial()) : str1); + string str2 = str; + string str3 = await Gestor.Application.Helpers.Connection.Get(string.Concat("Installation/Serial/", str2), false, false); + return str3; + } + + public NetworkInterface FindMacAddress(string macToSearch) + { + string[] strArrays = macToSearch.Split(new char[] { '|' }); + return NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault((NetworkInterface ni) => strArrays.Contains(ni.GetPhysicalAddress().ToString())); + } + + private string GetFrameworkVersion() + { + try + { + using (RegistryKey registryKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey("SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\\")) + { + if (registryKey != null && registryKey.GetValue("Version") != null) + { + return registryKey.GetValue("Version").ToString(); + } + } + } + catch + { + } + return "<4.5"; + } + + public async Task> GetInstalacoes() + { + List instalacaos = await Gestor.Application.Helpers.Connection.Get>(string.Format("Installation/Machine/{0}", ApplicationHelper.IdFornecedor), true, false); + return instalacaos; + } + + public string GetMacAddress() + { + IEnumerable strs = ((IEnumerable)NetworkInterface.GetAllNetworkInterfaces()).Where((NetworkInterface ni) => { + if (ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet) + { + return true; + } + return ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211; + }).OrderByDescending((NetworkInterface ni) => ni.Id).Select((NetworkInterface x) => x.GetPhysicalAddress().ToString()); + return string.Join("", strs); + } + + private string GetMachineSerial() + { + if (string.IsNullOrEmpty(this._guid)) + { + this._guid = Guid.NewGuid().ToString(); + } + return this._guid; + } + + public async Task Registrar(string chave) + { + string str3 = await Task.Run(() => { + IEnumerable strs; + if (string.IsNullOrEmpty(chave)) + { + return "false"; + } + RegistryHelper registryHelper = new RegistryHelper(""); + string[] strArrays = EncryptionHelper.Decrypt(chave).Split(new char[] { ' ' }); + if ((int)strArrays.Length < 2) + { + return "false"; + } + string str = registryHelper.Verificar(strArrays[0], EncryptionHelper.Encrypt(strArrays[0])); + if (str != "false") + { + if (str == "root") + { + return "root"; + } + ApplicationHelper.NumeroSerial = strArrays[0]; + ApplicationHelper.IdFornecedor = long.Parse(Gestor.Application.Helpers.Connection.Get("Maintenance/Customer", true, false).Result); + Instancia.Conexao = null; + ApplicationHelper.Subkey = strArrays[0]; + return "true"; + } + DateTime networkTime = Funcoes.GetNetworkTime(); + string result = Gestor.Application.Helpers.Connection.Get("Installation/Time", false, true).Result ?? networkTime.ToString("d"); + if (!ApplicationHelper.Conectado) + { + return "false"; + } + LicenseHelper.DataAtual = DateTime.Parse(string.Format("{0} {1}:{2}:{3}", new object[] { result, networkTime.Hour, networkTime.Minute, networkTime.Second })); + DateTime dateTime = DateTime.Parse(strArrays[1]); + if (Math.Abs((LicenseHelper.DataAtual - dateTime).TotalDays) > 1) + { + return "false"; + } + string str1 = EncryptionHelper.Decrypt(registryHelper.Read("NS", true)); + string str2 = registryHelper.Read("SERIALS", false); + if (string.IsNullOrWhiteSpace(str2) && !string.IsNullOrWhiteSpace(str1)) + { + registryHelper.Write("SERIALS", EncryptionHelper.Encrypt(str1), false); + str2 = registryHelper.Read("SERIALS", false); + } + strs = (str2 != null ? EncryptionHelper.Decrypt(str2).Split(new char[] { ':' }).ToList() : new List()); + List strs1 = new List(); + strs.Distinct().ToList().ForEach((string x) => { + if (registryHelper.Verificar(x, EncryptionHelper.Encrypt(x)) == "false") + { + return; + } + strs1.Add(x); + }); + strs1.Add(strArrays[0]); + registryHelper.Write("SERIALS", EncryptionHelper.Encrypt(string.Join(":", strs1.Distinct())), false); + registryHelper.set_Serial((strs1.Count > 1 ? string.Concat("\\", strArrays[0]) : "")); + ApplicationHelper.Subkey = (strs1.Count > 1 ? strArrays[0] : ""); + ApplicationHelper.NumeroSerial = strArrays[0]; + registryHelper.Write("PERFIL", Gestor.Application.Helpers.Connection.Get(string.Concat("Customer/Name/", strArrays[0]), true, false).Result, true); + registryHelper.Write("CURRENTDATE", EncryptionHelper.Encrypt(result), true); + registryHelper.Write("DATE", result, true); + registryHelper.Write("NS", EncryptionHelper.Encrypt(strArrays[0]), true); + registryHelper.Write("INSTALL", EncryptionHelper.Encrypt(strArrays[0]), true); + ApplicationHelper.IdFornecedor = long.Parse(Gestor.Application.Helpers.Connection.Get("Maintenance/Customer", true, false).Result); + registryHelper.Write("CUSTOMER", EncryptionHelper.Encrypt(ApplicationHelper.IdFornecedor.ToString()), true); + Instancia.Conexao = null; + return "true"; + }); + return str3; + } + + public async Task RegistrarMaquina() + { + bool flag = await Task.Run(() => { + int quantidade; + string str; + if (!ApplicationHelper.Conectado) + { + return false; + } + List result = this.GetInstalacoes().Result; + Licenca licenca = LicenseHelper.Produtos.FirstOrDefault((Licenca x) => x.get_Produto() == 1); + quantidade = (licenca != null ? licenca.get_Quantidade() : 0); + if (quantidade <= result.Count((Gestor.Model.License.Instalacao x) => x.get_Gerenciador() != null)) + { + return false; + } + string str1 = ""; + RegistryHelper registryHelper = new RegistryHelper(""); + if (LicenseHelper.Instalacao == null) + { + string machineSerial = this.GetMachineSerial(); + str1 = EncryptionHelper.Encrypt(string.Concat(this.GetMacAddress(), " ", machineSerial)); + Gestor.Model.License.Instalacao instalacao = new Gestor.Model.License.Instalacao(); + instalacao.set_IdFornecedor(ApplicationHelper.IdFornecedor); + instalacao.set_Data(LicenseHelper.DataAtual); + instalacao.set_Gerenciador(machineSerial); + instalacao.set_NomeMaquina(Environment.MachineName); + instalacao.set_UsuarioMaquina(Environment.UserName); + instalacao.set_UsuarioId(Recursos.Usuario.get_Id()); + instalacao.set_UsuarioSistema(Recursos.Usuario.get_Nome()); + instalacao.set_UltimoAcesso(DateTime.Now); + Gestor.Model.License.Instalacao instalacao1 = instalacao; + IPAddress pAddress = ((IEnumerable)Recursos.Host.AddressList).FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + instalacao1.set_Ip(str); + instalacao.set_OSInfo(string.Format("P={0};V={1};x64={2};N={3}", new object[] { (Environment.OSVersion.Platform == PlatformID.Win32NT ? "W" : "O"), Environment.OSVersion.Version, (Environment.Is64BitOperatingSystem ? "1" : "0"), this.GetFrameworkVersion() })); + LicenseHelper.Instalacao = instalacao; + } + registryHelper.Write("MACHINEID", str1, false); + LicenseHelper.Instalacao = Gestor.Application.Helpers.Connection.Put("Installation/Machine", LicenseHelper.Instalacao).Result; + return true; + }); + return flag; + } + + public async Task> VerificarAcesso() + { + Tuple tuple = await Task.Run>(() => { + DateTime dateTime; + TimeSpan timeSpan; + DateTime liberacao; + RegistryHelper registryHelper = new RegistryHelper(ApplicationHelper.Subkey); + DateTime networkTime = Funcoes.GetNetworkTime(); + DateTime date = networkTime.Date; + if (!ApplicationHelper.Conectado) + { + if ((date - LicenseHelper.DataAtual).TotalDays > 2) + { + return new Tuple(true, "DATA INVÁLIDA"); + } + dateTime = DateTime.Parse(EncryptionHelper.Decrypt(registryHelper.Read("EXPIRATION", true))); + timeSpan = dateTime.AddDays(5) - LicenseHelper.DataAtual; + LicenseHelper.DiasRestantes = new int?((int)timeSpan.TotalDays); + int? diasRestantes = LicenseHelper.DiasRestantes; + if (diasRestantes.GetValueOrDefault() < 1 & diasRestantes.HasValue) + { + return new Tuple(true, "SISTEMA BLOQUEADO"); + } + if (EncryptionHelper.Decrypt(registryHelper.Read("BLOCK", true)) == "TRUE") + { + return new Tuple(true, "SISTEMA BLOQUEADO"); + } + if (EncryptionHelper.Decrypt(registryHelper.Read("CONSULTA", true)) == "TRUE") + { + LicenseHelper.Status = 2; + } + string str = EncryptionHelper.Decrypt(registryHelper.Read("PRODUTOS", true)); + if (string.IsNullOrEmpty(str)) + { + LicenseHelper.Status = 3; + return new Tuple(false, "SISTEMA CANCELADO"); + } + LicenseHelper.Produtos = JsonConvert.DeserializeObject>(str); + LicenseHelper.Status = (LicenseHelper.Status != 2 ? 0 : LicenseHelper.Status); + return new Tuple(true, EnumHelper.GetDescription(LicenseHelper.Status)); + } + List result = Gestor.Application.Helpers.Connection.Get>(string.Format("Access/Customer/{0}", ApplicationHelper.IdFornecedor), true, false).Result; + List nums = new List() + { + (long)2, + (long)3, + (long)4, + (long)5, + (long)24, + (long)10024 + }; + LicenseHelper.Produtos = ( + from x in result + group x by new { ProductId = x.get_ProductId(), Status = x.get_Status() }).Select((x) => { + DateTime expiration; + Licenca licenca = new Licenca(); + licenca.set_Produto((int)x.Key.ProductId.GetValueOrDefault()); + var collection1 = x; + Func> u003cu003e9_2110 = LicenseHelper.u003cu003ec.u003cu003e9__21_10; + if (u003cu003e9_2110 == null) + { + u003cu003e9_2110 = (Access c) => c.get_Control(); + LicenseHelper.u003cu003ec.u003cu003e9__21_10 = u003cu003e9_2110; + } + IEnumerable accessControls1 = collection1.SelectMany(u003cu003e9_2110); + Func u003cu003e9_2111 = LicenseHelper.u003cu003ec.u003cu003e9__21_11; + if (u003cu003e9_2111 == null) + { + u003cu003e9_2111 = (AccessControl l) => l.get_Expiration(); + LicenseHelper.u003cu003ec.u003cu003e9__21_11 = u003cu003e9_2111; + } + AccessControl accessControl1 = accessControls1.OrderByDescending(u003cu003e9_2111).FirstOrDefault(); + expiration = (accessControl1 != null ? accessControl1.get_Expiration() : networkTime.AddDays(-1)); + licenca.set_Liberacao(expiration); + licenca.set_AcessoLiberado(x.All((Access l) => { + if (l.get_AgreementId().HasValue && nums.Contains(l.get_AgreementId().Value)) + { + return true; + } + var collection = x; + Func> u003cu003e9_2114 = LicenseHelper.u003cu003ec.u003cu003e9__21_14; + if (u003cu003e9_2114 == null) + { + u003cu003e9_2114 = (Access c) => c.get_Control(); + LicenseHelper.u003cu003ec.u003cu003e9__21_14 = u003cu003e9_2114; + } + IEnumerable accessControls = collection.SelectMany(u003cu003e9_2114); + Func u003cu003e9_2115 = LicenseHelper.u003cu003ec.u003cu003e9__21_15; + if (u003cu003e9_2115 == null) + { + u003cu003e9_2115 = (AccessControl d) => d.get_Expiration(); + LicenseHelper.u003cu003ec.u003cu003e9__21_15 = u003cu003e9_2115; + } + AccessControl accessControl = accessControls.OrderByDescending(u003cu003e9_2115).FirstOrDefault(); + if (accessControl == null) + { + return false; + } + return accessControl.get_Expiration() >= date; + })); + var collection2 = x; + Func u003cu003e9_2113 = LicenseHelper.u003cu003ec.u003cu003e9__21_13; + if (u003cu003e9_2113 == null) + { + u003cu003e9_2113 = (Access l) => l.get_Ammount().GetValueOrDefault(); + LicenseHelper.u003cu003ec.u003cu003e9__21_13 = u003cu003e9_2113; + } + licenca.set_Quantidade((int)collection2.Sum(u003cu003e9_2113)); + licenca.set_Status(int.Parse(x.Key.Status ?? "1")); + return licenca; + }).ToList(); + if (LicenseHelper.Produtos != null && LicenseHelper.Produtos.Count != 0) + { + if (!LicenseHelper.Produtos.All((Licenca x) => x.get_Status() == 3)) + { + Licenca licenca1 = ( + from x in LicenseHelper.Produtos + orderby x.get_Liberacao() + select x).FirstOrDefault((Licenca x) => { + if (x.get_AcessoLiberado()) + { + return false; + } + return x.get_Status() == 1; + }); + liberacao = (licenca1 != null ? licenca1.get_Liberacao() : networkTime); + DateTime dateTime1 = liberacao; + timeSpan = dateTime1 - date; + LicenseHelper.DiasRestantes = new int?((int)timeSpan.TotalDays); + registryHelper.Write("EXPIRATION", EncryptionHelper.Encrypt(dateTime1.ToString("d")), true); + registryHelper.Write("BLOCK", (dateTime1 >= date ? EncryptionHelper.Encrypt("FALSE") : EncryptionHelper.Encrypt("TRUE")), true); + bool flag = LicenseHelper.Produtos.Any((Licenca x) => { + if (x.get_Produto() != 1) + { + return false; + } + return x.get_Status() == 4; + }); + registryHelper.Write("CONSULTA", EncryptionHelper.Encrypt(flag.ToString().ToUpper()), true); + if (flag) + { + LicenseHelper.Status = 2; + } + LicenseHelper.Status = (dateTime1 < date ? 1 : 0); + if (LicenseHelper.Produtos.Any((Licenca x) => x.get_Produto() == 1) && LicenseHelper.Status == null) + { + registryHelper.Write("P1", EncryptionHelper.Encrypt(string.Concat("1$P1#", ApplicationHelper.NumeroSerial)), true); + registryHelper.Write("P5", EncryptionHelper.Encrypt(string.Concat("1$P1#", ApplicationHelper.NumeroSerial)), true); + registryHelper.Write("M1", EncryptionHelper.Encrypt("TRUE"), true); + } + IEnumerable produtos = + from x in LicenseHelper.Produtos + where x.get_Status() == 1 + select x; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registryHelper.Write("PRODUTOS", EncryptionHelper.Encrypt(JsonConvert.SerializeObject(produtos, 1, jsonSerializerSetting)), true); + if (LicenseHelper.Produtos.Find((Licenca p) => p.get_Produto() == 86) != null) + { + return new Tuple(true, EnumHelper.GetDescription(LicenseHelper.Status)); + } + if (Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(AssinadorHelper.Key().Result)) + { + List licencas = LicenseHelper.Produtos; + Licenca licenca2 = new Licenca(); + licenca2.set_AcessoLiberado(true); + licenca2.set_Liberacao(date); + licenca2.set_Produto(86); + licenca2.set_Quantidade(0); + licenca2.set_Status(1); + licencas.Add(licenca2); + } + return new Tuple(true, EnumHelper.GetDescription(LicenseHelper.Status)); + } + } + dateTime = networkTime.AddDays(-1); + registryHelper.Write("EXPIRATION", EncryptionHelper.Encrypt(dateTime.ToString("d")), true); + registryHelper.Write("BLOCK", EncryptionHelper.Encrypt("TRUE"), true); + LicenseHelper.Status = 3; + return new Tuple(false, ""); + }); + return tuple; + } + + public async Task VerificarMaquina() + { + bool flag = await Task.Run(() => { + Guid guid; + string str; + Gestor.Model.License.Instalacao instalacao; + string str1; + RegistryHelper registryHelper = new RegistryHelper(ApplicationHelper.Subkey); + string macAddress = this.GetMacAddress(); + if (string.IsNullOrEmpty(registryHelper.Read("MACHINEID", false))) + { + registryHelper.Write("MACHINEID", EncryptionHelper.Encrypt(string.Concat(macAddress, " ", this.GetMachineSerial())), false); + } + string[] strArrays = EncryptionHelper.Decrypt(registryHelper.Read("MACHINEID", false)).Split(new char[] { ' ' }); + string machineSerial = ((int)strArrays.Length > 1 ? strArrays[1] : strArrays[0]); + if (ApplicationHelper.Conectado) + { + List result = Gestor.Application.Helpers.Connection.Get>(string.Concat("Installation/Machine/", machineSerial, "/GerenciadorList"), true, false).Result; + if (!Guid.TryParse(machineSerial, out guid)) + { + machineSerial = this.GetMachineSerial(); + } + this._guid = machineSerial; + if (result != null) + { + instalacao = result.FirstOrDefault((Gestor.Model.License.Instalacao x) => x.get_IdFornecedor() == ApplicationHelper.IdFornecedor); + } + else + { + instalacao = null; + } + LicenseHelper.Instalacao = instalacao; + if (LicenseHelper.Instalacao != null && LicenseHelper.Instalacao.get_IdFornecedor() != ApplicationHelper.IdFornecedor) + { + LicenseHelper.Instalacao = null; + } + if (LicenseHelper.Instalacao != null) + { + LicenseHelper.Instalacao.set_Gerenciador(machineSerial); + LicenseHelper.Instalacao.set_UsuarioId(Recursos.Usuario.get_Id()); + LicenseHelper.Instalacao.set_UsuarioSistema(Recursos.Usuario.get_Nome()); + Gestor.Model.License.Instalacao instalacao1 = LicenseHelper.Instalacao; + IPAddress pAddress = ((IEnumerable)Recursos.Host.AddressList).FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork); + if (pAddress != null) + { + str1 = pAddress.ToString(); + } + else + { + str1 = null; + } + instalacao1.set_Ip(str1); + LicenseHelper.Instalacao.set_UltimoAcesso(DateTime.Now); + LicenseHelper.Instalacao.set_OSInfo(string.Format("P={0};V={1};x64={2};N={3}", new object[] { (Environment.OSVersion.Platform == PlatformID.Win32NT ? "W" : "O"), Environment.OSVersion.Version, (Environment.Is64BitOperatingSystem ? "1" : "0"), this.GetFrameworkVersion() })); + LicenseHelper.Instalacao = Gestor.Application.Helpers.Connection.Put("Installation/Machine", LicenseHelper.Instalacao).Result; + registryHelper.Write("MACHINEID", EncryptionHelper.Encrypt(string.Concat(macAddress, " ", LicenseHelper.Instalacao.get_Gerenciador())), false); + } + registryHelper.Write("ACCESS", (LicenseHelper.Instalacao != null || this.RegistrarMaquina().Result ? EncryptionHelper.Encrypt("TRUE") : EncryptionHelper.Encrypt("FALSE")), false); + } + else if (EncryptionHelper.Decrypt(registryHelper.Read("ACCESS", false)) == "TRUE") + { + Gestor.Model.License.Instalacao instalacao2 = new Gestor.Model.License.Instalacao(); + instalacao2.set_IdFornecedor(ApplicationHelper.IdFornecedor); + instalacao2.set_Data(LicenseHelper.DataAtual); + instalacao2.set_Gerenciador(machineSerial); + instalacao2.set_NomeMaquina(Environment.MachineName); + instalacao2.set_UsuarioMaquina(Environment.UserName); + instalacao2.set_UsuarioId(Recursos.Usuario.get_Id()); + instalacao2.set_UsuarioSistema(Recursos.Usuario.get_Nome()); + instalacao2.set_UltimoAcesso(DateTime.Now); + IPAddress pAddress1 = ((IEnumerable)Recursos.Host.AddressList).FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork); + if (pAddress1 != null) + { + str = pAddress1.ToString(); + } + else + { + str = null; + } + instalacao2.set_Ip(str); + LicenseHelper.Instalacao = instalacao2; + } + if (!LicenseHelper.Produtos.Any((Licenca x) => x.get_Produto() == 1)) + { + return false; + } + if (LicenseHelper.Instalacao != null) + { + return true; + } + return this.RegistrarMaquina().Result; + }); + return flag; + } + + public async Task VerificarRegistro() + { + bool flag = await Task.Run(() => { + long idFornecedor; + RegistryHelper registryHelper = new RegistryHelper(ApplicationHelper.Subkey); + if (string.IsNullOrEmpty(registryHelper.Read("NS", true))) + { + return false; + } + string str = EncryptionHelper.Decrypt(registryHelper.Read("CUSTOMER", true)); + if (long.TryParse(str, out idFornecedor)) + { + ApplicationHelper.IdFornecedor = long.Parse(str); + } + else + { + ApplicationHelper.IdFornecedor = long.Parse(Gestor.Application.Helpers.Connection.Get("Configuration/Customer", true, false).Result); + idFornecedor = ApplicationHelper.IdFornecedor; + registryHelper.Write("CUSTOMER", EncryptionHelper.Encrypt(idFornecedor.ToString()), true); + } + string result = Gestor.Application.Helpers.Connection.Get("Installation/Time", false, false).Result ?? Funcoes.GetNetworkTime().ToString("d"); + LicenseHelper.DataAtual = DateTime.Parse(result); + registryHelper.Write("CURRENTDATE", EncryptionHelper.Encrypt(result), true); + registryHelper.Write("DATE", result, true); + List objs = Gestor.Application.Helpers.Connection.Get>(string.Format("Configuration/Customer/{0}", ApplicationHelper.IdFornecedor), true, false).Result; + ApplicationHelper.Beta = (objs == null ? false : objs.Any((object x) => x.ToString().Contains("\"Tipo\": 45"))); + Address.set_Beta(ApplicationHelper.Beta); + return true; + }); + return flag; + } + + public async Task> VerificarVersao() + { + Tuple tuple = new Tuple(bool.Parse(await Gestor.Application.Helpers.Connection.Get(string.Format("Installation/Version/{0}", ApplicationHelper.IdFornecedor), true, false)), "VERSÃO INDISPONÍVEL"); + return tuple; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/MailHelper.cs b/Codemerx/Gestor.Application/Helpers/MailHelper.cs new file mode 100644 index 0000000..e9f2cde --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/MailHelper.cs @@ -0,0 +1,745 @@ +using CsQuery.ExtensionMethods.Internal; +using Gestor.Application.ViewModels; +using Gestor.Common.Helpers; +using Gestor.Common.Validation; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.MalaDireta; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using Google.Apis.Auth.OAuth2; +using Google.Apis.Gmail.v1; +using Google.Apis.Gmail.v1.Data; +using Google.Apis.Requests; +using Google.Apis.Services; +using Microsoft.Identity.Client; +using MimeKit; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Collections.Specialized; +using System.ComponentModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Mail; +using System.Net.Mime; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; + +namespace Gestor.Application.Helpers +{ + public class MailHelper + { + public MailHelper() + { + } + + private static StringContent ConverteMailMessageParaStringContent(MailMessage message) + { + StringContent stringContent; + MimeMessage mimeMessage = (MimeMessage)message; + using (MemoryStream memoryStream = new MemoryStream()) + { + mimeMessage.WriteTo(memoryStream, new CancellationToken()); + memoryStream.Position = (long)0; + using (StreamReader streamReader = new StreamReader(memoryStream)) + { + string end = streamReader.ReadToEnd(); + stringContent = new StringContent(Convert.ToBase64String(Encoding.ASCII.GetBytes(end)), Encoding.UTF8, "text/plain"); + } + } + return stringContent; + } + + public static AlternateView CreateAlternateView(string mailBody) + { + int i; + List linkedResources = new List(); + string[] array = ( + from Match m in Regex.Matches(mailBody, "", RegexOptions.IgnoreCase) + select m.Groups[0].Value).ToArray(); + for (i = 0; i < (int)array.Length; i++) + { + string value = Regex.Match(array[i], "(?<=src=\")(.*?)(?=\")", RegexOptions.IgnoreCase).Value; + string str = Regex.Match(value, "file:(///).*\\.(.*)", RegexOptions.IgnoreCase).Groups[2].Value; + if (str == "jpg") + { + str = "jpeg"; + } + if (Uri.IsWellFormedUriString(value, UriKind.Absolute)) + { + Uri uri = new Uri(value); + if (File.Exists(uri.LocalPath)) + { + mailBody = mailBody.Replace(value, string.Concat("data:image/", str, ";base64,", Convert.ToBase64String(File.ReadAllBytes(uri.LocalPath)))); + } + } + } + array = ( + from Match m in Regex.Matches(mailBody, "", RegexOptions.IgnoreCase) + select m.Groups[0].Value).ToArray(); + for (i = 0; i < (int)array.Length; i++) + { + string str1 = array[i]; + string value1 = Regex.Match(str1, "(?<=src=\").*(?=\")", RegexOptions.IgnoreCase).Value; + string value2 = Regex.Match(value1, "(?<=data:).*(?=;)", RegexOptions.IgnoreCase).Value; + if (Gestor.Common.Validation.ValidationHelper.IsNullOrEmpty(value2) || Gestor.Common.Validation.ValidationHelper.IsNullOrEmpty(value1)) + { + mailBody = mailBody.Replace(str1, string.Empty); + } + else + { + byte[] numArray = Convert.FromBase64String(Regex.Match(value1, "(?<=base64,)[^\"]*", RegexOptions.IgnoreCase).Value); + string str2 = Guid.NewGuid().ToString(); + linkedResources.Add(new LinkedResource(new MemoryStream(numArray), value2) + { + ContentId = str2, + TransferEncoding = TransferEncoding.Base64 + }); + string str3 = string.Concat("cid:", str2); + mailBody = mailBody.Replace(value1, str3); + } + } + AlternateView alternateView = AlternateView.CreateAlternateViewFromString(mailBody, null, "text/html"); + ExtensionMethods.AddRange(alternateView.LinkedResources, linkedResources); + return alternateView; + } + + public static string Encode(string text) + { + return Convert.ToBase64String(Encoding.UTF8.GetBytes(text)).Replace('+', '-').Replace('/', '\u005F').Replace("=", ""); + } + + public List Send(Credencial credencial, List destinatarios, TipoTela tela, long id) + { + List logEnvios1 = new List(); + int num = 100; + destinatarios.ForEach(async (Destinatario i) => { + if (num == 0) + { + num = 100; + await Task.Delay(1000); + } + List logEnvios = logEnvios1; + logEnvios.Add(await this.SendAsync(credencial, i, null, null, 0, false)); + logEnvios = null; + num--; + }); + return logEnvios1; + } + + public async Task SendAsync(Credencial credencial, Destinatario destinatario, FiltroArquivoDigital filtro = null, List maladireta = null, TipoTela tela = 0, bool confirmarLeitura = false) + { + TipoTela tipoTela = new TipoTela(); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + LogEnvio logEnvio2 = await Task.Run(() => { + AuthenticationResult result; + List strs; + string str; + long id; + string str1; + string str2; + string str3; + string str4; + string str5; + string str6; + Action action2 = null; + Action action3 = null; + LogEnvio logEnvio = new LogEnvio(); + logEnvio.set_Credencial(credencial); + logEnvio.set_Destinatario(destinatario); + LogEnvio logEnvio1 = logEnvio; + AlternateView alternateView = MailHelper.CreateAlternateView(destinatario.get_Corpo()); + try + { + MailMessage mailMessage = new MailMessage() + { + From = new MailAddress(credencial.get_Email(), (string.IsNullOrWhiteSpace(credencial.get_Header()) ? Recursos.Empresa.get_Nome() : credencial.get_Header())), + BodyEncoding = Encoding.UTF8, + Subject = destinatario.get_Assunto() + }; + mailMessage.AlternateViews.Add(alternateView); + mailMessage.ReplyToList.Add(new MailAddress((string.IsNullOrWhiteSpace(credencial.get_Replyto()) ? credencial.get_Email() : credencial.get_Replyto()))); + mailMessage.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; + mailMessage.IsBodyHtml = true; + MailMessage mailMessage1 = mailMessage; + if (confirmarLeitura) + { + mailMessage1.Headers.Add("Disposition-Notification-To", credencial.get_Email()); + } + destinatario.get_Email().Split(new char[] { ';' }).ToList().ForEach((string s) => { + if (!Gestor.Model.Helper.ValidationHelper.ValidacaoEmail(s)) + { + return; + } + mailMessage1.To.Add(new MailAddress(s)); + }); + List strs1 = new List(); + List encaminharOculto = destinatario.get_EncaminharOculto(); + if (encaminharOculto != null) + { + encaminharOculto.ForEach((string x) => { + if (string.IsNullOrEmpty(x)) + { + return; + } + if (!x.Contains(";")) + { + if (!Gestor.Model.Helper.ValidationHelper.ValidacaoEmail(x)) + { + return; + } + strs1.Add(x); + return; + } + List list = x.Split(new char[] { ';' }).ToList(); + Action u003cu003e9_6 = action2; + if (u003cu003e9_6 == null) + { + Action action = (string s) => { + if (!Gestor.Model.Helper.ValidationHelper.ValidacaoEmail(s)) + { + return; + } + strs1.Add(s); + }; + Action action1 = action; + action2 = action; + u003cu003e9_6 = action1; + } + list.ForEach(u003cu003e9_6); + }); + } + else + { + } + List encaminhar = destinatario.get_Encaminhar(); + if (encaminhar != null) + { + encaminhar.ForEach((string x) => { + if (string.IsNullOrEmpty(x)) + { + return; + } + if (!x.Contains(";")) + { + if (!Gestor.Model.Helper.ValidationHelper.ValidacaoEmail(x)) + { + return; + } + strs1.Add(x); + return; + } + List list = x.Split(new char[] { ';' }).ToList(); + Action u003cu003e9_7 = action3; + if (u003cu003e9_7 == null) + { + Action action = (string s) => { + if (!Gestor.Model.Helper.ValidationHelper.ValidacaoEmail(s)) + { + return; + } + strs1.Add(s); + }; + Action action1 = action; + action3 = action; + u003cu003e9_7 = action1; + } + list.ForEach(u003cu003e9_7); + }); + } + else + { + } + strs1.ForEach((string x) => mailMessage1.Bcc.Add(new MailAddress(x))); + List anexos = destinatario.get_Anexos(); + if (anexos != null) + { + anexos.ForEach((Gestor.Model.Domain.Common.ArquivoDigital x) => { + Attachment attachment = new Attachment(new MemoryStream(x.get_Arquivo()), string.Concat(x.get_Descricao(), Gestor.Common.Validation.ValidationHelper.GetDefaultExtension(x.get_Extensao()))); + mailMessage1.Attachments.Add(attachment); + }); + } + else + { + } + if (credencial.get_Email().Contains("@gmail.com")) + { + credencial.set_Tipo(1); + } + TipoEmail tipo = credencial.get_Tipo(); + if (tipo == 1) + { + ClientSecrets clientSecret = new ClientSecrets(); + clientSecret.set_ClientId("378618252089-fm92uqgnk2jivf25mk2tv9s735n4nf6u.apps.googleusercontent.com"); + clientSecret.set_ClientSecret("kUiTfSuwZLLfteqwX7x6glsu"); + UserCredential userCredential = GoogleWebAuthorizationBroker.AuthorizeAsync(clientSecret, new string[] { GmailService.Scope.GmailSend }, credencial.get_Email(), CancellationToken.None, null, null).Result; + Google.Apis.Gmail.v1.Data.Message message = new Google.Apis.Gmail.v1.Data.Message(); + message.set_Raw(MailHelper.Encode(MimeMessage.CreateFromMailMessage(mailMessage1).ToString())); + Google.Apis.Gmail.v1.Data.Message message1 = message; + BaseClientService.Initializer initializer = new BaseClientService.Initializer(); + initializer.set_HttpClientInitializer(userCredential); + initializer.set_ApplicationName("AGGER GESTOR"); + UsersResource.MessagesResource.SendRequest sendRequest = (new GmailService(initializer)).get_Users().get_Messages().Send(message1, credencial.get_Email()); + logEnvio1.set_Enviado(false); + if (sendRequest.Execute().get_LabelIds().Contains("SENT")) + { + logEnvio1.set_Enviado(true); + } + } + else if (tipo == 2) + { + StringContent stringContent = new StringContent(""); + PublicClientApplicationBuilder publicClientApplicationBuilder = PublicClientApplicationBuilder.Create("8d1c32fe-4c17-4d5b-a21b-55b5529c3e12").WithDefaultRedirectUri(); + CacheOptions cacheOption = new CacheOptions(); + cacheOption.set_UseSharedCache(true); + IPublicClientApplication publicClientApplication = publicClientApplicationBuilder.WithCacheOptions(cacheOption).Build(); + string[] strArrays = new string[] { "user.read", "https://graph.microsoft.com/Mail.Send" }; + try + { + stringContent = MailHelper.ConverteMailMessageParaStringContent(mailMessage1); + IEnumerable accounts = publicClientApplication.GetAccountsAsync().Result; + result = (accounts == null || accounts.Count() == 0 ? publicClientApplication.AcquireTokenInteractive(strArrays).ExecuteAsync().Result : publicClientApplication.AcquireTokenSilent(strArrays, (accounts != null ? accounts.FirstOrDefault() : null)).ExecuteAsync().Result); + } + catch + { + result = publicClientApplication.AcquireTokenInteractive(strArrays).ExecuteAsync().Result; + } + using (HttpClient httpClient = new HttpClient()) + { + httpClient.get_DefaultRequestHeaders().Clear(); + httpClient.get_DefaultRequestHeaders().Add("Authorization", string.Concat("Bearer ", (result != null ? result.get_AccessToken() : null))); + logEnvio1.set_Enviado(httpClient.PostAsync("https://graph.microsoft.com/v1.0/me/sendMail", stringContent).Result.get_IsSuccessStatusCode()); + } + } + else + { + NetworkCredential networkCredential = new NetworkCredential() + { + Password = EncryptionHelper.Decrypt(credencial.get_Senha()), + UserName = credencial.get_Usuario() ?? credencial.get_Email() + }; + SmtpClient smtpClient = new SmtpClient() + { + EnableSsl = credencial.get_Seguro(), + Host = credencial.get_Dominio(), + Port = credencial.get_Porta().GetValueOrDefault(587), + UseDefaultCredentials = false, + Credentials = networkCredential + }; + smtpClient.SendCompleted += new SendCompletedEventHandler((object sender, AsyncCompletedEventArgs args) => { + logEnvio1.set_Enviado((!args.Cancelled ? true : args.Error != null)); + if (args.Error != null) + { + logEnvio1.set_Erro(args.Error.ToString()); + } + }); + smtpClient.Send(mailMessage1); + logEnvio1.set_Enviado(true); + } + } + catch (Exception exception1) + { + Exception exception = exception1; + logEnvio1.set_Enviado(false); + logEnvio1.set_Erro((exception.InnerException == null ? exception.Message : string.Concat(exception.Message, " | ", exception.InnerException.Message))); + } + if (tela == 40) + { + return logEnvio1; + } + using (UnitOfWork commited = Instancia.Commited) + { + List strs2 = new List() + { + destinatario.get_Email() + }; + if (destinatario.get_Encaminhar() != null) + { + strs2.AddRange(destinatario.get_Encaminhar()); + } + List strs3 = new List(); + if (destinatario.get_EncaminharOculto() != null) + { + strs3.AddRange(destinatario.get_EncaminharOculto()); + } + List arquivoDigitals = destinatario.get_Anexos(); + if (arquivoDigitals != null) + { + Func u003cu003e9_09 = MailHelper.u003cu003ec.u003cu003e9__0_9; + if (u003cu003e9_09 == null) + { + u003cu003e9_09 = (Gestor.Model.Domain.Common.ArquivoDigital x) => string.Concat(x.get_Descricao(), Gestor.Common.Validation.ValidationHelper.GetDefaultExtension(x.get_Extensao())); + MailHelper.u003cu003ec.u003cu003e9__0_9 = u003cu003e9_09; + } + strs = arquivoDigitals.Select(u003cu003e9_09).ToList(); + } + else + { + strs = null; + } + List strs4 = strs; + DateTime networkTime = Funcoes.GetNetworkTime(); + if (filtro != null) + { + switch (filtro.get_Tipo()) + { + case 1: + { + tipoTela = 1; + break; + } + case 2: + { + tipoTela = 2; + break; + } + case 3: + { + tipoTela = 5; + break; + } + case 4: + { + tipoTela = 3; + break; + } + case 5: + { + tipoTela = 7; + break; + } + case 6: + { + tipoTela = 15; + break; + } + case 7: + { + tipoTela = 23; + break; + } + case 8: + { + tipoTela = 13; + break; + } + case 9: + { + tipoTela = 25; + break; + } + case 10: + { + tipoTela = 24; + break; + } + case 11: + { + tipoTela = 33; + break; + } + case 12: + { + tipoTela = 16; + break; + } + case 13: + { + tipoTela = 18; + break; + } + default: + { + tipoTela = 0; + break; + } + } + if (strs4 != null && logEnvio1.get_Enviado()) + { + LogEmail logEmail = new LogEmail(); + logEmail.set_Credencial(credencial); + logEmail.set_EntityId(filtro.get_Id()); + logEmail.set_Usuario(Recursos.Usuario); + logEmail.set_Data(networkTime); + logEmail.set_Tela(tipoTela); + logEmail.set_Destinatarios(string.Join(";", strs2)); + logEmail.set_Cco(string.Join(";", strs3)); + logEmail.set_Assunto(destinatario.get_Assunto()); + logEmail.set_Corpo(destinatario.get_Corpo()); + logEmail.set_Anexos(string.Join(";", strs4)); + logEmail.set_Versao(LoginViewModel.VersaoAtual); + logEmail.set_NomeMaquina(Environment.MachineName); + logEmail.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_010 = MailHelper.u003cu003ec.u003cu003e9__0_10; + if (u003cu003e9_010 == null) + { + u003cu003e9_010 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + MailHelper.u003cu003ec.u003cu003e9__0_10 = u003cu003e9_010; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_010); + if (pAddress != null) + { + str6 = pAddress.ToString(); + } + else + { + str6 = null; + } + logEmail.set_Ip(str6); + commited.get_RegistroLogRepository().SaveOrUpdate(logEmail); + } + commited.Commit(); + } + else if (maladireta == null) + { + if (strs4 != null) + { + LogEmail logEmail1 = new LogEmail(); + logEmail1.set_Credencial(credencial); + logEmail1.set_Usuario(Recursos.Usuario); + logEmail1.set_Data(networkTime); + logEmail1.set_Tela(tela); + logEmail1.set_Destinatarios(string.Join(";", strs2)); + logEmail1.set_Cco(string.Join(";", strs3)); + logEmail1.set_Assunto(destinatario.get_Assunto()); + logEmail1.set_Corpo(destinatario.get_Corpo()); + logEmail1.set_Anexos(string.Join(";", strs4)); + logEmail1.set_Versao(LoginViewModel.VersaoAtual); + logEmail1.set_NomeMaquina(Environment.MachineName); + logEmail1.set_UsuarioMaquina(Environment.UserName); + IPAddress[] pAddressArray = hostEntry.AddressList; + Func u003cu003e9_016 = MailHelper.u003cu003ec.u003cu003e9__0_16; + if (u003cu003e9_016 == null) + { + u003cu003e9_016 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + MailHelper.u003cu003ec.u003cu003e9__0_16 = u003cu003e9_016; + } + IPAddress pAddress1 = ((IEnumerable)pAddressArray).FirstOrDefault(u003cu003e9_016); + if (pAddress1 != null) + { + str = pAddress1.ToString(); + } + else + { + str = null; + } + logEmail1.set_Ip(str); + commited.get_RegistroLogRepository().SaveOrUpdate(logEmail1); + } + commited.Commit(); + } + else + { + foreach (MalaDireta maladiretum in maladireta) + { + if (maladiretum.get_Tela() == 1) + { + LogEmail logEmail2 = new LogEmail(); + logEmail2.set_Credencial(credencial); + logEmail2.set_Usuario(Recursos.Usuario); + logEmail2.set_EntityId(maladiretum.get_Cliente().get_Id()); + logEmail2.set_Data(networkTime); + logEmail2.set_Tela(maladiretum.get_Tela()); + logEmail2.set_Destinatarios(string.Join(";", strs2)); + logEmail2.set_Cco(string.Join(";", strs3)); + logEmail2.set_Assunto(destinatario.get_Assunto()); + logEmail2.set_Corpo(destinatario.get_Corpo()); + logEmail2.set_Anexos(string.Join(";", strs4)); + logEmail2.set_Versao(LoginViewModel.VersaoAtual); + logEmail2.set_NomeMaquina(Environment.MachineName); + logEmail2.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList1 = hostEntry.AddressList; + Func u003cu003e9_011 = MailHelper.u003cu003ec.u003cu003e9__0_11; + if (u003cu003e9_011 == null) + { + u003cu003e9_011 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + MailHelper.u003cu003ec.u003cu003e9__0_11 = u003cu003e9_011; + } + IPAddress pAddress2 = ((IEnumerable)addressList1).FirstOrDefault(u003cu003e9_011); + if (pAddress2 != null) + { + str5 = pAddress2.ToString(); + } + else + { + str5 = null; + } + logEmail2.set_Ip(str5); + logEmail2.set_Relatorio(maladiretum.get_Relatorio()); + commited.get_RegistroLogRepository().SaveOrUpdate(logEmail2); + } + else if (maladiretum.get_Tela() == 2) + { + LogEmail logEmail3 = new LogEmail(); + logEmail3.set_Credencial(credencial); + logEmail3.set_Usuario(Recursos.Usuario); + logEmail3.set_EntityId(maladiretum.get_Apolice().get_Id()); + logEmail3.set_Data(networkTime); + logEmail3.set_Tela(maladiretum.get_Tela()); + logEmail3.set_Destinatarios(string.Join(";", strs2)); + logEmail3.set_Cco(string.Join(";", strs3)); + logEmail3.set_Assunto(destinatario.get_Assunto()); + logEmail3.set_Corpo(destinatario.get_Corpo()); + logEmail3.set_Anexos(string.Join(";", strs4)); + logEmail3.set_Versao(LoginViewModel.VersaoAtual); + logEmail3.set_NomeMaquina(Environment.MachineName); + logEmail3.set_UsuarioMaquina(Environment.UserName); + IPAddress[] pAddressArray1 = hostEntry.AddressList; + Func u003cu003e9_012 = MailHelper.u003cu003ec.u003cu003e9__0_12; + if (u003cu003e9_012 == null) + { + u003cu003e9_012 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + MailHelper.u003cu003ec.u003cu003e9__0_12 = u003cu003e9_012; + } + IPAddress pAddress3 = ((IEnumerable)pAddressArray1).FirstOrDefault(u003cu003e9_012); + if (pAddress3 != null) + { + str4 = pAddress3.ToString(); + } + else + { + str4 = null; + } + logEmail3.set_Ip(str4); + logEmail3.set_Relatorio(maladiretum.get_Relatorio()); + commited.get_RegistroLogRepository().SaveOrUpdate(logEmail3); + } + else if (maladiretum.get_Tela() == 5) + { + LogEmail logEmail4 = new LogEmail(); + logEmail4.set_Credencial(credencial); + logEmail4.set_Usuario(Recursos.Usuario); + logEmail4.set_EntityId(maladiretum.get_Parcela().get_Id()); + logEmail4.set_Data(networkTime); + logEmail4.set_Tela(maladiretum.get_Tela()); + logEmail4.set_Destinatarios(string.Join(";", strs2)); + logEmail4.set_Cco(string.Join(";", strs3)); + logEmail4.set_Assunto(destinatario.get_Assunto()); + logEmail4.set_Corpo(destinatario.get_Corpo()); + logEmail4.set_Anexos(string.Join(";", strs4)); + logEmail4.set_Versao(LoginViewModel.VersaoAtual); + logEmail4.set_NomeMaquina(Environment.MachineName); + logEmail4.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList2 = hostEntry.AddressList; + Func u003cu003e9_013 = MailHelper.u003cu003ec.u003cu003e9__0_13; + if (u003cu003e9_013 == null) + { + u003cu003e9_013 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + MailHelper.u003cu003ec.u003cu003e9__0_13 = u003cu003e9_013; + } + IPAddress pAddress4 = ((IEnumerable)addressList2).FirstOrDefault(u003cu003e9_013); + if (pAddress4 != null) + { + str3 = pAddress4.ToString(); + } + else + { + str3 = null; + } + logEmail4.set_Ip(str3); + logEmail4.set_Relatorio(maladiretum.get_Relatorio()); + commited.get_RegistroLogRepository().SaveOrUpdate(logEmail4); + } + else if (maladiretum.get_Tela() != 7) + { + if (maladiretum.get_Tela() != null) + { + continue; + } + LogEmail logEmail5 = new LogEmail(); + logEmail5.set_Credencial(credencial); + logEmail5.set_Usuario(Recursos.Usuario); + Documento apolice = maladiretum.get_Apolice(); + id = (apolice != null ? apolice.get_Id() : (long)0); + logEmail5.set_EntityId(id); + logEmail5.set_Data(networkTime); + logEmail5.set_Tela(2); + logEmail5.set_Destinatarios(string.Join(";", strs2)); + logEmail5.set_Cco(string.Join(";", strs3)); + logEmail5.set_Assunto(destinatario.get_Assunto()); + logEmail5.set_Corpo(destinatario.get_Corpo()); + logEmail5.set_Anexos(string.Join(";", strs4)); + logEmail5.set_Versao(LoginViewModel.VersaoAtual); + logEmail5.set_NomeMaquina(Environment.MachineName); + logEmail5.set_UsuarioMaquina(Environment.UserName); + IPAddress[] pAddressArray2 = hostEntry.AddressList; + Func u003cu003e9_015 = MailHelper.u003cu003ec.u003cu003e9__0_15; + if (u003cu003e9_015 == null) + { + u003cu003e9_015 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + MailHelper.u003cu003ec.u003cu003e9__0_15 = u003cu003e9_015; + } + IPAddress pAddress5 = ((IEnumerable)pAddressArray2).FirstOrDefault(u003cu003e9_015); + if (pAddress5 != null) + { + str1 = pAddress5.ToString(); + } + else + { + str1 = null; + } + logEmail5.set_Ip(str1); + logEmail5.set_Relatorio(maladiretum.get_Relatorio()); + commited.get_RegistroLogRepository().SaveOrUpdate(logEmail5); + } + else + { + LogEmail logEmail6 = new LogEmail(); + logEmail6.set_Credencial(credencial); + logEmail6.set_Usuario(Recursos.Usuario); + logEmail6.set_EntityId(maladiretum.get_Sinistro().get_Id()); + logEmail6.set_Data(networkTime); + logEmail6.set_Tela(maladiretum.get_Tela()); + logEmail6.set_Destinatarios(string.Join(";", strs2)); + logEmail6.set_Cco(string.Join(";", strs3)); + logEmail6.set_Assunto(destinatario.get_Assunto()); + logEmail6.set_Corpo(destinatario.get_Corpo()); + logEmail6.set_Anexos(string.Join(";", strs4)); + logEmail6.set_Versao(LoginViewModel.VersaoAtual); + logEmail6.set_NomeMaquina(Environment.MachineName); + logEmail6.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList3 = hostEntry.AddressList; + Func u003cu003e9_014 = MailHelper.u003cu003ec.u003cu003e9__0_14; + if (u003cu003e9_014 == null) + { + u003cu003e9_014 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + MailHelper.u003cu003ec.u003cu003e9__0_14 = u003cu003e9_014; + } + IPAddress pAddress6 = ((IEnumerable)addressList3).FirstOrDefault(u003cu003e9_014); + if (pAddress6 != null) + { + str2 = pAddress6.ToString(); + } + else + { + str2 = null; + } + logEmail6.set_Ip(str2); + logEmail6.set_Relatorio(maladiretum.get_Relatorio()); + commited.get_RegistroLogRepository().SaveOrUpdate(logEmail6); + } + } + commited.Commit(); + } + } + return logEnvio1; + }); + return logEnvio2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/NotifyPropertyChangedExtension.cs b/Codemerx/Gestor.Application/Helpers/NotifyPropertyChangedExtension.cs new file mode 100644 index 0000000..955e38b --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/NotifyPropertyChangedExtension.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Application.Helpers +{ + public static class NotifyPropertyChangedExtension + { + public static void MutateVerbose(this INotifyPropertyChanged instance, ref TField field, TField newValue, Action raise, [CallerMemberName] string propertyName = null) + { + if (EqualityComparer.Default.Equals(field, newValue)) + { + return; + } + field = newValue; + if (raise != null) + { + raise(new PropertyChangedEventArgs(propertyName)); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/ObrigatorioValidationRule.cs b/Codemerx/Gestor.Application/Helpers/ObrigatorioValidationRule.cs new file mode 100644 index 0000000..ff5dc58 --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/ObrigatorioValidationRule.cs @@ -0,0 +1,34 @@ +using System; +using System.Globalization; +using System.Runtime.CompilerServices; +using System.Windows.Controls; + +namespace Gestor.Application.Helpers +{ + public class ObrigatorioValidationRule : ValidationRule + { + public bool IsRequired + { + get; + set; + } + + public ObrigatorioValidationRule() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + string str = value as string; + if (str == null) + { + return new ValidationResult(false, "OBRIGATÓRIO"); + } + if (str == null || !this.IsRequired || !string.IsNullOrWhiteSpace(str)) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "OBRIGATÓRIO"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/PasswordBoxAssistant.cs b/Codemerx/Gestor.Application/Helpers/PasswordBoxAssistant.cs new file mode 100644 index 0000000..8944bc7 --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/PasswordBoxAssistant.cs @@ -0,0 +1,95 @@ +using System; +using System.Windows; +using System.Windows.Controls; + +namespace Gestor.Application.Helpers +{ + public static class PasswordBoxAssistant + { + public readonly static DependencyProperty BoundPassword; + + public readonly static DependencyProperty BindPassword; + + private readonly static DependencyProperty UpdatingPassword; + + static PasswordBoxAssistant() + { + PasswordBoxAssistant.BoundPassword = DependencyProperty.RegisterAttached("BoundPassword", typeof(string), typeof(PasswordBoxAssistant), new PropertyMetadata(string.Empty, new PropertyChangedCallback(PasswordBoxAssistant.OnBoundPasswordChanged))); + PasswordBoxAssistant.BindPassword = DependencyProperty.RegisterAttached("BindPassword", typeof(bool), typeof(PasswordBoxAssistant), new PropertyMetadata(false, new PropertyChangedCallback(PasswordBoxAssistant.OnBindPasswordChanged))); + PasswordBoxAssistant.UpdatingPassword = DependencyProperty.RegisterAttached("UpdatingPassword", typeof(bool), typeof(PasswordBoxAssistant), new PropertyMetadata(false)); + } + + public static bool GetBindPassword(DependencyObject dp) + { + return (bool)dp.GetValue(PasswordBoxAssistant.BindPassword); + } + + public static string GetBoundPassword(DependencyObject dp) + { + return (string)dp.GetValue(PasswordBoxAssistant.BoundPassword); + } + + private static bool GetUpdatingPassword(DependencyObject dp) + { + return (bool)dp.GetValue(PasswordBoxAssistant.UpdatingPassword); + } + + private static void HandlePasswordChanged(object sender, RoutedEventArgs e) + { + PasswordBox passwordBox = sender as PasswordBox; + PasswordBoxAssistant.SetUpdatingPassword(passwordBox, true); + PasswordBoxAssistant.SetBoundPassword(passwordBox, passwordBox.Password); + PasswordBoxAssistant.SetUpdatingPassword(passwordBox, false); + } + + private static void OnBindPasswordChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e) + { + PasswordBox passwordBox = dp as PasswordBox; + if (passwordBox == null) + { + return; + } + bool oldValue = (bool)e.OldValue; + bool newValue = (bool)e.NewValue; + if (oldValue) + { + passwordBox.PasswordChanged -= new RoutedEventHandler(PasswordBoxAssistant.HandlePasswordChanged); + } + if (newValue) + { + passwordBox.PasswordChanged += new RoutedEventHandler(PasswordBoxAssistant.HandlePasswordChanged); + } + } + + private static void OnBoundPasswordChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + PasswordBox passwordBox = d as PasswordBox; + if (d == null || !PasswordBoxAssistant.GetBindPassword(d)) + { + return; + } + passwordBox.PasswordChanged -= new RoutedEventHandler(PasswordBoxAssistant.HandlePasswordChanged); + string newValue = (string)e.NewValue; + if (!PasswordBoxAssistant.GetUpdatingPassword(passwordBox)) + { + passwordBox.Password = newValue; + } + passwordBox.PasswordChanged += new RoutedEventHandler(PasswordBoxAssistant.HandlePasswordChanged); + } + + public static void SetBindPassword(DependencyObject dp, bool value) + { + dp.SetValue(PasswordBoxAssistant.BindPassword, value); + } + + public static void SetBoundPassword(DependencyObject dp, string value) + { + dp.SetValue(PasswordBoxAssistant.BoundPassword, value); + } + + private static void SetUpdatingPassword(DependencyObject dp, bool value) + { + dp.SetValue(PasswordBoxAssistant.UpdatingPassword, value); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/PipeClient.cs b/Codemerx/Gestor.Application/Helpers/PipeClient.cs new file mode 100644 index 0000000..5e8d841 --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/PipeClient.cs @@ -0,0 +1,52 @@ +using System; +using System.IO; +using System.IO.Pipes; +using System.Runtime.CompilerServices; + +namespace Gestor.Application.Helpers +{ + public class PipeClient + { + private string _pipeName; + + private NamedPipeClientStream Pipe + { + get; + set; + } + + public PipeClient(string pipeName) + { + this._pipeName = pipeName; + } + + public bool Send(dynamic message) + { + bool flag; + try + { + this.Pipe = new NamedPipeClientStream(".", this._pipeName, PipeDirection.Out, PipeOptions.Asynchronous); + this.Pipe.Connect(1000); + if (this.Pipe.IsConnected) + { + using (StreamWriter streamWriter = new StreamWriter(this.Pipe)) + { + streamWriter.AutoFlush = true; + streamWriter.WriteLine(JsonConvert.SerializeObject(message)); + this.Pipe.WaitForPipeDrain(); + } + return true; + } + else + { + flag = false; + } + } + catch (TimeoutException timeoutException) + { + flag = false; + } + return flag; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/PipeServer.cs b/Codemerx/Gestor.Application/Helpers/PipeServer.cs new file mode 100644 index 0000000..fa42e03 --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/PipeServer.cs @@ -0,0 +1,115 @@ +using Assinador.Model.Common; +using Gestor.Application.Actions; +using Newtonsoft.Json; +using System; +using System.IO; +using System.IO.Pipes; +using System.Runtime.CompilerServices; +using System.Security.AccessControl; +using System.Security.Principal; + +namespace Gestor.Application.Helpers +{ + public class PipeServer : IDisposable + { + private string _pipeName; + + private NamedPipeServerStream Pipe + { + get; + set; + } + + public PipeServer() + { + } + + private bool Create() + { + bool flag; + bool flag1 = true; + try + { + (new NamedPipeClientStream(".", this._pipeName, PipeDirection.Out, PipeOptions.Asynchronous)).Connect(1000); + } + catch (TimeoutException timeoutException) + { + flag1 = false; + } + catch (Exception exception) + { + flag = false; + return flag; + } + if (flag1) + { + return true; + } + try + { + PipeSecurity pipeSecurity = new PipeSecurity(); + SecurityIdentifier securityIdentifier = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null); + securityIdentifier.Translate(typeof(NTAccount)); + pipeSecurity.SetAccessRule(new PipeAccessRule(securityIdentifier, PipeAccessRights.ReadWrite, AccessControlType.Allow)); + this.Pipe = new NamedPipeServerStream(this._pipeName, PipeDirection.In, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 1, 1, pipeSecurity); + this.Pipe.BeginWaitForConnection(new AsyncCallback(this.WaitForConnectionCallBack), this.Pipe); + return true; + } + catch (Exception exception1) + { + flag = false; + } + return flag; + } + + public bool CreateServer(string name) + { + this._pipeName = name; + return this.Create(); + } + + public void Dispose() + { + this.Pipe.Dispose(); + } + + private void Handle(string message) + { + if (message == null) + { + return; + } + PipeMessageResult pipeMessageResult = JsonConvert.DeserializeObject(message); + Action acessarHoster = Gestor.Application.Actions.Actions.AcessarHoster; + if (acessarHoster == null) + { + return; + } + acessarHoster(pipeMessageResult); + } + + private void WaitForConnectionCallBack(IAsyncResult iar) + { + try + { + NamedPipeServerStream asyncState = (NamedPipeServerStream)iar.AsyncState; + asyncState.EndWaitForConnection(iar); + using (StreamReader streamReader = new StreamReader(this.Pipe)) + { + string str = streamReader.ReadLine(); + if ((str == null ? false : str.IndexOf("exit", StringComparison.InvariantCultureIgnoreCase) > -1)) + { + this.Dispose(); + } + this.Handle(str); + } + asyncState.Close(); + asyncState = null; + this.Create(); + } + catch + { + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/QueryableHelper.cs b/Codemerx/Gestor.Application/Helpers/QueryableHelper.cs new file mode 100644 index 0000000..5670bf2 --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/QueryableHelper.cs @@ -0,0 +1,26 @@ +using System; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Application.Helpers +{ + public static class QueryableHelper + { + public static IOrderedQueryable OrderBy(this IQueryable source, string propertyName) + { + return source.OrderBy(QueryableHelper.ToLambda(propertyName)); + } + + public static IOrderedQueryable OrderByDescending(this IQueryable source, string propertyName) + { + return source.OrderByDescending(QueryableHelper.ToLambda(propertyName)); + } + + private static Expression> ToLambda(string propertyName) + { + ParameterExpression parameterExpression = Expression.Parameter(typeof(T)); + return Expression.Lambda>(Expression.Convert(Expression.Property(parameterExpression, propertyName), typeof(object)), new ParameterExpression[] { parameterExpression }); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/Recursos.cs b/Codemerx/Gestor.Application/Helpers/Recursos.cs new file mode 100644 index 0000000..8800d53 --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/Recursos.cs @@ -0,0 +1,170 @@ +using Agger.Registro; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Net; +using System.Runtime.CompilerServices; + +namespace Gestor.Application.Helpers +{ + public static class Recursos + { + public const string AppStore = "https://apps.apple.com/br/app/agger-mobile/id1463091598"; + + public const string PlayStore = "https://play.google.com/store/apps/details?id=br.com.aggermobile&hl=pt&gl=US"; + + public const int DefaultMaxSize = 14336; + + public static Uri ApiArquivo + { + get; + } + + public static List BancosContas + { + get; + set; + } + + public static List Coberturas + { + get; + set; + } + + public static List Configuracoes + { + get; + set; + } + + public static List Descricao + { + get; + set; + } + + public static Gestor.Model.Domain.Common.Empresa Empresa + { + get; + set; + } + + public static List Empresas + { + get; + set; + } + + public static List Estipulantes + { + get; + set; + } + + public static List Fabricantes + { + get; + set; + } + + public static IPHostEntry Host + { + get; + set; + } + + public static List Parametros + { + get; + set; + } + + public static List Parceiros + { + get; + set; + } + + public static List Produtos + { + get; + set; + } + + public static List Ramos + { + get; + set; + } + + public static string Registrar + { + get; + set; + } + + public static List Seguradoras + { + get; + set; + } + + public static List Status + { + get; + set; + } + + public static List StatusProspeccao + { + get; + set; + } + + public static List TiposTarefa + { + get; + set; + } + + public static List TipoVendedor + { + get; + set; + } + + public static Gestor.Model.Domain.Seguros.Usuario Usuario + { + get; + set; + } + + public static List Usuarios + { + get; + set; + } + + public static List Vendedores + { + get; + set; + } + + public static Uri WhatsAppLink + { + get; + } + + static Recursos() + { + Recursos.WhatsAppLink = new Uri("https://api.whatsapp.com/send?"); + Recursos.ApiArquivo = Address.get_ApiArquivo(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/TipoToggle.cs b/Codemerx/Gestor.Application/Helpers/TipoToggle.cs new file mode 100644 index 0000000..294a15d --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/TipoToggle.cs @@ -0,0 +1,14 @@ +using System; + +namespace Gestor.Application.Helpers +{ + [Flags] + public enum TipoToggle + { + None = 0, + Consultar = 1, + Incluir = 2, + Alterar = 4, + Excluir = 8 + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/ViewHelper.cs b/Codemerx/Gestor.Application/Helpers/ViewHelper.cs new file mode 100644 index 0000000..9c17374 --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/ViewHelper.cs @@ -0,0 +1,462 @@ +using CurrencyTextBoxControl; +using Gestor.Application.Componentes; +using Gestor.Model.Helper; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using System.Dynamic; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Data; +using System.Windows.Media; +using Xceed.Wpf.Toolkit; +using Xceed.Wpf.Toolkit.Primitives; + +namespace Gestor.Application.Helpers +{ + public static class ViewHelper + { + internal static void BindData(this CheckComboBox comboBox, bool withSelect = true, bool enumDefault = true, string defaultValue = "", bool orderByLabel = false) + { + ViewHelper.DefaultBinding(comboBox, withSelect, enumDefault, defaultValue, string.Empty, orderByLabel); + } + + public static void ClearInvalid(this DependencyObject dependencyObject) + { + foreach (Control control in ViewHelper.FindChildren(dependencyObject)) + { + control.SetInvalid(null, null); + } + } + + private static bool Compare(Control currentControl) + { + object resolvedSource; + DependencyProperty dependencyProperty = ViewHelper.GetDependencyProperty(currentControl); + if (dependencyProperty == null) + { + return false; + } + BindingExpression bindingExpression = currentControl.GetBindingExpression(dependencyProperty); + if (bindingExpression != null) + { + resolvedSource = bindingExpression.ResolvedSource; + } + else + { + resolvedSource = null; + } + dynamic obj = resolvedSource; + dynamic obj1 = obj != (dynamic)null; + return (bool)((!obj1 ? obj1 : obj1 & (bool)obj.HasChange())); + } + + public static void ControlLostFocus(object sender, RoutedEventArgs e) + { + dynamic obj; + Control control; + Control control1 = null; + if (sender is CustomItemValidation) + { + control1 = ViewHelper.FindChildren(sender as CustomItemValidation).FirstOrDefault((Control currentControl) => { + if (currentControl is PasswordBox || currentControl is TextBox || currentControl is ToggleButton || currentControl is DatePicker || currentControl is ComboBox || currentControl is AutoCompleteBox || currentControl is CheckComboBox || currentControl is Button) + { + return true; + } + return currentControl is CustomPasswordBox; + }); + } + if (sender is CustomIsReadOnlyControl) + { + CustomIsReadOnlyControl customIsReadOnlyControl = sender as CustomIsReadOnlyControl; + if (!customIsReadOnlyControl.HasValidation) + { + control = null; + } + else + { + control = ViewHelper.FindChildren(customIsReadOnlyControl).LastOrDefault((Control currentControl) => { + if (currentControl is PasswordBox || currentControl is TextBox || currentControl is ToggleButton || currentControl is DatePicker || currentControl is ComboBox || currentControl is AutoCompleteBox || currentControl is CheckComboBox) + { + return true; + } + return currentControl is Button; + }); + } + control1 = control; + } + if (control1 == null) + { + return; + } + ComboBox comboBox = control1 as ComboBox; + if (comboBox != null && comboBox.IsDropDownOpen) + { + return; + } + if (control1 is TextBox && ((TextBox)control1).IsReadOnly) + { + return; + } + DependencyProperty dependencyProperty = ViewHelper.GetDependencyProperty(control1); + if (dependencyProperty == null) + { + return; + } + BindingExpression bindingExpression = control1.GetBindingExpression(dependencyProperty); + if (bindingExpression == null) + { + return; + } + Validation.ClearInvalid(bindingExpression); + List list = bindingExpression.ParentBinding.Path.Path.Split(new char[] { '.' }).ToList(); + Type type = bindingExpression.DataItem.GetType(); + if (!list.Any()) + { + return; + } + PropertyInfo property = type.GetProperty(list.First()); + if (property == null) + { + return; + } + dynamic value = property.GetValue(bindingExpression.DataItem, null); + List> keyValuePairs = new List>(); + if ((dynamic)(!ViewHelper.HasMethod(value, "ValidationEvent"))) + { + dynamic resolvedSource = bindingExpression.ResolvedSource; + if (resolvedSource is Control) + { + return; + } + if ((dynamic)(!ViewHelper.HasMethod(resolvedSource, "ValidationEvent"))) + { + return; + } + obj = resolvedSource; + if ((obj != null ? obj.ValidationEvent : null) == (dynamic)null) + { + return; + } + Func>> func = resolvedSource.ValidationEvent as Func>>; + if (func != null) + { + keyValuePairs = func(); + } + if (keyValuePairs.Count == 0) + { + return; + } + } + if (keyValuePairs.Count == 0) + { + obj = value; + if ((obj != null ? obj.ValidationEvent : null) == (dynamic)null) + { + return; + } + Func>> func1 = value.ValidationEvent as Func>>; + if (func1 != null) + { + keyValuePairs = func1(); + } + } + if (keyValuePairs == null || !keyValuePairs.Any>()) + { + return; + } + string str = (list.Last() == "Id" ? list[list.Count - 2] : list.Last()); + string valueExact = ValidationHelper.GetValueExact(keyValuePairs, str); + if (string.IsNullOrEmpty(valueExact)) + { + valueExact = ValidationHelper.GetValueExact(keyValuePairs, str); + if (string.IsNullOrEmpty(valueExact)) + { + return; + } + } + Validation.MarkInvalid(bindingExpression, new ValidationError(new ExceptionValidationRule(), bindingExpression) + { + ErrorContent = valueExact + }); + } + + private static void DefaultBinding(CheckComboBox comboBox, bool withSelect, bool enumDefault, string defaultValue = "", string defaultText = "", bool orderByLabel = false) + { + List> keyValuePairs = BindingHelper.BindingData(withSelect, enumDefault, defaultValue, defaultText, orderByLabel, false, false); + comboBox.ItemsSource = keyValuePairs; + comboBox.set_ValueMemberPath("Key"); + comboBox.DisplayMemberPath = "Value"; + comboBox.set_SelectedItem(keyValuePairs.First>()); + } + + public static IEnumerable FindAncestor(DependencyObject dependencyObject) + where T : DependencyObject + { + for (DependencyObject i = VisualTreeHelper.GetParent(dependencyObject); i != null; i = VisualTreeHelper.GetParent(i)) + { + T t = (T)(i as T); + if (t != null) + { + yield return t; + } + } + } + + public static IEnumerable FindChildren(DependencyObject depObj) + where T : DependencyObject + { + if (depObj != null) + { + IEnumerator enumerator = LogicalTreeHelper.GetChildren(depObj).GetEnumerator(); + while (enumerator.MoveNext()) + { + object current = enumerator.Current; + T t = (T)(current as T); + if (t != null) + { + ContentControl contentControl = (object)t as ContentControl; + if (contentControl == null || (object)t as UserControl != null) + { + yield return t; + } + } + foreach (T t1 in ViewHelper.FindChildren(current as DependencyObject)) + { + yield return t1; + } + current = null; + } + enumerator = null; + } + else + { + } + } + + public static IEnumerable FindParent(DependencyObject depObj) + where T : DependencyObject + { + if (depObj != null) + { + DependencyObject parent = LogicalTreeHelper.GetParent(depObj); + T t = (T)(parent as T); + if (t != null) + { + yield return t; + } + foreach (T t1 in ViewHelper.FindParent(parent)) + { + yield return t1; + } + } + else + { + } + } + + private static DependencyProperty GetDependencyProperty(Control currentControl) + { + DependencyProperty selectedValueProperty = null; + if (currentControl is CheckComboBox) + { + selectedValueProperty = Xceed.Wpf.Toolkit.Primitives.Selector.SelectedValueProperty; + } + if (currentControl is DatePicker) + { + selectedValueProperty = DatePicker.SelectedDateProperty; + } + if (currentControl is AutoCompleteBox) + { + selectedValueProperty = AutoCompleteBox.SelectedItemProperty; + } + if (currentControl is TextBox) + { + selectedValueProperty = TextBox.TextProperty; + } + if (currentControl is MaskedTextBox) + { + selectedValueProperty = TextBox.TextProperty; + } + if (currentControl is ComboBox) + { + selectedValueProperty = System.Windows.Controls.Primitives.Selector.SelectedValueProperty; + } + if (currentControl is CurrencyTextBox) + { + selectedValueProperty = CurrencyTextBox.NumberProperty; + } + if (currentControl is ToggleButton) + { + selectedValueProperty = ToggleButton.IsCheckedProperty; + } + if (currentControl is CustomPasswordBox) + { + selectedValueProperty = CustomPasswordBox.TextProperty; + } + return selectedValueProperty; + } + + public static bool HasMethod(object objectToCheck, string methodName) + { + if (objectToCheck == null) + { + return false; + } + return objectToCheck.GetType().GetProperty(methodName) != null; + } + + public static bool IsPropertyExist(dynamic settings, string name) + { + if (settings is ExpandoObject) + { + return ((IDictionary)settings).ContainsKey(name); + } + return (bool)(settings.GetType().GetProperty(name) != (dynamic)null); + } + + public static bool IsValid(this DependencyObject obj) + { + if (Validation.GetHasError(obj)) + { + return false; + } + return LogicalTreeHelper.GetChildren(obj).OfType().All(new Func(ViewHelper.IsValid)); + } + + public static bool IsWindowOpen(string name = "") + where T : Window + { + if (string.IsNullOrEmpty(name)) + { + return System.Windows.Application.Current.Windows.OfType().Any(); + } + return System.Windows.Application.Current.Windows.OfType().Any((T w) => w.Name.Equals(name)); + } + + public static Control SetInvalid(this Control currentControl, List> errorMessages = null, string specificKey = null) + { + DependencyProperty dependencyProperty = ViewHelper.GetDependencyProperty(currentControl); + if (dependencyProperty == null) + { + return null; + } + BindingExpression bindingExpression = currentControl.GetBindingExpression(dependencyProperty); + if (errorMessages == null) + { + dynamic obj = (bindingExpression != null ? bindingExpression.ResolvedSource : null); + if (obj is Control) + { + return null; + } + if ((dynamic)(!ViewHelper.HasMethod(obj, "ValidationEvent"))) + { + return null; + } + dynamic obj1 = obj; + if ((obj1 != null ? obj1.ValidationEvent : null) == (dynamic)null) + { + return null; + } + Func>> func = obj.ValidationEvent as Func>>; + if (func != null) + { + errorMessages = func(); + } + } + if (bindingExpression == null) + { + return null; + } + BindingExpressionBase bindingExpressionBase = BindingOperations.GetBindingExpressionBase(currentControl, dependencyProperty); + if (bindingExpressionBase == null) + { + return null; + } + Validation.ClearInvalid(bindingExpressionBase); + if (errorMessages == null || !errorMessages.Any>()) + { + return null; + } + string[] strArrays = bindingExpression.ParentBinding.Path.Path.Split(new char[] { '.' }); + string str = specificKey ?? (strArrays.Last() == "Id" ? strArrays[(int)strArrays.Length - 2] : strArrays.Last()); + string valueExact = ValidationHelper.GetValueExact(errorMessages, str); + if (string.IsNullOrEmpty(valueExact)) + { + valueExact = ValidationHelper.GetValueExact(errorMessages, str); + if (string.IsNullOrEmpty(valueExact)) + { + return null; + } + } + Validation.MarkInvalid(bindingExpressionBase, new ValidationError(new ExceptionValidationRule(), bindingExpression) + { + ErrorContent = valueExact + }); + return currentControl; + } + + public static void SetInvalid(Control control, string error, bool valid) + { + DependencyProperty dependencyProperty = ViewHelper.GetDependencyProperty(control); + if (dependencyProperty == null) + { + return; + } + BindingExpression bindingExpression = control.GetBindingExpression(dependencyProperty); + if (bindingExpression == null) + { + return; + } + ValidationError validationError = new ValidationError(new ExceptionValidationRule(), bindingExpression) + { + ErrorContent = error + }; + BindingExpressionBase bindingExpressionBase = BindingOperations.GetBindingExpressionBase(control, dependencyProperty); + if (bindingExpressionBase == null) + { + return; + } + Validation.ClearInvalid(bindingExpressionBase); + if (valid) + { + return; + } + Validation.MarkInvalid(bindingExpressionBase, validationError); + } + + public static void ValidateFields(this DependencyObject dependencyObject, List> errorMessages, bool focusField = true) + { + if ((errorMessages == null ? true : !errorMessages.Any>())) + { + dependencyObject.ClearInvalid(); + return; + } + Control control = null; + foreach (Control control1 in ViewHelper.FindChildren(dependencyObject)) + { + Control control2 = control1.SetInvalid(errorMessages, null); + if (control != null || control2 == null) + { + continue; + } + control = control2; + } + if (focusField && control != null) + { + control.Focus(); + } + } + + public static T Window() + where T : Window + { + return System.Windows.Application.Current.Windows.OfType().FirstOrDefault(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/MainWindow.cs b/Codemerx/Gestor.Application/MainWindow.cs new file mode 100644 index 0000000..a4ed795 --- /dev/null +++ b/Codemerx/Gestor.Application/MainWindow.cs @@ -0,0 +1,3069 @@ +using Agger.Application.Menu; +using Agger.Registro; +using Assinador.Model.Common; +using Gestor.Application.Actions; +using Gestor.Application.Componentes; +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Application.Views.BI; +using Gestor.Application.Views.Ferramentas; +using Gestor.Application.Views.Financeiro; +using Gestor.Application.Views.Financeiro.Relatorios; +using Gestor.Application.Views.Generic; +using Gestor.Application.Views.Menus; +using Gestor.Application.Views.Relatorios; +using Gestor.Application.Views.Seguros; +using Gestor.Common.Helpers; +using Gestor.Common.Security; +using Gestor.Common.Validation; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.API; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.License; +using MaterialDesignThemes.Wpf; +using QRCoder; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Drawing; +using System.Drawing.Imaging; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Sockets; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Forms; +using System.Windows.Input; +using System.Windows.Interop; +using System.Windows.Markup; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Shapes; +using System.Windows.Shell; +using System.Windows.Threading; + +namespace Gestor.Application +{ + public class MainWindow : Window, IComponentConnector, IStyleConnector + { + internal MainViewModel ViewModel; + + private bool _buttonClickable; + + private string _lastSearch; + + private DateTime? lastSearchTime; + + private System.Windows.Controls.TextBox _textBox; + + internal System.Windows.Shell.WindowChrome WindowChrome; + + internal Grid MinimizeButton; + + internal Grid MaximizeButton; + + internal Grid CloseButton; + + internal HamburgerMenu MainMenu; + + internal HamburgerMenuItem CentralDeNegociosMenu; + + internal HamburgerMenuItem DashBoard; + + internal HamburgerMenuItem PainelBi; + + internal HamburgerMenuItem Prospeccao; + + internal HamburgerMenuItem SegurosMenu; + + internal HamburgerMenuItem Consulta; + + internal HamburgerMenuItem Clientes; + + internal HamburgerMenuItem Apolices; + + internal HamburgerMenuItem Itens; + + internal HamburgerMenuItem Sinistros; + + internal HamburgerMenuItem ImportPdf; + + internal HamburgerMenuItem CriticaPdf; + + internal HamburgerMenuItem Comissao; + + internal HamburgerMenuItem RelatoriosMenu; + + internal HamburgerMenuItem RelatoriosCliente; + + internal HamburgerMenuItem RelatoriosDocumentos; + + internal HamburgerMenuItem RelatoriosParcelas; + + internal HamburgerMenuItem RelatoriosSinistros; + + internal HamburgerMenuItem RelatoriosFechamento; + + internal HamburgerMenuItem RelatoriosExtrato; + + internal HamburgerMenuItem RelatoriosNotas; + + internal HamburgerMenuItem RelatoriosTarefas; + + internal HamburgerMenuItem RelatoriosLogs; + + internal HamburgerMenuItem ExtratoConta; + + internal HamburgerMenuItem FechamentoFinanceiro; + + internal HamburgerMenuItem Assinatura; + + internal HamburgerMenuItem Aggilizador; + + internal HamburgerMenuItem Epic; + + internal HamburgerMenuItem FinanceiroMenu; + + internal HamburgerMenuItem Conta; + + internal HamburgerMenuItem Centro; + + internal HamburgerMenuItem Fornecedor; + + internal HamburgerMenuItem Plano; + + internal HamburgerMenuItem FerramentasMenu; + + internal HamburgerMenuItem Emails; + + internal HamburgerMenuItem Empresa; + + internal HamburgerMenuItem Estipulantes; + + internal HamburgerMenuItem ManutencaoPagamentos; + + internal HamburgerMenuItem NotaFiscal; + + internal HamburgerMenuItem Parceiro; + + internal HamburgerMenuItem Produtos; + + internal HamburgerMenuItem Qualificacao; + + internal HamburgerMenuItem Ramos; + + internal HamburgerMenuItem Recibo; + + internal HamburgerMenuItem Seguradoras; + + internal HamburgerMenuItem Socio; + + internal HamburgerMenuItem Statuses; + + internal HamburgerMenuItem StatusProspeccao; + + internal HamburgerMenuItem TipoTarefa; + + internal HamburgerMenuItem TipoVendedor; + + internal HamburgerMenuItem Usuarios; + + internal HamburgerMenuItem Vendedores; + + internal RowDefinition Area; + + internal System.Windows.Controls.ComboBox Status; + + internal System.Windows.Controls.ComboBox FiltroClienteTipoBox; + + internal AutoCompleteBox PesquisaCliente; + + internal AutoCompleteBox PesquisaClienteNome; + + internal Loading LoadingAutoComplete; + + internal System.Windows.Controls.TextBox DocumentoPrincipalBox; + + internal System.Windows.Controls.Button ObservacaoApolice; + + internal System.Windows.Controls.MenuItem PesquisaAvancada; + + internal System.Windows.Controls.MenuItem Voltar; + + internal System.Windows.Controls.ContentControl ContentControl; + + internal PopupBox QrCode; + + internal System.Windows.Controls.Image ImageAppStore; + + internal System.Windows.Controls.Image ImageGooglePlay; + + internal TextBlock SessionNumber; + + internal PopupBox BoletoPopup; + + internal PopupBox HelpPopup; + + internal StackPanel TarefaPopup; + + internal MaterialDesignThemes.Wpf.Snackbar Snackbar; + + internal Grid ProgressRing; + + internal MaterialDesignThemes.Wpf.DrawerHost DrawerHost; + + private bool _contentLoaded; + + public object _lastCustomer + { + get; + set; + } + + private AcessoApolice Acesso + { + get; + set; + } + + public static System.Windows.WindowState ApplicationState + { + get; + set; + } + + private Key? lastKey + { + get; + set; + } + + private string lastSearch + { + get + { + return this._lastSearch; + } + set + { + this._lastSearch = value; + this.lastSearchTime = new DateTime?(DateTime.Now); + } + } + + private Gestor.Model.Common.ManutencaoItem ManutencaoItem + { + get; + set; + } + + private string PipeName + { + get; + set; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public MainWindow() + { + this.ViewModel = new MainViewModel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + Gestor.Application.Actions.Actions.AcessaTela = new Action(this.AcessarTela); + Gestor.Application.Actions.Actions.IniciarAggilizador = new Action(this.IniciarAggilizador); + App.SnackBar = this.Snackbar; + App.ProgressRing = this.ProgressRing; + App.ProgressRing.Visibility = System.Windows.Visibility.Collapsed; + Gestor.Application.Actions.Actions.NomeTela = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.NomeTela, new Action(this.DefinirNomeTela)); + Gestor.Application.Actions.Actions.EnablePesquisarClientes = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.EnablePesquisarClientes, new Action(this.HabilitarPesquisarClientes)); + Gestor.Application.Actions.Actions.EnableMainMenu = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.EnableMainMenu, new Action(this.HabilitarMenu)); + Gestor.Application.Actions.Actions.AcessarHoster = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.AcessarHoster, new Action(this.AcessarHoster)); + this.MinimizeButton.MouseEnter += new System.Windows.Input.MouseEventHandler(MainWindow.TopControls_OnMouseEnter); + this.MinimizeButton.MouseLeave += new System.Windows.Input.MouseEventHandler(this.TopControls_OnMouseLeave); + this.MaximizeButton.MouseEnter += new System.Windows.Input.MouseEventHandler(MainWindow.TopControls_OnMouseEnter); + this.MaximizeButton.MouseLeave += new System.Windows.Input.MouseEventHandler(this.TopControls_OnMouseLeave); + this.CloseButton.MouseEnter += new System.Windows.Input.MouseEventHandler(MainWindow.TopControls_OnMouseEnter); + this.CloseButton.MouseLeave += new System.Windows.Input.MouseEventHandler(this.TopControls_OnMouseLeave); + this.ViewModel.Head = string.Concat("BEM VINDO, ", Recursos.Usuario.get_Nome()); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher != null) + { + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + else + { + } + base.Icon = new BitmapImage(Address.IconeGestor); + } + + private void AbrirAtendimento() + { + if (Recursos.Usuario == null || Recursos.Usuario.get_Id() == 0) + { + return; + } + string str = (Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(Recursos.Usuario.get_SsoId()) ? string.Format("{0}:{1}:SSO", Recursos.Usuario.get_SsoId(), Recursos.Usuario.get_Id()) : EncryptionHelper.Encrypt(Recursos.Usuario.get_Senha())); + string str1 = EncryptionHelper.Encrypt(string.Format("{0}:{1}:{2}", ApplicationHelper.IdFornecedor, Recursos.Usuario.get_Login(), str)); + Process.Start(Address.get_CentralAtendimento().Append(new string[] { "Acessar" }).AddQuery("id", str1).ToString()); + } + + private static void AbrirTarefas() + { + string str = string.Format("VOCÊ ESTÁ EM CONSULTA DE TAREFAS | VERSÃO GESTOR {0}", ApplicationHelper.Versao); + TarefaView tarefaView = new TarefaView(); + string[] nome = new string[] { "OLÁ, ", Recursos.Usuario.get_Nome(), " - ", Recursos.Empresa.get_Nome(), ", ", str }; + double? nullable = null; + double? nullable1 = nullable; + nullable = null; + (new HosterWindow(tarefaView, string.Concat(nome), nullable1, nullable, false)).Show(); + } + + private async void AcessarHoster(PipeMessageResult pipeMessage) + { + HosterWindow hosterWindow = null; + if (pipeMessage.get_Funcao() == null) + { + Documento documento = await (new ApoliceServico()).BuscarApoliceAsync(long.Parse(pipeMessage.get_Json()), false, false); + Documento documento1 = documento; + base.Dispatcher.Invoke(() => { + ApoliceView apoliceView = new ApoliceView(documento1, true, false, 0, (long)0, false); + double? nullable = null; + double? nullable1 = nullable; + nullable = null; + hosterWindow = new HosterWindow(apoliceView, string.Concat("CADASTRO DE APÓLICES - ", documento1.get_Controle().get_Cliente().get_Nome()), nullable1, nullable, false); + hosterWindow.Show(); + }); + } + } + + private async void AcessarTela(TipoTela tela, string subTela = "") + { + string str; + TipoTela tipoTela = tela; + switch (tipoTela) + { + case 1: + { + TipoRestricao? nullable = null; + if (await this.VerificarLicenca(this.Clientes.get_Produto(), this.Clientes.get_Tela(), nullable)) + { + this.Clientes_OnClick(this.Clientes, new RoutedEventArgs()); + goto case 6; + } + else + { + break; + } + } + case 2: + { + bool acesso = this.Acesso != 0; + if (acesso) + { + acesso = !await this.VerificarDocumento(this.Apolices.get_Produto(), this.Apolices.get_Tela()); + } + bool flag = acesso; + if (!flag) + { + flag = !await this.VerificarCliente(this.Apolices.get_Produto(), this.Apolices.get_Tela()); + } + if (!flag) + { + str = subTela; + if (str == "Parcela") + { + this.Acesso = 1; + } + else if (str == "Renovar") + { + this.Acesso = 3; + } + else if (str == "Endossar") + { + this.Acesso = 2; + } + else + { + this.Acesso = 0; + } + this.Apolices_OnClick(this.Apolices, new RoutedEventArgs()); + goto case 6; + } + else + { + break; + } + } + case 3: + { + if (await this.VerificarDocumento(this.Itens.get_Produto(), this.Itens.get_Tela())) + { + str = subTela; + if (str == "Renovação") + { + Gestor.Model.Common.ManutencaoItem manutencaoItem = new Gestor.Model.Common.ManutencaoItem(); + manutencaoItem.set_Documento(ConsultaViewModel.DocumentoRenovado); + manutencaoItem.set_Tipo(0); + this.ManutencaoItem = manutencaoItem; + ConsultaViewModel.DocumentoRenovado = null; + } + else if (str == "Endosso") + { + Gestor.Model.Common.ManutencaoItem manutencaoItem1 = new Gestor.Model.Common.ManutencaoItem(); + manutencaoItem1.set_Documento(ConsultaViewModel.DocumentoSelecionado); + manutencaoItem1.set_Tipo(1); + this.ManutencaoItem = manutencaoItem1; + } + else if (str == "Manutencao") + { + Gestor.Model.Common.ManutencaoItem manutencaoItem2 = new Gestor.Model.Common.ManutencaoItem(); + manutencaoItem2.set_Documento(ConsultaViewModel.DocumentoSelecionado); + manutencaoItem2.set_Tipo(2); + this.ManutencaoItem = manutencaoItem2; + } + else + { + this.ManutencaoItem = null; + } + this.Itens_OnClick(this.Itens, new RoutedEventArgs()); + goto case 6; + } + else + { + break; + } + } + case 4: + case 5: + case 6: + { + break; + } + case 7: + { + if (await this.VerificarDocumento(this.Sinistros.get_Produto(), this.Sinistros.get_Tela())) + { + this.Sinistros_OnClick(this.Clientes, new RoutedEventArgs()); + goto case 6; + } + else + { + break; + } + } + default: + { + if (tipoTela != 21) + { + goto case 6; + } + this.Consultar_OnClick(this.SegurosMenu, new RoutedEventArgs()); + goto case 6; + } + } + } + + private async void AcessoRemoto_OnClick(object sender, RoutedEventArgs e) + { + if (!this.ViewModel.Restricao(58)) + { + string str = "c:\\AggerSeguros\\Remoto.exe"; + if (!File.Exists(str)) + { + Parameters parameter = new Parameters(); + parameter.set_Beta(false); + parameter.set_Type(99); + parameter.set_Application("Remoto.exe"); + parameter.set_Directory(""); + parameter.set_Run(true); + (new DownloadWindow(parameter)).Show(); + } + else + { + Process.Start(str); + } + } + else + { + await this.ViewModel.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSO REMOTO.", "OK", "", false); + } + } + + private async void Agenda_OnClick(object sender, RoutedEventArgs e) + { + if (await this.ViewModel.VerificarPermissao(34, false)) + { + this.ViewModel.ShowDrawer(new AgendaDrawer(), 0, false); + } + } + + private async void Aggilizador_OnClick(object sender, RoutedEventArgs e) + { + long? permissaoAggilizador = Recursos.Usuario.get_PermissaoAggilizador(); + if (permissaoAggilizador.HasValue) + { + permissaoAggilizador = Recursos.Usuario.get_PermissaoAggilizador(); + long num = (long)0; + if (!(permissaoAggilizador.GetValueOrDefault() == num & permissaoAggilizador.HasValue)) + { + List produtos = LicenseHelper.Produtos; + if (!produtos.Any((Licenca produto) => produto.get_Produto() == 91)) + { + this.IniciarAggilizador(); + return; + } + else + { + Process.Start(Address.CalculoWeb.ToString()); + List licencas = LicenseHelper.Produtos; + if (licencas.Any((Licenca produto) => produto.get_Produto() != 77)) + { + this.IniciarAggilizador(); + } + return; + } + } + } + await this.ViewModel.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR O AGGILIZADOR", "OK", "", false); + } + + private void Apolices_OnClick(object sender, RoutedEventArgs e) + { + if (MainViewModel.ClienteSelecionado == null) + { + return; + } + this.SetControl(typeof(ApoliceView), null); + this.Acesso = 0; + } + + private async void Assinatura_OnClick(object sender, RoutedEventArgs e) + { + string str; + object obj; + if (await this.ViewModel.ShowMessage("DESEJA ABRIR O SIGGNER PARA ASSINATURAS ELETRÔNICAS?", "SIM", "NÃO", false)) + { + str = ((new PipeServer()).CreateServer(this.PipeName) ? string.Concat(":", this.PipeName) : ""); + string str1 = str; + Token token = new Token(); + object[] numeroSerial = new object[] { ApplicationHelper.NumeroSerial, ApplicationHelper.IdFornecedor, Recursos.Usuario.get_Id(), null, null }; + obj = (ApplicationHelper.Beta ? "1" : "0"); + numeroSerial[3] = obj; + numeroSerial[4] = str1; + string str2 = token.Encrypt(string.Format("{0}:{1}:{2}:{3}:{4}", numeroSerial)); + Parameters parameter = new Parameters(); + parameter.set_Beta(ApplicationHelper.Beta); + parameter.set_Type(8); + parameter.set_Application("Assinador.Application.exe"); + parameter.set_Directory("Assinador.Application"); + parameter.set_Arguments(str2); + parameter.set_Run(true); + (new DownloadWindow(parameter)).Show(); + } + } + + private async void Atendimentos_OnClick(object sender, RoutedEventArgs e) + { + if (!this.ViewModel.Restricao(54)) + { + this.AbrirAtendimento(); + } + else + { + await this.ViewModel.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA ATENDIMENTOS.", "OK", "", false); + } + } + + private void AutoCompleteBox_Populating(object sender, PopulatingEventArgs e) + { + if (e.get_Parameter().Trim().Length < 3) + { + return; + } + e.set_Cancel(true); + this.lastSearch = e.get_Parameter().Trim(); + this.LoadingAutoComplete.Visibility = System.Windows.Visibility.Visible; + List list = ( + from vu in this.ViewModel.VendedorUsuario + select vu.get_Vendedor().get_Id()).ToList(); + if (this.ViewModel.SelectedFiltroCliente != 1) + { + this.ViewModel.SelectedFiltroCliente = (Regex.Replace(e.get_Parameter().Trim(), "[.\\-\\/]", "").All(new Func(char.IsDigit)) ? 2 : 0); + } + this.ViewModel.BuscarCliente(e.get_Parameter().Trim(), list, this.ViewModel.SelectedFiltroCliente).ContinueWith((Task> searchResult) => { + this.LoadingAutoComplete.Visibility = System.Windows.Visibility.Collapsed; + if (searchResult.Result == null) + { + return; + } + this.ViewModel.ClientesEncontrados = searchResult.Result; + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void AutoCompleteCliente_OnGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) + { + Key? nullable; + Key? nullable1; + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + this.MainMenu.Close(); + if (string.IsNullOrEmpty(autoCompleteBox.get_Text())) + { + nullable = null; + nullable1 = nullable; + } + else if (autoCompleteBox.get_Text().ToArray().LastOrDefault().ToString() == " ") + { + nullable1 = new Key?(Key.Space); + } + else + { + nullable = null; + nullable1 = nullable; + } + this.lastKey = nullable1; + } + + private void AutoCompleteNomeBox_Populating(object sender, PopulatingEventArgs e) + { + if (e.get_Parameter().Trim().Length < 3) + { + return; + } + e.set_Cancel(true); + if (this.lastSearch != null && this.lastSearchTime.HasValue && e.get_Parameter().Trim().Contains(this.lastSearch) && (DateTime.Now - this.lastSearchTime.Value).TotalSeconds < 10) + { + AutoCompleteBox autoCompleteBox1 = (AutoCompleteBox)sender; + autoCompleteBox1.set_ItemsSource(this.ViewModel.FiltrarClientes(e.get_Parameter().Trim())); + autoCompleteBox1.PopulateComplete(); + return; + } + this.lastSearch = e.get_Parameter().Trim(); + this.LoadingAutoComplete.Visibility = System.Windows.Visibility.Visible; + List list = ( + from vu in this.ViewModel.VendedorUsuario + select vu.get_Vendedor().get_Id()).ToList(); + this.ViewModel.BuscarCliente(e.get_Parameter().Trim(), list, this.ViewModel.SelectedFiltroCliente).ContinueWith((Task> searchResult) => { + this.LoadingAutoComplete.Visibility = System.Windows.Visibility.Collapsed; + if (searchResult.Result == null) + { + return; + } + this.ViewModel.ClientesEncontrados = searchResult.Result; + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void Boleto_OnClick(object sender, RoutedEventArgs e) + { + System.Windows.Controls.Button button = (System.Windows.Controls.Button)sender; + if (button == null || button.DataContext == null) + { + return; + } + Payment dataContext = (Payment)button.DataContext; + Process.Start(string.Format("{0}billet/id/{1}", Address.get_ApiBoletoAgger(), dataContext.get_Id())); + } + + private async void BoletosNotas_OnClick(object sender, RoutedEventArgs e) + { + if (!this.ViewModel.Restricao(55)) + { + this.AbrirAtendimento(); + } + else + { + await this.ViewModel.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA BOLETOS E NOTAS.", "OK", "", false); + } + } + + private async void CartaoVisita_OnClick(object sender, RoutedEventArgs e) + { + Process.Start(string.Format("{0}{1}", Address.get_Card(), Recursos.Usuario.get_Id().GeraCartaoVisita())); + } + + private async void Centro_OnClick(object sender, RoutedEventArgs e) + { + if (Recursos.Usuario.get_IdEmpresa() <= (long)1) + { + this.SetControl(typeof(CentroDeCustoView), null); + } + else + { + await this.ViewModel.ShowMessage("SOMENTE A MATRIZ POSSUI ACESSO AO FINANCEIRO.", "OK", "", false); + } + } + + private void Clientes_OnClick(object sender, RoutedEventArgs e) + { + this.SetControl(typeof(ClienteView), null); + } + + public async void CloseButton_Click() + { + string str; + if (await this.ViewModel.ShowMessage("DESEJA REALMENTE FECHAR O SISTEMA?", "SIM", "NÃO", false)) + { + if (Recursos.Usuario.get_Id() > (long)0) + { + DateTime networkTime = Funcoes.GetNetworkTime(); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(0); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + registroLog.set_Descricao(string.Format("O USUÁRIO {0} SAIU DO SISTEMA, EM {1}.", Recursos.Usuario.get_Nome(), networkTime)); + registroLog.set_EntidadeId(Recursos.Usuario.get_Id()); + registroLog.set_Tela(49); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList; + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + RegistroLog registroLog1 = registroLog; + using (UnitOfWork commited = Instancia.Commited) + { + (new BaseServico()).SaveLog(registroLog1, commited); + commited.Commit(); + } + } + Environment.Exit(0); + } + } + + private async void Comissao_OnClick(object sender, RoutedEventArgs e) + { + if (Recursos.Usuario.get_IdEmpresa() <= (long)1) + { + this.SetControl(typeof(ComissaoView), null); + } + else + { + await this.ViewModel.ShowMessage("SOMENTE A MATRIZ POSSUI ACESSO A TELA DE COMISSÃO AUTOMÁTICA.", "OK", "", false); + } + } + + private void Consultar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.PermissaoWhatsapp = this.ViewModel.Restricao(32); + this.SetControl(typeof(ConsultaOriginalView), null); + } + + private async void Conta_OnClick(object sender, RoutedEventArgs e) + { + if (Recursos.Usuario.get_IdEmpresa() <= (long)1) + { + this.SetControl(typeof(BancosContasView), null); + } + else + { + await this.ViewModel.ShowMessage("SOMENTE A MATRIZ POSSUI ACESSO AO FINANCEIRO.", "OK", "", false); + } + } + + private void ContentControl_GotFocus(object sender, RoutedEventArgs e) + { + this.MainMenu.Close(); + } + + private void ContentControl_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) + { + this.MainMenu.Close(); + } + + private async void ContentLoad() + { + System.Windows.Visibility visibility; + Type type; + Type type1; + TipoRestricao? nullable = null; + if (await this.VerificarLicenca(new Gestor.Model.License.Produto?(1), new TipoTela?(21), nullable)) + { + this.ViewModel.PermissaoWhatsapp = this.ViewModel.Restricao(32); + TipoTelaInicial? telaInicial = Recursos.Usuario.get_TelaInicial(); + if (telaInicial.HasValue) + { + TipoTelaInicial valueOrDefault = telaInicial.GetValueOrDefault(); + if (valueOrDefault == 1) + { + MainWindow mainWindow = this; + type = (this.ViewModel.Restricao(47) ? typeof(ConsultaOriginalView) : typeof(PainelBiView)); + mainWindow.SetControl(type, null); + goto Label0; + } + else + { + if (valueOrDefault != 2) + { + goto Label1; + } + MainWindow mainWindow1 = this; + type1 = (this.ViewModel.Restricao(35) ? typeof(ConsultaOriginalView) : typeof(FinanceiroView)); + mainWindow1.SetControl(type1, null); + goto Label0; + } + } + Label1: + this.SetControl(typeof(ConsultaOriginalView), null); + Label0: + MainViewModel viewModel = this.ViewModel; + visibility = (Recursos.Usuario.get_Administrador() ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + viewModel.VisibleChaveInstalacao = visibility; + this.GerarQrCode(); + if (Recursos.Usuario.get_IdEmpresa() > (long)1) + { + this.Comissao.Visibility = System.Windows.Visibility.Collapsed; + this.FinanceiroMenu.Visibility = System.Windows.Visibility.Collapsed; + this.FechamentoFinanceiro.Visibility = System.Windows.Visibility.Collapsed; + this.ExtratoConta.Visibility = System.Windows.Visibility.Collapsed; + } + MainViewModel mainViewModel = this.ViewModel; + List vendedorUsuarios = await this.ViewModel.VerificaVinculoVendedor(Recursos.Usuario); + mainViewModel.VendedorUsuario = vendedorUsuarios; + mainViewModel = null; + await this.ViewModel.ShowDialogAdvertising(false); + } + } + + private async void Contratos_OnClick(object sender, RoutedEventArgs e) + { + if (!this.ViewModel.Restricao(56)) + { + this.AbrirAtendimento(); + } + else + { + await this.ViewModel.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA CONTRATOS.", "OK", "", false); + } + } + + private void CopiarChave_OnClick(object sender, RoutedEventArgs e) + { + if (string.IsNullOrEmpty(ApplicationHelper.NumeroSerial)) + { + return; + } + string numeroSerial = ApplicationHelper.NumeroSerial; + DateTime networkTime = Funcoes.GetNetworkTime(); + EncryptionHelper.Encrypt(string.Format("{0} {1:d}", numeroSerial, networkTime.Date)).CopyToClipboard(); + this.ViewModel.ToggleSnackBar("CHAVE DE INSTALAÇÃO COPIADA!", true); + } + + private void CopiarDocumento_Click(object sender, MouseButtonEventArgs e) + { + object text; + try + { + System.Windows.Controls.TextBox textBox = (System.Windows.Controls.TextBox)sender; + if (textBox != null) + { + text = textBox.Text; + } + else + { + text = null; + } + if (text == null) + { + text = string.Empty; + } + string str = (string)text; + if (!Gestor.Common.Validation.ValidationHelper.IsNullOrEmpty(str)) + { + str.CopyToClipboard(); + e.Handled = true; + this.ViewModel.ToggleSnackBar(string.Concat("COPIADO - ", str), true); + } + } + catch (Exception exception) + { + } + } + + private void CopyCode_Click(object sender, RoutedEventArgs e) + { + this.ViewModel.Code.CopyToClipboard(); + this.ViewModel.ToggleSnackBar(string.Concat("CÓDIGO COPIADO - ", this.ViewModel.Code), true); + } + + private void CopyLink_OnClick(object sender, RoutedEventArgs e) + { + System.Windows.Controls.Button button = (System.Windows.Controls.Button)sender; + if (button == null || button.DataContext == null) + { + return; + } + AjudaTela dataContext = (AjudaTela)button.DataContext; + string str = ""; + if (dataContext.get_Minuto() > 0 || dataContext.get_Segundo() > 0) + { + str = string.Format("&start={0}", dataContext.get_Minuto() * 60 + dataContext.get_Segundo()); + } + string.Concat(dataContext.get_Link(), str).CopyToClipboard(); + this.ViewModel.ToggleSnackBar("LINK COPIADO", true); + } + + private void CopyTelefoneToClipBoard_Click(object sender, RoutedEventArgs e) + { + System.Windows.Controls.Button button = (System.Windows.Controls.Button)sender; + if (button.DataContext != null) + { + Contato dataContext = button.DataContext as Contato; + if (dataContext != null) + { + dataContext.get_Numero().CopyToClipboard(); + this.ViewModel.ToggleSnackBar(string.Concat("COPIADO - ", dataContext.get_Numero()), true); + return; + } + } + } + + private void CriticaPdf_OnClick(object sender, RoutedEventArgs e) + { + this.SetControl(typeof(CriticaApoliceView), null); + } + + private void DashBoard_OnClick(object sender, RoutedEventArgs e) + { + this.SetControl(typeof(DashboardView), null); + } + + private void DefinirNomeTela(string tela) + { + this.ViewModel.Tela = tela; + } + + private void DocumentoPrincipal_MouseDoubleClick(object sender, MouseButtonEventArgs e) + { + try + { + ((System.Windows.Controls.TextBox)e.Source).SelectAll(); + } + catch + { + } + } + + private void Emails_OnClick(object sender, RoutedEventArgs e) + { + this.SetControl(typeof(CadastroEmailView), null); + } + + private void Empresa_OnClick(object sender, RoutedEventArgs e) + { + this.SetControl(typeof(EmpresaView), null); + } + + private void Epic_OnClick(object sender, RoutedEventArgs e) + { + Parameters parameter = new Parameters(); + parameter.set_Beta(false); + parameter.set_Type(5); + parameter.set_Application("Agger.Epic.exe"); + parameter.set_Directory("Agger.Epic"); + parameter.set_Arguments(string.Format("{0}|{1}", ApplicationHelper.NumeroSerial, Recursos.Usuario.get_Id())); + parameter.set_Run(true); + (new DownloadWindow(parameter)).Show(); + } + + private void Estipulantes_OnClick(object sender, RoutedEventArgs e) + { + this.SetControl(typeof(EstipulanteView), null); + } + + private void ExpandirMenu() + { + this.MainMenu.set_IsOpen(true); + this.CentralDeNegociosMenu.set_ContentVisible(System.Windows.Visibility.Visible); + this.SegurosMenu.set_ContentVisible(System.Windows.Visibility.Visible); + this.FerramentasMenu.set_ContentVisible(System.Windows.Visibility.Visible); + this.FinanceiroMenu.set_ContentVisible(System.Windows.Visibility.Visible); + } + + private async void ExtratoConta_OnClick(object sender, RoutedEventArgs e) + { + if (Recursos.Usuario.get_IdEmpresa() <= (long)1) + { + (new ExtratoWindow((long)0)).Show(); + } + else + { + await this.ViewModel.ShowMessage("SOMENTE A MATRIZ POSSUI ACESSO AO FINANCEIRO.", "OK", "", false); + } + } + + private async void FechamentoFinanceiro_OnClick(object sender, RoutedEventArgs e) + { + if (Recursos.Usuario.get_IdEmpresa() <= (long)1) + { + string str = string.Format("VOCÊ ESTÁ EM FECHAMENTO FINANCEIRO | VERSÃO GESTOR {0}", ApplicationHelper.Versao); + FechamentoFinanceiroView fechamentoFinanceiroView = new FechamentoFinanceiroView(); + string[] nome = new string[] { "OLÁ, ", Recursos.Usuario.get_Nome(), " - ", Recursos.Empresa.get_Nome(), ", ", str }; + (new HosterWindow(fechamentoFinanceiroView, string.Concat(nome), new double?((double)1024), new double?((double)600), true)).Show(); + } + else + { + await this.ViewModel.ShowMessage("SOMENTE A MATRIZ POSSUI ACESSO AO FINANCEIRO.", "OK", "", false); + } + } + + private void Fechar_OnClick(object sender, RoutedEventArgs e) + { + this.HelpPopup.set_IsPopupOpen(!this.HelpPopup.get_IsPopupOpen()); + } + + private async void FinanceiroMenu_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + if (Recursos.Usuario.get_IdEmpresa() <= (long)1) + { + flag = (!this.MainMenu.get_IsOpen() || this.ViewModel.Content != null ? this.ViewModel.Content.GetType() != typeof(FinanceiroView) : true); + this.SetControl(typeof(FinanceiroView), null); + if (flag) + { + ((HamburgerMenuItem)sender).set_ContentVisible(System.Windows.Visibility.Visible); + } + } + else + { + await this.ViewModel.ShowMessage("SOMENTE A MATRIZ POSSUI ACESSO AO FINANCEIRO.", "OK", "", false); + } + } + + private async void Fornecedor_OnClick(object sender, RoutedEventArgs e) + { + if (Recursos.Usuario.get_IdEmpresa() <= (long)1) + { + this.SetControl(typeof(FornecedorView), null); + } + else + { + await this.ViewModel.ShowMessage("SOMENTE A MATRIZ POSSUI ACESSO AO FINANCEIRO.", "OK", "", false); + } + } + + private async void GerarQrCode() + { + BitmapImage bitmapImage; + int num = 0; + try + { + QRCodeGenerator qRCodeGenerator = new QRCodeGenerator(); + Usuario usuario = await (new UsuarioServico()).BuscarUsuarioPorId(Recursos.Usuario.get_Id()); + if (usuario != null) + { + MainViewModel viewModel = this.ViewModel; + object[] numeroSerial = new object[] { ApplicationHelper.NumeroSerial, usuario.get_IdEmpresa(), usuario.get_Login(), (new Token()).AggerDecrypt(usuario.get_Senha()) }; + viewModel.Code = EncryptionHelper.Encrypt(string.Format("{0}:{1}:{2}:{3}", numeroSerial)); + Bitmap graphic = (new QRCode(qRCodeGenerator.CreateQrCode(this.ViewModel.Code, 2, false, false, 0, -1))).GetGraphic(20); + using (MemoryStream memoryStream = new MemoryStream()) + { + graphic.Save(memoryStream, ImageFormat.Png); + memoryStream.Position = (long)0; + bitmapImage = new BitmapImage(); + bitmapImage.BeginInit(); + bitmapImage.StreamSource = memoryStream; + bitmapImage.CacheOption = BitmapCacheOption.OnLoad; + bitmapImage.EndInit(); + } + this.ViewModel.QrCode = bitmapImage; + this.QrCode.Visibility = System.Windows.Visibility.Visible; + MainViewModel mainViewModel = this.ViewModel; + string str = ApplicationHelper.NumeroSerial; + if (str == null) + { + str = ""; + } + mainViewModel.Code = str; + qRCodeGenerator = null; + } + else + { + this.QrCode.Visibility = System.Windows.Visibility.Collapsed; + return; + } + } + catch (Exception exception) + { + num = 1; + } + if (num == 1) + { + await this.ViewModel.ShowMessage("ERRO AO GERAR QRCODE", "OK", "", false); + } + } + + [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false)] + private static extern bool GetCursorPos(out MainWindow.Point lpPoint); + + [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false)] + private static extern bool GetMonitorInfo(IntPtr hMonitor, MainWindow.Monitorinfo lpmi); + + private void HabilitarMenu(bool enable) + { + this.MainMenu.IsEnabled = enable; + this.Voltar.IsEnabled = enable; + } + + private void HabilitarPesquisarClientes(bool enable) + { + if (!(this.ViewModel.Content is ConsultaOriginalView) && !(this.ViewModel.Content is ClienteView)) + { + return; + } + this.ViewModel.EnableSeguros = enable; + } + + private async void HelpPopup_Opened(object sender, RoutedEventArgs e) + { + await this.ViewModel.CarregarAjuda(); + } + + private void ImageAppStore_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e) + { + Process.Start(new ProcessStartInfo("https://apps.apple.com/br/app/agger-mobile/id1463091598")); + } + + private void ImageGooglePlay_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e) + { + Process.Start(new ProcessStartInfo("https://play.google.com/store/apps/details?id=br.com.aggermobile&hl=pt&gl=US")); + } + + private async void ImportPdf_OnClick(object sender, RoutedEventArgs e) + { + Parameters parameter = new Parameters(); + parameter.set_Beta(false); + parameter.set_Type(4); + parameter.set_Application("Agger.ImportPDF.exe"); + parameter.set_Directory("Agger.Import"); + object[] id = new object[] { Recursos.Empresa.get_Id(), Recursos.Usuario.get_Id(), ApplicationHelper.Subkey, ApplicationHelper.NumeroSerial }; + parameter.set_Arguments(string.Format("{0} {1} NOVOGESTOR PERFIL:{2} SERIAL:{3}", id)); + parameter.set_Run(true); + Parameters parameter1 = parameter; + await (new ArquivoDigitalServico()).Criar(); + (new DownloadWindow(parameter1)).Show(); + parameter1 = null; + } + + private void IniciarAggilizador() + { + long id; + StringBuilder stringBuilder = new StringBuilder(); + StringBuilder stringBuilder1 = new StringBuilder(); + Parameters parameter = new Parameters(); + parameter.set_Beta(false); + parameter.set_Type(4); + parameter.set_Application("Agger.ImportPDF.exe"); + parameter.set_Directory("Agger.Import"); + parameter.set_Arguments(string.Format("{0} {1} NOVOGESTOR", Recursos.Empresa.get_Id(), Recursos.Usuario.get_Id())); + parameter.set_Run(false); + (new DownloadWindow(parameter)).Show(); + Token token = new Token(); + long id1 = Recursos.Usuario.get_Id(); + if (id1 == 0) + { + Usuario usuario = Recursos.Usuarios.FirstOrDefault((Usuario x) => { + long? permissaoAggilizador = x.get_PermissaoAggilizador(); + long num = (long)1; + return permissaoAggilizador.GetValueOrDefault() == num & permissaoAggilizador.HasValue; + }); + if (usuario != null) + { + id = usuario.get_Id(); + } + else + { + id = (long)0; + } + id1 = id; + } + stringBuilder.Append(token.AggerEncrypt(id1.ToString())); + if (Recursos.Usuario.get_Id() != 0) + { + stringBuilder1.Append(token.AggerEncrypt(Recursos.Usuario.get_TokenSso())); + } + Parameters parameter1 = new Parameters(); + parameter1.set_Beta(false); + parameter1.set_Type(88); + parameter1.set_Application("Instalador.exe"); + parameter1.set_Directory(""); + parameter1.set_Arguments(string.Format("/CALCULATION {0} {1}", stringBuilder, (Recursos.Usuario.get_Id() == 0 ? "" : string.Format(" /SSO {0}", stringBuilder1)))); + parameter1.set_Run(true); + Parameters parameter2 = parameter1; + (new RegistryHelper("")).Write("NSP", EncryptionHelper.Encrypt(ApplicationHelper.NumeroSerial), true); + try + { + (new DownloadWindow(parameter2)).Show(); + } + catch (Exception exception) + { + } + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/mainwindow.xaml", UriKind.Relative)); + } + + private async void Instalacao_OnClick(object sender, RoutedEventArgs e) + { + if (!this.ViewModel.Restricao(57)) + { + this.AbrirAtendimento(); + } + else + { + await this.ViewModel.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA INSTALAÇÕES.", "OK", "", false); + } + } + + private void Itens_OnClick(object sender, RoutedEventArgs e) + { + if (MainViewModel.ClienteSelecionado == null) + { + return; + } + this.SetControl(typeof(MenuItensView), this.ManutencaoItem); + } + + private async void MainWindow_OnInitialized(object sender, EventArgs e) + { + WindowInteropHelper windowInteropHelper = new WindowInteropHelper(this); + windowInteropHelper.EnsureHandle(); + HwndSource hwndSource = HwndSource.FromHwnd(windowInteropHelper.Handle); + if (hwndSource != null) + { + hwndSource.AddHook(new HwndSourceHook(this.WindowProc)); + } + else + { + } + this.ExpandirMenu(); + await (new BaseServico()).Sincronizar(Funcoes.GetNetworkTime(), null); + if (Recursos.Usuario.get_Administrador()) + { + MainViewModel viewModel = this.ViewModel; + List payments = await Gestor.Application.Helpers.Connection.Get>(string.Format("Billet/{0}", ApplicationHelper.IdFornecedor), true, false); + viewModel.Boletos = payments; + viewModel = null; + if (this.ViewModel.Boletos != null) + { + List boletos = this.ViewModel.Boletos; + if (boletos.Any((Payment x) => x.get_Vencimento() <= Funcoes.GetNetworkTime().Date.AddDays(7))) + { + this.BoletoPopup.Visibility = System.Windows.Visibility.Visible; + } + } + } + } + + private void MainWindow_OnSizeChanged(object sender, SizeChangedEventArgs e) + { + this.ViewModel.HeadMaxWidth = 300 + base.ActualWidth - 1024; + } + + private void Manutencao_OnClick(object sender, RoutedEventArgs e) + { + this.SetControl(typeof(ManutencaoPagamentosView), null); + } + + public void MaximizeButton_Click() + { + base.WindowState = (base.WindowState == System.Windows.WindowState.Normal ? System.Windows.WindowState.Maximized : System.Windows.WindowState.Normal); + } + + private void Medalha_OnMouseDown(object sender, MouseButtonEventArgs e) + { + this.ViewModel.Medalha(); + } + + private void MenuGestorMobile_OnClick(object sender, RoutedEventArgs e) + { + this.QrCode.Visibility = (this.QrCode.Visibility == System.Windows.Visibility.Visible ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible); + this.QrCode.set_IsPopupOpen(!this.QrCode.get_IsPopupOpen()); + } + + public void MinimizeButton_Click() + { + base.WindowState = System.Windows.WindowState.Minimized; + } + + [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false, SetLastError=true)] + private static extern IntPtr MonitorFromPoint(MainWindow.Point pt, MainWindow.MonitorOptions dwFlags); + + private void NotaFiscal_OnClick(object sender, RoutedEventArgs e) + { + this.SetControl(typeof(NotaFiscalView), null); + } + + private void Notas_OnClick(object sender, RoutedEventArgs e) + { + string str = string.Format("VOCÊ ESTÁ EM CADASTRO DE NOTAS | VERSÃO GESTOR {0}", ApplicationHelper.Versao); + NotasView notasView = new NotasView(); + string[] nome = new string[] { "OLÁ, ", Recursos.Usuario.get_Nome(), " - ", Recursos.Empresa.get_Nome(), ", ", str }; + double? nullable = null; + double? nullable1 = nullable; + nullable = null; + (new HosterWindow(notasView, string.Concat(nome), nullable1, nullable, false)).Show(); + } + + private void Observacoes_OnClick(object sender, RoutedEventArgs e) + { + if (this.ViewModel.SelectedCliente == null || this.ViewModel.SelectedCliente.get_Id() == 0) + { + return; + } + this.ViewModel.ShowDrawer(new ObservacoesDrawer(this.ViewModel.SelectedCliente.get_Id(), 1), 0, true); + } + + private void OcultarAjuda_OnClick(object sender, RoutedEventArgs e) + { + this.HelpPopup.Visibility = System.Windows.Visibility.Collapsed; + } + + private void OcultarBoleto_OnClick(object sender, RoutedEventArgs e) + { + this.BoletoPopup.Visibility = System.Windows.Visibility.Collapsed; + } + + private void OcultarTarefas_OnClick(object sender, RoutedEventArgs e) + { + this.TarefaPopup.Visibility = System.Windows.Visibility.Collapsed; + } + + protected sealed override void OnStateChanged(EventArgs e) + { + object obj; + base.BorderThickness = new Thickness((double)(base.WindowState != System.Windows.WindowState.Maximized)); + System.Windows.Shell.WindowChrome windowChrome = this.WindowChrome; + if (base.WindowState == System.Windows.WindowState.Maximized) + { + obj = null; + } + else + { + obj = 4; + } + windowChrome.ResizeBorderThickness = new Thickness((double)obj); + this.WindowChrome.CaptionHeight = (double)((base.WindowState == System.Windows.WindowState.Maximized ? 32 : 29)); + this.ViewModel.MaximizeRestore = (base.WindowState == System.Windows.WindowState.Maximized ? Geometry.Parse((string)System.Windows.Application.Current.Resources["Restore"]) : Geometry.Parse((string)System.Windows.Application.Current.Resources["Maximize"])); + base.OnStateChanged(e); + } + + private void PainelBi_OnClick(object sender, RoutedEventArgs e) + { + this.SetControl(typeof(PainelBiView), null); + this.ViewModel.VisibleBi = System.Windows.Visibility.Visible; + } + + private void Parceiro_OnClick(object sender, RoutedEventArgs e) + { + this.SetControl(typeof(CadastroParceiroView), null); + } + + private async void PesquisaAvancada_OnClick(object sender, RoutedEventArgs e) + { + Gestor.Model.Domain.Common.PesquisaAvancada pesquisaAvancada = await this.ViewModel.ShowPesquisaAvancadaDialog(); + if (pesquisaAvancada != null) + { + this.ViewModel.Invoke = false; + this.ViewModel.SelectedCliente = null; + this.ViewModel.SelectedStatus = pesquisaAvancada.get_Status(); + this.ViewModel.PesquisaAvançada = true; + Cliente cliente = await (new ClienteServico()).BuscarCliente(pesquisaAvancada.get_IdCliente()); + this.ViewModel.ClientesFiltrados = new List() + { + cliente + }; + this.ViewModel.SelectedCliente = cliente; + this.ViewModel.PesquisaAvançada = false; + MainViewModel.ClienteSelecionado = this.ViewModel.SelectedCliente; + this.ViewModel.Pesquisa = this.ViewModel.SelectedCliente.get_NomeSocial(); + this.ViewModel.Invoke = true; + ((ConsultaOriginalView)this.ViewModel.Content).Pesquisar(pesquisaAvancada); + } + pesquisaAvancada = null; + } + + private void PesquisaCliente_MouseDoubleClick(object sender, MouseButtonEventArgs e) + { + System.Windows.Controls.TextBox textBox = this._textBox; + if (textBox == null) + { + return; + } + textBox.SelectAll(); + } + + private void PesquisaCliente_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e) + { + if (e.Key == Key.Space && this.lastKey.HasValue && this.lastKey.Value == e.Key) + { + e.Handled = true; + } + this.lastKey = new Key?(e.Key); + if (e.OriginalSource.GetType() == typeof(System.Windows.Controls.TextBox)) + { + this._textBox = (System.Windows.Controls.TextBox)e.OriginalSource; + } + } + + private async void PesquisaCliente_SelectionChanged(object sender, SelectionChangedEventArgs e) + { + if (this.ViewModel.SelectedCliente == null) + { + this._lastCustomer = null; + this.ViewModel.LimparDocumentos(); + } + else if (this._lastCustomer == null || this.ViewModel.Content is ClienteView) + { + this._lastCustomer = this.ViewModel.SelectedCliente; + await this.ViewModel.SelecionarCliente(this.ViewModel.SelectedCliente); + if (this.ViewModel.Content is DashboardView) + { + this.ViewModel.Content = new ConsultaOriginalView(this.ViewModel.ConsultaViewModel); + } + } + else + { + Cliente cliente = this._lastCustomer as Cliente; + this.ViewModel.SelectedCliente = cliente; + if (this.ViewModel.Content is DashboardView) + { + this.ViewModel.Content = new ConsultaOriginalView(this.ViewModel.ConsultaViewModel); + } + } + } + + private async void Plano_OnClick(object sender, RoutedEventArgs e) + { + if (Recursos.Usuario.get_IdEmpresa() <= (long)1) + { + this.SetControl(typeof(PlanosView), null); + } + else + { + await this.ViewModel.ShowMessage("SOMENTE A MATRIZ POSSUI ACESSO AO FINANCEIRO.", "OK", "", false); + } + } + + private void Play_Click(object sender, RoutedEventArgs e) + { + System.Windows.Controls.Button button = (System.Windows.Controls.Button)sender; + if (button == null || button.DataContext == null) + { + return; + } + AjudaTela dataContext = (AjudaTela)button.DataContext; + string str = ""; + if (dataContext.get_Minuto() > 0 || dataContext.get_Segundo() > 0) + { + str = string.Format("&start={0}", dataContext.get_Minuto() * 60 + dataContext.get_Segundo()); + } + Process.Start(string.Concat(dataContext.get_Link(), str)); + } + + private async Task PostMonitor(string tela) + { + try + { + if (!Gestor.Common.Validation.ValidationHelper.IsNullOrEmpty(tela)) + { + using (HttpClient httpClient = new HttpClient()) + { + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + httpClient.set_Timeout(TimeSpan.FromSeconds(10)); + TipoTela enumFromEntity = Gestor.Common.Validation.ValidationHelper.GetEnumFromEntity(tela); + object idFornecedor = ApplicationHelper.IdFornecedor; + object obj = (int)enumFromEntity; + DateTime universalTime = Funcoes.GetNetworkTime().ToUniversalTime(); + string str = string.Format("{0}:{1}:{2}", idFornecedor, obj, universalTime.Ticks).EncodeBase64(); + Uri apiMonitor = Address.get_ApiMonitor(); + string[] strArrays = new string[] { "screen" }; + Uri uri = apiMonitor.Append(strArrays).AddQuery("screenQuery", str); + await httpClient.GetAsync(uri); + } + httpClient = null; + } + else + { + return; + } + } + catch + { + } + } + + private void Produtos_OnClick(object sender, RoutedEventArgs e) + { + this.SetControl(typeof(ProdutoView), null); + } + + private void Prospeccao_OnClick(object sender, RoutedEventArgs e) + { + this.SetControl(typeof(ProspeccaoView), null); + } + + private void Protocolos_OnClick(object sender, RoutedEventArgs e) + { + this.SetControl(typeof(ProtocoloDocumentosView), null); + } + + private void Qualificacao_OnClick(object sender, RoutedEventArgs e) + { + this.SetControl(typeof(QualificacaoView), null); + } + + private void Ramos_OnClick(object sender, RoutedEventArgs e) + { + this.SetControl(typeof(RamoView), null); + } + + private void Recibo_OnClick(object sender, RoutedEventArgs e) + { + this.SetControl(typeof(ReciboView), null); + } + + private void Relatorios_OnClick(object sender, RoutedEventArgs e) + { + string str = "DOCUMENTO"; + string name = ((HamburgerMenuItem)sender).Name; + if (name != null) + { + switch (name.Length) + { + case 14: + { + if (name == "RelatoriosLogs") + { + str = "LOGS"; + break; + } + else + { + break; + } + } + case 15: + { + if (name == "RelatoriosNotas") + { + str = "NOTA FISCAL"; + break; + } + else + { + break; + } + } + case 17: + { + char chr = name[10]; + if (chr == 'C') + { + if (name == "RelatoriosCliente") + { + str = "CLIENTE"; + break; + } + else + { + break; + } + } + else if (chr == 'E') + { + if (name == "RelatoriosExtrato") + { + str = "EXTRATO"; + break; + } + else + { + break; + } + } + else if (chr != 'T') + { + break; + } + else if (name == "RelatoriosTarefas") + { + str = "TAREFA"; + break; + } + else + { + break; + } + } + case 18: + { + if (name == "RelatoriosParcelas") + { + str = "PARCELA"; + break; + } + else + { + break; + } + } + case 19: + { + if (name == "RelatoriosSinistros") + { + str = "SINISTRO"; + break; + } + else + { + break; + } + } + case 20: + { + if (name == "RelatoriosFechamento") + { + str = "FECHAMENTO"; + break; + } + else + { + break; + } + } + } + } + string str1 = string.Format("VOCÊ ESTÁ EM RELATÓRIOS | VERSÃO GESTOR {0}", ApplicationHelper.Versao); + (new HosterWindow(new RelatorioView(str), string.Concat(new string[] { "OLÁ, ", Recursos.Usuario.get_Nome(), " - ", Recursos.Empresa.get_Nome(), ", ", str1 }), new double?((double)1024), new double?((double)600), true)).Show(); + } + + private void Seguradoras_OnClick(object sender, RoutedEventArgs e) + { + this.SetControl(typeof(SeguradoraView), null); + } + + private void SetControl(Type tipo, object arguments = null) + { + System.Windows.Controls.UserControl apoliceView; + char chr; + bool? nullable; + string str; + IDisposable dataContext; + bool valueOrDefault; + bool? dashboard; + Task task; + IDisposable disposable; + Gestor.Application.Actions.Actions.AtualizaBadges(); + if (this.ViewModel.Content != null && this.ViewModel.Content.GetType() == tipo) + { + return; + } + this.lastSearch = null; + MainViewModel.ViewAberta = tipo.Name; + this.ViewModel.VisibleSeguros = System.Windows.Visibility.Collapsed; + this.ViewModel.VisibilityVoltar = System.Windows.Visibility.Collapsed; + this.ViewModel.EnableBuscar = false; + this.ViewModel.EnableSeguros = false; + string name = tipo.Name; + if (name != null) + { + int length = name.Length; + switch (length) + { + case 11: + { + chr = name[0]; + if (chr == 'A') + { + if (name == "ApoliceView") + { + apoliceView = new ApoliceView(ConsultaViewModel.DocumentoSelecionado, false, true, this.Acesso, (long)0, false); + this.ViewModel.VisibilityVoltar = System.Windows.Visibility.Visible; + this.ViewModel.VisibleSeguros = System.Windows.Visibility.Visible; + this.ViewModel.EnableBuscar = false; + this.ViewModel.EnableSeguros = false; + this.ShowHelp(tipo.Name); + str = (apoliceView.Tag == null ? "" : apoliceView.Tag.ToString()); + this.DefinirNomeTela(str); + task = this.PostMonitor(tipo.Name); + dataContext = this.ContentControl.DataContext as IDisposable; + if (dataContext != null) + { + dataContext.Dispose(); + } + else + { + disposable = dataContext; + } + this.ViewModel.Content = apoliceView; + return; + } + else + { + break; + } + } + else if (chr != 'C') + { + break; + } + else if (name == "ClienteView") + { + this.ViewModel.ClienteViewModel = new ClienteViewModel(null, true); + apoliceView = new ClienteView(this.ViewModel.SelectedCliente, false, this.ViewModel.ClienteViewModel); + this.ViewModel.VisibilityVoltar = System.Windows.Visibility.Visible; + this.ViewModel.VisibleSeguros = System.Windows.Visibility.Visible; + this.ViewModel.EnableBuscar = false; + this.ViewModel.EnableSeguros = true; + this.ShowHelp(tipo.Name); + str = (apoliceView.Tag == null ? "" : apoliceView.Tag.ToString()); + this.DefinirNomeTela(str); + task = this.PostMonitor(tipo.Name); + dataContext = this.ContentControl.DataContext as IDisposable; + if (dataContext != null) + { + dataContext.Dispose(); + } + else + { + disposable = dataContext; + } + this.ViewModel.Content = apoliceView; + return; + } + else + { + break; + } + } + case 12: + { + if (name != "SinistroView") + { + break; + } + apoliceView = new SinistroView(null, true); + this.ViewModel.VisibilityVoltar = System.Windows.Visibility.Visible; + this.ViewModel.VisibleSeguros = System.Windows.Visibility.Visible; + this.ViewModel.EnableBuscar = false; + this.ViewModel.EnableSeguros = false; + this.ShowHelp(tipo.Name); + str = (apoliceView.Tag == null ? "" : apoliceView.Tag.ToString()); + this.DefinirNomeTela(str); + task = this.PostMonitor(tipo.Name); + dataContext = this.ContentControl.DataContext as IDisposable; + if (dataContext != null) + { + dataContext.Dispose(); + } + else + { + disposable = dataContext; + } + this.ViewModel.Content = apoliceView; + return; + } + case 13: + { + chr = name[0]; + if (chr == 'D') + { + if (name == "DashboardView") + { + if (this.ViewModel.DashboardViewModel == null) + { + this.ViewModel.DashboardViewModel = new DashboardViewModel(); + } + apoliceView = new DashboardView(this.ViewModel.DashboardViewModel); + this.ShowHelp(tipo.Name); + str = (apoliceView.Tag == null ? "" : apoliceView.Tag.ToString()); + this.DefinirNomeTela(str); + task = this.PostMonitor(tipo.Name); + dataContext = this.ContentControl.DataContext as IDisposable; + if (dataContext != null) + { + dataContext.Dispose(); + } + else + { + disposable = dataContext; + } + this.ViewModel.Content = apoliceView; + return; + } + else + { + break; + } + } + else if (chr != 'M') + { + break; + } + else if (name == "MenuItensView") + { + apoliceView = new MenuItensView(this.ViewModel.SelectedRamo, (Gestor.Model.Common.ManutencaoItem)arguments); + this.ViewModel.VisibilityVoltar = System.Windows.Visibility.Visible; + this.ViewModel.VisibleSeguros = System.Windows.Visibility.Visible; + this.ViewModel.EnableBuscar = false; + this.ViewModel.EnableSeguros = false; + this.ShowHelp(tipo.Name); + str = (apoliceView.Tag == null ? "" : apoliceView.Tag.ToString()); + this.DefinirNomeTela(str); + task = this.PostMonitor(tipo.Name); + dataContext = this.ContentControl.DataContext as IDisposable; + if (dataContext != null) + { + dataContext.Dispose(); + } + else + { + disposable = dataContext; + } + this.ViewModel.Content = apoliceView; + return; + } + else + { + break; + } + } + case 14: + { + if (name == "FinanceiroView") + { + this.ViewModel.FinanceiroView = new FinanceiroView(); + apoliceView = this.ViewModel.FinanceiroView; + this.ShowHelp(tipo.Name); + str = (apoliceView.Tag == null ? "" : apoliceView.Tag.ToString()); + this.DefinirNomeTela(str); + task = this.PostMonitor(tipo.Name); + dataContext = this.ContentControl.DataContext as IDisposable; + if (dataContext != null) + { + dataContext.Dispose(); + } + else + { + disposable = dataContext; + } + this.ViewModel.Content = apoliceView; + return; + } + else + { + break; + } + } + default: + { + if (length != 20) + { + break; + } + chr = name[1]; + if (chr == 'a') + { + if (name == "CadastroParceiroView") + { + apoliceView = new CadastroParceiroView(null); + this.ShowHelp(tipo.Name); + str = (apoliceView.Tag == null ? "" : apoliceView.Tag.ToString()); + this.DefinirNomeTela(str); + task = this.PostMonitor(tipo.Name); + dataContext = this.ContentControl.DataContext as IDisposable; + if (dataContext != null) + { + dataContext.Dispose(); + } + else + { + disposable = dataContext; + } + this.ViewModel.Content = apoliceView; + return; + } + else + { + break; + } + } + else if (chr != 'o') + { + break; + } + else if (name == "ConsultaOriginalView") + { + if (this.ViewModel.ConsultaViewModel != null || this.ViewModel.Restricao(108)) + { + valueOrDefault = false; + } + else + { + Usuario usuario = Recursos.Usuario; + if (usuario != null) + { + dashboard = usuario.get_Dashboard(); + } + else + { + nullable = null; + dashboard = nullable; + } + nullable = dashboard; + valueOrDefault = nullable.GetValueOrDefault(); + } + this.ViewModel.ConsultaViewModel = new ConsultaViewModel(); + if (!valueOrDefault) + { + apoliceView = new ConsultaOriginalView(this.ViewModel.ConsultaViewModel); + } + else + { + this.ViewModel.DashboardViewModel = new DashboardViewModel(); + apoliceView = new DashboardView(this.ViewModel.DashboardViewModel); + } + this.ViewModel.VisibleSeguros = System.Windows.Visibility.Visible; + this.ViewModel.EnableBuscar = true; + this.ViewModel.EnableSeguros = true; + this.ShowHelp(tipo.Name); + str = (apoliceView.Tag == null ? "" : apoliceView.Tag.ToString()); + this.DefinirNomeTela(str); + task = this.PostMonitor(tipo.Name); + dataContext = this.ContentControl.DataContext as IDisposable; + if (dataContext != null) + { + dataContext.Dispose(); + } + else + { + disposable = dataContext; + } + this.ViewModel.Content = apoliceView; + return; + } + else + { + break; + } + } + } + } + apoliceView = (System.Windows.Controls.UserControl)Activator.CreateInstance(tipo); + this.ShowHelp(tipo.Name); + str = (apoliceView.Tag == null ? "" : apoliceView.Tag.ToString()); + this.DefinirNomeTela(str); + task = this.PostMonitor(tipo.Name); + dataContext = this.ContentControl.DataContext as IDisposable; + if (dataContext != null) + { + dataContext.Dispose(); + } + else + { + disposable = dataContext; + } + this.ViewModel.Content = apoliceView; + } + + private async void ShowHelp(string name) + { + bool valueOrDefault; + if (await this.ViewModel.VerificarRestricao(61, true, false)) + { + TipoTela? nullable = Funcoes.ConvertTela(name); + if (!nullable.HasValue) + { + valueOrDefault = false; + } + else + { + TipoTela? nullable1 = nullable; + TipoTela tipoTela = 0; + valueOrDefault = !(nullable1.GetValueOrDefault() == tipoTela & nullable1.HasValue); + } + this.HelpPopup.Visibility = (valueOrDefault ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.ViewModel.TelaAberta = nullable; + } + else + { + this.HelpPopup.Visibility = System.Windows.Visibility.Collapsed; + } + } + + private void Sinistros_OnClick(object sender, RoutedEventArgs e) + { + if (MainViewModel.ClienteSelecionado == null) + { + return; + } + this.SetControl(typeof(SinistroView), null); + } + + private void SnackbarMessage_ActionClick(object sender, RoutedEventArgs e) + { + this.Snackbar.set_IsActive(false); + } + + private void Socio_OnClick(object sender, RoutedEventArgs e) + { + this.SetControl(typeof(SocioView), null); + } + + private void Status_OnClick(object sender, RoutedEventArgs e) + { + this.SetControl(typeof(StatusView), null); + } + + private void StatusProspeccao_OnClick(object sender, RoutedEventArgs e) + { + this.SetControl(typeof(StatusProspeccaoView), null); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((MainWindow)target).Loaded += new RoutedEventHandler(this.Window_Loaded); + ((MainWindow)target).Initialized += new EventHandler(this.MainWindow_OnInitialized); + ((MainWindow)target).SizeChanged += new SizeChangedEventHandler(this.MainWindow_OnSizeChanged); + return; + } + case 2: + { + this.WindowChrome = (System.Windows.Shell.WindowChrome)target; + return; + } + case 3: + { + ((System.Windows.Controls.Button)target).Click += new RoutedEventHandler(this.CartaoVisita_OnClick); + return; + } + case 4: + { + ((System.Windows.Controls.MenuItem)target).Click += new RoutedEventHandler(this.Notas_OnClick); + return; + } + case 5: + { + ((System.Windows.Controls.MenuItem)target).Click += new RoutedEventHandler(this.Tarefas_OnClick); + return; + } + case 6: + { + ((System.Windows.Controls.Button)target).Click += new RoutedEventHandler(this.Agenda_OnClick); + return; + } + case 7: + { + ((System.Windows.Controls.Button)target).Click += new RoutedEventHandler(this.MenuGestorMobile_OnClick); + return; + } + case 8: + { + ((System.Windows.Controls.MenuItem)target).Click += new RoutedEventHandler(this.Atendimentos_OnClick); + return; + } + case 9: + { + ((System.Windows.Controls.MenuItem)target).Click += new RoutedEventHandler(this.BoletosNotas_OnClick); + return; + } + case 10: + { + ((System.Windows.Controls.MenuItem)target).Click += new RoutedEventHandler(this.Contratos_OnClick); + return; + } + case 11: + { + ((System.Windows.Controls.MenuItem)target).Click += new RoutedEventHandler(this.Instalacao_OnClick); + return; + } + case 12: + { + ((System.Windows.Controls.MenuItem)target).Click += new RoutedEventHandler(this.CopiarChave_OnClick); + return; + } + case 13: + { + ((System.Windows.Controls.MenuItem)target).Click += new RoutedEventHandler(this.AcessoRemoto_OnClick); + return; + } + case 14: + { + this.MinimizeButton = (Grid)target; + this.MinimizeButton.MouseLeftButtonDown += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonDown); + this.MinimizeButton.MouseLeftButtonUp += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonUp); + return; + } + case 15: + { + this.MaximizeButton = (Grid)target; + this.MaximizeButton.MouseLeftButtonDown += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonDown); + this.MaximizeButton.MouseLeftButtonUp += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonUp); + return; + } + case 16: + { + this.CloseButton = (Grid)target; + this.CloseButton.MouseLeftButtonDown += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonDown); + this.CloseButton.MouseLeftButtonUp += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonUp); + return; + } + case 17: + { + this.MainMenu = (HamburgerMenu)target; + return; + } + case 18: + { + this.CentralDeNegociosMenu = (HamburgerMenuItem)target; + return; + } + case 19: + { + this.DashBoard = (HamburgerMenuItem)target; + this.DashBoard.add_Click(new RoutedEventHandler(this.DashBoard_OnClick)); + return; + } + case 20: + { + this.PainelBi = (HamburgerMenuItem)target; + this.PainelBi.add_Click(new RoutedEventHandler(this.PainelBi_OnClick)); + return; + } + case 21: + { + this.Prospeccao = (HamburgerMenuItem)target; + this.Prospeccao.add_Click(new RoutedEventHandler(this.Prospeccao_OnClick)); + return; + } + case 22: + { + this.SegurosMenu = (HamburgerMenuItem)target; + this.SegurosMenu.add_DoubleClick(new RoutedEventHandler(this.Consultar_OnClick)); + return; + } + case 23: + { + this.Consulta = (HamburgerMenuItem)target; + this.Consulta.add_Click(new RoutedEventHandler(this.Consultar_OnClick)); + return; + } + case 24: + { + this.Clientes = (HamburgerMenuItem)target; + this.Clientes.add_Click(new RoutedEventHandler(this.Clientes_OnClick)); + return; + } + case 25: + { + this.Apolices = (HamburgerMenuItem)target; + this.Apolices.add_Click(new RoutedEventHandler(this.Apolices_OnClick)); + return; + } + case 26: + { + this.Itens = (HamburgerMenuItem)target; + this.Itens.add_Click(new RoutedEventHandler(this.Itens_OnClick)); + return; + } + case 27: + { + this.Sinistros = (HamburgerMenuItem)target; + this.Sinistros.add_Click(new RoutedEventHandler(this.Sinistros_OnClick)); + return; + } + case 28: + { + this.ImportPdf = (HamburgerMenuItem)target; + this.ImportPdf.add_Click(new RoutedEventHandler(this.ImportPdf_OnClick)); + return; + } + case 29: + { + this.CriticaPdf = (HamburgerMenuItem)target; + this.CriticaPdf.add_Click(new RoutedEventHandler(this.CriticaPdf_OnClick)); + return; + } + case 30: + { + this.Comissao = (HamburgerMenuItem)target; + this.Comissao.add_Click(new RoutedEventHandler(this.Comissao_OnClick)); + return; + } + case 31: + { + this.RelatoriosMenu = (HamburgerMenuItem)target; + return; + } + case 32: + { + this.RelatoriosCliente = (HamburgerMenuItem)target; + this.RelatoriosCliente.add_Click(new RoutedEventHandler(this.Relatorios_OnClick)); + return; + } + case 33: + { + this.RelatoriosDocumentos = (HamburgerMenuItem)target; + this.RelatoriosDocumentos.add_Click(new RoutedEventHandler(this.Relatorios_OnClick)); + return; + } + case 34: + { + this.RelatoriosParcelas = (HamburgerMenuItem)target; + this.RelatoriosParcelas.add_Click(new RoutedEventHandler(this.Relatorios_OnClick)); + return; + } + case 35: + { + this.RelatoriosSinistros = (HamburgerMenuItem)target; + this.RelatoriosSinistros.add_Click(new RoutedEventHandler(this.Relatorios_OnClick)); + return; + } + case 36: + { + this.RelatoriosFechamento = (HamburgerMenuItem)target; + this.RelatoriosFechamento.add_Click(new RoutedEventHandler(this.Relatorios_OnClick)); + return; + } + case 37: + { + this.RelatoriosExtrato = (HamburgerMenuItem)target; + this.RelatoriosExtrato.add_Click(new RoutedEventHandler(this.Relatorios_OnClick)); + return; + } + case 38: + { + this.RelatoriosNotas = (HamburgerMenuItem)target; + this.RelatoriosNotas.add_Click(new RoutedEventHandler(this.Relatorios_OnClick)); + return; + } + case 39: + { + this.RelatoriosTarefas = (HamburgerMenuItem)target; + this.RelatoriosTarefas.add_Click(new RoutedEventHandler(this.Relatorios_OnClick)); + return; + } + case 40: + { + this.RelatoriosLogs = (HamburgerMenuItem)target; + this.RelatoriosLogs.add_Click(new RoutedEventHandler(this.Relatorios_OnClick)); + return; + } + case 41: + { + this.ExtratoConta = (HamburgerMenuItem)target; + this.ExtratoConta.add_Click(new RoutedEventHandler(this.ExtratoConta_OnClick)); + return; + } + case 42: + { + this.FechamentoFinanceiro = (HamburgerMenuItem)target; + this.FechamentoFinanceiro.add_Click(new RoutedEventHandler(this.FechamentoFinanceiro_OnClick)); + return; + } + case 43: + { + this.Assinatura = (HamburgerMenuItem)target; + this.Assinatura.add_Click(new RoutedEventHandler(this.Assinatura_OnClick)); + return; + } + case 44: + { + this.Aggilizador = (HamburgerMenuItem)target; + this.Aggilizador.add_Click(new RoutedEventHandler(this.Aggilizador_OnClick)); + return; + } + case 45: + { + this.Epic = (HamburgerMenuItem)target; + this.Epic.add_Click(new RoutedEventHandler(this.Epic_OnClick)); + return; + } + case 46: + { + this.FinanceiroMenu = (HamburgerMenuItem)target; + this.FinanceiroMenu.add_Click(new RoutedEventHandler(this.FinanceiroMenu_OnClick)); + return; + } + case 47: + { + this.Conta = (HamburgerMenuItem)target; + this.Conta.add_Click(new RoutedEventHandler(this.Conta_OnClick)); + return; + } + case 48: + { + this.Centro = (HamburgerMenuItem)target; + this.Centro.add_Click(new RoutedEventHandler(this.Centro_OnClick)); + return; + } + case 49: + { + this.Fornecedor = (HamburgerMenuItem)target; + this.Fornecedor.add_Click(new RoutedEventHandler(this.Fornecedor_OnClick)); + return; + } + case 50: + { + this.Plano = (HamburgerMenuItem)target; + this.Plano.add_Click(new RoutedEventHandler(this.Plano_OnClick)); + return; + } + case 51: + { + this.FerramentasMenu = (HamburgerMenuItem)target; + return; + } + case 52: + { + this.Emails = (HamburgerMenuItem)target; + this.Emails.add_Click(new RoutedEventHandler(this.Emails_OnClick)); + return; + } + case 53: + { + this.Empresa = (HamburgerMenuItem)target; + this.Empresa.add_Click(new RoutedEventHandler(this.Empresa_OnClick)); + return; + } + case 54: + { + this.Estipulantes = (HamburgerMenuItem)target; + this.Estipulantes.add_Click(new RoutedEventHandler(this.Estipulantes_OnClick)); + return; + } + case 55: + { + this.ManutencaoPagamentos = (HamburgerMenuItem)target; + this.ManutencaoPagamentos.add_Click(new RoutedEventHandler(this.Manutencao_OnClick)); + return; + } + case 56: + { + this.NotaFiscal = (HamburgerMenuItem)target; + this.NotaFiscal.add_Click(new RoutedEventHandler(this.NotaFiscal_OnClick)); + return; + } + case 57: + { + this.Parceiro = (HamburgerMenuItem)target; + this.Parceiro.add_Click(new RoutedEventHandler(this.Parceiro_OnClick)); + return; + } + case 58: + { + this.Produtos = (HamburgerMenuItem)target; + this.Produtos.add_Click(new RoutedEventHandler(this.Produtos_OnClick)); + return; + } + case 59: + { + ((HamburgerMenuItem)target).add_Click(new RoutedEventHandler(this.Protocolos_OnClick)); + return; + } + case 60: + { + this.Qualificacao = (HamburgerMenuItem)target; + this.Qualificacao.add_Click(new RoutedEventHandler(this.Qualificacao_OnClick)); + return; + } + case 61: + { + this.Ramos = (HamburgerMenuItem)target; + this.Ramos.add_Click(new RoutedEventHandler(this.Ramos_OnClick)); + return; + } + case 62: + { + this.Recibo = (HamburgerMenuItem)target; + this.Recibo.add_Click(new RoutedEventHandler(this.Recibo_OnClick)); + return; + } + case 63: + { + this.Seguradoras = (HamburgerMenuItem)target; + this.Seguradoras.add_Click(new RoutedEventHandler(this.Seguradoras_OnClick)); + return; + } + case 64: + { + this.Socio = (HamburgerMenuItem)target; + this.Socio.add_Click(new RoutedEventHandler(this.Socio_OnClick)); + return; + } + case 65: + { + this.Statuses = (HamburgerMenuItem)target; + this.Statuses.add_Click(new RoutedEventHandler(this.Status_OnClick)); + return; + } + case 66: + { + this.StatusProspeccao = (HamburgerMenuItem)target; + this.StatusProspeccao.add_Click(new RoutedEventHandler(this.StatusProspeccao_OnClick)); + return; + } + case 67: + { + this.TipoTarefa = (HamburgerMenuItem)target; + this.TipoTarefa.add_Click(new RoutedEventHandler(this.TipoTarefa_OnClick)); + return; + } + case 68: + { + this.TipoVendedor = (HamburgerMenuItem)target; + this.TipoVendedor.add_Click(new RoutedEventHandler(this.TipoVendedor_OnClick)); + return; + } + case 69: + { + this.Usuarios = (HamburgerMenuItem)target; + this.Usuarios.add_Click(new RoutedEventHandler(this.Usuarios_OnClick)); + return; + } + case 70: + { + this.Vendedores = (HamburgerMenuItem)target; + this.Vendedores.add_Click(new RoutedEventHandler(this.Vendedores_OnClick)); + return; + } + case 71: + { + this.Area = (RowDefinition)target; + return; + } + case 72: + { + this.Status = (System.Windows.Controls.ComboBox)target; + return; + } + case 73: + { + ((PackIcon)target).MouseDown += new MouseButtonEventHandler(this.Medalha_OnMouseDown); + return; + } + case 74: + { + this.FiltroClienteTipoBox = (System.Windows.Controls.ComboBox)target; + return; + } + case 75: + { + this.PesquisaCliente = (AutoCompleteBox)target; + this.PesquisaCliente.add_Populating(new PopulatingEventHandler(this, MainWindow.AutoCompleteBox_Populating)); + this.PesquisaCliente.GotKeyboardFocus += new KeyboardFocusChangedEventHandler(this.AutoCompleteCliente_OnGotKeyboardFocus); + this.PesquisaCliente.add_SelectionChanged(new SelectionChangedEventHandler(this.PesquisaCliente_SelectionChanged)); + this.PesquisaCliente.PreviewKeyDown += new System.Windows.Input.KeyEventHandler(this.PesquisaCliente_PreviewKeyDown); + this.PesquisaCliente.MouseDoubleClick += new MouseButtonEventHandler(this.PesquisaCliente_MouseDoubleClick); + return; + } + case 76: + { + this.PesquisaClienteNome = (AutoCompleteBox)target; + this.PesquisaClienteNome.add_Populating(new PopulatingEventHandler(this, MainWindow.AutoCompleteNomeBox_Populating)); + this.PesquisaClienteNome.GotKeyboardFocus += new KeyboardFocusChangedEventHandler(this.AutoCompleteCliente_OnGotKeyboardFocus); + this.PesquisaClienteNome.add_SelectionChanged(new SelectionChangedEventHandler(this.PesquisaCliente_SelectionChanged)); + this.PesquisaClienteNome.PreviewKeyDown += new System.Windows.Input.KeyEventHandler(this.PesquisaCliente_PreviewKeyDown); + this.PesquisaClienteNome.MouseDoubleClick += new MouseButtonEventHandler(this.PesquisaCliente_MouseDoubleClick); + return; + } + case 77: + { + this.LoadingAutoComplete = (Loading)target; + return; + } + case 78: + { + this.DocumentoPrincipalBox = (System.Windows.Controls.TextBox)target; + this.DocumentoPrincipalBox.MouseDoubleClick += new MouseButtonEventHandler(this.DocumentoPrincipal_MouseDoubleClick); + this.DocumentoPrincipalBox.MouseRightButtonUp += new MouseButtonEventHandler(this.CopiarDocumento_Click); + return; + } + case 79: + { + this.ObservacaoApolice = (System.Windows.Controls.Button)target; + this.ObservacaoApolice.Click += new RoutedEventHandler(this.Observacoes_OnClick); + return; + } + case 80: + { + this.PesquisaAvancada = (System.Windows.Controls.MenuItem)target; + this.PesquisaAvancada.Click += new RoutedEventHandler(this.PesquisaAvancada_OnClick); + return; + } + case 81: + { + this.Voltar = (System.Windows.Controls.MenuItem)target; + this.Voltar.Click += new RoutedEventHandler(this.Voltar_OnClick); + return; + } + case 82: + case 83: + case 94: + case 98: + case 99: + { + this._contentLoaded = true; + return; + } + case 84: + { + this.ContentControl = (System.Windows.Controls.ContentControl)target; + this.ContentControl.GotFocus += new RoutedEventHandler(this.ContentControl_GotFocus); + this.ContentControl.MouseLeftButtonDown += new MouseButtonEventHandler(this.ContentControl_MouseLeftButtonDown); + return; + } + case 85: + { + this.QrCode = (PopupBox)target; + return; + } + case 86: + { + ((System.Windows.Controls.Button)target).Click += new RoutedEventHandler(this.MenuGestorMobile_OnClick); + return; + } + case 87: + { + this.ImageAppStore = (System.Windows.Controls.Image)target; + this.ImageAppStore.MouseLeftButtonUp += new MouseButtonEventHandler(this.ImageAppStore_OnMouseLeftButtonUp); + return; + } + case 88: + { + this.ImageGooglePlay = (System.Windows.Controls.Image)target; + this.ImageGooglePlay.MouseLeftButtonUp += new MouseButtonEventHandler(this.ImageGooglePlay_OnMouseLeftButtonUp); + return; + } + case 89: + { + this.SessionNumber = (TextBlock)target; + return; + } + case 90: + { + ((System.Windows.Controls.Button)target).Click += new RoutedEventHandler(this.CopyCode_Click); + return; + } + case 91: + { + this.BoletoPopup = (PopupBox)target; + return; + } + case 92: + { + ((System.Windows.Controls.Button)target).Click += new RoutedEventHandler(this.OcultarBoleto_OnClick); + return; + } + case 93: + { + ((System.Windows.Controls.Button)target).Click += new RoutedEventHandler(this.Fechar_OnClick); + return; + } + case 95: + { + this.HelpPopup = (PopupBox)target; + this.HelpPopup.add_Opened(new RoutedEventHandler(this.HelpPopup_Opened)); + return; + } + case 96: + { + ((System.Windows.Controls.Button)target).Click += new RoutedEventHandler(this.OcultarAjuda_OnClick); + return; + } + case 97: + { + ((System.Windows.Controls.Button)target).Click += new RoutedEventHandler(this.Fechar_OnClick); + return; + } + case 100: + { + this.TarefaPopup = (StackPanel)target; + return; + } + case 101: + { + ((System.Windows.Controls.Button)target).Click += new RoutedEventHandler(this.Tarefas_OnClick); + return; + } + case 102: + { + ((System.Windows.Controls.Button)target).Click += new RoutedEventHandler(this.OcultarTarefas_OnClick); + return; + } + case 103: + { + this.Snackbar = (MaterialDesignThemes.Wpf.Snackbar)target; + return; + } + case 104: + { + ((SnackbarMessage)target).add_ActionClick(new RoutedEventHandler(this.SnackbarMessage_ActionClick)); + return; + } + case 105: + { + this.ProgressRing = (Grid)target; + return; + } + case 106: + { + this.DrawerHost = (MaterialDesignThemes.Wpf.DrawerHost)target; + return; + } + default: + { + this._contentLoaded = true; + return; + } + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + if (connectionId <= 83) + { + if (connectionId == 82) + { + ((System.Windows.Controls.Button)target).Click += new RoutedEventHandler(this.CopyTelefoneToClipBoard_Click); + return; + } + if (connectionId != 83) + { + return; + } + ((System.Windows.Controls.Button)target).Click += new RoutedEventHandler(this.WhatsAppMessage_Click); + return; + } + if (connectionId == 94) + { + ((System.Windows.Controls.Button)target).Click += new RoutedEventHandler(this.Boleto_OnClick); + return; + } + if (connectionId == 98) + { + ((System.Windows.Controls.Button)target).Click += new RoutedEventHandler(this.CopyLink_OnClick); + return; + } + if (connectionId != 99) + { + return; + } + ((System.Windows.Controls.Button)target).Click += new RoutedEventHandler(this.Play_Click); + } + + private async void Tarefas_OnClick(object sender, RoutedEventArgs e) + { + if (await this.ViewModel.VerificarPermissao(38, false)) + { + this.ViewModel.MensagemTarefasVisibility = System.Windows.Visibility.Collapsed; + MainWindow.AbrirTarefas(); + } + } + + private void TipoTarefa_OnClick(object sender, RoutedEventArgs e) + { + this.SetControl(typeof(TipoTarefaView), null); + } + + private void TipoVendedor_OnClick(object sender, RoutedEventArgs e) + { + this.SetControl(typeof(TipoVendedorView), null); + } + + private static void TopControls_OnMouseEnter(object sender, System.Windows.Input.MouseEventArgs e) + { + ((Grid)sender).Background = (((Grid)sender).Name == "CloseButton" ? new SolidColorBrush(Colors.IndianRed) : new SolidColorBrush(Colors.Gray)); + System.Windows.Shapes.Path child = VisualTreeHelper.GetChild((Grid)sender, 0) as System.Windows.Shapes.Path; + if (child != null) + { + child.Stroke = new SolidColorBrush(Colors.White); + } + } + + private void TopControls_OnMouseLeave(object sender, System.Windows.Input.MouseEventArgs e) + { + this._buttonClickable = false; + ((Grid)sender).Background = new SolidColorBrush(Colors.Transparent); + System.Windows.Shapes.Path child = VisualTreeHelper.GetChild((Grid)sender, 0) as System.Windows.Shapes.Path; + if (child != null) + { + child.Stroke = new SolidColorBrush(Colors.White); + } + } + + private void TopControls_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e) + { + this._buttonClickable = true; + if (((Grid)sender).Name != "CloseButton") + { + ((Grid)sender).Background = new SolidColorBrush(Colors.DimGray); + } + else + { + ((Grid)sender).Background = new SolidColorBrush(Colors.Red); + System.Windows.Shapes.Path child = VisualTreeHelper.GetChild((Grid)sender, 0) as System.Windows.Shapes.Path; + if (child != null) + { + child.Stroke = new SolidColorBrush(Colors.Black); + return; + } + } + } + + private void TopControls_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e) + { + if (this._buttonClickable) + { + MethodInfo method = base.GetType().GetMethod(string.Concat(((Grid)sender).Name, "_Click")); + if (method == null) + { + return; + } + method.Invoke(this, null); + } + } + + private void Usuarios_OnClick(object sender, RoutedEventArgs e) + { + this.SetControl(typeof(UsuarioView), null); + } + + private void Vendedores_OnClick(object sender, RoutedEventArgs e) + { + this.SetControl(typeof(VendedorView), null); + } + + private async Task VerificarCliente(Gestor.Model.License.Produto? produto, TipoTela? tela) + { + bool flag; + if (MainViewModel.ClienteSelecionado == null || MainViewModel.ClienteSelecionado.get_Id() == 0) + { + flag = false; + } + else + { + flag = await this.VerificarLicenca(produto, tela, null); + } + return flag; + } + + private async Task VerificarComissao(Gestor.Model.License.Produto? produto = null, TipoTela? tela = null, TipoRestricao? restricao = null) + { + bool flag; + if (!tela.HasValue || tela.GetValueOrDefault() != 35 || !this.ViewModel.MatrizFilial || Recursos.Empresa.get_Id() <= (long)1) + { + flag = await this.VerificarLicenca(produto, tela, restricao); + } + else + { + await this.ViewModel.ShowMessage("FILIAL NÃO POSSUI AUTORIZAÇÃO PARA BAIXA DE COMISSÃO AUTOMÁTICA, TODA BAIXA DE COMISSÃO AUTOMÁTICA DEVE SER FEITA PELA MATRIZ.", "OK", "", false); + flag = false; + } + return flag; + } + + private async Task VerificarDocumento(Gestor.Model.License.Produto? produto, TipoTela? tela) + { + bool flag; + if (ConsultaViewModel.DocumentoSelecionado == null || ConsultaViewModel.DocumentoSelecionado.get_Id() == 0) + { + flag = false; + } + else + { + flag = await this.VerificarLicenca(produto, tela, null); + } + return flag; + } + + private async Task VerificarLicenca(Gestor.Model.License.Produto? produto = null, TipoTela? tela = null, TipoRestricao? restricao = null) + { + bool flag; + bool hasValue; + string str = await this.ViewModel.VerificarAcesso(Recursos.Usuario.get_Id()); + if (Recursos.Usuario.get_Id() == 0 || str == null) + { + if (produto.GetValueOrDefault() != 83 || produto.GetValueOrDefault() == 86) + { + hasValue = produto.HasValue; + if (hasValue) + { + hasValue = !await this.ViewModel.VerificarContrato(produto.Value, true, true); + } + if (hasValue) + { + flag = false; + return flag; + } + } + hasValue = restricao.HasValue; + if (hasValue) + { + hasValue = !await this.ViewModel.VerificarRestricao(restricao.Value, true, true); + } + if (!hasValue) + { + hasValue = tela.HasValue; + if (hasValue) + { + hasValue = !await this.ViewModel.VerificarPermissao(tela.Value, true); + } + if (!hasValue) + { + if (tela.GetValueOrDefault() == 58) + { + if (!Recursos.Usuario.get_Administrador() && Recursos.Usuario.get_Id() > (long)0) + { + await this.ViewModel.ShowMessage("VOCÊ PRECISA SER ADMINISTRADOR PARA ACESSAR ESSA TELA.", "OK", "", false); + flag = false; + return flag; + } + else if (await this.ViewModel.VerificaVinculoVendedor(Recursos.Usuario).Count > 0) + { + await this.ViewModel.ShowMessage("PARA ACESSAR ESSA TELA, REMOVA QUALQUER VÍNCULO DE VENDEDOR DO SEU USUÁRIO.", "OK", "", false); + flag = false; + return flag; + } + } + hasValue = restricao.GetValueOrDefault() == 44; + if (hasValue) + { + hasValue = !await this.ViewModel.VerificarPermissao(60, true); + } + flag = (!hasValue ? true : false); + } + else + { + flag = false; + } + } + else + { + flag = false; + } + } + else + { + await this.ViewModel.ShowMessage(string.Concat(str, " O SISTEMA SERÁ ENCERRADO."), "OK", "", false); + Environment.Exit(0); + flag = false; + } + return flag; + } + + private void Voltar_OnClick(object sender, RoutedEventArgs e) + { + this.VoltarAction(); + } + + private void VoltarAction() + { + this.ManutencaoItem = null; + this.Consultar_OnClick(this.SegurosMenu, new RoutedEventArgs()); + } + + private async void WhatsAppMessage_Click(object sender, RoutedEventArgs e) + { + string str; + if (!this.ViewModel.Restricao(32)) + { + bool flag = await this.ViewModel.ShowMessage("DESEJA ENVIAR SEU CARTÃO DE VISITA ELETRÔNICO VIA WHATSAPP?", "SIM", "NÃO", false); + object[] nome = new object[] { this.ViewModel.SelectedCliente.get_Nome(), Environment.NewLine, Environment.NewLine, Address.get_Card(), Recursos.Usuario.get_Id().GeraCartaoVisita() }; + string str1 = string.Format("Prezado {0} abaixo o link para meu Cartão de Visita.{1}{2}{3}{4}", nome); + System.Windows.Controls.Button button = (System.Windows.Controls.Button)sender; + if (button.DataContext != null) + { + Contato dataContext = button.DataContext as Contato; + if (dataContext != null) + { + string str2 = string.Concat("55", dataContext.get_Numero().Clear()); + if (!flag) + { + str = null; + } + else + { + str = str1; + } + if (!str2.EnviarWhatsapp(str)) + { + await this.ViewModel.ShowMessage("HOUVE UM PROBLEMA AO ABRIR LINK DO WHATSAPP, O LINK FOI COPIADO EM SUA MAQUINA, BASTA ABRIR O NAVEGADOR DE INTERNET E COLAR NA BARRA DE ENDEREÇOS", "OK", "", false); + } + return; + } + } + } + else + { + await this.ViewModel.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR O WHATSAPP", "OK", "", false); + } + } + + private void Window_Loaded(object sender, RoutedEventArgs e) + { + EventManager.RegisterClassHandler(typeof(CustomItemValidation), UIElement.LostFocusEvent, new RoutedEventHandler(ViewHelper.ControlLostFocus)); + EventManager.RegisterClassHandler(typeof(CustomIsReadOnlyControl), UIElement.LostFocusEvent, new RoutedEventHandler(ViewHelper.ControlLostFocus)); + this.PipeName = string.Format("GESTORPIPE{0}{1}", ApplicationHelper.NumeroSerial, Recursos.Usuario.get_Id()); + (new PipeServer()).CreateServer(this.PipeName); + } + + private IntPtr WindowProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) + { + if (msg == 36) + { + this.WmGetMinMaxInfo(lParam); + } + return IntPtr.Zero; + } + + private void WmGetMinMaxInfo(IntPtr lParam) + { + MainWindow.Point point; + System.Drawing.Rectangle workingArea = Screen.FromHandle((new WindowInteropHelper(this)).Handle).WorkingArea; + base.MaxHeight = (double)workingArea.Height; + MainWindow.GetCursorPos(out point); + IntPtr intPtr = MainWindow.MonitorFromPoint(new MainWindow.Point(0, 0), MainWindow.MonitorOptions.MonitorDefaulttoprimary); + MainWindow.Monitorinfo monitorinfo = new MainWindow.Monitorinfo(); + if (!MainWindow.GetMonitorInfo(intPtr, monitorinfo)) + { + return; + } + IntPtr intPtr1 = MainWindow.MonitorFromPoint(point, MainWindow.MonitorOptions.MonitorDefaulttonearest); + MainWindow.Minmaxinfo structure = (MainWindow.Minmaxinfo)Marshal.PtrToStructure(lParam, typeof(MainWindow.Minmaxinfo)); + if (!intPtr.Equals(intPtr1)) + { + structure.ptMaxPosition.X = monitorinfo.rcMonitor.Left; + structure.ptMaxPosition.Y = monitorinfo.rcMonitor.Top; + structure.ptMaxSize.X = monitorinfo.rcMonitor.Right - monitorinfo.rcMonitor.Left; + structure.ptMaxSize.Y = monitorinfo.rcMonitor.Bottom - monitorinfo.rcMonitor.Top; + } + else + { + structure.ptMaxPosition.X = monitorinfo.rcWork.Left; + structure.ptMaxPosition.Y = monitorinfo.rcWork.Top; + structure.ptMaxSize.X = monitorinfo.rcWork.Right - monitorinfo.rcWork.Left; + structure.ptMaxSize.Y = monitorinfo.rcWork.Bottom - monitorinfo.rcWork.Top; + } + Marshal.StructureToPtr(structure, lParam, true); + } + + private struct Minmaxinfo + { + private readonly MainWindow.Point ptReserved; + + public MainWindow.Point ptMaxSize; + + public MainWindow.Point ptMaxPosition; + + private readonly MainWindow.Point ptMinTrackSize; + + private readonly MainWindow.Point ptMaxTrackSize; + } + + private class Monitorinfo + { + private readonly int cbSize; + + public readonly MainWindow.Rect rcMonitor; + + public readonly MainWindow.Rect rcWork; + + private readonly int dwFlags; + + public Monitorinfo() + { + } + } + + private enum MonitorOptions : uint + { + MonitorDefaulttoprimary = 1, + MonitorDefaulttonearest = 2 + } + + public struct Point + { + public int X; + + public int Y; + + public Point(int x, int y) + { + this.X = x; + this.Y = y; + } + } + + public struct Rect + { + public int Left; + + public int Top; + + public int Right; + + public int Bottom; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Migration/Migrator.cs b/Codemerx/Gestor.Application/Migration/Migrator.cs new file mode 100644 index 0000000..eab28a3 --- /dev/null +++ b/Codemerx/Gestor.Application/Migration/Migrator.cs @@ -0,0 +1,189 @@ +using Gestor.Application.Helpers; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Helper; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; + +namespace Gestor.Application.Migration +{ + public class Migrator + { + private readonly Assembly _executingAssembly; + + private static string _connection + { + get; + set; + } + + public Migrator() + { + this._executingAssembly = Assembly.GetExecutingAssembly(); + } + + public async Task Execute() + { + bool flag; + try + { + string[] allFiles = await this.GetAllFiles(); + flag = await this.ExecuteFiles(allFiles); + return flag; + } + catch (Exception exception) + { + } + flag = false; + return flag; + } + + private async Task ExecuteFiles(IEnumerable filesToExecute) + { + bool flag; + IEnumerable strs = filesToExecute; + foreach (string str in + from x in strs + orderby x + select x) + { + using (Stream manifestResourceStream = this._executingAssembly.GetManifestResourceStream(str)) + { + if (manifestResourceStream != null) + { + Encoding encoding = Encoding.GetEncoding("ISO-8859-1"); + Encoding uTF8 = Encoding.UTF8; + using (StreamReader streamReader = new StreamReader(manifestResourceStream)) + { + byte[] bytes = uTF8.GetBytes(streamReader.ReadToEnd()); + byte[] numArray = Encoding.Convert(uTF8, encoding, bytes); + if (await Migrator.ExecuteScript(encoding.GetString(numArray))) + { + string str1 = str; + char[] chrArray = new char[] { '\u005F' }; + if (!await Migrator.SaveUpdate((long)ValidationHelper.ToInt(ValidationHelper.Clear(ValidationHelper.Index(str1.Split(chrArray), 1))))) + { + flag = false; + return flag; + } + } + else + { + flag = false; + return flag; + } + } + streamReader = null; + } + else + { + continue; + } + } + manifestResourceStream = null; + } + flag = true; + return flag; + } + + private static async Task ExecuteScript(string scriptText) + { + bool flag1 = await Task.Run(() => { + bool flag; + IEnumerable strs = Regex.Split(scriptText, "^\\s*GO\\s*$", RegexOptions.IgnoreCase | RegexOptions.Multiline); + try + { + if (string.IsNullOrEmpty(Migrator._connection)) + { + Migrator._connection = Connection.GetConnection(true); + } + using (SqlConnection sqlConnection = new SqlConnection(Migrator._connection)) + { + sqlConnection.Open(); + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + foreach (string str in strs) + { + if (str.Trim() == "") + { + continue; + } + sqlCommand.CommandText = str; + sqlCommand.ExecuteNonQuery(); + } + } + } + flag = true; + } + catch (Exception exception) + { + flag = false; + } + return flag; + }); + return flag1; + } + + private async Task GetAllFiles() + { + string str = string.Concat(this._executingAssembly.GetName().Name, ".Migration.Files"); + long num1 = await Migrator.LastUpdate(); + string[] array = this._executingAssembly.GetManifestResourceNames().Where((string r) => { + long num = (long)0; + if (r.StartsWith(str) && r.EndsWith(".SQL")) + { + num = (long)ValidationHelper.ToInt(ValidationHelper.Clear(ValidationHelper.Index(r.Split(new char[] { '\u005F' }), 1))); + } + return num > num1; + }).ToArray(); + return array; + } + + private static async Task LastUpdate() + { + long num1 = await Task.Run(() => { + long num; + using (UnitOfWork commited = Instancia.Commited) + { + num = commited.get_AtualizacaoRepository().FindLastUpdate(); + } + return num; + }); + return num1; + } + + private static async Task SaveUpdate(long fileId) + { + bool flag1 = await Task.Run(() => { + bool flag; + using (UnitOfWork commited = Instancia.Commited) + { + try + { + commited.get_AtualizacaoRepository().Save(fileId); + commited.Commit(); + return true; + } + catch (Exception exception) + { + commited.Rollback(); + flag = false; + } + } + return flag; + }); + return flag1; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Model/Ajuda/Atendimento.cs b/Codemerx/Gestor.Application/Model/Ajuda/Atendimento.cs new file mode 100644 index 0000000..ebfdf09 --- /dev/null +++ b/Codemerx/Gestor.Application/Model/Ajuda/Atendimento.cs @@ -0,0 +1,106 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Application.Model.Ajuda +{ + public class Atendimento + { + private string _solicitante; + + private string _assunto; + + private string _status; + + private string _corpo; + + public DateTime? Abertura + { + get; + set; + } + + public string Assunto + { + get + { + string str = this._assunto; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._assunto = value; + } + } + + public string Corpo + { + get + { + string str = this._corpo; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._corpo = value; + } + } + + public long IdAtendimento + { + get; + set; + } + + public string Solicitante + { + get + { + string str = this._solicitante; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._solicitante = value; + } + } + + public DateTime? Solucao + { + get; + set; + } + + public string Status + { + get + { + string str = this._status; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._status = value; + } + } + + public Atendimento() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Model/Ajuda/Boleto.cs b/Codemerx/Gestor.Application/Model/Ajuda/Boleto.cs new file mode 100644 index 0000000..77e0191 --- /dev/null +++ b/Codemerx/Gestor.Application/Model/Ajuda/Boleto.cs @@ -0,0 +1,48 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Application.Model.Ajuda +{ + public class Boleto + { + public string Historico + { + get; + set; + } + + public long IdBoleto + { + get; + set; + } + + public string Nota + { + get; + set; + } + + public DateTime? Pagamento + { + get; + set; + } + + public decimal Valor + { + get; + set; + } + + public DateTime Vencimento + { + get; + set; + } + + public Boleto() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Model/Ajuda/Contrato.cs b/Codemerx/Gestor.Application/Model/Ajuda/Contrato.cs new file mode 100644 index 0000000..cd99b6d --- /dev/null +++ b/Codemerx/Gestor.Application/Model/Ajuda/Contrato.cs @@ -0,0 +1,24 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Application.Model.Ajuda +{ + public class Contrato + { + public string HtmlContrato + { + get; + set; + } + + public long IdModulo + { + get; + set; + } + + public Contrato() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Model/Ajuda/EmailAtendimento.cs b/Codemerx/Gestor.Application/Model/Ajuda/EmailAtendimento.cs new file mode 100644 index 0000000..813e444 --- /dev/null +++ b/Codemerx/Gestor.Application/Model/Ajuda/EmailAtendimento.cs @@ -0,0 +1,68 @@ +using Gestor.Model.Domain.Common; +using System; +using System.Collections.ObjectModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Application.Model.Ajuda +{ + public class EmailAtendimento + { + public ObservableCollection ArquivosAnexados + { + get; + set; + } + + public string Assunto + { + get; + set; + } + + public string Corpo + { + get; + set; + } + + public string DDD + { + get; + set; + } + + public string EMail + { + get; + set; + } + + public string IDAcesso + { + get; + set; + } + + public string Nome + { + get; + set; + } + + public string SenhaAcesso + { + get; + set; + } + + public string Telefone + { + get; + set; + } + + public EmailAtendimento() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Model/Ajuda/Instalacao.cs b/Codemerx/Gestor.Application/Model/Ajuda/Instalacao.cs new file mode 100644 index 0000000..63ea074 --- /dev/null +++ b/Codemerx/Gestor.Application/Model/Ajuda/Instalacao.cs @@ -0,0 +1,60 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Application.Model.Ajuda +{ + public class Instalacao + { + public DateTime? DataAtualizacaoAggilizador + { + get; + set; + } + + public DateTime? DataIntalacao + { + get; + set; + } + + public long Id + { + get; + set; + } + + public string IdAggilizador + { + get; + set; + } + + public long IdFornecedor + { + get; + set; + } + + public string IdGerenciador + { + get; + set; + } + + public string Maquina + { + get; + set; + } + + public string Usuario + { + get; + set; + } + + public Instalacao() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Model/AnaliticoSource.cs b/Codemerx/Gestor.Application/Model/AnaliticoSource.cs new file mode 100644 index 0000000..bdb6f5d --- /dev/null +++ b/Codemerx/Gestor.Application/Model/AnaliticoSource.cs @@ -0,0 +1,24 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Application.Model +{ + public class AnaliticoSource + { + public string Agrupamento + { + get; + set; + } + + public long Id + { + get; + set; + } + + public AnaliticoSource() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Model/Configuracoes.cs b/Codemerx/Gestor.Application/Model/Configuracoes.cs new file mode 100644 index 0000000..24e4fad --- /dev/null +++ b/Codemerx/Gestor.Application/Model/Configuracoes.cs @@ -0,0 +1,24 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Application.Model +{ + public class Configuracoes + { + public string LinkPromo + { + get; + set; + } + + public bool NaoverPromo + { + get; + set; + } + + public Configuracoes() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Model/Grafico.cs b/Codemerx/Gestor.Application/Model/Grafico.cs new file mode 100644 index 0000000..9104315 --- /dev/null +++ b/Codemerx/Gestor.Application/Model/Grafico.cs @@ -0,0 +1,25 @@ +using LiveCharts; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Application.Model +{ + public class Grafico + { + public Func Formatter + { + get; + set; + } + + public SeriesCollection Series + { + get; + set; + } + + public Grafico() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Model/RelacaoItens.cs b/Codemerx/Gestor.Application/Model/RelacaoItens.cs new file mode 100644 index 0000000..2274857 --- /dev/null +++ b/Codemerx/Gestor.Application/Model/RelacaoItens.cs @@ -0,0 +1,259 @@ +using Gestor.Model.Common; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Application.Model +{ + public class RelacaoItens + { + [Description("Ano Fabricação")] + public string AnoFab + { + get; + set; + } + + [Description("Ano Modelo")] + public string AnoMod + { + get; + set; + } + + [Description("Apólice")] + public string Apolice + { + get; + set; + } + + [Description("Bairro")] + public string Bairro + { + get; + set; + } + + [Description("Bens")] + public string Bens + { + get; + set; + } + + [Description("Bônus")] + public int? Bonus + { + get; + set; + } + + [Description("CEP")] + public string Cep + { + get; + set; + } + + [Description("Chassi")] + public string Chassi + { + get; + set; + } + + [Description("Cidade")] + public string Cidade + { + get; + set; + } + + [Description("Cobertura")] + public string Cobertura + { + get; + set; + } + + [Description("Complemento")] + public string Complemento + { + get; + set; + } + + [Description("Data Liquidação")] + public DateTime? DataLiq + { + get; + set; + } + + [Description("Data Reclamação")] + public DateTime? DataRec + { + get; + set; + } + + [Description("Data Sinistro")] + public DateTime? DataSinistro + { + get; + set; + } + + [Description("Descrição")] + public string Descricao + { + get; + set; + } + + [Description("Documento")] + public string Documento + { + get; + set; + } + + [Description("Endereço")] + public string Endereco + { + get; + set; + } + + [Description("Estado")] + public string Estado + { + get; + set; + } + + [Description("Fabricante")] + public string Fabricante + { + get; + set; + } + + [Description("Fipe")] + public string Fipe + { + get; + set; + } + + [Description("Item Sinistrado")] + public string ItemSinistrado + { + get; + set; + } + + [Description("Modelo")] + public string Modelo + { + get; + set; + } + + [Description("Motivo")] + public string Motivo + { + get; + set; + } + + [Description("Nome")] + public string Nome + { + get; + set; + } + + [Description("Número")] + public string Numero + { + get; + set; + } + + [Description("Número Sinistro")] + public string NumSinistro + { + get; + set; + } + + [Description("Ordem")] + public int? Ordem + { + get; + set; + } + + [Description("Placa")] + public string Placa + { + get; + set; + } + + [Description("Região Circulação")] + public string RegiaoCirculacao + { + get; + set; + } + + [Description("Sinistrado")] + public string Sinistrado + { + get; + set; + } + + [Description("Status")] + public string Status + { + get; + set; + } + + [Description("Status Sinistro")] + public Gestor.Model.Common.StatusSinistro? StatusSinistro + { + get; + set; + } + + [Description("Valor")] + public decimal? Valor + { + get; + set; + } + + [Description("Vigência Final")] + public DateTime? VigenciaFinal + { + get; + set; + } + + [Description("Vigência Inicial")] + public DateTime VigenciaInicial + { + get; + set; + } + + public RelacaoItens() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Model/SinteticoSource.cs b/Codemerx/Gestor.Application/Model/SinteticoSource.cs new file mode 100644 index 0000000..5ba3675 --- /dev/null +++ b/Codemerx/Gestor.Application/Model/SinteticoSource.cs @@ -0,0 +1,97 @@ +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using LiveCharts; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Gestor.Application.Model +{ + public class SinteticoSource : INotifyPropertyChanged + { + public List Clientes + { + get; + set; + } + + public SeriesCollection Colecao + { + get; + set; + } + + public DateTime? DateFinal + { + get; + set; + } + + public DateTime? DateStart + { + get; + set; + } + + public List Documentos + { + get; + set; + } + + public ObservableCollection Lista + { + get; + set; + } + + public bool Mostrar + { + get; + set; + } + + public List Parcelas + { + get; + set; + } + + public string Quantidade + { + get; + set; + } + + public string Titulo + { + get; + set; + } + + public string Valor + { + get; + set; + } + + public SinteticoSource() + { + } + + public void OnPropertyChanged([CallerMemberName] string name = "") + { + PropertyChangedEventHandler propertyChangedEventHandler = this.PropertyChanged; + if (propertyChangedEventHandler == null) + { + return; + } + propertyChangedEventHandler(this, new PropertyChangedEventArgs(name)); + } + + public event PropertyChangedEventHandler PropertyChanged; + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Properties/Settings.cs b/Codemerx/Gestor.Application/Properties/Settings.cs new file mode 100644 index 0000000..af7601d --- /dev/null +++ b/Codemerx/Gestor.Application/Properties/Settings.cs @@ -0,0 +1,31 @@ +using System; +using System.CodeDom.Compiler; +using System.Configuration; +using System.Runtime.CompilerServices; + +namespace Gestor.Application.Properties +{ + [CompilerGenerated] + [GeneratedCode("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.14.0.0")] + internal sealed class Settings : ApplicationSettingsBase + { + private static Settings defaultInstance; + + public static Settings Default + { + get + { + return Settings.defaultInstance; + } + } + + static Settings() + { + Settings.defaultInstance = (Settings)SettingsBase.Synchronized(new Settings()); + } + + public Settings() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Ajuda/AjudaServico.cs b/Codemerx/Gestor.Application/Servicos/Ajuda/AjudaServico.cs new file mode 100644 index 0000000..30e8886 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Ajuda/AjudaServico.cs @@ -0,0 +1,129 @@ +using CsQuery.ExtensionMethods.Internal; +using Gestor.Application.Helpers; +using Gestor.Application.Model.Ajuda; +using Gestor.Application.Servicos.Generic; +using Gestor.Model.License; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Ajuda +{ + public class AjudaServico : BaseServico + { + public AjudaServico() + { + } + + internal async Task> BuscarAtendimentos(string status) + { + ObservableCollection observableCollection = await Task.Run>(() => { + ObservableCollection result; + try + { + result = Connection.Get>(string.Format("Attendance/{0}", (status == "PENDENTES" ? 1 : 2)), true, false).Result; + } + catch (Exception exception) + { + result = null; + } + return result; + }); + return observableCollection; + } + + internal async Task> BuscarBoletosNotas(string status) + { + List boletos = await Task.Run>(() => { + List result; + try + { + result = Connection.Get>(string.Format("Billet/{0}", status == "BAIXADOS"), true, false).Result; + } + catch (Exception exception) + { + result = null; + } + return result; + }); + return boletos; + } + + internal async Task BuscarContrato(Produto produto) + { + Contrato contrato = await Task.Run(() => { + Contrato result; + try + { + result = Connection.Get(string.Format("Contract/{0}", ExtensionMethods.GetValue(produto)), true, false).Result; + } + catch (Exception exception) + { + result = null; + } + return result; + }); + return contrato; + } + + internal async Task BuscarCorpoAtendimentos(long id) + { + string str = await Task.Run(() => { + string result; + try + { + result = Connection.Get(string.Format("Attendance/Body/{0}", id), true, false).Result; + } + catch (Exception exception) + { + result = null; + } + return result; + }); + return str; + } + + internal async Task> BuscarLicencas() + { + ObservableCollection observableCollection = await Task.Run>(() => { + ObservableCollection result; + try + { + result = Connection.Get>(string.Format("License/{0}", ApplicationHelper.IdFornecedor), true, false).Result; + } + catch (Exception exception) + { + result = null; + } + return result; + }); + return observableCollection; + } + + internal async Task ExcluirInstalacao(long id) + { + int num = 3; + bool flag = await Task.Run(() => { + bool result; + while (num > 0) + { + try + { + result = Connection.Delete(string.Format("License/{0}", id)).Result; + } + catch (Exception exception) + { + num = base.Registrar(exception, 273, num, id, true); + continue; + } + return result; + } + return false; + }); + return flag; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/ArquivoDigitalServico.cs b/Codemerx/Gestor.Application/Servicos/ArquivoDigitalServico.cs new file mode 100644 index 0000000..fdeae7d --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/ArquivoDigitalServico.cs @@ -0,0 +1,538 @@ +using ArquivoDigital.Infrastructure.Repository.Interface; +using ArquivoDigital.Infrastructure.UnitOfWork.Generic; +using ArquivoDigital.Infrastructure.UnitOfWork.Logic; +using CsQuery.ExtensionMethods.Internal; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.API; +using Gestor.Model.Common; +using Gestor.Model.Domain.Aggilizador; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.License; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos +{ + public class ArquivoDigitalServico : BaseServico + { + public ArquivoDigitalServico() + { + } + + public async Task> BaixarArquivosPendentes(List arquivos) + { + string banco = Gestor.Application.Helpers.ArquivoDigital.Banco; + int num = 3; + List arquivoVinculos1 = await Task.Run>(() => { + List arquivoVinculos; + while (num > 0) + { + try + { + using (Gestor.Application.Helpers.ArquivoDigital.Read) + { + foreach (ArquivoVinculo arquivo in arquivos) + { + if (arquivo.get_Arquivo() != null || ExtensionMethods.IsNullOrEmpty(arquivo.get_Chave())) + { + continue; + } + byte[] result = Connection.DownloadFile(arquivo.get_Storage(), arquivo.get_Ano(), Guid.Parse(arquivo.get_Chave()), ".pdf", "aggilizador", false).Result; + if (result == null) + { + continue; + } + arquivo.set_Arquivo(result); + } + arquivoVinculos = arquivos; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 65, num, new { arquivos = arquivos, banco = banco }, true); + continue; + } + return arquivoVinculos; + } + return null; + }); + return arquivoVinculos1; + } + + public async Task> Buscar(List ids) + { + int num = 3; + List arquivoDigitals4 = await Task.Run>(() => { + List arquivoDigitals2; + while (num > 0) + { + try + { + List arquivoDigitals3 = new List(); + List indiceArquivoDigitals2 = ids; + Func u003cu003e9_61 = ArquivoDigitalServico.u003cu003ec.u003cu003e9__6_1; + if (u003cu003e9_61 == null) + { + u003cu003e9_61 = (IndiceArquivoDigital x) => x.get_Bd(); + ArquivoDigitalServico.u003cu003ec.u003cu003e9__6_1 = u003cu003e9_61; + } + indiceArquivoDigitals2.GroupBy(u003cu003e9_61).ToList>().ForEach((IGrouping x) => { + Gestor.Application.Helpers.ArquivoDigital.SetConnection(x.Key); + IGrouping strs = x; + Func u003cu003e9_63 = ArquivoDigitalServico.u003cu003ec.u003cu003e9__6_3; + if (u003cu003e9_63 == null) + { + u003cu003e9_63 = (IndiceArquivoDigital l) => !l.get_Assinado(); + ArquivoDigitalServico.u003cu003ec.u003cu003e9__6_3 = u003cu003e9_63; + } + IEnumerable indiceArquivoDigitals = strs.Where(u003cu003e9_63); + Func u003cu003e9_64 = ArquivoDigitalServico.u003cu003ec.u003cu003e9__6_4; + if (u003cu003e9_64 == null) + { + u003cu003e9_64 = (IndiceArquivoDigital l) => l.get_IdArquivoDigital(); + ArquivoDigitalServico.u003cu003ec.u003cu003e9__6_4 = u003cu003e9_64; + } + List list = indiceArquivoDigitals.Select(u003cu003e9_64).ToList(); + IGrouping strs1 = x; + Func u003cu003e9_65 = ArquivoDigitalServico.u003cu003ec.u003cu003e9__6_5; + if (u003cu003e9_65 == null) + { + u003cu003e9_65 = (IndiceArquivoDigital l) => l.get_Assinado(); + ArquivoDigitalServico.u003cu003ec.u003cu003e9__6_5 = u003cu003e9_65; + } + IEnumerable indiceArquivoDigitals1 = strs1.Where(u003cu003e9_65); + Func u003cu003e9_66 = ArquivoDigitalServico.u003cu003ec.u003cu003e9__6_6; + if (u003cu003e9_66 == null) + { + u003cu003e9_66 = (IndiceArquivoDigital l) => l.get_Id(); + ArquivoDigitalServico.u003cu003ec.u003cu003e9__6_6 = u003cu003e9_66; + } + List nums = indiceArquivoDigitals1.Select(u003cu003e9_66).ToList(); + if (nums.Any()) + { + List arquivoDigitals = new List(); + using (Gestor.Infrastructure.UnitOfWork.Logic.UnitOfWork read = Instancia.Read) + { + nums.ForEach((long a) => { + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital = read.get_IndiceArquivoDigitalRepository().FindAssinatura(a); + if (arquivoDigital.get_AzureGuid().HasValue) + { + arquivoDigital.set_Arquivo(Connection.DownloadFile(arquivoDigital.get_AzureStorage(), arquivoDigital.get_DataCriacao().Value.Year, arquivoDigital.get_AzureGuid().Value, Path.GetExtension(arquivoDigital.get_Descricao()), "siggner", false).Result); + } + if (arquivoDigital.get_Arquivo() != null) + { + arquivoDigitals.Add(arquivoDigital); + } + }); + } + arquivoDigitals3.AddRange(arquivoDigitals); + } + if (list.Any()) + { + List arquivoDigitals1 = new List(); + using (ArquivoDigital.Infrastructure.UnitOfWork.Logic.UnitOfWork unitOfWork = Gestor.Application.Helpers.ArquivoDigital.Read) + { + list.ForEach((long a) => { + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital = unitOfWork.get_ArquivoDigitalRepository().FindById(a, true); + if (arquivoDigital.get_AzureGuid().HasValue) + { + arquivoDigital.set_Arquivo(Connection.DownloadFile(arquivoDigital.get_AzureStorage(), arquivoDigital.get_DataCriacao().Value.Year, arquivoDigital.get_AzureGuid().Value, arquivoDigital.get_Extensao(), "ad", false).Result); + } + if (arquivoDigital.get_Arquivo() != null) + { + arquivoDigitals1.Add(arquivoDigital); + } + }); + } + arquivoDigitals3.AddRange(arquivoDigitals1); + } + }); + arquivoDigitals2 = arquivoDigitals3; + } + catch (Exception exception) + { + num = base.Registrar(exception, 66, num, ids, true); + continue; + } + return arquivoDigitals2; + } + return new List(); + }); + return arquivoDigitals4; + } + + public async Task BuscarPorId(long id, string banco) + { + int num = 3; + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital2 = await Task.Run(() => { + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital; + while (num > 0) + { + try + { + Gestor.Application.Helpers.ArquivoDigital.SetConnection(banco); + if (string.IsNullOrEmpty(banco)) + { + banco = Gestor.Application.Helpers.ArquivoDigital.Banco; + } + using (ArquivoDigital.Infrastructure.UnitOfWork.Logic.UnitOfWork read = Gestor.Application.Helpers.ArquivoDigital.Read) + { + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital1 = read.get_ArquivoDigitalRepository().FindById(id, true); + if (arquivoDigital1 != null) + { + if (arquivoDigital1.get_AzureGuid().HasValue) + { + byte[] result = Connection.DownloadFile(arquivoDigital1.get_AzureStorage(), arquivoDigital1.get_DataCriacao().Value.Year, arquivoDigital1.get_AzureGuid().Value, arquivoDigital1.get_Extensao(), "ad", false).Result; + if (result != null) + { + arquivoDigital1.set_Arquivo(result); + } + else + { + arquivoDigital = null; + return arquivoDigital; + } + } + arquivoDigital = arquivoDigital1; + } + else + { + arquivoDigital = null; + } + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 65, num, new { id = id, banco = banco }, true); + continue; + } + return arquivoDigital; + } + return null; + }); + return arquivoDigital2; + } + + public async Task BuscarPorId(long id) + { + int num = 3; + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital2 = await Task.Run(() => { + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital; + while (num > 0) + { + try + { + using (Gestor.Infrastructure.UnitOfWork.Logic.UnitOfWork read = Instancia.Read) + { + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital1 = read.get_IndiceArquivoDigitalRepository().FindAssinatura(id); + if (arquivoDigital1.get_AzureGuid().HasValue) + { + byte[] result = Connection.DownloadFile(arquivoDigital1.get_AzureStorage(), arquivoDigital1.get_DataCriacao().Value.Year, arquivoDigital1.get_AzureGuid().Value, Path.GetExtension(arquivoDigital1.get_Descricao()), "siggner", false).Result; + if (result != null) + { + arquivoDigital1.set_Arquivo(result); + } + else + { + arquivoDigital = null; + return arquivoDigital; + } + } + arquivoDigital = arquivoDigital1; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 64, num, id, true); + continue; + } + return arquivoDigital; + } + return null; + }); + return arquivoDigital2; + } + + public async Task> BuscarPorTipo(TipoArquivoDigital tipo, long id) + { + int num2 = 3; + long num3 = Recursos.Usuario.get_Id(); + List indiceArquivoDigitals1 = await Task.Run>(() => { + List indiceArquivoDigitals; + while (num2 > 0) + { + try + { + using (Gestor.Infrastructure.UnitOfWork.Logic.UnitOfWork read = Instancia.Read) + { + IIndiceArquivoDigitalRepository indiceArquivoDigitalRepository = read.get_IndiceArquivoDigitalRepository(); + TipoArquivoDigital tipoArquivoDigital = tipo; + long num = id; + long num1 = num3; + List produtos = LicenseHelper.Produtos; + Func u003cu003e9_01 = ArquivoDigitalServico.u003cu003ec.u003cu003e9__0_1; + if (u003cu003e9_01 == null) + { + u003cu003e9_01 = (Licenca x) => { + if (x.get_Produto() != 86) + { + return false; + } + return x.get_Status() != 3; + }; + ArquivoDigitalServico.u003cu003ec.u003cu003e9__0_1 = u003cu003e9_01; + } + indiceArquivoDigitals = indiceArquivoDigitalRepository.Find(tipoArquivoDigital, num, num1, produtos.Any(u003cu003e9_01)); + } + } + catch (Exception exception) + { + num2 = base.Registrar(exception, 64, num2, new { tipo = tipo, id = id }, true); + continue; + } + return indiceArquivoDigitals; + } + return new List(); + }); + return indiceArquivoDigitals1; + } + + public async Task Criar() + { + int num = 3; + await Task.Run(() => { + while (num > 0) + { + try + { + using (ArquivoDigital.Infrastructure.UnitOfWork.Logic.UnitOfWork read = Gestor.Application.Helpers.ArquivoDigital.Read) + { + read.get_ArquivoDigitalRepository().FindById((long)1, false); + break; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 288, num, null, true); + } + } + }); + } + + public async Task DeleteAttachment(IndiceArquivoDigital indice) + { + int num = 3; + DateTime networkTime = Funcoes.GetNetworkTime(); + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + List registroLogs = new List(); + try + { + using (Gestor.Infrastructure.UnitOfWork.Logic.UnitOfWork commited = Instancia.Commited) + { + indice.set_Excluido(true); + List diferencas = new List(); + Diferenca diferenca = new Diferenca(); + diferenca.set_Campo("Id"); + diferenca.set_Descricao("ID"); + diferenca.set_ValorAtual(indice.get_Id().ToString()); + diferencas.Add(diferenca); + Diferenca diferenca1 = new Diferenca(); + diferenca1.set_Campo("Descricao"); + diferenca1.set_Descricao("DESCRIÇÃO"); + diferenca1.set_ValorAtual(indice.get_Descricao()); + diferencas.Add(diferenca1); + List diferencas1 = diferencas; + if (indice.get_AzureGuid().HasValue && Connection.DeleteFile(indice.get_AzureStorage(), indice.get_DataCriacao().Value.Year, indice.get_AzureGuid().Value, indice.get_Extensao(), "ad").Result) + { + Diferenca diferenca2 = new Diferenca(); + diferenca2.set_Campo("AzureGuid"); + diferenca2.set_Descricao("AzureGuid"); + diferenca2.set_ValorAtual(indice.get_AzureGuid().ToString()); + diferencas1.Add(diferenca2); + } + registroLogs.Add(base.CreateLog(indice.get_Id(), diferencas1, 6, 2)); + indice.set_DataAtualizacao(new DateTime?(networkTime)); + if (!indice.get_DataCriacao().HasValue || indice.get_DataCriacao().Value.Year < 1754) + { + indice.set_DataCriacao(new DateTime?(networkTime)); + } + commited.get_IndiceArquivoDigitalRepository().Merge(indice); + base.SaveLog(registroLogs, commited); + commited.Commit(); + } + flag = true; + } + catch (Exception exception) + { + num = base.Registrar(exception, 253, num, indice, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task> Insert(List files) + { + int num = 3; + base.Sucesso = true; + DateTime networkTime = Funcoes.GetNetworkTime(); + List arquivoDigitals = files; + List indiceArquivoDigitals2 = await Task.Run>(() => { + List indiceArquivoDigitals; + while (num > 0) + { + List registroLogs = new List(); + files = arquivoDigitals; + try + { + List indiceArquivoDigitals1 = new List(); + files.ForEach((Gestor.Model.Domain.Common.ArquivoDigital file) => { + file.set_UsuarioCriacao(Recursos.Usuario.get_Id()); + file.set_DataCriacao(new DateTime?(networkTime)); + file.set_DataAtualizacao(null); + UploadFile uploadFile = new UploadFile(); + uploadFile.set_Ano(networkTime.Year); + uploadFile.set_Id(Guid.NewGuid()); + uploadFile.set_Extensao(file.get_Extensao().Replace(".", string.Empty)); + uploadFile.set_Arquivo(file.get_Arquivo()); + UploadFile uploadFile1 = uploadFile; + if (Connection.ConnectionAddress.get_UsaAzureStorage() && Connection.UploadFile(uploadFile1, "ad").Result) + { + file.set_AzureGuid(new Guid?(uploadFile1.get_Id())); + file.set_Arquivo(null); + file.set_AzureStorage(Connection.ConnectionAddress.get_AzureStorage()); + } + IndiceArquivoDigital indiceArquivoDigital = new IndiceArquivoDigital(); + indiceArquivoDigital.set_Descricao(file.get_Descricao()); + indiceArquivoDigital.set_Bd(Gestor.Application.Helpers.ArquivoDigital.Banco); + indiceArquivoDigital.set_Extensao(file.get_Extensao()); + indiceArquivoDigital.set_IdCliente(file.get_IdCliente()); + indiceArquivoDigital.set_IdDocumento(file.get_IdDocumento()); + indiceArquivoDigital.set_IdEmpresa(file.get_IdEmpresa()); + indiceArquivoDigital.set_IdParcela(file.get_IdParcela()); + indiceArquivoDigital.set_IdItem(file.get_IdItem()); + indiceArquivoDigital.set_IdExtrato(file.get_IdExtrato()); + indiceArquivoDigital.set_IdSinistro(file.get_IdSinistro()); + indiceArquivoDigital.set_IdSeguradora(file.get_IdSeguradora()); + indiceArquivoDigital.set_IdVendedor(file.get_IdVendedor()); + indiceArquivoDigital.set_IdUsuario(file.get_IdUsuario()); + indiceArquivoDigital.set_IdLancamento(file.get_IdLancamento()); + indiceArquivoDigital.set_IdFornecedor(file.get_IdFornecedor()); + indiceArquivoDigital.set_IdProspeccao(file.get_IdProspeccao()); + indiceArquivoDigital.set_IdSocio(file.get_IdSocio()); + indiceArquivoDigital.set_IdTarefa(file.get_IdTarefa()); + indiceArquivoDigital.set_IdNotaFiscal(file.get_IdNotaFiscal()); + indiceArquivoDigital.set_IdEstipulante(file.get_IdEstipulante()); + indiceArquivoDigital.set_Excluido(file.get_Excluido()); + indiceArquivoDigital.set_UsuarioCriacao(file.get_UsuarioCriacao()); + indiceArquivoDigital.set_DataCriacao(file.get_DataCriacao()); + indiceArquivoDigital.set_DataAtualizacao(file.get_DataAtualizacao()); + indiceArquivoDigital.set_AzureGuid(file.get_AzureGuid()); + indiceArquivoDigital.set_AzureStorage(file.get_AzureStorage()); + IndiceArquivoDigital indiceArquivoDigital1 = indiceArquivoDigital; + Gestor.Application.Helpers.ArquivoDigital.SetConnection(""); + indiceArquivoDigital1.set_Bd(Gestor.Application.Helpers.ArquivoDigital.Banco); + using (ArquivoDigital.Infrastructure.UnitOfWork.Logic.UnitOfWork commited = Gestor.Application.Helpers.ArquivoDigital.Commited) + { + file = commited.get_ArquivoDigitalRepository().SaveOrUpdate(file); + indiceArquivoDigital1.set_IdArquivoDigital(file.get_Id()); + commited.Commit(); + } + using (Gestor.Infrastructure.UnitOfWork.Logic.UnitOfWork unitOfWork = Instancia.Commited) + { + indiceArquivoDigital1 = unitOfWork.get_IndiceArquivoDigitalRepository().SaveOrUpdate(indiceArquivoDigital1); + List diferencas = new List(); + Diferenca diferenca = new Diferenca(); + diferenca.set_Campo("Descricao"); + diferenca.set_Descricao("DESCRIÇÃO"); + diferenca.set_ValorAtual(indiceArquivoDigital1.get_Descricao()); + diferencas.Add(diferenca); + registroLogs.Add(base.CreateLog(indiceArquivoDigital1.get_Id(), diferencas, 6, 0)); + base.SaveLog(registroLogs, unitOfWork); + unitOfWork.Commit(); + } + indiceArquivoDigitals1.Add(indiceArquivoDigital1); + }); + indiceArquivoDigitals = indiceArquivoDigitals1; + } + catch (Exception exception) + { + num = base.Registrar(exception, 252, num, files, true); + continue; + } + return indiceArquivoDigitals; + } + return new List(); + }); + return indiceArquivoDigitals2; + } + + public async Task Save(IndiceArquivoDigital indice) + { + int num = 3; + base.Sucesso = true; + IndiceArquivoDigital indiceArquivoDigital1 = indice; + DateTime networkTime = Funcoes.GetNetworkTime(); + IndiceArquivoDigital indiceArquivoDigital2 = await Task.Run(() => { + IndiceArquivoDigital indiceArquivoDigital; + while (num > 0) + { + indice = indiceArquivoDigital1; + List registroLogs = new List(); + try + { + using (Gestor.Infrastructure.UnitOfWork.Logic.UnitOfWork commited = Instancia.Commited) + { + TipoAcao tipoAcao = (indice.get_Id() == 0 ? 0 : 1); + indice.set_DataAtualizacao(new DateTime?(networkTime)); + indice.set_UsuarioAtualizacao(Recursos.Usuario.get_Id()); + indice.set_Excluido(false); + if (tipoAcao == 1) + { + registroLogs.Add(base.CreateLog(indice.get_Id(), indice, 6)); + } + indice = (tipoAcao == 1 ? commited.get_IndiceArquivoDigitalRepository().Merge(indice) : commited.get_IndiceArquivoDigitalRepository().SaveOrUpdate(indice)); + if (tipoAcao != 1) + { + List diferencas = new List(); + Diferenca diferenca = new Diferenca(); + diferenca.set_Campo("Descricao"); + diferenca.set_Descricao("DESCRIÇÃO"); + diferenca.set_ValorAtual(indice.get_Descricao()); + diferencas.Add(diferenca); + registroLogs.Add(base.CreateLog(indice.get_Id(), diferencas, 6, tipoAcao)); + } + base.SaveLog(registroLogs, commited); + commited.Commit(); + } + indiceArquivoDigital = indice; + } + catch (Exception exception) + { + num = base.Registrar(exception, 252, num, indice, true); + continue; + } + return indiceArquivoDigital; + } + return indiceArquivoDigital1; + }); + return indiceArquivoDigital2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/AssinaturaServico.cs b/Codemerx/Gestor.Application/Servicos/AssinaturaServico.cs new file mode 100644 index 0000000..2151fd9 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/AssinaturaServico.cs @@ -0,0 +1,178 @@ +using Assinador.Infrastructure.Repository.Interface; +using Assinador.Infrastructure.UnitOfWork.Generic; +using Assinador.Infrastructure.UnitOfWork.Logic; +using Assinador.Model.Domain; +using Assinador.Model.Generic; +using Assinador.Modelos; +using Assinador.Processos; +using Gestor.Application.Helpers; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Newtonsoft.Json; +using Sign.Modelos; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos +{ + public class AssinaturaServico + { + public AssinaturaServico() + { + } + + public async Task Assinar(Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital, ApoliceAssinador apolice) + { + AggerSigner aggerSigner = new AggerSigner(AssinadorHelper.Remetente); + ArquivoAssinatura arquivoAssinatura = new ArquivoAssinatura(); + arquivoAssinatura.set_Bytes(arquivoDigital.get_Arquivo()); + arquivoAssinatura.set_Nome(string.Concat(arquivoDigital.get_Descricao(), arquivoDigital.get_Extensao().ToLower())); + ArquivoAssinatura arquivoAssinatura1 = arquivoAssinatura; + List destinatarios = new List(); + Destinatario destinatario = new Destinatario(); + destinatario.set_Email(apolice.get_Email()); + destinatario.set_Nome(apolice.get_Cliente()); + destinatario.set_Documento(apolice.get_Documento()); + destinatarios.Add(destinatario); + arquivoAssinatura1.set_Destinatarios(destinatarios); + ArquivoCriado arquivoCriado = await aggerSigner.EnviarParaAssinatura(arquivoAssinatura1); + ArquivoParaAssinaturaAssinador arquivoParaAssinaturaAssinador = new ArquivoParaAssinaturaAssinador(); + arquivoParaAssinaturaAssinador.set_AssinaturaId(arquivoCriado.get_Id()); + arquivoParaAssinaturaAssinador.set_Chave(arquivoCriado.get_Chave()); + arquivoParaAssinaturaAssinador.set_DocumentoId(apolice.get_Id()); + arquivoParaAssinaturaAssinador.set_ClienteId(apolice.get_ClienteId()); + arquivoParaAssinaturaAssinador.set_IndiceId(apolice.get_ArquivoId()); + arquivoParaAssinaturaAssinador.set_UrlAssinatura(arquivoCriado.get_Url()); + arquivoParaAssinaturaAssinador.set_Enviado(Funcoes.GetNetworkTime()); + arquivoParaAssinaturaAssinador.set_UsuarioId(Recursos.Usuario.get_Id()); + return arquivoParaAssinaturaAssinador; + } + + public static async Task BuscarParametrosAssinatura(long id) + { + ParametrosAssinaturaAssinador parametrosAssinaturaAssinador1 = await Task.Run(() => { + ParametrosAssinaturaAssinador parametrosAssinaturaAssinador; + try + { + using (UnitOfWork read = InstanciaAssinador.Read) + { + parametrosAssinaturaAssinador = read.get_EmpresaRepository().FindByEmpresa(id); + } + } + catch (Exception exception) + { + parametrosAssinaturaAssinador = null; + } + return parametrosAssinaturaAssinador; + }); + return parametrosAssinaturaAssinador1; + } + + public async Task Reenviar(long indice) + { + ArquivoParaAssinaturaAssinador arquivoParaAssinaturaAssinador; + AggerSigner aggerSigner = new AggerSigner(AssinadorHelper.Remetente); + using (UnitOfWork commited = InstanciaAssinador.Commited) + { + ArquivoParaAssinaturaAssinador arquivoParaAssinaturaAssinador1 = commited.get_ArquivoParaAssinaturaRepository().FindByIndice(indice); + List nums = new List() + { + arquivoParaAssinaturaAssinador1.get_AssinaturaId() + }; + await aggerSigner.ReenviarParaAssinatura(nums, null); + AssinaturaLogAssinador assinaturaLogAssinador = new AssinaturaLogAssinador(); + assinaturaLogAssinador.set_Acao(1); + assinaturaLogAssinador.set_EntidadeId(arquivoParaAssinaturaAssinador1.get_Id()); + assinaturaLogAssinador.set_DataHora(Funcoes.GetNetworkTime()); + ArquivoParaAssinaturaAssinador arquivoParaAssinaturaAssinador2 = arquivoParaAssinaturaAssinador1; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + assinaturaLogAssinador.set_Descricao(JsonConvert.SerializeObject(arquivoParaAssinaturaAssinador2, jsonSerializerSetting)); + assinaturaLogAssinador.set_UsuarioId(Recursos.Usuario.get_Id()); + assinaturaLogAssinador.set_Versao(ApplicationHelper.Versao.ToString()); + this.SaveLog(assinaturaLogAssinador, commited); + arquivoParaAssinaturaAssinador = arquivoParaAssinaturaAssinador1; + } + return arquivoParaAssinaturaAssinador; + } + + public async Task Save(ArquivoParaAssinaturaAssinador arquivo) + { + ArquivoParaAssinaturaAssinador arquivoParaAssinaturaAssinador2 = await Task.Run(() => { + ArquivoParaAssinaturaAssinador arquivoParaAssinaturaAssinador; + try + { + using (UnitOfWork commited = InstanciaAssinador.Commited) + { + arquivo = (arquivo.get_Id() == 0 ? commited.get_ArquivoParaAssinaturaRepository().SaveOrUpdate(arquivo) : commited.get_ArquivoParaAssinaturaRepository().Merge(arquivo)); + AssinaturaLogAssinador assinaturaLogAssinador = new AssinaturaLogAssinador(); + assinaturaLogAssinador.set_Acao(0); + assinaturaLogAssinador.set_EntidadeId(arquivo.get_Id()); + assinaturaLogAssinador.set_DataHora(Funcoes.GetNetworkTime()); + ArquivoParaAssinaturaAssinador arquivoParaAssinaturaAssinador1 = arquivo; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + assinaturaLogAssinador.set_Descricao(JsonConvert.SerializeObject(arquivoParaAssinaturaAssinador1, jsonSerializerSetting)); + assinaturaLogAssinador.set_UsuarioId(Recursos.Usuario.get_Id()); + assinaturaLogAssinador.set_Versao(ApplicationHelper.Versao.ToString()); + this.SaveLog(assinaturaLogAssinador, commited); + commited.Commit(); + arquivoParaAssinaturaAssinador = arquivo; + } + } + catch (Exception exception) + { + arquivoParaAssinaturaAssinador = null; + } + return arquivoParaAssinaturaAssinador; + }); + return arquivoParaAssinaturaAssinador2; + } + + internal async void SaveLog(AssinaturaLogAssinador keyValues, UnitOfWork unitOfWork) + { + if (keyValues != null) + { + try + { + unitOfWork.get_AssinaturaLogRepository().SaveOrUpdate(keyValues); + unitOfWork.Commit(); + } + catch (Exception exception) + { + } + } + } + + public async Task VerificarAssinado(long id) + { + bool flag1 = await Task.Run(() => { + bool flag; + using (UnitOfWork read = InstanciaAssinador.Read) + { + ArquivoParaAssinaturaAssinador arquivoParaAssinaturaAssinador = read.get_ArquivoParaAssinaturaRepository().FindByIndice(id); + flag = (arquivoParaAssinaturaAssinador == null ? false : (arquivoParaAssinaturaAssinador.get_Status() == 1 ? true : arquivoParaAssinaturaAssinador.get_Status() == 2)); + } + return flag; + }); + return flag1; + } + + public async Task VerificarEnviado(long id) + { + bool flag1 = await Task.Run(() => { + bool flag; + using (UnitOfWork read = InstanciaAssinador.Read) + { + ArquivoParaAssinaturaAssinador arquivoParaAssinaturaAssinador = read.get_ArquivoParaAssinaturaRepository().FindByIndice(id); + flag = (arquivoParaAssinaturaAssinador == null ? false : arquivoParaAssinaturaAssinador.get_Status() == 0); + } + return flag; + }); + return flag1; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/CepService.cs b/Codemerx/Gestor.Application/Servicos/CepService.cs new file mode 100644 index 0000000..f33d711 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/CepService.cs @@ -0,0 +1,161 @@ +using Agger.Registro; +using Gestor.Application.Helpers; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Newtonsoft.Json.Linq; +using System; +using System.Diagnostics; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos +{ + public class CepService + { + private const string GuidGestor = "bbbf4f03-01fc-4300-b430-33e007753578"; + + public CepService() + { + } + + private static async Task Authorization() + { + string str; + string empty; + using (HttpClient httpClient = new HttpClient()) + { + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + string str1 = DateTime.Now.ToString("yyyy-MM-dd"); + string base64String = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}|{1}|{2}", ApplicationHelper.IdFornecedor, "bbbf4f03-01fc-4300-b430-33e007753578", str1))); + Uri apiCep = Address.get_ApiCep(); + string[] strArrays = new string[] { "/auth" }; + Uri uri = apiCep.Append(strArrays); + HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(uri, base64String.ToHttpContent(null, "application/json")); + if (httpResponseMessage.get_IsSuccessStatusCode()) + { + JToken item = httpResponseMessage.get_Content().ToJObject().get_Item("token"); + if (item != null) + { + empty = item.ToString(); + } + else + { + empty = null; + } + } + else + { + empty = string.Empty; + } + str = empty; + } + return str; + } + + public async Task SearchDirect(string cep) + { + return await this.SearchDirectApiAgger(cep); + } + + public async Task SearchDirectApiAgger(string cep) + { + EnderecoBase enderecoBase; + string upper; + string str; + string upper1; + string str1; + string upper2; + try + { + string str2 = Gestor.Model.Helper.ValidationHelper.OnlyNumber(cep); + if (!Gestor.Common.Validation.ValidationHelper.IsNullOrEmpty(str2)) + { + using (HttpClient httpClient = new HttpClient()) + { + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + string str3 = await CepService.Authorization(); + httpClient.get_DefaultRequestHeaders().TryAddWithoutValidation("Authorization", string.Concat("Bearer ", str3)); + Uri apiCep = Address.get_ApiCep(); + string[] strArrays = new string[] { str2 }; + Uri uri = apiCep.Append(strArrays); + string str4 = await await httpClient.GetAsync(uri).get_Content().ReadAsStringAsync(); + JObject jObject = JObject.Parse(str4); + if (jObject == null || str4.Equals("Endereço não encontrado")) + { + enderecoBase = null; + } + else + { + EnderecoBase enderecoBase1 = new EnderecoBase(); + JToken item = jObject.get_Item("logradouro"); + if (item != null) + { + upper = item.ToString().ToUpper(); + } + else + { + upper = null; + } + enderecoBase1.set_Endereco(upper); + JToken jToken = jObject.get_Item("bairro"); + if (jToken != null) + { + str = jToken.ToString().ToUpper(); + } + else + { + str = null; + } + enderecoBase1.set_Bairro(str); + JToken item1 = jObject.get_Item("cidade"); + if (item1 != null) + { + upper1 = item1.ToString().ToUpper(); + } + else + { + upper1 = null; + } + enderecoBase1.set_Cidade(upper1); + JToken jToken1 = jObject.get_Item("estado"); + if (jToken1 != null) + { + str1 = jToken1.ToString().ToUpper(); + } + else + { + str1 = null; + } + enderecoBase1.set_Estado(str1); + JToken item2 = jObject.get_Item("cep"); + if (item2 != null) + { + upper2 = item2.ToString().ToUpper(); + } + else + { + upper2 = null; + } + enderecoBase1.set_Cep(upper2); + enderecoBase = enderecoBase1; + } + } + } + else + { + enderecoBase = null; + } + } + catch (Exception exception) + { + enderecoBase = null; + } + return enderecoBase; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Configuracoes/ConfuguracoesServico.cs b/Codemerx/Gestor.Application/Servicos/Configuracoes/ConfuguracoesServico.cs new file mode 100644 index 0000000..d61518e --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Configuracoes/ConfuguracoesServico.cs @@ -0,0 +1,464 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Validation; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Configuracoes +{ + public class ConfuguracoesServico : BaseServico + { + public ConfuguracoesServico() + { + } + + public async Task> Buscar() + { + int num = 3; + List configuracaoSistemas1 = await Task.Run>(() => { + List configuracaoSistemas; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + configuracaoSistemas = read.get_ConfiguracaoRepository().BuscarConfiguracoes(); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 297, num, null, true); + continue; + } + return configuracaoSistemas; + } + return null; + }); + return configuracaoSistemas1; + } + + public async Task> BuscarParametros(Relatorio relatorio) + { + int num = 3; + List parametrosRelatorios1 = await Task.Run>(() => { + List parametrosRelatorios; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + parametrosRelatorios = read.get_ParametrosRelatorioRepository().Find(Recursos.Usuario.get_Id(), relatorio); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 301, num, new { Id = Recursos.Usuario.get_Id(), relatorio = relatorio }, true); + continue; + } + return parametrosRelatorios; + } + return null; + }); + return parametrosRelatorios1; + } + + public List BuscarParametroTotalizacao(Relatorio relatorio) + { + List parametrosTotalizacaos; + int num = 3; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + parametrosTotalizacaos = read.get_ParametrosTotalizacaoRepository().Find(Recursos.Usuario.get_Id(), relatorio); + } + } + catch (Exception exception1) + { + Exception exception = exception1; + num = base.Registrar(exception, 302, num, new { Id = Recursos.Usuario.get_Id(), relatorio = relatorio }, true); + continue; + } + return parametrosTotalizacaos; + } + return null; + } + + public async Task> BuscarParametroTotalizacaoAsync(Relatorio relatorio) + { + int num = 3; + List parametrosTotalizacaos1 = await Task.Run>(() => { + List parametrosTotalizacaos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + parametrosTotalizacaos = read.get_ParametrosTotalizacaoRepository().Find(Recursos.Usuario.get_Id(), relatorio); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 302, num, new { Id = Recursos.Usuario.get_Id(), relatorio = relatorio }, true); + continue; + } + return parametrosTotalizacaos; + } + return null; + }); + return parametrosTotalizacaos1; + } + + public async Task Excluir(ConfiguracaoSistema configuracao) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + string str; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + commited.get_ConfiguracaoRepository().Delete(configuracao.get_Id()); + DateTime networkTime = Gestor.Application.Helpers.Funcoes.GetNetworkTime(); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(2); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + registroLog.set_Descricao(string.Format("O USUÁRIO {0} EXCLUIU, EM {1}, A CONFIGURAÇÃO {2} ", Recursos.Usuario.get_Nome(), networkTime, Gestor.Model.Validation.Funcoes.GetDescription(configuracao.get_Configuracao()))); + registroLog.set_EntidadeId(configuracao.get_Id()); + registroLog.set_Tela(50); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_21 = ConfuguracoesServico.u003cu003ec.u003cu003e9__2_1; + if (u003cu003e9_21 == null) + { + u003cu003e9_21 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + ConfuguracoesServico.u003cu003ec.u003cu003e9__2_1 = u003cu003e9_21; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_21); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 298, num, configuracao, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task Salvar(ConfiguracaoSistema configuracao) + { + int num = 3; + ConfiguracaoSistema configuracaoSistema2 = await Task.Run(() => { + ConfiguracaoSistema configuracaoSistema; + string str; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + ConfiguracaoSistema configuracaoSistema1 = commited.get_ConfiguracaoRepository().SaveOrUpdate(configuracao); + DateTime networkTime = Gestor.Application.Helpers.Funcoes.GetNetworkTime(); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(0); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + registroLog.set_Descricao(string.Format("O USUÁRIO {0} ADICIONOU, EM {1}, A CONFIGURAÇÃO {2} ", Recursos.Usuario.get_Nome(), networkTime, Gestor.Model.Validation.Funcoes.GetDescription(configuracaoSistema1.get_Configuracao()))); + registroLog.set_EntidadeId(configuracaoSistema1.get_Id()); + registroLog.set_Tela(50); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_11 = ConfuguracoesServico.u003cu003ec.u003cu003e9__1_1; + if (u003cu003e9_11 == null) + { + u003cu003e9_11 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + ConfuguracoesServico.u003cu003ec.u003cu003e9__1_1 = u003cu003e9_11; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_11); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + configuracaoSistema = configuracaoSistema1; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 298, num, configuracao, true); + continue; + } + return configuracaoSistema; + } + return configuracao; + }); + return configuracaoSistema2; + } + + public async Task Salvar(List parametrosSalvar, List parametrosDelete) + { + int num = 3; + DateTime networkTime = Gestor.Application.Helpers.Funcoes.GetNetworkTime(); + bool flag1 = await Task.Run(() => { + bool flag; + string str; + string str1; + while (num > 0) + { + try + { + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + using (UnitOfWork commited = Instancia.Commited) + { + foreach (ParametrosRelatorio parametrosRelatorio in parametrosSalvar) + { + if (parametrosRelatorio.get_IdUsuario() == 0) + { + parametrosRelatorio.set_Id((long)0); + parametrosRelatorio.set_IdUsuario(Recursos.Usuario.get_Id()); + } + parametrosRelatorio.set_Ordem(parametrosSalvar.IndexOf(parametrosRelatorio)); + TipoAcao tipoAcao = (parametrosRelatorio.get_Id() == 0 ? 0 : 1); + ParametrosRelatorio parametrosRelatorio1 = (parametrosRelatorio.get_Id() == 0 ? commited.get_ParametrosRelatorioRepository().SaveOrUpdate(parametrosRelatorio) : commited.get_ParametrosRelatorioRepository().Merge(parametrosRelatorio)); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(tipoAcao); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + registroLog.set_Descricao(JsonConvert.SerializeObject(parametrosRelatorio1)); + registroLog.set_EntidadeId(parametrosRelatorio1.get_Id()); + registroLog.set_Tela(50); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_61 = ConfuguracoesServico.u003cu003ec.u003cu003e9__6_1; + if (u003cu003e9_61 == null) + { + u003cu003e9_61 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + ConfuguracoesServico.u003cu003ec.u003cu003e9__6_1 = u003cu003e9_61; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_61); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + } + foreach (ParametrosRelatorio parametrosRelatorio2 in parametrosDelete) + { + if (parametrosRelatorio2.get_Id() == 0) + { + continue; + } + commited.get_ParametrosRelatorioRepository().Delete(parametrosRelatorio2.get_Id()); + RegistroLog registroLog1 = new RegistroLog(); + registroLog1.set_Acao(2); + registroLog1.set_Usuario(Recursos.Usuario); + registroLog1.set_DataHora(networkTime); + registroLog1.set_Descricao(JsonConvert.SerializeObject(parametrosRelatorio2)); + registroLog1.set_EntidadeId(parametrosRelatorio2.get_Id()); + registroLog1.set_Tela(50); + registroLog1.set_Versao(LoginViewModel.VersaoAtual); + registroLog1.set_NomeMaquina(Environment.MachineName); + registroLog1.set_UsuarioMaquina(Environment.UserName); + IPAddress[] pAddressArray = hostEntry.AddressList; + Func u003cu003e9_62 = ConfuguracoesServico.u003cu003ec.u003cu003e9__6_2; + if (u003cu003e9_62 == null) + { + u003cu003e9_62 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + ConfuguracoesServico.u003cu003ec.u003cu003e9__6_2 = u003cu003e9_62; + } + IPAddress pAddress1 = ((IEnumerable)pAddressArray).FirstOrDefault(u003cu003e9_62); + if (pAddress1 != null) + { + str1 = pAddress1.ToString(); + } + else + { + str1 = null; + } + registroLog1.set_Ip(str1); + base.SaveLog(registroLog1, commited); + } + commited.Commit(); + } + flag = true; + } + catch (Exception exception) + { + num = base.Registrar(exception, 303, num, parametrosSalvar, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task SalvarTotalizacoes(List parametrosSalvar, List parametrosDeletar) + { + int num = 3; + DateTime networkTime = Gestor.Application.Helpers.Funcoes.GetNetworkTime(); + bool flag1 = await Task.Run(() => { + bool flag; + string str; + string str1; + while (num > 0) + { + try + { + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + using (UnitOfWork commited = Instancia.Commited) + { + foreach (ParametrosTotalizacao parametrosTotalizacao in parametrosSalvar) + { + if (parametrosTotalizacao.get_IdUsuario() == 0) + { + parametrosTotalizacao.set_Id((long)0); + parametrosTotalizacao.set_IdUsuario(Recursos.Usuario.get_Id()); + } + parametrosTotalizacao.set_Ativa(true); + TipoAcao tipoAcao = (parametrosTotalizacao.get_Id() == 0 ? 0 : 1); + ParametrosTotalizacao parametrosTotalizacao1 = (parametrosTotalizacao.get_Id() == 0 ? commited.get_ParametrosTotalizacaoRepository().SaveOrUpdate(parametrosTotalizacao) : commited.get_ParametrosTotalizacaoRepository().Merge(parametrosTotalizacao)); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(tipoAcao); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + registroLog.set_Descricao(JsonConvert.SerializeObject(parametrosTotalizacao1)); + registroLog.set_EntidadeId(parametrosTotalizacao1.get_Id()); + registroLog.set_Tela(50); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_71 = ConfuguracoesServico.u003cu003ec.u003cu003e9__7_1; + if (u003cu003e9_71 == null) + { + u003cu003e9_71 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + ConfuguracoesServico.u003cu003ec.u003cu003e9__7_1 = u003cu003e9_71; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_71); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + } + foreach (ParametrosTotalizacao parametrosTotalizacao2 in parametrosDeletar) + { + if (parametrosTotalizacao2.get_Id() == 0) + { + continue; + } + commited.get_ParametrosTotalizacaoRepository().Delete(parametrosTotalizacao2.get_Id()); + RegistroLog registroLog1 = new RegistroLog(); + registroLog1.set_Acao(2); + registroLog1.set_Usuario(Recursos.Usuario); + registroLog1.set_DataHora(networkTime); + registroLog1.set_Descricao(JsonConvert.SerializeObject(parametrosTotalizacao2)); + registroLog1.set_EntidadeId(parametrosTotalizacao2.get_Id()); + registroLog1.set_Tela(50); + registroLog1.set_Versao(LoginViewModel.VersaoAtual); + registroLog1.set_NomeMaquina(Environment.MachineName); + registroLog1.set_UsuarioMaquina(Environment.UserName); + IPAddress[] pAddressArray = hostEntry.AddressList; + Func u003cu003e9_72 = ConfuguracoesServico.u003cu003ec.u003cu003e9__7_2; + if (u003cu003e9_72 == null) + { + u003cu003e9_72 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + ConfuguracoesServico.u003cu003ec.u003cu003e9__7_2 = u003cu003e9_72; + } + IPAddress pAddress1 = ((IEnumerable)pAddressArray).FirstOrDefault(u003cu003e9_72); + if (pAddress1 != null) + { + str1 = pAddress1.ToString(); + } + else + { + str1 = null; + } + registroLog1.set_Ip(str1); + base.SaveLog(registroLog1, commited); + } + commited.Commit(); + } + flag = true; + } + catch (Exception exception) + { + num = base.Registrar(exception, 304, num, parametrosSalvar, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Ferramentas/AdiantamentoServico.cs b/Codemerx/Gestor.Application/Servicos/Ferramentas/AdiantamentoServico.cs new file mode 100644 index 0000000..24289ac --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Ferramentas/AdiantamentoServico.cs @@ -0,0 +1,281 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Ferramentas +{ + public class AdiantamentoServico : BaseServico + { + public AdiantamentoServico() + { + } + + public async Task> BuscarAdiantamentos(long id, bool concluido) + { + int num = 3; + List adiantamentos1 = await Task.Run>(() => { + List adiantamentos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + adiantamentos = read.get_AdiantamentoRepository().BuscarAdiantamentos(id, concluido); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 16, num, new { id = id, concluido = concluido }, true); + continue; + } + return adiantamentos; + } + return new List(); + }); + return adiantamentos1; + } + + public async Task> BuscarPorData(Filtros filtro, bool segundavia = false) + { + int num = 3; + List adiantamentos1 = await Task.Run>(() => { + List adiantamentos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + adiantamentos = read.get_AdiantamentoRepository().FindByDate(filtro.get_Inicio(), filtro.get_Fim(), filtro.get_Vendedores(), segundavia); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 15, num, filtro, true); + continue; + } + return adiantamentos; + } + return new List(); + }); + return adiantamentos1; + } + + public async Task Delete(Adiantamento adiantamento) + { + int num = 3; + DateTime networkTime = Funcoes.GetNetworkTime(); + bool flag1 = await Task.Run(() => { + bool flag; + object obj; + string str; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + commited.get_AdiantamentoRepository().Delete(adiantamento.get_Id()); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(2); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + RegistroLog registroLog1 = registroLog; + string[] strArrays = new string[] { string.Format("O USUÁRIO {0} EXCLUIU, EM {1}, O PARCEIRO DE ", Recursos.Usuario.get_Nome(), networkTime), string.Format("ID: '{0}'", adiantamento.get_Id()), ", HISTÓRICO: '", null, null, null, null, null }; + strArrays[3] = (string.IsNullOrWhiteSpace(adiantamento.get_Historico()) ? "" : adiantamento.get_Historico() ?? ""); + strArrays[4] = "', DATA DO ADIANTAMENTO: '"; + DateTime? data = adiantamento.get_Data(); + if (!data.HasValue) + { + obj = ""; + } + else + { + data = adiantamento.get_Data(); + obj = (data.HasValue ? data.GetValueOrDefault().ToShortDateString() : null) ?? ""; + } + strArrays[5] = (string)obj; + strArrays[6] = "'"; + strArrays[7] = string.Format(", VALOR DO ADIANTAMENTO: 'R${0}'.", adiantamento.get_Valor()); + registroLog1.set_Descricao(string.Concat(strArrays)); + registroLog.set_EntidadeId(adiantamento.get_Id()); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_Tela(36); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + RegistroLog registroLog2 = registroLog; + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_11 = AdiantamentoServico.u003cu003ec.u003cu003e9__1_1; + if (u003cu003e9_11 == null) + { + u003cu003e9_11 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + AdiantamentoServico.u003cu003ec.u003cu003e9__1_1 = u003cu003e9_11; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_11); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog2.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 210, num, adiantamento, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task GerarPagamento(List adiantamentos) + { + int num = 3; + DateTime networkTime = Funcoes.GetNetworkTime(); + await Task.Run(() => { + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + adiantamentos.ForEach((Adiantamento x) => { + string str; + Adiantamento adiantamento = commited.get_AdiantamentoRepository().FindById(x.get_Id()); + adiantamento.set_Pago(true); + adiantamento.set_Pagamento(new DateTime?(networkTime)); + adiantamento = commited.get_AdiantamentoRepository().Merge(adiantamento); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(1); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(adiantamento, jsonSerializerSetting)); + registroLog.set_EntidadeId(adiantamento.get_Id()); + registroLog.set_Tela(36); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_42 = AdiantamentoServico.u003cu003ec.u003cu003e9__4_2; + if (u003cu003e9_42 == null) + { + u003cu003e9_42 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + AdiantamentoServico.u003cu003ec.u003cu003e9__4_2 = u003cu003e9_42; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_42); + str = (pAddress != null ? pAddress.ToString() : null); + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + }); + commited.Commit(); + break; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 194, num, adiantamentos, true); + } + } + }); + } + + public async Task Save(Adiantamento adiatamento) + { + int num = 3; + base.Sucesso = true; + Adiantamento adiantamento2 = adiatamento; + DateTime networkTime = Funcoes.GetNetworkTime(); + Adiantamento adiantamento3 = await Task.Run(() => { + Adiantamento adiantamento; + string str; + while (num > 0) + { + adiatamento = adiantamento2; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + TipoAcao tipoAcao = (adiatamento.get_Id() == 0 ? 0 : 1); + adiatamento.set_Pagamento((adiatamento.get_Pago() ? new DateTime?(networkTime) : null)); + adiatamento = (adiatamento.get_Id() == 0 ? commited.get_AdiantamentoRepository().SaveOrUpdate(adiatamento) : commited.get_AdiantamentoRepository().Merge(adiatamento)); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(tipoAcao); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + Adiantamento adiantamento1 = adiatamento; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(adiantamento1, jsonSerializerSetting)); + registroLog.set_EntidadeId(adiatamento.get_Id()); + registroLog.set_Tela(36); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_01 = AdiantamentoServico.u003cu003ec.u003cu003e9__0_1; + if (u003cu003e9_01 == null) + { + u003cu003e9_01 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + AdiantamentoServico.u003cu003ec.u003cu003e9__0_1 = u003cu003e9_01; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_01); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + adiantamento = adiatamento; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 209, num, adiatamento, true); + continue; + } + return adiantamento; + } + return adiantamento2; + }); + return adiantamento3; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Ferramentas/AgendaServico.cs b/Codemerx/Gestor.Application/Servicos/Ferramentas/AgendaServico.cs new file mode 100644 index 0000000..d52af23 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Ferramentas/AgendaServico.cs @@ -0,0 +1,257 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Ferramentas +{ + internal class AgendaServico : BaseServico + { + public AgendaServico() + { + } + + internal async Task> BuscarEmailsAsync(long id) + { + int num = 3; + ObservableCollection observableCollection1 = await Task.Run>(() => { + ObservableCollection observableCollection; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + observableCollection = new ObservableCollection(read.get_AgendaEmailRepository().FindByAgendaId(id)); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 108, num, id, true); + continue; + } + return observableCollection; + } + return new ObservableCollection(); + }); + return observableCollection1; + } + + internal async Task> BuscarTelefonesAsync(long id) + { + int num = 3; + ObservableCollection observableCollection1 = await Task.Run>(() => { + ObservableCollection observableCollection; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + observableCollection = new ObservableCollection(read.get_AgendaTelefoneRepository().FindByAgendaId(id)); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 107, num, id, true); + continue; + } + return observableCollection; + } + return new ObservableCollection(); + }); + return observableCollection1; + } + + public async Task Delete(Agenda agenda) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + string str; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + commited.get_AgendaRepository().Delete(agenda.get_Id()); + DateTime networkTime = Funcoes.GetNetworkTime(); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(2); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + registroLog.set_Descricao(string.Concat(new string[] { string.Format("O USUÁRIO {0} EXCLUIU, EM {1}, O CONTATO DE ", Recursos.Usuario.get_Nome(), networkTime), string.Format("ID: '{0}'", agenda.get_Id()), ", NOME: '", (string.IsNullOrWhiteSpace(agenda.get_Nome()) ? "" : agenda.get_Nome() ?? ""), "', ENDEREÇO: '", agenda.get_Endereco(), ", ", agenda.get_Numero(), ", ", (string.IsNullOrWhiteSpace(agenda.get_Complemento()) ? "-" : agenda.get_Complemento() ?? ""), ", ", agenda.get_Bairro(), ", ", agenda.get_Cidade(), "/", agenda.get_Estado(), " - ", agenda.get_Cep(), "', OBSERVAÇÃO: '", (string.IsNullOrWhiteSpace(agenda.get_Observacao()) ? "" : agenda.get_Observacao() ?? ""), "'." })); + registroLog.set_EntidadeId(agenda.get_Id()); + registroLog.set_Tela(34); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + RegistroLog registroLog1 = registroLog; + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_11 = AgendaServico.u003cu003ec.u003cu003e9__1_1; + if (u003cu003e9_11 == null) + { + u003cu003e9_11 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + AgendaServico.u003cu003ec.u003cu003e9__1_1 = u003cu003e9_11; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_11); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog1.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 216, num, agenda, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task Save(Agenda agenda) + { + int num = 3; + base.Sucesso = true; + Agenda agenda2 = agenda; + Agenda agenda3 = await Task.Run(() => { + Agenda agenda4; + List list; + List agendaEmails; + string str; + while (num > 0) + { + agenda = agenda2; + try + { + TipoAcao tipoAcao = (agenda.get_Id() == 0 ? 0 : 1); + ObservableCollection telefones = agenda.get_Telefones(); + if (telefones != null) + { + list = telefones.ToList(); + } + else + { + list = null; + } + List agendaTelefones = list; + ObservableCollection emails = agenda.get_Emails(); + if (emails != null) + { + agendaEmails = emails.ToList(); + } + else + { + agendaEmails = null; + } + List agendaEmails1 = agendaEmails; + agenda.set_Telefones(null); + agenda.set_Emails(null); + using (UnitOfWork commited = Instancia.Commited) + { + if (agenda.get_Id() != (long)0) + { + if (agendaTelefones != null) + { + agendaTelefones = commited.get_AgendaTelefoneRepository().Merge(agendaTelefones, agenda); + } + if (agendaEmails1 != null) + { + agendaEmails1 = commited.get_AgendaEmailRepository().Merge(agendaEmails1, agenda); + } + agenda = commited.get_AgendaRepository().Merge(agenda); + } + else + { + agenda = commited.get_AgendaRepository().SaveOrUpdate(agenda); + if (agendaTelefones != null) + { + agendaTelefones = commited.get_AgendaTelefoneRepository().Inserir(agendaTelefones, agenda); + } + if (agendaEmails1 != null) + { + agendaEmails1 = commited.get_AgendaEmailRepository().Inserir(agendaEmails1, agenda); + } + } + agenda.set_Telefones((agendaTelefones == null ? null : new ObservableCollection(agendaTelefones))); + agenda.set_Emails((agendaEmails1 == null ? null : new ObservableCollection(agendaEmails1))); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(tipoAcao); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(Funcoes.GetNetworkTime()); + Agenda agenda1 = agenda; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(agenda1, jsonSerializerSetting)); + registroLog.set_EntidadeId(agenda.get_Id()); + registroLog.set_Tela(34); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_01 = AgendaServico.u003cu003ec.u003cu003e9__0_1; + if (u003cu003e9_01 == null) + { + u003cu003e9_01 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + AgendaServico.u003cu003ec.u003cu003e9__0_1 = u003cu003e9_01; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_01); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + agenda4 = agenda; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 215, num, agenda, true); + continue; + } + return agenda4; + } + return agenda2; + }); + return agenda3; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Ferramentas/EmailServico.cs b/Codemerx/Gestor.Application/Servicos/Ferramentas/EmailServico.cs new file mode 100644 index 0000000..2e8887d --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Ferramentas/EmailServico.cs @@ -0,0 +1,127 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Common.Helpers; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Ferramentas +{ + internal class EmailServico : BaseServico + { + public EmailServico() + { + } + + internal async Task> BuscarEmail(string email) + { + int num = 3; + List clienteEmails1 = await Task.Run>(() => { + List clienteEmails; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + clienteEmails = read.get_ClienteEmailRepository().FindEmailCliente(email, (Recursos.Usuario.get_IdEmpresa() == (long)1 ? (long)0 : Recursos.Usuario.get_IdEmpresa())); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 109, num, email, true); + continue; + } + return clienteEmails; + } + return new List(); + }); + return clienteEmails1; + } + + public async Task Delete(Credencial email) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + List registroLogs = new List(); + try + { + using (UnitOfWork commited = Instancia.Commited) + { + registroLogs.Add(base.CreateLog(email.get_Id(), email.GetValorOriginal(), 17, 2)); + commited.get_CredencialRepository().Delete(email.get_Id()); + base.SaveLog(registroLogs, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 218, num, email, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task Save(Credencial credencial) + { + int num = 3; + base.Sucesso = true; + Credencial credencial1 = credencial; + Credencial credencial2 = await Task.Run(() => { + Credencial credencial3; + bool flag; + List registroLogs = new List(); + credencial = credencial1; + while (num > 0) + { + credencial = credencial1; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + flag = (credencial.get_Id() == 0 ? false : true); + credencial.set_Senha(EncryptionHelper.Encrypt(credencial.get_Senha())); + if (flag) + { + registroLogs.Add(base.CreateLog(credencial.get_Id(), credencial, 17)); + } + credencial = (credencial.get_Id() == 0 ? commited.get_CredencialRepository().SaveOrUpdate(credencial) : commited.get_CredencialRepository().Merge(credencial)); + if (!flag) + { + registroLogs.Add(base.CreateLog(credencial.get_Id(), credencial.GetValorOriginal(), 17, 0)); + } + base.SaveLog(registroLogs, commited); + commited.Commit(); + credencial3 = credencial; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 217, num, credencial, true); + continue; + } + return credencial3; + } + return credencial1; + }); + return credencial2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Ferramentas/EmpresaServico.cs b/Codemerx/Gestor.Application/Servicos/Ferramentas/EmpresaServico.cs new file mode 100644 index 0000000..4d6d354 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Ferramentas/EmpresaServico.cs @@ -0,0 +1,287 @@ +using ArquivoDigital.Infrastructure.Repository.Interface; +using ArquivoDigital.Infrastructure.UnitOfWork.Logic; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.API; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Ferramentas +{ + internal class EmpresaServico : BaseServico + { + public EmpresaServico() + { + } + + public async void AtualizarLogoId(long id, string idLogo) + { + await Task.Run(() => { + try + { + using (Gestor.Infrastructure.UnitOfWork.Logic.UnitOfWork commited = Instancia.Commited) + { + Empresa empresa = commited.get_EmpresaRepository().FindById(id); + empresa.set_LogoId(idLogo); + commited.get_EmpresaRepository().Merge(empresa); + commited.Commit(); + } + } + catch (Exception exception) + { + } + }); + } + + internal async Task BuscarEmpresaPorId(long id) + { + int num = 3; + Empresa empresa1 = await Task.Run(() => { + Empresa empresa; + while (num > 0) + { + try + { + using (Gestor.Infrastructure.UnitOfWork.Logic.UnitOfWork read = Instancia.Read) + { + empresa = read.get_EmpresaRepository().FindById(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 114, num, id, true); + continue; + } + return empresa; + } + return new Empresa(); + }); + return empresa1; + } + + internal async Task> BuscarEmpresas() + { + int num = 3; + List empresas1 = await Task.Run>(() => { + List empresas; + while (num > 0) + { + try + { + using (Gestor.Infrastructure.UnitOfWork.Logic.UnitOfWork read = Instancia.Read) + { + empresas = read.get_EmpresaRepository().Find((Recursos.Usuario.get_IdEmpresa() == (long)1 ? (long)0 : Recursos.Usuario.get_IdEmpresa())); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 113, num, null, true); + continue; + } + return empresas; + } + return new List(); + }); + return empresas1; + } + + public string BuscarSenhaAdm() + { + string str; + int num = 3; + while (num > 0) + { + try + { + using (Gestor.Infrastructure.UnitOfWork.Logic.UnitOfWork read = Instancia.Read) + { + str = read.get_EmpresaRepository().BuscarSenhaAdm((long)1); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 115, num, null, true); + continue; + } + return str; + } + return null; + } + + public async Task ConsultaEspacoBancoInGb() + { + double num3 = await Task.Run(() => { + double num; + try + { + using (Gestor.Infrastructure.UnitOfWork.Logic.UnitOfWork read = Instancia.Read) + { + double num1 = read.get_EmpresaRepository().ConsultaEspacoBancoInGb(); + double num2 = 0; + try + { + foreach (ControleArquivoDigital controleArquivoDigital in read.get_IndiceArquivoDigitalRepository().BuscarBancos()) + { + if (controleArquivoDigital.get_Tabela().ToLower() == "arquivos") + { + continue; + } + try + { + Gestor.Application.Helpers.ArquivoDigital.SetConnection(controleArquivoDigital.get_Catalogo()); + using (ArquivoDigital.Infrastructure.UnitOfWork.Logic.UnitOfWork unitOfWork = Gestor.Application.Helpers.ArquivoDigital.Read) + { + num2 += unitOfWork.get_ArquivoDigitalRepository().ConsultaEspacoBancoInGb(); + } + } + catch + { + } + } + } + catch + { + } + num = num1 + num2; + } + } + catch (Exception exception) + { + return 0; + } + return num; + }); + return num3; + } + + internal async Task Save(Customer customer) + { + int num = 3; + base.Sucesso = true; + Customer customer1 = customer; + Customer customer2 = await Task.Run(() => { + Customer customer3; + while (num > 0) + { + customer = customer1; + try + { + using (Gestor.Infrastructure.UnitOfWork.Logic.UnitOfWork commited = Instancia.Commited) + { + Empresa empresa = new Empresa(); + empresa.set_Nome(customer.get_Name()); + empresa.set_Documento(customer.get_Document()); + empresa.set_Bairro(customer.get_District()); + empresa.set_Cidade(customer.get_City()); + empresa.set_Complemento(customer.get_Adjunct()); + empresa.set_Numero(customer.get_Number()); + empresa.set_Cep(customer.get_PostCode()); + empresa.set_Estado(customer.get_State()); + empresa.set_Email(customer.get_Mail()); + empresa.set_PrimeiroPrefixo(customer.get_AreaCode()); + empresa.set_PrimeiroTelefone(customer.get_Phone()); + empresa.set_SegundoPrefixo(customer.get_SecondAreaCode()); + empresa.set_SegundoTelefone(customer.get_SecondPhone()); + empresa.set_Serial(ApplicationHelper.NumeroSerial); + empresa.set_Site(customer.get_Site()); + commited.get_EmpresaRepository().SaveOrUpdate(empresa); + commited.Commit(); + customer3 = customer; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 277, num, customer, true); + continue; + } + return customer3; + } + return customer1; + }); + return customer2; + } + + public async Task Save(Empresa empresa) + { + int num = 3; + base.Sucesso = true; + Empresa empresa2 = empresa; + Empresa empresa3 = await Task.Run(() => { + Empresa empresa4; + string str; + while (num > 0) + { + empresa = empresa2; + try + { + using (Gestor.Infrastructure.UnitOfWork.Logic.UnitOfWork commited = Instancia.Commited) + { + TipoAcao tipoAcao = (empresa.get_Id() == 0 ? 0 : 1); + empresa = (empresa.get_Id() == 0 ? commited.get_EmpresaRepository().SaveOrUpdate(empresa) : commited.get_EmpresaRepository().Merge(empresa)); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + if (Recursos.Usuario.get_Id() != 0) + { + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(tipoAcao); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(Funcoes.GetNetworkTime()); + Empresa empresa1 = empresa; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(empresa1, jsonSerializerSetting)); + registroLog.set_EntidadeId(empresa.get_Id()); + registroLog.set_Tela(18); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_31 = EmpresaServico.u003cu003ec.u003cu003e9__3_1; + if (u003cu003e9_31 == null) + { + u003cu003e9_31 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + EmpresaServico.u003cu003ec.u003cu003e9__3_1 = u003cu003e9_31; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_31); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + } + commited.Commit(); + empresa4 = empresa; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 277, num, empresa, true); + continue; + } + return empresa4; + } + return empresa2; + }); + return empresa3; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Ferramentas/EstipulanteServico.cs b/Codemerx/Gestor.Application/Servicos/Ferramentas/EstipulanteServico.cs new file mode 100644 index 0000000..413a361 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Ferramentas/EstipulanteServico.cs @@ -0,0 +1,124 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Ferramentas +{ + internal class EstipulanteServico : BaseServico + { + public EstipulanteServico() + { + } + + internal async Task BuscarEstipulantePorId(long id) + { + int num = 3; + Estipulante estipulante1 = await Task.Run(() => { + Estipulante estipulante; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + estipulante = read.get_EstipulanteRepository().FindById(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 110, num, id, true); + continue; + } + return estipulante; + } + return new Estipulante(); + }); + return estipulante1; + } + + public async Task Delete(Estipulante estipulante) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + List registroLogs = new List(); + try + { + using (UnitOfWork commited = Instancia.Commited) + { + registroLogs.Add(base.CreateLog(estipulante.get_Id(), estipulante.GetValorOriginal(), 9, 2)); + commited.get_EstipulanteRepository().Delete(estipulante.get_Id()); + base.SaveLog(registroLogs, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 220, num, estipulante, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task Save(Estipulante estipulante) + { + int num = 3; + base.Sucesso = true; + Estipulante estipulante1 = estipulante; + Estipulante estipulante2 = await Task.Run(() => { + Estipulante estipulante3; + bool flag; + while (num > 0) + { + List registroLogs = new List(); + estipulante = estipulante1; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + estipulante.set_IdEmpresa(Recursos.Empresa.get_Id()); + flag = (estipulante.get_Id() == 0 ? false : true); + if (flag) + { + registroLogs.Add(base.CreateLog(estipulante.get_Id(), estipulante, 9)); + } + estipulante = (estipulante.get_Id() == 0 ? commited.get_EstipulanteRepository().SaveOrUpdate(estipulante) : commited.get_EstipulanteRepository().Merge(estipulante)); + if (!flag) + { + registroLogs.Add(base.CreateLog(estipulante.get_Id(), estipulante.GetValorOriginal(), 9, 0)); + } + base.SaveLog(registroLogs, commited); + commited.Commit(); + estipulante3 = estipulante; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 219, num, estipulante, true); + continue; + } + return estipulante3; + } + return estipulante1; + }); + return estipulante2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Ferramentas/ImpostoServico.cs b/Codemerx/Gestor.Application/Servicos/Ferramentas/ImpostoServico.cs new file mode 100644 index 0000000..ac8cd9f --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Ferramentas/ImpostoServico.cs @@ -0,0 +1,171 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Ferramentas +{ + public class ImpostoServico : BaseServico + { + public ImpostoServico() + { + } + + public async Task> Buscar(bool? ativo) + { + int num = 3; + List impostos1 = await Task.Run>(() => { + List impostos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + impostos = read.get_ImpostoRepository().DefaultSelect(ativo); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 317, num, ativo, true); + continue; + } + return impostos; + } + return new List(); + }); + return impostos1; + } + + public async Task> BuscarPorRamo(long id) + { + int num = 3; + List impostos1 = await Task.Run>(() => { + List impostos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + impostos = read.get_ImpostoRepository().FindByRamo(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 317, num, id, true); + continue; + } + return impostos; + } + return new List(); + }); + return impostos1; + } + + public async Task> BuscarPorSeguradora(long id) + { + int num = 3; + List impostos1 = await Task.Run>(() => { + List impostos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + impostos = read.get_ImpostoRepository().FindBySeguradora(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 317, num, id, true); + continue; + } + return impostos; + } + return new List(); + }); + return impostos1; + } + + public async Task Salvar(Imposto imposto) + { + int num = 3; + Imposto imposto2 = await Task.Run(() => { + Imposto imposto3; + string str; + while (num > 0) + { + this.Sucesso = true; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + TipoAcao tipoAcao = (imposto.get_Id() == 0 ? 0 : 1); + Imposto imposto1 = (tipoAcao == null ? commited.get_ImpostoRepository().SaveOrUpdate(imposto) : commited.get_ImpostoRepository().Merge(imposto)); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(tipoAcao); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(Funcoes.GetNetworkTime()); + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(imposto1, jsonSerializerSetting)); + registroLog.set_EntidadeId(imposto1.get_Id()); + registroLog.set_Tela(56); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_31 = ImpostoServico.u003cu003ec.u003cu003e9__3_1; + if (u003cu003e9_31 == null) + { + u003cu003e9_31 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + ImpostoServico.u003cu003ec.u003cu003e9__3_1 = u003cu003e9_31; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_31); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + imposto3 = imposto1; + } + } + catch (Exception exception1) + { + Exception exception = exception1; + this.Sucesso = false; + num = base.Registrar(exception, 318, num, imposto, false); + continue; + } + return imposto3; + } + return imposto; + }); + return imposto2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Ferramentas/MetaSeguradoraServico.cs b/Codemerx/Gestor.Application/Servicos/Ferramentas/MetaSeguradoraServico.cs new file mode 100644 index 0000000..3cac6b8 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Ferramentas/MetaSeguradoraServico.cs @@ -0,0 +1,182 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels; +using Gestor.Common.Validation; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Ferramentas +{ + internal class MetaSeguradoraServico : BaseServico + { + public MetaSeguradoraServico() + { + } + + public async Task> BuscarMetasSeguradoras(Filtros filtro) + { + int num = 3; + List metaSeguradoras1 = await Task.Run>(() => { + List metaSeguradoras; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + metaSeguradoras = read.get_MetaSeguradoraRepository().FindByMeta(filtro); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 284, num, filtro, true); + continue; + } + return metaSeguradoras; + } + return new List(); + }); + return metaSeguradoras1; + } + + public async Task Delete(MetaSeguradora meta) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + string str; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + commited.get_MetaSeguradoraRepository().Delete(meta.get_Id()); + DateTime networkTime = Funcoes.GetNetworkTime(); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(2); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + registroLog.set_Descricao(string.Concat(new string[] { string.Format("O USUÁRIO {0} EXCLUIU, EM {1}, A META DE", Recursos.Usuario.get_Nome(), networkTime), string.Format("ID: '{0}'", meta.get_Id()), ", MÊS: '", Gestor.Common.Validation.ValidationHelper.GetDescription(meta.get_Mes()), "'", string.Format(", ANO: '{0}'", meta.get_Ano()), string.Format(", VALOR: 'R${0}'.", meta.get_Valor()) })); + registroLog.set_EntidadeId(meta.get_Id()); + registroLog.set_Tela(31); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + RegistroLog registroLog1 = registroLog; + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_11 = MetaSeguradoraServico.u003cu003ec.u003cu003e9__1_1; + if (u003cu003e9_11 == null) + { + u003cu003e9_11 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + MetaSeguradoraServico.u003cu003ec.u003cu003e9__1_1 = u003cu003e9_11; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_11); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog1.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 223, num, meta, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task Save(MetaSeguradora metaSeguradora) + { + int num = 3; + base.Sucesso = true; + MetaSeguradora metaSeguradora2 = metaSeguradora; + MetaSeguradora metaSeguradora3 = await Task.Run(() => { + MetaSeguradora metaSeguradora4; + string str; + while (num > 0) + { + metaSeguradora = metaSeguradora2; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + TipoAcao tipoAcao = (metaSeguradora.get_Id() == 0 ? 0 : 1); + metaSeguradora = (metaSeguradora.get_Id() == 0 ? commited.get_MetaSeguradoraRepository().SaveOrUpdate(metaSeguradora) : commited.get_MetaSeguradoraRepository().Merge(metaSeguradora)); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(tipoAcao); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(Funcoes.GetNetworkTime()); + MetaSeguradora metaSeguradora1 = metaSeguradora; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(metaSeguradora1, jsonSerializerSetting)); + registroLog.set_EntidadeId(metaSeguradora.get_Id()); + registroLog.set_Tela(31); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_01 = MetaSeguradoraServico.u003cu003ec.u003cu003e9__0_1; + if (u003cu003e9_01 == null) + { + u003cu003e9_01 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + MetaSeguradoraServico.u003cu003ec.u003cu003e9__0_1 = u003cu003e9_01; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_01); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + metaSeguradora4 = metaSeguradora; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 222, num, metaSeguradora, true); + continue; + } + return metaSeguradora4; + } + return metaSeguradora2; + }); + return metaSeguradora3; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Ferramentas/MetaVendedorServico.cs b/Codemerx/Gestor.Application/Servicos/Ferramentas/MetaVendedorServico.cs new file mode 100644 index 0000000..5e30a23 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Ferramentas/MetaVendedorServico.cs @@ -0,0 +1,182 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels; +using Gestor.Common.Validation; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Ferramentas +{ + internal class MetaVendedorServico : BaseServico + { + public MetaVendedorServico() + { + } + + public async Task> BuscarMetasVendedores(Filtros filtro) + { + int num = 3; + List metaVendedors1 = await Task.Run>(() => { + List metaVendedors; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + metaVendedors = read.get_MetaVendedorRepository().FindByMeta(filtro); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 285, num, filtro, true); + continue; + } + return metaVendedors; + } + return new List(); + }); + return metaVendedors1; + } + + public async Task Delete(MetaVendedor meta) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + string str; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + commited.get_MetaVendedorRepository().Delete(meta.get_Id()); + DateTime networkTime = Funcoes.GetNetworkTime(); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(2); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + registroLog.set_Descricao(string.Concat(new string[] { string.Format("O USUÁRIO {0} EXCLUIU, EM {1}, A META DE", Recursos.Usuario.get_Nome(), networkTime), string.Format("ID: '{0}'", meta.get_Id()), ", MÊS: '", Gestor.Common.Validation.ValidationHelper.GetDescription(meta.get_Mes()), "'", string.Format(", ANO: '{0}'", meta.get_Ano()), string.Format(", VALOR: 'R${0}'.", meta.get_Valor()) })); + registroLog.set_EntidadeId(meta.get_Id()); + registroLog.set_Tela(30); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + RegistroLog registroLog1 = registroLog; + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_11 = MetaVendedorServico.u003cu003ec.u003cu003e9__1_1; + if (u003cu003e9_11 == null) + { + u003cu003e9_11 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + MetaVendedorServico.u003cu003ec.u003cu003e9__1_1 = u003cu003e9_11; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_11); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog1.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 225, num, meta, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task Save(MetaVendedor metaVendedor) + { + int num = 3; + base.Sucesso = true; + MetaVendedor metaVendedor2 = metaVendedor; + MetaVendedor metaVendedor3 = await Task.Run(() => { + MetaVendedor metaVendedor4; + string str; + while (num > 0) + { + metaVendedor = metaVendedor2; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + TipoAcao tipoAcao = (metaVendedor.get_Id() == 0 ? 0 : 1); + metaVendedor = (metaVendedor.get_Id() == 0 ? commited.get_MetaVendedorRepository().SaveOrUpdate(metaVendedor) : commited.get_MetaVendedorRepository().Merge(metaVendedor)); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(tipoAcao); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(Funcoes.GetNetworkTime()); + MetaVendedor metaVendedor1 = metaVendedor; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(metaVendedor1, jsonSerializerSetting)); + registroLog.set_EntidadeId(metaVendedor.get_Id()); + registroLog.set_Tela(30); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_01 = MetaVendedorServico.u003cu003ec.u003cu003e9__0_1; + if (u003cu003e9_01 == null) + { + u003cu003e9_01 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + MetaVendedorServico.u003cu003ec.u003cu003e9__0_1 = u003cu003e9_01; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_01); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + metaVendedor4 = metaVendedor; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 224, num, metaVendedor, true); + continue; + } + return metaVendedor4; + } + return metaVendedor2; + }); + return metaVendedor3; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Ferramentas/NotaFiscalServico.cs b/Codemerx/Gestor.Application/Servicos/Ferramentas/NotaFiscalServico.cs new file mode 100644 index 0000000..9ea8485 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Ferramentas/NotaFiscalServico.cs @@ -0,0 +1,176 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Ferramentas +{ + internal class NotaFiscalServico : BaseServico + { + public NotaFiscalServico() + { + } + + internal async Task> BuscarNotasFiscais() + { + int num = 3; + List notaFiscals1 = await Task.Run>(() => { + List notaFiscals; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + notaFiscals = read.get_NotaFiscalRepository().FindAll(); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 312, num, null, true); + continue; + } + return notaFiscals; + } + return new List(); + }); + return notaFiscals1; + } + + public async Task> BuscarNotasFiscais(Filtros filtro) + { + int num = 3; + List notaFiscals1 = await Task.Run>(() => { + List notaFiscals; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + notaFiscals = read.get_NotaFiscalRepository().FindByDatas(filtro); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 315, num, filtro, true); + continue; + } + return notaFiscals; + } + return new List(); + }); + return notaFiscals1; + } + + internal async Task Cadatrada(long idExtrato) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + flag = read.get_NotaFiscalRepository().FindByExtrato(idExtrato); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 315, num, idExtrato, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task Delete(NotaFiscal notaFiscal) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + List registroLogs = new List(); + try + { + using (UnitOfWork commited = Instancia.Commited) + { + registroLogs.Add(base.CreateLog(notaFiscal.get_Id(), notaFiscal.GetValorOriginal(), 55, 2)); + commited.get_NotaFiscalRepository().Delete(notaFiscal.get_Id()); + base.SaveLog(registroLogs, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 314, num, notaFiscal, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + internal async Task Save(NotaFiscal notaFiscal) + { + int num = 3; + base.Sucesso = true; + NotaFiscal notaFiscal1 = notaFiscal; + NotaFiscal notaFiscal2 = await Task.Run(() => { + NotaFiscal notaFiscal3; + bool flag; + while (num > 0) + { + List registroLogs = new List(); + notaFiscal = notaFiscal1; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + flag = (notaFiscal.get_Id() == 0 ? false : true); + if (flag) + { + registroLogs.Add(base.CreateLog(notaFiscal.get_Id(), notaFiscal, 55)); + } + notaFiscal = (notaFiscal.get_Id() == 0 ? commited.get_NotaFiscalRepository().SaveOrUpdate(notaFiscal) : commited.get_NotaFiscalRepository().Merge(notaFiscal)); + if (!flag) + { + registroLogs.Add(base.CreateLog(notaFiscal.get_Id(), notaFiscal.GetValorOriginal(), 55, 0)); + } + base.SaveLog(registroLogs, commited); + commited.Commit(); + notaFiscal3 = notaFiscal; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 313, num, notaFiscal, true); + continue; + } + return notaFiscal3; + } + return notaFiscal1; + }); + return notaFiscal2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Ferramentas/ProdutoServico.cs b/Codemerx/Gestor.Application/Servicos/Ferramentas/ProdutoServico.cs new file mode 100644 index 0000000..76fd16d --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Ferramentas/ProdutoServico.cs @@ -0,0 +1,92 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Ferramentas +{ + internal class ProdutoServico : BaseServico + { + public ProdutoServico() + { + } + + internal async Task BuscarProdutoPorId(long id) + { + int num = 3; + Produto produto1 = await Task.Run(() => { + Produto produto; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + produto = read.get_ProdutoRepository().FindById(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 116, num, id, true); + continue; + } + return produto; + } + return new Produto(); + }); + return produto1; + } + + public async Task Save(Produto produto) + { + int num = 3; + base.Sucesso = true; + Produto produto1 = produto; + Produto produto2 = await Task.Run(() => { + Produto produto3; + bool flag; + while (num > 0) + { + List registroLogs = new List(); + produto = produto1; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + flag = (produto.get_Id() == 0 ? false : true); + if (flag) + { + registroLogs.Add(base.CreateLog(produto.get_Id(), produto, 10)); + } + produto = (produto.get_Id() == 0 ? commited.get_ProdutoRepository().SaveOrUpdate(produto) : commited.get_ProdutoRepository().Merge(produto)); + if (!flag) + { + registroLogs.Add(base.CreateLog(produto.get_Id(), produto.GetValorOriginal(), 10, 0)); + } + base.SaveLog(registroLogs, commited); + commited.Commit(); + produto3 = produto; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 226, num, produto, true); + continue; + } + return produto3; + } + return produto1; + }); + return produto2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Ferramentas/QualificacaoServico.cs b/Codemerx/Gestor.Application/Servicos/Ferramentas/QualificacaoServico.cs new file mode 100644 index 0000000..5d7507b --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Ferramentas/QualificacaoServico.cs @@ -0,0 +1,57 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Ferramentas +{ + internal class QualificacaoServico : BaseServico + { + public QualificacaoServico() + { + } + + internal async Task Save(Qualificacao qualificacao) + { + int num = 3; + base.Sucesso = true; + Qualificacao qualificacao2 = qualificacao; + Qualificacao qualificacao3 = await Task.Run(() => { + Qualificacao qualificacao4; + while (num > 0) + { + List registroLogs = new List(); + qualificacao = qualificacao2; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + registroLogs.Add(base.CreateLog(qualificacao.get_Id(), qualificacao, 48)); + Qualificacao qualificacao1 = commited.get_QualificacaoRepository().SaveOrUpdate(qualificacao); + base.SaveLog(registroLogs, commited); + commited.Commit(); + qualificacao4 = qualificacao1; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 229, num, qualificacao, true); + continue; + } + return qualificacao4; + } + return qualificacao2; + }); + return qualificacao3; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Ferramentas/RamoServico.cs b/Codemerx/Gestor.Application/Servicos/Ferramentas/RamoServico.cs new file mode 100644 index 0000000..a347e2c --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Ferramentas/RamoServico.cs @@ -0,0 +1,192 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Ferramentas +{ + internal class RamoServico : BaseServico + { + public RamoServico() + { + } + + public async Task> BuscarRamos() + { + int num = 3; + List ramos1 = await Task.Run>(() => { + List ramos; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + ramos = commited.get_RamoRepository().Find(); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 169, num, null, true); + continue; + } + return ramos; + } + return null; + }); + return ramos1; + } + + public async Task Insert(Ramo ramo) + { + int num = 3; + base.Sucesso = true; + DateTime networkTime = Funcoes.GetNetworkTime(); + Ramo ramo2 = ramo; + Ramo ramo3 = await Task.Run(() => { + Ramo ramo4; + string str; + while (num > 0) + { + ramo = ramo2; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + ramo = commited.get_RamoRepository().SaveOrUpdate(ramo); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(0); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + Ramo ramo1 = ramo; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(ramo1, jsonSerializerSetting)); + registroLog.set_EntidadeId(ramo.get_Id()); + registroLog.set_Tela(12); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_21 = RamoServico.u003cu003ec.u003cu003e9__2_1; + if (u003cu003e9_21 == null) + { + u003cu003e9_21 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + RamoServico.u003cu003ec.u003cu003e9__2_1 = u003cu003e9_21; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_21); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + ramo4 = ramo; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 230, num, ramo, true); + continue; + } + return ramo4; + } + return ramo2; + }); + return ramo3; + } + + internal async Task Save(Ramo ramo, List coberturas) + { + int num = 3; + base.Sucesso = true; + DateTime networkTime = Funcoes.GetNetworkTime(); + Ramo ramo3 = ramo; + Ramo ramo4 = await Task.Run(() => { + Ramo ramo5; + string str; + while (num > 0) + { + ramo = ramo3; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + Ramo ramo1 = commited.get_RamoRepository().SaveOrUpdate(ramo); + List coberturaPadraos = coberturas; + if (coberturaPadraos != null) + { + coberturaPadraos.ForEach((CoberturaPadrao x) => commited.get_CoberturaPadraoRepository().Merge(x)); + } + else + { + } + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(1); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + Ramo ramo2 = ramo; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(ramo2, jsonSerializerSetting)); + registroLog.set_EntidadeId(ramo.get_Id()); + registroLog.set_Tela(12); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_02 = RamoServico.u003cu003ec.u003cu003e9__0_2; + if (u003cu003e9_02 == null) + { + u003cu003e9_02 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + RamoServico.u003cu003ec.u003cu003e9__0_2 = u003cu003e9_02; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_02); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + ramo5 = ramo1; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 228, num, new { ramo = ramo, coberturas = coberturas }, true); + continue; + } + return ramo5; + } + return ramo3; + }); + return ramo4; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Ferramentas/ReciboServico.cs b/Codemerx/Gestor.Application/Servicos/Ferramentas/ReciboServico.cs new file mode 100644 index 0000000..ceee657 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Ferramentas/ReciboServico.cs @@ -0,0 +1,123 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Ferramentas +{ + internal class ReciboServico : BaseServico + { + public ReciboServico() + { + } + + internal async Task> BuscarRecibos() + { + int num = 3; + List recibos1 = await Task.Run>(() => { + List recibos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + recibos = read.get_ReciboRepository().BuscarRecibos(); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 123, num, null, true); + continue; + } + return recibos; + } + return new List(); + }); + return recibos1; + } + + public async Task Delete(Recibo recibo) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + List registroLogs = new List(); + try + { + using (UnitOfWork commited = Instancia.Commited) + { + registroLogs.Add(base.CreateLog(recibo.get_Id(), recibo.GetValorOriginal(), 42, 2)); + commited.get_ReciboRepository().Delete(recibo.get_Id()); + base.SaveLog(registroLogs, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 232, num, recibo, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task Save(Recibo recibo) + { + int num = 3; + base.Sucesso = true; + Recibo recibo1 = recibo; + Recibo recibo2 = await Task.Run(() => { + Recibo recibo3; + bool flag; + while (num > 0) + { + List registroLogs = new List(); + recibo = recibo1; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + flag = (recibo.get_Id() == 0 ? false : true); + if (flag) + { + registroLogs.Add(base.CreateLog(recibo.get_Id(), recibo, 42)); + } + recibo = (recibo.get_Id() == 0 ? commited.get_ReciboRepository().SaveOrUpdate(recibo) : commited.get_ReciboRepository().Merge(recibo)); + if (!flag) + { + registroLogs.Add(base.CreateLog(recibo.get_Id(), recibo.GetValorOriginal(), 42, 0)); + } + base.SaveLog(registroLogs, commited); + commited.Commit(); + recibo3 = recibo; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 231, num, recibo, true); + continue; + } + return recibo3; + } + return recibo1; + }); + return recibo2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Ferramentas/SeguradoraServico.cs b/Codemerx/Gestor.Application/Servicos/Ferramentas/SeguradoraServico.cs new file mode 100644 index 0000000..fe44719 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Ferramentas/SeguradoraServico.cs @@ -0,0 +1,372 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Ferramentas +{ + internal class SeguradoraServico : BaseServico + { + public SeguradoraServico() + { + } + + public async Task> BuscarAssistencias(long id) + { + int num = 3; + List seguradoraContatos1 = await Task.Run>(() => { + List seguradoraContatos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + seguradoraContatos = read.get_SeguradoraContatoRepository().FindAssistencia(Recursos.Empresa.get_Id(), id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 125, num, new { Id = Recursos.Empresa.get_Id(), id = id }, true); + continue; + } + return seguradoraContatos; + } + return new List(); + }); + return seguradoraContatos1; + } + + internal async Task> BuscarConfig(long id) + { + int num = 3; + List configExtratoImports1 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List configExtratoImports = read.get_ConfigExtratoImportRepository().FindBySeguradora(id); + Func u003cu003e9_21 = SeguradoraServico.u003cu003ec.u003cu003e9__2_1; + if (u003cu003e9_21 == null) + { + u003cu003e9_21 = (ConfigExtratoImport x) => x.get_Descricao(); + SeguradoraServico.u003cu003ec.u003cu003e9__2_1 = u003cu003e9_21; + } + list = configExtratoImports.OrderBy(u003cu003e9_21).ToList(); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 124, num, id, true); + continue; + } + return list; + } + return new List(); + }); + return configExtratoImports1; + } + + public async Task> BuscarContatos(long id) + { + int num = 3; + ObservableCollection observableCollection1 = await Task.Run>(() => { + ObservableCollection observableCollection; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List seguradoraContatos = read.get_SeguradoraContatoRepository().FindBySeguradora(Recursos.Empresa.get_Id(), id); + Func u003cu003e9_31 = SeguradoraServico.u003cu003ec.u003cu003e9__3_1; + if (u003cu003e9_31 == null) + { + u003cu003e9_31 = (SeguradoraContato x) => x.get_NomeContato(); + SeguradoraServico.u003cu003ec.u003cu003e9__3_1 = u003cu003e9_31; + } + observableCollection = new ObservableCollection(seguradoraContatos.OrderBy(u003cu003e9_31)); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 125, num, new { Id = Recursos.Empresa.get_Id(), id = id }, true); + continue; + } + return observableCollection; + } + return new ObservableCollection(); + }); + return observableCollection1; + } + + public async Task> BuscarEnderecos(long id) + { + int num = 3; + ObservableCollection observableCollection1 = await Task.Run>(() => { + ObservableCollection observableCollection; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List seguradoraEnderecos = read.get_SeguradoraEnderecoRepository().FindBySeguradora(Recursos.Empresa.get_Id(), id); + Func u003cu003e9_41 = SeguradoraServico.u003cu003ec.u003cu003e9__4_1; + if (u003cu003e9_41 == null) + { + u003cu003e9_41 = (SeguradoraEndereco x) => x.get_Id(); + SeguradoraServico.u003cu003ec.u003cu003e9__4_1 = u003cu003e9_41; + } + observableCollection = new ObservableCollection(seguradoraEnderecos.OrderBy(u003cu003e9_41)); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 126, num, new { Id = Recursos.Empresa.get_Id(), id = id }, true); + continue; + } + return observableCollection; + } + return new ObservableCollection(); + }); + return observableCollection1; + } + + public async Task BuscarSeguradora(long id) + { + int num = 3; + Seguradora seguradora1 = await Task.Run(() => { + Seguradora seguradora; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + seguradora = read.get_SeguradoraRepository().FindById(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 128, num, null, true); + continue; + } + return seguradora; + } + return new Seguradora(); + }); + return seguradora1; + } + + public async Task> BuscarSeguradoras() + { + int num = 3; + List seguradoras1 = await Task.Run>(() => { + List seguradoras; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + seguradoras = read.get_SeguradoraRepository().Find(); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 127, num, null, true); + continue; + } + return seguradoras; + } + return new List(); + }); + return seguradoras1; + } + + public async Task Insert(Seguradora seguradora) + { + int num = 3; + base.Sucesso = true; + DateTime networkTime = Funcoes.GetNetworkTime(); + Seguradora seguradora2 = seguradora; + Seguradora seguradora3 = await Task.Run(() => { + Seguradora seguradora4; + string str; + while (num > 0) + { + seguradora = seguradora2; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + seguradora = commited.get_SeguradoraRepository().SaveOrUpdate(seguradora); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(0); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + Seguradora seguradora1 = seguradora; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(seguradora1, jsonSerializerSetting)); + registroLog.set_EntidadeId(seguradora.get_Id()); + registroLog.set_Tela(13); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_11 = SeguradoraServico.u003cu003ec.u003cu003e9__1_1; + if (u003cu003e9_11 == null) + { + u003cu003e9_11 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + SeguradoraServico.u003cu003ec.u003cu003e9__1_1 = u003cu003e9_11; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_11); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + seguradora4 = seguradora; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 234, num, seguradora, true); + continue; + } + return seguradora4; + } + return seguradora2; + }); + return seguradora3; + } + + public async Task Save(Seguradora seguradora, List config, bool primeiroAcesso = false) + { + Action action2 = null; + int num = 3; + base.Sucesso = true; + DateTime networkTime = Funcoes.GetNetworkTime(); + Seguradora seguradora2 = seguradora; + Seguradora seguradora3 = await Task.Run(() => { + Seguradora seguradora4; + string str; + while (num > 0) + { + seguradora = seguradora2; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + TipoAcao tipoAcao = (seguradora.get_Id() == 0 ? 0 : 1); + List contatos = seguradora.get_Contatos(); + if (contatos != null) + { + List seguradoraContatos = contatos; + Action u003cu003e9_1 = action2; + if (u003cu003e9_1 == null) + { + Action action = (SeguradoraContato x) => x.set_Seguradora(seguradora); + Action action1 = action; + action2 = action; + u003cu003e9_1 = action1; + } + seguradoraContatos.ForEach(u003cu003e9_1); + contatos = commited.get_SeguradoraContatoRepository().Merge(contatos, seguradora, Recursos.Empresa.get_Id()); + } + List enderecos = seguradora.get_Enderecos(); + if (contatos != null) + { + enderecos = commited.get_SeguradoraEnderecoRepository().Merge(enderecos, seguradora, Recursos.Empresa.get_Id()); + } + if (contatos != null | primeiroAcesso) + { + seguradora = commited.get_SeguradoraRepository().Merge(seguradora); + } + seguradora.set_Contatos(contatos); + seguradora.set_Enderecos(enderecos); + List configExtratoImports = config; + if (configExtratoImports != null) + { + configExtratoImports.ForEach((ConfigExtratoImport x) => commited.get_ConfigExtratoImportRepository().Merge(x)); + } + else + { + } + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(tipoAcao); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + Seguradora seguradora1 = seguradora; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(seguradora1, jsonSerializerSetting)); + registroLog.set_EntidadeId(seguradora.get_Id()); + registroLog.set_Tela(13); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_03 = SeguradoraServico.u003cu003ec.u003cu003e9__0_3; + if (u003cu003e9_03 == null) + { + u003cu003e9_03 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + SeguradoraServico.u003cu003ec.u003cu003e9__0_3 = u003cu003e9_03; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_03); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + seguradora4 = seguradora; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 233, num, new { seguradora = seguradora, config = config }, true); + continue; + } + return seguradora4; + } + return seguradora2; + }); + return seguradora3; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Ferramentas/SocioServico.cs b/Codemerx/Gestor.Application/Servicos/Ferramentas/SocioServico.cs new file mode 100644 index 0000000..9b46d97 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Ferramentas/SocioServico.cs @@ -0,0 +1,97 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Ferramentas +{ + internal class SocioServico : BaseServico + { + public SocioServico() + { + } + + public async Task Delete(Socio socio) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + List registroLogs = new List(); + try + { + using (UnitOfWork commited = Instancia.Commited) + { + registroLogs.Add(base.CreateLog(socio.get_Id(), socio.GetValorOriginal(), 19, 2)); + commited.get_SocioRepository().Delete(socio.get_Id()); + base.SaveLog(registroLogs, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 236, num, socio, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task Save(Socio socio) + { + int num = 3; + base.Sucesso = true; + Socio socio1 = socio; + Socio socio2 = await Task.Run(() => { + Socio socio3; + bool flag; + List registroLogs = new List(); + socio = socio1; + while (num > 0) + { + socio = socio1; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + flag = (socio.get_Id() == 0 ? false : true); + if (flag) + { + registroLogs.Add(base.CreateLog(socio.get_Id(), socio, 19)); + } + socio = (socio.get_Id() == 0 ? commited.get_SocioRepository().SaveOrUpdate(socio) : commited.get_SocioRepository().Merge(socio)); + if (!flag) + { + registroLogs.Add(base.CreateLog(socio.get_Id(), socio.GetValorOriginal(), 19, 0)); + } + base.SaveLog(registroLogs, commited); + commited.Commit(); + socio3 = socio; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 235, num, socio, true); + continue; + } + return socio3; + } + return socio1; + }); + return socio2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Ferramentas/StatusProspeccaoServico.cs b/Codemerx/Gestor.Application/Servicos/Ferramentas/StatusProspeccaoServico.cs new file mode 100644 index 0000000..1af6770 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Ferramentas/StatusProspeccaoServico.cs @@ -0,0 +1,93 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Ferramentas +{ + internal class StatusProspeccaoServico : BaseServico + { + public StatusProspeccaoServico() + { + } + + internal async Task> BuscarProspeccoes() + { + int num = 3; + List statusDeProspeccaos1 = await Task.Run>(() => { + List statusDeProspeccaos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + statusDeProspeccaos = read.get_StatusProspeccaoRepository().FindAll(); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 308, num, null, true); + continue; + } + return statusDeProspeccaos; + } + return new List(); + }); + return statusDeProspeccaos1; + } + + internal async Task Save(StatusDeProspeccao statusProspeccao) + { + int num = 3; + base.Sucesso = true; + StatusDeProspeccao statusDeProspeccao1 = statusProspeccao; + StatusDeProspeccao statusDeProspeccao2 = await Task.Run(() => { + StatusDeProspeccao statusDeProspeccao; + bool flag; + List registroLogs = new List(); + statusProspeccao = statusDeProspeccao1; + while (num > 0) + { + statusProspeccao = statusDeProspeccao1; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + flag = (statusProspeccao.get_Id() == 0 ? false : true); + if (flag) + { + registroLogs.Add(base.CreateLog(statusProspeccao.get_Id(), statusProspeccao, 57)); + } + statusProspeccao = (statusProspeccao.get_Id() == 0 ? commited.get_StatusProspeccaoRepository().SaveOrUpdate(statusProspeccao) : commited.get_StatusProspeccaoRepository().Merge(statusProspeccao)); + if (!flag) + { + registroLogs.Add(base.CreateLog(statusProspeccao.get_Id(), statusProspeccao.GetValorOriginal(), 57, 0)); + } + base.SaveLog(registroLogs, commited); + commited.Commit(); + statusDeProspeccao = statusProspeccao; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 307, num, statusProspeccao, true); + continue; + } + return statusDeProspeccao; + } + return statusDeProspeccao1; + }); + return statusDeProspeccao2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Ferramentas/StatusServico.cs b/Codemerx/Gestor.Application/Servicos/Ferramentas/StatusServico.cs new file mode 100644 index 0000000..88b146c --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Ferramentas/StatusServico.cs @@ -0,0 +1,124 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Ferramentas +{ + internal class StatusServico : BaseServico + { + public StatusServico() + { + } + + internal async Task BuscarStatusPorId(long id) + { + int num = 3; + Status statu1 = await Task.Run(() => { + Status statu; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + statu = read.get_StatusRepository().FindById(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 119, num, id, true); + continue; + } + return statu; + } + return new Status(); + }); + return statu1; + } + + public async Task Delete(Status status) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + List registroLogs = new List(); + try + { + using (UnitOfWork commited = Instancia.Commited) + { + registroLogs.Add(base.CreateLog(status.get_Id(), status.GetValorOriginal(), 11, 2)); + commited.get_StatusRepository().Delete(status.get_Id()); + base.SaveLog(registroLogs, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 221, num, status, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task Save(Status status) + { + int num = 3; + base.Sucesso = true; + Status statu1 = status; + Status statu2 = await Task.Run(() => { + Status statu; + bool flag; + List registroLogs = new List(); + status = statu1; + while (num > 0) + { + status = statu1; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + flag = (status.get_Id() == 0 ? false : true); + if (flag) + { + registroLogs.Add(base.CreateLog(status.get_Id(), status, 11)); + } + status = (status.get_Id() == 0 ? commited.get_StatusRepository().SaveOrUpdate(status) : commited.get_StatusRepository().Merge(status)); + if (!flag) + { + registroLogs.Add(base.CreateLog(status.get_Id(), status.GetValorOriginal(), 11, 0)); + } + base.SaveLog(registroLogs, commited); + commited.Commit(); + statu = status; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 227, num, status, true); + continue; + } + return statu; + } + return statu1; + }); + return statu2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Ferramentas/TipoTarefaServico.cs b/Codemerx/Gestor.Application/Servicos/Ferramentas/TipoTarefaServico.cs new file mode 100644 index 0000000..fa7c297 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Ferramentas/TipoTarefaServico.cs @@ -0,0 +1,93 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Ferramentas +{ + internal class TipoTarefaServico : BaseServico + { + public TipoTarefaServico() + { + } + + internal async Task> BuscarTarefas() + { + int num = 3; + List tipoDeTarefas1 = await Task.Run>(() => { + List tipoDeTarefas; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + tipoDeTarefas = read.get_TipoTarefaRepository().FindAll(); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 308, num, null, true); + continue; + } + return tipoDeTarefas; + } + return new List(); + }); + return tipoDeTarefas1; + } + + internal async Task Save(TipoDeTarefa tipoTarefa) + { + int num = 3; + base.Sucesso = true; + TipoDeTarefa tipoDeTarefa1 = tipoTarefa; + TipoDeTarefa tipoDeTarefa2 = await Task.Run(() => { + TipoDeTarefa tipoDeTarefa; + bool flag; + List registroLogs = new List(); + tipoTarefa = tipoDeTarefa1; + while (num > 0) + { + tipoTarefa = tipoDeTarefa1; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + flag = (tipoTarefa.get_Id() == 0 ? false : true); + if (flag) + { + registroLogs.Add(base.CreateLog(tipoTarefa.get_Id(), tipoTarefa, 52)); + } + tipoTarefa = (tipoTarefa.get_Id() == 0 ? commited.get_TipoTarefaRepository().SaveOrUpdate(tipoTarefa) : commited.get_TipoTarefaRepository().Merge(tipoTarefa)); + if (!flag) + { + registroLogs.Add(base.CreateLog(tipoTarefa.get_Id(), tipoTarefa.GetValorOriginal(), 52, 0)); + } + base.SaveLog(registroLogs, commited); + commited.Commit(); + tipoDeTarefa = tipoTarefa; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 306, num, tipoTarefa, true); + continue; + } + return tipoDeTarefa; + } + return tipoDeTarefa1; + }); + return tipoDeTarefa2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Ferramentas/TipoVendedorServico.cs b/Codemerx/Gestor.Application/Servicos/Ferramentas/TipoVendedorServico.cs new file mode 100644 index 0000000..0757820 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Ferramentas/TipoVendedorServico.cs @@ -0,0 +1,131 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Ferramentas +{ + internal class TipoVendedorServico : BaseServico + { + public TipoVendedorServico() + { + } + + public async Task Delete(TipoVendedor tipoVendedor) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + List registroLogs = new List(); + try + { + using (UnitOfWork commited = Instancia.Commited) + { + registroLogs.Add(base.CreateLog(tipoVendedor.get_Id(), tipoVendedor.GetValorOriginal(), 14, 2)); + commited.get_TipoVendedorRepository().Delete(tipoVendedor.get_Id()); + base.SaveLog(registroLogs, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 238, num, tipoVendedor, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task FindLastId() + { + int num1 = 3; + long num2 = await Task.Run(() => { + long num; + while (num1 > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + num = read.get_TipoVendedorRepository().FindLastId(); + } + } + catch (Exception exception) + { + num1 = base.Registrar(exception, 17, num1, null, true); + continue; + } + return num; + } + return (long)0; + }); + return num2; + } + + internal async Task Save(TipoVendedor tipoVendedor) + { + int num = 3; + base.Sucesso = true; + TipoVendedor tipoVendedor2 = tipoVendedor; + TipoVendedor tipoVendedor3 = await Task.Run(async () => { + TipoVendedor tipoVendedor4; + while (num > 0) + { + List registroLogs = new List(); + tipoVendedor = tipoVendedor2; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + TipoAcao tipoAcao = (tipoVendedor.get_Id() == 0 ? 0 : 1); + if (tipoVendedor.get_Id() == 0) + { + TipoVendedor tipoVendedor1 = tipoVendedor; + tipoVendedor1.set_Id(await this.FindLastId() + (long)1); + tipoVendedor1 = null; + } + TipoAcao tipoAcao1 = tipoAcao; + if (tipoAcao1 == null) + { + registroLogs.Add(base.CreateLog(tipoVendedor.get_Id(), tipoVendedor.GetValorOriginal(), 14, 0)); + } + else if (tipoAcao1 == 1) + { + registroLogs.Add(base.CreateLog(tipoVendedor.get_Id(), tipoVendedor, 14)); + } + tipoVendedor = (tipoAcao == null ? commited.get_TipoVendedorRepository().SaveOrUpdate(tipoVendedor) : commited.get_TipoVendedorRepository().Merge(tipoVendedor)); + base.SaveLog(registroLogs, commited); + commited.Commit(); + tipoVendedor4 = tipoVendedor; + return tipoVendedor4; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 237, num, tipoVendedor, true); + } + registroLogs = null; + } + tipoVendedor4 = tipoVendedor2; + return tipoVendedor4; + }); + return tipoVendedor3; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Ferramentas/UsuarioServico.cs b/Codemerx/Gestor.Application/Servicos/Ferramentas/UsuarioServico.cs new file mode 100644 index 0000000..5b04623 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Ferramentas/UsuarioServico.cs @@ -0,0 +1,303 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Common.Security; +using Gestor.Common.Validation; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.API; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Ferramentas +{ + internal class UsuarioServico : BaseServico + { + public UsuarioServico() + { + } + + public async Task AddCentralSegurado(long id, bool update = true) + { + await Task.Run(() => { + using (UnitOfWork commited = Instancia.Commited) + { + commited.get_ClienteRepository().AddCentralSegurado(id, update); + } + }); + } + + public async Task BuscarLogin(string login) + { + int num = 3; + Usuario usuario2 = await Task.Run(() => { + Usuario usuario; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + Empresa empresa = read.get_EmpresaRepository().FindBySerial(ApplicationHelper.NumeroSerial); + AuthSso result = base.VerificaUsuarioSso(login, empresa.get_Documento()).Result; + if (result == null || result.get_Code() == 401) + { + usuario = new Usuario(); + } + else + { + Usuario usuario1 = read.get_UsuarioRepository().FindUsuario(login); + usuario = (result.get_Code() == 404 ? usuario1 : CustomMap.FromUserSso(usuario1, result.get_Data().get_User())); + } + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 134, num, login, true); + continue; + } + return usuario; + } + return new Usuario(); + }); + return usuario2; + } + + public async Task> BuscarPermissaoAggilizador() + { + List permissaoAggilizadors2 = await Task.Run>(() => { + List permissaoAggilizadors; + try + { + using (UnitOfWork read = Instancia.Read) + { + permissaoAggilizadors = read.get_UsuarioRepository().PermissaoAggilizador(); + } + } + catch (Exception exception) + { + List permissaoAggilizadors1 = new List(); + PermissaoAggilizador permissaoAggilizador = new PermissaoAggilizador(); + permissaoAggilizador.set_Id((long)1); + permissaoAggilizador.set_Descricao("ADMINISTRADOR"); + permissaoAggilizadors1.Add(permissaoAggilizador); + PermissaoAggilizador permissaoAggilizador1 = new PermissaoAggilizador(); + permissaoAggilizador1.set_Id((long)2); + permissaoAggilizador1.set_Descricao("NORMAL"); + permissaoAggilizadors1.Add(permissaoAggilizador1); + PermissaoAggilizador permissaoAggilizador2 = new PermissaoAggilizador(); + permissaoAggilizador2.set_Id((long)3); + permissaoAggilizador2.set_Descricao("LIMITADO"); + permissaoAggilizadors1.Add(permissaoAggilizador2); + permissaoAggilizadors = permissaoAggilizadors1; + } + return permissaoAggilizadors; + }); + return permissaoAggilizadors2; + } + + internal async Task BuscarUsuarioPorId(long id) + { + int num = 3; + Usuario usuario1 = await Task.Run(() => { + Usuario usuario; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + usuario = read.get_UsuarioRepository().FindById(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 130, num, id, true); + continue; + } + return usuario; + } + return new Usuario(); + }); + return usuario1; + } + + public async Task BuscaUsuarioInicial(string usuario, string senha) + { + Usuario usuario2 = await Task.Run(() => { + Usuario usuario3; + using (UnitOfWork read = Instancia.Read) + { + Empresa empresa = read.get_EmpresaRepository().FindBySerial(ApplicationHelper.NumeroSerial); + string str = (new Token()).AggerEncrypt(senha); + AuthSso result = base.BuscaUsuarioSso(usuario, str, empresa.get_Documento()).Result; + if (result.get_Code() != 401) + { + Usuario usuario1 = read.get_UsuarioRepository().FindUsuario(usuario); + usuario3 = (result.get_Code() != 404 || usuario1 != null ? (result.get_Data() != null || usuario1 == null ? (usuario1 != null || result.get_Data() == null ? usuario1 : CustomMap.ToUsuario(result.get_Data().get_User(), empresa.get_Id())) : usuario1) : new Usuario()); + } + else + { + usuario3 = null; + } + } + return usuario3; + }); + return usuario2; + } + + public async Task Delete(Usuario usuario) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + List registroLogs = new List(); + try + { + using (UnitOfWork commited = Instancia.Commited) + { + registroLogs.Add(base.CreateLog(usuario.get_Id(), usuario.GetValorOriginal(), 16, 2)); + commited.get_UsuarioRepository().Delete(usuario.get_Id()); + base.SaveLog(registroLogs, commited); + commited.Commit(); + usuario.set_TokenSso(Recursos.Usuario.get_TokenSso()); + base.DeleteUsuarioSso(usuario, Recursos.Empresa.get_Documento()).Wait(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 240, num, usuario, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task Save(Usuario usuario) + { + int num = 3; + base.Sucesso = true; + Usuario usuario5 = usuario; + Usuario usuario6 = await Task.Run(() => { + Usuario usuario7; + long? nullable; + string tokenSso; + string documento; + long? nullable1; + bool flag; + List registroLogs = new List(); + while (num > 0) + { + usuario = usuario5; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + Usuario usuario1 = Recursos.Usuario; + if (usuario1 != null) + { + tokenSso = usuario1.get_TokenSso(); + } + else + { + tokenSso = null; + } + string token = tokenSso; + Empresa empresa = Recursos.Empresa; + if (empresa != null) + { + documento = empresa.get_Documento(); + } + else + { + documento = null; + } + string str = documento; + if (ValidationHelper.IsNullOrEmpty(token)) + { + Empresa empresa1 = commited.get_EmpresaRepository().FindBySerial(ApplicationHelper.NumeroSerial); + string senha = usuario.get_Senha(); + if (ValidationHelper.IsNotNullOrEmpty(usuario.get_SenhaAnterior())) + { + if ((new Token()).AggerDecrypt(usuario.get_SenhaAnterior()).ToUpper().Contains("AGGER@")) + { + Usuario result = this.BuscarLogin(usuario.get_Login()).Result; + usuario.set_SenhaAnterior(result.get_Senha()); + } + senha = usuario.get_SenhaAnterior(); + } + AuthSso authSso = base.BuscaUsuarioSso(usuario.get_Login(), senha, empresa1.get_Documento()).Result; + if (authSso == null || authSso.get_Code() == 401) + { + this.Sucesso = false; + usuario7 = usuario5; + return usuario7; + } + else + { + token = authSso.get_Data().get_Token(); + str = empresa1.get_Documento(); + } + } + Usuario usuario2 = usuario; + if (!usuario.get_PermissaoAggilizador().HasValue) + { + Usuario usuario3 = usuario; + long? nullable2 = new long?((long)2); + nullable = nullable2; + usuario3.set_PermissaoAggilizador(nullable2); + nullable1 = nullable; + } + else + { + Usuario usuario4 = usuario; + long? permissaoAggilizador = usuario.get_PermissaoAggilizador(); + nullable = permissaoAggilizador; + usuario4.set_PermissaoAggilizador(permissaoAggilizador); + nullable1 = nullable; + } + usuario2.set_PermissaoAggilizador(nullable1); + flag = (usuario.get_Id() == 0 ? false : true); + if (flag) + { + registroLogs.Add(base.CreateLog(usuario.get_Id(), usuario, 16)); + } + usuario = (usuario.get_Id() == 0 ? commited.get_UsuarioRepository().SaveOrUpdate(usuario) : commited.get_UsuarioRepository().Merge(usuario)); + if (!flag) + { + registroLogs.Add(base.CreateLog(usuario.get_Id(), usuario.GetValorOriginal(), 16, 0)); + } + base.SaveLog(registroLogs, commited); + commited.Commit(); + usuario.set_TokenSso(token); + base.AddOrUpdateUsuarioSso(usuario, str, usuario.get_SsoId()).Wait(); + usuario7 = usuario; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 239, num, usuario, true); + continue; + } + return usuario7; + } + return usuario5; + }); + return usuario6; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Ferramentas/VendedorServico.cs b/Codemerx/Gestor.Application/Servicos/Ferramentas/VendedorServico.cs new file mode 100644 index 0000000..9c81d34 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Ferramentas/VendedorServico.cs @@ -0,0 +1,851 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels; +using Gestor.Common.Validation; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Ferramentas +{ + public class VendedorServico : BaseServico + { + public VendedorServico() + { + } + + public async Task BuscarCorretora() + { + Vendedor vendedor1 = await Task.Run(() => { + Vendedor vendedor; + try + { + using (UnitOfWork read = Instancia.Read) + { + vendedor = read.get_VendedorRepository().FindCorretora(); + } + } + catch (Exception exception) + { + vendedor = null; + } + return vendedor; + }); + return vendedor1; + } + + public async Task> BuscaRepasse(long id) + { + int num = 3; + List vendedorParcelas1 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List vendedorParcelas = read.get_VendedorParcelaRepository().FindByDocumentId(id); + Func u003cu003e9_31 = VendedorServico.u003cu003ec.u003cu003e9__3_1; + if (u003cu003e9_31 == null) + { + u003cu003e9_31 = (VendedorParcela x) => x.get_TipoVendedor().get_Id(); + VendedorServico.u003cu003ec.u003cu003e9__3_1 = u003cu003e9_31; + } + list = vendedorParcelas.OrderBy(u003cu003e9_31).ToList(); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 136, num, id, true); + continue; + } + return list; + } + return new List(); + }); + return vendedorParcelas1; + } + + public async Task> BuscaRepasseParcela(long id) + { + int num = 3; + List vendedorParcelas1 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List vendedorParcelas = read.get_VendedorParcelaRepository().FindByParcela(id); + Func u003cu003e9_41 = VendedorServico.u003cu003ec.u003cu003e9__4_1; + if (u003cu003e9_41 == null) + { + u003cu003e9_41 = (VendedorParcela x) => { + TipoVendedor tipoVendedor = x.get_TipoVendedor(); + if (tipoVendedor != null) + { + return new long?(tipoVendedor.get_Id()); + } + return null; + }; + VendedorServico.u003cu003ec.u003cu003e9__4_1 = u003cu003e9_41; + } + list = vendedorParcelas.OrderBy(u003cu003e9_41).ToList(); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 137, num, id, true); + continue; + } + return list; + } + return new List(); + }); + return vendedorParcelas1; + } + + public async Task> BuscaRepasses() + { + int num = 3; + List repasses1 = await Task.Run>(() => { + List repasses; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + repasses = read.get_RepasseRepository().DefaultSelect((long)0); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 142, num, null, true); + continue; + } + return repasses; + } + return new List(); + }); + return repasses1; + } + + public async Task> BuscaRepassesPorIdVendedor(long id) + { + int num = 3; + ObservableCollection observableCollection1 = await Task.Run>(() => { + ObservableCollection observableCollection; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + observableCollection = new ObservableCollection(read.get_RepasseRepository().FindByIdVendedor(id)); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 143, num, id, true); + continue; + } + return observableCollection; + } + return new ObservableCollection(); + }); + return observableCollection1; + } + + public async Task> BuscarPagos(Filtros filtro) + { + int num = 3; + List manutencaoPagamentos = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + list = read.get_VendedorParcelaRepository().FindByDate(filtro).ToList(); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 80, num, null, true); + continue; + } + return list; + } + return new List(); + }); + return manutencaoPagamentos; + } + + internal async Task> BuscarTelefonesAsync(long id) + { + int num = 3; + ObservableCollection observableCollection1 = await Task.Run>(() => { + ObservableCollection observableCollection; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List vendedorTelefones = read.get_VendedorTelefoneRepository().FindByVendedorId(id); + Func u003cu003e9_51 = VendedorServico.u003cu003ec.u003cu003e9__5_1; + if (u003cu003e9_51 == null) + { + u003cu003e9_51 = (VendedorTelefone x) => x.get_Nome(); + VendedorServico.u003cu003ec.u003cu003e9__5_1 = u003cu003e9_51; + } + observableCollection = new ObservableCollection(vendedorTelefones.OrderBy(u003cu003e9_51)); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 138, num, id, true); + continue; + } + return observableCollection; + } + return new ObservableCollection(); + }); + return observableCollection1; + } + + internal async Task> BuscarVendedoresAtivosAsync() + { + int num = 3; + List vendedors2 = await Task.Run>(() => { + List vendedors; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List vendedors1 = read.get_VendedorRepository().Find(true, (Recursos.Usuario.get_IdEmpresa() == (long)1 ? (long)0 : Recursos.Usuario.get_IdEmpresa())); + Func u003cu003e9_01 = VendedorServico.u003cu003ec.u003cu003e9__0_1; + if (u003cu003e9_01 == null) + { + u003cu003e9_01 = (Vendedor x) => x.get_Nome(); + VendedorServico.u003cu003ec.u003cu003e9__0_1 = u003cu003e9_01; + } + vendedors = new List(vendedors1.OrderBy(u003cu003e9_01)); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 135, num, null, true); + continue; + } + return vendedors; + } + return new List(); + }); + return vendedors2; + } + + public async Task> BuscarVendedorParcela(long id) + { + int num = 3; + List vendedorParcelas1 = await Task.Run>(() => { + List vendedorParcelas; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + vendedorParcelas = read.get_RepasseRepository().FindByIdRepasse(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 143, num, id, true); + continue; + } + return vendedorParcelas; + } + return new List(); + }); + return vendedorParcelas1; + } + + public async Task BuscarVendedorParcelaCompleto(long id) + { + int num = 3; + VendedorParcela vendedorParcela1 = await Task.Run(() => { + VendedorParcela vendedorParcela; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + vendedorParcela = read.get_VendedorParcelaRepository().FindById(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 81, num, null, true); + continue; + } + return vendedorParcela; + } + return new VendedorParcela(); + }); + return vendedorParcela1; + } + + internal async Task BuscarVendedorPorId(long id) + { + int num = 3; + Vendedor vendedor1 = await Task.Run(() => { + Vendedor vendedor; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + vendedor = read.get_VendedorRepository().FindById(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 139, num, id, true); + continue; + } + return vendedor; + } + return new Vendedor(); + }); + return vendedor1; + } + + public async Task> BuscarVinculosCliente(long idCliente) + { + int num = 3; + List vendedors1 = await Task.Run>(() => { + List vendedors; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + if (Recursos.Usuario.get_IdEmpresa() != (long)1) + { + Recursos.Usuario.get_IdEmpresa(); + } + vendedors = read.get_VendedorParcelaRepository().FindVinculoByIdCliente(idCliente); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 143, num, null, true); + continue; + } + return vendedors; + } + return null; + }); + return vendedors1; + } + + public async Task Delete(VinculoRepasse vinculo) + { + int num = 3; + base.Sucesso = true; + DateTime networkTime = Funcoes.GetNetworkTime(); + bool flag1 = await Task.Run(() => { + bool flag; + string str; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + commited.get_RepasseRepository().DeleteVinculo(vinculo.get_Id()); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(2); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + VinculoRepasse vinculoRepasse = vinculo; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(vinculoRepasse, jsonSerializerSetting)); + registroLog.set_EntidadeId(vinculo.get_Id()); + registroLog.set_Tela(53); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_101 = VendedorServico.u003cu003ec.u003cu003e9__10_1; + if (u003cu003e9_101 == null) + { + u003cu003e9_101 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + VendedorServico.u003cu003ec.u003cu003e9__10_1 = u003cu003e9_101; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_101); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 311, num, vinculo, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task Delete(Vendedor vendedor) + { + int num = 3; + DateTime networkTime = Funcoes.GetNetworkTime(); + bool flag1 = await Task.Run(() => { + bool flag; + string str; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + commited.get_VendedorRepository().Delete(vendedor.get_Id()); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(2); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + RegistroLog registroLog1 = registroLog; + string[] strArrays = new string[] { string.Format("O USUÁRIO {0} EXCLUIU, EM {1}, O VENDEDOR DE ", Recursos.Usuario.get_Nome(), networkTime), string.Format("ID: '{0}'", vendedor.get_Id()), ", NOME: '", null, null, null, null, null, null, null, null }; + strArrays[3] = (string.IsNullOrWhiteSpace(vendedor.get_Nome()) ? "" : vendedor.get_Nome() ?? ""); + strArrays[4] = "', DOCUMENTO: '"; + strArrays[5] = (string.IsNullOrWhiteSpace(vendedor.get_Documento()) ? "" : vendedor.get_Documento() ?? ""); + strArrays[6] = "', BANCO: '"; + strArrays[7] = (vendedor.get_Banco() == null ? "" : vendedor.get_Banco().get_Nome() ?? ""); + strArrays[8] = "', CONTA: '"; + strArrays[9] = (string.IsNullOrWhiteSpace(vendedor.get_Conta()) ? "" : vendedor.get_Conta() ?? ""); + strArrays[10] = "'."; + registroLog1.set_Descricao(string.Concat(strArrays)); + registroLog.set_EntidadeId(vendedor.get_Id()); + registroLog.set_Tela(15); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + RegistroLog registroLog2 = registroLog; + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_131 = VendedorServico.u003cu003ec.u003cu003e9__13_1; + if (u003cu003e9_131 == null) + { + u003cu003e9_131 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + VendedorServico.u003cu003ec.u003cu003e9__13_1 = u003cu003e9_131; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_131); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog2.set_Ip(str); + RegistroLog registroLog3 = registroLog; + if (vendedor.get_Telefones() != null && vendedor.get_Telefones().Count != 0) + { + foreach (VendedorTelefone telefone in vendedor.get_Telefones()) + { + RegistroLog registroLog4 = registroLog3; + string descricao = registroLog4.get_Descricao(); + object[] objArray = new object[] { vendedor.get_Telefones().IndexOf(telefone), null, null, null }; + objArray[1] = (!telefone.get_Tipo().HasValue ? "-" : Gestor.Common.Validation.ValidationHelper.GetDescription(telefone.get_Tipo())); + objArray[2] = (string.IsNullOrWhiteSpace(telefone.get_Prefixo()) ? "" : telefone.get_Prefixo() ?? ""); + objArray[3] = (string.IsNullOrWhiteSpace(telefone.get_Numero()) ? "" : telefone.get_Numero() ?? ""); + registroLog4.set_Descricao(string.Concat(descricao, string.Format(", TELEFONE {0}: {1} ({2}) {3}", objArray))); + } + } + RegistroLog registroLog5 = registroLog3; + registroLog5.set_Descricao(string.Concat(registroLog5.get_Descricao(), ".")); + base.SaveLog(registroLog3, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 242, num, vendedor, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task Save(Vendedor vendedor, Repasse repasse) + { + int num = 3; + base.Sucesso = true; + Vendedor vendedor1 = vendedor; + Vendedor vendedor2 = await Task.Run(() => { + Vendedor vendedor3; + while (num > 0) + { + vendedor = vendedor1; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + vendedor.set_IdEmpresa((vendedor.get_IdEmpresa() == 0 ? Recursos.Empresa.get_Id() : vendedor.get_IdEmpresa())); + vendedor = commited.get_VendedorRepository().SaveOrUpdate(vendedor); + repasse.set_Vendedor(vendedor); + repasse = commited.get_RepasseRepository().SaveOrUpdate(repasse); + commited.Commit(); + vendedor3 = vendedor; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 241, num, new { vendedor = vendedor, repasse = repasse }, true); + continue; + } + return vendedor3; + } + return vendedor1; + }); + return vendedor2; + } + + public async Task Save(VinculoRepasse vinculo) + { + int num = 3; + base.Sucesso = true; + DateTime networkTime = Funcoes.GetNetworkTime(); + VinculoRepasse vinculoRepasse2 = await Task.Run(() => { + VinculoRepasse vinculoRepasse; + string str; + while (num > 0) + { + VinculoRepasse vinculoRepasse1 = vinculo; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + TipoAcao tipoAcao = (vinculoRepasse1.get_Id() == 0 ? 0 : 1); + vinculoRepasse1 = (tipoAcao == null ? commited.get_RepasseRepository().SaveOrUpdate(vinculoRepasse1) : commited.get_RepasseRepository().Merge(vinculoRepasse1)); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(tipoAcao); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(vinculoRepasse1, jsonSerializerSetting)); + registroLog.set_EntidadeId(vinculoRepasse1.get_Id()); + registroLog.set_Tela(53); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_91 = VendedorServico.u003cu003ec.u003cu003e9__9_1; + if (u003cu003e9_91 == null) + { + u003cu003e9_91 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + VendedorServico.u003cu003ec.u003cu003e9__9_1 = u003cu003e9_91; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_91); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + vinculoRepasse = vinculoRepasse1; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 311, num, vinculo, true); + continue; + } + return vinculoRepasse; + } + return vinculo; + }); + return vinculoRepasse2; + } + + public async Task Save(Vendedor vendedor, List repasses) + { + int num = 3; + base.Sucesso = true; + DateTime networkTime = Funcoes.GetNetworkTime(); + Vendedor vendedor2 = vendedor; + Vendedor vendedor3 = await Task.Run(() => { + Vendedor vendedor4; + string str; + string str1; + while (num > 0) + { + vendedor = vendedor2; + try + { + List telefones = vendedor.get_Telefones(); + using (UnitOfWork commited = Instancia.Commited) + { + List repasses1 = repasses; + Func u003cu003e9_111 = VendedorServico.u003cu003ec.u003cu003e9__11_1; + if (u003cu003e9_111 == null) + { + u003cu003e9_111 = (Repasse r) => { + Ramo ramo = r.get_Ramo(); + if (ramo == null) + { + return false; + } + return ramo.get_Id() == (long)0; + }; + VendedorServico.u003cu003ec.u003cu003e9__11_1 = u003cu003e9_111; + } + foreach (Repasse repasse in repasses1.Where(u003cu003e9_111)) + { + repasse.set_Ramo(null); + } + bool id = vendedor.get_Id() == (long)0; + vendedor.set_IdEmpresa((vendedor.get_IdEmpresa() == 0 ? Recursos.Empresa.get_Id() : vendedor.get_IdEmpresa())); + TipoAcao tipoAcao = (vendedor.get_Id() == 0 ? 0 : 1); + if (!id) + { + vendedor = commited.get_VendedorRepository().Merge(vendedor); + if (telefones != null) + { + telefones = commited.get_VendedorTelefoneRepository().Merge(telefones, vendedor); + } + if (repasses != null && repasses.Count > 0) + { + foreach (Repasse repass in repasses) + { + if (repass.get_Id() != 0) + { + commited.get_RepasseRepository().Merge(repass); + } + else + { + commited.get_RepasseRepository().SaveOrUpdate(repass); + } + } + } + } + else + { + vendedor = commited.get_VendedorRepository().SaveOrUpdate(vendedor); + if (telefones != null) + { + telefones = commited.get_VendedorTelefoneRepository().Inserir(telefones, vendedor); + } + if (repasses != null && repasses.Count > 0) + { + foreach (Repasse repass1 in repasses) + { + repass1.set_Vendedor(vendedor); + commited.get_RepasseRepository().SaveOrUpdate(repass1); + } + } + } + vendedor.set_Telefones(telefones); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + if (Recursos.Usuario.get_Id() != 0) + { + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(tipoAcao); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + Vendedor vendedor1 = vendedor; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(vendedor1, jsonSerializerSetting)); + registroLog.set_EntidadeId(vendedor.get_Id()); + registroLog.set_Tela(15); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_112 = VendedorServico.u003cu003ec.u003cu003e9__11_2; + if (u003cu003e9_112 == null) + { + u003cu003e9_112 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + VendedorServico.u003cu003ec.u003cu003e9__11_2 = u003cu003e9_112; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_112); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + foreach (Repasse repasse1 in repasses) + { + RegistroLog registroLog1 = new RegistroLog(); + registroLog1.set_Acao(tipoAcao); + registroLog1.set_Usuario(Recursos.Usuario); + registroLog1.set_DataHora(networkTime); + JsonSerializerSettings jsonSerializerSetting1 = new JsonSerializerSettings(); + jsonSerializerSetting1.set_ReferenceLoopHandling(1); + registroLog1.set_Descricao(JsonConvert.SerializeObject(repasse1, jsonSerializerSetting1)); + registroLog1.set_EntidadeId(repasse1.get_Id()); + registroLog1.set_Tela(54); + registroLog1.set_Versao(LoginViewModel.VersaoAtual); + registroLog1.set_NomeMaquina(Environment.MachineName); + registroLog1.set_UsuarioMaquina(Environment.UserName); + IPAddress[] pAddressArray = hostEntry.AddressList; + Func u003cu003e9_113 = VendedorServico.u003cu003ec.u003cu003e9__11_3; + if (u003cu003e9_113 == null) + { + u003cu003e9_113 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + VendedorServico.u003cu003ec.u003cu003e9__11_3 = u003cu003e9_113; + } + IPAddress pAddress1 = ((IEnumerable)pAddressArray).FirstOrDefault(u003cu003e9_113); + if (pAddress1 != null) + { + str1 = pAddress1.ToString(); + } + else + { + str1 = null; + } + registroLog1.set_Ip(str1); + base.SaveLog(registroLog1, commited); + } + } + commited.Commit(); + vendedor4 = vendedor; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 241, num, new { vendedor = vendedor, repasses = repasses }, true); + continue; + } + return vendedor4; + } + return vendedor2; + }); + return vendedor3; + } + + public async Task Save(Repasse repasse) + { + int num = 3; + base.Sucesso = true; + DateTime networkTime = Funcoes.GetNetworkTime(); + Repasse repasse2 = repasse; + Repasse repasse3 = await Task.Run(() => { + Repasse repasse4; + string str; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + repasse2 = commited.get_RepasseRepository().Merge(repasse2); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(1); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + Repasse repasse1 = repasse; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(repasse1, jsonSerializerSetting)); + registroLog.set_EntidadeId(repasse.get_Id()); + registroLog.set_Tela(54); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_121 = VendedorServico.u003cu003ec.u003cu003e9__12_1; + if (u003cu003e9_121 == null) + { + u003cu003e9_121 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + VendedorServico.u003cu003ec.u003cu003e9__12_1 = u003cu003e9_121; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_121); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + repasse4 = repasse2; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 241, num, new { repasse = repasse }, true); + continue; + } + return repasse4; + } + return repasse; + }); + return repasse3; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Financeiro/BancosContasServico.cs b/Codemerx/Gestor.Application/Servicos/Financeiro/BancosContasServico.cs new file mode 100644 index 0000000..68c9a50 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Financeiro/BancosContasServico.cs @@ -0,0 +1,362 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Financeiro +{ + internal class BancosContasServico : BaseServico + { + public BancosContasServico() + { + } + + public async Task> BuscarBancos() + { + int num = 3; + List bancosContas1 = await Task.Run>(() => { + List bancosContas; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + bancosContas = read.get_BancosContasRepository().Find(); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 145, num, null, true); + continue; + } + return bancosContas; + } + return new List(); + }); + return bancosContas1; + } + + public async Task BuscarSaldo(DateTime inicio, long id) + { + int num = 3; + Saldo saldo1 = await Task.Run(() => { + Saldo saldo; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + saldo = read.get_SaldoRepository().BuscarPorData(inicio, id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 151, num, new { inicio = inicio, id = id }, true); + continue; + } + return saldo; + } + return new Saldo(); + }); + return saldo1; + } + + public async Task BuscarSaldoAberto(long id) + { + int num = 3; + Saldo saldo1 = await Task.Run(() => { + Saldo saldo; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + saldo = read.get_SaldoRepository().BuscarAberto(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 147, num, id, true); + continue; + } + return saldo; + } + return new Saldo(); + }); + return saldo1; + } + + public async Task> BuscarSaldoAberto(List ids) + { + int num = 3; + List saldos2 = await Task.Run>(() => { + List saldos; + while (num > 0) + { + try + { + List saldos1 = new List(); + using (UnitOfWork read = Instancia.Read) + { + ids.ForEach((long id) => { + Saldo saldo = read.get_SaldoRepository().BuscarAberto(id); + if (saldo == null) + { + return; + } + saldos1.Add(saldo); + }); + } + saldos = saldos1; + } + catch (Exception exception) + { + num = base.Registrar(exception, 148, num, ids, true); + continue; + } + return saldos; + } + return new List(); + }); + return saldos2; + } + + public async Task BuscarSaldoInicial(long id) + { + int num = 3; + Saldo saldo1 = await Task.Run(() => { + Saldo saldo; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + saldo = read.get_SaldoRepository().BuscarPorMenorData(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 151, num, new { id = id }, true); + continue; + } + return saldo; + } + return new Saldo(); + }); + return saldo1; + } + + public async Task> BuscarSaldos(long id) + { + int num = 3; + List saldos1 = await Task.Run>(() => { + List saldos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + saldos = read.get_SaldoRepository().BuscarPorConta(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 150, num, id, true); + continue; + } + return saldos; + } + return new List(); + }); + return saldos1; + } + + public async Task Delete(BancosContas bancosContas) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + List registroLogs = new List(); + try + { + using (UnitOfWork commited = Instancia.Commited) + { + registroLogs.Add(base.CreateLog(bancosContas.get_Id(), bancosContas.GetValorOriginal(), 26, 2)); + commited.get_BancosContasRepository().Delete(bancosContas.get_Id()); + base.SaveLog(registroLogs, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 246, num, bancosContas, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task DeleteSaldo(Saldo saldo) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + List registroLogs = new List(); + try + { + using (UnitOfWork commited = Instancia.Commited) + { + registroLogs.Add(base.CreateLog(saldo.get_Id(), saldo.GetValorOriginal(), 26, 2)); + commited.get_SaldoRepository().Delete(saldo.get_Id()); + base.SaveLog(registroLogs, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 248, num, saldo, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task FecharSaldo(Saldo saldo) + { + int num = 3; + Saldo saldo1 = await Task.Run(() => { + Saldo saldo2; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + saldo2 = read.get_LancamentoRepository().FecharSaldo(saldo); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 149, num, saldo, true); + continue; + } + return saldo2; + } + return new Saldo(); + }); + return saldo1; + } + + public async Task Save(BancosContas bancosContas) + { + int num = 3; + base.Sucesso = true; + BancosContas bancosConta1 = bancosContas; + BancosContas bancosConta2 = await Task.Run(() => { + BancosContas bancosConta; + bool flag; + while (num > 0) + { + List registroLogs = new List(); + bancosContas = bancosConta1; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + flag = (bancosContas.get_Id() == 0 ? false : true); + if (flag) + { + registroLogs.Add(base.CreateLog(bancosContas.get_Id(), bancosContas, 26)); + } + bancosContas = (bancosContas.get_Id() == 0 ? commited.get_BancosContasRepository().SaveOrUpdate(bancosContas) : commited.get_BancosContasRepository().Merge(bancosContas)); + if (!flag) + { + registroLogs.Add(base.CreateLog(bancosContas.get_Id(), bancosContas.GetValorOriginal(), 26, 0)); + } + base.SaveLog(registroLogs, commited); + commited.Commit(); + bancosConta = bancosContas; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 245, num, bancosContas, true); + continue; + } + return bancosConta; + } + return bancosConta1; + }); + return bancosConta2; + } + + public async Task Save(Saldo saldo) + { + int num = 3; + base.Sucesso = true; + Saldo saldo1 = saldo; + Saldo saldo2 = await Task.Run(() => { + Saldo saldo3; + bool flag; + while (num > 0) + { + List registroLogs = new List(); + saldo = saldo1; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + flag = (saldo.get_Id() == 0 ? false : true); + if (flag) + { + registroLogs.Add(base.CreateLog(saldo.get_Conta().get_Id(), saldo, 26)); + } + saldo = (saldo.get_Id() == 0 ? commited.get_SaldoRepository().SaveOrUpdate(saldo) : commited.get_SaldoRepository().Merge(saldo)); + if (!flag) + { + registroLogs.Add(base.CreateLog(saldo.get_Conta().get_Id(), saldo.GetValorOriginal(), 26, 0)); + } + base.SaveLog(registroLogs, commited); + commited.Commit(); + saldo3 = saldo; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 247, num, saldo, true); + continue; + } + return saldo3; + } + return saldo1; + }); + return saldo2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Financeiro/CentroServico.cs b/Codemerx/Gestor.Application/Servicos/Financeiro/CentroServico.cs new file mode 100644 index 0000000..7d16a58 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Financeiro/CentroServico.cs @@ -0,0 +1,92 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Financeiro +{ + internal class CentroServico : BaseServico + { + public CentroServico() + { + } + + public async Task> BuscarCentros() + { + int num = 3; + List centros1 = await Task.Run>(() => { + List centros; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + centros = read.get_CentroRepository().Find(); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 153, num, null, true); + continue; + } + return centros; + } + return new List(); + }); + return centros1; + } + + public async Task Save(Centro centro) + { + int num = 3; + base.Sucesso = true; + Centro centro1 = centro; + Centro centro2 = await Task.Run(() => { + Centro centro3; + bool flag; + while (num > 0) + { + List registroLogs = new List(); + centro = centro1; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + flag = (centro.get_Id() == 0 ? false : true); + if (flag) + { + registroLogs.Add(base.CreateLog(centro.get_Id(), centro, 29)); + } + centro = (centro.get_Id() == 0 ? commited.get_CentroRepository().SaveOrUpdate(centro) : commited.get_CentroRepository().Merge(centro)); + if (!flag) + { + registroLogs.Add(base.CreateLog(centro.get_Id(), centro.GetValorOriginal(), 29, 0)); + } + base.SaveLog(registroLogs, commited); + commited.Commit(); + centro3 = centro; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 249, num, centro, true); + continue; + } + return centro3; + } + return centro1; + }); + return centro2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Financeiro/FinanceiroServico.cs b/Codemerx/Gestor.Application/Servicos/Financeiro/FinanceiroServico.cs new file mode 100644 index 0000000..817dca0 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Financeiro/FinanceiroServico.cs @@ -0,0 +1,738 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Financeiro.Relatorios; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Financeiro +{ + public class FinanceiroServico : BaseServico + { + public FinanceiroServico() + { + } + + public async Task> AddRange(List lancamentos) + { + int num = 3; + base.Sucesso = true; + DateTime networkTime = Funcoes.GetNetworkTime(); + List lancamentos1 = lancamentos; + List lancamentos2 = await Task.Run>(() => { + List lancamentos3; + while (num > 0) + { + List registroLogs = new List(); + lancamentos = lancamentos1; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + ControleFinanceiro controle = lancamentos.First().get_Controle(); + controle = (controle.get_Id() == 0 ? commited.get_ControleFinanceiroRepository().SaveOrUpdate(controle) : commited.get_ControleFinanceiroRepository().Merge(controle)); + lancamentos.ForEach((Lancamento x) => { + x.set_Controle(controle); + x.set_DataLancamento(new DateTime?(networkTime)); + }); + lancamentos = commited.get_LancamentoRepository().AddRange(lancamentos); + lancamentos.ForEach((Lancamento x) => this.logs.Add(base.CreateLog(x.get_Id(), x.GetValorOriginal(), 25, 0))); + base.SaveLog(registroLogs, commited); + commited.Commit(); + lancamentos3 = lancamentos; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 279, num, lancamentos, true); + continue; + } + return lancamentos3; + } + return lancamentos1; + }); + return lancamentos2; + } + + public async Task> Atualizar(List lancamentos) + { + int num = 3; + base.Sucesso = true; + Funcoes.GetNetworkTime(); + List lancamentos1 = lancamentos; + List lancamentos2 = await Task.Run>(() => { + List lancamentos3; + while (num > 0) + { + List registroLogs = new List(); + lancamentos = lancamentos1; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + lancamentos.ForEach((Lancamento lancamento) => { + registroLogs.Add(base.CreateLog(lancamento.get_Id(), lancamento, 25)); + lancamento.set_Controle(commited.get_ControleFinanceiroRepository().Merge(lancamento.get_Controle())); + lancamento = commited.get_LancamentoRepository().Merge(lancamento); + }); + base.SaveLog(registroLogs, commited); + commited.Commit(); + lancamentos3 = lancamentos; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 280, num, lancamentos, true); + continue; + } + return lancamentos3; + } + return lancamentos1; + }); + return lancamentos2; + } + + public async Task> BuscarFechamento(FiltroFinanceiro filtro) + { + int num = 3; + List lancamentos1 = await Task.Run>(() => { + List lancamentos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + lancamentos = read.get_LancamentoRepository().Fechamento(filtro); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 294, num, filtro, true); + continue; + } + return lancamentos; + } + return new List(); + }); + return lancamentos1; + } + + public async Task BuscarLancamento(long id, int parcela) + { + int num = 3; + Lancamento lancamento1 = await Task.Run(() => { + Lancamento lancamento; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + lancamento = read.get_LancamentoRepository().FindByControle(id, parcela); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 163, num, new { id = id, parcela = parcela }, true); + continue; + } + return lancamento; + } + return new Lancamento(); + }); + return lancamento1; + } + + public async Task BuscarLancamento(long id) + { + int num = 3; + Lancamento lancamento1 = await Task.Run(() => { + Lancamento lancamento; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + lancamento = read.get_LancamentoRepository().FindById(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 164, num, id, true); + continue; + } + return lancamento; + } + return new Lancamento(); + }); + return lancamento1; + } + + public async Task> BuscarLancamentos(DateTime inicio, DateTime fim, StatusLancamento status) + { + int num = 3; + List lancamentos1 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List lancamentos = read.get_LancamentoRepository().Find(inicio, fim, status); + Func u003cu003e9_41 = FinanceiroServico.u003cu003ec.u003cu003e9__4_1; + if (u003cu003e9_41 == null) + { + u003cu003e9_41 = (Lancamento x) => x.get_Vencimento(); + FinanceiroServico.u003cu003ec.u003cu003e9__4_1 = u003cu003e9_41; + } + list = lancamentos.OrderByDescending(u003cu003e9_41).ToList(); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 160, num, new { inicio = inicio, fim = fim, status = status }, true); + continue; + } + return list; + } + return new List(); + }); + return lancamentos1; + } + + public async Task> BuscarLancamentos(DateTime inicio, DateTime fim, long conta) + { + int num = 3; + List lancamentos1 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List lancamentos = read.get_LancamentoRepository().FindLancamentosByConta(inicio, fim, conta); + Func u003cu003e9_61 = FinanceiroServico.u003cu003ec.u003cu003e9__6_1; + if (u003cu003e9_61 == null) + { + u003cu003e9_61 = (Lancamento x) => x.get_Vencimento(); + FinanceiroServico.u003cu003ec.u003cu003e9__6_1 = u003cu003e9_61; + } + list = lancamentos.OrderByDescending(u003cu003e9_61).ToList(); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 165, num, new { inicio = inicio, fim = fim, conta = conta }, true); + continue; + } + return list; + } + return new List(); + }); + return lancamentos1; + } + + public async Task> BuscarLancamentosPersonalizados(DateTime inicio, DateTime fim, StatusLancamento status, FiltroLancamentoData filtrodata) + { + int num = 3; + List lancamentos1 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List lancamentos = read.get_LancamentoRepository().FindPersonalizado(inicio, fim, status, filtrodata); + Func u003cu003e9_71 = FinanceiroServico.u003cu003ec.u003cu003e9__7_1; + if (u003cu003e9_71 == null) + { + u003cu003e9_71 = (Lancamento x) => x.get_Vencimento(); + FinanceiroServico.u003cu003ec.u003cu003e9__7_1 = u003cu003e9_71; + } + list = lancamentos.OrderByDescending(u003cu003e9_71).ToList(); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 160, num, new { inicio = inicio, fim = fim, status = status }, true); + continue; + } + return list; + } + return new List(); + }); + return lancamentos1; + } + + public async Task> BuscarLancamentosPorBaixa(DateTime inicio, DateTime fim) + { + int num = 3; + List lancamentos1 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List lancamentos = read.get_LancamentoRepository().FindByBaixa(inicio, fim); + Func u003cu003e9_81 = FinanceiroServico.u003cu003ec.u003cu003e9__8_1; + if (u003cu003e9_81 == null) + { + u003cu003e9_81 = (Lancamento x) => x.get_Baixa(); + FinanceiroServico.u003cu003ec.u003cu003e9__8_1 = u003cu003e9_81; + } + list = lancamentos.OrderByDescending(u003cu003e9_81).ToList(); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 161, num, new { inicio = inicio, fim = fim }, true); + continue; + } + return list; + } + return new List(); + }); + return lancamentos1; + } + + public async Task> BuscarLancamentosPorConta(DateTime inicio, DateTime fim, long id) + { + int num = 3; + List extratoContas1 = await Task.Run>(() => { + List extratoContas; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + extratoContas = read.get_LancamentoRepository().FindByConta(inicio, fim, id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 165, num, new { inicio = inicio, fim = fim, id = id }, true); + continue; + } + return extratoContas; + } + return new List(); + }); + return extratoContas1; + } + + public async Task> BuscarLancamentosPorControle(long id) + { + int num = 3; + List lancamentos1 = await Task.Run>(() => { + List lancamentos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + lancamentos = read.get_LancamentoRepository().FindByControle(id, 2); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 158, num, new { id = id }, true); + continue; + } + return lancamentos; + } + return new List(); + }); + return lancamentos1; + } + + public async Task> BuscarLancamentosPorFornecedor(long id, StatusLancamento status) + { + int num = 3; + List lancamentos1 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List lancamentos = read.get_LancamentoRepository().FindByFornecedor(id, status); + Func u003cu003e9_11 = FinanceiroServico.u003cu003ec.u003cu003e9__1_1; + if (u003cu003e9_11 == null) + { + u003cu003e9_11 = (Lancamento x) => x.get_Vencimento(); + FinanceiroServico.u003cu003ec.u003cu003e9__1_1 = u003cu003e9_11; + } + list = lancamentos.OrderByDescending(u003cu003e9_11).ToList(); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 157, num, new { id = id, status = status }, true); + continue; + } + return list; + } + return new List(); + }); + return lancamentos1; + } + + public async Task> BuscarLancamentosPorFornecedor(long id, DateTime date, Sinal sinal) + { + int num = 3; + List lancamentos1 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List lancamentos = read.get_LancamentoRepository().FindByFornecedor(id, date, sinal); + Func u003cu003e9_21 = FinanceiroServico.u003cu003ec.u003cu003e9__2_1; + if (u003cu003e9_21 == null) + { + u003cu003e9_21 = (Lancamento x) => x.get_Vencimento(); + FinanceiroServico.u003cu003ec.u003cu003e9__2_1 = u003cu003e9_21; + } + list = lancamentos.OrderByDescending(u003cu003e9_21).ToList(); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 157, num, new { id = id, date = date }, true); + continue; + } + return list; + } + return new List(); + }); + return lancamentos1; + } + + public async Task> BuscarLancamentosPorLancamento(DateTime inicio, DateTime fim, StatusLancamento status) + { + int num = 3; + List lancamentos1 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List lancamentos = read.get_LancamentoRepository().FindByLancamento(inicio, fim, status); + Func u003cu003e9_51 = FinanceiroServico.u003cu003ec.u003cu003e9__5_1; + if (u003cu003e9_51 == null) + { + u003cu003e9_51 = (Lancamento x) => x.get_DataLancamento(); + FinanceiroServico.u003cu003ec.u003cu003e9__5_1 = u003cu003e9_51; + } + list = lancamentos.OrderByDescending(u003cu003e9_51).ToList(); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 329, num, new { inicio = inicio, fim = fim, status = status }, true); + continue; + } + return list; + } + return new List(); + }); + return lancamentos1; + } + + public async Task> BuscarLancamentosPorPagamento(DateTime inicio, DateTime fim) + { + int num = 3; + List lancamentos1 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List lancamentos = read.get_LancamentoRepository().FindByPagamento(inicio, fim); + Func u003cu003e9_91 = FinanceiroServico.u003cu003ec.u003cu003e9__9_1; + if (u003cu003e9_91 == null) + { + u003cu003e9_91 = (Lancamento x) => x.get_Pagamento(); + FinanceiroServico.u003cu003ec.u003cu003e9__9_1 = u003cu003e9_91; + } + list = lancamentos.OrderBy(u003cu003e9_91).ToList(); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 162, num, new { inicio = inicio, fim = fim }, true); + continue; + } + return list; + } + return new List(); + }); + return lancamentos1; + } + + public async Task Excluir(List lancamentos) + { + int num = 3; + Funcoes.GetNetworkTime(); + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + List registroLogs = new List(); + try + { + using (UnitOfWork commited = Instancia.Commited) + { + lancamentos.ForEach((Lancamento x) => { + registroLogs.Add(base.CreateLog(x.get_Id(), x.GetValorOriginal(), 25, 2)); + if (commited.get_LancamentoRepository().FindByControle(x.get_Controle().get_Id(), 2).Count == 1) + { + commited.get_ControleFinanceiroRepository().Delete(x.get_Controle().get_Id()); + return; + } + x.get_Controle().set_Parcelas(x.get_Controle().get_Parcelas() - 1); + commited.get_ControleFinanceiroRepository().Merge(x.get_Controle()); + commited.get_LancamentoRepository().Delete(x.get_Id()); + }); + base.SaveLog(registroLogs, commited); + commited.Commit(); + } + flag = true; + } + catch (Exception exception) + { + num = base.Registrar(exception, 282, num, lancamentos, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task Excluir(Lancamento lancamento) + { + int num = 3; + Funcoes.GetNetworkTime(); + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + List registroLogs = new List(); + try + { + using (UnitOfWork commited = Instancia.Commited) + { + registroLogs.Add(base.CreateLog(lancamento.get_Id(), lancamento.GetValorOriginal(), 25, 2)); + if (commited.get_LancamentoRepository().FindByControle(lancamento.get_Controle().get_Id(), 2).Count != 1) + { + lancamento.get_Controle().set_Parcelas(lancamento.get_Controle().get_Parcelas() - 1); + commited.get_ControleFinanceiroRepository().Merge(lancamento.get_Controle()); + commited.get_LancamentoRepository().Delete(lancamento.get_Id()); + } + else + { + commited.get_ControleFinanceiroRepository().Delete(lancamento.get_Controle().get_Id()); + } + base.SaveLog(registroLogs, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 282, num, lancamento, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task> IncluirRange(List lancamentos) + { + int num = 3; + base.Sucesso = true; + Funcoes.GetNetworkTime(); + List lancamentos1 = lancamentos; + List lancamentos2 = await Task.Run>(() => { + List lancamentos3; + while (num > 0) + { + List registroLogs = new List(); + lancamentos = lancamentos1; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + lancamentos.ForEach((Lancamento lancamento) => { + lancamento.set_Controle(commited.get_ControleFinanceiroRepository().Merge(lancamento.get_Controle())); + lancamento = commited.get_LancamentoRepository().SaveOrUpdate(lancamento); + registroLogs.Add(base.CreateLog(lancamento.get_Id(), lancamento.GetValorOriginal(), 25, 0)); + }); + base.SaveLog(registroLogs, commited); + commited.Commit(); + lancamentos3 = lancamentos; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 281, num, lancamentos, true); + continue; + } + return lancamentos3; + } + return lancamentos1; + }); + return lancamentos2; + } + + public async Task Save(Lancamento lancamento) + { + int num = 3; + base.Sucesso = true; + DateTime networkTime = Funcoes.GetNetworkTime(); + Lancamento lancamento1 = lancamento; + Lancamento lancamento2 = await Task.Run(() => { + Lancamento lancamento3; + bool flag; + while (num > 0) + { + List registroLogs = new List(); + lancamento = lancamento1; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + flag = (lancamento.get_Id() == 0 ? false : true); + if (!flag) + { + lancamento.set_DataLancamento(new DateTime?(networkTime)); + } + if (flag) + { + registroLogs.Add(base.CreateLog(lancamento.get_Id(), lancamento, 25)); + } + ControleFinanceiro controle = lancamento.get_Controle(); + controle = (controle.get_Id() == 0 ? commited.get_ControleFinanceiroRepository().SaveOrUpdate(controle) : commited.get_ControleFinanceiroRepository().Merge(controle)); + lancamento.set_Controle(controle); + lancamento = (lancamento.get_Id() == 0 ? commited.get_LancamentoRepository().SaveOrUpdate(lancamento) : commited.get_LancamentoRepository().Merge(lancamento)); + if (!flag) + { + registroLogs.Add(base.CreateLog(lancamento.get_Id(), lancamento.GetValorOriginal(), 25, 0)); + } + base.SaveLog(registroLogs, commited); + commited.Commit(); + lancamento3 = lancamento; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 279, num, lancamento, true); + continue; + } + return lancamento3; + } + return lancamento1; + }); + return lancamento2; + } + + public async Task TemLancamentosPorFornecedor(long id) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + flag = read.get_LancamentoRepository().HasByFornecedor(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 154, num, id, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task Transferir(Lancamento lancamentoOrigem, Lancamento lancamentoDestino) + { + int num = 3; + Lancamento lancamento = lancamentoOrigem; + Lancamento lancamento1 = lancamentoDestino; + Funcoes.GetNetworkTime(); + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + List registroLogs = new List(); + lancamentoOrigem = lancamento; + lancamentoDestino = lancamento1; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + ControleFinanceiro controle = lancamentoOrigem.get_Controle(); + controle = commited.get_ControleFinanceiroRepository().SaveOrUpdate(controle); + lancamentoOrigem.set_Controle(controle); + lancamentoDestino.set_Controle(controle); + lancamentoOrigem = commited.get_LancamentoRepository().SaveOrUpdate(lancamentoOrigem); + lancamentoDestino = commited.get_LancamentoRepository().SaveOrUpdate(lancamentoDestino); + registroLogs.Add(base.CreateLog(lancamentoOrigem.get_Id(), lancamentoOrigem.GetValorOriginal(), 25, 0)); + registroLogs.Add(base.CreateLog(lancamentoDestino.get_Id(), lancamentoDestino.GetValorOriginal(), 25, 0)); + base.SaveLog(registroLogs, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 283, num, new { lancamentoOrigem = lancamentoOrigem, lancamentoDestino = lancamentoDestino }, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Financeiro/FornecedorServico.cs b/Codemerx/Gestor.Application/Servicos/Financeiro/FornecedorServico.cs new file mode 100644 index 0000000..674f46a --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Financeiro/FornecedorServico.cs @@ -0,0 +1,123 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Financeiro +{ + public class FornecedorServico : BaseServico + { + public FornecedorServico() + { + } + + public async Task> BuscarFornecedores() + { + int num = 3; + List fornecedors1 = await Task.Run>(() => { + List fornecedors; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + fornecedors = read.get_FornecedorRepository().Find(); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 166, num, null, true); + continue; + } + return fornecedors; + } + return new List(); + }); + return fornecedors1; + } + + public async Task Delete(Fornecedor fornecedor) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + List registroLogs = new List(); + try + { + using (UnitOfWork commited = Instancia.Commited) + { + registroLogs.Add(base.CreateLog(fornecedor.get_Id(), fornecedor.GetValorOriginal(), 24, 2)); + commited.get_FornecedorRepository().Delete(fornecedor.get_Id()); + base.SaveLog(registroLogs, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 244, num, fornecedor, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task Save(Fornecedor fornecedor) + { + int num = 3; + base.Sucesso = true; + Fornecedor fornecedor1 = fornecedor; + Fornecedor fornecedor2 = await Task.Run(() => { + Fornecedor fornecedor3; + while (num > 0) + { + List registroLogs = new List(); + fornecedor = fornecedor1; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + TipoAcao tipoAcao = (fornecedor.get_Id() == 0 ? 0 : 1); + if (tipoAcao == 1) + { + registroLogs.Add(base.CreateLog(fornecedor.get_Id(), fornecedor, 24)); + } + fornecedor = (tipoAcao == null ? commited.get_FornecedorRepository().SaveOrUpdate(fornecedor) : commited.get_FornecedorRepository().Merge(fornecedor)); + if (tipoAcao == null) + { + registroLogs.Add(base.CreateLog(fornecedor.get_Id(), fornecedor.GetValorOriginal(), 24, 0)); + } + base.SaveLog(registroLogs, commited); + commited.Commit(); + fornecedor3 = fornecedor; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 243, num, fornecedor, true); + continue; + } + return fornecedor3; + } + return fornecedor1; + }); + return fornecedor2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Financeiro/PlanoServico.cs b/Codemerx/Gestor.Application/Servicos/Financeiro/PlanoServico.cs new file mode 100644 index 0000000..9fc078a --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Financeiro/PlanoServico.cs @@ -0,0 +1,120 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Financeiro +{ + internal class PlanoServico : BaseServico + { + public PlanoServico() + { + } + + public async Task> BuscarPlanos() + { + int num = 3; + List planos1 = await Task.Run>(() => { + List planos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + planos = read.get_PlanosRepository().Find(); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 167, num, null, true); + continue; + } + return planos; + } + return new List(); + }); + return planos1; + } + + public async Task Save(Plano plano) + { + int num = 3; + base.Sucesso = true; + Plano plano2 = plano; + Plano plano3 = await Task.Run(() => { + Plano plano4; + string str; + while (num > 0) + { + plano = plano2; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + TipoAcao tipoAcao = (plano.get_Id() == 0 ? 0 : 1); + plano = (plano.get_Id() == 0 ? commited.get_PlanoRepository().SaveOrUpdate(plano) : commited.get_PlanoRepository().Merge(plano)); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(tipoAcao); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(Funcoes.GetNetworkTime()); + Plano plano1 = plano; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(plano1, jsonSerializerSetting)); + registroLog.set_EntidadeId(plano.get_Id()); + registroLog.set_Tela(27); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_01 = PlanoServico.u003cu003ec.u003cu003e9__0_1; + if (u003cu003e9_01 == null) + { + u003cu003e9_01 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + PlanoServico.u003cu003ec.u003cu003e9__0_1 = u003cu003e9_01; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_01); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + plano4 = plano; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 250, num, plano, true); + continue; + } + return plano4; + } + return plano2; + }); + return plano3; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Financeiro/PlanosServico.cs b/Codemerx/Gestor.Application/Servicos/Financeiro/PlanosServico.cs new file mode 100644 index 0000000..b00efbe --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Financeiro/PlanosServico.cs @@ -0,0 +1,93 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Financeiro +{ + internal class PlanosServico : BaseServico + { + public PlanosServico() + { + } + + internal async Task> BuscarPlanos() + { + int num = 3; + ObservableCollection observableCollection1 = await Task.Run>(() => { + ObservableCollection observableCollection; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + observableCollection = new ObservableCollection(read.get_PlanosRepository().Find()); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 168, num, null, true); + continue; + } + return observableCollection; + } + return new ObservableCollection(); + }); + return observableCollection1; + } + + public async Task Save(Planos planos) + { + int num = 3; + base.Sucesso = true; + Planos plano1 = planos; + Planos plano2 = await Task.Run(() => { + Planos plano; + bool flag; + while (num > 0) + { + List registroLogs = new List(); + planos = plano1; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + flag = (planos.get_Id() == 0 ? false : true); + if (flag) + { + registroLogs.Add(base.CreateLog(planos.get_Id(), planos, 28)); + } + planos = (planos.get_Id() == 0 ? commited.get_PlanosRepository().SaveOrUpdate(planos) : commited.get_PlanosRepository().Merge(planos)); + if (!flag) + { + registroLogs.Add(base.CreateLog(planos.get_Id(), planos.GetValorOriginal(), 28, 0)); + } + base.SaveLog(registroLogs, commited); + commited.Commit(); + plano = planos; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 251, num, planos, true); + continue; + } + return plano; + } + return plano1; + }); + return plano2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Generic/BaseServico.cs b/Codemerx/Gestor.Application/Servicos/Generic/BaseServico.cs new file mode 100644 index 0000000..1570e96 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Generic/BaseServico.cs @@ -0,0 +1,2567 @@ +using Agger.Registro; +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels; +using Gestor.Common.Security; +using Gestor.Common.Validation; +using Gestor.Infrastructure.Helpers; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.API; +using Gestor.Model.Common; +using Gestor.Model.Domain.Aggilizador; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using Newtonsoft.Json; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Generic +{ + public class BaseServico + { + private const int UnathorizedSsoCode = 401; + + private const int NotFoundSsoCode = 404; + + public bool Sucesso + { + get; + set; + } + + public BaseServico() + { + } + + internal async Task AddOrUpdateUsuarioSso(Usuario usuario, string documentoEmpresa, string ssoId = null) + { + UserSso userSso; + HttpResponseMessage httpResponseMessage; + UserSso userSso1; + using (HttpClient httpClient = new HttpClient()) + { + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + Uri apiSso = Address.get_ApiSso(); + string[] strArrays = new string[] { "user" }; + Uri uri = apiSso.Append(strArrays); + httpClient.get_DefaultRequestHeaders().TryAddWithoutValidation("Authorization", string.Concat("Bearer ", usuario.get_TokenSso())); + UserSso userSso2 = usuario.ToUserSso(ApplicationHelper.NumeroSerial, documentoEmpresa, ssoId); + httpResponseMessage = (userSso2.get_Id() != null ? await httpClient.PutAsync(uri, userSso2.ToHttpContent(null, "application/json")) : await httpClient.PostAsync(uri, userSso2.ToHttpContent(null, "application/json"))); + HttpResponseMessage httpResponseMessage1 = httpResponseMessage; + if (!httpResponseMessage1.get_IsSuccessStatusCode()) + { + userSso1 = null; + } + else + { + userSso1 = JsonConvert.DeserializeObject(await httpResponseMessage1.get_Content().ReadAsStringAsync()); + } + userSso = userSso1; + } + return userSso; + } + + public async Task ArquivoDigital() + { + int num = 3; + ControleArquivoDigital controleArquivoDigital1 = await Task.Run(() => { + ControleArquivoDigital controleArquivoDigital; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + controleArquivoDigital = read.get_IndiceArquivoDigitalRepository().BuscarBanco(); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 188, num, null, true); + continue; + } + return controleArquivoDigital; + } + return new ControleArquivoDigital(); + }); + return controleArquivoDigital1; + } + + public async Task ArquivoDigital(string banco) + { + int num = 3; + ControleArquivoDigital controleArquivoDigital1 = await Task.Run(() => { + ControleArquivoDigital controleArquivoDigital; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + controleArquivoDigital = read.get_IndiceArquivoDigitalRepository().ConsultarBanco(banco); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 188, num, banco, true); + continue; + } + return controleArquivoDigital; + } + return new ControleArquivoDigital(); + }); + return controleArquivoDigital1; + } + + public async Task> ArquivoVinculo(List ids, TipoArquivoVinculo type) + { + int num = 3; + List arquivoVinculos1 = await Task.Run>(() => { + List arquivoVinculos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + arquivoVinculos = read.get_VinculoDocumentoRepository().BuscarArquivos(ids, type); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 293, num, null, true); + continue; + } + return arquivoVinculos; + } + return null; + }); + return arquivoVinculos1; + } + + private async Task AtualizarUsuarios() + { + bool count; + try + { + if (!Gestor.Common.Validation.ValidationHelper.IsNullOrEmpty(Recursos.Usuario.get_TokenSso())) + { + List userSsos = await this.BuscarUsuariosSso(); + List userSsos1 = userSsos; + if (userSsos1 != null) + { + count = userSsos1.Count == 0; + } + else + { + count = false; + } + if (count || userSsos == null) + { + return; + } + else + { + List usuarios = await this.BuscarUsuariosAsync(); + foreach (UserSso userSso in userSsos) + { + Usuario usuario = usuarios.FirstOrDefault((Usuario u) => { + if (u.get_SsoId() != null) + { + return userSso.get_Id() == u.get_SsoId(); + } + return u.get_Login() == userSso.get_Username(); + }); + if (usuario != null && (userSso.get_IsDeleted() != usuario.get_Excluido() || Gestor.Common.Validation.ValidationHelper.NotEquals(userSso.get_Password(), usuario.get_Senha()) || Gestor.Common.Validation.ValidationHelper.NotEquals(userSso.get_Name(), usuario.get_Nome()) || Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(userSso.get_Email()) && Gestor.Common.Validation.ValidationHelper.NotEquals(userSso.get_Email(), usuario.get_Email()) || Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(userSso.get_Document()) && Gestor.Common.Validation.ValidationHelper.NotEquals(userSso.get_Document(), usuario.get_Documento().Clear()) || Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(userSso.get_Phone()) && Gestor.Common.Validation.ValidationHelper.NotEquals(userSso.get_Phone(), string.Concat(usuario.get_Prefixo(), usuario.get_Telefone()).Clear()) || Gestor.Common.Validation.ValidationHelper.IsNullOrEmpty(usuario.get_SsoId()))) + { + string phone = userSso.get_Phone(); + usuario.set_Nome(userSso.get_Name()); + usuario.set_Documento(userSso.get_Document()); + if (Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(phone) && phone.Length > 3) + { + usuario.set_Prefixo(phone.Substring(0, 2)); + usuario.set_Telefone(phone.Substring(2, phone.Length - 2)); + } + usuario.set_Login(userSso.get_Username()); + usuario.set_Senha(userSso.get_Password()); + usuario.set_Email(userSso.get_Email()); + usuario.set_Excluido(userSso.get_IsDeleted()); + usuario.set_SsoId(userSso.get_Id()); + using (UnitOfWork commited = Instancia.Commited) + { + commited.get_UsuarioRepository().Merge(usuario); + commited.Commit(); + } + } + if (usuario != null) + { + continue; + } + using (UnitOfWork read = Instancia.Read) + { + Empresa empresa = read.get_EmpresaRepository().FindByDocumento(userSso.get_CustomerDocument()); + Usuario usuario1 = new Usuario(); + usuario1.set_IdEmpresa(empresa.get_Id()); + usuario1.set_Nome(userSso.get_Name()); + usuario1.set_Documento(userSso.get_Document()); + usuario1.set_Login(userSso.get_Username()); + usuario1.set_Senha(userSso.get_Password()); + usuario1.set_Email(userSso.get_Email()); + usuario1.set_SsoId(userSso.get_Id()); + usuario1.set_Excluido(userSso.get_IsDeleted()); + usuario1.set_Administrador(false); + usuario1.set_PermissaoAggilizador(new long?((long)1)); + usuario = usuario1; + string str = userSso.get_Phone(); + if (Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(str) && str.Length > 3) + { + usuario.set_Prefixo(str.Substring(0, 2)); + usuario.set_Telefone(str.Substring(2, str.Length - 2)); + } + } + using (UnitOfWork unitOfWork = Instancia.Commited) + { + unitOfWork.get_UsuarioRepository().SaveOrUpdate(usuario); + unitOfWork.Commit(); + } + } + userSsos = null; + } + } + else + { + return; + } + } + catch (Exception exception) + { + this.Registrar(exception, 239, 1, null, true); + } + } + + private static async Task AtualizaUsuariosSso(List usuarios) + { + List list; + List usuarios1 = usuarios; + IEnumerable excluido = + from usuario in usuarios1 + where !usuario.get_Excluido() + select usuario; + if (excluido != null) + { + list = excluido.ToList(); + } + else + { + list = null; + } + usuarios = list; + foreach (Usuario usuario1 in usuarios) + { + UserSso userSso = new UserSso(); + userSso.set_Name(usuario1.get_Nome()); + userSso.set_Username(usuario1.get_Login()); + userSso.set_Password(usuario1.get_Senha()); + userSso.set_Email(usuario1.get_Email()); + userSso.set_Phone(usuario1.get_Telefone()); + userSso.set_IsDeleted(usuario1.get_Excluido()); + userSso.set_Id(usuario1.get_SsoId()); + string documento = Recursos.Empresas.FirstOrDefault((Empresa x) => x.get_Id() == usuario1.get_IdEmpresa()).get_Documento(); + await (new BaseServico()).AddOrUpdateUsuarioSso(usuario1, documento, usuario1.get_SsoId()); + } + } + + public async Task BancosContasUtilizado(long id) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + flag = read.get_LancamentoRepository().BancosContasUtilizado(id); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 155, num, id, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + internal async Task> BuscaCoberturas() + { + int num = 3; + List coberturaPadraos1 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List coberturaPadraos = read.get_CoberturaPadraoRepository().Find(); + Func u003cu003e9_511 = BaseServico.u003cu003ec.u003cu003e9__51_1; + if (u003cu003e9_511 == null) + { + u003cu003e9_511 = (CoberturaPadrao x) => x.get_Descricao(); + BaseServico.u003cu003ec.u003cu003e9__51_1 = u003cu003e9_511; + } + list = coberturaPadraos.OrderBy(u003cu003e9_511).ToList(); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 58, num, null, true); + continue; + } + return list; + } + return new List(); + }); + return coberturaPadraos1; + } + + public async Task> BuscarAdiantamentoAsync(Vendedor vendedor) + { + int num = 3; + List adiantamentos2 = await Task.Run>(() => { + List adiantamentos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List adiantamentos1 = read.get_AdiantamentoRepository().Find(vendedor.get_Id()); + Func u003cu003e9_371 = BaseServico.u003cu003ec.u003cu003e9__37_1; + if (u003cu003e9_371 == null) + { + u003cu003e9_371 = (Adiantamento x) => x.get_Id(); + BaseServico.u003cu003ec.u003cu003e9__37_1 = u003cu003e9_371; + } + adiantamentos = new List(adiantamentos1.OrderBy(u003cu003e9_371)); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 185, num, vendedor, true); + continue; + } + return adiantamentos; + } + return new List(); + }); + return adiantamentos2; + } + + public async Task> BuscarAgendasAsync() + { + int num = 3; + List agendas2 = await Task.Run>(() => { + List agendas; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List agendas1 = read.get_AgendaRepository().Find(); + Func u003cu003e9_461 = BaseServico.u003cu003ec.u003cu003e9__46_1; + if (u003cu003e9_461 == null) + { + u003cu003e9_461 = (Agenda x) => x.get_Id(); + BaseServico.u003cu003ec.u003cu003e9__46_1 = u003cu003e9_461; + } + agendas = new List(agendas1.OrderBy(u003cu003e9_461)); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 129, num, null, true); + continue; + } + return agendas; + } + return new List(); + }); + return agendas2; + } + + internal async Task> BuscarAtividade(string value) + { + int num = 3; + List atividades1 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List atividades = read.get_AtividadeRepository().Find(value); + Func u003cu003e9_161 = BaseServico.u003cu003ec.u003cu003e9__16_1; + if (u003cu003e9_161 == null) + { + u003cu003e9_161 = (Atividade x) => x.get_Nome(); + BaseServico.u003cu003ec.u003cu003e9__16_1 = u003cu003e9_161; + } + list = atividades.OrderBy(u003cu003e9_161).ToList(); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 181, num, value, true); + continue; + } + return list; + } + return new List(); + }); + return atividades1; + } + + internal async Task> BuscarBanco(string value) + { + int num = 3; + List bancos1 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List bancos = read.get_BancoRepository().Find(value); + Func u003cu003e9_171 = BaseServico.u003cu003ec.u003cu003e9__17_1; + if (u003cu003e9_171 == null) + { + u003cu003e9_171 = (Banco x) => x.get_Nome(); + BaseServico.u003cu003ec.u003cu003e9__17_1 = u003cu003e9_171; + } + list = bancos.OrderBy(u003cu003e9_171).ToList(); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 144, num, value, true); + continue; + } + return list; + } + return new List(); + }); + return bancos1; + } + + internal async Task> BuscarBancosContas(string value) + { + int num = 3; + List bancosContas1 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List bancosContas = read.get_BancosContasRepository().Find(value); + Func u003cu003e9_181 = BaseServico.u003cu003ec.u003cu003e9__18_1; + if (u003cu003e9_181 == null) + { + u003cu003e9_181 = (BancosContas x) => x.get_Descricao(); + BaseServico.u003cu003ec.u003cu003e9__18_1 = u003cu003e9_181; + } + list = bancosContas.OrderBy(u003cu003e9_181).ToList(); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 146, num, value, true); + continue; + } + return list; + } + return new List(); + }); + return bancosContas1; + } + + public async Task> BuscarCentroAsync() + { + int num = 3; + List centros1 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List centros = read.get_CentroRepository().Find(); + Func u003cu003e9_601 = BaseServico.u003cu003ec.u003cu003e9__60_1; + if (u003cu003e9_601 == null) + { + u003cu003e9_601 = (Centro x) => x.get_Descricao(); + BaseServico.u003cu003ec.u003cu003e9__60_1 = u003cu003e9_601; + } + list = centros.OrderBy(u003cu003e9_601).ToList(); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 153, num, null, true); + continue; + } + return list; + } + return new List(); + }); + return centros1; + } + + internal async Task> BuscarClienteEmpresa(string value) + { + List clientes3; + if (!string.IsNullOrWhiteSpace(value)) + { + int num = 3; + clientes3 = await Task.Run>(() => { + List clientes; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List clientes1 = read.get_ClienteRepository().Find(value, (long)0, false, false); + Func u003cu003e9_731 = BaseServico.u003cu003ec.u003cu003e9__73_1; + if (u003cu003e9_731 == null) + { + u003cu003e9_731 = (Cliente x) => x.get_Nome(); + BaseServico.u003cu003ec.u003cu003e9__73_1 = u003cu003e9_731; + } + List list = clientes1.OrderBy(u003cu003e9_731).ToList(); + List clientes2 = read.get_EmpresaRepository().FindAsCliente(value); + Func u003cu003e9_732 = BaseServico.u003cu003ec.u003cu003e9__73_2; + if (u003cu003e9_732 == null) + { + u003cu003e9_732 = (Cliente x) => x.get_Nome(); + BaseServico.u003cu003ec.u003cu003e9__73_2 = u003cu003e9_732; + } + list.AddRange(clientes2.OrderBy(u003cu003e9_732).ToList()); + clientes = list; + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 29, num, value, true); + continue; + } + return clientes; + } + return new List(); + }); + } + else + { + clientes3 = new List(); + } + return clientes3; + } + + public async Task BuscarControle() + { + ControleArquivoDigital controleArquivoDigital1 = await Task.Run(() => { + ControleArquivoDigital controleArquivoDigital; + try + { + using (UnitOfWork read = Instancia.Read) + { + controleArquivoDigital = read.get_IndiceArquivoDigitalRepository().BuscarBanco(); + } + } + catch (Exception exception) + { + controleArquivoDigital = null; + } + return controleArquivoDigital; + }); + return controleArquivoDigital1; + } + + public async Task> BuscarCredenciais() + { + int num = 3; + List credencials1 = await Task.Run>(() => { + List credencials; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + credencials = read.get_CredencialRepository().Find(Recursos.Empresa.get_Id()); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 187, num, null, true); + continue; + } + return credencials; + } + return new List(); + }); + return credencials1; + } + + public async Task> BuscarDocumentosPorEstipulante(long id) + { + int num = 3; + List documentos1 = await Task.Run>(() => { + List documentos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + documentos = read.get_DocumentoRepository().BuscarDocumentoPorEstipulante(id); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 11, num, id, true); + continue; + } + return documentos; + } + return new List(); + }); + return documentos1; + } + + public async Task> BuscarDocumentosPorStatus(long id) + { + int num = 3; + List documentos1 = await Task.Run>(() => { + List documentos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + documentos = read.get_DocumentoRepository().BuscarDocumentoPorStatus(id); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 12, num, id, true); + continue; + } + return documentos; + } + return new List(); + }); + return documentos1; + } + + internal Empresa BuscarEmpresa(long id) + { + Empresa empresa; + int num = 3; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + empresa = read.get_EmpresaRepository().FindById(id); + } + } + catch (Exception exception1) + { + Exception exception = exception1; + num = this.Registrar(exception, 114, num, id, true); + continue; + } + return empresa; + } + return new Empresa(); + } + + public async Task> BuscarEmpresasAsync() + { + int num = 3; + List empresas2 = await Task.Run>(() => { + List empresas; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List empresas1 = read.get_EmpresaRepository().Find((long)0); + Func u003cu003e9_251 = BaseServico.u003cu003ec.u003cu003e9__25_1; + if (u003cu003e9_251 == null) + { + u003cu003e9_251 = (Empresa x) => x.get_Id(); + BaseServico.u003cu003ec.u003cu003e9__25_1 = u003cu003e9_251; + } + empresas = new List(empresas1.OrderBy(u003cu003e9_251)); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 113, num, null, true); + continue; + } + return empresas; + } + return new List(); + }); + return empresas2; + } + + public async Task> BuscarEstipulante(string value) + { + int num = 3; + List estipulantes1 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List estipulantes = read.get_EstipulanteRepository().Find(value, (Recursos.Usuario.get_IdEmpresa() == (long)1 ? (long)0 : Recursos.Usuario.get_IdEmpresa())); + Func u003cu003e9_221 = BaseServico.u003cu003ec.u003cu003e9__22_1; + if (u003cu003e9_221 == null) + { + u003cu003e9_221 = (Estipulante x) => x.get_Nome(); + BaseServico.u003cu003ec.u003cu003e9__22_1 = u003cu003e9_221; + } + list = estipulantes.OrderBy(u003cu003e9_221).ToList(); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 111, num, value, true); + continue; + } + return list; + } + return new List(); + }); + return estipulantes1; + } + + public async Task> BuscarEstipulantes() + { + int num = 3; + List estipulantes1 = await Task.Run>(() => { + List estipulantes; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + Recursos.Estipulantes = read.get_EstipulanteRepository().Find(); + estipulantes = Recursos.Estipulantes; + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 186, num, null, true); + continue; + } + return estipulantes; + } + return Recursos.Estipulantes; + }); + return estipulantes1; + } + + public async Task> BuscarEstipulantesAsync() + { + int num = 3; + List estipulantes2 = await Task.Run>(() => { + List estipulantes; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List estipulantes1 = read.get_EstipulanteRepository().Find(); + Func u003cu003e9_231 = BaseServico.u003cu003ec.u003cu003e9__23_1; + if (u003cu003e9_231 == null) + { + u003cu003e9_231 = (Estipulante x) => x.get_Id(); + BaseServico.u003cu003ec.u003cu003e9__23_1 = u003cu003e9_231; + } + estipulantes = new List(estipulantes1.OrderBy(u003cu003e9_231)); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 112, num, null, true); + continue; + } + return estipulantes; + } + return new List(); + }); + return estipulantes2; + } + + internal async Task> BuscarFabricante(string value) + { + int num = 3; + List fabricantes1 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List fabricantes = read.get_FabricanteRepository().Find(value); + Func u003cu003e9_191 = BaseServico.u003cu003ec.u003cu003e9__19_1; + if (u003cu003e9_191 == null) + { + u003cu003e9_191 = (Fabricante x) => x.get_Descricao(); + BaseServico.u003cu003ec.u003cu003e9__19_1 = u003cu003e9_191; + } + list = fabricantes.OrderBy(u003cu003e9_191).ToList(); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 182, num, value, true); + continue; + } + return list; + } + return new List(); + }); + return fabricantes1; + } + + public async Task> BuscarFornecedor(string value, bool ativo = false) + { + int num = 3; + List fornecedors1 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List fornecedors = read.get_FornecedorRepository().Find(value, ativo); + Func u003cu003e9_631 = BaseServico.u003cu003ec.u003cu003e9__63_1; + if (u003cu003e9_631 == null) + { + u003cu003e9_631 = (Fornecedor x) => x.get_Nome(); + BaseServico.u003cu003ec.u003cu003e9__63_1 = u003cu003e9_631; + } + list = fornecedors.OrderBy(u003cu003e9_631).ToList(); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 159, num, value, true); + continue; + } + return list; + } + return new List(); + }); + return fornecedors1; + } + + public async Task> BuscarFornecedor() + { + int num = 3; + List fornecedors1 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List fornecedors = read.get_FornecedorRepository().Find(); + Func u003cu003e9_641 = BaseServico.u003cu003ec.u003cu003e9__64_1; + if (u003cu003e9_641 == null) + { + u003cu003e9_641 = (Fornecedor x) => x.get_Nome(); + BaseServico.u003cu003ec.u003cu003e9__64_1 = u003cu003e9_641; + } + list = fornecedors.OrderBy(u003cu003e9_641).ToList(); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 166, num, null, true); + continue; + } + return list; + } + return new List(); + }); + return fornecedors1; + } + + public async Task> BuscarMetaSeguradoraAsync(Seguradora seguradora) + { + int num = 3; + List metaSeguradoras2 = await Task.Run>(() => { + List metaSeguradoras; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List metaSeguradoras1 = read.get_MetaSeguradoraRepository().Find(seguradora.get_Id()); + Func u003cu003e9_381 = BaseServico.u003cu003ec.u003cu003e9__38_1; + if (u003cu003e9_381 == null) + { + u003cu003e9_381 = (MetaSeguradora x) => x.get_Id(); + BaseServico.u003cu003ec.u003cu003e9__38_1 = u003cu003e9_381; + } + metaSeguradoras = new List(metaSeguradoras1.OrderBy(u003cu003e9_381)); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 184, num, seguradora, true); + continue; + } + return metaSeguradoras; + } + return new List(); + }); + return metaSeguradoras2; + } + + public async Task> BuscarMetaVendedorAsync(Vendedor vendedor) + { + int num = 3; + List metaVendedors2 = await Task.Run>(() => { + List metaVendedors; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List metaVendedors1 = read.get_MetaVendedorRepository().Find(vendedor.get_Id()); + Func u003cu003e9_361 = BaseServico.u003cu003ec.u003cu003e9__36_1; + if (u003cu003e9_361 == null) + { + u003cu003e9_361 = (MetaVendedor x) => x.get_Id(); + BaseServico.u003cu003ec.u003cu003e9__36_1 = u003cu003e9_361; + } + metaVendedors = new List(metaVendedors1.OrderBy(u003cu003e9_361)); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 183, num, vendedor, true); + continue; + } + return metaVendedors; + } + return new List(); + }); + return metaVendedors2; + } + + public async Task> BuscarParceirosAsync() + { + int num = 3; + List parceiros2 = await Task.Run>(() => { + List parceiros; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List parceiros1 = read.get_ParceiroRepository().Find(); + Func u003cu003e9_351 = BaseServico.u003cu003ec.u003cu003e9__35_1; + if (u003cu003e9_351 == null) + { + u003cu003e9_351 = (Parceiro x) => x.get_Id(); + BaseServico.u003cu003ec.u003cu003e9__35_1 = u003cu003e9_351; + } + parceiros = new List(parceiros1.OrderBy(u003cu003e9_351)); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 72, num, null, true); + continue; + } + return parceiros; + } + return new List(); + }); + return parceiros2; + } + + public async Task BuscarParcelaPendente(long id) + { + int num = 3; + ParcelaPendente parcelaPendente1 = await Task.Run(() => { + ParcelaPendente parcelaPendente; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + parcelaPendente = read.get_ParcelaRepository().BuscarPendencia(id); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 299, num, id, true); + continue; + } + return parcelaPendente; + } + return null; + }); + return parcelaPendente1; + } + + public async Task> BuscarPlanoAsync() + { + int num = 3; + List planos2 = await Task.Run>(() => { + List planos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List planos1 = read.get_PlanoRepository().Find(); + Func u003cu003e9_611 = BaseServico.u003cu003ec.u003cu003e9__61_1; + if (u003cu003e9_611 == null) + { + u003cu003e9_611 = (Plano x) => x.get_Descricao(); + BaseServico.u003cu003ec.u003cu003e9__61_1 = u003cu003e9_611; + } + planos = new List(planos1.OrderBy(u003cu003e9_611)); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 167, num, null, true); + continue; + } + return planos; + } + return new List(); + }); + return planos2; + } + + public async Task> BuscarPlanosAsync() + { + int num = 3; + List planos1 = await Task.Run>(() => { + List planos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + planos = new List(read.get_PlanosRepository().Find()); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 168, num, null, true); + continue; + } + return planos; + } + return new List(); + }); + return planos1; + } + + public async Task> BuscarProduto(string value) + { + int num = 3; + List produtos1 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List produtos = read.get_ProdutoRepository().Find(value); + Func u003cu003e9_411 = BaseServico.u003cu003ec.u003cu003e9__41_1; + if (u003cu003e9_411 == null) + { + u003cu003e9_411 = (Produto x) => x.get_Nome(); + BaseServico.u003cu003ec.u003cu003e9__41_1 = u003cu003e9_411; + } + list = produtos.OrderBy(u003cu003e9_411).ToList(); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 117, num, value, true); + continue; + } + return list; + } + return new List(); + }); + return produtos1; + } + + public async Task> BuscarProdutosAsync() + { + int num = 3; + List produtos2 = await Task.Run>(() => { + List produtos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List produtos1 = read.get_ProdutoRepository().Find(); + Func u003cu003e9_491 = BaseServico.u003cu003ec.u003cu003e9__49_1; + if (u003cu003e9_491 == null) + { + u003cu003e9_491 = (Produto x) => x.get_Nome(); + BaseServico.u003cu003ec.u003cu003e9__49_1 = u003cu003e9_491; + } + produtos = new List(produtos1.OrderBy(u003cu003e9_491)); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 118, num, null, true); + continue; + } + return produtos; + } + return new List(); + }); + return produtos2; + } + + internal async Task> BuscarProfissao(string value) + { + int num = 3; + List profissaos1 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List profissaos = read.get_ProfissaoRepository().Find(value); + Func u003cu003e9_151 = BaseServico.u003cu003ec.u003cu003e9__15_1; + if (u003cu003e9_151 == null) + { + u003cu003e9_151 = (Profissao x) => x.get_Nome(); + BaseServico.u003cu003ec.u003cu003e9__15_1 = u003cu003e9_151; + } + list = profissaos.OrderBy(u003cu003e9_151).ToList(); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 180, num, value, true); + continue; + } + return list; + } + return new List(); + }); + return profissaos1; + } + + public async Task BuscarQualificacaoAsync() + { + int num = 3; + Qualificacao qualificacao1 = await Task.Run(() => { + Qualificacao qualificacao; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + qualificacao = read.get_QualificacaoRepository().FindById((long)1); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 170, num, null, true); + continue; + } + return qualificacao; + } + return new Qualificacao(); + }); + return qualificacao1; + } + + public async Task> BuscarRamosAsync() + { + int num = 3; + List ramos2 = await Task.Run>(() => { + List ramos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List ramos1 = read.get_RamoRepository().Find(); + Func u003cu003e9_431 = BaseServico.u003cu003ec.u003cu003e9__43_1; + if (u003cu003e9_431 == null) + { + u003cu003e9_431 = (Ramo x) => x.get_Nome(); + BaseServico.u003cu003ec.u003cu003e9__43_1 = u003cu003e9_431; + } + ramos = new List(ramos1.OrderBy(u003cu003e9_431)); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 169, num, null, true); + continue; + } + return ramos; + } + return new List(); + }); + return ramos2; + } + + public async Task> BuscarSeguradorasAsync() + { + int num = 3; + List seguradoras2 = await Task.Run>(() => { + List seguradoras; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List seguradoras1 = read.get_SeguradoraRepository().Find(); + Func u003cu003e9_451 = BaseServico.u003cu003ec.u003cu003e9__45_1; + if (u003cu003e9_451 == null) + { + u003cu003e9_451 = (Seguradora x) => x.get_Id(); + BaseServico.u003cu003ec.u003cu003e9__45_1 = u003cu003e9_451; + } + seguradoras = new List(seguradoras1.OrderBy(u003cu003e9_451)); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 127, num, null, true); + continue; + } + return seguradoras; + } + return new List(); + }); + return seguradoras2; + } + + public async Task> BuscarSociosAsync(long id) + { + int num = 3; + List socios1 = await Task.Run>(() => { + List socios; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + socios = read.get_SocioRepository().FindByEmpresa(id); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 122, num, id, true); + continue; + } + return socios; + } + return new List(); + }); + return socios1; + } + + public async Task> BuscarStatus(string value) + { + int num = 3; + List statuses1 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List statuses = read.get_StatusRepository().Find(value); + Func u003cu003e9_421 = BaseServico.u003cu003ec.u003cu003e9__42_1; + if (u003cu003e9_421 == null) + { + u003cu003e9_421 = (Status x) => x.get_Nome(); + BaseServico.u003cu003ec.u003cu003e9__42_1 = u003cu003e9_421; + } + list = statuses.OrderBy(u003cu003e9_421).ToList(); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 120, num, value, true); + continue; + } + return list; + } + return new List(); + }); + return statuses1; + } + + public async Task> BuscarStatusAsync() + { + int num = 3; + List statuses2 = await Task.Run>(() => { + List statuses; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List statuses1 = read.get_StatusRepository().Find(); + Func u003cu003e9_501 = BaseServico.u003cu003ec.u003cu003e9__50_1; + if (u003cu003e9_501 == null) + { + u003cu003e9_501 = (Status x) => x.get_Nome(); + BaseServico.u003cu003ec.u003cu003e9__50_1 = u003cu003e9_501; + } + statuses = new List(statuses1.OrderBy(u003cu003e9_501)); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 121, num, null, true); + continue; + } + return statuses; + } + return new List(); + }); + return statuses2; + } + + public async Task> BuscarTipoVendedoresAsync() + { + int num = 3; + List tipoVendedors1 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List tipoVendedors = read.get_TipoVendedorRepository().Find(); + Func u003cu003e9_481 = BaseServico.u003cu003ec.u003cu003e9__48_1; + if (u003cu003e9_481 == null) + { + u003cu003e9_481 = (TipoVendedor x) => x.get_Id(); + BaseServico.u003cu003ec.u003cu003e9__48_1 = u003cu003e9_481; + } + list = tipoVendedors.OrderBy(u003cu003e9_481).ToList(); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 141, num, null, true); + continue; + } + return list; + } + return new List(); + }); + return tipoVendedors1; + } + + internal async Task> BuscarUsuario(string value) + { + int num = 3; + List usuarios1 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List usuarios = read.get_UsuarioRepository().Find(value, (long)0); + Func u003cu003e9_271 = BaseServico.u003cu003ec.u003cu003e9__27_1; + if (u003cu003e9_271 == null) + { + u003cu003e9_271 = (Usuario x) => x.get_Nome(); + BaseServico.u003cu003ec.u003cu003e9__27_1 = u003cu003e9_271; + } + list = usuarios.OrderBy(u003cu003e9_271).ToList(); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 132, num, value, true); + continue; + } + return list; + } + return new List(); + }); + return usuarios1; + } + + internal async Task BuscarUsuario(string login, string password) + { + int num = 3; + string str = (new Token()).AggerEncrypt(password); + Usuario usuario2 = await Task.Run(() => { + Usuario usuario; + Usuario usuario1; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + Empresa empresa = read.get_EmpresaRepository().FindBySerial(ApplicationHelper.NumeroSerial); + AuthSso result = this.BuscaUsuarioSso(login, str, empresa.get_Documento()).Result; + if (result == null || result.get_Code() == 401) + { + usuario1 = null; + } + else if (result.get_Code() != 404) + { + usuario = read.get_UsuarioRepository().SsoId(result) ?? read.get_UsuarioRepository().FindFromSso(result.get_Data().get_User()); + if (usuario != null) + { + if (usuario.get_Excluido()) + { + using (UnitOfWork commited = Instancia.Commited) + { + usuario.set_Excluido(false); + commited.get_UsuarioRepository().Merge(usuario); + commited.Commit(); + } + } + usuario.set_TokenSso(result.get_Data().get_Token()); + if (!Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(usuario.get_SsoId()) || !usuario.get_SsoId().Equals(result.get_Data().get_User().get_Id())) + { + using (UnitOfWork unitOfWork = Instancia.Commited) + { + usuario.set_SsoId(result.get_Data().get_User().get_Id()); + unitOfWork.get_UsuarioRepository().Merge(usuario); + unitOfWork.Commit(); + } + usuario1 = usuario; + } + else + { + usuario1 = usuario; + } + } + else + { + using (UnitOfWork commited1 = Instancia.Commited) + { + usuario = commited1.get_UsuarioRepository().AddUsuarioFromSso(result.get_Data().get_User()); + commited1.Commit(); + } + usuario.set_TokenSso(result.get_Data().get_Token()); + usuario1 = usuario; + } + } + else + { + usuario = read.get_UsuarioRepository().ValidateLogin(login, str); + if (usuario != null) + { + usuario.set_TokenSso(result.get_Data().get_Token()); + UserSso userSso = this.AddOrUpdateUsuarioSso(usuario, empresa.get_Documento(), null).Result; + if (userSso != null) + { + using (UnitOfWork unitOfWork1 = Instancia.Commited) + { + usuario.set_SsoId(userSso.get_Id()); + unitOfWork1.get_UsuarioRepository().Merge(usuario); + unitOfWork1.Commit(); + } + usuario.set_TokenSso(this.BuscaUsuarioSso(login, str, empresa.get_Documento()).Result.get_Data().get_Token()); + usuario1 = usuario; + } + else + { + usuario1 = usuario; + } + } + else + { + usuario1 = null; + } + } + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 134, num, null, true); + continue; + } + return usuario1; + } + return new Usuario(); + }); + return usuario2; + } + + internal async Task BuscarUsuarioMesmoDocumento(string value, long id, long idempresa) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + flag = read.get_UsuarioRepository().FindDocUsedByDocumento(value, id, idempresa); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 134, num, value, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + internal async Task> BuscarUsuarioPorLoginInteiro(string value) + { + int num = 3; + List usuarios1 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List usuarios = read.get_UsuarioRepository().FindByLoginInteiro(value); + Func u003cu003e9_391 = BaseServico.u003cu003ec.u003cu003e9__39_1; + if (u003cu003e9_391 == null) + { + u003cu003e9_391 = (Usuario x) => x.get_Nome(); + BaseServico.u003cu003ec.u003cu003e9__39_1 = u003cu003e9_391; + } + list = usuarios.OrderBy(u003cu003e9_391).ToList(); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 134, num, value, true); + continue; + } + return list; + } + return new List(); + }); + return usuarios1; + } + + public async Task> BuscarUsuariosAsync() + { + int num = 3; + List usuarios2 = await Task.Run>(() => { + List usuarios; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List usuarios1 = read.get_UsuarioRepository().Find((Recursos.Usuario.get_IdEmpresa() == (long)1 ? (long)0 : Recursos.Usuario.get_IdEmpresa())); + Func u003cu003e9_241 = BaseServico.u003cu003ec.u003cu003e9__24_1; + if (u003cu003e9_241 == null) + { + u003cu003e9_241 = (Usuario x) => x.get_Id(); + BaseServico.u003cu003ec.u003cu003e9__24_1 = u003cu003e9_241; + } + usuarios = new List(usuarios1.OrderBy(u003cu003e9_241)); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 131, num, null, true); + continue; + } + return usuarios; + } + return new List(); + }); + return usuarios2; + } + + public async Task> BuscarUsuariosSso() + { + List userSsos; + List userSsos1; + try + { + using (HttpClient httpClient = new HttpClient()) + { + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + Uri apiSso = Address.get_ApiSso(); + string[] strArrays = new string[] { "user" }; + Uri uri = apiSso.Append(strArrays); + string[] strArrays1 = new string[] { "onlyempresa" }; + Uri uri1 = uri.Append(strArrays1); + string[] strArrays2 = new string[] { "list" }; + Uri uri2 = uri1.Append(strArrays2); + httpClient.get_DefaultRequestHeaders().TryAddWithoutValidation("Authorization", string.Concat("Bearer ", Recursos.Usuario.get_TokenSso())); + HttpResponseMessage async = await httpClient.GetAsync(uri2); + if (!async.get_IsSuccessStatusCode()) + { + userSsos1 = null; + } + else + { + userSsos1 = JsonConvert.DeserializeObject>(await async.get_Content().ReadAsStringAsync()); + } + userSsos = userSsos1; + } + } + catch + { + userSsos = new List(); + } + return userSsos; + } + + internal async Task> BuscarVendedor(string value) + { + int num = 3; + List vendedors1 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List vendedors = read.get_VendedorRepository().Find((Recursos.Usuario.get_IdEmpresa() == (long)1 ? (long)0 : Recursos.Usuario.get_IdEmpresa())); + Func u003cu003e9_211 = BaseServico.u003cu003ec.u003cu003e9__21_1; + if (u003cu003e9_211 == null) + { + u003cu003e9_211 = (Vendedor x) => x.get_Nome(); + BaseServico.u003cu003ec.u003cu003e9__21_1 = u003cu003e9_211; + } + list = vendedors.OrderBy(u003cu003e9_211).ToList(); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 140, num, value, true); + continue; + } + return list; + } + return new List(); + }); + return vendedors1; + } + + public async Task> BuscarVendedoresAsync() + { + int num = 3; + List vendedors2 = await Task.Run>(() => { + List vendedors; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List vendedors1 = read.get_VendedorRepository().Find((Recursos.Usuario.get_IdEmpresa() == (long)1 ? (long)0 : Recursos.Usuario.get_IdEmpresa())); + Func u003cu003e9_471 = BaseServico.u003cu003ec.u003cu003e9__47_1; + if (u003cu003e9_471 == null) + { + u003cu003e9_471 = (Vendedor x) => x.get_Id(); + BaseServico.u003cu003ec.u003cu003e9__47_1 = u003cu003e9_471; + } + vendedors = new List(vendedors1.OrderBy(u003cu003e9_471)); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 140, num, null, true); + continue; + } + return vendedors; + } + return new List(); + }); + return vendedors2; + } + + private async Task BuscaUsuarioByToken(Usuario usuario) + { + bool flag; + using (HttpClient httpClient = new HttpClient()) + { + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + Uri apiSso = Address.get_ApiSso(); + string[] strArrays = new string[] { "user" }; + Uri uri = apiSso.Append(strArrays); + httpClient.get_DefaultRequestHeaders().TryAddWithoutValidation("Authorization", string.Concat("Bearer ", usuario.get_TokenSso())); + JsonConvert.DeserializeObject(await await httpClient.GetAsync(uri).get_Content().ReadAsStringAsync()); + flag = true; + } + return flag; + } + + internal async Task BuscaUsuarioSso(string login, string password, string documentoEmpresa) + { + AuthSso authSso; + AuthSso authSso1; + using (HttpClient httpClient = new HttpClient()) + { + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + Uri apiSso = Address.get_ApiSso(); + string[] strArrays = new string[] { "auth" }; + Uri uri = apiSso.Append(strArrays); + object[] ticks = new object[] { login, password, ApplicationHelper.NumeroSerial, documentoEmpresa, null }; + DateTime universalTime = Funcoes.GetNetworkTime().ToUniversalTime(); + ticks[4] = universalTime.Ticks; + string base64BasicEncode = string.Format("{0}:{1}:{2}:{3}:{4}", ticks).ToBase64BasicEncode(); + httpClient.get_DefaultRequestHeaders().TryAddWithoutValidation("Authorization", base64BasicEncode); + HttpResponseMessage async = await httpClient.GetAsync(uri); + if (!async.get_IsSuccessStatusCode()) + { + authSso1 = null; + } + else + { + authSso1 = JsonConvert.DeserializeObject(await async.get_Content().ReadAsStringAsync()); + } + authSso = authSso1; + } + return authSso; + } + + public async Task> CarregarUsuarios() + { + await this.AtualizarUsuarios(); + return await this.BuscarUsuariosAsync(); + } + + public RegistroLog CreateDynamicLog(long id, dynamic lista, TipoTela tela) + { + RegistroLog registroLog; + string str; + string str1; + string str2; + string str3; + try + { + List diferencas = new List(); + List valorOriginals = new List(); + foreach (dynamic listum in (IEnumerable)lista) + { + if (listum == (dynamic)null) + { + continue; + } + if (!listum.GetType().Name.ToUpper().StartsWith("LIST")) + { + try + { + diferencas.AddRange(this.DynamicObjeto(listum)); + } + catch + { + } + } + else + { + foreach (dynamic obj1 in (IEnumerable)listum) + { + try + { + if (obj1.Id != 0) + { + diferencas.AddRange(this.DynamicObjeto(obj1)); + } + else + { + valorOriginals.AddRange(obj1.GetValorOriginal()); + } + } + catch + { + } + } + } + } + DateTime networkTime = Funcoes.GetNetworkTime(); + if (diferencas == null || diferencas.Count != 0) + { + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + str = JsonConvert.SerializeObject(diferencas, jsonSerializerSetting).Replace("]", ",").Replace("[", ""); + } + else + { + str = ""; + } + string str4 = str; + if (valorOriginals == null || valorOriginals.Count != 0) + { + JsonSerializerSettings jsonSerializerSetting1 = new JsonSerializerSettings(); + jsonSerializerSetting1.set_ReferenceLoopHandling(1); + str1 = JsonConvert.SerializeObject(valorOriginals, jsonSerializerSetting1).Replace("]", "").Replace("[", ""); + } + else + { + str1 = ""; + } + string str5 = str1; + RegistroLog registroLog1 = new RegistroLog(); + registroLog1.set_Acao(1); + registroLog1.set_Usuario(Recursos.Usuario); + registroLog1.set_DataHora(networkTime); + if (!string.IsNullOrEmpty(str4) || !string.IsNullOrEmpty(str5)) + { + str2 = string.Concat("[", str4, str5, "]"); + } + else + { + str2 = null; + } + registroLog1.set_Descricao(str2); + registroLog1.set_EntidadeId(id); + registroLog1.set_Tela(tela); + registroLog1.set_Versao(LoginViewModel.VersaoAtual); + registroLog1.set_NomeMaquina(Environment.MachineName); + registroLog1.set_UsuarioMaquina(Environment.UserName); + IPAddress pAddress = ((IEnumerable)Recursos.Host.AddressList).FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork); + if (pAddress != null) + { + str3 = pAddress.ToString(); + } + else + { + str3 = null; + } + registroLog1.set_Ip(str3); + registroLog1.set_ModeloNovo(true); + registroLog = registroLog1; + } + catch (Exception exception) + { + registroLog = null; + } + return registroLog; + } + + public RegistroLog CreateLog(long id, dynamic obj, TipoTela tela) + { + RegistroLog registroLog; + string str; + string str1; + try + { + List diferencas = (List)obj.Compare(); + DateTime networkTime = Funcoes.GetNetworkTime(); + RegistroLog registroLog1 = new RegistroLog(); + registroLog1.set_Acao(1); + registroLog1.set_Usuario(Recursos.Usuario); + registroLog1.set_DataHora(networkTime); + if (diferencas == null || diferencas.Count != 0) + { + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + str = JsonConvert.SerializeObject(diferencas, jsonSerializerSetting); + } + else + { + str = null; + } + registroLog1.set_Descricao(str); + registroLog1.set_EntidadeId(id); + registroLog1.set_Tela(tela); + registroLog1.set_Versao(LoginViewModel.VersaoAtual); + registroLog1.set_NomeMaquina(Environment.MachineName); + registroLog1.set_UsuarioMaquina(Environment.UserName); + IPAddress pAddress = ((IEnumerable)Recursos.Host.AddressList).FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork); + if (pAddress != null) + { + str1 = pAddress.ToString(); + } + else + { + str1 = null; + } + registroLog1.set_Ip(str1); + registroLog1.set_ModeloNovo(true); + registroLog = registroLog1; + } + catch (Exception exception) + { + registroLog = null; + } + return registroLog; + } + + public RegistroLog CreateLog(long id, List diferenca, TipoTela tela) + { + RegistroLog registroLog; + string str; + try + { + DateTime networkTime = Funcoes.GetNetworkTime(); + RegistroLog registroLog1 = new RegistroLog(); + registroLog1.set_Acao(1); + registroLog1.set_Usuario(Recursos.Usuario); + registroLog1.set_DataHora(networkTime); + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog1.set_Descricao(JsonConvert.SerializeObject(diferenca, jsonSerializerSetting)); + registroLog1.set_EntidadeId(id); + registroLog1.set_Tela(tela); + registroLog1.set_Versao(LoginViewModel.VersaoAtual); + registroLog1.set_NomeMaquina(Environment.MachineName); + registroLog1.set_UsuarioMaquina(Environment.UserName); + IPAddress pAddress = ((IEnumerable)Recursos.Host.AddressList).FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog1.set_Ip(str); + registroLog1.set_ModeloNovo(true); + registroLog = registroLog1; + } + catch (Exception exception) + { + registroLog = null; + } + return registroLog; + } + + public RegistroLog CreateLog(long id, List diferenca, TipoTela tela, TipoAcao acao) + { + RegistroLog registroLog; + string str; + try + { + DateTime networkTime = Funcoes.GetNetworkTime(); + RegistroLog registroLog1 = new RegistroLog(); + registroLog1.set_Acao(acao); + registroLog1.set_Usuario(Recursos.Usuario); + registroLog1.set_DataHora(networkTime); + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog1.set_Descricao(JsonConvert.SerializeObject(diferenca, jsonSerializerSetting)); + registroLog1.set_EntidadeId(id); + registroLog1.set_Tela(tela); + registroLog1.set_Versao(LoginViewModel.VersaoAtual); + registroLog1.set_NomeMaquina(Environment.MachineName); + registroLog1.set_UsuarioMaquina(Environment.UserName); + IPAddress pAddress = ((IEnumerable)Recursos.Host.AddressList).FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog1.set_Ip(str); + registroLog1.set_ModeloNovo(true); + registroLog = registroLog1; + } + catch (Exception exception) + { + registroLog = null; + } + return registroLog; + } + + public RegistroLog CreateLog(long id, List valor, TipoTela tela, TipoAcao acao) + { + RegistroLog registroLog; + string str; + try + { + DateTime networkTime = Funcoes.GetNetworkTime(); + RegistroLog registroLog1 = new RegistroLog(); + registroLog1.set_Acao(acao); + registroLog1.set_Usuario(Recursos.Usuario); + registroLog1.set_DataHora(networkTime); + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog1.set_Descricao(JsonConvert.SerializeObject(valor, jsonSerializerSetting)); + registroLog1.set_EntidadeId(id); + registroLog1.set_Tela(tela); + registroLog1.set_Versao(LoginViewModel.VersaoAtual); + registroLog1.set_NomeMaquina(Environment.MachineName); + registroLog1.set_UsuarioMaquina(Environment.UserName); + IPAddress pAddress = ((IEnumerable)Recursos.Host.AddressList).FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog1.set_Ip(str); + registroLog1.set_ModeloNovo(true); + registroLog = registroLog1; + } + catch (Exception exception) + { + registroLog = null; + } + return registroLog; + } + + internal async Task DeleteUsuarioSso(Usuario usuario, string documentoEmpresa) + { + UserSso userSso; + UserSso userSso1; + using (HttpClient httpClient = new HttpClient()) + { + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + Uri apiSso = Address.get_ApiSso(); + string[] strArrays = new string[] { "user" }; + Uri uri = apiSso.Append(strArrays).AddQuery("userId", usuario.get_SsoId()); + httpClient.get_DefaultRequestHeaders().TryAddWithoutValidation("Authorization", string.Concat("Bearer ", usuario.get_TokenSso())); + HttpResponseMessage httpResponseMessage = await httpClient.DeleteAsync(uri); + if (!httpResponseMessage.get_IsSuccessStatusCode()) + { + userSso1 = null; + } + else + { + userSso1 = JsonConvert.DeserializeObject(await httpResponseMessage.get_Content().ReadAsStringAsync()); + } + userSso = userSso1; + } + return userSso; + } + + public List DynamicObjeto(dynamic objeto) + { + dynamic obj = objeto.Compare(); + if (obj.Count <= 0) + { + return new List(); + } + return (List)obj; + } + + public async Task LoadInicialParameters() + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List parceiros = read.get_ParceiroRepository().Find(); + Func u003cu003e9_521 = BaseServico.u003cu003ec.u003cu003e9__52_1; + if (u003cu003e9_521 == null) + { + u003cu003e9_521 = (Parceiro x) => x.get_Id(); + BaseServico.u003cu003ec.u003cu003e9__52_1 = u003cu003e9_521; + } + Recursos.Parceiros = new List(parceiros.OrderBy(u003cu003e9_521)); + List fabricantes = read.get_FabricanteRepository().Select(); + Func u003cu003e9_522 = BaseServico.u003cu003ec.u003cu003e9__52_2; + if (u003cu003e9_522 == null) + { + u003cu003e9_522 = (Fabricante x) => x.get_Descricao(); + BaseServico.u003cu003ec.u003cu003e9__52_2 = u003cu003e9_522; + } + Recursos.Fabricantes = fabricantes.OrderBy(u003cu003e9_522).ToList(); + Recursos.Configuracoes = read.get_ConfiguracaoRepository().BuscarConfiguracoes(); + read.CriarAuxiliar(false); + Recursos.Empresas = Auxiliar.get_Empresas(); + Recursos.Ramos = Auxiliar.get_Ramos(); + Recursos.Seguradoras = Auxiliar.get_Seguradoras(); + Recursos.Produtos = Auxiliar.get_Produtos(); + Recursos.Status = Auxiliar.get_StatusApolice(); + Recursos.TipoVendedor = Auxiliar.get_TipoVendedores(); + Recursos.Estipulantes = Auxiliar.get_Estipulantes(); + Recursos.Vendedores = Auxiliar.get_Vendedores(); + Recursos.Usuarios = Auxiliar.get_Usuarios(); + Recursos.TiposTarefa = Auxiliar.get_TiposTarefa(); + Recursos.StatusProspeccao = Auxiliar.get_StatusProspeccao(); + Recursos.Coberturas = Auxiliar.get_CoberturasPadrao(); + } + flag = true; + } + catch (Exception exception) + { + num = this.Registrar(exception, 186, num, null, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task ParceiroUtilizado(long id) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + flag = read.get_SinistroAutoRepository().ParceiroUtilizado(id); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 156, num, id, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public int Registrar(Exception e, TipoErro erro, int tries, object objeto = null, bool abrirTela = true) + { + string str; + string nome; + string nome1; + long id; + string str1; + tries--; + if (tries > 0) + { + return tries; + } + try + { + int fileLineNumber = (new StackTrace(e, true)).GetFrame(0).GetFileLineNumber(); + if (objeto != null) + { + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + str = JsonConvert.SerializeObject(objeto, 1, jsonSerializerSetting); + } + else + { + str = null; + } + string str2 = str; + LogError logError = new LogError(); + logError.set_IdFornecedor(ApplicationHelper.IdFornecedor); + Empresa empresa = Recursos.Empresa; + if (empresa != null) + { + nome = empresa.get_Nome(); + } + else + { + nome = null; + } + logError.set_Fornecedor(nome); + Usuario usuario = Recursos.Usuario; + if (usuario != null) + { + nome1 = usuario.get_Nome(); + } + else + { + nome1 = null; + } + logError.set_UsuarioLogado(nome1); + Usuario usuario1 = Recursos.Usuario; + if (usuario1 != null) + { + id = usuario1.get_Id(); + } + else + { + id = (long)0; + } + logError.set_IdUsuarioLogado(id); + logError.set_Versao(ApplicationHelper.Versao.ToString()); + logError.set_Data(Funcoes.GetNetworkTime()); + logError.set_IdErro(erro); + logError.set_Erro(Gestor.Common.Validation.ValidationHelper.GetDescription(erro)); + logError.set_HResult(e.HResult); + Exception innerException = e.InnerException; + if (innerException != null) + { + str1 = innerException.ToString(); + } + else + { + str1 = null; + } + logError.set_InnerException(str1); + logError.set_HelpLink(e.HelpLink); + logError.set_Message(e.Message); + logError.set_Source(e.Source); + logError.set_StackTrace(e.StackTrace); + logError.set_Maquina(Environment.MachineName); + logError.set_UsuarioMaquina(Environment.UserName); + logError.set_Linha(fileLineNumber.ToString()); + logError.set_Objeto(str2); + Erro.RegistrarErro(logError, abrirTela); + this.Sucesso = false; + } + catch (Exception exception) + { + } + return 0; + } + + public async Task ReloadAuxiliar() + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + read.CriarAuxiliar(true); + Recursos.Empresas = Auxiliar.get_Empresas(); + Recursos.Ramos = Auxiliar.get_Ramos(); + Recursos.Seguradoras = Auxiliar.get_Seguradoras(); + Recursos.Produtos = Auxiliar.get_Produtos(); + Recursos.Status = Auxiliar.get_StatusApolice(); + Recursos.TipoVendedor = Auxiliar.get_TipoVendedores(); + Recursos.Estipulantes = Auxiliar.get_Estipulantes(); + Recursos.Vendedores = Auxiliar.get_Vendedores(); + Recursos.Usuarios = Auxiliar.get_Usuarios(); + Recursos.TiposTarefa = Auxiliar.get_TiposTarefa(); + Recursos.StatusProspeccao = Auxiliar.get_StatusProspeccao(); + } + flag = true; + } + catch (Exception exception) + { + num = this.Registrar(exception, 186, num, null, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public void SalvarAcao(RegistroAcao log, object obs = null) + { + string str; + string str1; + if (log == null || Recursos.Usuario.get_Id() == 0) + { + return; + } + try + { + using (UnitOfWork commited = Instancia.Commited) + { + log.set_Usuario(Recursos.Usuario); + log.set_DataHora(Funcoes.GetNetworkTime()); + log.set_Versao(LoginViewModel.VersaoAtual); + log.set_NomeMaquina(Environment.MachineName); + log.set_UsuarioMaquina(Environment.UserName); + RegistroAcao registroAcao = log; + IPAddress pAddress = ((IEnumerable)Dns.GetHostEntry(Dns.GetHostName()).AddressList).FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroAcao.set_Ip(str); + RegistroAcao registroAcao1 = log; + if (obs == null) + { + str1 = ""; + } + else if (!(obs is string)) + { + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + str1 = JsonConvert.SerializeObject(obs, jsonSerializerSetting); + } + else + { + str1 = obs.ToString(); + } + registroAcao1.set_Observacao(str1); + commited.get_RegistroAcaoRepository().SaveOrUpdate(log); + commited.Commit(); + } + } + catch (Exception exception) + { + this.Registrar(exception, 0, 3, log, true); + } + } + + public async Task SalvarControle(ControleArquivoDigital controle) + { + int num = 3; + await Task.Run(() => { + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + commited.get_IndiceArquivoDigitalRepository().SaveOrUpdate(controle); + commited.Commit(); + } + break; + } + catch (Exception exception) + { + num = this.Registrar(exception, 179, num, controle, true); + } + } + }); + } + + public void SaveLog(RegistroLog keyValues, UnitOfWork unitOfWork) + { + if (keyValues == null) + { + return; + } + try + { + unitOfWork.get_RegistroLogRepository().SaveOrUpdate(keyValues); + } + catch (Exception exception) + { + } + } + + public void SaveLog(List keyValues, UnitOfWork unitOfWork) + { + if (keyValues == null) + { + return; + } + try + { + List list = keyValues.Where((RegistroLog x) => { + if (string.IsNullOrEmpty((x != null ? x.get_Descricao() : null))) + { + return false; + } + return !string.IsNullOrEmpty(x.get_Versao()); + }).ToList(); + unitOfWork.get_RegistroLogRepository().AddRange(list); + } + catch (Exception exception) + { + } + } + + public async Task Sincronizar(List dados, Filtros filtros) + { + int num2 = 3; + int num3 = await Task.Run(() => { + int num; + while (num2 > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + int num1 = commited.get_VinculoDocumentoRepository().Sincronize(filtros.get_Inicio(), dados); + commited.Commit(); + num = num1; + } + } + catch (Exception exception) + { + num2 = this.Registrar(exception, 293, num2, null, true); + continue; + } + return num; + } + return 0; + }); + return num3; + } + + public async Task Sincronizar(DateTime data, List ids = null) + { + int num = 3; + int[] numArray2 = await Task.Run(() => { + int[] numArray; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + int[] numArray1 = commited.get_ParcelaRepository().SincronizarPendencia(data, ids); + commited.Commit(); + numArray = numArray1; + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 300, num, false, true); + continue; + } + return numArray; + } + return new int[2]; + }); + return numArray2; + } + + public async Task TipoVendedorUtilizado(long id) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + flag = read.get_VendedorParcelaRepository().TipoVendedorUtilizado(id); + } + } + catch (Exception exception) + { + num = this.Registrar(exception, 155, num, id, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + internal async Task VerificaUsuarioSso(string login, string documentoEmpresa) + { + AuthSso authSso; + AuthSso authSso1; + using (HttpClient httpClient = new HttpClient()) + { + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + Uri apiSso = Address.get_ApiSso(); + string[] strArrays = new string[] { "exist" }; + Uri uri = apiSso.Append(strArrays); + object[] ticks = new object[] { login, login, ApplicationHelper.NumeroSerial, documentoEmpresa, null }; + DateTime universalTime = Funcoes.GetNetworkTime().ToUniversalTime(); + ticks[4] = universalTime.Ticks; + string base64BasicEncode = string.Format("{0}:{1}:{2}:{3}:{4}", ticks).ToBase64BasicEncode(); + httpClient.get_DefaultRequestHeaders().TryAddWithoutValidation("Authorization", base64BasicEncode); + HttpResponseMessage async = await httpClient.GetAsync(uri); + if (!async.get_IsSuccessStatusCode()) + { + authSso1 = null; + } + else + { + authSso1 = JsonConvert.DeserializeObject(await async.get_Content().ReadAsStringAsync()); + } + authSso = authSso1; + } + return authSso; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/LogServico.cs b/Codemerx/Gestor.Application/Servicos/LogServico.cs new file mode 100644 index 0000000..bc61ed1 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/LogServico.cs @@ -0,0 +1,262 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Relatorios.LogsEnvio; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos +{ + public class LogServico : BaseServico + { + public LogServico() + { + } + + public async Task> BuscaLogParcelas(List ids) + { + int num = 3; + ObservableCollection observableCollection1 = await Task.Run>(() => { + ObservableCollection observableCollection; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List registroLogs = read.get_RegistroLogRepository().BuscaLogParcelas(ids); + Func u003cu003e9_11 = LogServico.u003cu003ec.u003cu003e9__1_1; + if (u003cu003e9_11 == null) + { + u003cu003e9_11 = (RegistroLog x) => x.get_DataHora(); + LogServico.u003cu003ec.u003cu003e9__1_1 = u003cu003e9_11; + } + observableCollection = new ObservableCollection(registroLogs.OrderByDescending(u003cu003e9_11)); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 67, num, new { Parcela = 5, ids = ids }, true); + continue; + } + return observableCollection; + } + return new ObservableCollection(); + }); + return observableCollection1; + } + + public async Task> BuscarLogs(Filtros filtro) + { + int num = 3; + List registroAcaos1 = await Task.Run>(() => { + List registroAcaos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + registroAcaos = read.get_RegistroAcaoRepository().Find(filtro); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 321, num, filtro, true); + continue; + } + return registroAcaos; + } + return new List(); + }); + return registroAcaos1; + } + + public async Task> BuscarLogsAntigos(Filtros filtro) + { + int num = 3; + List registroAcaos1 = await Task.Run>(() => { + List registroAcaos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + registroAcaos = read.get_RegistroAcaoRepository().FindOld(filtro, Connection.GetConnectionString()); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 321, num, filtro, true); + continue; + } + return registroAcaos; + } + return new List(); + }); + return registroAcaos1; + } + + public async Task> BuscarLogsEnvio(Filtros filtro) + { + int num = 3; + List logsEnvios1 = await Task.Run>(() => { + List logsEnvios; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + logsEnvios = read.get_RegistroLogRepository().LogsEnvio(filtro); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 9, num, filtro, true); + continue; + } + return logsEnvios; + } + return new List(); + }); + return logsEnvios1; + } + + public async Task> FindAllByEntityId(TipoTela tela, long id) + { + int num = 3; + ObservableCollection observableCollection1 = await Task.Run>(() => { + ObservableCollection observableCollection; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List registroLogs = read.get_RegistroLogRepository().FindByEntityId(tela, id); + Func u003cu003e9_41 = LogServico.u003cu003ec.u003cu003e9__4_1; + if (u003cu003e9_41 == null) + { + u003cu003e9_41 = (RegistroLog x) => x.get_DataHora(); + LogServico.u003cu003ec.u003cu003e9__4_1 = u003cu003e9_41; + } + observableCollection = new ObservableCollection(registroLogs.OrderByDescending(u003cu003e9_41)); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 67, num, new { tela = tela, id = id }, true); + continue; + } + return observableCollection; + } + return new ObservableCollection(); + }); + return observableCollection1; + } + + public async Task> FindByEntity(TipoTela tela, long id) + { + int num = 3; + ObservableCollection observableCollection1 = await Task.Run>(() => { + ObservableCollection observableCollection; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List logEmails = read.get_RegistroLogRepository().FindByEntity(tela, id); + Func u003cu003e9_21 = LogServico.u003cu003ec.u003cu003e9__2_1; + if (u003cu003e9_21 == null) + { + u003cu003e9_21 = (LogEmail x) => x.get_Data(); + LogServico.u003cu003ec.u003cu003e9__2_1 = u003cu003e9_21; + } + observableCollection = new ObservableCollection(logEmails.OrderByDescending(u003cu003e9_21)); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 68, num, new { tela = tela, id = id }, true); + continue; + } + return observableCollection; + } + return new ObservableCollection(); + }); + return observableCollection1; + } + + public async Task> FindByEntityId(TipoTela tela, long id) + { + int num = 3; + ObservableCollection observableCollection1 = await Task.Run>(() => { + ObservableCollection observableCollection; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List registroLogs = read.get_RegistroLogRepository().FindByEntityId(tela, id); + Func u003cu003e9_01 = LogServico.u003cu003ec.u003cu003e9__0_1; + if (u003cu003e9_01 == null) + { + u003cu003e9_01 = (RegistroLog x) => x.get_DataHora(); + LogServico.u003cu003ec.u003cu003e9__0_1 = u003cu003e9_01; + } + observableCollection = new ObservableCollection(registroLogs.OrderByDescending(u003cu003e9_01)); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 67, num, new { tela = tela, id = id }, true); + continue; + } + return observableCollection; + } + return new ObservableCollection(); + }); + return observableCollection1; + } + + public async Task> FindById(long id) + { + int num = 3; + ObservableCollection observableCollection1 = await Task.Run>(() => { + ObservableCollection observableCollection; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + observableCollection = new ObservableCollection(read.get_RegistroLogRepository().FindByIdSingle(id)); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 69, num, new { id = id }, true); + continue; + } + return observableCollection; + } + return new ObservableCollection(); + }); + return observableCollection1; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/MalaDiretaServico.cs b/Codemerx/Gestor.Application/Servicos/MalaDiretaServico.cs new file mode 100644 index 0000000..3eb72d5 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/MalaDiretaServico.cs @@ -0,0 +1,188 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.MalaDireta; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos +{ + public class MalaDiretaServico : BaseServico + { + public MalaDiretaServico() + { + } + + public async Task> BuscarModelos() + { + int num = 3; + List modeloMalaDiretas1 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List modeloMalaDiretas = read.get_ModeloMalaDiretaRepository().Find(); + Func u003cu003e9_01 = MalaDiretaServico.u003cu003ec.u003cu003e9__0_1; + if (u003cu003e9_01 == null) + { + u003cu003e9_01 = (ModeloMalaDireta x) => x.get_Assunto(); + MalaDiretaServico.u003cu003ec.u003cu003e9__0_1 = u003cu003e9_01; + } + list = modeloMalaDiretas.OrderBy(u003cu003e9_01).ToList(); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 70, num, null, true); + continue; + } + return list; + } + return new List(); + }); + return modeloMalaDiretas1; + } + + public async Task Delete(ModeloMalaDireta modelo) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + string str; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + commited.get_ModeloMalaDiretaRepository().Delete(modelo.get_Id()); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(2); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(Funcoes.GetNetworkTime()); + ModeloMalaDireta modeloMalaDiretum = modelo; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(modeloMalaDiretum, jsonSerializerSetting)); + registroLog.set_EntidadeId(modelo.get_Id()); + registroLog.set_Tela(39); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_21 = MalaDiretaServico.u003cu003ec.u003cu003e9__2_1; + if (u003cu003e9_21 == null) + { + u003cu003e9_21 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + MalaDiretaServico.u003cu003ec.u003cu003e9__2_1 = u003cu003e9_21; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_21); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 255, num, modelo, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task Save(ModeloMalaDireta modelo) + { + int num = 3; + base.Sucesso = true; + ModeloMalaDireta modeloMalaDiretum2 = modelo; + ModeloMalaDireta modeloMalaDiretum3 = await Task.Run(() => { + ModeloMalaDireta modeloMalaDiretum; + string str; + while (num > 0) + { + modelo = modeloMalaDiretum2; + try + { + TipoAcao tipoAcao = (modelo.get_Id() == 0 ? 0 : 1); + using (UnitOfWork commited = Instancia.Commited) + { + modelo = (tipoAcao == null ? commited.get_ModeloMalaDiretaRepository().SaveOrUpdate(modelo) : commited.get_ModeloMalaDiretaRepository().Merge(modelo)); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(tipoAcao); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(Funcoes.GetNetworkTime()); + ModeloMalaDireta modeloMalaDiretum1 = modelo; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(modeloMalaDiretum1, jsonSerializerSetting)); + registroLog.set_EntidadeId(modelo.get_Id()); + registroLog.set_Tela(39); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_11 = MalaDiretaServico.u003cu003ec.u003cu003e9__1_1; + if (u003cu003e9_11 == null) + { + u003cu003e9_11 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + MalaDiretaServico.u003cu003ec.u003cu003e9__1_1 = u003cu003e9_11; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_11); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + modeloMalaDiretum = modelo; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 254, num, modelo, true); + continue; + } + return modeloMalaDiretum; + } + return modeloMalaDiretum2; + }); + return modeloMalaDiretum3; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/ParceiroServico.cs b/Codemerx/Gestor.Application/Servicos/ParceiroServico.cs new file mode 100644 index 0000000..b5b51f4 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/ParceiroServico.cs @@ -0,0 +1,123 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos +{ + internal class ParceiroServico : BaseServico + { + public ParceiroServico() + { + } + + internal async Task BuscarParceiro(long id) + { + int num = 3; + Parceiro parceiro1 = await Task.Run(() => { + Parceiro parceiro; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + parceiro = read.get_ParceiroRepository().FindById(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 71, num, id, true); + continue; + } + return parceiro; + } + return new Parceiro(); + }); + return parceiro1; + } + + public async Task Delete(Parceiro parceiro) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + List registroLogs = new List(); + try + { + using (UnitOfWork commited = Instancia.Commited) + { + registroLogs.Add(base.CreateLog(parceiro.get_Id(), parceiro.GetValorOriginal(), 22, 2)); + commited.get_ParceiroRepository().Delete(parceiro.get_Id()); + base.SaveLog(registroLogs, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 257, num, parceiro, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task Save(Parceiro parceiro) + { + int num = 3; + base.Sucesso = true; + Parceiro parceiro1 = parceiro; + Parceiro parceiro2 = await Task.Run(() => { + Parceiro parceiro3; + bool flag; + while (num > 0) + { + List registroLogs = new List(); + parceiro = parceiro1; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + flag = (parceiro.get_Id() == 0 ? false : true); + if (flag) + { + registroLogs.Add(base.CreateLog(parceiro.get_Id(), parceiro, 22)); + } + parceiro = (parceiro.get_Id() == 0 ? commited.get_ParceiroRepository().SaveOrUpdate(parceiro) : commited.get_ParceiroRepository().Merge(parceiro)); + if (!flag) + { + registroLogs.Add(base.CreateLog(parceiro.get_Id(), parceiro.GetValorOriginal(), 22, 0)); + } + base.SaveLog(registroLogs, commited); + commited.Commit(); + parceiro3 = parceiro; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 256, num, parceiro, true); + continue; + } + return parceiro3; + } + return parceiro1; + }); + return parceiro2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/ParcelaServico.cs b/Codemerx/Gestor.Application/Servicos/ParcelaServico.cs new file mode 100644 index 0000000..fcb987e --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/ParcelaServico.cs @@ -0,0 +1,1006 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Relatorios.PrevisaoPagamentoComissao; +using Gestor.Model.Domain.Seguros; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos +{ + internal class ParcelaServico : BaseServico + { + public ParcelaServico() + { + } + + public async Task BuscarApolice(long id) + { + int num = 3; + Documento documento1 = await Task.Run(() => { + Documento documento; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + documento = read.get_ParcelaRepository().BuscarApolice(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 3, num, id, true); + continue; + } + return documento; + } + return new Documento(); + }); + return documento1; + } + + public async Task> BuscarFatura(string numero) + { + int num = 3; + List documentos1 = await Task.Run>(() => { + List documentos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + documentos = read.get_ParcelaRepository().FindNumFatura(numero); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 322, num, numero, true); + continue; + } + return documentos; + } + return new List(); + }); + return documentos1; + } + + public async Task> BuscarFaturas(Filtros filtro, bool buscaAssinaturas = false, bool painelBi = false) + { + int num = 3; + List documentos1 = await Task.Run>(async () => { + List documentos; + while (true) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + documentos = await read.get_ParcelaRepository().BuscaDocumentosPorVigencia(filtro, buscaAssinaturas, painelBi); + return documentos; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 76, num, filtro, true); + } + if (num <= 0) + { + break; + } + } + documentos = new List(); + return documentos; + }); + return documentos1; + } + + public async Task BuscarLogAntigo(long id) + { + int num = 3; + string str1 = await Task.Run(() => { + string str; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + str = read.get_ParcelaRepository().BuscarLogAntigo(id, Gestor.Application.Helpers.Connection.GetConnectionString()); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 319, num, id, true); + continue; + } + return str; + } + return null; + }); + return str1; + } + + public async Task> BuscarPagamentoVendedor(Filtros filtro, bool reciboPagamento, bool segundaViaReciboPagamento) + { + int num = 3; + List vendedorParcelas1 = await Task.Run>(() => { + List vendedorParcelas; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + IParcelaRepository parcelaRepository = read.get_ParcelaRepository(); + Filtros filtro1 = filtro; + bool flag = reciboPagamento; + bool flag1 = segundaViaReciboPagamento; + List configuracoes = Recursos.Configuracoes; + Func u003cu003e9_201 = ParcelaServico.u003cu003ec.u003cu003e9__20_1; + if (u003cu003e9_201 == null) + { + u003cu003e9_201 = (ConfiguracaoSistema x) => x.get_Configuracao() == 34; + ParcelaServico.u003cu003ec.u003cu003e9__20_1 = u003cu003e9_201; + } + vendedorParcelas = parcelaRepository.FindByPagamento(filtro1, flag, flag1, configuracoes.Any(u003cu003e9_201)); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 80, num, filtro, true); + continue; + } + return vendedorParcelas; + } + return new List(); + }); + return vendedorParcelas1; + } + + public async Task BuscarParcela(long id) + { + int num = 3; + Parcela parcela1 = await Task.Run(() => { + Parcela parcela; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + parcela = read.get_ParcelaRepository().FindById(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 74, num, id, true); + continue; + } + return parcela; + } + return new Parcela(); + }); + return parcela1; + } + + internal async Task> BuscarParcelas(long id) + { + int num = 3; + List parcelas1 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List parcelas = read.get_ParcelaRepository().FindByDocumentId(id); + Func u003cu003e9_31 = ParcelaServico.u003cu003ec.u003cu003e9__3_1; + if (u003cu003e9_31 == null) + { + u003cu003e9_31 = (Parcela x) => x.get_NumeroParcela(); + ParcelaServico.u003cu003ec.u003cu003e9__3_1 = u003cu003e9_31; + } + list = parcelas.OrderBy(u003cu003e9_31).ToList(); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 73, num, id, true); + continue; + } + return list; + } + return new List(); + }); + return parcelas1; + } + + internal async Task> BuscarParcelas(string ids, List documentos) + { + int num = 3; + List documentos1 = await Task.Run>(() => { + List documentos2; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + documentos2 = read.get_ParcelaRepository().FindByDocumentIds(ids, documentos); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 75, num, null, true); + continue; + } + return documentos2; + } + return new List(); + }); + return documentos1; + } + + public async Task> BuscarParcelas(Filtros filtro, bool somenteAtivos = false) + { + int num = 3; + List parcelas1 = await Task.Run>(() => { + List parcelas; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + parcelas = read.get_ParcelaRepository().FindByPendente(filtro, false, somenteAtivos); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 79, num, filtro, true); + continue; + } + return parcelas; + } + return new List(); + }); + return parcelas1; + } + + internal async Task> BuscarParcelasAsync(long id) + { + int num = 3; + ObservableCollection observableCollection1 = await Task.Run>(() => { + ObservableCollection observableCollection; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List parcelas = read.get_ParcelaRepository().FindByDocumentId(id); + Func u003cu003e9_01 = ParcelaServico.u003cu003ec.u003cu003e9__0_1; + if (u003cu003e9_01 == null) + { + u003cu003e9_01 = (Parcela x) => x.get_NumeroParcela(); + ParcelaServico.u003cu003ec.u003cu003e9__0_1 = u003cu003e9_01; + } + observableCollection = new ObservableCollection(parcelas.OrderBy(u003cu003e9_01)); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 73, num, id, true); + continue; + } + return observableCollection; + } + return new ObservableCollection(); + }); + return observableCollection1; + } + + public async Task> BuscarParcelasPendentes(Filtros filtro, bool somenteAtivos = false) + { + int num = 3; + List parcelas1 = await Task.Run>(() => { + List parcelas; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + parcelas = read.get_ParcelaRepository().FindByPendente(filtro, true, somenteAtivos); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 78, num, filtro, true); + continue; + } + return parcelas; + } + return new List(); + }); + return parcelas1; + } + + internal async Task> BuscarParcelasPorDocumento(Documento documento) + { + int num = 3; + ObservableCollection observableCollection1 = await Task.Run>(() => { + ObservableCollection observableCollection; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List parcelas = read.get_ParcelaRepository().FindByDocumento(documento); + Func u003cu003e9_11 = ParcelaServico.u003cu003ec.u003cu003e9__1_1; + if (u003cu003e9_11 == null) + { + u003cu003e9_11 = (Parcela x) => x.get_NumeroParcela(); + ParcelaServico.u003cu003ec.u003cu003e9__1_1 = u003cu003e9_11; + } + observableCollection = new ObservableCollection(parcelas.OrderBy(u003cu003e9_11)); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 73, num, documento.get_Id(), true); + continue; + } + return observableCollection; + } + return new ObservableCollection(); + }); + return observableCollection1; + } + + public async Task> BuscarParcelasRecebimento(Filtros filtro) + { + int num = 3; + List parcelas1 = await Task.Run>(async () => { + List parcelas; + while (true) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + parcelas = await read.get_ParcelaRepository().FindByRecebimento(filtro); + return parcelas; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 77, num, filtro, true); + } + if (num <= 0) + { + break; + } + } + parcelas = new List(); + return parcelas; + }); + return parcelas1; + } + + public async Task> BuscarPrevisaoPagamentoComissao(Filtros filtro) + { + int num = 3; + List previsaoPagamentos1 = await Task.Run>(() => { + List previsaoPagamentos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + previsaoPagamentos = read.get_ParcelaRepository().PrevisaoPagamentoComissao(filtro); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 316, num, filtro, true); + continue; + } + return previsaoPagamentos; + } + return new List(); + }); + return previsaoPagamentos1; + } + + internal async Task> BuscarTodasParcelas(List ids) + { + int num = 3; + List parcelas1 = await Task.Run>(() => { + List parcelas; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + parcelas = read.get_ParcelaRepository().FindByDocumentId(ids); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 73, num, ids, true); + continue; + } + return parcelas; + } + return new List(); + }); + return parcelas1; + } + + internal async Task> BuscarVendedores(long id) + { + int num = 3; + List vendedors = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List vendedorParcelas = read.get_VendedorParcelaRepository().FindByDocumentId(id); + Func u003cu003e9_51 = ParcelaServico.u003cu003ec.u003cu003e9__5_1; + if (u003cu003e9_51 == null) + { + u003cu003e9_51 = (VendedorParcela x) => x.get_Vendedor().get_Id(); + ParcelaServico.u003cu003ec.u003cu003e9__5_1 = u003cu003e9_51; + } + IEnumerable> groupings = vendedorParcelas.GroupBy(u003cu003e9_51); + Func, Vendedor> u003cu003e9_52 = ParcelaServico.u003cu003ec.u003cu003e9__5_2; + if (u003cu003e9_52 == null) + { + u003cu003e9_52 = (IGrouping x) => x.First().get_Vendedor(); + ParcelaServico.u003cu003ec.u003cu003e9__5_2 = u003cu003e9_52; + } + list = groupings.Select, Vendedor>(u003cu003e9_52).ToList(); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 140, num, null, true); + continue; + } + return list; + } + return new List(); + }); + return vendedors; + } + + public async Task Delete(Parcela parcela, List todas) + { + int num = 3; + Funcoes.GetNetworkTime(); + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + commited.get_ParcelaRepository().Delete(parcela.get_Id()); + List registroLogs = new List() + { + base.CreateLog(parcela.get_Id(), parcela.GetValorOriginal(), 5, 2) + }; + base.SaveLog(registroLogs, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 190, num, parcela, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task DeletePagamentoRange(List repasses) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + commited.get_VendedorParcelaRepository().DeleteRange(repasses); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 21, num, repasses, false); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task> FaturaPendente(Filtros filtro) + { + int num = 3; + List documentos1 = await Task.Run>(async () => { + List documentos; + while (true) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + documentos = await read.get_ParcelaRepository().FaturaPendente(filtro); + return documentos; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 83, num, filtro, true); + } + if (num <= 0) + { + break; + } + } + documentos = new List(); + return documentos; + }); + return documentos1; + } + + public async Task GerarPagamento(List pagamentos) + { + int num = 3; + DateTime networkTime = Funcoes.GetNetworkTime(); + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + IVendedorParcelaRepository vendedorParcelaRepository = commited.get_VendedorParcelaRepository(); + List vendedorParcelas = pagamentos; + Func u003cu003e9_221 = ParcelaServico.u003cu003ec.u003cu003e9__22_1; + if (u003cu003e9_221 == null) + { + u003cu003e9_221 = (VendedorParcela x) => x.get_Id(); + ParcelaServico.u003cu003ec.u003cu003e9__22_1 = u003cu003e9_221; + } + if (vendedorParcelaRepository.GerarPagamento(vendedorParcelas.Select(u003cu003e9_221).ToList(), networkTime)) + { + commited.Commit(); + flag = true; + } + else + { + flag = false; + } + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 193, num, pagamentos, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task SalvarObservacoes(long id, string observacao) + { + int num = 3; + base.Sucesso = true; + Funcoes.GetNetworkTime(); + string str1 = await Task.Run(() => { + string str; + while (num > 0) + { + List registroLogs = new List(); + try + { + using (UnitOfWork commited = Instancia.Commited) + { + Parcela parcela = commited.get_ParcelaRepository().FindById(id); + parcela.Initialize(); + parcela.set_Observacao(observacao); + registroLogs.Add(base.CreateLog(parcela.get_Id(), parcela, 5)); + commited.get_ParcelaRepository().Merge(parcela); + base.SaveLog(registroLogs, commited); + commited.Commit(); + } + str = observacao; + } + catch (Exception exception) + { + num = base.Registrar(exception, 24, num, new { id = id, observacao = observacao }, true); + continue; + } + return str; + } + return ""; + }); + return str1; + } + + public async Task Save(Parcela parcela, List todas, List repasses = null, bool abrirTela = true) + { + Func func1 = null; + int num = 3; + base.Sucesso = true; + Parcela parcela2 = parcela; + List vendedorParcelas = repasses; + Funcoes.GetNetworkTime(); + ObservableCollection observableCollection1 = await this.BuscarParcelasAsync(parcela.get_Documento().get_Id()); + ObservableCollection observableCollection2 = observableCollection1; + Parcela parcela3 = await Task.Run(async () => { + Parcela parcela4; + while (num > 0) + { + try + { + ObservableCollection observableCollection = observableCollection2; + Func u003cu003e9_1 = func1; + if (u003cu003e9_1 == null) + { + Func id = (Parcela x) => x.get_Id() == parcela.get_Id(); + Func func = id; + func1 = id; + u003cu003e9_1 = func; + } + Parcela parcela1 = observableCollection.FirstOrDefault(u003cu003e9_1); + List registroLogs = new List(); + using (UnitOfWork commited = Instancia.Commited) + { + bool flag = parcela.get_Id() == (long)0; + parcela.set_IdEmpresa(parcela.get_Documento().get_Controle().get_IdEmpresa()); + parcela = (flag ? commited.get_ParcelaRepository().SaveOrUpdate(parcela) : commited.get_ParcelaRepository().Merge(parcela)); + if (repasses != null) + { + foreach (VendedorParcela repass in repasses) + { + repass.set_Documento(parcela.get_Documento()); + repass.set_Parcela(parcela); + if (repass.get_Id() != 0) + { + commited.get_VendedorParcelaRepository().Merge(repass); + } + else + { + commited.get_VendedorParcelaRepository().SaveOrUpdate(repass); + } + } + parcela.set_Vendedores(new ObservableCollection(repasses)); + } + if (!flag) + { + registroLogs.Add(base.CreateLog(parcela.get_Id(), parcela.Compare(parcela1.GetValorOriginal()), 5, 1)); + } + else + { + registroLogs.Add(base.CreateLog(parcela.get_Id(), parcela.GetValorOriginal(), 5, 0)); + } + base.SaveLog(registroLogs, commited); + commited.Commit(); + parcela4 = parcela; + return parcela4; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 24, num, parcela2, abrirTela); + } + } + parcela2.set_Vendedores((vendedorParcelas != null ? new ObservableCollection(vendedorParcelas) : null)); + parcela4 = parcela2; + return parcela4; + }); + return parcela3; + } + + public async Task Save(VendedorParcela pagamento) + { + int num = 3; + base.Sucesso = true; + Funcoes.GetNetworkTime(); + VendedorParcela vendedorParcela2 = await Task.Run(() => { + VendedorParcela vendedorParcela; + while (num > 0) + { + VendedorParcela vendedorParcela1 = pagamento; + try + { + List registroLogs = new List(); + using (UnitOfWork commited = Instancia.Commited) + { + vendedorParcela1 = (vendedorParcela1.get_Id() == 0 ? commited.get_VendedorParcelaRepository().SaveOrUpdate(vendedorParcela1) : commited.get_VendedorParcelaRepository().Merge(vendedorParcela1)); + if (pagamento.get_Id() != 0) + { + registroLogs.Add(base.CreateLog(vendedorParcela1.get_Id(), vendedorParcela1.Compare(vendedorParcela1.GetValorOriginal()), 37, 1)); + } + else + { + registroLogs.Add(base.CreateLog(vendedorParcela1.get_Id(), vendedorParcela1.GetValorOriginal(), 37, 0)); + } + base.SaveLog(registroLogs, commited); + commited.Commit(); + vendedorParcela = vendedorParcela1; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 189, num, pagamento, true); + continue; + } + return vendedorParcela; + } + return pagamento; + }); + return vendedorParcela2; + } + + public async Task> SaveRange(List parcela) + { + int num = 3; + base.Sucesso = true; + List parcelas2 = await Task.Run>(() => { + List parcelas; + while (num > 0) + { + List parcelas1 = parcela; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + foreach (Parcela parcela1 in parcelas1) + { + if (parcela1.get_Id() != 0) + { + commited.get_ParcelaRepository().Merge(parcela1); + } + else + { + parcela1.set_IdEmpresa(parcela1.get_Documento().get_Controle().get_IdEmpresa()); + commited.get_ParcelaRepository().SaveOrUpdate(parcela1); + } + } + commited.Commit(); + parcelas = parcelas1; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 24, num, parcela, true); + continue; + } + return parcelas; + } + return parcela; + }); + return parcelas2; + } + + public async Task SaveRange(List repasses) + { + int num = 3; + List vendedorParcelas1 = repasses; + Funcoes.GetNetworkTime(); + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + repasses = vendedorParcelas1; + try + { + List registroLogs = new List(); + using (UnitOfWork commited = Instancia.Commited) + { + List vendedorParcelas = repasses; + if (vendedorParcelas != null) + { + vendedorParcelas.ForEach((VendedorParcela x) => { + x.get_Id(); + x = (x.get_Id() == 0 ? commited.get_VendedorParcelaRepository().SaveOrUpdate(x) : commited.get_VendedorParcelaRepository().Merge(x)); + if (x.get_Id() == 0) + { + registroLogs.Add(base.CreateLog(x.get_Id(), x.GetValorOriginal(), 37, 0)); + return; + } + registroLogs.Add(base.CreateLog(x.get_Id(), x.Compare(x.GetValorOriginal()), 37, 1)); + }); + } + else + { + } + base.SaveLog(registroLogs, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 189, num, repasses, false); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task TemPagamento(long id) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + flag = read.get_VendedorParcelaRepository().TemPagamentoParcela(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 82, num, id, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task UpdateDetalhes(List detalhes) + { + int num = 3; + DateTime networkTime = Funcoes.GetNetworkTime(); + bool flag3 = await Task.Run(() => { + bool flag; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + List configuracoes = Recursos.Configuracoes; + Func u003cu003e9_141 = ParcelaServico.u003cu003ec.u003cu003e9__14_1; + if (u003cu003e9_141 == null) + { + u003cu003e9_141 = (ConfiguracaoSistema x) => x.get_Configuracao() == 51; + ParcelaServico.u003cu003ec.u003cu003e9__14_1 = u003cu003e9_141; + } + bool flag1 = configuracoes.Any(u003cu003e9_141); + bool flag2 = commited.get_ParcelaRepository().Update(detalhes, flag1); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + detalhes.ForEach((DetalheExtrato x) => { + string str; + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(1); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(x, jsonSerializerSetting)); + registroLog.set_EntidadeId(x.get_Id()); + registroLog.set_Tela(23); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_143 = ParcelaServico.u003cu003ec.u003cu003e9__14_3; + if (u003cu003e9_143 == null) + { + u003cu003e9_143 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + ParcelaServico.u003cu003ec.u003cu003e9__14_3 = u003cu003e9_143; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_143); + str = (pAddress != null ? pAddress.ToString() : null); + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + }); + commited.Commit(); + flag = flag2; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 192, num, detalhes, true); + continue; + } + return flag; + } + return false; + }); + return flag3; + } + + public async Task> UpdateRange(List parcelas) + { + base.Sucesso = true; + int num = 3; + List parcelas1 = parcelas; + Funcoes.GetNetworkTime(); + List parcelas2 = await Task.Run>(() => { + List parcelas3; + while (num > 0) + { + parcelas = parcelas1; + try + { + List registroLogs = new List(); + using (UnitOfWork commited = Instancia.Commited) + { + parcelas = commited.get_ParcelaRepository().UpdateRange(parcelas); + parcelas.ForEach((Parcela x) => { + registroLogs.Add(base.CreateLog(x.get_Id(), x.Compare(x.GetValorOriginal()), 5, 1)); + base.SaveLog(registroLogs, commited); + }); + commited.Commit(); + parcelas3 = parcelas; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 24, num, parcelas, false); + continue; + } + return parcelas3; + } + return parcelas1; + }); + return parcelas2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/PermissaoArquivoDigitalServico.cs b/Codemerx/Gestor.Application/Servicos/PermissaoArquivoDigitalServico.cs new file mode 100644 index 0000000..525efc6 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/PermissaoArquivoDigitalServico.cs @@ -0,0 +1,167 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos +{ + public class PermissaoArquivoDigitalServico : BaseServico + { + public PermissaoArquivoDigitalServico() + { + } + + public PermissaoArquivoDigital BuscarPermissao(Usuario usuario, TipoArquivoDigital tela) + { + PermissaoArquivoDigital permissaoArquivoDigital; + int num = 3; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + PermissaoArquivoDigital permissaoArquivoDigital1 = read.get_PermissaoArquivoDigitalRepository().FindByPermissao(usuario.get_Id(), tela); + if (permissaoArquivoDigital1 != null) + { + permissaoArquivoDigital = permissaoArquivoDigital1; + } + else + { + PermissaoArquivoDigital permissaoArquivoDigital2 = new PermissaoArquivoDigital(); + permissaoArquivoDigital2.set_Usuario(usuario); + permissaoArquivoDigital2.set_Tela(tela); + permissaoArquivoDigital2.set_Consultar(true); + permissaoArquivoDigital2.set_Excluir(true); + permissaoArquivoDigital2.set_Incluir(true); + permissaoArquivoDigital = permissaoArquivoDigital2; + } + } + } + catch (Exception exception1) + { + Exception exception = exception1; + num = base.Registrar(exception, 85, num, new { usuario = usuario, tela = tela }, true); + continue; + } + return permissaoArquivoDigital; + } + return null; + } + + public async Task> PermissArquivoDigital(Usuario usuario) + { + int num = 3; + List permissaoArquivoDigitals1 = await Task.Run>(() => { + List permissaoArquivoDigitals; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + permissaoArquivoDigitals = read.get_PermissaoArquivoDigitalRepository().FindByUsuario(usuario.get_Id()); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 84, num, usuario, true); + continue; + } + return permissaoArquivoDigitals; + } + return new List(); + }); + return permissaoArquivoDigitals1; + } + + public async Task> SavePermiss(List permissao, List prev) + { + int num = 3; + base.Sucesso = true; + List permissaoArquivoDigitals1 = permissao; + List permissaoArquivoDigitals2 = prev; + List permissaoArquivoDigitals3 = await Task.Run>(() => { + List permissaoArquivoDigitals; + while (num > 0) + { + permissao = permissaoArquivoDigitals1; + prev = permissaoArquivoDigitals2; + List diferencas = new List(); + List registroLogs = new List(); + try + { + using (UnitOfWork commited = Instancia.Commited) + { + permissao.ForEach((PermissaoArquivoDigital x) => { + PermissaoArquivoDigital permissaoArquivoDigital = x; + PermissaoArquivoDigital permissaoArquivoDigital1 = prev.FirstOrDefault((PermissaoArquivoDigital y) => y.get_Id() == permissaoArquivoDigital.get_Id()); + if (permissaoArquivoDigital1 != null && permissaoArquivoDigital1.get_Consultar() == permissaoArquivoDigital.get_Consultar() && permissaoArquivoDigital1.get_Excluir() == permissaoArquivoDigital.get_Excluir() && permissaoArquivoDigital1.get_Incluir() == permissaoArquivoDigital.get_Incluir()) + { + return; + } + if (permissaoArquivoDigital1 != null) + { + registroLogs.Add(base.CreateLog(permissaoArquivoDigital.get_Usuario().get_Id(), permissaoArquivoDigital.Compare(permissaoArquivoDigital1.GetValorOriginal()), 43, 1)); + } + else + { + registroLogs.Add(base.CreateLog(permissaoArquivoDigital.get_Usuario().get_Id(), permissaoArquivoDigital.GetValorOriginal(), 43, 0)); + } + permissaoArquivoDigital = (permissaoArquivoDigital.get_Id() == 0 ? commited.get_PermissaoArquivoDigitalRepository().SaveOrUpdate(permissaoArquivoDigital) : commited.get_PermissaoArquivoDigitalRepository().Merge(permissaoArquivoDigital)); + }); + base.SaveLog(registroLogs, commited); + commited.Commit(); + permissaoArquivoDigitals = permissao; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 258, num, new { permissao = permissao, prev = prev }, true); + continue; + } + return permissaoArquivoDigitals; + } + return permissaoArquivoDigitals1; + }); + return permissaoArquivoDigitals3; + } + + public async Task VerificarPermissao(Usuario usuario, TipoArquivoDigital tela) + { + int num = 3; + PermissaoArquivoDigital permissaoArquivoDigital1 = await Task.Run(() => { + PermissaoArquivoDigital permissaoArquivoDigital; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + permissaoArquivoDigital = read.get_PermissaoArquivoDigitalRepository().FindByPermissao(usuario.get_Id(), tela); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 85, num, new { usuario = usuario, tela = tela }, true); + continue; + } + return permissaoArquivoDigital; + } + return null; + }); + return permissaoArquivoDigital1; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/PermissaoUsuarioServico.cs b/Codemerx/Gestor.Application/Servicos/PermissaoUsuarioServico.cs new file mode 100644 index 0000000..061797e --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/PermissaoUsuarioServico.cs @@ -0,0 +1,152 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos +{ + public class PermissaoUsuarioServico : BaseServico + { + public PermissaoUsuarioServico() + { + } + + public PermissaoUsuario BuscarPermissao(Usuario usuario, TipoTela tela) + { + PermissaoUsuario permissaoUsuario; + int num = 3; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + permissaoUsuario = read.get_PermissaoUsuarioRepository().FindByPermissao(usuario.get_Id(), tela); + } + } + catch (Exception exception1) + { + Exception exception = exception1; + num = base.Registrar(exception, 85, num, new { usuario = usuario, tela = tela }, true); + continue; + } + return permissaoUsuario; + } + return null; + } + + public async Task> PermissUsuario(Usuario usuario) + { + int num = 3; + List permissaoUsuarios1 = await Task.Run>(() => { + List permissaoUsuarios; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + permissaoUsuarios = read.get_PermissaoUsuarioRepository().FindByUsuario(usuario.get_Id()); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 84, num, usuario, true); + continue; + } + return permissaoUsuarios; + } + return new List(); + }); + return permissaoUsuarios1; + } + + public async Task> SavePermiss(List permissao, List prev) + { + int num = 3; + base.Sucesso = true; + List permissaoUsuarios1 = permissao; + List permissaoUsuarios2 = prev; + List permissaoUsuarios3 = await Task.Run>(() => { + List permissaoUsuarios; + List registroLogs = new List(); + while (num > 0) + { + permissao = permissaoUsuarios1; + prev = permissaoUsuarios2; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + permissao.ForEach((PermissaoUsuario x) => { + PermissaoUsuario permissaoUsuario = x; + PermissaoUsuario permissaoUsuario1 = prev.FirstOrDefault((PermissaoUsuario y) => y.get_Id() == permissaoUsuario.get_Id()); + if (permissaoUsuario1 != null && permissaoUsuario1.get_Alterar() == permissaoUsuario.get_Alterar() && permissaoUsuario1.get_Consultar() == permissaoUsuario.get_Consultar() && permissaoUsuario1.get_Excluir() == permissaoUsuario.get_Excluir() && permissaoUsuario1.get_Incluir() == permissaoUsuario.get_Incluir()) + { + return; + } + if (permissaoUsuario1 != null) + { + registroLogs.Add(base.CreateLog(permissaoUsuario.get_Usuario().get_Id(), permissaoUsuario.Compare(permissaoUsuario1.GetValorOriginal()), 43, 1)); + } + else + { + registroLogs.Add(base.CreateLog(permissaoUsuario.get_Usuario().get_Id(), permissaoUsuario.GetValorOriginal(), 43, 0)); + } + permissaoUsuario = (permissaoUsuario.get_Id() == 0 ? commited.get_PermissaoUsuarioRepository().SaveOrUpdate(permissaoUsuario) : commited.get_PermissaoUsuarioRepository().Merge(permissaoUsuario)); + }); + base.SaveLog(registroLogs, commited); + commited.Commit(); + permissaoUsuarios = permissao; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 258, num, new { permissao = permissao, prev = prev }, true); + continue; + } + return permissaoUsuarios; + } + return permissaoUsuarios1; + }); + return permissaoUsuarios3; + } + + public async Task VerificarPermissao(Usuario usuario, TipoTela tela) + { + int num = 3; + PermissaoUsuario permissaoUsuario1 = await Task.Run(() => { + PermissaoUsuario permissaoUsuario; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + permissaoUsuario = read.get_PermissaoUsuarioRepository().FindByPermissao(usuario.get_Id(), tela); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 85, num, new { usuario = usuario, tela = tela }, true); + continue; + } + return permissaoUsuario; + } + return null; + }); + return permissaoUsuario1; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/ProspeccaoServico.cs b/Codemerx/Gestor.Application/Servicos/ProspeccaoServico.cs new file mode 100644 index 0000000..ab7ab6f --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/ProspeccaoServico.cs @@ -0,0 +1,338 @@ +using Gestor.Application.Actions; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Threading; + +namespace Gestor.Application.Servicos +{ + public class ProspeccaoServico : BaseServico + { + public ProspeccaoServico() + { + } + + public async Task BuscarProspeccao(long id) + { + int num = 3; + Prospeccao prospeccao1 = await Task.Run(() => { + Prospeccao prospeccao; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + prospeccao = read.get_ProspectRepository().FindById(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 87, num, id, true); + continue; + } + return prospeccao; + } + return new Prospeccao(); + }); + return prospeccao1; + } + + internal async Task> BuscarProspeccoes(long id, DateTime inicio, DateTime fim, StatusProspeccao? status) + { + int num = 3; + List prospeccaos1 = await Task.Run>(() => { + List prospeccaos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + prospeccaos = read.get_ProspectRepository().Find(Recursos.Empresa.get_Id(), id, inicio, fim, status); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 86, num, new { id = id, inicio = inicio, fim = fim, status = status }, true); + continue; + } + return prospeccaos; + } + return new List(); + }); + return prospeccaos1; + } + + public async Task> BuscarProspeccoes(Filtros filtro) + { + int num = 3; + List prospeccaos1 = await Task.Run>(() => { + List prospeccaos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + prospeccaos = read.get_ProspectRepository().Find(filtro); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 88, num, filtro, true); + continue; + } + return prospeccaos; + } + return new List(); + }); + return prospeccaos1; + } + + public async Task> BuscarProspeccoesPorStatus(StatusDeProspeccao statusProspeccao) + { + int num = 3; + List prospeccaos1 = await Task.Run>(() => { + List prospeccaos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + prospeccaos = read.get_ProspectRepository().FindByStatusPersonalizado(statusProspeccao.get_Id()); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 310, num, new { statusProspeccao = statusProspeccao }, true); + continue; + } + return prospeccaos; + } + return new List(); + }); + return prospeccaos1; + } + + public async Task Delete(Prospeccao prospeccao) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + string str; + string str1; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + if (prospeccao.get_Tarefa() != null) + { + commited.get_TarefaRepository().Excluir(prospeccao.get_Tarefa().get_Id()); + } + commited.get_ProspectRepository().Delete(prospeccao.get_Id()); + DateTime networkTime = Funcoes.GetNetworkTime(); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + if (prospeccao.get_Tarefa() != null) + { + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(2); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + Tarefa tarefa = prospeccao.get_Tarefa(); + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(tarefa, jsonSerializerSetting)); + registroLog.set_EntidadeId(prospeccao.get_Tarefa().get_Id()); + registroLog.set_Tela(38); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_22 = ProspeccaoServico.u003cu003ec.u003cu003e9__2_2; + if (u003cu003e9_22 == null) + { + u003cu003e9_22 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + ProspeccaoServico.u003cu003ec.u003cu003e9__2_2 = u003cu003e9_22; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_22); + if (pAddress != null) + { + str1 = pAddress.ToString(); + } + else + { + str1 = null; + } + registroLog.set_Ip(str1); + base.SaveLog(registroLog, commited); + } + RegistroLog registroLog1 = new RegistroLog(); + registroLog1.set_Acao(2); + registroLog1.set_Usuario(Recursos.Usuario); + registroLog1.set_DataHora(networkTime); + Prospeccao prospeccao1 = prospeccao; + JsonSerializerSettings jsonSerializerSetting1 = new JsonSerializerSettings(); + jsonSerializerSetting1.set_ReferenceLoopHandling(1); + registroLog1.set_Descricao(JsonConvert.SerializeObject(prospeccao1, jsonSerializerSetting1)); + registroLog1.set_EntidadeId(prospeccao.get_Id()); + registroLog1.set_Tela(33); + registroLog1.set_Versao(LoginViewModel.VersaoAtual); + registroLog1.set_NomeMaquina(Environment.MachineName); + registroLog1.set_UsuarioMaquina(Environment.UserName); + IPAddress[] pAddressArray = hostEntry.AddressList; + Func u003cu003e9_23 = ProspeccaoServico.u003cu003ec.u003cu003e9__2_3; + if (u003cu003e9_23 == null) + { + u003cu003e9_23 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + ProspeccaoServico.u003cu003ec.u003cu003e9__2_3 = u003cu003e9_23; + } + IPAddress pAddress1 = ((IEnumerable)pAddressArray).FirstOrDefault(u003cu003e9_23); + if (pAddress1 != null) + { + str = pAddress1.ToString(); + } + else + { + str = null; + } + registroLog1.set_Ip(str); + base.SaveLog(registroLog1, commited); + commited.Commit(); + } + Dispatcher dispatcher = System.Windows.Application.Current.Dispatcher; + Action u003cu003e9_21 = ProspeccaoServico.u003cu003ec.u003cu003e9__2_1; + if (u003cu003e9_21 == null) + { + u003cu003e9_21 = () => Gestor.Application.Actions.Actions.AtualizaBadges(); + ProspeccaoServico.u003cu003ec.u003cu003e9__2_1 = u003cu003e9_21; + } + dispatcher.Invoke(u003cu003e9_21); + flag = true; + } + catch (Exception exception) + { + num = base.Registrar(exception, 260, num, prospeccao, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task Salvar(Prospeccao prospecao) + { + int num = 3; + base.Sucesso = true; + Prospeccao prospeccao2 = prospecao; + Prospeccao prospeccao3 = await Task.Run(() => { + Prospeccao prospeccao; + string str; + while (num > 0) + { + prospecao = prospeccao2; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + DateTime networkTime = Funcoes.GetNetworkTime(); + TipoAcao tipoAcao = (prospecao.get_Id() == 0 ? 0 : 1); + prospecao.set_IdEmpresa(Recursos.Usuario.get_IdEmpresa()); + if (!prospecao.get_DataCriacao().HasValue) + { + prospecao.set_DataCriacao(new DateTime?(networkTime)); + } + if (prospecao.get_UsuarioCriacao() == 0) + { + prospecao.set_UsuarioCriacao(Recursos.Usuario.get_Id()); + } + Tarefa tarefa = prospecao.get_Tarefa(); + tarefa = (!prospecao.get_CriarTarefa() ? null : (tarefa.get_Id() == 0 ? commited.get_TarefaRepository().Salvar(tarefa) : commited.get_TarefaRepository().Atualizar(tarefa))); + prospecao.set_Tarefa(tarefa); + prospecao = (prospecao.get_Id() == 0 ? commited.get_ProspectRepository().SaveOrUpdate(prospecao) : commited.get_ProspectRepository().Merge(prospecao)); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + if (prospecao.get_Tarefa() != null) + { + prospecao.get_Tarefa().set_IdEntidade(prospecao.get_Id()); + prospecao.set_Tarefa(commited.get_TarefaRepository().Atualizar(prospecao.get_Tarefa())); + } + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(tipoAcao); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + Prospeccao prospeccao1 = prospecao; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(prospeccao1, jsonSerializerSetting)); + registroLog.set_EntidadeId(prospecao.get_Id()); + registroLog.set_Tela(33); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_12 = ProspeccaoServico.u003cu003ec.u003cu003e9__1_2; + if (u003cu003e9_12 == null) + { + u003cu003e9_12 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + ProspeccaoServico.u003cu003ec.u003cu003e9__1_2 = u003cu003e9_12; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_12); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + Dispatcher dispatcher = System.Windows.Application.Current.Dispatcher; + Action u003cu003e9_11 = ProspeccaoServico.u003cu003ec.u003cu003e9__1_1; + if (u003cu003e9_11 == null) + { + u003cu003e9_11 = () => Gestor.Application.Actions.Actions.AtualizaBadges(); + ProspeccaoServico.u003cu003ec.u003cu003e9__1_1 = u003cu003e9_11; + } + dispatcher.Invoke(u003cu003e9_11); + prospeccao = prospecao; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 259, num, prospecao, true); + continue; + } + return prospeccao; + } + return prospeccao2; + }); + return prospeccao3; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/RestricaoUsuarioServico.cs b/Codemerx/Gestor.Application/Servicos/RestricaoUsuarioServico.cs new file mode 100644 index 0000000..c9cbe35 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/RestricaoUsuarioServico.cs @@ -0,0 +1,221 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos +{ + public class RestricaoUsuarioServico : BaseServico + { + public RestricaoUsuarioServico() + { + } + + public RestricaoUsuario BuscarRestricao(Usuario usuario, TipoRestricao restricao) + { + RestricaoUsuario restricaoUsuario; + int num = 3; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + restricaoUsuario = read.get_RestricaoUsuarioRepository().FindRestricao(usuario.get_Id(), restricao); + } + } + catch (Exception exception1) + { + Exception exception = exception1; + num = base.Registrar(exception, 89, num, new { usuario = usuario, restricao = restricao }, true); + continue; + } + return restricaoUsuario; + } + return null; + } + + public async Task> BuscarRestricoes(long id) + { + int num = 3; + List restricaoUsuarios1 = await Task.Run>(() => { + List restricaoUsuarios; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + restricaoUsuarios = read.get_RestricaoUsuarioRepository().FindByUsuario(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 90, num, id, true); + continue; + } + return restricaoUsuarios; + } + return new List(); + }); + return restricaoUsuarios1; + } + + public async Task> BuscarRestricoesCamposRelatorios(long id) + { + int num = 3; + List restricaoUsuarioCamposRelatorios1 = await Task.Run>(() => { + List restricaoUsuarioCamposRelatorios; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + restricaoUsuarioCamposRelatorios = read.get_RestricaoUsuarioCamposRelatoriosRepository().FindByUsuario(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 90, num, id, true); + continue; + } + return restricaoUsuarioCamposRelatorios; + } + return new List(); + }); + return restricaoUsuarioCamposRelatorios1; + } + + public async Task> SaveRestri(List restricoes, List prev) + { + int num = 3; + base.Sucesso = true; + List restricaoUsuarios1 = restricoes; + List restricaoUsuarios2 = prev; + List restricaoUsuarios3 = await Task.Run>(() => { + List restricaoUsuarios; + while (num > 0) + { + List diferencas = new List(); + List registroLogs = new List(); + restricoes = restricaoUsuarios1; + prev = restricaoUsuarios2; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + restricoes.ForEach((RestricaoUsuario x) => { + RestricaoUsuario restricaoUsuario = x; + RestricaoUsuario restricaoUsuario1 = prev.FirstOrDefault((RestricaoUsuario y) => { + if (restricaoUsuario.get_Id() != 0) + { + return y.get_Id() == restricaoUsuario.get_Id(); + } + return y.get_Tipo() == restricaoUsuario.get_Tipo(); + }); + if (restricaoUsuario1 != null && restricaoUsuario1.get_Restricao() == restricaoUsuario.get_Restricao()) + { + return; + } + if (restricaoUsuario1 != null) + { + registroLogs.Add(base.CreateLog(restricaoUsuario.get_Usuario().get_Id(), restricaoUsuario.Compare(restricaoUsuario1.GetValorOriginal()), 43, 1)); + } + else + { + registroLogs.Add(base.CreateLog(restricaoUsuario.get_Usuario().get_Id(), restricaoUsuario.GetValorOriginal(), 43, 0)); + } + restricaoUsuario = (restricaoUsuario.get_Id() == 0 ? commited.get_RestricaoUsuarioRepository().SaveOrUpdate(restricaoUsuario) : commited.get_RestricaoUsuarioRepository().Merge(restricaoUsuario)); + }); + base.SaveLog(registroLogs, commited); + commited.Commit(); + restricaoUsuarios = restricoes; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 261, num, new { restricoes = restricoes, prev = prev }, true); + continue; + } + return restricaoUsuarios; + } + return restricaoUsuarios1; + }); + return restricaoUsuarios3; + } + + public async Task> SaveRestriCamposRelatorios(List restricoes, List prev) + { + int num = 3; + base.Sucesso = true; + List restricaoUsuarioCamposRelatorios1 = restricoes; + List restricaoUsuarioCamposRelatorios2 = prev; + List restricaoUsuarioCamposRelatorios3 = await Task.Run>(() => { + List restricaoUsuarioCamposRelatorios; + while (num > 0) + { + List diferencas = new List(); + List registroLogs = new List(); + restricoes = restricaoUsuarioCamposRelatorios1; + prev = restricaoUsuarioCamposRelatorios2; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + restricoes.ForEach((RestricaoUsuarioCamposRelatorios x) => { + RestricaoUsuarioCamposRelatorios restricaoUsuarioCamposRelatorio = x; + RestricaoUsuarioCamposRelatorios restricaoUsuarioCamposRelatorio1 = prev.FirstOrDefault((RestricaoUsuarioCamposRelatorios y) => { + if (y.get_Id() != 0) + { + return y.get_Id() == restricaoUsuarioCamposRelatorio.get_Id(); + } + if (y.get_Campo() != restricaoUsuarioCamposRelatorio.get_Campo()) + { + return false; + } + return y.get_Relatorio() == restricaoUsuarioCamposRelatorio.get_Relatorio(); + }); + if (restricaoUsuarioCamposRelatorio1 != null && restricaoUsuarioCamposRelatorio1.get_Restricao() == restricaoUsuarioCamposRelatorio.get_Restricao()) + { + return; + } + if (restricaoUsuarioCamposRelatorio1 != null) + { + registroLogs.Add(base.CreateLog(restricaoUsuarioCamposRelatorio.get_Usuario().get_Id(), restricaoUsuarioCamposRelatorio.Compare(restricaoUsuarioCamposRelatorio1.GetValorOriginal()), 43, 1)); + } + else + { + registroLogs.Add(base.CreateLog(restricaoUsuarioCamposRelatorio.get_Usuario().get_Id(), restricaoUsuarioCamposRelatorio.GetValorOriginal(), 43, 0)); + } + restricaoUsuarioCamposRelatorio = (restricaoUsuarioCamposRelatorio.get_Id() == 0 ? commited.get_RestricaoUsuarioCamposRelatoriosRepository().SaveOrUpdate(restricaoUsuarioCamposRelatorio) : commited.get_RestricaoUsuarioCamposRelatoriosRepository().Merge(restricaoUsuarioCamposRelatorio)); + }); + base.SaveLog(registroLogs, commited); + commited.Commit(); + restricaoUsuarioCamposRelatorios = restricoes; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 261, num, new { restricoes = restricoes, prev = prev }, true); + continue; + } + return restricaoUsuarioCamposRelatorios; + } + return restricaoUsuarioCamposRelatorios1; + }); + return restricaoUsuarioCamposRelatorios3; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Seguros/ApoliceServico.cs b/Codemerx/Gestor.Application/Servicos/Seguros/ApoliceServico.cs new file mode 100644 index 0000000..0aae6a5 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Seguros/ApoliceServico.cs @@ -0,0 +1,1848 @@ +using CsQuery.ExtensionMethods; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Relatorios.Fechamento; +using Gestor.Model.Domain.Relatorios.Tarefa; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.License; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Seguros +{ + internal class ApoliceServico : BaseServico + { + private bool _carregando; + + public ApoliceServico() + { + } + + public async Task AtualizarNumero(long id, string numero, string endosso, int tipoDocumento) + { + bool flag2 = await Task.Run(() => { + bool flag; + try + { + bool flag1 = true; + using (UnitOfWork commited = Instancia.Commited) + { + flag1 = commited.get_DocumentoRepository().AtualizarNumero(id, numero, endosso, tipoDocumento); + commited.Commit(); + } + flag = flag1; + } + catch (Exception exception) + { + flag = false; + } + return flag; + }); + return flag2; + } + + public async Task> Auditoria(Filtros filtro) + { + int num = 3; + List documentos1 = await Task.Run>(() => { + List documentos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + documentos = read.get_DocumentoRepository().Auditoria(filtro); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 13, num, filtro, true); + continue; + } + return documentos; + } + return new List(); + }); + return documentos1; + } + + public async Task BaixarParcelasCancelamento(Documento documento, bool estorno) + { + int num1 = 3; + base.Sucesso = true; + DateTime networkTime = Funcoes.GetNetworkTime(); + bool flag1 = await Task.Run(() => { + bool flag; + string str1; + Action action3 = null; + Action action4 = null; + while (num1 > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + commited.get_ParcelaRepository().FindByDocumentId(documento.get_Id()).ToList().ForEach((Parcela x) => { + Action action; + List vendedorParcelas = commited.get_VendedorParcelaRepository().FindByParcela(x.get_Id()); + if (vendedorParcelas.Count > 0) + { + if (!estorno) + { + List vendedorParcelas1 = vendedorParcelas; + Func u003cu003e9_302 = ApoliceServico.u003cu003ec.u003cu003e9__30_2; + if (u003cu003e9_302 == null) + { + u003cu003e9_302 = (VendedorParcela v) => !v.get_DataPrePagamento().HasValue; + ApoliceServico.u003cu003ec.u003cu003e9__30_2 = u003cu003e9_302; + } + List list = vendedorParcelas1.Where(u003cu003e9_302).ToList(); + Action u003cu003e9_3 = action4; + if (u003cu003e9_3 == null) + { + Action action1 = (VendedorParcela v) => { + v.set_ValorRepasse(new decimal?(new decimal())); + v.set_DataPagamento(new DateTime?(networkTime)); + v.set_DataPrePagamento(new DateTime?(v.get_DataPrePagamento().GetValueOrDefault(networkTime))); + commited.get_VendedorParcelaRepository().Merge(v); + }; + action = action1; + action4 = action1; + u003cu003e9_3 = action; + } + list.ForEach(u003cu003e9_3); + } + else + { + string str = (documento.get_Tipo() == 0 ? string.Concat(" PROPOSTA ", documento.get_Proposta(), " DO CLIENTE ", documento.get_Controle().get_Cliente().get_Nome()) : string.Concat(" PROPOSTA DE ENDOSSO ", documento.get_PropostaEndosso(), " DO CLIENTE ", documento.get_Controle().get_Cliente().get_Nome())); + List vendedorParcelas2 = vendedorParcelas; + Func u003cu003e9_304 = ApoliceServico.u003cu003ec.u003cu003e9__30_4; + if (u003cu003e9_304 == null) + { + u003cu003e9_304 = (VendedorParcela v) => v.get_DataPagamento().HasValue; + ApoliceServico.u003cu003ec.u003cu003e9__30_4 = u003cu003e9_304; + } + IEnumerable vendedorParcelas3 = vendedorParcelas2.Where(u003cu003e9_304); + Func u003cu003e9_305 = ApoliceServico.u003cu003ec.u003cu003e9__30_5; + if (u003cu003e9_305 == null) + { + u003cu003e9_305 = (VendedorParcela v) => v.get_Vendedor().get_Id(); + ApoliceServico.u003cu003ec.u003cu003e9__30_5 = u003cu003e9_305; + } + List adiantamentos = vendedorParcelas3.GroupBy(u003cu003e9_305).Select, Adiantamento>((IGrouping v) => { + Adiantamento adiantamento = new Adiantamento(); + adiantamento.set_Vendedor(v.First().get_Vendedor()); + adiantamento.set_Data(new DateTime?(networkTime)); + IGrouping nums = v; + Func u003cu003e9_309 = ApoliceServico.u003cu003ec.u003cu003e9__30_9; + if (u003cu003e9_309 == null) + { + u003cu003e9_309 = (VendedorParcela s) => s.get_ValorRepasse().HasValue; + ApoliceServico.u003cu003ec.u003cu003e9__30_9 = u003cu003e9_309; + } + adiantamento.set_Valor(nums.Where(u003cu003e9_309).Sum((VendedorParcela s) => { + decimal? nullable; + decimal? nullable1; + decimal? valorRepasse = s.get_ValorRepasse(); + decimal value = valorRepasse.Value; + decimal num = 1; + valorRepasse = v.First().get_Vendedor().get_Desconto(); + if (valorRepasse.HasValue) + { + nullable1 = new decimal?(num - valorRepasse.GetValueOrDefault()); + } + else + { + nullable = null; + nullable1 = nullable; + } + nullable = nullable1; + return value * nullable.GetValueOrDefault(); + })); + adiantamento.set_Historico(string.Format("ESTORNO DEVIDO A RECUSA {0} PARCELA {1}", str, x.get_NumeroParcela())); + return adiantamento; + }).ToList(); + commited.get_AdiantamentoRepository().AddRange(adiantamentos); + List vendedorParcelas4 = vendedorParcelas; + Func u003cu003e9_307 = ApoliceServico.u003cu003ec.u003cu003e9__30_7; + if (u003cu003e9_307 == null) + { + u003cu003e9_307 = (VendedorParcela v) => !v.get_DataPagamento().HasValue; + ApoliceServico.u003cu003ec.u003cu003e9__30_7 = u003cu003e9_307; + } + List list1 = vendedorParcelas4.Where(u003cu003e9_307).ToList(); + Action u003cu003e9_8 = action3; + if (u003cu003e9_8 == null) + { + Action action2 = (VendedorParcela v) => { + v.set_ValorRepasse(new decimal?(new decimal())); + v.set_DataPagamento(new DateTime?(networkTime)); + v.set_DataPrePagamento(new DateTime?(v.get_DataPrePagamento().GetValueOrDefault(networkTime))); + commited.get_VendedorParcelaRepository().Merge(v); + }; + action = action2; + action3 = action2; + u003cu003e9_8 = action; + } + list1.ForEach(u003cu003e9_8); + } + } + if (x.get_DataRecebimento().HasValue) + { + return; + } + x.set_DataRecebimento(new DateTime?(networkTime)); + x.set_DataCredito(new DateTime?(networkTime)); + x.set_ValorComissao(decimal.Zero); + x.set_ValorComDesconto(decimal.Zero); + commited.get_ParcelaRepository().Merge(x); + }); + commited.get_DocumentoRepository().Merge(documento); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(1); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + Documento documento1 = documento; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(documento1, jsonSerializerSetting)); + registroLog.set_EntidadeId(documento.get_Id()); + registroLog.set_Tela(2); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_3011 = ApoliceServico.u003cu003ec.u003cu003e9__30_11; + if (u003cu003e9_3011 == null) + { + u003cu003e9_3011 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + ApoliceServico.u003cu003ec.u003cu003e9__30_11 = u003cu003e9_3011; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_3011); + if (pAddress != null) + { + str1 = pAddress.ToString(); + } + else + { + str1 = null; + } + registroLog.set_Ip(str1); + base.SaveLog(registroLog, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num1 = base.Registrar(exception, 26, num1, documento, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + internal async Task> BuscarApolice(string pesquisa, FiltroStatusDocumento status, List vendedorVinculado, string campo = "Apolice", bool tipobusca = false) + { + int num1 = 3; + List documentos1 = await Task.Run>(() => { + List documentos; + long num; + while (num1 > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + IDocumentoRepository documentoRepository = read.get_DocumentoRepository(); + string str = pesquisa; + FiltroStatusDocumento filtroStatusDocumento = status; + List vendedorUsuarios = vendedorVinculado; + string str1 = campo; + num = (Recursos.Usuario.get_IdEmpresa() == (long)1 ? (long)0 : Recursos.Usuario.get_IdEmpresa()); + List configuracoes = Recursos.Configuracoes; + Func u003cu003e9_211 = ApoliceServico.u003cu003ec.u003cu003e9__21_1; + if (u003cu003e9_211 == null) + { + u003cu003e9_211 = (ConfiguracaoSistema x) => x.get_Configuracao() == 43; + ApoliceServico.u003cu003ec.u003cu003e9__21_1 = u003cu003e9_211; + } + documentos = documentoRepository.FindApolice(str, filtroStatusDocumento, vendedorUsuarios, str1, num, configuracoes.Any(u003cu003e9_211), tipobusca); + } + } + catch (Exception exception) + { + num1 = base.Registrar(exception, 7, num1, new { pesquisa = pesquisa, status = status, campo = campo }, true); + continue; + } + return documentos; + } + return new List(); + }); + return documentos1; + } + + public async Task BuscarApoliceAsync(long id, bool itens = false, bool sinistrosPorControle = false) + { + int num = 3; + Documento documento1 = await Task.Run(() => { + Documento documento; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + documento = read.get_DocumentoRepository().FindById(id, itens, sinistrosPorControle); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 3, num, id, true); + continue; + } + return documento; + } + return new Documento(); + }); + return documento1; + } + + public async Task> BuscarApolices(Filtros filtro, bool buscarAssinatura = false, bool painelBi = false) + { + int num = 3; + List documentos1 = await Task.Run>(async () => { + List documentos; + while (true) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + documentos = await read.get_DocumentoRepository().BuscaDocumentosPorVigencia(filtro, buscarAssinatura, painelBi); + return documentos; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 5, num, filtro, true); + } + if (num <= 0) + { + break; + } + } + documentos = new List(); + return documentos; + }); + return documentos1; + } + + internal async Task> BuscarApolicesAsync(long id, FiltroStatusDocumento status = 0, List vendedorVinculado = null) + { + ObservableCollection observableCollection1; + if (!this._carregando) + { + int num1 = 3; + observableCollection1 = await Task.Run>(() => { + ObservableCollection observableCollection; + while (num1 > 0) + { + try + { + this._carregando = true; + using (UnitOfWork read = Instancia.Read) + { + IDocumentoRepository documentoRepository = read.get_DocumentoRepository(); + long num = id; + FiltroStatusDocumento filtroStatusDocumento = status; + List vendedorUsuarios = vendedorVinculado; + List produtos = LicenseHelper.Produtos; + bool flag1 = Recursos.Usuario.get_Id() == (long)0; + List configuracoes = Recursos.Configuracoes; + Func u003cu003e9_11 = ApoliceServico.u003cu003ec.u003cu003e9__1_1; + if (u003cu003e9_11 == null) + { + u003cu003e9_11 = (ConfiguracaoSistema x) => x.get_Configuracao() == 43; + ApoliceServico.u003cu003ec.u003cu003e9__1_1 = u003cu003e9_11; + } + this._carregando = false; + observableCollection = new ObservableCollection(documentoRepository.FindApoliceByCustomer(num, filtroStatusDocumento, vendedorUsuarios, produtos, false, flag1, configuracoes.Any(u003cu003e9_11))); + } + } + catch (Exception exception1) + { + Exception exception = exception1; + List licencas = LicenseHelper.Produtos; + Func u003cu003e9_12 = ApoliceServico.u003cu003ec.u003cu003e9__1_2; + if (u003cu003e9_12 == null) + { + u003cu003e9_12 = (Licenca x) => { + if (x.get_Produto() != 86) + { + return false; + } + return x.get_Status() != 3; + }; + ApoliceServico.u003cu003ec.u003cu003e9__1_2 = u003cu003e9_12; + } + bool flag = licencas.Any(u003cu003e9_12); + num1 = base.Registrar(exception, 1, num1, new { id = id, status = status, vendedorVinculado = vendedorVinculado, assinatura = flag }, true); + continue; + } + return observableCollection; + } + this._carregando = false; + return new ObservableCollection(); + }); + } + else + { + observableCollection1 = new ObservableCollection(); + } + return observableCollection1; + } + + internal async Task> BuscarApolicesComissao(long id, FiltroStatusDocumento status = 0) + { + int num = 3; + ObservableCollection observableCollection1 = await Task.Run>(() => { + ObservableCollection observableCollection; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + observableCollection = new ObservableCollection(read.get_DocumentoRepository().FindApoliceByCustomer(id, status, null, LicenseHelper.Produtos, true, false, false)); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 2, num, new { id = id, status = status }, true); + continue; + } + return observableCollection; + } + return new ObservableCollection(); + }); + return observableCollection1; + } + + public async Task> BuscarApolicesPendentes(Filtros filtro) + { + int num = 3; + List documentos1 = await Task.Run>(() => { + List documentos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + documentos = read.get_DocumentoRepository().FindPendenciasByVigencia(filtro); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 10, num, filtro, true); + continue; + } + return documentos; + } + return new List(); + }); + return documentos1; + } + + public async Task> BuscarApolicesPorId(List ids) + { + int num = 3; + List documentos1 = await Task.Run>(() => { + List documentos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + documentos = read.get_DocumentoRepository().FindByIds(ids); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 3, num, ids, true); + continue; + } + return documentos; + } + return new List(); + }); + return documentos1; + } + + public async Task> BuscarApolicesPorIdParcela(List ids) + { + int num = 3; + List documentos1 = await Task.Run>(() => { + List documentos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + documentos = read.get_DocumentoRepository().FindByParcelaIds(ids); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 3, num, ids, true); + continue; + } + return documentos; + } + return new List(); + }); + return documentos1; + } + + public async Task> BuscarApolicesVigenciaFinal(Filtros filtro, bool somarPremios = false) + { + int num = 3; + List documentos1 = await Task.Run>(() => { + List documentos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + documentos = read.get_DocumentoRepository().FindByVigenciaFinal(filtro, LicenseHelper.Produtos, somarPremios); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 6, num, filtro, true); + continue; + } + return documentos; + } + return new List(); + }); + return documentos1; + } + + internal async Task BuscarCodDocumento(long pesquisa, List vendedorVinculado) + { + int num = 3; + Documento documento1 = await Task.Run(() => { + Documento documento; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + documento = read.get_DocumentoRepository().FindById(pesquisa, vendedorVinculado); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 3, num, pesquisa, true); + continue; + } + return documento; + } + return new Documento(); + }); + return documento1; + } + + public async Task BuscarControleAsync(long id) + { + int num = 3; + Controle controle1 = await Task.Run(() => { + Controle controle; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + controle = read.get_ControleRepository().FindById(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 4, num, id, true); + continue; + } + return controle; + } + return new Controle(); + }); + return controle1; + } + + public async Task> BuscarEndossos(Filtros filtro, bool buscarAssinatura = false) + { + int num = 3; + List documentos1 = await Task.Run>(async () => { + List documentos; + while (true) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + documentos = await read.get_DocumentoRepository().FindEndossoByVigencia(filtro, buscarAssinatura); + return documentos; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 5, num, filtro, true); + } + if (num <= 0) + { + break; + } + } + documentos = new List(); + return documentos; + }); + return documentos1; + } + + public async Task> BuscarFechamento(Filtros filtro) + { + int num = 3; + List fechamentos1 = await Task.Run>(async () => { + List fechamentos; + while (true) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + fechamentos = await read.get_DocumentoRepository().Fechamento(filtro); + return fechamentos; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 8, num, filtro, true); + } + if (num <= 0) + { + break; + } + } + fechamentos = new List(); + return fechamentos; + }); + return fechamentos1; + } + + public async Task> BuscarLicenciamentos(Filtros filtro) + { + int num = 3; + List documentos1 = await Task.Run>(() => { + List documentos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + documentos = read.get_DocumentoRepository().FindByLicenciamento(filtro); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 295, num, filtro, true); + continue; + } + return documentos; + } + return new List(); + }); + return documentos1; + } + + public async Task BuscarLogAntigo(long id) + { + int num = 3; + string str1 = await Task.Run(() => { + string str; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + str = read.get_DocumentoRepository().BuscarLogAntigo(id, Gestor.Application.Helpers.Connection.GetConnectionString()); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 319, num, id, true); + continue; + } + return str; + } + return null; + }); + return str1; + } + + public async Task> BuscarPlacas(Filtros filtro) + { + int num = 3; + List documentos1 = await Task.Run>(() => { + List documentos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + documentos = read.get_DocumentoRepository().FindByPlaca(filtro); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 327, num, filtro, true); + continue; + } + return documentos; + } + return new List(); + }); + return documentos1; + } + + public async Task> BuscarPlanilhaCompleta(List ids, bool configFranquia, bool configPremio) + { + int num = 3; + List planilhaCompletas1 = await Task.Run>(() => { + List planilhaCompletas; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + planilhaCompletas = read.get_ReportRepository().PlanilhaCompleta(ids, configFranquia, configPremio); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 296, num, ids, true); + continue; + } + return planilhaCompletas; + } + return null; + }); + return planilhaCompletas1; + } + + public async Task> BuscarPlanilhaCompletaFatura(List ids, Relatorio relatorio, DateTime inicio, DateTime fim, bool configFranquia, bool configPremio) + { + int num = 3; + List planilhaCompletas1 = await Task.Run>(() => { + List planilhaCompletas; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + planilhaCompletas = read.get_ReportRepository().PlanilhaCompletaFatura(ids, relatorio, inicio, fim, configFranquia, configPremio); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 296, num, ids, true); + continue; + } + return planilhaCompletas; + } + return null; + }); + return planilhaCompletas1; + } + + public async Task> BuscarPlanilhaCompletaProspeccao(List ids) + { + int num = 3; + List planilhaCompletas1 = await Task.Run>(() => { + List planilhaCompletas; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + planilhaCompletas = read.get_DocumentoRepository().BuscarPlanilhaCompletaProspeccao(ids); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 296, num, ids, true); + continue; + } + return planilhaCompletas; + } + return null; + }); + return planilhaCompletas1; + } + + public async Task> BuscarTarefas(Filtros filtro) + { + int num = 3; + List tarefas1 = await Task.Run>(() => { + List tarefas; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + tarefas = read.get_TarefaRepository().BuscarTarefaPorFiltro(filtro.get_Inicio(), filtro.get_Fim()); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 97, num, filtro, true); + continue; + } + return tarefas; + } + return new List(); + }); + return tarefas1; + } + + public async Task BuscarVendedorPrincipal(long id) + { + int num = 3; + Vendedor vendedor1 = await Task.Run(() => { + Vendedor vendedor; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + vendedor = read.get_VendedorParcelaRepository().BuscarVendedorPorControle(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 3, num, id, true); + continue; + } + return vendedor; + } + return new Vendedor(); + }); + return vendedor1; + } + + public async Task Cotacoes(Filtros filtro) + { + int num1 = 3; + int num2 = await Task.Run(() => { + int num; + while (num1 > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + num = read.get_DocumentoRepository().Cotacoes(filtro); + } + } + catch (Exception exception) + { + num1 = base.Registrar(exception, 14, num1, filtro, true); + continue; + } + return num; + } + return 0; + }); + return num2; + } + + public async Task Excluir(Documento documento) + { + int num = 3; + base.Sucesso = true; + Documento documento2 = documento; + DateTime networkTime = Funcoes.GetNetworkTime(); + Documento documento3 = await Task.Run(() => { + Documento documento4; + bool id; + string str; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + TipoAcao tipoAcao = 2; + Controle controle = documento.get_Controle(); + if (controle == null) + { + controle = commited.get_DocumentoRepository().FindById(documento.get_Id(), false, false).get_Controle(); + documento.set_Controle(controle); + } + commited.get_ParcelaRepository().ExcluirVinculoParcelaPendenteDocExcluido(documento); + Status status = documento.get_Status(); + id = (status != null ? status.get_Id() == (long)0 : false); + if (id) + { + documento.set_Status(null); + } + documento = commited.get_DocumentoRepository().Merge(documento); + documento.set_Controle(commited.get_ControleRepository().Merge(controle)); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(tipoAcao); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + Documento documento1 = documento; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(documento1, jsonSerializerSetting)); + registroLog.set_EntidadeId(documento.get_Id()); + registroLog.set_Tela(2); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_41 = ApoliceServico.u003cu003ec.u003cu003e9__4_1; + if (u003cu003e9_41 == null) + { + u003cu003e9_41 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + ApoliceServico.u003cu003ec.u003cu003e9__4_1 = u003cu003e9_41; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_41); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + documento4 = documento; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 20, num, documento, true); + continue; + } + return documento4; + } + return documento2; + }); + return documento3; + } + + public async Task ExcluirCritica(long id) + { + int num = 3; + base.Sucesso = true; + DateTime networkTime = Funcoes.GetNetworkTime(); + bool flag1 = await Task.Run(() => { + bool flag; + string str; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + CriticaApolice criticaApolouse = commited.get_CriticaApoliceRepository().FindByApolice(id); + if (criticaApolouse != null) + { + commited.get_CriticaApoliceRepository().Delete(criticaApolouse.get_Id()); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(2); + registroLog.set_Tela(20); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(criticaApolouse, jsonSerializerSetting)); + registroLog.set_EntidadeId(criticaApolouse.get_Id()); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_281 = ApoliceServico.u003cu003ec.u003cu003e9__28_1; + if (u003cu003e9_281 == null) + { + u003cu003e9_281 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + ApoliceServico.u003cu003ec.u003cu003e9__28_1 = u003cu003e9_281; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_281); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + flag = true; + } + else + { + flag = true; + } + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 25, num, id, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task ExcluirPagamento(List pagamentos) + { + int num = 3; + base.Sucesso = true; + DateTime networkTime = Funcoes.GetNetworkTime(); + bool flag1 = await Task.Run(() => { + bool flag; + string str; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + commited.get_VendedorParcelaRepository().DeleteRange(pagamentos); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + foreach (VendedorParcela pagamento in pagamentos) + { + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(2); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(pagamento, jsonSerializerSetting)); + registroLog.set_EntidadeId(pagamento.get_Parcela().get_Id()); + registroLog.set_Tela(37); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_141 = ApoliceServico.u003cu003ec.u003cu003e9__14_1; + if (u003cu003e9_141 == null) + { + u003cu003e9_141 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + ApoliceServico.u003cu003ec.u003cu003e9__14_1 = u003cu003e9_141; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_141); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + } + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 21, num, pagamentos, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + internal async Task ExcluirVinculo(long id) + { + await Task.Run(() => { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + commited.get_VinculoDocumentoRepository().Delete(id); + commited.Commit(); + } + } + catch (Exception exception) + { + } + }); + } + + public async Task IncluirVendedor(VendedorParcela vendedor) + { + int num = 3; + base.Sucesso = true; + VendedorParcela vendedorParcela1 = vendedor; + DateTime networkTime = Funcoes.GetNetworkTime(); + VendedorParcela vendedorParcela2 = await Task.Run(() => { + VendedorParcela vendedorParcela; + object obj; + string str; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + vendedorParcela1 = commited.get_VendedorParcelaRepository().SaveOrUpdate(vendedorParcela1); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(0); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + RegistroLog registroLog1 = registroLog; + string[] strArrays = new string[] { string.Format("O USUÁRIO {0} INCLUIU, EM {1}, O VENDEDOR DE ", Recursos.Usuario.get_Nome(), networkTime), string.Format("ID: '{0}'", vendedor.get_Id()), string.Format(", VALOR DO PAGAMENTO: 'R${0}'", vendedor.get_ValorRepasse()), string.Format(", VALOR TOTAL: 'R${0}'", vendedor.get_ValorTotal()), ", DATA DO PAGAMENTO: '", null, null, null }; + DateTime? dataPagamento = vendedor.get_DataPagamento(); + if (!dataPagamento.HasValue) + { + obj = ""; + } + else + { + dataPagamento = vendedor.get_DataPagamento(); + obj = (dataPagamento.HasValue ? dataPagamento.GetValueOrDefault().ToShortDateString() : null) ?? ""; + } + strArrays[5] = (string)obj; + strArrays[6] = "'"; + strArrays[7] = string.Format(", PORCENTAGEM DO PAGAMENTO: '{0}%'.", vendedor.get_PorcentagemRepasse()); + registroLog1.set_Descricao(string.Concat(strArrays)); + registroLog.set_EntidadeId(vendedor.get_Id()); + registroLog.set_Tela(37); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + RegistroLog registroLog2 = registroLog; + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_151 = ApoliceServico.u003cu003ec.u003cu003e9__15_1; + if (u003cu003e9_151 == null) + { + u003cu003e9_151 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + ApoliceServico.u003cu003ec.u003cu003e9__15_1 = u003cu003e9_151; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_151); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog2.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + vendedorParcela = vendedorParcela1; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 22, num, vendedor, true); + continue; + } + return vendedorParcela; + } + return vendedor; + }); + return vendedorParcela2; + } + + public async Task> IncluirVendedores(List repasses) + { + int num = 3; + base.Sucesso = true; + List vendedorParcelas1 = repasses; + DateTime networkTime = Funcoes.GetNetworkTime(); + List vendedorParcelas2 = await Task.Run>(() => { + List vendedorParcelas; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + vendedorParcelas1 = commited.get_VendedorParcelaRepository().AddRange(vendedorParcelas1); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + vendedorParcelas1.ForEach((VendedorParcela x) => { + string str; + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(0); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(x, jsonSerializerSetting)); + registroLog.set_EntidadeId(x.get_Parcela().get_Id()); + registroLog.set_Tela(37); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_162 = ApoliceServico.u003cu003ec.u003cu003e9__16_2; + if (u003cu003e9_162 == null) + { + u003cu003e9_162 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + ApoliceServico.u003cu003ec.u003cu003e9__16_2 = u003cu003e9_162; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_162); + str = (pAddress != null ? pAddress.ToString() : null); + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + }); + vendedorParcelas = vendedorParcelas1; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 22, num, repasses, true); + continue; + } + return vendedorParcelas; + } + return repasses; + }); + return vendedorParcelas2; + } + + public async Task Perdido(long id) + { + int num = 3; + base.Sucesso = true; + DateTime networkTime = Funcoes.GetNetworkTime(); + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + commited.get_DocumentoRepository().FindByControle(id).ForEach((Documento x) => { + string str; + x.set_SituacaoAnterior(new TipoSeguro?(x.get_Situacao())); + x.set_Situacao(6); + commited.get_DocumentoRepository().Merge(x); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(1); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(x, jsonSerializerSetting)); + registroLog.set_EntidadeId(x.get_Id()); + registroLog.set_Tela(2); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_252 = ApoliceServico.u003cu003ec.u003cu003e9__25_2; + if (u003cu003e9_252 == null) + { + u003cu003e9_252 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + ApoliceServico.u003cu003ec.u003cu003e9__25_2 = u003cu003e9_252; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_252); + str = (pAddress != null ? pAddress.ToString() : null); + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + }); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 23, num, id, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task Prorrogar(long id, DateTime vigencia2) + { + int num = 3; + base.Sucesso = true; + DateTime networkTime = Funcoes.GetNetworkTime(); + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + commited.get_DocumentoRepository().FindByControle(id).ForEach((Documento x) => { + string str; + if (!x.get_NegocioCorretora().HasValue) + { + x.set_NegocioCorretora(new NegocioCorretora?((!x.get_Negocio().HasValue || x.get_Negocio().GetValueOrDefault() != 1 ? 0 : 1))); + } + x.set_Vigencia2(new DateTime?(vigencia2)); + commited.get_DocumentoRepository().Merge(x); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(1); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(x, jsonSerializerSetting)); + registroLog.set_EntidadeId(x.get_Id()); + registroLog.set_Tela(2); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_232 = ApoliceServico.u003cu003ec.u003cu003e9__23_2; + if (u003cu003e9_232 == null) + { + u003cu003e9_232 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + ApoliceServico.u003cu003ec.u003cu003e9__23_2 = u003cu003e9_232; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_232); + str = (pAddress != null ? pAddress.ToString() : null); + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + }); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 23, num, id, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task Reabilitar(long id) + { + int num = 3; + base.Sucesso = true; + DateTime networkTime = Funcoes.GetNetworkTime(); + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + commited.get_DocumentoRepository().FindByControle(id).ForEach((Documento x) => { + string str; + if (x.get_TipoEndosso().HasValue && x.get_TipoEndosso().GetValueOrDefault() == 2) + { + return; + } + x.set_Situacao(4); + commited.get_DocumentoRepository().Merge(x); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(1); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(x, jsonSerializerSetting)); + registroLog.set_EntidadeId(x.get_Id()); + registroLog.set_Tela(2); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_242 = ApoliceServico.u003cu003ec.u003cu003e9__24_2; + if (u003cu003e9_242 == null) + { + u003cu003e9_242 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + ApoliceServico.u003cu003ec.u003cu003e9__24_2 = u003cu003e9_242; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_242); + str = (pAddress != null ? pAddress.ToString() : null); + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + }); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 23, num, id, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task SalvarAssistencia(string id, long controleId) + { + await Task.Run(() => { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + commited.get_DocumentoRepository().SalvarAssistencia(id, controleId); + commited.Commit(); + } + } + catch (Exception exception) + { + } + }); + } + + public async Task Save(Controle controle, Cliente cliente) + { + int num = 3; + await Task.Run(() => { + while (num > 0) + { + List registroLogs = new List(); + List registroLogs1 = new List(); + try + { + using (UnitOfWork commited = Instancia.Commited) + { + List diferencas = new List(); + List diferencas1 = new List(); + List diferencas2 = diferencas; + Diferenca diferenca = new Diferenca(); + diferenca.set_Campo("Cliente"); + diferenca.set_Descricao("NOME"); + diferenca.set_ValorAtual(cliente.get_Nome()); + diferenca.set_ValorAnterior(controle.get_Cliente().get_Nome()); + diferencas2.Insert(0, diferenca); + List diferencas3 = diferencas1; + Diferenca diferenca1 = new Diferenca(); + diferenca1.set_Campo("Cliente"); + diferenca1.set_Descricao("APÓLICE TROCADA DE CLIENTE"); + diferenca1.set_ValorAtual(cliente.get_Nome()); + diferenca1.set_ValorAnterior(controle.get_Cliente().get_Nome()); + diferencas3.Insert(0, diferenca1); + ExtensionMethods.ForEach(controle.get_Documentos(), (Documento x) => { + registroLogs.Add(base.CreateLog(x.get_Id(), diferencas, 2)); + registroLogs1.Add(base.CreateLog(x.get_Id(), diferencas1, 41)); + }); + commited.get_DocumentoRepository().TrocarCliente(controle, cliente); + base.SaveLog(registroLogs, commited); + base.SaveLog(registroLogs1, commited); + commited.Commit(); + break; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 325, num, controle, true); + } + } + }); + } + + public async Task Save(Documento documento, bool updateParcelas, bool criarParcelas) + { + Action action4 = null; + Action action5 = null; + int num = 3; + base.Sucesso = true; + Documento documento1 = documento; + DateTime networkTime = Funcoes.GetNetworkTime(); + List registroLogs = new List(); + Documento documento2 = await Task.Run(() => { + Documento documento3; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + documento.get_Id(); + bool id = documento.get_Id() == (long)0; + Controle controle = documento.get_Controle(); + ObservableCollection parcelas = documento.get_Parcelas(); + if (!id) + { + if (controle != null) + { + if ((controle != null ? controle.get_Seguradora() : false)) + { + goto Label0; + } + } + controle = commited.get_DocumentoRepository().FindById(documento.get_Id(), false, false).get_Controle(); + documento.set_Controle(controle); + Label0: + registroLogs.Add(base.CreateLog(documento.get_Id(), documento, 2)); + documento = commited.get_DocumentoRepository().Merge(documento); + if (documento.get_TipoRecebimento().GetValueOrDefault() == 1) + { + if (criarParcelas) + { + List parcelas1 = commited.get_ParcelaRepository().FindByDocumentId(documento.get_Id()); + if (parcelas1 != null) + { + Action u003cu003e9_3 = action4; + if (u003cu003e9_3 == null) + { + Action action = (Parcela pa) => registroLogs.Add(base.CreateLog(documento.get_Id(), pa.GetValorOriginal(), 5, 2)); + Action action1 = action; + action4 = action; + u003cu003e9_3 = action1; + } + parcelas1.ForEach(u003cu003e9_3); + } + else + { + } + List vendedorParcelas = commited.get_VendedorParcelaRepository().FindByDocumentId(documento.get_Id()); + if (vendedorParcelas != null) + { + Action u003cu003e9_4 = action5; + if (u003cu003e9_4 == null) + { + Action action2 = (VendedorParcela pa) => registroLogs.Add(base.CreateLog(pa.get_Parcela().get_Id(), pa.GetValorOriginal(), 37, 2)); + Action action3 = action2; + action5 = action2; + u003cu003e9_4 = action3; + } + vendedorParcelas.ForEach(u003cu003e9_4); + } + else + { + } + commited.get_VendedorParcelaRepository().DeleteRange(documento.get_Id()); + commited.get_ParcelaRepository().DeleteRange(documento.get_Id()); + parcelas.ToList().ForEach((Parcela p) => { + Parcela parcela = p; + ObservableCollection vendedores = parcela.get_Vendedores(); + parcela.set_Documento(documento); + parcela.set_IdEmpresa(documento.get_Controle().get_IdEmpresa()); + parcela = commited.get_ParcelaRepository().SaveOrUpdate(parcela); + vendedores.ToList().ForEach((VendedorParcela v) => { + v.set_Documento(documento); + v.set_Parcela(parcela); + if (v.get_Repasse() != null) + { + BaseRepasse? @base = v.get_Repasse().get_Base(); + if (@base.HasValue) + { + switch (@base.GetValueOrDefault()) + { + case 1: + { + v.set_DataPrePagamento(new DateTime?(documento.get_Vigencia1())); + break; + } + case 2: + { + v.set_DataPrePagamento(new DateTime?(networkTime)); + break; + } + case 3: + { + v.set_DataPrePagamento(new DateTime?(parcela.get_Vencimento())); + break; + } + case 4: + { + v.set_DataPrePagamento(documento.get_Emissao()); + break; + } + case 5: + { + v.set_DataPrePagamento(documento.get_Remessa()); + break; + } + } + } + } + v = commited.get_VendedorParcelaRepository().SaveOrUpdate(v); + registroLogs.Add(base.CreateLog(parcela.get_Id(), v.GetValorOriginal(), 37, 0)); + }); + parcela.set_Vendedores(vendedores); + registroLogs.Add(base.CreateLog(documento.get_Id(), parcela.GetValorOriginal(), 5, 0)); + }); + } + if (updateParcelas && !criarParcelas) + { + List parcelas2 = commited.get_ParcelaRepository().FindByDocumentId(documento.get_Id()); + List vendedorParcelas1 = commited.get_VendedorParcelaRepository().FindByDocumentId(documento.get_Id()); + parcelas.ToList().ForEach((Parcela p) => { + Parcela parcela = p; + ObservableCollection vendedores = parcela.get_Vendedores(); + parcela.set_Documento(documento); + parcela = commited.get_ParcelaRepository().Merge(parcela); + vendedores.ToList().ForEach((VendedorParcela v) => { + bool flag; + VendedorParcela vendedorParcela = v; + vendedorParcela.set_Documento(documento); + vendedorParcela.set_Parcela(parcela); + flag = (vendedorParcela.get_Id() > (long)0 ? false : true); + vendedorParcela = (vendedorParcela.get_Id() > (long)0 ? commited.get_VendedorParcelaRepository().Merge(vendedorParcela) : commited.get_VendedorParcelaRepository().SaveOrUpdate(vendedorParcela)); + if (!flag) + { + registroLogs.Add(base.CreateLog(parcela.get_Id(), vendedorParcela.GetValorOriginal(), 37, 0)); + } + VendedorParcela vendedorParcela1 = vendedorParcelas1.FirstOrDefault((VendedorParcela pa) => vendedorParcela.get_Id() == pa.get_Id()); + if (vendedorParcela1 == null) + { + return; + } + List diferencas = vendedorParcela.Compare(vendedorParcela1.GetValorOriginal()); + if (diferencas.Count > 0) + { + Diferenca diferenca = new Diferenca(); + diferenca.set_Campo("Vendedor"); + diferenca.set_Descricao("VENDEDOR"); + diferenca.set_ValorAtual(vendedorParcela.get_Vendedor().get_Nome()); + diferenca.set_ValorAnterior(vendedorParcela.get_Vendedor().get_Nome()); + diferencas.Insert(0, diferenca); + registroLogs.Add(base.CreateLog(parcela.get_Id(), diferencas, 37)); + } + }); + parcela.set_Vendedores(vendedores); + Parcela parcela1 = parcelas2.FirstOrDefault((Parcela pa) => parcela.get_Id() == pa.get_Id()); + if (parcela1 == null) + { + return; + } + List diferencas1 = parcela.Compare(parcela1.GetValorOriginal()); + if (diferencas1.Count > 0) + { + Diferenca diferenca1 = new Diferenca(); + diferenca1.set_Campo("Parcela"); + diferenca1.set_Descricao("PARCELA"); + int numeroParcela = parcela.get_NumeroParcela(); + diferenca1.set_ValorAtual(numeroParcela.ToString()); + numeroParcela = parcela.get_NumeroParcela(); + diferenca1.set_ValorAnterior(numeroParcela.ToString()); + diferencas1.Insert(0, diferenca1); + registroLogs.Add(base.CreateLog(documento.get_Id(), diferencas1, 5)); + } + }); + } + } + documento.set_Controle(commited.get_ControleRepository().Merge(controle)); + } + else + { + controle = (documento.get_Tipo() <= 0 || controle.get_Id() <= (long)0 ? commited.get_ControleRepository().SaveOrUpdate(controle) : controle); + documento.set_Controle(controle); + documento = commited.get_DocumentoRepository().SaveOrUpdate(documento); + registroLogs.Add(base.CreateLog(documento.get_Id(), documento.GetValorOriginal(), 2, 0)); + if (parcelas != null) + { + parcelas.ToList().ForEach((Parcela p) => { + Parcela parcela = p; + ObservableCollection vendedores = parcela.get_Vendedores(); + parcela.set_Documento(documento); + parcela.set_IdEmpresa(documento.get_Controle().get_IdEmpresa()); + parcela = commited.get_ParcelaRepository().SaveOrUpdate(parcela); + registroLogs.Add(base.CreateLog(documento.get_Id(), parcela.GetValorOriginal(), 5, 0)); + vendedores.ToList().ForEach((VendedorParcela v) => { + v.set_Documento(documento); + v.set_Parcela(parcela); + if (v.get_Repasse() != null) + { + BaseRepasse? @base = v.get_Repasse().get_Base(); + if (@base.HasValue) + { + switch (@base.GetValueOrDefault()) + { + case 1: + { + v.set_DataPrePagamento(new DateTime?(documento.get_Vigencia1())); + break; + } + case 2: + { + v.set_DataPrePagamento(new DateTime?(networkTime)); + break; + } + case 3: + { + v.set_DataPrePagamento(new DateTime?(parcela.get_Vencimento())); + break; + } + case 4: + { + v.set_DataPrePagamento(documento.get_Emissao()); + break; + } + case 5: + { + v.set_DataPrePagamento(documento.get_Remessa()); + break; + } + } + } + } + v = commited.get_VendedorParcelaRepository().SaveOrUpdate(v); + registroLogs.Add(base.CreateLog(parcela.get_Id(), v.GetValorOriginal(), 37, 0)); + }); + parcela.set_Vendedores(vendedores); + }); + } + } + documento.set_Parcelas(parcelas); + base.SaveLog(registroLogs, commited); + commited.Commit(); + documento3 = documento; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 18, num, new { documentoOriginal = documento1, updateParcelas = updateParcelas, criarParcelas = criarParcelas }, true); + continue; + } + return documento3; + } + return documento1; + }); + return documento2; + } + + public async Task Save(long id, string observacao) + { + int num = 3; + base.Sucesso = true; + Funcoes.GetNetworkTime(); + string str1 = await Task.Run(() => { + string str; + while (num > 0) + { + List registroLogs = new List(); + try + { + using (UnitOfWork commited = Instancia.Commited) + { + Documento documento = commited.get_DocumentoRepository().FindById(id, false, false); + documento.Initialize(); + documento.set_Observacao(observacao); + registroLogs.Add(base.CreateLog(documento.get_Id(), documento, 2)); + commited.get_DocumentoRepository().Merge(documento); + base.SaveLog(registroLogs, commited); + commited.Commit(); + } + str = observacao; + } + catch (Exception exception) + { + num = base.Registrar(exception, 18, num, new { id = id, observacao = observacao }, true); + continue; + } + return str; + } + return ""; + }); + return str1; + } + + public async Task UpdateRange(Controle controle) + { + int num = 3; + Controle controle1 = controle; + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + controle1 = commited.get_ControleRepository().Merge(controle1); + controle1.get_Documentos().ToList().ForEach((Documento x) => x = commited.get_DocumentoRepository().Merge(x)); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 19, num, controle, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Seguros/AtividadeServico.cs b/Codemerx/Gestor.Application/Servicos/Seguros/AtividadeServico.cs new file mode 100644 index 0000000..bec5089 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Seguros/AtividadeServico.cs @@ -0,0 +1,78 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using System; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Seguros +{ + internal class AtividadeServico : BaseServico + { + public AtividadeServico() + { + } + + public async Task FindLastId() + { + int num1 = 3; + long num2 = await Task.Run(() => { + long num; + while (num1 > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + num = read.get_AtividadeRepository().FindLastId(); + } + } + catch (Exception exception) + { + num1 = base.Registrar(exception, 17, num1, null, true); + continue; + } + return num; + } + return (long)0; + }); + return num2; + } + + public async Task Save(Atividade atividade) + { + int num = 3; + base.Sucesso = true; + Atividade atividade1 = atividade; + Atividade atividade2 = await Task.Run(() => { + Atividade atividade3; + while (num > 0) + { + atividade = atividade1; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + atividade = (atividade.get_Id() == (long)0 ? commited.get_AtividadeRepository().SaveOrUpdate(atividade) : commited.get_AtividadeRepository().Merge(atividade)); + commited.Commit(); + atividade3 = atividade; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 211, num, atividade, true); + continue; + } + return atividade3; + } + return atividade1; + }); + return atividade2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Seguros/ClienteServico.cs b/Codemerx/Gestor.Application/Servicos/Seguros/ClienteServico.cs new file mode 100644 index 0000000..db5c9d2 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Seguros/ClienteServico.cs @@ -0,0 +1,1194 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Common.Validation; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Relatorios.Classificacao; +using Gestor.Model.Domain.Relatorios.ClientesAtivosInativos; +using Gestor.Model.Domain.Relatorios.Dashboard; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.License; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Seguros +{ + internal class ClienteServico : BaseServico + { + public ClienteServico() + { + } + + public async Task AddCentralSegurado(long id, bool update = true) + { + await Task.Run(() => { + using (UnitOfWork commited = Instancia.Commited) + { + commited.get_ClienteRepository().AddCentralSegurado(id, update); + } + }); + } + + public async Task> BuscarAniversariantes(Filtros filtro) + { + int num = 3; + List clientesAtivosInativos1 = await Task.Run>(() => { + List clientesAtivosInativos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + clientesAtivosInativos = read.get_ClienteRepository().BuscarAniversariantes(filtro, (Recursos.Usuario.get_IdEmpresa() == (long)1 ? (long)0 : Recursos.Usuario.get_IdEmpresa())); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 41, num, null, true); + continue; + } + return clientesAtivosInativos; + } + return new List(); + }); + return clientesAtivosInativos1; + } + + public async Task> BuscarAniversariantesVinculo(Filtros filtro, List vinculo) + { + int num = 3; + List clientesAtivosInativos1 = await Task.Run>(() => { + List clientesAtivosInativos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + clientesAtivosInativos = read.get_ClienteRepository().BuscarAniversariantesVinculo(filtro, vinculo, (Recursos.Usuario.get_IdEmpresa() == (long)1 ? (long)0 : Recursos.Usuario.get_IdEmpresa())); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 41, num, null, true); + continue; + } + return clientesAtivosInativos; + } + return new List(); + }); + return clientesAtivosInativos1; + } + + public async Task> BuscarClassificacoes() + { + int num = 3; + List classificacaos1 = await Task.Run>(async () => { + List classificacaos; + while (true) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + classificacaos = await read.get_ClienteRepository().BuscarClassificacoes((Recursos.Usuario.get_IdEmpresa() == (long)1 ? (long)0 : Recursos.Usuario.get_IdEmpresa())); + return classificacaos; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 286, num, null, true); + } + if (num <= 0) + { + break; + } + } + classificacaos = new List(); + return classificacaos; + }); + return classificacaos1; + } + + internal async Task> BuscarCliente(string value, List vinculos = null, TipoFiltroCliente tipoFiltroCliente = 2) + { + List clientes1; + string str = value; + str = ValidationHelper.RemoverAcentos(str.Trim()); + if (!string.IsNullOrWhiteSpace(str)) + { + int num1 = 3; + clientes1 = await Task.Run>(() => { + List list; + while (num1 > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + long num = (Recursos.Usuario.get_IdEmpresa() == (long)1 ? (long)0 : Recursos.Usuario.get_IdEmpresa()); + List produtos = LicenseHelper.Produtos; + Func u003cu003e9_01 = ClienteServico.u003cu003ec.u003cu003e9__0_1; + if (u003cu003e9_01 == null) + { + u003cu003e9_01 = (Licenca x) => { + if (x.get_Produto() != 86) + { + return false; + } + return x.get_Status() != 3; + }; + ClienteServico.u003cu003ec.u003cu003e9__0_1 = u003cu003e9_01; + } + bool flag = produtos.Any(u003cu003e9_01); + List clientes = read.get_ClienteRepository().FindClienteVinculo(str, vinculos, num, Recursos.Usuario.get_Id() == (long)0, flag, tipoFiltroCliente); + Func u003cu003e9_02 = ClienteServico.u003cu003ec.u003cu003e9__0_2; + if (u003cu003e9_02 == null) + { + u003cu003e9_02 = (Cliente x) => x.get_Nome(); + ClienteServico.u003cu003ec.u003cu003e9__0_2 = u003cu003e9_02; + } + list = clientes.OrderBy(u003cu003e9_02).ToList(); + } + } + catch (Exception exception) + { + num1 = base.Registrar(exception, 29, num1, str, true); + continue; + } + return list; + } + return new List(); + }); + } + else + { + clientes1 = new List(); + } + return clientes1; + } + + internal async Task BuscarCliente(long id) + { + int num = 3; + Cliente cliente2 = await Task.Run(() => { + Cliente cliente; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + Cliente cliente1 = read.get_ClienteRepository().FindById(id); + cliente1.set_Nome(cliente1.get_Nome()); + cliente = cliente1; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 28, num, id, true); + continue; + } + return cliente; + } + return new Cliente(); + }); + return cliente2; + } + + public async Task BuscarClienteAsync(long id) + { + int num = 3; + Cliente cliente2 = await Task.Run(() => { + Cliente cliente; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + Cliente cliente1 = read.get_ClienteRepository().FindById(id); + cliente1.set_Nome(cliente1.get_Nome()); + cliente = cliente1; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 27, num, null, true); + continue; + } + return cliente; + } + return new Cliente(); + }); + return cliente2; + } + + internal async Task> BuscarClientePorDocumento(string documento) + { + List clientes1; + string upper = documento; + upper = ValidationHelper.RemoverAcentos(upper.Trim()).ToUpper(); + if (!string.IsNullOrWhiteSpace(upper)) + { + int num = 3; + clientes1 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List clientes = read.get_ClienteRepository().FindClienteDocumento(upper); + Func u003cu003e9_11 = ClienteServico.u003cu003ec.u003cu003e9__1_1; + if (u003cu003e9_11 == null) + { + u003cu003e9_11 = (Cliente c) => c.get_Nome(); + ClienteServico.u003cu003ec.u003cu003e9__1_1 = u003cu003e9_11; + } + list = clientes.OrderBy(u003cu003e9_11).ToList(); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 29, num, upper, true); + continue; + } + return list; + } + return new List(); + }); + } + else + { + clientes1 = new List(); + } + return clientes1; + } + + public async Task> BuscarClientesAtvosInativos(bool completo) + { + int num = 3; + IEnumerable clientesAtivosInativos1 = await Task.Run>(async () => { + IEnumerable clientesAtivosInativos; + while (true) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + clientesAtivosInativos = await read.get_ClienteRepository().BuscaClientes(completo, (Recursos.Usuario.get_IdEmpresa() == (long)1 ? (long)0 : Recursos.Usuario.get_IdEmpresa())); + return clientesAtivosInativos; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 286, num, null, true); + } + if (num <= 0) + { + break; + } + } + clientesAtivosInativos = new List(); + return clientesAtivosInativos; + }); + return clientesAtivosInativos1; + } + + public async Task> BuscarClientesAtvosInativosVinculo(bool completo, List vinculo) + { + int num = 3; + IEnumerable clientesAtivosInativos1 = await Task.Run>(async () => { + IEnumerable clientesAtivosInativos; + while (true) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + clientesAtivosInativos = await read.get_ClienteRepository().BuscaClientesVinculo(completo, vinculo, (Recursos.Usuario.get_IdEmpresa() == (long)1 ? (long)0 : Recursos.Usuario.get_IdEmpresa())); + return clientesAtivosInativos; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 286, num, null, true); + } + if (num <= 0) + { + break; + } + } + clientesAtivosInativos = new List(); + return clientesAtivosInativos; + }); + return clientesAtivosInativos1; + } + + internal async Task> BuscarClienteVinculo(string value, long id) + { + List clientes1; + if (!string.IsNullOrWhiteSpace(value)) + { + int num = 3; + clientes1 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List clientes = read.get_ClienteRepository().FindVinculo(value, id); + Func u003cu003e9_21 = ClienteServico.u003cu003ec.u003cu003e9__2_1; + if (u003cu003e9_21 == null) + { + u003cu003e9_21 = (Cliente x) => x.get_Nome(); + ClienteServico.u003cu003ec.u003cu003e9__2_1 = u003cu003e9_21; + } + list = clientes.OrderBy(u003cu003e9_21).ToList(); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 29, num, value, true); + continue; + } + return list; + } + return new List(); + }); + } + else + { + clientes1 = new List(); + } + return clientes1; + } + + internal async Task> BuscarContatosAsync(long id) + { + int num = 3; + ObservableCollection observableCollection1 = await Task.Run>(() => { + ObservableCollection observableCollection; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + observableCollection = new ObservableCollection(read.get_MaisContatoRepository().FindByCustomerId(id)); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 35, num, id, true); + continue; + } + return observableCollection; + } + return new ObservableCollection(); + }); + return observableCollection1; + } + + internal async Task> BuscarEmailsAsync(long id) + { + int num = 3; + ObservableCollection observableCollection1 = await Task.Run>(() => { + ObservableCollection observableCollection; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List clienteEmails = read.get_ClienteEmailRepository().FindByClienteId(id); + Func u003cu003e9_71 = ClienteServico.u003cu003ec.u003cu003e9__7_1; + if (u003cu003e9_71 == null) + { + u003cu003e9_71 = (ClienteEmail mail) => mail.get_Ordem(); + ClienteServico.u003cu003ec.u003cu003e9__7_1 = u003cu003e9_71; + } + observableCollection = new ObservableCollection(clienteEmails.OrderBy(u003cu003e9_71)); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 32, num, id, true); + continue; + } + return observableCollection; + } + return new ObservableCollection(); + }); + return observableCollection1; + } + + public async Task> BuscarEmailsPorCliente(List ids) + { + int num = 3; + List clienteEmails1 = await Task.Run>(() => { + List clienteEmails; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + clienteEmails = read.get_ClienteEmailRepository().FindByCliente(ids); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 37, num, null, true); + continue; + } + return clienteEmails; + } + return new List(); + }); + return clienteEmails1; + } + + internal async Task> BuscarEnderecosAsync(long id) + { + int num = 3; + ObservableCollection observableCollection1 = await Task.Run>(() => { + ObservableCollection observableCollection; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List clienteEnderecos = read.get_ClienteEnderecoRepository().FindByClienteId(id); + Func u003cu003e9_91 = ClienteServico.u003cu003ec.u003cu003e9__9_1; + if (u003cu003e9_91 == null) + { + u003cu003e9_91 = (ClienteEndereco x) => x.get_Ordem(); + ClienteServico.u003cu003ec.u003cu003e9__9_1 = u003cu003e9_91; + } + observableCollection = new ObservableCollection(clienteEnderecos.OrderBy(u003cu003e9_91)); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 34, num, id, true); + continue; + } + return observableCollection; + } + return new ObservableCollection(); + }); + return observableCollection1; + } + + public async Task> BuscarEnderecosPorCliente(List clientes) + { + List clienteEnderecos1; + int num = 3; + List clientes1 = clientes; + if (!clientes1.All((Cliente x) => x.get_Id() < (long)0)) + { + clienteEnderecos1 = await Task.Run>(() => { + List clienteEnderecos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + clienteEnderecos = read.get_ClienteEnderecoRepository().FindByCliente(clientes); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 38, num, null, true); + continue; + } + return clienteEnderecos; + } + return new List(); + }); + } + else + { + clienteEnderecos1 = new List(); + } + return clienteEnderecos1; + } + + public async Task BuscarLogAntigo(long id) + { + int num = 3; + string str1 = await Task.Run(() => { + string str; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + str = read.get_ClienteRepository().BuscarLogAntigo(id, Connection.GetConnectionString()); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 319, num, id, true); + continue; + } + return str; + } + return null; + }); + return str1; + } + + internal DateTime? BuscarNascimento(long id) + { + DateTime? nullable; + int num = 3; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + nullable = read.get_ClienteRepository().BuscaNascimeto(id); + } + } + catch (Exception exception1) + { + Exception exception = exception1; + num = base.Registrar(exception, 328, num, id, true); + continue; + } + return nullable; + } + return null; + } + + public async Task> BuscarObsCliente(string pesquisa) + { + int num = 3; + List clientes1 = await Task.Run>(() => { + List clientes; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + clientes = read.get_ClienteRepository().FindObsCliente(pesquisa, (Recursos.Usuario.get_IdEmpresa() == (long)1 ? (long)0 : Recursos.Usuario.get_IdEmpresa())); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 39, num, null, true); + continue; + } + return clientes; + } + return new List(); + }); + return clientes1; + } + + public async Task> BuscarOrigens(long id) + { + int num = 3; + ObservableCollection observableCollection1 = await Task.Run>(() => { + ObservableCollection observableCollection; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + observableCollection = new ObservableCollection(read.get_ClienteRepository().BuscarOrigem(id)); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 326, num, id, true); + continue; + } + return observableCollection; + } + return new ObservableCollection(); + }); + return observableCollection1; + } + + public async Task> BuscarPastaCliente(string pesquisa, bool busca) + { + int num = 3; + List clientes1 = await Task.Run>(() => { + List clientes; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + clientes = read.get_ClienteRepository().FindPastaCliente(pesquisa, busca, (long)0); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 40, num, null, true); + continue; + } + return clientes; + } + return new List(); + }); + return clientes1; + } + + public async Task> BuscarProspect(Filtros filtro) + { + int num = 3; + List prospectars1 = await Task.Run>(async () => { + List prospectars; + while (true) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + prospectars = await read.get_ClienteRepository().BuscaProspeccoes(filtro, (Recursos.Usuario.get_IdEmpresa() == (long)1 ? (long)0 : Recursos.Usuario.get_IdEmpresa())); + return prospectars; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 324, num, null, true); + } + if (num <= 0) + { + break; + } + } + prospectars = new List(); + return prospectars; + }); + return prospectars1; + } + + internal ObservableCollection BuscarTelefones(long id) + { + ObservableCollection observableCollection; + int num = 3; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + observableCollection = new ObservableCollection( + from x in read.get_ClienteTelefoneRepository().FindByClienteId(id) + orderby x.get_Ordem() + select x); + } + } + catch (Exception exception1) + { + Exception exception = exception1; + num = base.Registrar(exception, 30, num, id, true); + continue; + } + return observableCollection; + } + return new ObservableCollection(); + } + + internal async Task> BuscarTelefonesAsync(long id) + { + int num = 3; + ObservableCollection observableCollection1 = await Task.Run>(() => { + ObservableCollection observableCollection; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List clienteTelefones = read.get_ClienteTelefoneRepository().FindByClienteId(id); + Func u003cu003e9_41 = ClienteServico.u003cu003ec.u003cu003e9__4_1; + if (u003cu003e9_41 == null) + { + u003cu003e9_41 = (ClienteTelefone x) => x.get_Ordem(); + ClienteServico.u003cu003ec.u003cu003e9__4_1 = u003cu003e9_41; + } + observableCollection = new ObservableCollection(clienteTelefones.OrderBy(u003cu003e9_41)); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 30, num, id, true); + continue; + } + return observableCollection; + } + return new ObservableCollection(); + }); + return observableCollection1; + } + + internal async Task> BuscarTelefonesClientes(string telefone) + { + int num = 3; + List clienteTelefones1 = await Task.Run>(() => { + List clienteTelefones; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + clienteTelefones = read.get_ClienteTelefoneRepository().Find(telefone, (Recursos.Usuario.get_IdEmpresa() == (long)1 ? (long)0 : Recursos.Usuario.get_IdEmpresa())); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 31, num, telefone, true); + continue; + } + return clienteTelefones; + } + return new List(); + }); + return clienteTelefones1; + } + + public async Task> BuscarTodosClientes() + { + int num = 3; + List clientesAtivosInativos1 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List clientesAtivosInativos = read.get_ClienteRepository().FindAllClientes(false, (Recursos.Usuario.get_IdEmpresa() == (long)1 ? (long)0 : Recursos.Usuario.get_IdEmpresa())); + Func u003cu003e9_141 = ClienteServico.u003cu003ec.u003cu003e9__14_1; + if (u003cu003e9_141 == null) + { + u003cu003e9_141 = (ClientesAtivosInativos x) => x.get_Nome(); + ClienteServico.u003cu003ec.u003cu003e9__14_1 = u003cu003e9_141; + } + list = clientesAtivosInativos.OrderBy(u003cu003e9_141).ToList(); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 36, num, null, true); + continue; + } + return list; + } + return new List(); + }); + return clientesAtivosInativos1; + } + + public async Task> BuscarVencimentosCnh(Filtros filtro) + { + int num = 3; + List clientesAtivosInativos1 = await Task.Run>(() => { + List clientesAtivosInativos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + clientesAtivosInativos = read.get_ClienteRepository().BuscarVencimentoCnh(filtro, (Recursos.Usuario.get_IdEmpresa() == (long)1 ? (long)0 : Recursos.Usuario.get_IdEmpresa())); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 42, num, null, true); + continue; + } + return clientesAtivosInativos; + } + return new List(); + }); + return clientesAtivosInativos1; + } + + internal async Task> BuscarVinculosAsync(long id) + { + int num = 3; + ObservableCollection observableCollection1 = await Task.Run>(() => { + ObservableCollection observableCollection; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + observableCollection = new ObservableCollection(read.get_ClienteVinculoRepository().FindByCliente(id)); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 33, num, id, true); + continue; + } + return observableCollection; + } + return new ObservableCollection(); + }); + return observableCollection1; + } + + public async Task Delete(Cliente cliente) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + List registroLogs = new List(); + try + { + using (UnitOfWork commited = Instancia.Commited) + { + registroLogs.Add(base.CreateLog(cliente.get_Id(), cliente.GetValorOriginal(), 1, 2)); + commited.get_ClienteRepository().Merge(cliente); + base.SaveLog(registroLogs, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 172, num, cliente, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task SalvarObservacoes(long id, string observacao) + { + int num = 3; + base.Sucesso = true; + Funcoes.GetNetworkTime(); + string str1 = await Task.Run(() => { + string str; + while (num > 0) + { + List registroLogs = new List(); + try + { + using (UnitOfWork commited = Instancia.Commited) + { + Cliente cliente = commited.get_ClienteRepository().FindById(id); + cliente.Initialize(); + cliente.set_Observacao(observacao); + registroLogs.Add(base.CreateLog(cliente.get_Id(), cliente, 1)); + commited.get_ClienteRepository().Merge(cliente); + base.SaveLog(registroLogs, commited); + commited.Commit(); + } + str = observacao; + } + catch (Exception exception) + { + num = base.Registrar(exception, 171, num, new { id = id, observacao = observacao }, true); + continue; + } + return str; + } + return ""; + }); + return str1; + } + + public async Task Save(Cliente cliente, bool salvando = false) + { + int num = 3; + base.Sucesso = true; + Cliente cliente1 = cliente; + Cliente cliente2 = await Task.Run(() => { + Cliente cliente3; + List list; + List clienteEnderecos; + List maisContatos; + List clienteEmails; + List clienteVinculos; + while (num > 0) + { + List registroLogs = new List(); + cliente = cliente1; + try + { + TipoAcao tipoAcao = (cliente.get_Id() == 0 ? 0 : 1); + ObservableCollection telefones = cliente.get_Telefones(); + if (telefones != null) + { + list = telefones.ToList(); + } + else + { + list = null; + } + List clienteTelefones = list; + ObservableCollection enderecos = cliente.get_Enderecos(); + if (enderecos != null) + { + clienteEnderecos = enderecos.ToList(); + } + else + { + clienteEnderecos = null; + } + List clienteEnderecos1 = clienteEnderecos; + ObservableCollection contatos = cliente.get_Contatos(); + if (contatos != null) + { + maisContatos = contatos.ToList(); + } + else + { + maisContatos = null; + } + List maisContatos1 = maisContatos; + ObservableCollection emails = cliente.get_Emails(); + if (emails != null) + { + clienteEmails = emails.ToList(); + } + else + { + clienteEmails = null; + } + List clienteEmails1 = clienteEmails; + ObservableCollection vinculos = cliente.get_Vinculos(); + if (vinculos != null) + { + clienteVinculos = vinculos.ToList(); + } + else + { + clienteVinculos = null; + } + List clienteVinculos1 = clienteVinculos; + List origens = cliente.get_Origens(); + cliente.set_Telefones(null); + cliente.set_Enderecos(null); + cliente.set_Contatos(null); + cliente.set_Emails(null); + cliente.set_Vinculos(null); + cliente.set_Contatos(null); + cliente.set_Origens(null); + using (UnitOfWork commited = Instancia.Commited) + { + bool id = cliente.get_Id() == (long)0; + if (cliente.get_Id() != (long)0 & salvando) + { + id = true; + tipoAcao = 0; + } + if (tipoAcao == 1) + { + List objs = new List() + { + clienteTelefones, + clienteEnderecos1, + maisContatos1, + clienteEmails1, + clienteVinculos1, + cliente + }; + registroLogs.Add(base.CreateDynamicLog(cliente.get_Id(), objs, 1)); + List clienteTelefones1 = commited.get_ClienteTelefoneRepository().DeleteFone(cliente.get_Id(), clienteTelefones); + if (clienteTelefones1 != null) + { + clienteTelefones1.ForEach((ClienteTelefone fone) => this.logs.Add(base.CreateLog(cliente.get_Id(), fone.GetValorOriginal(), 1, 2))); + } + else + { + } + List clienteEnderecos2 = commited.get_ClienteEnderecoRepository().DeleteEndereco(cliente.get_Id(), clienteEnderecos1); + if (clienteEnderecos2 != null) + { + clienteEnderecos2.ForEach((ClienteEndereco endereco) => this.logs.Add(base.CreateLog(cliente.get_Id(), endereco.GetValorOriginal(), 1, 2))); + } + else + { + } + List maisContatos2 = commited.get_MaisContatoRepository().DeleteContato(cliente.get_Id(), maisContatos1); + if (maisContatos2 != null) + { + maisContatos2.ForEach((MaisContato contato) => this.logs.Add(base.CreateLog(cliente.get_Id(), contato.GetValorOriginal(), 1, 2))); + } + else + { + } + List clienteEmails2 = commited.get_ClienteEmailRepository().DeleteMail(cliente.get_Id(), clienteEmails1); + if (clienteEmails2 != null) + { + clienteEmails2.ForEach((ClienteEmail mail) => this.logs.Add(base.CreateLog(cliente.get_Id(), mail.GetValorOriginal(), 1, 2))); + } + else + { + } + List clienteVinculos2 = commited.get_ClienteVinculoRepository().DeleteVinculo(cliente.get_Id(), clienteVinculos1); + if (clienteVinculos2 != null) + { + clienteVinculos2.ForEach((ClienteVinculo vinculo) => this.logs.Add(base.CreateLog(cliente.get_Id(), vinculo.GetValorOriginal(), 1, 2))); + } + else + { + } + } + if (!id) + { + if (clienteTelefones != null) + { + clienteTelefones = commited.get_ClienteTelefoneRepository().Merge(clienteTelefones, cliente); + } + if (clienteEnderecos1 != null) + { + clienteEnderecos1 = commited.get_ClienteEnderecoRepository().Merge(clienteEnderecos1, cliente); + } + if (maisContatos1 != null) + { + maisContatos1 = commited.get_MaisContatoRepository().Merge(maisContatos1, cliente); + } + if (clienteEmails1 != null) + { + clienteEmails1 = commited.get_ClienteEmailRepository().Merge(clienteEmails1, cliente); + } + if (clienteVinculos1 != null) + { + clienteVinculos1 = commited.get_ClienteVinculoRepository().Merge(clienteVinculos1, cliente); + } + origens = commited.get_ClienteRepository().Sincronize(origens, cliente.get_Id()); + cliente = commited.get_ClienteRepository().Merge(cliente); + } + else + { + cliente = commited.get_ClienteRepository().SaveOrUpdate(cliente); + if (clienteTelefones != null) + { + clienteTelefones = commited.get_ClienteTelefoneRepository().Inserir(clienteTelefones, cliente); + } + if (clienteEnderecos1 != null) + { + clienteEnderecos1 = commited.get_ClienteEnderecoRepository().Inserir(clienteEnderecos1, cliente); + } + if (maisContatos1 != null) + { + maisContatos1 = commited.get_MaisContatoRepository().Inserir(maisContatos1, cliente); + } + if (clienteEmails1 != null) + { + clienteEmails1 = commited.get_ClienteEmailRepository().Inserir(clienteEmails1, cliente); + } + if (clienteVinculos1 != null) + { + clienteVinculos1 = commited.get_ClienteVinculoRepository().Inserir(clienteVinculos1, cliente); + } + if (origens != null) + { + origens.ForEach((OrigemCliente x) => { + x.set_Cliente(cliente); + x = commited.get_ClienteRepository().SaveOrUpdate(x); + }); + } + } + cliente.set_Nome(cliente.get_Nome()); + cliente.set_Telefones((clienteTelefones == null ? null : new ObservableCollection(clienteTelefones))); + cliente.set_Enderecos((clienteEnderecos1 == null ? null : new ObservableCollection(clienteEnderecos1))); + cliente.set_Contatos((maisContatos1 == null ? null : new ObservableCollection(maisContatos1))); + cliente.set_Emails((clienteEmails1 == null ? null : new ObservableCollection(clienteEmails1))); + cliente.set_Vinculos((clienteVinculos1 == null ? null : new ObservableCollection(clienteVinculos1))); + cliente.set_Origens(origens); + if (tipoAcao == null) + { + registroLogs.Add(base.CreateLog(cliente.get_Id(), cliente.GetValorOriginal(), 1, 0)); + ObservableCollection observableCollection = cliente.get_Telefones(); + if (observableCollection != null) + { + observableCollection.ToList().ForEach((ClienteTelefone fone) => this.logs.Add(base.CreateLog(cliente.get_Id(), fone.GetValorOriginal(), 1, 0))); + } + else + { + } + ObservableCollection enderecos1 = cliente.get_Enderecos(); + if (enderecos1 != null) + { + enderecos1.ToList().ForEach((ClienteEndereco endereco) => this.logs.Add(base.CreateLog(cliente.get_Id(), endereco.GetValorOriginal(), 1, 0))); + } + else + { + } + ObservableCollection contatos1 = cliente.get_Contatos(); + if (contatos1 != null) + { + contatos1.ToList().ForEach((MaisContato contato) => this.logs.Add(base.CreateLog(cliente.get_Id(), contato.GetValorOriginal(), 1, 0))); + } + else + { + } + ObservableCollection emails1 = cliente.get_Emails(); + if (emails1 != null) + { + emails1.ToList().ForEach((ClienteEmail mail) => this.logs.Add(base.CreateLog(cliente.get_Id(), mail.GetValorOriginal(), 1, 0))); + } + else + { + } + ObservableCollection vinculos1 = cliente.get_Vinculos(); + if (vinculos1 != null) + { + vinculos1.ToList().ForEach((ClienteVinculo vinculo) => this.logs.Add(base.CreateLog(cliente.get_Id(), vinculo.GetValorOriginal(), 1, 0))); + } + else + { + } + } + base.SaveLog(registroLogs, commited); + commited.Commit(); + cliente3 = cliente; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 171, num, cliente, true); + continue; + } + return cliente3; + } + return cliente1; + }); + return cliente2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Seguros/CriticaApoliceServico.cs b/Codemerx/Gestor.Application/Servicos/Seguros/CriticaApoliceServico.cs new file mode 100644 index 0000000..67d9e1f --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Seguros/CriticaApoliceServico.cs @@ -0,0 +1,321 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Seguros +{ + internal class CriticaApoliceServico : BaseServico + { + private bool _carregando; + + public CriticaApoliceServico() + { + } + + internal async Task BuscarCliente(long id) + { + int num = 3; + Cliente cliente1 = await Task.Run(() => { + Cliente cliente; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + cliente = read.get_ClienteRepository().FindById(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 27, num, id, true); + continue; + } + return cliente; + } + return new Cliente(); + }); + return cliente1; + } + + public async Task> BuscarCritica(long usuario, DateTime inicio, DateTime fim, long id = 0L, bool criticado = false, List vinculos = null) + { + List criticaApolices1; + if (!this._carregando) + { + int num3 = 3; + criticaApolices1 = await Task.Run>(() => { + List criticaApolices; + long num; + while (num3 > 0) + { + try + { + this._carregando = true; + using (UnitOfWork read = Instancia.Read) + { + id = read.get_VendedorRepository().FindCorretora().get_Id(); + ICriticaApoliceRepository criticaApoliceRepository = read.get_CriticaApoliceRepository(); + long num1 = usuario; + DateTime dateTime = inicio; + DateTime dateTime1 = fim; + long num2 = id; + bool flag = criticado; + num = (Recursos.Usuario.get_IdEmpresa() == (long)1 ? (long)0 : Recursos.Usuario.get_IdEmpresa()); + List vendedorUsuarios = vinculos; + List configuracoes = Recursos.Configuracoes; + Func u003cu003e9_21 = CriticaApoliceServico.u003cu003ec.u003cu003e9__2_1; + if (u003cu003e9_21 == null) + { + u003cu003e9_21 = (ConfiguracaoSistema x) => x.get_Configuracao() == 43; + CriticaApoliceServico.u003cu003ec.u003cu003e9__2_1 = u003cu003e9_21; + } + bool flag1 = configuracoes.Any(u003cu003e9_21); + List configuracaoSistemas = Recursos.Configuracoes; + Func u003cu003e9_22 = CriticaApoliceServico.u003cu003ec.u003cu003e9__2_2; + if (u003cu003e9_22 == null) + { + u003cu003e9_22 = (ConfiguracaoSistema x) => x.get_Configuracao() == 38; + CriticaApoliceServico.u003cu003ec.u003cu003e9__2_2 = u003cu003e9_22; + } + this._carregando = false; + criticaApolices = criticaApoliceRepository.Find(num1, dateTime, dateTime1, num2, flag, num, vendedorUsuarios, flag1, configuracaoSistemas.Any(u003cu003e9_22)); + } + } + catch (Exception exception) + { + num3 = base.Registrar(exception, 43, num3, new { usuario = usuario, inicio = inicio, fim = fim, criticado = criticado }, true); + continue; + } + return criticaApolices; + } + this._carregando = false; + return new List(); + }); + } + else + { + criticaApolices1 = new List(); + } + return criticaApolices1; + } + + public async Task> BuscarCritica(DateTime inicio, DateTime fim) + { + int num = 3; + List criticaApolices1 = await Task.Run>(() => { + List criticaApolices; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + criticaApolices = read.get_CriticaApoliceRepository().Find(inicio, fim, (Recursos.Usuario.get_IdEmpresa() == (long)1 ? (long)0 : Recursos.Usuario.get_IdEmpresa())); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 43, num, new { inicio = inicio, fim = fim }, true); + continue; + } + return criticaApolices; + } + return new List(); + }); + return criticaApolices1; + } + + public async Task> BuscarCritica(long id) + { + int num = 3; + List criticaApolices1 = await Task.Run>(() => { + List criticaApolices; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + criticaApolices = read.get_CriticaApoliceRepository().Find(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 44, num, id, true); + continue; + } + return criticaApolices; + } + return new List(); + }); + return criticaApolices1; + } + + public async Task> BuscarImportacao(long id) + { + int num = 3; + List criticaApolices1 = await Task.Run>(() => { + List criticaApolices; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + criticaApolices = read.get_CriticaApoliceRepository().FindImport(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 45, num, id, true); + continue; + } + return criticaApolices; + } + return new List(); + }); + return criticaApolices1; + } + + public async Task> BuscarSeguroCombinado(long id, DateTime vigencia) + { + int num = 3; + List criticaApolices1 = await Task.Run>(() => { + List criticaApolices; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + criticaApolices = read.get_CriticaApoliceRepository().FindDuo(id, vigencia); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 44, num, id, true); + continue; + } + return criticaApolices; + } + return new List(); + }); + return criticaApolices1; + } + + public async Task> BuscarUsuarioCritica(DateTime inicio, DateTime fim, bool criticado = false) + { + int num = 3; + List usuarios1 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List usuarios = read.get_CriticaApoliceRepository().BuscarUsuarioCritica(inicio, fim, criticado, (Recursos.Usuario.get_IdEmpresa() == (long)1 ? (long)0 : Recursos.Usuario.get_IdEmpresa())); + Func u003cu003e9_41 = CriticaApoliceServico.u003cu003ec.u003cu003e9__4_1; + if (u003cu003e9_41 == null) + { + u003cu003e9_41 = (Usuario x) => x.get_Nome(); + CriticaApoliceServico.u003cu003ec.u003cu003e9__4_1 = u003cu003e9_41; + } + list = usuarios.OrderBy(u003cu003e9_41).ToList(); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 43, num, new { inicio = inicio, fim = fim, criticado = criticado }, true); + continue; + } + return list; + } + return new List(); + }); + return usuarios1; + } + + public async Task Save(CriticaApolice critica) + { + int num = 3; + base.Sucesso = true; + CriticaApolice criticaApolouse2 = critica; + CriticaApolice criticaApolouse3 = await Task.Run(() => { + CriticaApolice criticaApolouse; + string str; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + TipoAcao tipoAcao = (criticaApolouse2.get_Id() == 0 ? 0 : 1); + criticaApolouse2 = commited.get_CriticaApoliceRepository().Merge(criticaApolouse2); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(tipoAcao); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(Funcoes.GetNetworkTime()); + CriticaApolice criticaApolouse1 = criticaApolouse2; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(criticaApolouse1, jsonSerializerSetting)); + registroLog.set_EntidadeId(criticaApolouse2.get_Id()); + registroLog.set_Tela(20); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_81 = CriticaApoliceServico.u003cu003ec.u003cu003e9__8_1; + if (u003cu003e9_81 == null) + { + u003cu003e9_81 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + CriticaApoliceServico.u003cu003ec.u003cu003e9__8_1 = u003cu003e9_81; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_81); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + criticaApolouse = criticaApolouse2; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 173, num, critica, true); + continue; + } + return criticaApolouse; + } + return critica; + }); + return criticaApolouse3; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Seguros/ExpedicaoServico.cs b/Codemerx/Gestor.Application/Servicos/Seguros/ExpedicaoServico.cs new file mode 100644 index 0000000..47fb942 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Seguros/ExpedicaoServico.cs @@ -0,0 +1,192 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Seguros +{ + public class ExpedicaoServico : BaseServico + { + public ExpedicaoServico() + { + } + + public async Task> BuscarExpedicoes(Documento documento) + { + int num = 3; + List expedicaos1 = await Task.Run>(() => { + List expedicaos; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + expedicaos = read.get_ExpedicaoRepository().FindByIdDocumento(documento.get_Id()); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 289, num, documento, true); + continue; + } + return expedicaos; + } + return new List(); + }); + return expedicaos1; + } + + public async Task Delete(Expedicao expedicao) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + string str; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + commited.get_ExpedicaoRepository().Delete(expedicao.get_Id()); + DateTime networkTime = Funcoes.GetNetworkTime(); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(2); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + registroLog.set_Descricao(string.Concat(new string[] { string.Format("O USUÁRIO {0} EXCLUIU, EM {1}, A EXPEDIÇÃO DE ", Recursos.Usuario.get_Nome(), networkTime), string.Format("ID: '{0}'", expedicao.get_Id()), ", DOCUMENTO: '", expedicao.get_Documento(), "', DESTINO: '", expedicao.get_Destino(), "'", string.Format(", DATA ENVIO: '{0}'", expedicao.get_DataEnvio()), string.Format(", DATA RECEBIMENTO: '{0}'", expedicao.get_DataRecebimento()), ", RESPONSÁVEL: 'R$", expedicao.get_Responsavel(), "'." })); + registroLog.set_EntidadeId(expedicao.get_Id()); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_Tela(46); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + RegistroLog registroLog1 = registroLog; + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_21 = ExpedicaoServico.u003cu003ec.u003cu003e9__2_1; + if (u003cu003e9_21 == null) + { + u003cu003e9_21 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + ExpedicaoServico.u003cu003ec.u003cu003e9__2_1 = u003cu003e9_21; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_21); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog1.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 291, num, expedicao, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task Save(Expedicao expedicao) + { + int num = 3; + base.Sucesso = true; + Expedicao expedicao2 = expedicao; + Expedicao expedicao3 = await Task.Run(() => { + Expedicao expedicao4; + string str; + while (num > 0) + { + expedicao = expedicao2; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + TipoAcao tipoAcao = (expedicao.get_Id() == 0 ? 0 : 1); + DateTime networkTime = Funcoes.GetNetworkTime(); + if (expedicao.get_Id() != 0) + { + expedicao.set_UsuarioAlteracao(new long?(Recursos.Usuario.get_Id())); + expedicao.set_DataAlteracao(new DateTime?(networkTime)); + expedicao = commited.get_ExpedicaoRepository().Merge(expedicao); + } + else + { + expedicao.set_UsuarioCriacao(new long?(Recursos.Usuario.get_Id())); + expedicao.set_DataCriacao(new DateTime?(networkTime)); + expedicao = commited.get_ExpedicaoRepository().SaveOrUpdate(expedicao); + } + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(tipoAcao); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + Expedicao expedicao1 = expedicao; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(expedicao1, jsonSerializerSetting)); + registroLog.set_EntidadeId(expedicao.get_Id()); + registroLog.set_Tela(46); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_11 = ExpedicaoServico.u003cu003ec.u003cu003e9__1_1; + if (u003cu003e9_11 == null) + { + u003cu003e9_11 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + ExpedicaoServico.u003cu003ec.u003cu003e9__1_1 = u003cu003e9_11; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_11); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + expedicao4 = expedicao; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 290, num, expedicao, true); + continue; + } + return expedicao4; + } + return expedicao2; + }); + return expedicao3; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Seguros/Itens/AeronauticoServico.cs b/Codemerx/Gestor.Application/Servicos/Seguros/Itens/AeronauticoServico.cs new file mode 100644 index 0000000..11c0f6f --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Seguros/Itens/AeronauticoServico.cs @@ -0,0 +1,121 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Seguros.Itens +{ + internal class AeronauticoServico : BaseServico + { + public AeronauticoServico() + { + } + + public async Task Delete(Item item) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + long id; + string str; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + if (item.get_Aeronautico() != null && item.get_Aeronautico().get_Id() > (long)0) + { + commited.get_AeronauticoRepository().Delete(item.get_Aeronautico().get_Id()); + } + commited.get_CoberturaRepository().DeletebyItem(item.get_Id()); + commited.get_ControleSinistroRepository().DeleteByItem(item.get_Id()); + commited.get_ItemRepository().Delete(item.get_Id()); + DateTime networkTime = Funcoes.GetNetworkTime(); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(2); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + Item item1 = item; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(item1, jsonSerializerSetting)); + Aeronautico aeronautico = item.get_Aeronautico(); + id = (aeronautico != null ? aeronautico.get_Id() : (long)0); + registroLog.set_EntidadeId(id); + registroLog.set_Tela(3); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_11 = AeronauticoServico.u003cu003ec.u003cu003e9__1_1; + if (u003cu003e9_11 == null) + { + u003cu003e9_11 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + AeronauticoServico.u003cu003ec.u003cu003e9__1_1 = u003cu003e9_11; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_11); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 203, num, item, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task Save(Aeronautico aeronautico) + { + Aeronautico aeronautico1 = await Task.Run(() => { + Aeronautico aeronautico2; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + aeronautico = (aeronautico.get_Id() == 0 ? commited.get_AeronauticoRepository().SaveOrUpdate(aeronautico) : commited.get_AeronauticoRepository().Merge(aeronautico)); + commited.Commit(); + aeronautico2 = aeronautico; + } + } + catch (Exception exception) + { + aeronautico2 = null; + } + return aeronautico2; + }); + return aeronautico1; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Seguros/Itens/AutoServico.cs b/Codemerx/Gestor.Application/Servicos/Seguros/Itens/AutoServico.cs new file mode 100644 index 0000000..ba8eb2f --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Seguros/Itens/AutoServico.cs @@ -0,0 +1,262 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Seguros.Itens +{ + internal class AutoServico : BaseServico + { + public AutoServico() + { + } + + internal async Task BuscarAuto(string value, long id, DateTime vigencia1, DateTime? vigencia2, long idSeguradora) + { + int num = 3; + Documento documento1 = await Task.Run(() => { + Documento documento; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + documento = read.get_AutoRepository().FindByChassi(value, id, vigencia1, vigencia2, idSeguradora); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 50, num, new { @value = value, id = id }, true); + continue; + } + return documento; + } + return new Documento(); + }); + return documento1; + } + + internal async Task> BuscarChassi(string chassi, FiltroStatusDocumento status, List vendedorVinculado, bool tipobusca = false) + { + List pesquisaAvancadas1 = await Task.Run>(() => { + List pesquisaAvancadas; + try + { + using (UnitOfWork read = Instancia.Read) + { + pesquisaAvancadas = read.get_AutoRepository().FindAuto(chassi, status, vendedorVinculado, 0, tipobusca); + } + } + catch (Exception exception) + { + pesquisaAvancadas = null; + } + return pesquisaAvancadas; + }); + return pesquisaAvancadas1; + } + + public async Task BuscarChassi(long id) + { + string str1 = await Task.Run(() => { + string str; + try + { + using (UnitOfWork read = Instancia.Read) + { + str = read.get_AutoRepository().FindChassi(id); + } + } + catch (Exception exception) + { + str = null; + } + return str; + }); + return str1; + } + + public async Task> BuscarItem(string item, FiltroStatusDocumento status, List vendedorVinculado, bool tipobusca = false) + { + List pesquisaAvancadas1 = await Task.Run>(() => { + List pesquisaAvancadas; + try + { + using (UnitOfWork read = Instancia.Read) + { + pesquisaAvancadas = read.get_AutoRepository().FindAuto(item, status, vendedorVinculado, 6, tipobusca); + } + } + catch (Exception exception) + { + pesquisaAvancadas = null; + } + return pesquisaAvancadas; + }); + return pesquisaAvancadas1; + } + + internal async Task> BuscarPlaca(string placa, FiltroStatusDocumento status, List vendedorVinculado, bool tipobusca = false) + { + List pesquisaAvancadas1 = await Task.Run>(() => { + List pesquisaAvancadas; + try + { + using (UnitOfWork read = Instancia.Read) + { + pesquisaAvancadas = read.get_AutoRepository().FindAuto(placa, status, vendedorVinculado, 14, tipobusca); + } + } + catch (Exception exception) + { + pesquisaAvancadas = null; + } + return pesquisaAvancadas; + }); + return pesquisaAvancadas1; + } + + public async Task Delete(Item item) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + long id; + string str; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + if (item.get_Auto() != null && item.get_Auto().get_Id() > (long)0) + { + commited.get_AutoRepository().Delete(item.get_Auto().get_Id()); + } + commited.get_CoberturaRepository().DeletebyItem(item.get_Id()); + commited.get_ControleSinistroRepository().DeleteByItem(item.get_Id()); + commited.get_ItemRepository().Delete(item.get_Id()); + DateTime networkTime = Funcoes.GetNetworkTime(); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(2); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + Item item1 = item; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(item1, jsonSerializerSetting)); + Auto auto = item.get_Auto(); + id = (auto != null ? auto.get_Id() : (long)0); + registroLog.set_EntidadeId(id); + registroLog.set_Tela(3); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_21 = AutoServico.u003cu003ec.u003cu003e9__2_1; + if (u003cu003e9_21 == null) + { + u003cu003e9_21 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + AutoServico.u003cu003ec.u003cu003e9__2_1 = u003cu003e9_21; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_21); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 205, num, item, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task Save(Auto auto) + { + Auto auto2 = await Task.Run(() => { + Auto auto3; + string str; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + TipoAcao tipoAcao = (auto.get_Id() == 0 ? 0 : 1); + auto = (auto.get_Id() == 0 ? commited.get_AutoRepository().SaveOrUpdate(auto) : commited.get_AutoRepository().Merge(auto)); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(tipoAcao); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(Funcoes.GetNetworkTime()); + Auto auto1 = auto; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(auto1, jsonSerializerSetting)); + registroLog.set_EntidadeId(auto.get_Id()); + registroLog.set_Tela(3); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_11 = AutoServico.u003cu003ec.u003cu003e9__1_1; + if (u003cu003e9_11 == null) + { + u003cu003e9_11 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + AutoServico.u003cu003ec.u003cu003e9__1_1 = u003cu003e9_11; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_11); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + auto3 = auto; + } + } + catch (Exception exception) + { + auto3 = null; + } + return auto3; + }); + return auto2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Seguros/Itens/ConsorcioServico.cs b/Codemerx/Gestor.Application/Servicos/Seguros/Itens/ConsorcioServico.cs new file mode 100644 index 0000000..2c981c8 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Seguros/Itens/ConsorcioServico.cs @@ -0,0 +1,156 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Seguros.Itens +{ + internal class ConsorcioServico : BaseServico + { + public ConsorcioServico() + { + } + + public async Task Delete(Item item) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + long id; + string str; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + if (item.get_Consorcio() != null && item.get_Consorcio().get_Id() > (long)0) + { + commited.get_ConsorcioRepository().Delete(item.get_Consorcio().get_Id()); + } + commited.get_CoberturaRepository().DeletebyItem(item.get_Id()); + commited.get_ControleSinistroRepository().DeleteByItem(item.get_Id()); + commited.get_ItemRepository().Delete(item.get_Id()); + DateTime networkTime = Funcoes.GetNetworkTime(); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(2); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + Item item1 = item; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(item1, jsonSerializerSetting)); + Consorcio consorcio = item.get_Consorcio(); + id = (consorcio != null ? consorcio.get_Id() : (long)0); + registroLog.set_EntidadeId(id); + registroLog.set_Tela(3); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_11 = ConsorcioServico.u003cu003ec.u003cu003e9__1_1; + if (u003cu003e9_11 == null) + { + u003cu003e9_11 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + ConsorcioServico.u003cu003ec.u003cu003e9__1_1 = u003cu003e9_11; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_11); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 332, num, null, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task Save(Gestor.Model.Domain.Seguros.Consorcio Consorcio) + { + Gestor.Model.Domain.Seguros.Consorcio consorcio2 = await Task.Run(() => { + Gestor.Model.Domain.Seguros.Consorcio consorcio; + string str; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + TipoAcao tipoAcao = (Consorcio.get_Id() == 0 ? 0 : 1); + Consorcio = (Consorcio.get_Id() == 0 ? commited.get_ConsorcioRepository().SaveOrUpdate(Consorcio) : commited.get_ConsorcioRepository().Merge(Consorcio)); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(tipoAcao); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(Funcoes.GetNetworkTime()); + Gestor.Model.Domain.Seguros.Consorcio consorcio1 = Consorcio; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(consorcio1, jsonSerializerSetting)); + registroLog.set_EntidadeId(Consorcio.get_Id()); + registroLog.set_Tela(3); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_01 = ConsorcioServico.u003cu003ec.u003cu003e9__0_1; + if (u003cu003e9_01 == null) + { + u003cu003e9_01 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + ConsorcioServico.u003cu003ec.u003cu003e9__0_1 = u003cu003e9_01; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_01); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + consorcio = Consorcio; + } + } + catch (Exception exception) + { + consorcio = null; + } + return consorcio; + }); + return consorcio2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Seguros/Itens/GranizoServico.cs b/Codemerx/Gestor.Application/Servicos/Seguros/Itens/GranizoServico.cs new file mode 100644 index 0000000..054685c --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Seguros/Itens/GranizoServico.cs @@ -0,0 +1,156 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Seguros.Itens +{ + internal class GranizoServico : BaseServico + { + public GranizoServico() + { + } + + public async Task Delete(Item item) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + long id; + string str; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + if (item.get_Granizo() != null && item.get_Granizo().get_Id() > (long)0) + { + commited.get_GranizoRepository().Delete(item.get_Granizo().get_Id()); + } + commited.get_CoberturaRepository().DeletebyItem(item.get_Id()); + commited.get_ControleSinistroRepository().DeleteByItem(item.get_Id()); + commited.get_ItemRepository().Delete(item.get_Id()); + DateTime networkTime = Funcoes.GetNetworkTime(); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(2); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + Item item1 = item; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(item1, jsonSerializerSetting)); + Granizo granizo = item.get_Granizo(); + id = (granizo != null ? granizo.get_Id() : (long)0); + registroLog.set_EntidadeId(id); + registroLog.set_Tela(3); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_11 = GranizoServico.u003cu003ec.u003cu003e9__1_1; + if (u003cu003e9_11 == null) + { + u003cu003e9_11 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + GranizoServico.u003cu003ec.u003cu003e9__1_1 = u003cu003e9_11; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_11); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 207, num, item, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task Save(Granizo granizo) + { + Granizo granizo2 = await Task.Run(() => { + Granizo granizo3; + string str; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + TipoAcao tipoAcao = (granizo.get_Id() == 0 ? 0 : 1); + granizo = (granizo.get_Id() == 0 ? commited.get_GranizoRepository().SaveOrUpdate(granizo) : commited.get_GranizoRepository().Merge(granizo)); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(tipoAcao); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(Funcoes.GetNetworkTime()); + Granizo granizo1 = granizo; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(granizo1, jsonSerializerSetting)); + registroLog.set_EntidadeId(granizo.get_Id()); + registroLog.set_Tela(3); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_01 = GranizoServico.u003cu003ec.u003cu003e9__0_1; + if (u003cu003e9_01 == null) + { + u003cu003e9_01 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + GranizoServico.u003cu003ec.u003cu003e9__0_1 = u003cu003e9_01; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_01); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + granizo3 = granizo; + } + } + catch (Exception exception) + { + granizo3 = null; + } + return granizo3; + }); + return granizo2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Seguros/Itens/ItemServico.cs b/Codemerx/Gestor.Application/Servicos/Seguros/Itens/ItemServico.cs new file mode 100644 index 0000000..a666367 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Seguros/Itens/ItemServico.cs @@ -0,0 +1,1900 @@ +using Agger.Registro; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels; +using Gestor.Common.Validation; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Seguros.Itens +{ + public class ItemServico : BaseServico + { + private const string GuidGestorFipe = "bbbf4f03-01fc-4300-b430-33e007753578"; + + public ItemServico() + { + } + + public async Task BuscaAeronautico(long id) + { + int num = 3; + Aeronautico aeronautico1 = await Task.Run(() => { + Aeronautico aeronautico; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + aeronautico = read.get_AeronauticoRepository().Find(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 63, num, id, true); + continue; + } + return aeronautico; + } + return new Aeronautico(); + }); + return aeronautico1; + } + + internal async Task BuscaAuto(long id) + { + int num = 3; + Auto auto1 = await Task.Run(() => { + Auto auto; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + auto = read.get_AutoRepository().Find(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 55, num, id, true); + continue; + } + return auto; + } + return new Auto(); + }); + return auto1; + } + + public async Task BuscaConsorcio(long id) + { + int num = 3; + Consorcio consorcio1 = await Task.Run(() => { + Consorcio consorcio; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + consorcio = read.get_ConsorcioRepository().Find(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 330, num, id, true); + continue; + } + return consorcio; + } + return new Consorcio(); + }); + return consorcio1; + } + + internal async Task BuscaGranizo(long id) + { + int num = 3; + Granizo granizo1 = await Task.Run(() => { + Granizo granizo; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + granizo = read.get_GranizoRepository().Find(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 56, num, id, true); + continue; + } + return granizo; + } + return new Granizo(); + }); + return granizo1; + } + + internal async Task> BuscaItensPorObs(string observacao, FiltroStatusDocumento status, List vendedorVinculado, bool tipobusca = false) + { + List pesquisaAvancadas1 = await Task.Run>(async () => { + List pesquisaAvancadas; + try + { + using (UnitOfWork read = Instancia.Read) + { + pesquisaAvancadas = await read.get_ItemRepository().BuscaItensPorObs(observacao, status, vendedorVinculado, 18, tipobusca); + } + } + catch (Exception exception) + { + pesquisaAvancadas = null; + } + return pesquisaAvancadas; + }); + return pesquisaAvancadas1; + } + + public async Task BuscaPatrimonial(long id) + { + int num = 3; + Patrimonial patrimonial1 = await Task.Run(() => { + Patrimonial patrimonial; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + patrimonial = read.get_PatrimonialRepository().Find(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 59, num, id, true); + continue; + } + return patrimonial; + } + return new Patrimonial(); + }); + return patrimonial1; + } + + public async Task BuscarCliente(long id) + { + int num = 3; + Cliente cliente1 = await Task.Run(() => { + Cliente cliente; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + cliente = read.get_ItemRepository().BuscarCliente(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 27, num, id, true); + continue; + } + return cliente; + } + return new Cliente(); + }); + return cliente1; + } + + internal async Task> BuscarCoberturasPorItemAsync(long id) + { + int num = 3; + ObservableCollection observableCollection1 = await Task.Run>(() => { + ObservableCollection observableCollection; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + observableCollection = new ObservableCollection(read.get_CoberturaRepository().FindByItemId(id)); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 57, num, id, true); + continue; + } + return observableCollection; + } + return new ObservableCollection(); + }); + return observableCollection1; + } + + public async Task BuscaRiscosDiversos(long id) + { + int num = 3; + RiscosDiversos riscosDiverso1 = await Task.Run(() => { + RiscosDiversos riscosDiverso; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + riscosDiverso = read.get_RiscosDiversosRepository().Find(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 62, num, id, true); + continue; + } + return riscosDiverso; + } + return new RiscosDiversos(); + }); + return riscosDiverso1; + } + + internal async Task BuscarItemPorIdAsync(long id) + { + int num = 3; + Item item1 = await Task.Run(() => { + Item item; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + item = read.get_ItemRepository().FindById(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 51, num, id, true); + continue; + } + return item; + } + return new Item(); + }); + return item1; + } + + internal async Task> BuscarItems(long id, StatusItem status = 2, bool sinsitroCompleto = false) + { + int num = 3; + ObservableCollection observableCollection1 = await Task.Run>(() => { + ObservableCollection observableCollection; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + observableCollection = new ObservableCollection(read.get_ItemRepository().FindByDocumentsIds(id, status, sinsitroCompleto)); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 52, num, new { id = id, status = status }, true); + continue; + } + return observableCollection; + } + return new ObservableCollection(); + }); + return observableCollection1; + } + + internal async Task> BuscarItems(List ids) + { + int num = 3; + List items1 = await Task.Run>(() => { + List items; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + items = read.get_ItemRepository().FindByIds(ids); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 52, num, ids, true); + continue; + } + return items; + } + return new List(); + }); + return items1; + } + + public async Task> BuscarItens(List ids) + { + int num = 3; + ObservableCollection observableCollection1 = await Task.Run>(() => { + ObservableCollection observableCollection; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List items = read.get_ItemRepository().FindItens(ids); + if (items != null) + { + List items1 = items; + Func u003cu003e9_281 = ItemServico.u003cu003ec.u003cu003e9__28_1; + if (u003cu003e9_281 == null) + { + u003cu003e9_281 = (Item x) => x.get_Ordem(); + ItemServico.u003cu003ec.u003cu003e9__28_1 = u003cu003e9_281; + } + IOrderedEnumerable items2 = items1.OrderBy(u003cu003e9_281); + Func u003cu003e9_282 = ItemServico.u003cu003ec.u003cu003e9__28_2; + if (u003cu003e9_282 == null) + { + u003cu003e9_282 = (Item x) => x.get_Descricao(); + ItemServico.u003cu003ec.u003cu003e9__28_2 = u003cu003e9_282; + } + observableCollection = new ObservableCollection(items2.ThenBy(u003cu003e9_282)); + return observableCollection; + } + } + continue; + } + catch (Exception exception) + { + num = base.Registrar(exception, 52, num, ids, true); + continue; + } + return observableCollection; + } + return new ObservableCollection(); + }); + return observableCollection1; + } + + public async Task> BuscarItens(long id, StatusItem status) + { + int num = 3; + ObservableCollection observableCollection1 = await Task.Run>(() => { + ObservableCollection observableCollection; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List items = read.get_ItemRepository().FindItens(id, status); + if (items != null) + { + List items1 = items; + Func u003cu003e9_291 = ItemServico.u003cu003ec.u003cu003e9__29_1; + if (u003cu003e9_291 == null) + { + u003cu003e9_291 = (Item x) => x.get_Ordem(); + ItemServico.u003cu003ec.u003cu003e9__29_1 = u003cu003e9_291; + } + IOrderedEnumerable items2 = items1.OrderBy(u003cu003e9_291); + Func u003cu003e9_292 = ItemServico.u003cu003ec.u003cu003e9__29_2; + if (u003cu003e9_292 == null) + { + u003cu003e9_292 = (Item x) => x.get_Descricao(); + ItemServico.u003cu003ec.u003cu003e9__29_2 = u003cu003e9_292; + } + observableCollection = new ObservableCollection(items2.ThenBy(u003cu003e9_292)); + return observableCollection; + } + } + continue; + } + catch (Exception exception) + { + num = base.Registrar(exception, 53, num, new { id = id, status = status }, true); + continue; + } + return observableCollection; + } + return new ObservableCollection(); + }); + return observableCollection1; + } + + public async Task> BuscarItens(List documento) + { + int num = 3; + ObservableCollection observableCollection1 = await Task.Run>(() => { + ObservableCollection observableCollection; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List items = read.get_ItemRepository().FindItens(documento); + if (items != null) + { + List items1 = items; + Func u003cu003e9_301 = ItemServico.u003cu003ec.u003cu003e9__30_1; + if (u003cu003e9_301 == null) + { + u003cu003e9_301 = (Item x) => x.get_Ordem(); + ItemServico.u003cu003ec.u003cu003e9__30_1 = u003cu003e9_301; + } + IOrderedEnumerable items2 = items1.OrderBy(u003cu003e9_301); + Func u003cu003e9_302 = ItemServico.u003cu003ec.u003cu003e9__30_2; + if (u003cu003e9_302 == null) + { + u003cu003e9_302 = (Item x) => x.get_Descricao(); + ItemServico.u003cu003ec.u003cu003e9__30_2 = u003cu003e9_302; + } + observableCollection = new ObservableCollection(items2.ThenBy(u003cu003e9_302)); + return observableCollection; + } + } + continue; + } + catch (Exception exception) + { + num = base.Registrar(exception, 305, num, documento, true); + continue; + } + return observableCollection; + } + return new ObservableCollection(); + }); + return observableCollection1; + } + + public async Task> BuscarItens(long id) + { + int num = 3; + ObservableCollection observableCollection1 = await Task.Run>(() => { + ObservableCollection observableCollection; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List items = read.get_ItemRepository().FindItens(id); + if (items != null) + { + List items1 = items; + Func u003cu003e9_311 = ItemServico.u003cu003ec.u003cu003e9__31_1; + if (u003cu003e9_311 == null) + { + u003cu003e9_311 = (Item x) => x.get_Ordem(); + ItemServico.u003cu003ec.u003cu003e9__31_1 = u003cu003e9_311; + } + IOrderedEnumerable items2 = items1.OrderBy(u003cu003e9_311); + Func u003cu003e9_312 = ItemServico.u003cu003ec.u003cu003e9__31_2; + if (u003cu003e9_312 == null) + { + u003cu003e9_312 = (Item x) => x.get_Descricao(); + ItemServico.u003cu003ec.u003cu003e9__31_2 = u003cu003e9_312; + } + observableCollection = new ObservableCollection(items2.ThenBy(u003cu003e9_312)); + return observableCollection; + } + } + continue; + } + catch (Exception exception) + { + num = base.Registrar(exception, 53, num, id, true); + continue; + } + return observableCollection; + } + return new ObservableCollection(); + }); + return observableCollection1; + } + + public async Task BuscarModelo(string fipe) + { + Fipe fipe1; + try + { + fipe1 = await this.FipeCode(fipe); + } + catch (Exception exception) + { + fipe1 = null; + } + return fipe1; + } + + public async Task> BuscarPorModelo(string modelo) + { + List fipes; + try + { + fipes = await this.FipeModel(modelo); + } + catch (Exception exception) + { + fipes = null; + } + return fipes; + } + + public async Task BuscarProximoItem(long id) + { + int num1 = 3; + int num2 = await Task.Run(() => { + int num; + while (num1 > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + num = read.get_ItemRepository().FindNextItem(id); + } + } + catch (Exception exception) + { + num1 = base.Registrar(exception, 54, num1, id, true); + continue; + } + return num; + } + return 0; + }); + return num2; + } + + public async Task> BuscaTitularesVida(long id) + { + int num = 3; + List titularesVidas1 = await Task.Run>(() => { + List titularesVidas; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + titularesVidas = read.get_TitularesVidaRepository().Find(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 61, num, id, true); + continue; + } + return titularesVidas; + } + return new List(); + }); + return titularesVidas1; + } + + public async Task BuscaVida(long id) + { + int num = 3; + Vida vida1 = await Task.Run(() => { + Vida vida; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + vida = read.get_VidaRepository().Find(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 60, num, id, true); + continue; + } + return vida; + } + return new Vida(); + }); + return vida1; + } + + public async Task Cancelar(Item item, string descricao, long idDocumento) + { + Item item1 = await Task.Run(() => { + Item item2; + string str; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + item = commited.get_ItemRepository().FindById(item.get_Id()); + item.set_Cancelado(true); + item.set_Status(descricao); + item.set_IdDocumentoCancelado(new long?(idDocumento)); + item = commited.get_ItemRepository().Merge(item); + DateTime networkTime = Funcoes.GetNetworkTime(); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(1); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + RegistroLog registroLog1 = registroLog; + string[] strArrays = new string[] { string.Format("O USUÁRIO {0} CANCELOU, EM {1}, O ITEM DE ", Recursos.Usuario.get_Nome(), networkTime), string.Format("ID: '{0}'", item.get_Id()), ", DESCRIÇÃO: '", null, null, null, null, null, null, null, null }; + strArrays[3] = (string.IsNullOrWhiteSpace(item.get_Descricao()) ? "" : item.get_Descricao() ?? ""); + strArrays[4] = "', OBSERVAÇÃO: '"; + strArrays[5] = (string.IsNullOrWhiteSpace(item.get_Observacao()) ? "" : item.get_Observacao() ?? ""); + strArrays[6] = "', STATUS: '"; + strArrays[7] = (string.IsNullOrWhiteSpace(item.get_Status()) ? "" : item.get_Status() ?? ""); + strArrays[8] = "' - "; + strArrays[9] = descricao; + strArrays[10] = "."; + registroLog1.set_Descricao(string.Concat(strArrays)); + registroLog.set_EntidadeId(item.get_Id()); + registroLog.set_Tela(3); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + RegistroLog registroLog2 = registroLog; + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_201 = ItemServico.u003cu003ec.u003cu003e9__20_1; + if (u003cu003e9_201 == null) + { + u003cu003e9_201 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + ItemServico.u003cu003ec.u003cu003e9__20_1 = u003cu003e9_201; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_201); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog2.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + item2 = item; + } + } + catch (Exception exception) + { + item2 = null; + } + return item2; + }); + return item1; + } + + public async Task ChecarQuantidade(long idDocumento) + { + int num1 = await Task.Run(() => { + int num; + try + { + using (UnitOfWork read = Instancia.Read) + { + num = read.get_ItemRepository().ChecarQuantidade(idDocumento); + } + } + catch + { + num = 0; + } + return num; + }); + return num1; + } + + public async Task Delete(Item item) + { + int num = 3; + DateTime networkTime = Funcoes.GetNetworkTime(); + await Task.Run(() => { + string str; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + commited.get_CoberturaRepository().DeletebyItem(item.get_Id()); + commited.get_ControleSinistroRepository().Delete(item.get_Id()); + commited.get_ItemRepository().Delete(item.get_Id()); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(2); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + RegistroLog registroLog1 = registroLog; + string[] strArrays = new string[] { string.Format("O USUÁRIO {0} SUBSTITUIU, EM {1}, O ITEM DE", Recursos.Usuario.get_Nome(), networkTime), string.Format("ID: '{0}'", item.get_Id()), ", DESCRIÇÃO: '", null, null, null, null, null, null }; + strArrays[3] = (string.IsNullOrWhiteSpace(item.get_Descricao()) ? "" : item.get_Descricao() ?? ""); + strArrays[4] = "', OBSERVAÇÃO: '"; + strArrays[5] = (string.IsNullOrWhiteSpace(item.get_Observacao()) ? "" : item.get_Observacao() ?? ""); + strArrays[6] = "', STATUS: '"; + strArrays[7] = (string.IsNullOrWhiteSpace(item.get_Status()) ? "" : item.get_Status() ?? ""); + strArrays[8] = "'."; + registroLog1.set_Descricao(string.Concat(strArrays)); + registroLog.set_EntidadeId(item.get_Id()); + registroLog.set_Tela(3); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + RegistroLog registroLog2 = registroLog; + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_241 = ItemServico.u003cu003ec.u003cu003e9__24_1; + if (u003cu003e9_241 == null) + { + u003cu003e9_241 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + ItemServico.u003cu003ec.u003cu003e9__24_1 = u003cu003e9_241; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_241); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog2.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 274, num, item, true); + } + } + }); + } + + public async Task DeleteRange(List itens, long ramo) + { + if (itens != null && itens.Count != 0) + { + int num2 = 3; + DateTime networkTime = Funcoes.GetNetworkTime(); + await Task.Run(() => { + TipoTela tipoTela; + string str; + while (num2 > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + ICoberturaRepository coberturaRepository = commited.get_CoberturaRepository(); + List items = itens; + Func u003cu003e9_251 = ItemServico.u003cu003ec.u003cu003e9__25_1; + if (u003cu003e9_251 == null) + { + u003cu003e9_251 = (Item x) => x.get_Id(); + ItemServico.u003cu003ec.u003cu003e9__25_1 = u003cu003e9_251; + } + coberturaRepository.DeleteRange(items.Select(u003cu003e9_251).ToList()); + IControleSinistroRepository controleSinistroRepository = commited.get_ControleSinistroRepository(); + List items1 = itens; + Func u003cu003e9_252 = ItemServico.u003cu003ec.u003cu003e9__25_2; + if (u003cu003e9_252 == null) + { + u003cu003e9_252 = (Item x) => x.get_Id(); + ItemServico.u003cu003ec.u003cu003e9__25_2 = u003cu003e9_252; + } + controleSinistroRepository.DeleteRange(items1.Select(u003cu003e9_252).ToList()); + long num = ramo; + if (num > (long)36) + { + if (num == (long)37) + { + goto Label0; + } + if (num == (long)53) + { + goto Label1; + } + } + else + { + long num1 = num - (long)1; + if (num1 <= (long)19) + { + switch ((uint)num1) + { + case 0: + case 1: + case 2: + case 14: + case 17: + { + IPatrimonialRepository patrimonialRepository = commited.get_PatrimonialRepository(); + List items2 = itens; + Func u003cu003e9_254 = ItemServico.u003cu003ec.u003cu003e9__25_4; + if (u003cu003e9_254 == null) + { + u003cu003e9_254 = (Item x) => x.get_Id(); + ItemServico.u003cu003ec.u003cu003e9__25_4 = u003cu003e9_254; + } + patrimonialRepository.DeleteRange(items2.Select(u003cu003e9_254).ToList()); + tipoTela = 3; + goto Label2; + } + case 3: + case 7: + case 10: + case 11: + case 13: + case 15: + case 16: + case 18: + { + goto Label3; + } + case 4: + { + goto Label0; + } + case 5: + case 6: + case 8: + case 9: + { + goto Label1; + } + case 12: + { + IAeronauticoRepository aeronauticoRepository = commited.get_AeronauticoRepository(); + List items3 = itens; + Func u003cu003e9_255 = ItemServico.u003cu003ec.u003cu003e9__25_5; + if (u003cu003e9_255 == null) + { + u003cu003e9_255 = (Item x) => x.get_Id(); + ItemServico.u003cu003ec.u003cu003e9__25_5 = u003cu003e9_255; + } + aeronauticoRepository.DeleteRange(items3.Select(u003cu003e9_255).ToList()); + tipoTela = 3; + goto Label2; + } + case 19: + { + IGranizoRepository granizoRepository = commited.get_GranizoRepository(); + List items4 = itens; + Func u003cu003e9_256 = ItemServico.u003cu003ec.u003cu003e9__25_6; + if (u003cu003e9_256 == null) + { + u003cu003e9_256 = (Item x) => x.get_Id(); + ItemServico.u003cu003ec.u003cu003e9__25_6 = u003cu003e9_256; + } + granizoRepository.DeleteRange(items4.Select(u003cu003e9_256).ToList()); + tipoTela = 3; + goto Label2; + } + } + } + else + { + } + if (num != (long)36) + { + goto Label3; + } + IConsorcioRepository consorcioRepository = commited.get_ConsorcioRepository(); + List items5 = itens; + Func u003cu003e9_258 = ItemServico.u003cu003ec.u003cu003e9__25_8; + if (u003cu003e9_258 == null) + { + u003cu003e9_258 = (Item x) => x.get_Id(); + ItemServico.u003cu003ec.u003cu003e9__25_8 = u003cu003e9_258; + } + consorcioRepository.DeleteRange(items5.Select(u003cu003e9_258).ToList()); + tipoTela = 3; + goto Label2; + } + Label3: + IRiscosDiversosRepository riscosDiversosRepository = commited.get_RiscosDiversosRepository(); + List items6 = itens; + Func u003cu003e9_259 = ItemServico.u003cu003ec.u003cu003e9__25_9; + if (u003cu003e9_259 == null) + { + u003cu003e9_259 = (Item x) => x.get_Id(); + ItemServico.u003cu003ec.u003cu003e9__25_9 = u003cu003e9_259; + } + riscosDiversosRepository.DeleteRange(items6.Select(u003cu003e9_259).ToList()); + tipoTela = 3; + Label2: + IItemRepository itemRepository = commited.get_ItemRepository(); + List items7 = itens; + Func u003cu003e9_2510 = ItemServico.u003cu003ec.u003cu003e9__25_10; + if (u003cu003e9_2510 == null) + { + u003cu003e9_2510 = (Item x) => x.get_Id(); + ItemServico.u003cu003ec.u003cu003e9__25_10 = u003cu003e9_2510; + } + itemRepository.DeleteRange(items7.Select(u003cu003e9_2510).ToList()); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + List.Enumerator enumerator = itens.GetEnumerator(); + try + { + if (enumerator.MoveNext()) + { + Item current = enumerator.Current; + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(2); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + RegistroLog registroLog1 = registroLog; + string[] strArrays = new string[] { string.Format("O USUÁRIO {0} SUBSTITUIU, EM {1}, O ITEM DE", Recursos.Usuario.get_Nome(), networkTime), string.Format("ID: '{0}'", current.get_Id()), ", DESCRIÇÃO: '", null, null, null, null, null, null, null }; + strArrays[3] = (string.IsNullOrWhiteSpace(current.get_Descricao()) ? "" : current.get_Descricao() ?? ""); + strArrays[4] = "', OBSERVAÇÃO: '"; + strArrays[5] = (string.IsNullOrWhiteSpace(current.get_Observacao()) ? "" : current.get_Observacao() ?? ""); + strArrays[6] = "', STATUS: '"; + strArrays[7] = (string.IsNullOrWhiteSpace(current.get_Status()) ? "" : current.get_Status() ?? ""); + strArrays[8] = "'"; + strArrays[9] = string.Format(", RAMO: '{0}'.", ramo); + registroLog1.set_Descricao(string.Concat(strArrays)); + registroLog.set_EntidadeId(current.get_Id()); + registroLog.set_Tela(tipoTela); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + RegistroLog registroLog2 = registroLog; + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_2511 = ItemServico.u003cu003ec.u003cu003e9__25_11; + if (u003cu003e9_2511 == null) + { + u003cu003e9_2511 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + ItemServico.u003cu003ec.u003cu003e9__25_11 = u003cu003e9_2511; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_2511); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog2.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + break; + } + } + finally + { + ((IDisposable)enumerator).Dispose(); + } + } + } + catch (Exception exception) + { + num2 = base.Registrar(exception, 275, num2, itens, true); + } + } + return; + Label0: + IAutoRepository autoRepository = commited.get_AutoRepository(); + List items8 = itens; + Func u003cu003e9_253 = ItemServico.u003cu003ec.u003cu003e9__25_3; + if (u003cu003e9_253 == null) + { + u003cu003e9_253 = (Item x) => x.get_Id(); + ItemServico.u003cu003ec.u003cu003e9__25_3 = u003cu003e9_253; + } + autoRepository.DeleteRange(items8.Select(u003cu003e9_253).ToList()); + tipoTela = 3; + goto Label2; + Label1: + IVidaRepository vidaRepository = commited.get_VidaRepository(); + List items9 = itens; + Func u003cu003e9_257 = ItemServico.u003cu003ec.u003cu003e9__25_7; + if (u003cu003e9_257 == null) + { + u003cu003e9_257 = (Item x) => x.get_Id(); + ItemServico.u003cu003ec.u003cu003e9__25_7 = u003cu003e9_257; + } + vidaRepository.DeleteRange(items9.Select(u003cu003e9_257).ToList()); + tipoTela = 3; + goto Label2; + }); + } + } + + public async Task DeleteTitulares(List titularesVidas) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + ITitularesVidaRepository titularesVidaRepository = commited.get_TitularesVidaRepository(); + List titularesVidas1 = titularesVidas; + Func u003cu003e9_331 = ItemServico.u003cu003ec.u003cu003e9__33_1; + if (u003cu003e9_331 == null) + { + u003cu003e9_331 = (TitularesVida x) => x.get_Id(); + ItemServico.u003cu003ec.u003cu003e9__33_1 = u003cu003e9_331; + } + titularesVidaRepository.DeleteRange(titularesVidas1.Select(u003cu003e9_331).ToList()); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 276, num, titularesVidas, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + private async Task FipeAuthentication() + { + string str; + string empty; + using (HttpClient httpClient = new HttpClient()) + { + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + string str1 = DateTime.Now.ToString("yyyy-MM-dd"); + string base64String = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}|{1}|{2}", ApplicationHelper.IdFornecedor, "bbbf4f03-01fc-4300-b430-33e007753578", str1))); + Uri apiFipe = Address.get_ApiFipe(); + string[] strArrays = new string[] { "api" }; + Uri uri = apiFipe.Append(strArrays); + string[] strArrays1 = new string[] { "auth" }; + Uri uri1 = uri.Append(strArrays1); + HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(uri1, base64String.ToHttpContent(null, "application/json")); + if (httpResponseMessage.get_IsSuccessStatusCode()) + { + JToken item = httpResponseMessage.get_Content().ToJObject().get_Item("token"); + if (item != null) + { + empty = item.ToString(); + } + else + { + empty = null; + } + } + else + { + empty = string.Empty; + } + str = empty; + } + return str; + } + + private async Task FipeCode(string code) + { + Fipe fipe; + Fipe fipe1; + using (HttpClient httpClient = new HttpClient()) + { + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + string str = await this.FipeAuthentication(); + if (Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(str)) + { + httpClient.get_DefaultRequestHeaders().TryAddWithoutValidation("Authorization", string.Concat("Bearer ", str)); + } + Uri apiFipe = Address.get_ApiFipe(); + string[] strArrays = new string[] { "v1" }; + Uri uri = apiFipe.Append(strArrays); + string[] strArrays1 = new string[] { "fipe" }; + Uri uri1 = uri.Append(strArrays1).AddQuery("fipeCode", code); + HttpResponseMessage async = await httpClient.GetAsync(uri1); + fipe1 = (!async.get_IsSuccessStatusCode() ? new Fipe() : JsonConvert.DeserializeObject(await async.get_Content().ReadAsStringAsync())); + fipe = fipe1; + } + return fipe; + } + + private async Task> FipeModel(string model) + { + List fipes; + List fipes1; + using (HttpClient httpClient = new HttpClient()) + { + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + string str = await this.FipeAuthentication(); + if (Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(str)) + { + httpClient.get_DefaultRequestHeaders().TryAddWithoutValidation("Authorization", string.Concat("Bearer ", str)); + } + Uri apiFipe = Address.get_ApiFipe(); + string[] strArrays = new string[] { "v1" }; + Uri uri = apiFipe.Append(strArrays); + string[] strArrays1 = new string[] { "fipe" }; + Uri uri1 = uri.Append(strArrays1); + string[] strArrays2 = new string[] { "modelo" }; + Uri uri2 = uri1.Append(strArrays2); + string[] strArrays3 = new string[] { model }; + Uri uri3 = uri2.Append(strArrays3); + HttpResponseMessage async = await httpClient.GetAsync(uri3); + fipes1 = (!async.get_IsSuccessStatusCode() ? new List() : JsonConvert.DeserializeObject>(await async.get_Content().ReadAsStringAsync())); + fipes = fipes1; + } + return fipes; + } + + private static async Task Get(string command) + where T : class + { + Uri uri = new Uri(command); + ConfiguredTaskAwaitable configuredTaskAwaitable = (new HttpClient()).GetAsync(uri).ConfigureAwait(false); + HttpResponseMessage httpResponseMessage = await configuredTaskAwaitable; + if (httpResponseMessage.get_StatusCode() != HttpStatusCode.OK) + { + throw new Exception(string.Concat("Api connection Error ", Environment.NewLine, " ", command), null); + } + T t = JsonConvert.DeserializeObject(httpResponseMessage.get_Content().ReadAsStringAsync().Result); + return t; + } + + public async Task Reativar(Item item, string descricao) + { + Item item1 = await Task.Run(() => { + Item item2; + string str; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + item = commited.get_ItemRepository().FindById(item.get_Id()); + item.set_Cancelado(false); + long? nullable = null; + item.set_Substituido(nullable); + nullable = null; + item.set_IdDocumentoCancelado(nullable); + item.set_Status(descricao); + item = commited.get_ItemRepository().Merge(item); + DateTime networkTime = Funcoes.GetNetworkTime(); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(1); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + RegistroLog registroLog1 = registroLog; + string[] strArrays = new string[] { string.Format("O USUÁRIO {0} REATIVOU, EM {1}, O ITEM DE", Recursos.Usuario.get_Nome(), networkTime), string.Format("ID: '{0}'", item.get_Id()), ", DESCRIÇÃO: '", null, null, null, null, null, null, null, null }; + strArrays[3] = (string.IsNullOrWhiteSpace(item.get_Descricao()) ? "" : item.get_Descricao() ?? ""); + strArrays[4] = "', OBSERVAÇÃO: '"; + strArrays[5] = (string.IsNullOrWhiteSpace(item.get_Observacao()) ? "" : item.get_Observacao() ?? ""); + strArrays[6] = "', STATUS: '"; + strArrays[7] = (string.IsNullOrWhiteSpace(item.get_Status()) ? "" : item.get_Status() ?? ""); + strArrays[8] = "' - "; + strArrays[9] = descricao; + strArrays[10] = "."; + registroLog1.set_Descricao(string.Concat(strArrays)); + registroLog.set_EntidadeId(item.get_Id()); + registroLog.set_Tela(3); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + RegistroLog registroLog2 = registroLog; + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_211 = ItemServico.u003cu003ec.u003cu003e9__21_1; + if (u003cu003e9_211 == null) + { + u003cu003e9_211 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + ItemServico.u003cu003ec.u003cu003e9__21_1 = u003cu003e9_211; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_211); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog2.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + item2 = item; + } + } + catch (Exception exception) + { + item2 = null; + } + return item2; + }); + return item1; + } + + public async Task Save(Item item) + { + Action action3 = null; + Action action4 = null; + int num3 = 3; + Item item2 = item; + base.Sucesso = true; + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + DateTime networkTime = Funcoes.GetNetworkTime(); + Item item3 = await Task.Run(() => { + bool id; + Auto auto; + Vida vida; + RiscosDiversos riscosDiversos; + Action action; + Item item4; + string str1; + TipoTela tipoTela; + Label5: + while (num3 > 0) + { + item = item2; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + id = item.get_Id() == (long)0; + auto = item.get_Auto(); + Patrimonial patrimonial = item.get_Patrimonial(); + Granizo granizo = item.get_Granizo(); + Aeronautico aeronautico = item.get_Aeronautico(); + vida = item.get_Vida(); + riscosDiversos = item.get_RiscosDiversos(); + Consorcio consorcio = item.get_Consorcio(); + tipoTela = 3; + IList coberturas = item.get_Coberturas(); + item.set_StatusInclusao((item.get_Documento().get_Tipo() == 0 ? "ITEM DA APÓLICE" : "ITEM DO ENDOSSO")); + if (id) + { + item.set_Coberturas(null); + } + if (!id && coberturas != null && coberturas.Count > 0) + { + try + { + List list = coberturas.ToList(); + Action u003cu003e9_2 = action3; + if (u003cu003e9_2 == null) + { + Action action1 = (Cobertura x) => x.set_Item(item); + action = action1; + action3 = action1; + u003cu003e9_2 = action; + } + list.ForEach(u003cu003e9_2); + IList coberturas1 = coberturas; + Func u003cu003e9_233 = ItemServico.u003cu003ec.u003cu003e9__23_3; + if (u003cu003e9_233 == null) + { + u003cu003e9_233 = (Cobertura c) => c.get_Id() == (long)0; + ItemServico.u003cu003ec.u003cu003e9__23_3 = u003cu003e9_233; + } + List list1 = coberturas1.Where(u003cu003e9_233).ToList(); + if (list1.Count > 0) + { + list1 = commited.get_CoberturaRepository().AddRange(list1.ToList()); + list1.ForEach((Cobertura c) => { + string str; + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(0); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(c, jsonSerializerSetting)); + registroLog.set_EntidadeId(c.get_Id()); + registroLog.set_Tela(tipoTela); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_237 = ItemServico.u003cu003ec.u003cu003e9__23_7; + if (u003cu003e9_237 == null) + { + u003cu003e9_237 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + ItemServico.u003cu003ec.u003cu003e9__23_7 = u003cu003e9_237; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_237); + str = (pAddress != null ? pAddress.ToString() : null); + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + }); + } + IList coberturas2 = coberturas; + Func u003cu003e9_235 = ItemServico.u003cu003ec.u003cu003e9__23_5; + if (u003cu003e9_235 == null) + { + u003cu003e9_235 = (Cobertura c) => c.get_Id() > (long)0; + ItemServico.u003cu003ec.u003cu003e9__23_5 = u003cu003e9_235; + } + List list2 = coberturas2.Where(u003cu003e9_235).ToList(); + if (list2.Count > 0) + { + list2 = commited.get_CoberturaRepository().MergeRange(list2); + list2.ForEach((Cobertura c) => { + string str; + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(1); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(c, jsonSerializerSetting)); + registroLog.set_EntidadeId(c.get_Id()); + registroLog.set_Tela(tipoTela); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_238 = ItemServico.u003cu003ec.u003cu003e9__23_8; + if (u003cu003e9_238 == null) + { + u003cu003e9_238 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + ItemServico.u003cu003ec.u003cu003e9__23_8 = u003cu003e9_238; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_238); + str = (pAddress != null ? pAddress.ToString() : null); + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + }); + } + list2.AddRange(list1); + item.set_Coberturas(list2); + } + catch (Exception exception) + { + num3 = base.Registrar(exception, 208, num3, coberturas, true); + continue; + } + } + if (!item.get_Documento().get_Sinistro() && item.get_Sinistrado() && item.get_Documento().get_Situacao() == 2 && item.get_Status() != null && !item.get_Status().Contains("ALTERADO")) + { + item.set_Sinistrado(false); + } + item = (id ? commited.get_ItemRepository().SaveOrUpdate(item) : commited.get_ItemRepository().Merge(item)); + long num = item.get_Documento().get_Controle().get_Ramo().get_Id(); + if (num > (long)38) + { + if (num == (long)47 || num == (long)53 || num == (long)66) + { + goto Label0; + } + goto Label1; + } + else + { + long num1 = num - (long)1; + if (num1 <= (long)19) + { + switch ((uint)num1) + { + case 0: + case 1: + case 2: + case 14: + case 17: + { + goto Label3; + } + case 3: + case 7: + case 10: + case 11: + case 13: + case 15: + case 16: + case 18: + { + goto Label1; + } + case 4: + { + goto Label4; + } + case 5: + case 6: + case 8: + case 9: + { + goto Label0; + } + case 12: + { + try + { + if (aeronautico != null) + { + aeronautico.set_Item(item); + aeronautico = (id ? commited.get_AeronauticoRepository().SaveOrUpdate(aeronautico) : commited.get_AeronauticoRepository().Merge(aeronautico)); + item.set_Aeronautico(aeronautico); + tipoTela = 3; + goto Label2; + } + else + { + goto Label2; + } + } + catch (Exception exception1) + { + num3 = base.Registrar(exception1, 202, num3, aeronautico, true); + continue; + } + break; + } + case 19: + { + try + { + if (granizo != null) + { + granizo.set_Item(item); + granizo = (id ? commited.get_GranizoRepository().SaveOrUpdate(granizo) : commited.get_GranizoRepository().Merge(granizo)); + item.set_Granizo(granizo); + tipoTela = 3; + goto Label2; + } + else + { + goto Label2; + } + } + catch (Exception exception2) + { + num3 = base.Registrar(exception2, 206, num3, granizo, true); + continue; + } + break; + } + } + } + else + { + } + if (num != (long)30) + { + long num2 = num - (long)36; + if (num2 <= (long)2) + { + switch ((uint)num2) + { + case 0: + { + try + { + if (consorcio != null) + { + consorcio.set_Item(item); + consorcio = (id ? commited.get_ConsorcioRepository().SaveOrUpdate(consorcio) : commited.get_ConsorcioRepository().Merge(consorcio)); + item.set_Consorcio(consorcio); + tipoTela = 3; + goto Label2; + } + else + { + goto Label2; + } + } + catch (Exception exception3) + { + num3 = base.Registrar(exception3, 331, num3, consorcio, true); + continue; + } + break; + } + case 1: + { + goto Label4; + } + case 2: + { + break; + } + default: + { + goto Label1; + } + } + } + else + { + goto Label1; + } + } + Label3: + try + { + if (patrimonial != null) + { + patrimonial.set_Item(item); + patrimonial = (id ? commited.get_PatrimonialRepository().SaveOrUpdate(patrimonial) : commited.get_PatrimonialRepository().Merge(patrimonial)); + item.set_Patrimonial(patrimonial); + tipoTela = 3; + } + } + catch (Exception exception4) + { + num3 = base.Registrar(exception4, 196, num3, patrimonial, true); + continue; + } + } + Label2: + if (id && coberturas != null && coberturas.Count > 0) + { + try + { + item.set_Coberturas(new List()); + List list3 = coberturas.ToList(); + Action u003cu003e9_1 = action4; + if (u003cu003e9_1 == null) + { + Action action2 = (Cobertura x) => { + x.set_Id((long)0); + x.set_Item(item); + }; + action = action2; + action4 = action2; + u003cu003e9_1 = action; + } + list3.ForEach(u003cu003e9_1); + coberturas = commited.get_CoberturaRepository().AddRange(coberturas.ToList()); + item.set_Coberturas(coberturas); + } + catch (Exception exception5) + { + num3 = base.Registrar(exception5, 208, num3, coberturas, true); + continue; + } + } + TipoAcao tipoAcao = (id ? 0 : 1); + RegistroLog registroLog1 = new RegistroLog(); + registroLog1.set_Acao(tipoAcao); + registroLog1.set_Usuario(Recursos.Usuario); + registroLog1.set_DataHora(networkTime); + Item item1 = item; + JsonSerializerSettings jsonSerializerSetting1 = new JsonSerializerSettings(); + jsonSerializerSetting1.set_ReferenceLoopHandling(1); + registroLog1.set_Descricao(JsonConvert.SerializeObject(item1, jsonSerializerSetting1)); + registroLog1.set_EntidadeId(item.get_Id()); + registroLog1.set_Tela(tipoTela); + registroLog1.set_Versao(LoginViewModel.VersaoAtual); + registroLog1.set_NomeMaquina(Environment.MachineName); + registroLog1.set_UsuarioMaquina(Environment.UserName); + IPAddress[] pAddressArray = hostEntry.AddressList; + Func u003cu003e9_239 = ItemServico.u003cu003ec.u003cu003e9__23_9; + if (u003cu003e9_239 == null) + { + u003cu003e9_239 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + ItemServico.u003cu003ec.u003cu003e9__23_9 = u003cu003e9_239; + } + IPAddress pAddress1 = ((IEnumerable)pAddressArray).FirstOrDefault(u003cu003e9_239); + if (pAddress1 != null) + { + str1 = pAddress1.ToString(); + } + else + { + str1 = null; + } + registroLog1.set_Ip(str1); + base.SaveLog(registroLog1, commited); + commited.Commit(); + item4 = item; + } + } + catch (Exception exception6) + { + num3 = base.Registrar(exception6, 195, num3, item, true); + continue; + } + return item4; + } + return item2; + Label0: + try + { + if (vida != null) + { + vida.set_Item(item); + vida = (id ? commited.get_VidaRepository().SaveOrUpdate(vida) : commited.get_VidaRepository().Merge(vida)); + item.set_Vida(vida); + tipoTela = 3; + goto Label2; + } + else + { + goto Label2; + } + } + catch (Exception exception7) + { + num3 = base.Registrar(exception7, 200, num3, vida, true); + goto Label5; + } + Label1: + try + { + if (riscosDiversos != null) + { + riscosDiversos.set_Item(item); + riscosDiversos = (id ? commited.get_RiscosDiversosRepository().SaveOrUpdate(riscosDiversos) : commited.get_RiscosDiversosRepository().Merge(riscosDiversos)); + item.set_RiscosDiversos(riscosDiversos); + tipoTela = 3; + goto Label2; + } + else + { + goto Label2; + } + } + catch (Exception exception8) + { + num3 = base.Registrar(exception8, 198, num3, riscosDiversos, true); + goto Label5; + } + Label4: + try + { + if (auto != null) + { + auto.set_Item(item); + auto = (id ? commited.get_AutoRepository().SaveOrUpdate(auto) : commited.get_AutoRepository().Merge(auto)); + item.set_Auto(auto); + tipoTela = 3; + goto Label2; + } + else + { + goto Label2; + } + } + catch (Exception exception9) + { + num3 = base.Registrar(exception9, 204, num3, auto, true); + goto Label5; + } + }); + return item3; + } + + public async Task SaveRange(List itens) + { + int num = 3; + DateTime networkTime = Funcoes.GetNetworkTime(); + await Task.Run(() => { + string str; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + itens.ForEach((Item x) => commited.get_ItemRepository().Merge(x)); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + foreach (Item iten in itens) + { + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(2); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(iten, jsonSerializerSetting)); + registroLog.set_EntidadeId(iten.get_Id()); + registroLog.set_Tela(3); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_272 = ItemServico.u003cu003ec.u003cu003e9__27_2; + if (u003cu003e9_272 == null) + { + u003cu003e9_272 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + ItemServico.u003cu003ec.u003cu003e9__27_2 = u003cu003e9_272; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_272); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + } + commited.Commit(); + this.Sucesso = true; + break; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 276, num, itens, true); + } + } + }); + } + + public async Task> SaveTitulares(List titularesVidas) + { + int num = 3; + List titularesVidas5 = await Task.Run>(() => { + List titularesVidas6; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + List titularesVidas1 = titularesVidas; + Action u003cu003e9_321 = ItemServico.u003cu003ec.u003cu003e9__32_1; + if (u003cu003e9_321 == null) + { + u003cu003e9_321 = (TitularesVida x) => { + if (x.get_Tipo().GetValueOrDefault() != 2 && x.get_Dependente() != null) + { + x.set_Dependente(null); + } + }; + ItemServico.u003cu003ec.u003cu003e9__32_1 = u003cu003e9_321; + } + titularesVidas1.ForEach(u003cu003e9_321); + List titularesVidas2 = titularesVidas; + Func u003cu003e9_322 = ItemServico.u003cu003ec.u003cu003e9__32_2; + if (u003cu003e9_322 == null) + { + u003cu003e9_322 = (TitularesVida x) => { + if (x.get_Id() != 0) + { + return false; + } + return x.get_Tipo().GetValueOrDefault() != 2; + }; + ItemServico.u003cu003ec.u003cu003e9__32_2 = u003cu003e9_322; + } + titularesVidas2.Where(u003cu003e9_322).ToList().ForEach((TitularesVida x) => titularesVidas.First((TitularesVida y) => (object)y == (object)x).set_Id(commited.get_TitularesVidaRepository().SaveOrUpdate(x).get_Id())); + List titularesVidas3 = titularesVidas; + Func u003cu003e9_324 = ItemServico.u003cu003ec.u003cu003e9__32_4; + if (u003cu003e9_324 == null) + { + u003cu003e9_324 = (TitularesVida x) => { + if (x.get_Id() != 0) + { + return false; + } + return x.get_Tipo().GetValueOrDefault() == 2; + }; + ItemServico.u003cu003ec.u003cu003e9__32_4 = u003cu003e9_324; + } + titularesVidas3.Where(u003cu003e9_324).ToList().ForEach((TitularesVida x) => titularesVidas.First((TitularesVida y) => (object)y == (object)x).set_Id(commited.get_TitularesVidaRepository().SaveOrUpdate(x).get_Id())); + List titularesVidas4 = titularesVidas; + Func u003cu003e9_326 = ItemServico.u003cu003ec.u003cu003e9__32_6; + if (u003cu003e9_326 == null) + { + u003cu003e9_326 = (TitularesVida x) => x.get_Id() > (long)0; + ItemServico.u003cu003ec.u003cu003e9__32_6 = u003cu003e9_326; + } + titularesVidas4.Where(u003cu003e9_326).ToList().ForEach((TitularesVida x) => commited.get_TitularesVidaRepository().Merge(x)); + commited.Commit(); + this.Sucesso = true; + titularesVidas6 = titularesVidas; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 276, num, titularesVidas, true); + continue; + } + return titularesVidas6; + } + return new List(); + }); + return titularesVidas5; + } + + public async Task Substituir(Item item, long substituido, string descricao) + { + Item item1 = await Task.Run(() => { + Item item2; + string str; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + item = commited.get_ItemRepository().FindById(item.get_Id()); + item.set_Substituido(new long?(substituido)); + item.set_Status(descricao); + item = commited.get_ItemRepository().Merge(item); + DateTime networkTime = Funcoes.GetNetworkTime(); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(1); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + RegistroLog registroLog1 = registroLog; + string[] strArrays = new string[] { string.Format("O USUÁRIO {0} SUBSTITUIU, EM {1}, O ITEM DE", Recursos.Usuario.get_Nome(), networkTime), string.Format("ID: '{0}'", item.get_Id()), ", DESCRIÇÃO: '", null, null, null, null, null, null, null, null }; + strArrays[3] = (string.IsNullOrWhiteSpace(item.get_Descricao()) ? "" : item.get_Descricao() ?? ""); + strArrays[4] = "', OBSERVAÇÃO: '"; + strArrays[5] = (string.IsNullOrWhiteSpace(item.get_Observacao()) ? "" : item.get_Observacao() ?? ""); + strArrays[6] = "', STATUS: '"; + strArrays[7] = (string.IsNullOrWhiteSpace(item.get_Status()) ? "" : item.get_Status() ?? ""); + strArrays[8] = "' - "; + strArrays[9] = descricao; + strArrays[10] = "."; + registroLog1.set_Descricao(string.Concat(strArrays)); + registroLog.set_EntidadeId(item.get_Id()); + registroLog.set_Tela(3); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + RegistroLog registroLog2 = registroLog; + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_221 = ItemServico.u003cu003ec.u003cu003e9__22_1; + if (u003cu003e9_221 == null) + { + u003cu003e9_221 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + ItemServico.u003cu003ec.u003cu003e9__22_1 = u003cu003e9_221; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_221); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog2.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + item2 = item; + } + } + catch (Exception exception) + { + item2 = null; + } + return item2; + }); + return item1; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Seguros/Itens/PatrimonialServico.cs b/Codemerx/Gestor.Application/Servicos/Seguros/Itens/PatrimonialServico.cs new file mode 100644 index 0000000..2bd46f5 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Seguros/Itens/PatrimonialServico.cs @@ -0,0 +1,196 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Seguros.Itens +{ + internal class PatrimonialServico : BaseServico + { + public PatrimonialServico() + { + } + + public async Task> BuscarImobiliaria(string imobiliaria, FiltroStatusDocumento status, List vendedorVinculado) + { + List pesquisaAvancadas1 = await Task.Run>(() => { + List pesquisaAvancadas; + try + { + using (UnitOfWork read = Instancia.Read) + { + pesquisaAvancadas = read.get_PatrimonialRepository().FindImobiliaria(imobiliaria, status, vendedorVinculado); + } + } + catch (Exception exception) + { + pesquisaAvancadas = null; + } + return pesquisaAvancadas; + }); + return pesquisaAvancadas1; + } + + public async Task> BuscarLocatario(string locatario, FiltroStatusDocumento status, List vendedorVinculado) + { + List pesquisaAvancadas1 = await Task.Run>(() => { + List pesquisaAvancadas; + try + { + using (UnitOfWork read = Instancia.Read) + { + pesquisaAvancadas = read.get_PatrimonialRepository().Findlocatario(locatario, status, vendedorVinculado); + } + } + catch (Exception exception) + { + pesquisaAvancadas = null; + } + return pesquisaAvancadas; + }); + return pesquisaAvancadas1; + } + + public async Task Delete(Item item) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + long id; + string str; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + if (item.get_Patrimonial() != null && item.get_Patrimonial().get_Id() > (long)0) + { + commited.get_PatrimonialRepository().Delete(item.get_Patrimonial().get_Id()); + } + commited.get_CoberturaRepository().DeletebyItem(item.get_Id()); + commited.get_ControleSinistroRepository().DeleteByItem(item.get_Id()); + commited.get_ItemRepository().Delete(item.get_Id()); + DateTime networkTime = Funcoes.GetNetworkTime(); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(2); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + Item item1 = item; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(item1, jsonSerializerSetting)); + Patrimonial patrimonial = item.get_Patrimonial(); + id = (patrimonial != null ? patrimonial.get_Id() : (long)0); + registroLog.set_EntidadeId(id); + registroLog.set_Tela(3); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_11 = PatrimonialServico.u003cu003ec.u003cu003e9__1_1; + if (u003cu003e9_11 == null) + { + u003cu003e9_11 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + PatrimonialServico.u003cu003ec.u003cu003e9__1_1 = u003cu003e9_11; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_11); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 197, num, null, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task Save(Patrimonial patrimonial) + { + Patrimonial patrimonial2 = await Task.Run(() => { + Patrimonial patrimonial3; + string str; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + TipoAcao tipoAcao = (patrimonial.get_Id() == 0 ? 0 : 1); + patrimonial = (patrimonial.get_Id() == 0 ? commited.get_PatrimonialRepository().SaveOrUpdate(patrimonial) : commited.get_PatrimonialRepository().Merge(patrimonial)); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(tipoAcao); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(Funcoes.GetNetworkTime()); + Patrimonial patrimonial1 = patrimonial; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(patrimonial1, jsonSerializerSetting)); + registroLog.set_EntidadeId(patrimonial.get_Id()); + registroLog.set_Tela(3); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_01 = PatrimonialServico.u003cu003ec.u003cu003e9__0_1; + if (u003cu003e9_01 == null) + { + u003cu003e9_01 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + PatrimonialServico.u003cu003ec.u003cu003e9__0_1 = u003cu003e9_01; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_01); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + patrimonial3 = patrimonial; + } + } + catch (Exception exception) + { + patrimonial3 = null; + } + return patrimonial3; + }); + return patrimonial2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Seguros/Itens/RiscosDiversosServico.cs b/Codemerx/Gestor.Application/Servicos/Seguros/Itens/RiscosDiversosServico.cs new file mode 100644 index 0000000..77873c3 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Seguros/Itens/RiscosDiversosServico.cs @@ -0,0 +1,156 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Seguros.Itens +{ + internal class RiscosDiversosServico : BaseServico + { + public RiscosDiversosServico() + { + } + + public async Task Delete(Item item) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + long id; + string str; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + if (item.get_RiscosDiversos() != null && item.get_RiscosDiversos().get_Id() > (long)0) + { + commited.get_RiscosDiversosRepository().Delete(item.get_RiscosDiversos().get_Id()); + } + commited.get_CoberturaRepository().DeletebyItem(item.get_Id()); + commited.get_ControleSinistroRepository().DeleteByItem(item.get_Id()); + commited.get_ItemRepository().Delete(item.get_Id()); + DateTime networkTime = Funcoes.GetNetworkTime(); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(2); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + Item item1 = item; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(item1, jsonSerializerSetting)); + RiscosDiversos riscosDiversos = item.get_RiscosDiversos(); + id = (riscosDiversos != null ? riscosDiversos.get_Id() : (long)0); + registroLog.set_EntidadeId(id); + registroLog.set_Tela(3); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_11 = RiscosDiversosServico.u003cu003ec.u003cu003e9__1_1; + if (u003cu003e9_11 == null) + { + u003cu003e9_11 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + RiscosDiversosServico.u003cu003ec.u003cu003e9__1_1 = u003cu003e9_11; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_11); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 199, num, null, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task Save(RiscosDiversos riscosdiversos) + { + RiscosDiversos riscosDiverso2 = await Task.Run(() => { + RiscosDiversos riscosDiverso; + string str; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + TipoAcao tipoAcao = (riscosdiversos.get_Id() == 0 ? 0 : 1); + riscosdiversos = (riscosdiversos.get_Id() == 0 ? commited.get_RiscosDiversosRepository().SaveOrUpdate(riscosdiversos) : commited.get_RiscosDiversosRepository().Merge(riscosdiversos)); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(tipoAcao); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(Funcoes.GetNetworkTime()); + RiscosDiversos riscosDiverso1 = riscosdiversos; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(riscosDiverso1, jsonSerializerSetting)); + registroLog.set_EntidadeId(riscosdiversos.get_Id()); + registroLog.set_Tela(3); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_01 = RiscosDiversosServico.u003cu003ec.u003cu003e9__0_1; + if (u003cu003e9_01 == null) + { + u003cu003e9_01 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + RiscosDiversosServico.u003cu003ec.u003cu003e9__0_1 = u003cu003e9_01; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_01); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + riscosDiverso = riscosdiversos; + } + } + catch (Exception exception) + { + riscosDiverso = null; + } + return riscosDiverso; + }); + return riscosDiverso2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Seguros/Itens/VidaServico.cs b/Codemerx/Gestor.Application/Servicos/Seguros/Itens/VidaServico.cs new file mode 100644 index 0000000..3e03bfb --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Seguros/Itens/VidaServico.cs @@ -0,0 +1,156 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Seguros.Itens +{ + internal class VidaServico : BaseServico + { + public VidaServico() + { + } + + public async Task Delete(Item item) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + long id; + string str; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + if (item.get_Vida() != null && item.get_Vida().get_Id() > (long)0) + { + commited.get_VidaRepository().Delete(item.get_Vida().get_Id()); + } + commited.get_CoberturaRepository().DeletebyItem(item.get_Id()); + commited.get_ControleSinistroRepository().DeleteByItem(item.get_Id()); + commited.get_ItemRepository().Delete(item.get_Id()); + DateTime networkTime = Funcoes.GetNetworkTime(); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(2); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + Item item1 = item; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(item1, jsonSerializerSetting)); + Vida vida = item.get_Vida(); + id = (vida != null ? vida.get_Id() : (long)0); + registroLog.set_EntidadeId(id); + registroLog.set_Tela(3); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_11 = VidaServico.u003cu003ec.u003cu003e9__1_1; + if (u003cu003e9_11 == null) + { + u003cu003e9_11 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + VidaServico.u003cu003ec.u003cu003e9__1_1 = u003cu003e9_11; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_11); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 201, num, null, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task Save(Vida vida) + { + Vida vida2 = await Task.Run(() => { + Vida vida3; + string str; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + TipoAcao tipoAcao = (vida.get_Id() == 0 ? 0 : 1); + vida = (vida.get_Id() == 0 ? commited.get_VidaRepository().SaveOrUpdate(vida) : commited.get_VidaRepository().Merge(vida)); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(tipoAcao); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(Funcoes.GetNetworkTime()); + Vida vida1 = vida; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(vida1, jsonSerializerSetting)); + registroLog.set_EntidadeId(vida.get_Id()); + registroLog.set_Tela(3); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_01 = VidaServico.u003cu003ec.u003cu003e9__0_1; + if (u003cu003e9_01 == null) + { + u003cu003e9_01 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + VidaServico.u003cu003ec.u003cu003e9__0_1 = u003cu003e9_01; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_01); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + vida3 = vida; + } + } + catch (Exception exception) + { + vida3 = null; + } + return vida3; + }); + return vida2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Seguros/PerfilEmpresaServico.cs b/Codemerx/Gestor.Application/Servicos/Seguros/PerfilEmpresaServico.cs new file mode 100644 index 0000000..21aa774 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Seguros/PerfilEmpresaServico.cs @@ -0,0 +1,179 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Seguros +{ + internal class PerfilEmpresaServico : BaseServico + { + public PerfilEmpresaServico() + { + } + + internal async Task BuscarPerfis(long controleId) + { + int num = 3; + PerfilEmpresa perfilEmpresa1 = await Task.Run(() => { + PerfilEmpresa perfilEmpresa; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + perfilEmpresa = read.get_PerfilEmpresaRepository().FindByControleId(controleId); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 46, num, controleId, true); + continue; + } + return perfilEmpresa; + } + return new PerfilEmpresa(); + }); + return perfilEmpresa1; + } + + public async Task Delete(PerfilEmpresa perfil) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + string str; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + commited.get_PerfilEmpresaRepository().Delete(perfil.get_Id()); + DateTime networkTime = Funcoes.GetNetworkTime(); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(2); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + registroLog.set_Descricao(string.Concat(string.Format("O USUÁRIO {0} EXCLUIU O PERFIL, EM {1}, DE ", Recursos.Usuario.get_Nome(), networkTime), string.Format("ID: '{0}'", perfil.get_Id()))); + registroLog.set_EntidadeId(perfil.get_Id()); + registroLog.set_Tela(3); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_21 = PerfilEmpresaServico.u003cu003ec.u003cu003e9__2_1; + if (u003cu003e9_21 == null) + { + u003cu003e9_21 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + PerfilEmpresaServico.u003cu003ec.u003cu003e9__2_1 = u003cu003e9_21; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_21); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 213, num, perfil, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task Save(PerfilEmpresa perfil) + { + int num = 3; + base.Sucesso = true; + PerfilEmpresa perfilEmpresa2 = perfil; + PerfilEmpresa perfilEmpresa3 = await Task.Run(() => { + PerfilEmpresa perfilEmpresa; + string str; + while (num > 0) + { + perfil = perfilEmpresa2; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + TipoAcao tipoAcao = (perfil.get_Id() == 0 ? 0 : 1); + perfil = (perfil.get_Id() == 0 ? commited.get_PerfilEmpresaRepository().SaveOrUpdate(perfil) : commited.get_PerfilEmpresaRepository().Merge(perfil)); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(tipoAcao); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(Funcoes.GetNetworkTime()); + PerfilEmpresa perfilEmpresa1 = perfil; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(perfilEmpresa1, jsonSerializerSetting)); + registroLog.set_EntidadeId(perfil.get_Id()); + registroLog.set_Tela(32); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_11 = PerfilEmpresaServico.u003cu003ec.u003cu003e9__1_1; + if (u003cu003e9_11 == null) + { + u003cu003e9_11 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + PerfilEmpresaServico.u003cu003ec.u003cu003e9__1_1 = u003cu003e9_11; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_11); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + perfilEmpresa = perfil; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 212, num, perfil, true); + continue; + } + return perfilEmpresa; + } + return perfilEmpresa2; + }); + return perfilEmpresa3; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Seguros/PerfilServico.cs b/Codemerx/Gestor.Application/Servicos/Seguros/PerfilServico.cs new file mode 100644 index 0000000..293af5c --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Seguros/PerfilServico.cs @@ -0,0 +1,241 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels; +using Gestor.Common.Validation; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Seguros +{ + internal class PerfilServico : BaseServico + { + public PerfilServico() + { + } + + internal async Task> BuscarPerfis(long controleId) + { + int num = 3; + List perfils1 = await Task.Run>(() => { + List perfils; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + perfils = read.get_PerfilRepository().FindByControleId(controleId); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 46, num, controleId, true); + continue; + } + return perfils; + } + return new List(); + }); + return perfils1; + } + + public async Task Delete(Perfil perfil) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + object obj; + string str; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + commited.get_PerfilRepository().Delete(perfil.get_Id()); + DateTime networkTime = Funcoes.GetNetworkTime(); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(2); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + RegistroLog registroLog1 = registroLog; + string[] description = new string[47]; + description[0] = string.Format("O USUÁRIO {0} EXCLUIU O PERFIL, EM {1}, DE ", Recursos.Usuario.get_Nome(), networkTime); + description[1] = string.Format("ID: '{0}'", perfil.get_Id()); + description[2] = ", NOME: '"; + description[3] = (string.IsNullOrWhiteSpace(perfil.get_Nome()) ? "" : perfil.get_Nome() ?? ""); + description[4] = "', CPF: '"; + description[5] = (string.IsNullOrWhiteSpace(perfil.get_Cpf()) ? "" : perfil.get_Cpf() ?? ""); + description[6] = "', HABILITAÇÃO: '"; + description[7] = (string.IsNullOrWhiteSpace(perfil.get_Habilitacao()) ? "" : perfil.get_Habilitacao() ?? ""); + description[8] = "', TEMPO DE HABILITAÇÃO: '"; + description[9] = Gestor.Common.Validation.ValidationHelper.GetDescription(perfil.get_TempoHabilitacao()); + description[10] = "', NASCIMENTO: '"; + DateTime? nascimento = perfil.get_Nascimento(); + if (!nascimento.HasValue) + { + obj = ""; + } + else + { + nascimento = perfil.get_Nascimento(); + obj = (nascimento.HasValue ? nascimento.GetValueOrDefault().ToShortDateString() : null) ?? ""; + } + description[11] = (string)obj; + description[12] = "', SEXO: '"; + description[13] = Gestor.Common.Validation.ValidationHelper.GetDescription(perfil.get_Sexo()); + description[14] = "', ESTADO CIVIL: '"; + description[15] = Gestor.Common.Validation.ValidationHelper.GetDescription(perfil.get_EstadoCivil()); + description[16] = "', OCUPAÇÃO: '"; + description[17] = Gestor.Common.Validation.ValidationHelper.GetDescription(perfil.get_Ocupacao()); + description[18] = "', RELAÇÃOO: '"; + description[19] = Gestor.Common.Validation.ValidationHelper.GetDescription(perfil.get_Relacao()); + description[20] = "', DISTÂNCIA DO TRABALHO: '"; + description[21] = Gestor.Common.Validation.ValidationHelper.GetDescription(perfil.get_DistanciaResidenciaTrabalho()); + description[22] = "', USO POR DEPENDENTES: '"; + description[23] = Gestor.Common.Validation.ValidationHelper.GetDescription(perfil.get_UsoDependentes()); + description[24] = "', TIPO DE RESIDÊNCIA: '"; + description[25] = Gestor.Common.Validation.ValidationHelper.GetDescription(perfil.get_TipoResidencia()); + description[26] = "', GARAGEM NA RESIDÊNCIA: '"; + description[27] = Gestor.Common.Validation.ValidationHelper.GetDescription(perfil.get_GaragemResidencia()); + description[28] = "', GARAGEM NO TRABALHO: '"; + description[29] = Gestor.Common.Validation.ValidationHelper.GetDescription(perfil.get_GaragemTrabalho()); + description[30] = "', GARAGEM NO ESTUDO: '"; + description[31] = Gestor.Common.Validation.ValidationHelper.GetDescription(perfil.get_GaragemEstudo()); + description[32] = "', VEÍCULOS NA RESIDÊNCIA: '"; + description[33] = (!perfil.get_VeiculoResidencia().HasValue ? "" : string.Format("{0}", perfil.get_VeiculoResidencia())); + description[34] = "', ANTFURTO: '"; + description[35] = (!perfil.get_AntiFurto().HasValue ? "" : Gestor.Common.Validation.ValidationHelper.GetDescription(perfil.get_AntiFurto())); + description[36] = "', SEGURO DE VIDA: '"; + description[37] = (!perfil.get_SeguroVida().HasValue ? "" : (perfil.get_SeguroVida().Value ? "SIM" : "NÃO")); + description[38] = "', USO PROFISSIONAL: '"; + description[39] = (!perfil.get_UsoProfissional().HasValue ? "" : (perfil.get_UsoProfissional().Value ? "SIM" : "NÃO")); + description[40] = "', COBERTURA ESTENDIDA: '"; + description[41] = (!perfil.get_EstenderCobertura().HasValue ? "" : (perfil.get_EstenderCobertura().Value ? "SIM" : "NÃO")); + description[42] = "', CEP CIRCULAÇÃO: '"; + description[43] = (string.IsNullOrWhiteSpace(perfil.get_CepCirculacao()) ? "" : perfil.get_CepCirculacao() ?? ""); + description[44] = "', CEP PERNOITE: '"; + description[45] = (string.IsNullOrWhiteSpace(perfil.get_CepPernoite()) ? "" : perfil.get_CepPernoite() ?? ""); + description[46] = "'."; + registroLog1.set_Descricao(string.Concat(description)); + registroLog.set_EntidadeId(perfil.get_Id()); + registroLog.set_Tela(3); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + RegistroLog registroLog2 = registroLog; + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_21 = PerfilServico.u003cu003ec.u003cu003e9__2_1; + if (u003cu003e9_21 == null) + { + u003cu003e9_21 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + PerfilServico.u003cu003ec.u003cu003e9__2_1 = u003cu003e9_21; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_21); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog2.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 213, num, perfil, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task Save(Perfil perfil) + { + int num = 3; + base.Sucesso = true; + Perfil perfil2 = perfil; + Perfil perfil3 = await Task.Run(() => { + Perfil perfil4; + string str; + while (num > 0) + { + perfil = perfil2; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + TipoAcao tipoAcao = (perfil.get_Id() == 0 ? 0 : 1); + perfil = (perfil.get_Id() == 0 ? commited.get_PerfilRepository().SaveOrUpdate(perfil) : commited.get_PerfilRepository().Merge(perfil)); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(tipoAcao); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(Funcoes.GetNetworkTime()); + Perfil perfil1 = perfil; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(perfil1, jsonSerializerSetting)); + registroLog.set_EntidadeId(perfil.get_Id()); + registroLog.set_Tela(32); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_11 = PerfilServico.u003cu003ec.u003cu003e9__1_1; + if (u003cu003e9_11 == null) + { + u003cu003e9_11 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + PerfilServico.u003cu003ec.u003cu003e9__1_1 = u003cu003e9_11; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_11); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + perfil4 = perfil; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 212, num, perfil, true); + continue; + } + return perfil4; + } + return perfil2; + }); + return perfil3; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Seguros/ProfissaoServico.cs b/Codemerx/Gestor.Application/Servicos/Seguros/ProfissaoServico.cs new file mode 100644 index 0000000..f528fcb --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Seguros/ProfissaoServico.cs @@ -0,0 +1,78 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using System; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Seguros +{ + internal class ProfissaoServico : BaseServico + { + public ProfissaoServico() + { + } + + public async Task FindLastId() + { + int num1 = 3; + long num2 = await Task.Run(() => { + long num; + while (num1 > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + num = read.get_ProfissaoRepository().FindLastId(); + } + } + catch (Exception exception) + { + num1 = base.Registrar(exception, 17, num1, null, true); + continue; + } + return num; + } + return (long)0; + }); + return num2; + } + + public async Task Save(Profissao profissao) + { + int num = 3; + base.Sucesso = true; + Profissao profissao1 = profissao; + Profissao profissao2 = await Task.Run(() => { + Profissao profissao3; + while (num > 0) + { + profissao = profissao1; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + profissao = (profissao.get_Id() == (long)0 ? commited.get_ProfissaoRepository().SaveOrUpdate(profissao) : commited.get_ProfissaoRepository().Merge(profissao)); + commited.Commit(); + profissao3 = profissao; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 214, num, profissao, true); + continue; + } + return profissao3; + } + return profissao1; + }); + return profissao2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/Seguros/SinistroServico.cs b/Codemerx/Gestor.Application/Servicos/Seguros/SinistroServico.cs new file mode 100644 index 0000000..19049b1 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/Seguros/SinistroServico.cs @@ -0,0 +1,400 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos.Seguros +{ + internal class SinistroServico : BaseServico + { + public SinistroServico() + { + } + + internal async Task> BuscarControles(long id) + { + int num = 3; + List controleSinistros1 = await Task.Run>(() => { + List controleSinistros; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + controleSinistros = read.get_ControleSinistroRepository().FindByIdItem(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 48, num, id, true); + continue; + } + return controleSinistros; + } + return new List(); + }); + return controleSinistros1; + } + + public async Task BuscarSinistro(long id) + { + int num = 3; + Sinistro sinistro1 = await Task.Run(() => { + Sinistro sinistro; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + sinistro = read.get_SinistroRepository().FindById(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 49, num, id, true); + continue; + } + return sinistro; + } + return new Sinistro(); + }); + return sinistro1; + } + + public async Task> BuscarSinistro(Filtros filtro) + { + int num = 3; + List sinistros1 = await Task.Run>(() => { + List sinistros; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + sinistros = read.get_SinistroRepository().FindByData(filtro, false); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 176, num, filtro, true); + continue; + } + return sinistros; + } + return new List(); + }); + return sinistros1; + } + + public async Task> BuscarSinistroPendente(Filtros filtro) + { + int num = 3; + List sinistros1 = await Task.Run>(() => { + List sinistros; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + sinistros = read.get_SinistroRepository().FindByData(filtro, true); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 176, num, filtro, true); + continue; + } + return sinistros; + } + return new List(); + }); + return sinistros1; + } + + public async Task> BuscarSinistros(string numero) + { + int num = 3; + List sinistros1 = await Task.Run>(() => { + List sinistros; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + sinistros = read.get_SinistroRepository().FindNumeroSinistro(numero); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 177, num, numero, true); + continue; + } + return sinistros; + } + return new List(); + }); + return sinistros1; + } + + public async Task Delete(Sinistro sinistro) + { + int num = 3; + base.Sucesso = true; + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + List registroLogs = new List(); + try + { + using (UnitOfWork commited = Instancia.Commited) + { + registroLogs.Add(base.CreateLog(sinistro.get_Id(), sinistro.GetValorOriginal(), 26, 2)); + SinistroAuto sinistroAuto = commited.get_SinistroAutoRepository().FindBySinistroId(sinistro.get_Id()); + SinistroVida sinistroVida = commited.get_SinistroVidaRepository().FindBySinistroId(sinistro.get_Id()); + if (sinistroAuto != null) + { + commited.get_SinistroAutoRepository().Delete(sinistroAuto.get_Id()); + } + if (sinistroVida != null) + { + commited.get_SinistroVidaRepository().Delete(sinistroVida.get_Id()); + } + commited.get_SinistroRepository().Delete(sinistro.get_Id()); + base.SaveLog(registroLogs, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 174, num, sinistro, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task DeleteControle(ControleSinistro controle, bool atualizarItem) + { + int num = 3; + base.Sucesso = true; + bool flag1 = await Task.Run(async () => { + bool flag; + while (num > 0) + { + List registroLogs = new List(); + try + { + using (UnitOfWork commited = Instancia.Commited) + { + if (atualizarItem) + { + Item item = commited.get_ItemRepository().FindById(controle.get_Item().get_Id()); + item.set_Sinistrado(false); + commited.get_ItemRepository().Merge(item); + } + foreach (Sinistro sinistro in commited.get_SinistroRepository().FindByControleId(controle.get_Id())) + { + registroLogs.Add(base.CreateLog(sinistro.get_Id(), sinistro.GetValorOriginal(), 26, 2)); + if (await this.Delete(sinistro)) + { + continue; + } + flag = false; + return flag; + } + commited.get_ControleSinistroRepository().Delete(controle.get_Id()); + base.SaveLog(registroLogs, commited); + commited.Commit(); + flag = true; + return flag; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 174, num, controle, true); + } + registroLogs = null; + } + flag = false; + return flag; + }); + return flag1; + } + + public async Task Save(Sinistro sinistro, long idramo) + { + int num3 = 3; + base.Sucesso = true; + Sinistro sinistro1 = sinistro; + Funcoes.GetNetworkTime(); + Sinistro sinistro2 = await Task.Run(() => { + SinistroVida sinistroVida; + long num; + Sinistro sinistro3; + while (num3 > 0) + { + List registroLogs = new List(); + try + { + using (UnitOfWork commited = Instancia.Commited) + { + Item item = commited.get_ItemRepository().FindById(sinistro.get_ControleSinistro().get_Item().get_Id()); + item.set_Sinistrado(true); + sinistro1.get_ControleSinistro().set_Item(commited.get_ItemRepository().Merge(item)); + bool id = sinistro1.get_ControleSinistro().get_Id() == (long)0; + SinistroAuto sinistroAuto = sinistro1.get_SinistroAuto(); + sinistroVida = sinistro1.get_SinistroVida(); + if (!id) + { + registroLogs.Add(base.CreateLog(sinistro1.get_Id(), sinistro1, 7)); + sinistro1.set_ControleSinistro(commited.get_ControleSinistroRepository().Merge(sinistro1.get_ControleSinistro())); + sinistro1 = (sinistro1.get_Id() == 0 ? commited.get_SinistroRepository().SaveOrUpdate(sinistro1) : commited.get_SinistroRepository().Merge(sinistro1)); + num = idramo; + long num1 = num - (long)5; + if (num1 <= (long)5) + { + switch ((uint)num1) + { + case 0: + { + goto Label0; + } + case 1: + case 2: + case 4: + case 5: + { + goto Label1; + } + case 3: + { + goto Label2; + } + } + } + else + { + } + if (num != (long)37) + { + goto Label3; + } + Label0: + if (sinistroAuto != null) + { + sinistroAuto.set_Sinistro(sinistro1); + sinistroAuto = (sinistroAuto.get_Id() == 0 ? commited.get_SinistroAutoRepository().SaveOrUpdate(sinistroAuto) : commited.get_SinistroAutoRepository().Merge(sinistroAuto)); + sinistro1.set_SinistroAuto(sinistroAuto); + } + } + else + { + sinistro1.set_ControleSinistro(commited.get_ControleSinistroRepository().SaveOrUpdate(sinistro1.get_ControleSinistro())); + sinistro1 = commited.get_SinistroRepository().SaveOrUpdate(sinistro1); + registroLogs.Add(base.CreateLog(sinistro1.get_Id(), sinistro1.GetValorOriginal(), 7, 0)); + num = idramo; + long num2 = num - (long)5; + if (num2 <= (long)5) + { + switch ((uint)num2) + { + case 0: + { + goto Label4; + } + case 1: + case 2: + case 4: + case 5: + { + goto Label5; + } + case 3: + { + goto Label2; + } + } + } + else + { + } + if (num != (long)37) + { + goto Label6; + } + Label4: + sinistroAuto.set_Sinistro(sinistro1); + sinistroAuto = commited.get_SinistroAutoRepository().SaveOrUpdate(sinistroAuto); + sinistro1.set_SinistroAuto(sinistroAuto); + } + Label2: + base.SaveLog(registroLogs, commited); + commited.Commit(); + sinistro3 = sinistro1; + } + } + catch (Exception exception) + { + num3 = base.Registrar(exception, 175, num3, sinistro, true); + continue; + } + return sinistro3; + } + return sinistro; + Label1: + if (sinistroVida == null) + { + sinistroVida = new SinistroVida(); + } + sinistroVida.set_Sinistro(sinistro1); + sinistroVida = (sinistroVida.get_Id() == 0 ? commited.get_SinistroVidaRepository().SaveOrUpdate(sinistroVida) : commited.get_SinistroVidaRepository().Merge(sinistroVida)); + sinistro1.set_SinistroVida(sinistroVida); + goto Label2; + Label3: + if (num != (long)53) + { + goto Label2; + } + else + { + goto Label1; + } + Label5: + sinistroVida.set_Sinistro(sinistro1); + sinistroVida = commited.get_SinistroVidaRepository().SaveOrUpdate(sinistroVida); + sinistro1.set_SinistroVida(sinistroVida); + goto Label2; + Label6: + if (num != (long)53) + { + goto Label2; + } + else + { + goto Label5; + } + }); + return sinistro2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/ServicoExtrato.cs b/Codemerx/Gestor.Application/Servicos/ServicoExtrato.cs new file mode 100644 index 0000000..a2742e4 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/ServicoExtrato.cs @@ -0,0 +1,335 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos +{ + internal class ServicoExtrato : BaseServico + { + public ServicoExtrato() + { + } + + internal async Task> BuscarDetalhes(long id) + { + int num = 3; + ObservableCollection observableCollection1 = await Task.Run>(() => { + ObservableCollection observableCollection; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List detalheExtratos = read.get_DetalheExtratoRepository().Find(id); + Func u003cu003e9_01 = ServicoExtrato.u003cu003ec.u003cu003e9__0_1; + if (u003cu003e9_01 == null) + { + u003cu003e9_01 = (DetalheExtrato x) => x.get_Cliente(); + ServicoExtrato.u003cu003ec.u003cu003e9__0_1 = u003cu003e9_01; + } + IOrderedEnumerable detalheExtratos1 = detalheExtratos.OrderBy(u003cu003e9_01); + Func u003cu003e9_02 = ServicoExtrato.u003cu003ec.u003cu003e9__0_2; + if (u003cu003e9_02 == null) + { + u003cu003e9_02 = (DetalheExtrato x) => x.get_Apolice(); + ServicoExtrato.u003cu003ec.u003cu003e9__0_2 = u003cu003e9_02; + } + IOrderedEnumerable detalheExtratos2 = detalheExtratos1.ThenBy(u003cu003e9_02); + Func u003cu003e9_03 = ServicoExtrato.u003cu003ec.u003cu003e9__0_3; + if (u003cu003e9_03 == null) + { + u003cu003e9_03 = (DetalheExtrato x) => x.get_Endosso(); + ServicoExtrato.u003cu003ec.u003cu003e9__0_3 = u003cu003e9_03; + } + IOrderedEnumerable detalheExtratos3 = detalheExtratos2.ThenBy(u003cu003e9_03); + Func u003cu003e9_04 = ServicoExtrato.u003cu003ec.u003cu003e9__0_4; + if (u003cu003e9_04 == null) + { + u003cu003e9_04 = (DetalheExtrato x) => x.get_NumeroParcela(); + ServicoExtrato.u003cu003ec.u003cu003e9__0_4 = u003cu003e9_04; + } + observableCollection = new ObservableCollection(detalheExtratos3.ThenBy(u003cu003e9_04)); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 91, num, id, true); + continue; + } + return observableCollection; + } + return new ObservableCollection(); + }); + return observableCollection1; + } + + public async Task> BuscarExtrato(long id, long idusuario, StatusExtrato status, DateTime inicio, DateTime fim) + { + int num = 3; + List extratos2 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List extratos = read.get_ExtratoRepository().FindBySeguradora(id, idusuario, Recursos.Empresa.get_Id(), inicio, fim, new StatusExtrato?(status)); + Func u003cu003e9_21 = ServicoExtrato.u003cu003ec.u003cu003e9__2_1; + if (u003cu003e9_21 == null) + { + u003cu003e9_21 = (Extrato x) => x.get_Numero(); + ServicoExtrato.u003cu003ec.u003cu003e9__2_1 = u003cu003e9_21; + } + IOrderedEnumerable extratos1 = extratos.OrderBy(u003cu003e9_21); + Func u003cu003e9_22 = ServicoExtrato.u003cu003ec.u003cu003e9__2_2; + if (u003cu003e9_22 == null) + { + u003cu003e9_22 = (Extrato x) => x.get_Data(); + ServicoExtrato.u003cu003ec.u003cu003e9__2_2 = u003cu003e9_22; + } + list = extratos1.ThenByDescending(u003cu003e9_22).ToList(); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 92, num, new { id = id, status = status, inicio = inicio, fim = fim }, true); + continue; + } + return list; + } + return new List(); + }); + return extratos2; + } + + public async Task> BuscarExtratoPorData(Filtros filtros) + { + int num = 3; + List extratos1 = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + List extratos = read.get_ExtratoRepository().FindByData(filtros); + Func u003cu003e9_31 = ServicoExtrato.u003cu003ec.u003cu003e9__3_1; + if (u003cu003e9_31 == null) + { + u003cu003e9_31 = (Extrato x) => x.get_Data(); + ServicoExtrato.u003cu003ec.u003cu003e9__3_1 = u003cu003e9_31; + } + list = extratos.OrderBy(u003cu003e9_31).ToList(); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 93, num, filtros, true); + continue; + } + return list; + } + return new List(); + }); + return extratos1; + } + + internal async Task BuscarNumExtrato(long? id) + { + string str1; + if (id.HasValue) + { + long? nullable = id; + long num = (long)0; + if (!(nullable.GetValueOrDefault() <= num & nullable.HasValue)) + { + string str2 = ""; + int num1 = 3; + str1 = await Task.Run(() => { + string str; + while (num1 > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + DetalheExtrato detalheExtrato = read.get_DetalheExtratoRepository().FindByLongId(id).FirstOrDefault(); + str2 = (detalheExtrato == null || detalheExtrato.get_Id() <= (long)0 ? "" : detalheExtrato.get_Extrato().get_Numero()); + str = str2; + } + } + catch (Exception exception) + { + num1 = base.Registrar(exception, 91, num1, id, true); + continue; + } + return str; + } + return ""; + }); + return str1; + } + } + str1 = ""; + return str1; + } + + public async Task Delete(Extrato extrato) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + try + { + List registroLogs = new List(); + using (UnitOfWork commited = Instancia.Commited) + { + commited.get_ExtratoRepository().Delete(extrato.get_Id()); + registroLogs.Add(base.CreateLog(extrato.get_Id(), extrato.GetValorOriginal(), 1, 2)); + base.SaveLog(registroLogs, commited); + commited.Commit(); + flag = true; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 264, num, extrato, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task FindByParcelaId(long id) + { + int num = 3; + DetalheExtrato detalheExtrato1 = await Task.Run(() => { + DetalheExtrato detalheExtrato; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + detalheExtrato = read.get_DetalheExtratoRepository().FindByParcelaId(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 74, num, id, true); + continue; + } + return detalheExtrato; + } + return new DetalheExtrato(); + }); + return detalheExtrato1; + } + + public async Task Save(DetalheExtrato detalhe) + { + int num = 3; + base.Sucesso = true; + DetalheExtrato detalheExtrato1 = detalhe; + DetalheExtrato detalheExtrato2 = await Task.Run(() => { + DetalheExtrato detalheExtrato; + while (num > 0) + { + detalhe = detalheExtrato1; + try + { + List registroLogs = new List(); + using (UnitOfWork commited = Instancia.Commited) + { + TipoAcao tipoAcao = (detalhe.get_Id() == 0 ? 0 : 1); + commited.get_DetalheExtratoRepository().Merge(detalhe); + if (tipoAcao != 1) + { + registroLogs.Add(base.CreateLog(detalhe.get_Id(), detalhe.Compare(detalheExtrato1.GetValorOriginal()), 23, tipoAcao)); + } + else + { + registroLogs.Add(base.CreateLog(detalhe.get_Id(), detalhe.GetValorOriginal(), 23, tipoAcao)); + } + base.SaveLog(registroLogs, commited); + commited.Commit(); + detalheExtrato = detalhe; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 262, num, detalhe, true); + continue; + } + return detalheExtrato; + } + return detalheExtrato1; + }); + return detalheExtrato2; + } + + public async Task Save(Extrato extrato) + { + int num = 3; + base.Sucesso = true; + Extrato extrato1 = extrato; + Extrato extrato2 = await Task.Run(() => { + Extrato extrato3; + while (num > 0) + { + extrato = extrato1; + try + { + List registroLogs = new List(); + using (UnitOfWork commited = Instancia.Commited) + { + TipoAcao tipoAcao = (extrato.get_Id() == 0 ? 0 : 1); + commited.get_ExtratoRepository().Merge(extrato); + if (tipoAcao != 1) + { + registroLogs.Add(base.CreateLog(extrato.get_Id(), extrato.Compare(extrato1.GetValorOriginal()), 23, tipoAcao)); + } + else + { + registroLogs.Add(base.CreateLog(extrato.get_Id(), extrato.GetValorOriginal(), 23, tipoAcao)); + } + base.SaveLog(registroLogs, commited); + commited.Commit(); + } + extrato3 = extrato; + } + catch (Exception exception) + { + num = base.Registrar(exception, 263, num, extrato, true); + continue; + } + return extrato3; + } + return extrato1; + }); + return extrato2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/TarefaServico.cs b/Codemerx/Gestor.Application/Servicos/TarefaServico.cs new file mode 100644 index 0000000..792aea6 --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/TarefaServico.cs @@ -0,0 +1,795 @@ +using Gestor.Application.Actions; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Threading; + +namespace Gestor.Application.Servicos +{ + public class TarefaServico : BaseServico + { + public TarefaServico() + { + } + + public async Task AtualizarNotasTarefas() + { + int num = 3; + int[] numArray1 = await Task.Run(() => { + int[] numArray; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + numArray = read.get_TarefaRepository().ContarTarefas(Recursos.Usuario.get_Id()); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 100, num, Recursos.Usuario.get_Id(), true); + continue; + } + return numArray; + } + return new int[1]; + }); + return numArray1; + } + + public async Task> BuscarFases(long id) + { + int num = 3; + List fases1 = await Task.Run>(() => { + List fases; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + fases = read.get_TarefaRepository().BuscarFases(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 102, num, id, true); + continue; + } + return fases; + } + return new List(); + }); + return fases1; + } + + public async Task> BuscarNotas(long id) + { + int num = 3; + List tarefas1 = await Task.Run>(() => { + List tarefas; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + tarefas = read.get_TarefaRepository().BuscarTarefaPorUsuario(id, 1); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 98, num, id, true); + continue; + } + return tarefas; + } + return new List(); + }); + return tarefas1; + } + + public async Task> BuscarNotasConcluidas(long id) + { + int num = 3; + List tarefas1 = await Task.Run>(() => { + List tarefas; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + tarefas = read.get_TarefaRepository().BuscarTarefaConcluidaPorUsuario(id, 1); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 99, num, id, true); + continue; + } + return tarefas; + } + return new List(); + }); + return tarefas1; + } + + public async Task BuscarTarefa(long id) + { + int num = 3; + Tarefa tarefa1 = await Task.Run(() => { + Tarefa tarefa; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + tarefa = read.get_TarefaRepository().BuscarTarefa(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 105, num, id, true); + continue; + } + return tarefa; + } + return new Tarefa(); + }); + return tarefa1; + } + + public async Task> BuscarTarefas(TipoTarefa entidade, long id, bool? concluido) + { + int num = 3; + List tarefas1 = await Task.Run>(() => { + List tarefas; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + tarefas = read.get_TarefaRepository().BuscarTarefa(entidade, id, concluido); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 94, num, new { entidade = entidade, id = id, concluido = concluido }, true); + continue; + } + return tarefas; + } + return new List(); + }); + return tarefas1; + } + + public async Task> BuscarTarefas(long id, DateTime inicio, DateTime fim, bool? concluido) + { + int num = 3; + List tarefas1 = await Task.Run>(() => { + List tarefas; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + tarefas = read.get_TarefaRepository().BuscarTarefaPorUsuario(id, inicio, fim, concluido); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 95, num, new { id = id, inicio = inicio, fim = fim, concluido = concluido }, true); + continue; + } + return tarefas; + } + return new List(); + }); + return tarefas1; + } + + public async Task> BuscarTarefas(long id) + { + int num = 3; + List tarefas1 = await Task.Run>(() => { + List tarefas; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + tarefas = read.get_TarefaRepository().BuscarTarefaPorTrilha(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 101, num, id, true); + continue; + } + return tarefas; + } + return new List(); + }); + return tarefas1; + } + + public async Task> BuscarTarefasCliente(long id) + { + int num = 3; + List tarefas1 = await Task.Run>(() => { + List tarefas; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + tarefas = read.get_TarefaRepository().BuscarTarefaPorCliente(id); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 96, num, id, true); + continue; + } + return tarefas; + } + return new List(); + }); + return tarefas1; + } + + public async Task> BuscarTarefasPorTipo(TipoDeTarefa tipoTarefa) + { + int num = 3; + List tarefas1 = await Task.Run>(() => { + List tarefas; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + tarefas = read.get_TarefaRepository().BuscarTarefasPorTipo(tipoTarefa.get_Id()); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 309, num, new { tipoTarefa = tipoTarefa }, true); + continue; + } + return tarefas; + } + return new List(); + }); + return tarefas1; + } + + public async Task> BuscarTrilhas() + { + int num = 3; + List trilhas1 = await Task.Run>(() => { + List trilhas; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + trilhas = read.get_TarefaRepository().BuscarTrilhas(true); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 104, num, null, true); + continue; + } + return trilhas; + } + return new List(); + }); + return trilhas1; + } + + private static void CleanWebEditor(Tarefa tarefa) + { + if (tarefa.get_Descricao() != null) + { + tarefa.set_Descricao(TarefaServico.RemoveXml(tarefa.get_Descricao())); + } + if (tarefa.get_DescricaoInterna() != null) + { + tarefa.set_DescricaoInterna(TarefaServico.RemoveXml(tarefa.get_DescricaoInterna())); + } + } + + public async Task Excluir(long id) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + commited.get_TarefaRepository().Excluir(id); + commited.Commit(); + } + Dispatcher dispatcher = System.Windows.Application.Current.Dispatcher; + Action u003cu003e9_51 = TarefaServico.u003cu003ec.u003cu003e9__5_1; + if (u003cu003e9_51 == null) + { + u003cu003e9_51 = () => Gestor.Application.Actions.Actions.AtualizaBadges(); + TarefaServico.u003cu003ec.u003cu003e9__5_1 = u003cu003e9_51; + } + dispatcher.Invoke(u003cu003e9_51); + flag = true; + } + catch (Exception exception) + { + num = base.Registrar(exception, 268, num, id, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task ExcluirTarefasDocumento(long id) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + string str; + while (num > 0) + { + try + { + List tarefas = new List(); + using (UnitOfWork read = Instancia.Read) + { + tarefas = read.get_TarefaRepository().BuscarTarefa(0, id, new bool?(false)); + } + foreach (Tarefa tarefa in tarefas) + { + using (UnitOfWork commited = Instancia.Commited) + { + commited.get_TarefaRepository().Excluir(tarefa.get_Id()); + commited.Commit(); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(1); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(DateTime.Now); + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(tarefa, jsonSerializerSetting)); + registroLog.set_EntidadeId(tarefa.get_Id()); + registroLog.set_Tela(4); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_192 = TarefaServico.u003cu003ec.u003cu003e9__19_2; + if (u003cu003e9_192 == null) + { + u003cu003e9_192 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + TarefaServico.u003cu003ec.u003cu003e9__19_2 = u003cu003e9_192; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_192); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + } + } + Dispatcher dispatcher = System.Windows.Application.Current.Dispatcher; + Action u003cu003e9_191 = TarefaServico.u003cu003ec.u003cu003e9__19_1; + if (u003cu003e9_191 == null) + { + u003cu003e9_191 = () => Gestor.Application.Actions.Actions.AtualizaBadges(); + TarefaServico.u003cu003ec.u003cu003e9__19_1 = u003cu003e9_191; + } + dispatcher.Invoke(u003cu003e9_191); + flag = true; + } + catch (Exception exception) + { + num = base.Registrar(exception, 268, num, id, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public static string RemoveXml(string description) + { + try + { + List strs = new List(); + string[] strArrays = description.Split(new char[] { '<' }); + for (int i = 0; i < (int)strArrays.Length; i++) + { + string str = strArrays[i]; + if (str.Contains("?xml") || str.Contains("o:p")) + { + strs.Add(string.Concat("<", str)); + } + } + foreach (string str1 in strs) + { + description = description.Replace(str1, ""); + } + } + catch (Exception exception) + { + throw exception; + } + return description; + } + + public async Task Salvar(Tarefa tarefa) + { + int num = 3; + base.Sucesso = true; + DateTime networkTime = Funcoes.GetNetworkTime(); + Tarefa tarefa2 = tarefa; + Tarefa tarefa3 = await Task.Run(() => { + Tarefa tarefa4; + string str; + while (num > 0) + { + tarefa = tarefa2; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + TarefaServico.CleanWebEditor(tarefa); + if (tarefa.get_Entidade() == 1) + { + tarefa.set_Descricao((!string.IsNullOrWhiteSpace(tarefa.get_Anotacoes()) ? tarefa.get_Anotacoes() : tarefa.get_Descricao())); + } + tarefa = (tarefa.get_Id() == (long)0 ? commited.get_TarefaRepository().Salvar(tarefa) : commited.get_TarefaRepository().Atualizar(tarefa)); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(1); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + Tarefa tarefa1 = tarefa; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(tarefa1, jsonSerializerSetting)); + registroLog.set_EntidadeId(tarefa.get_Id()); + registroLog.set_Tela(38); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_12 = TarefaServico.u003cu003ec.u003cu003e9__1_2; + if (u003cu003e9_12 == null) + { + u003cu003e9_12 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + TarefaServico.u003cu003ec.u003cu003e9__1_2 = u003cu003e9_12; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_12); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + Dispatcher dispatcher = System.Windows.Application.Current.Dispatcher; + Action u003cu003e9_11 = TarefaServico.u003cu003ec.u003cu003e9__1_1; + if (u003cu003e9_11 == null) + { + u003cu003e9_11 = () => Gestor.Application.Actions.Actions.AtualizaBadges(); + TarefaServico.u003cu003ec.u003cu003e9__1_1 = u003cu003e9_11; + } + dispatcher.Invoke(u003cu003e9_11); + tarefa4 = tarefa; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 265, num, tarefa, true); + continue; + } + return tarefa4; + } + return tarefa2; + }); + return tarefa3; + } + + public async Task Salvar(Trilha trilha) + { + int num = 3; + base.Sucesso = true; + DateTime networkTime = Funcoes.GetNetworkTime(); + Trilha trilha2 = trilha; + Trilha trilha3 = await Task.Run(() => { + Trilha trilha4; + string str; + while (num > 0) + { + trilha = trilha2; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + trilha = (trilha.get_Id() == (long)0 ? commited.get_TarefaRepository().Salvar(trilha) : commited.get_TarefaRepository().Atualizar(trilha)); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(1); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + Trilha trilha1 = trilha; + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(trilha1, jsonSerializerSetting)); + registroLog.set_EntidadeId(trilha.get_Id()); + registroLog.set_Tela(4); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_42 = TarefaServico.u003cu003ec.u003cu003e9__4_2; + if (u003cu003e9_42 == null) + { + u003cu003e9_42 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + TarefaServico.u003cu003ec.u003cu003e9__4_2 = u003cu003e9_42; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_42); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + commited.Commit(); + Dispatcher dispatcher = System.Windows.Application.Current.Dispatcher; + Action u003cu003e9_41 = TarefaServico.u003cu003ec.u003cu003e9__4_1; + if (u003cu003e9_41 == null) + { + u003cu003e9_41 = () => Gestor.Application.Actions.Actions.AtualizaBadges(); + TarefaServico.u003cu003ec.u003cu003e9__4_1 = u003cu003e9_41; + } + dispatcher.Invoke(u003cu003e9_41); + trilha4 = trilha; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 267, num, trilha, true); + continue; + } + return trilha4; + } + return trilha2; + }); + return trilha3; + } + + public async Task> Salvar(List fases) + { + int num = 3; + base.Sucesso = true; + DateTime networkTime = Funcoes.GetNetworkTime(); + List fases1 = fases; + List fases2 = await Task.Run>(() => { + List fases3; + string str; + while (num > 0) + { + fases = fases1; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + fases = commited.get_TarefaRepository().Salvar(fases); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + foreach (Fase fase in fases) + { + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(1); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(fase, jsonSerializerSetting)); + registroLog.set_EntidadeId(fase.get_Id()); + registroLog.set_Tela(4); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_142 = TarefaServico.u003cu003ec.u003cu003e9__14_2; + if (u003cu003e9_142 == null) + { + u003cu003e9_142 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + TarefaServico.u003cu003ec.u003cu003e9__14_2 = u003cu003e9_142; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_142); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + } + commited.Commit(); + Dispatcher dispatcher = System.Windows.Application.Current.Dispatcher; + Action u003cu003e9_141 = TarefaServico.u003cu003ec.u003cu003e9__14_1; + if (u003cu003e9_141 == null) + { + u003cu003e9_141 = () => Gestor.Application.Actions.Actions.AtualizaBadges(); + TarefaServico.u003cu003ec.u003cu003e9__14_1 = u003cu003e9_141; + } + dispatcher.Invoke(u003cu003e9_141); + fases3 = fases; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 269, num, fases, true); + continue; + } + return fases3; + } + return fases1; + }); + return fases2; + } + + public async Task> Salvar(List tarefas) + { + int num = 3; + base.Sucesso = true; + DateTime networkTime = Funcoes.GetNetworkTime(); + List tarefas1 = tarefas; + List tarefas2 = await Task.Run>(() => { + List tarefas3; + string str; + while (num > 0) + { + tarefas = tarefas1; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + tarefas = commited.get_TarefaRepository().Salvar(tarefas); + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + foreach (Tarefa tarefa in tarefas) + { + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(1); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(tarefa, jsonSerializerSetting)); + registroLog.set_EntidadeId(tarefa.get_Id()); + registroLog.set_Tela(4); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + Func u003cu003e9_152 = TarefaServico.u003cu003ec.u003cu003e9__15_2; + if (u003cu003e9_152 == null) + { + u003cu003e9_152 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; + TarefaServico.u003cu003ec.u003cu003e9__15_2 = u003cu003e9_152; + } + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_152); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + base.SaveLog(registroLog, commited); + } + commited.Commit(); + Dispatcher dispatcher = System.Windows.Application.Current.Dispatcher; + Action u003cu003e9_151 = TarefaServico.u003cu003ec.u003cu003e9__15_1; + if (u003cu003e9_151 == null) + { + u003cu003e9_151 = () => Gestor.Application.Actions.Actions.AtualizaBadges(); + TarefaServico.u003cu003ec.u003cu003e9__15_1 = u003cu003e9_151; + } + dispatcher.Invoke(u003cu003e9_151); + tarefas3 = tarefas; + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 265, num, tarefas, true); + continue; + } + return tarefas3; + } + return tarefas1; + }); + return tarefas2; + } + + public async Task> Validar(List ids, long trilhaId) + { + int num = 3; + List nums1 = await Task.Run>(() => { + List nums; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + nums = commited.get_TarefaRepository().Validar(ids, trilhaId); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 266, num, new { ids = ids, trilhaId = trilhaId }, true); + continue; + } + return nums; + } + return null; + }); + return nums1; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Servicos/VendedorUsuarioServico.cs b/Codemerx/Gestor.Application/Servicos/VendedorUsuarioServico.cs new file mode 100644 index 0000000..4804dac --- /dev/null +++ b/Codemerx/Gestor.Application/Servicos/VendedorUsuarioServico.cs @@ -0,0 +1,160 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.Servicos +{ + public class VendedorUsuarioServico : BaseServico + { + public VendedorUsuarioServico() + { + } + + public async Task Delete(List vinculo) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + try + { + using (UnitOfWork commited = Instancia.Commited) + { + vinculo.ForEach((VendedorUsuario x) => commited.get_VendedorUsuarioRepository().Delete(x.get_Id())); + commited.Commit(); + } + flag = true; + } + catch (Exception exception) + { + num = base.Registrar(exception, 272, num, vinculo, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task> FindByVinculo(Usuario usuario) + { + int num = 3; + List vendedorUsuarios = await Task.Run>(() => { + List list; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + list = read.get_VendedorUsuarioRepository().FindByVinculo(usuario.get_Id()).ToList(); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 106, num, usuario, true); + continue; + } + return list; + } + return new List(); + }); + return vendedorUsuarios; + } + + public async Task FindVinculo(Vendedor vendedor) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + flag = read.get_VendedorUsuarioRepository().Exist(vendedor.get_Id()); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 271, num, vendedor, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task FindVinculoByUsuario(long idusuario) + { + int num = 3; + bool flag1 = await Task.Run(() => { + bool flag; + while (num > 0) + { + try + { + using (UnitOfWork read = Instancia.Read) + { + flag = read.get_VendedorUsuarioRepository().ExistVinculoUsuario(idusuario); + } + } + catch (Exception exception) + { + num = base.Registrar(exception, 106, num, null, true); + continue; + } + return flag; + } + return false; + }); + return flag1; + } + + public async Task> SaveOrUpdate(List vinculo) + { + int num = 3; + base.Sucesso = true; + List vendedorUsuarios1 = vinculo; + List vendedorUsuarios2 = await Task.Run>(() => { + List vendedorUsuarios; + while (num > 0) + { + vinculo = vendedorUsuarios1; + try + { + using (UnitOfWork commited = Instancia.Commited) + { + vinculo.ForEach((VendedorUsuario x) => commited.get_VendedorUsuarioRepository().SaveOrUpdate(x)); + commited.Commit(); + } + vendedorUsuarios = vinculo; + } + catch (Exception exception) + { + num = base.Registrar(exception, 271, num, vinculo, true); + continue; + } + return vendedorUsuarios; + } + return vendedorUsuarios1; + }); + return vendedorUsuarios2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/AnaliticoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/AnaliticoViewModel.cs new file mode 100644 index 0000000..bdf394b --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/AnaliticoViewModel.cs @@ -0,0 +1,210 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.BI; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Relatorios.ClientesAtivosInativos; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; + +namespace Gestor.Application.ViewModels +{ + internal class AnaliticoViewModel : BaseSegurosViewModel + { + private string _head; + + public string Head + { + get + { + return this._head; + } + set + { + this._head = value; + base.OnPropertyChanged("Head"); + } + } + + public TipoTela Tela { get; set; } = 1; + + public string Tipo + { + get; + set; + } + + public AnaliticoViewModel(string tipo) + { + this.Tipo = tipo; + string str = this.Tipo; + if (str == "PARCELAS") + { + this.Tela = 5; + return; + } + if (str != "APOLICES") + { + this.Tela = 1; + return; + } + this.Tela = 2; + } + + private async Task GerarHtml(DataGrid grid) + { + PropertyInfo[] properties = typeof(Analitico).GetProperties(); + List list = ( + from x in (IEnumerable)properties + select x.Name).ToList(); + List strs = new List(); + for (int i = 0; i < grid.Columns.Count; i++) + { + if (!(grid.Columns[i] is DataGridTemplateColumn)) + { + Binding binding = (grid.Columns[i] as DataGridBoundColumn).Binding as Binding; + strs.Add(binding.Path.Path); + } + } + List list1 = list.Except(strs).ToList(); + IEnumerable analiticos = grid.Items.Cast(); + string str = await Funcoes.GenerateTable(( + from x in analiticos + where x.get_Selecionado() + select x).ToList(), list1, false, true, "", null); + string str1 = Funcoes.CreateCard("", str, false); + TipoRelatorio tipoRelatorio = new TipoRelatorio(); + tipoRelatorio.set_Nome(string.Concat("ANALÍTICO - ", this.Head)); + string str2 = str1; + if (str2 == null) + { + str2 = ""; + } + string str3 = Funcoes.ExportarHtml(tipoRelatorio, str2, "60", "landscape", false, ""); + return str3; + } + + public async Task Print(DataGrid grid) + { + IEnumerable analiticos = grid.Items.Cast(); + if (analiticos.Any((Analitico x) => x.get_Selecionado())) + { + string str = await this.GerarHtml(grid); + if (!string.IsNullOrEmpty(str)) + { + string tempPath = Path.GetTempPath(); + string str1 = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.html", tempPath, (new Regex(string.Concat("[", Regex.Escape(string.Concat(new string(Path.GetInvalidFileNameChars()), new string(Path.GetInvalidPathChars()))), "]"))).Replace(this.Head, ""), Funcoes.GetNetworkTime()); + StreamWriter streamWriter = new StreamWriter(str1, true, Encoding.UTF8); + streamWriter.Write(str); + streamWriter.Close(); + Process.Start(str1); + } + } + else + { + await base.ShowMessage("É NECESSÁRIO SELECIONAR AO MENOS UM DOCUMENTO", "OK", "", false); + } + } + + public async Task Salvar(Trilha destino) + { + Trilha trilha; + List fases = destino.get_Fases(); + TarefaServico tarefaServico = new TarefaServico(); + Trilha trilha1 = await tarefaServico.Salvar(destino); + if (tarefaServico.Sucesso) + { + fases.ForEach((Fase x) => x.set_Trilha(trilha1)); + fases = await tarefaServico.Salvar(fases); + if (tarefaServico.Sucesso) + { + trilha1.set_Fases(fases); + trilha = trilha1; + } + else + { + trilha = null; + } + } + else + { + trilha = null; + } + fases = null; + tarefaServico = null; + return trilha; + } + + public async Task Save(List tarefas) + { + await (new TarefaServico()).Salvar(tarefas); + } + + public async Task> Validar(List analitico, Trilha trilha) + { + List list; + List analiticos; + TarefaServico tarefaServico = new TarefaServico(); + string tipo = this.Tipo; + if (tipo == "CLIENTES") + { + List analiticos1 = analitico; + list = ( + from x in analiticos1 + select x.get_Cliente().get_Id()).ToList(); + } + else if (tipo == "PARCELAS" || tipo == "COMISSÃO") + { + List analiticos2 = analitico; + list = ( + from x in analiticos2 + select x.get_Parcela().get_Id()).ToList(); + } + else + { + List analiticos3 = analitico; + list = ( + from x in analiticos3 + select x.get_Documento().get_Id()).ToList(); + } + List nums = await tarefaServico.Validar(list, trilha.get_Id()); + List nums1 = nums; + tipo = this.Head; + if (tipo == "CLIENTES") + { + analiticos = ( + from x in analitico + where nums1.Contains(x.get_Cliente().get_Id()) + select x).ToList(); + } + else + { + analiticos = (tipo == "PARCELAS" || tipo == "COMISSÃO" ? ( + from x in analitico + where nums1.Contains(x.get_Parcela().get_Id()) + select x).ToList() : ( + from x in analitico + where nums1.Contains(x.get_Documento().get_Id()) + select x).ToList()); + } + List list1 = analitico.Except(analiticos).ToList(); + return list1; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Arquivo.cs b/Codemerx/Gestor.Application/ViewModels/Arquivo.cs new file mode 100644 index 0000000..5a1d80e --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Arquivo.cs @@ -0,0 +1,24 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Application.ViewModels +{ + public class Arquivo + { + public string Nome + { + get; + set; + } + + public int Processo + { + get; + set; + } + + public Arquivo() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/BI/BISeriesViewModel.cs b/Codemerx/Gestor.Application/ViewModels/BI/BISeriesViewModel.cs new file mode 100644 index 0000000..0d5a5f0 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/BI/BISeriesViewModel.cs @@ -0,0 +1,70 @@ +using Gestor.Application.ViewModels.Generic; +using LiveCharts; +using System; + +namespace Gestor.Application.ViewModels.BI +{ + public class BISeriesViewModel : BaseSegurosViewModel + { + private int _indice; + + private string _titulo; + + private SeriesCollection _serie; + + public int Indice + { + get + { + return this._indice; + } + set + { + if (this._indice == value) + { + return; + } + this._indice = value; + base.OnPropertyChanged("Indice"); + } + } + + public SeriesCollection Serie + { + get + { + return this._serie; + } + set + { + if ((object)this._serie == (object)value) + { + return; + } + this._serie = value; + base.OnPropertyChanged("Serie"); + } + } + + public string Titulo + { + get + { + return this._titulo; + } + set + { + if (this._titulo == value) + { + return; + } + this._titulo = value; + base.OnPropertyChanged("Titulo"); + } + } + + public BISeriesViewModel() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/BI/NotasViewModel.cs b/Codemerx/Gestor.Application/ViewModels/BI/NotasViewModel.cs new file mode 100644 index 0000000..dca2d31 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/BI/NotasViewModel.cs @@ -0,0 +1,311 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.BI +{ + public class NotasViewModel : BaseSegurosViewModel + { + private readonly TarefaServico _servico; + + private bool _enableIncluirNota = true; + + private bool _ocultarUsuarios; + + private ObservableCollection _usuarios; + + private Usuario _selectedUsuario; + + private Gestor.Model.Domain.Ferramentas.Tarefa _tarefa; + + private ObservableCollection _notas; + + private ObservableCollection _notasConcluidas; + + private Gestor.Model.Domain.Ferramentas.Tarefa _selectedNota; + + private bool _ocultarNotasConcluidas = true; + + public bool EnableIncluirNota + { + get + { + return this._enableIncluirNota; + } + set + { + this._enableIncluirNota = value; + base.OnPropertyChanged("EnableIncluirNota"); + } + } + + public ObservableCollection Notas + { + get + { + return this._notas; + } + set + { + this._notas = value; + base.OnPropertyChanged("Notas"); + } + } + + public ObservableCollection NotasConcluidas + { + get + { + return this._notasConcluidas; + } + set + { + this._notasConcluidas = value; + base.OnPropertyChanged("NotasConcluidas"); + } + } + + public bool OcultarNotasConcluidas + { + get + { + return this._ocultarNotasConcluidas; + } + set + { + this._ocultarNotasConcluidas = value; + base.OnPropertyChanged("OcultarNotasConcluidas"); + } + } + + public bool OcultarUsuarios + { + get + { + return this._ocultarUsuarios; + } + set + { + this._ocultarUsuarios = value; + base.OnPropertyChanged("OcultarUsuarios"); + } + } + + public Gestor.Model.Domain.Ferramentas.Tarefa SelectedNota + { + get + { + return this._selectedNota; + } + set + { + this._selectedNota = value; + base.OnPropertyChanged("SelectedNota"); + } + } + + public Usuario SelectedUsuario + { + get + { + return this._selectedUsuario; + } + set + { + this._selectedUsuario = value; + this.Carregar(); + base.OnPropertyChanged("SelectedUsuario"); + } + } + + public Gestor.Model.Domain.Ferramentas.Tarefa Tarefa + { + get + { + return this._tarefa; + } + set + { + this._tarefa = value; + base.OnPropertyChanged("Tarefa"); + } + } + + public ObservableCollection Usuarios + { + get + { + return this._usuarios; + } + set + { + this._usuarios = value; + base.OnPropertyChanged("Usuarios"); + } + } + + public NotasViewModel() + { + bool administrador; + bool id; + this._servico = new TarefaServico(); + this.Usuarios = new ObservableCollection(Recursos.Usuarios.Where((Usuario x) => { + if (Recursos.Usuario.get_IdEmpresa() != (long)1 && x.get_IdEmpresa() != Recursos.Usuario.get_IdEmpresa()) + { + return false; + } + return !x.get_Excluido(); + }).OrderBy((Usuario x) => x.get_Nome()).ToList()); + this.SelectedUsuario = this.Usuarios.FirstOrDefault((Usuario x) => x.get_Id() == Recursos.Usuario.get_Id()); + Usuario usuario = Recursos.Usuario; + if (usuario != null) + { + administrador = usuario.get_Administrador(); + } + else + { + administrador = false; + } + this.OcultarUsuarios = administrador; + Usuario usuario1 = Recursos.Usuario; + if (usuario1 != null) + { + id = usuario1.get_Id() > (long)0; + } + else + { + id = false; + } + this.EnableIncluirNota = id; + } + + public async Task AdicionarNota() + { + Gestor.Model.Domain.Ferramentas.Tarefa tarefa; + if (this.Notas != null) + { + ObservableCollection notas = this.Notas; + if (notas.Any((Gestor.Model.Domain.Ferramentas.Tarefa x) => { + if (x.get_Titulo() != "TÍTULO") + { + return false; + } + return x.get_Descricao() == "DESCRIÇÃO"; + })) + { + await base.ShowMessage("PARA ADICIONAR OUTRA NOTA, INSERIR TÍTULO E DESCRIÇÃO DA NOTA JÁ ADICIONADA", "OK", "", false); + tarefa = null; + return; + } + } + Gestor.Model.Domain.Ferramentas.Tarefa tarefa1 = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa1.set_Agendamento(Funcoes.GetNetworkTime()); + tarefa1.set_Titulo("TÍTULO"); + tarefa1.set_Anotacoes("DESCRIÇÃO"); + tarefa1.set_Usuario(this.Usuarios.First((Usuario x) => x.get_Id() == this.SelectedUsuario.get_Id())); + tarefa1.set_UsuarioCadastro(Recursos.Usuario); + tarefa1.set_Entidade(1); + tarefa1.set_Status(0); + tarefa = tarefa1; + tarefa = await this._servico.Salvar(tarefa); + await this.CarregarNotas(); + this.SelectedNota = tarefa; + tarefa = null; + } + + public async void Carregar() + { + await this.CarregarNotas(); + } + + public async Task CarregarNotas() + { + if (this.SelectedUsuario != null) + { + List tarefas = await this._servico.BuscarNotas(this.SelectedUsuario.get_Id()); + List tarefas1 = tarefas; + tarefas1.ForEach((Gestor.Model.Domain.Ferramentas.Tarefa x) => { + if (x.get_Titulo() == "TÍTULO" && x.get_Descricao() == "DESCRIÇÃO") + { + x.set_HabilitarPublica(true); + } + }); + this.Notas = new ObservableCollection(tarefas); + this.NotasConcluidas = new ObservableCollection(await this._servico.BuscarNotasConcluidas(this.SelectedUsuario.get_Id())); + } + } + + public async Task ExcluirNota(Gestor.Model.Domain.Ferramentas.Tarefa nota) + { + await this._servico.Excluir(nota.get_Id()); + } + + public async Task>> Salvar(Gestor.Model.Domain.Ferramentas.Tarefa destino) + { + List> keyValuePairs; + Gestor.Model.Domain.Ferramentas.Tarefa tarefa = destino; + List configuracoes = Recursos.Configuracoes; + tarefa.set_AgendamentoRetroativo(configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 45)); + List> keyValuePairs1 = destino.Validate(); + if (keyValuePairs1.Count <= 0) + { + bool publica = destino.get_Publica(); + await this._servico.Salvar(destino); + if (this._servico.Sucesso) + { + if (publica) + { + long id = destino.get_Usuario().get_Id(); + List usuarios = Recursos.Usuarios; + List tasks = new List(); + foreach (Usuario usuario in usuarios) + { + if (id == usuario.get_Id()) + { + continue; + } + Gestor.Model.Domain.Ferramentas.Tarefa tarefa1 = (Gestor.Model.Domain.Ferramentas.Tarefa)destino.Clone(); + tarefa1.set_Id((long)0); + tarefa1.set_Usuario(usuario); + tasks.Add(this._servico.Salvar(tarefa1)); + } + await Task.WhenAll(tasks); + } + await this.CarregarNotas(); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + return keyValuePairs; + } + + public async Task SalvarNota(Gestor.Model.Domain.Ferramentas.Tarefa nota) + { + return await this._servico.Salvar(nota); + } + + public void ToggleNotasConcluidas() + { + this.OcultarNotasConcluidas = !this.OcultarNotasConcluidas; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/BI/PainelBiViewModel.cs b/Codemerx/Gestor.Application/ViewModels/BI/PainelBiViewModel.cs new file mode 100644 index 0000000..99695e4 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/BI/PainelBiViewModel.cs @@ -0,0 +1,1590 @@ +using Gestor.Application.Componentes; +using Gestor.Application.Helpers; +using Gestor.Application.Model; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.BI; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Relatorios.ClientesAtivosInativos; +using Gestor.Model.Domain.Seguros; +using LiveCharts; +using LiveCharts.Defaults; +using LiveCharts.Definitions.Series; +using LiveCharts.Helpers; +using LiveCharts.Wpf; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.BI +{ + public class PainelBiViewModel : BaseSegurosViewModel + { + private readonly ClienteServico _clienteServico; + + private readonly ApoliceServico _apoliceServico; + + private readonly ParcelaServico _parcelaServico; + + private Visibility _isVisibleProducao = Visibility.Collapsed; + + private Visibility _isVisibleClientes = Visibility.Collapsed; + + private Visibility _isVisiblePendencia = Visibility.Collapsed; + + private Visibility _isVisibleVencimento = Visibility.Collapsed; + + private DateTime _inicio; + + private DateTime _fim; + + private DateTime _inicioClientes; + + private DateTime _fimClientes; + + private DateTime _inicioVencimento; + + private DateTime _fimVencimento; + + private Grafico _producao; + + private Grafico _fechamento; + + private int _aniversariantes; + + private int _vencimentoCnh; + + private int _vencimentos; + + private int _parcelasPendentes; + + private int _parcelasAVencer; + + private int _cotacoes; + + private List _parcelasPendencia; + + private List _parcelasVencimento; + + private List _documentosVencimento; + + private List _clientesAniversariantes; + + private List _clientesCnh; + + private int _quatidadeProducao; + + private int _endossos; + + private int _faturas; + + private int _apolicesPendentes; + + private int _novosNegocios; + + private int _renovacoes; + + private int _cancelamentos; + + private decimal _producaoTotal; + + private decimal _producaoTotalAnterior; + + private decimal _comissaoTotal; + + private List _documentosProducao; + + private List _documentosPendentes; + + private List _documentosFechamento; + + private Grafico _gerada; + + private Grafico _mediaComissao; + + private Func _yFormatter; + + private Func _xFormatter; + + public int Aniversariantes + { + get + { + return this._aniversariantes; + } + set + { + this._aniversariantes = value; + base.OnPropertyChanged("Aniversariantes"); + } + } + + public int ApolicesPendentes + { + get + { + return this._apolicesPendentes; + } + set + { + this._apolicesPendentes = value; + base.OnPropertyChanged("ApolicesPendentes"); + } + } + + public int Cancelamentos + { + get + { + return this._cancelamentos; + } + set + { + this._cancelamentos = value; + base.OnPropertyChanged("Cancelamentos"); + } + } + + public decimal ComissaoTotal + { + get + { + return this._comissaoTotal; + } + set + { + this._comissaoTotal = value; + base.OnPropertyChanged("ComissaoTotal"); + } + } + + public int Cotacoes + { + get + { + return this._cotacoes; + } + set + { + this._cotacoes = value; + base.OnPropertyChanged("Cotacoes"); + } + } + + public int Endossos + { + get + { + return this._endossos; + } + set + { + this._endossos = value; + base.OnPropertyChanged("Endossos"); + } + } + + public int Faturas + { + get + { + return this._faturas; + } + set + { + this._faturas = value; + base.OnPropertyChanged("Faturas"); + } + } + + public Grafico Fechamento + { + get + { + return this._fechamento; + } + set + { + this._fechamento = value; + base.OnPropertyChanged("Fechamento"); + } + } + + public DateTime Fim + { + get + { + return this._fim; + } + set + { + this._fim = value; + base.OnPropertyChanged("Fim"); + } + } + + public DateTime FimClientes + { + get + { + return this._fimClientes; + } + set + { + this._fimClientes = value; + base.OnPropertyChanged("FimClientes"); + } + } + + public DateTime FimVencimento + { + get + { + return this._fimVencimento; + } + set + { + this._fimVencimento = value; + base.OnPropertyChanged("FimVencimento"); + } + } + + public Grafico Gerada + { + get + { + return this._gerada; + } + set + { + this._gerada = value; + base.OnPropertyChanged("Gerada"); + } + } + + public DateTime Inicio + { + get + { + return this._inicio; + } + set + { + this._inicio = value; + base.OnPropertyChanged("Inicio"); + } + } + + public DateTime InicioClientes + { + get + { + return this._inicioClientes; + } + set + { + this._inicioClientes = value; + base.OnPropertyChanged("InicioClientes"); + } + } + + public DateTime InicioVencimento + { + get + { + return this._inicioVencimento; + } + set + { + this._inicioVencimento = value; + base.OnPropertyChanged("InicioVencimento"); + } + } + + public Visibility IsVisibleClientes + { + get + { + return this._isVisibleClientes; + } + set + { + this._isVisibleClientes = value; + base.OnPropertyChanged("IsVisibleClientes"); + } + } + + public Visibility IsVisiblePendencia + { + get + { + return this._isVisiblePendencia; + } + set + { + this._isVisiblePendencia = value; + base.OnPropertyChanged("IsVisiblePendencia"); + } + } + + public Visibility IsVisibleProducao + { + get + { + return this._isVisibleProducao; + } + set + { + this._isVisibleProducao = value; + base.OnPropertyChanged("IsVisibleProducao"); + } + } + + public Visibility IsVisibleVencimento + { + get + { + return this._isVisibleVencimento; + } + set + { + this._isVisibleVencimento = value; + base.OnPropertyChanged("IsVisibleVencimento"); + } + } + + public Grafico MediaComissao + { + get + { + return this._mediaComissao; + } + set + { + this._mediaComissao = value; + base.OnPropertyChanged("MediaComissao"); + } + } + + public int NovosNegocios + { + get + { + return this._novosNegocios; + } + set + { + this._novosNegocios = value; + base.OnPropertyChanged("NovosNegocios"); + } + } + + public int ParcelasAVencer + { + get + { + return this._parcelasAVencer; + } + set + { + this._parcelasAVencer = value; + base.OnPropertyChanged("ParcelasAVencer"); + } + } + + public int ParcelasPendentes + { + get + { + return this._parcelasPendentes; + } + set + { + this._parcelasPendentes = value; + base.OnPropertyChanged("ParcelasPendentes"); + } + } + + public Grafico Producao + { + get + { + return this._producao; + } + set + { + this._producao = value; + base.OnPropertyChanged("Producao"); + } + } + + public decimal ProducaoTotal + { + get + { + return this._producaoTotal; + } + set + { + this._producaoTotal = value; + base.OnPropertyChanged("ProducaoTotal"); + } + } + + public decimal ProducaoTotalAnterior + { + get + { + return this._producaoTotalAnterior; + } + set + { + this._producaoTotalAnterior = value; + base.OnPropertyChanged("ProducaoTotalAnterior"); + } + } + + public int QuatidadeProducao + { + get + { + return this._quatidadeProducao; + } + set + { + this._quatidadeProducao = value; + base.OnPropertyChanged("QuatidadeProducao"); + } + } + + public int Renovacoes + { + get + { + return this._renovacoes; + } + set + { + this._renovacoes = value; + base.OnPropertyChanged("Renovacoes"); + } + } + + public int VencimentoCnh + { + get + { + return this._vencimentoCnh; + } + set + { + this._vencimentoCnh = value; + base.OnPropertyChanged("VencimentoCnh"); + } + } + + public int Vencimentos + { + get + { + return this._vencimentos; + } + set + { + this._vencimentos = value; + base.OnPropertyChanged("Vencimentos"); + } + } + + public Func XFormatter + { + get + { + return this._xFormatter; + } + set + { + this._xFormatter = value; + base.OnPropertyChanged("XFormatter"); + } + } + + public Func YFormatter + { + get + { + return this._yFormatter; + } + set + { + this._yFormatter = value; + base.OnPropertyChanged("YFormatter"); + } + } + + public PainelBiViewModel() + { + this._isVisibleProducao = Visibility.Collapsed; + this._isVisibleClientes = Visibility.Collapsed; + this._isVisiblePendencia = Visibility.Collapsed; + this._isVisibleVencimento = Visibility.Collapsed; + DateTime date = Funcoes.GetNetworkTime().Date; + this._inicio = date.AddDays(-7); + this._fim = Funcoes.GetNetworkTime().Date; + date = Funcoes.GetNetworkTime().Date; + this._inicioClientes = date.AddDays(-7); + this._fimClientes = Funcoes.GetNetworkTime().Date; + this._inicioVencimento = Funcoes.GetNetworkTime().Date; + date = Funcoes.GetNetworkTime().Date; + this._fimVencimento = date.AddDays(7); + base(); + this._clienteServico = new ClienteServico(); + this._apoliceServico = new ApoliceServico(); + this._parcelaServico = new ParcelaServico(); + this.LoadInicial(); + } + + public async void Detalhar(int tipo) + { + List list; + string str = ""; + string str1 = "APOLICES"; + List strs = new List() + { + "Nome", + "Apolice", + "Endosso", + "Status", + "Negocio", + "VigenciaInicial", + "VigenciaFinal", + "Comissao", + "PremioLiquido", + "PremioTotal", + "Seguradora", + "Ramo" + }; + List strs1 = strs; + switch (tipo) + { + case 1: + { + str = "COMPARATIVO"; + List documentos = this._documentosProducao; + List documentos1 = this._documentosFechamento; + List documentos2 = new List(); + documentos2.AddRange(documentos); + documentos2.AddRange(documentos1); + IOrderedEnumerable vigencia1 = + from x in documentos2 + orderby x.get_Vigencia1() + select x; + list = vigencia1.Select((Documento x) => { + object description; + Analitico analitico = new Analitico(); + analitico.set_Nome(x.get_Controle().get_Cliente().get_Nome() ?? ""); + analitico.set_Apolice(x.get_Apolice() ?? ""); + analitico.set_Endosso(x.get_Endosso() ?? ""); + analitico.set_Comissao(x.get_Comissao()); + NegocioCorretora? negocioCorretora = x.get_NegocioCorretora(); + if (!negocioCorretora.HasValue) + { + description = ValidationHelper.GetDescription(x.get_Negocio()); + } + else + { + negocioCorretora = x.get_NegocioCorretora(); + description = (negocioCorretora.HasValue ? ValidationHelper.GetDescription(negocioCorretora.GetValueOrDefault()) : null) ?? ""; + } + analitico.set_Negocio((string)description); + analitico.set_PremioLiquido(x.get_PremioLiquido()); + analitico.set_PremioTotal(x.get_PremioTotal()); + analitico.set_VigenciaFinal(x.get_Vigencia2()); + analitico.set_VigenciaInicial(x.get_Vigencia1()); + analitico.set_Status(ValidationHelper.GetDescription(x.get_Situacao()) ?? ""); + analitico.set_Seguradora(x.get_Controle().get_Seguradora().get_NomeSocial()); + analitico.set_Ramo(x.get_Controle().get_Ramo().get_Nome()); + ClientesAtivosInativos clientesAtivosInativo = new ClientesAtivosInativos(); + clientesAtivosInativo.set_Id(x.get_Controle().get_Cliente().get_Id()); + clientesAtivosInativo.set_Nome(x.get_Controle().get_Cliente().get_Nome()); + analitico.set_Cliente(clientesAtivosInativo); + analitico.set_Documento(x); + return analitico; + }).ToList(); + break; + } + case 2: + { + str = "NOVOS NEGÓCIOS"; + List documentos3 = this._documentosProducao; + IEnumerable documentos4 = documentos3.Where((Documento x) => { + if (x.get_Tipo() != 0) + { + return false; + } + if (x.get_Situacao() == 1) + { + return true; + } + if (x.get_Situacao() != 2) + { + return false; + } + NegocioCorretora? negocioCorretora = x.get_NegocioCorretora(); + return negocioCorretora.GetValueOrDefault() == 0 & negocioCorretora.HasValue; + }); + IOrderedEnumerable vigencia11 = + from x in documentos4 + orderby x.get_Vigencia1() + select x; + list = vigencia11.Select((Documento x) => { + object description; + Analitico analitico = new Analitico(); + analitico.set_Nome(x.get_Controle().get_Cliente().get_Nome() ?? ""); + analitico.set_Apolice(x.get_Apolice() ?? ""); + analitico.set_Endosso(x.get_Endosso() ?? ""); + analitico.set_Comissao(x.get_Comissao()); + NegocioCorretora? negocioCorretora = x.get_NegocioCorretora(); + if (!negocioCorretora.HasValue) + { + description = ValidationHelper.GetDescription(x.get_Negocio()); + } + else + { + negocioCorretora = x.get_NegocioCorretora(); + description = (negocioCorretora.HasValue ? ValidationHelper.GetDescription(negocioCorretora.GetValueOrDefault()) : null) ?? ""; + } + analitico.set_Negocio((string)description); + analitico.set_PremioLiquido(x.get_PremioLiquido()); + analitico.set_PremioTotal(x.get_PremioTotal()); + analitico.set_VigenciaFinal(x.get_Vigencia2()); + analitico.set_VigenciaInicial(x.get_Vigencia1()); + analitico.set_Status(ValidationHelper.GetDescription(x.get_Situacao()) ?? ""); + analitico.set_Seguradora(x.get_Controle().get_Seguradora().get_NomeSocial()); + analitico.set_Ramo(x.get_Controle().get_Ramo().get_Nome()); + ClientesAtivosInativos clientesAtivosInativo = new ClientesAtivosInativos(); + clientesAtivosInativo.set_Id(x.get_Controle().get_Cliente().get_Id()); + clientesAtivosInativo.set_Nome(x.get_Controle().get_Cliente().get_Nome()); + analitico.set_Cliente(clientesAtivosInativo); + analitico.set_Documento(x); + return analitico; + }).ToList(); + break; + } + case 3: + { + str = "RENOVAÇÕES"; + List documentos5 = this._documentosProducao; + IEnumerable documentos6 = documentos5.Where((Documento x) => { + if (x.get_Tipo() != 0) + { + return false; + } + if (x.get_Situacao() != 2) + { + return false; + } + if (x.get_NegocioCorretora().GetValueOrDefault() == 1) + { + return true; + } + return x.get_Negocio().GetValueOrDefault() == 1; + }); + IOrderedEnumerable vigencia12 = + from x in documentos6 + orderby x.get_Vigencia1() + select x; + list = vigencia12.Select((Documento x) => { + object description; + Analitico analitico = new Analitico(); + analitico.set_Nome(x.get_Controle().get_Cliente().get_Nome() ?? ""); + analitico.set_Apolice(x.get_Apolice() ?? ""); + analitico.set_Endosso(x.get_Endosso() ?? ""); + analitico.set_Comissao(x.get_Comissao()); + NegocioCorretora? negocioCorretora = x.get_NegocioCorretora(); + if (!negocioCorretora.HasValue) + { + description = ValidationHelper.GetDescription(x.get_Negocio()); + } + else + { + negocioCorretora = x.get_NegocioCorretora(); + description = (negocioCorretora.HasValue ? ValidationHelper.GetDescription(negocioCorretora.GetValueOrDefault()) : null) ?? ""; + } + analitico.set_Negocio((string)description); + analitico.set_PremioLiquido(x.get_PremioLiquido()); + analitico.set_PremioTotal(x.get_PremioTotal()); + analitico.set_VigenciaFinal(x.get_Vigencia2()); + analitico.set_VigenciaInicial(x.get_Vigencia1()); + analitico.set_Status(ValidationHelper.GetDescription(x.get_Situacao()) ?? ""); + analitico.set_Seguradora(x.get_Controle().get_Seguradora().get_NomeSocial()); + analitico.set_Ramo(x.get_Controle().get_Ramo().get_Nome()); + ClientesAtivosInativos clientesAtivosInativo = new ClientesAtivosInativos(); + clientesAtivosInativo.set_Id(x.get_Controle().get_Cliente().get_Id()); + clientesAtivosInativo.set_Nome(x.get_Controle().get_Cliente().get_Nome()); + analitico.set_Cliente(clientesAtivosInativo); + analitico.set_Documento(x); + return analitico; + }).ToList(); + break; + } + case 4: + { + str = "CANCELAMENTOS"; + List documentos7 = this._documentosProducao; + IEnumerable documentos8 = documentos7.Where((Documento x) => { + if (x.get_Situacao() != 3) + { + return false; + } + return x.get_Tipo() == 1; + }); + IOrderedEnumerable vigencia13 = + from x in documentos8 + orderby x.get_Vigencia1() + select x; + list = vigencia13.Select((Documento x) => { + object description; + Analitico analitico = new Analitico(); + analitico.set_Nome(x.get_Controle().get_Cliente().get_Nome() ?? ""); + analitico.set_Apolice(x.get_Apolice() ?? ""); + analitico.set_Endosso(x.get_Endosso() ?? ""); + analitico.set_Comissao(x.get_Comissao()); + NegocioCorretora? negocioCorretora = x.get_NegocioCorretora(); + if (!negocioCorretora.HasValue) + { + description = ValidationHelper.GetDescription(x.get_Negocio()); + } + else + { + negocioCorretora = x.get_NegocioCorretora(); + description = (negocioCorretora.HasValue ? ValidationHelper.GetDescription(negocioCorretora.GetValueOrDefault()) : null) ?? ""; + } + analitico.set_Negocio((string)description); + analitico.set_PremioLiquido(x.get_PremioLiquido()); + analitico.set_PremioTotal(x.get_PremioTotal()); + analitico.set_VigenciaFinal(x.get_Vigencia2()); + analitico.set_VigenciaInicial(x.get_Vigencia1()); + analitico.set_Status(ValidationHelper.GetDescription(x.get_Situacao()) ?? ""); + analitico.set_Seguradora(x.get_Controle().get_Seguradora().get_NomeSocial()); + analitico.set_Ramo(x.get_Controle().get_Ramo().get_Nome()); + ClientesAtivosInativos clientesAtivosInativo = new ClientesAtivosInativos(); + clientesAtivosInativo.set_Id(x.get_Controle().get_Cliente().get_Id()); + clientesAtivosInativo.set_Nome(x.get_Controle().get_Cliente().get_Nome()); + analitico.set_Cliente(clientesAtivosInativo); + analitico.set_Documento(x); + return analitico; + }).ToList(); + break; + } + case 5: + { + str1 = "CLIENTES"; + List strs2 = new List() + { + "Nome", + "DocumentoCliente", + "Dia/Mês", + "Nascimento", + "TipoPessoa", + "Cidade", + "Uf", + "Cep", + "Telefone", + "E-mail", + "Profissão" + }; + strs1 = strs2; + List clientesAtivosInativos = this._clientesAniversariantes; + list = clientesAtivosInativos.Select((ClientesAtivosInativos x) => { + Analitico analitico = new Analitico(); + analitico.set_Nome(x.get_Nome() ?? ""); + analitico.set_DocumentoCliente(x.get_Documento()); + analitico.set_DiaMes(x.get_Aniversario()); + analitico.set_TipoPessoa((ValidationHelper.OnlyNumber(x.get_Documento()).Length > 11 ? "JURÍDICA" : "FÍSICA")); + analitico.set_Nascimento(x.get_Nascimento()); + analitico.set_VencimentoHabilitacao(x.get_VencimentoCnh()); + analitico.set_Cliente(x); + analitico.set_Cidade(x.get_Cidade()); + analitico.set_Uf(x.get_Estado()); + analitico.set_Cep(x.get_Cep()); + analitico.set_Telefone(x.get_Telefone()); + analitico.set_Email(x.get_Email()); + analitico.set_Profissao(x.get_Profissao()); + return analitico; + }).ToList(); + break; + } + case 6: + { + str1 = "CLIENTES"; + strs1 = new List() + { + "Nome", + "DocumentoCliente", + "Nascimento", + "VencimentoHabilitacao" + }; + List clientesAtivosInativos1 = this._clientesCnh; + list = clientesAtivosInativos1.Select((ClientesAtivosInativos x) => { + Analitico analitico = new Analitico(); + analitico.set_Nome(x.get_Nome() ?? ""); + analitico.set_DocumentoCliente(x.get_Documento()); + analitico.set_Nascimento(x.get_Nascimento()); + analitico.set_VencimentoHabilitacao(x.get_VencimentoCnh()); + analitico.set_Cliente(x); + return analitico; + }).ToList(); + break; + } + case 7: + { + str = "APÓLICES À VENCER"; + List documentos9 = this._documentosVencimento; + IOrderedEnumerable vigencia14 = + from x in documentos9 + orderby x.get_Vigencia1() + select x; + list = vigencia14.Select((Documento x) => { + object description; + Analitico analitico = new Analitico(); + analitico.set_Nome(x.get_Controle().get_Cliente().get_Nome() ?? ""); + analitico.set_Apolice(x.get_Apolice() ?? ""); + analitico.set_Endosso(x.get_Endosso() ?? ""); + analitico.set_Comissao(x.get_Comissao()); + NegocioCorretora? negocioCorretora = x.get_NegocioCorretora(); + if (!negocioCorretora.HasValue) + { + description = ValidationHelper.GetDescription(x.get_Negocio()); + } + else + { + negocioCorretora = x.get_NegocioCorretora(); + description = (negocioCorretora.HasValue ? ValidationHelper.GetDescription(negocioCorretora.GetValueOrDefault()) : null) ?? ""; + } + analitico.set_Negocio((string)description); + analitico.set_PremioLiquido(x.get_PremioLiquido()); + analitico.set_PremioTotal(x.get_PremioTotal()); + analitico.set_VigenciaFinal(x.get_Vigencia2()); + analitico.set_VigenciaInicial(x.get_Vigencia1()); + analitico.set_Status(ValidationHelper.GetDescription(x.get_Situacao()) ?? ""); + analitico.set_Seguradora(x.get_Controle().get_Seguradora().get_NomeSocial()); + analitico.set_Ramo(x.get_Controle().get_Ramo().get_Nome()); + ClientesAtivosInativos clientesAtivosInativo = new ClientesAtivosInativos(); + clientesAtivosInativo.set_Id(x.get_Controle().get_Cliente().get_Id()); + clientesAtivosInativo.set_Nome(x.get_Controle().get_Cliente().get_Nome()); + analitico.set_Cliente(clientesAtivosInativo); + analitico.set_Documento(x); + return analitico; + }).ToList(); + break; + } + case 8: + { + List strs3 = new List() + { + "Nome", + "Apolice", + "Endosso", + "Seguradora", + "Comissao", + "Vencimento", + "Recebimento", + "Valor", + "ComissaoGerada", + "NumeroParcela", + "Ramo" + }; + strs1 = strs3; + str = "PARCELAS À VENCER"; + str1 = "PARCELAS"; + List parcelas = this._parcelasVencimento; + IOrderedEnumerable vencimento = + from x in parcelas + orderby x.get_Vencimento() + select x; + list = vencimento.Select((Parcela x) => { + Analitico analitico = new Analitico(); + analitico.set_Nome(x.get_Documento().get_Controle().get_Cliente().get_Nome() ?? ""); + analitico.set_Apolice(x.get_Documento().get_Apolice() ?? ""); + analitico.set_Endosso(x.get_Documento().get_Endosso() ?? ""); + analitico.set_Comissao(x.get_Comissao()); + analitico.set_Seguradora(x.get_Documento().get_Controle().get_Seguradora().get_NomeSocial()); + analitico.set_Ramo(x.get_Documento().get_Controle().get_Ramo().get_Nome()); + analitico.set_Vencimento(x.get_Vencimento()); + analitico.set_Recebimento(x.get_DataRecebimento()); + analitico.set_Valor(x.get_Valor()); + analitico.set_ValorComissao(x.get_ValorComDesconto()); + analitico.set_NumeroParcela(x.get_NumeroParcela()); + ClientesAtivosInativos clientesAtivosInativo = new ClientesAtivosInativos(); + clientesAtivosInativo.set_Id(x.get_Documento().get_Controle().get_Cliente().get_Id()); + clientesAtivosInativo.set_Nome(x.get_Documento().get_Controle().get_Cliente().get_Nome()); + analitico.set_Cliente(clientesAtivosInativo); + analitico.set_Documento(x.get_Documento()); + analitico.set_Parcela(x); + return analitico; + }).ToList(); + break; + } + case 9: + { + str = "APÓLICES PENDENTES"; + List documentos10 = this._documentosPendentes; + IEnumerable documentos11 = documentos10.Where((Documento x) => { + if (!string.IsNullOrEmpty(x.get_Apolice())) + { + return false; + } + return x.get_Tipo() != 2; + }); + IOrderedEnumerable vigencia15 = + from x in documentos11 + orderby x.get_Vigencia1() + select x; + list = vigencia15.Select((Documento x) => { + object description; + Analitico analitico = new Analitico(); + analitico.set_Nome(x.get_Controle().get_Cliente().get_Nome() ?? ""); + analitico.set_Apolice(x.get_Apolice() ?? ""); + analitico.set_Endosso(x.get_Endosso() ?? ""); + analitico.set_Comissao(x.get_Comissao()); + NegocioCorretora? negocioCorretora = x.get_NegocioCorretora(); + if (!negocioCorretora.HasValue) + { + description = ValidationHelper.GetDescription(x.get_Negocio()); + } + else + { + negocioCorretora = x.get_NegocioCorretora(); + description = (negocioCorretora.HasValue ? ValidationHelper.GetDescription(negocioCorretora.GetValueOrDefault()) : null) ?? ""; + } + analitico.set_Negocio((string)description); + analitico.set_PremioLiquido(x.get_PremioLiquido()); + analitico.set_PremioTotal(x.get_PremioTotal()); + analitico.set_VigenciaFinal(x.get_Vigencia2()); + analitico.set_VigenciaInicial(x.get_Vigencia1()); + analitico.set_Status(ValidationHelper.GetDescription(x.get_Situacao()) ?? ""); + analitico.set_Seguradora(x.get_Controle().get_Seguradora().get_NomeSocial()); + analitico.set_Ramo(x.get_Controle().get_Ramo().get_Nome()); + ClientesAtivosInativos clientesAtivosInativo = new ClientesAtivosInativos(); + clientesAtivosInativo.set_Id(x.get_Controle().get_Cliente().get_Id()); + clientesAtivosInativo.set_Nome(x.get_Controle().get_Cliente().get_Nome()); + analitico.set_Cliente(clientesAtivosInativo); + analitico.set_Documento(x); + return analitico; + }).ToList(); + break; + } + case 10: + { + List strs4 = new List() + { + "Nome", + "Apolice", + "Endosso", + "Seguradora", + "Comissao", + "Vencimento", + "Valor", + "NumeroParcela", + "Ramo" + }; + strs1 = strs4; + str = "PARCELAS PENDENTES"; + str1 = "PARCELAS"; + List parcelas1 = this._parcelasPendencia; + IOrderedEnumerable vencimento1 = + from x in parcelas1 + orderby x.get_Vencimento() + select x; + list = vencimento1.Select((Parcela x) => { + Analitico analitico = new Analitico(); + analitico.set_Nome(x.get_Documento().get_Controle().get_Cliente().get_Nome() ?? ""); + analitico.set_Apolice(x.get_Documento().get_Apolice() ?? ""); + analitico.set_Endosso(x.get_Documento().get_Endosso() ?? ""); + analitico.set_Comissao(x.get_Comissao()); + analitico.set_Seguradora(x.get_Documento().get_Controle().get_Seguradora().get_NomeSocial()); + analitico.set_Ramo(x.get_Documento().get_Controle().get_Ramo().get_Nome()); + analitico.set_Vencimento(x.get_Vencimento()); + analitico.set_Recebimento(x.get_DataRecebimento()); + analitico.set_Valor(x.get_Valor()); + analitico.set_ValorComissao(x.get_ValorComissao()); + analitico.set_NumeroParcela(x.get_NumeroParcela()); + ClientesAtivosInativos clientesAtivosInativo = new ClientesAtivosInativos(); + clientesAtivosInativo.set_Id(x.get_Documento().get_Controle().get_Cliente().get_Id()); + clientesAtivosInativo.set_Nome(x.get_Documento().get_Controle().get_Cliente().get_Nome()); + analitico.set_Cliente(clientesAtivosInativo); + analitico.set_Documento(x.get_Documento()); + analitico.set_Parcela(x); + return analitico; + }).ToList(); + break; + } + case 11: + { + str = "ENDOSSOS"; + List documentos12 = this._documentosProducao; + IEnumerable documentos13 = + from x in documentos12 + where x.get_Tipo() == 1 + select x; + IOrderedEnumerable vigencia16 = + from x in documentos13 + orderby x.get_Vigencia1() + select x; + list = vigencia16.Select((Documento x) => { + object description; + Analitico analitico = new Analitico(); + analitico.set_Nome(x.get_Controle().get_Cliente().get_Nome() ?? ""); + analitico.set_Apolice(x.get_Apolice() ?? ""); + analitico.set_Endosso(x.get_Endosso() ?? ""); + analitico.set_Comissao(x.get_Comissao()); + NegocioCorretora? negocioCorretora = x.get_NegocioCorretora(); + if (!negocioCorretora.HasValue) + { + description = ValidationHelper.GetDescription(x.get_Negocio()); + } + else + { + negocioCorretora = x.get_NegocioCorretora(); + description = (negocioCorretora.HasValue ? ValidationHelper.GetDescription(negocioCorretora.GetValueOrDefault()) : null) ?? ""; + } + analitico.set_Negocio((string)description); + analitico.set_PremioLiquido(x.get_PremioLiquido()); + analitico.set_PremioTotal(x.get_PremioTotal()); + analitico.set_VigenciaFinal(x.get_Vigencia2()); + analitico.set_VigenciaInicial(x.get_Vigencia1()); + analitico.set_Status(ValidationHelper.GetDescription(x.get_Situacao()) ?? ""); + analitico.set_Seguradora(x.get_Controle().get_Seguradora().get_NomeSocial()); + analitico.set_Ramo(x.get_Controle().get_Ramo().get_Nome()); + ClientesAtivosInativos clientesAtivosInativo = new ClientesAtivosInativos(); + clientesAtivosInativo.set_Id(x.get_Controle().get_Cliente().get_Id()); + clientesAtivosInativo.set_Nome(x.get_Controle().get_Cliente().get_Nome()); + analitico.set_Cliente(clientesAtivosInativo); + analitico.set_Documento(x); + return analitico; + }).ToList(); + break; + } + case 12: + { + str = "FATURAS"; + List documentos14 = this._documentosProducao; + IEnumerable documentos15 = + from x in documentos14 + where x.get_Tipo() == 2 + select x; + IOrderedEnumerable vigencia17 = + from x in documentos15 + orderby x.get_Vigencia1() + select x; + list = vigencia17.Select((Documento x) => { + object description; + Analitico analitico = new Analitico(); + analitico.set_Nome(x.get_Controle().get_Cliente().get_Nome() ?? ""); + analitico.set_Apolice(x.get_Apolice() ?? ""); + analitico.set_Endosso(x.get_Endosso() ?? ""); + analitico.set_Comissao(x.get_Comissao()); + NegocioCorretora? negocioCorretora = x.get_NegocioCorretora(); + if (!negocioCorretora.HasValue) + { + description = ValidationHelper.GetDescription(x.get_Negocio()); + } + else + { + negocioCorretora = x.get_NegocioCorretora(); + description = (negocioCorretora.HasValue ? ValidationHelper.GetDescription(negocioCorretora.GetValueOrDefault()) : null) ?? ""; + } + analitico.set_Negocio((string)description); + analitico.set_PremioLiquido(x.get_PremioLiquido()); + analitico.set_PremioTotal(x.get_PremioTotal()); + analitico.set_VigenciaFinal(x.get_Vigencia2()); + analitico.set_VigenciaInicial(x.get_Vigencia1()); + analitico.set_Status(ValidationHelper.GetDescription(x.get_Situacao()) ?? ""); + analitico.set_Seguradora(x.get_Controle().get_Seguradora().get_NomeSocial()); + analitico.set_Ramo(x.get_Controle().get_Ramo().get_Nome()); + ClientesAtivosInativos clientesAtivosInativo = new ClientesAtivosInativos(); + clientesAtivosInativo.set_Id(x.get_Controle().get_Cliente().get_Id()); + clientesAtivosInativo.set_Nome(x.get_Controle().get_Cliente().get_Nome()); + analitico.set_Cliente(clientesAtivosInativo); + analitico.set_Documento(x); + return analitico; + }).ToList(); + break; + } + case 13: + { + str = "TOTAL DOCUMENTOS"; + List documentos16 = this._documentosProducao; + IEnumerable documentos17 = + from x in documentos16 + where x.get_Tipo() != 2 + select x; + IOrderedEnumerable vigencia18 = + from x in documentos17 + orderby x.get_Vigencia1() + select x; + list = vigencia18.Select((Documento x) => { + object description; + Analitico analitico = new Analitico(); + analitico.set_Nome(x.get_Controle().get_Cliente().get_Nome() ?? ""); + analitico.set_Apolice(x.get_Apolice() ?? ""); + analitico.set_Endosso(x.get_Endosso() ?? ""); + analitico.set_Comissao(x.get_Comissao()); + NegocioCorretora? negocioCorretora = x.get_NegocioCorretora(); + if (!negocioCorretora.HasValue) + { + description = ValidationHelper.GetDescription(x.get_Negocio()); + } + else + { + negocioCorretora = x.get_NegocioCorretora(); + description = (negocioCorretora.HasValue ? ValidationHelper.GetDescription(negocioCorretora.GetValueOrDefault()) : null) ?? ""; + } + analitico.set_Negocio((string)description); + analitico.set_PremioLiquido(x.get_PremioLiquido()); + analitico.set_PremioTotal(x.get_PremioTotal()); + analitico.set_VigenciaFinal(x.get_Vigencia2()); + analitico.set_VigenciaInicial(x.get_Vigencia1()); + analitico.set_Status(ValidationHelper.GetDescription(x.get_Situacao()) ?? ""); + analitico.set_Seguradora(x.get_Controle().get_Seguradora().get_NomeSocial()); + analitico.set_Ramo(x.get_Controle().get_Ramo().get_Nome()); + ClientesAtivosInativos clientesAtivosInativo = new ClientesAtivosInativos(); + clientesAtivosInativo.set_Id(x.get_Controle().get_Cliente().get_Id()); + clientesAtivosInativo.set_Nome(x.get_Controle().get_Cliente().get_Nome()); + analitico.set_Cliente(clientesAtivosInativo); + analitico.set_Documento(x); + return analitico; + }).ToList(); + break; + } + case 14: + { + str = "PRODUÇÃO ANTERIOR"; + List documentos18 = this._documentosFechamento; + list = documentos18.Select((Documento x) => { + object description; + Analitico analitico = new Analitico(); + analitico.set_Nome(x.get_Controle().get_Cliente().get_Nome() ?? ""); + analitico.set_Apolice(x.get_Apolice() ?? ""); + analitico.set_Endosso(x.get_Endosso() ?? ""); + analitico.set_Comissao(x.get_Comissao()); + NegocioCorretora? negocioCorretora = x.get_NegocioCorretora(); + if (!negocioCorretora.HasValue) + { + description = ValidationHelper.GetDescription(x.get_Negocio()); + } + else + { + negocioCorretora = x.get_NegocioCorretora(); + description = (negocioCorretora.HasValue ? ValidationHelper.GetDescription(negocioCorretora.GetValueOrDefault()) : null) ?? ""; + } + analitico.set_Negocio((string)description); + analitico.set_PremioLiquido(x.get_PremioLiquido()); + analitico.set_PremioTotal(x.get_PremioTotal()); + analitico.set_VigenciaFinal(x.get_Vigencia2()); + analitico.set_VigenciaInicial(x.get_Vigencia1()); + analitico.set_Status(ValidationHelper.GetDescription(x.get_Situacao()) ?? ""); + analitico.set_Seguradora(x.get_Controle().get_Seguradora().get_NomeSocial()); + analitico.set_Ramo(x.get_Controle().get_Ramo().get_Nome()); + ClientesAtivosInativos clientesAtivosInativo = new ClientesAtivosInativos(); + clientesAtivosInativo.set_Id(x.get_Controle().get_Cliente().get_Id()); + clientesAtivosInativo.set_Nome(x.get_Controle().get_Cliente().get_Nome()); + analitico.set_Cliente(clientesAtivosInativo); + analitico.set_Documento(x); + return analitico; + }).ToList(); + break; + } + default: + { + str = "PRODUÇÃO"; + List documentos19 = this._documentosProducao; + list = documentos19.Select((Documento x) => { + object description; + Analitico analitico = new Analitico(); + analitico.set_Nome(x.get_Controle().get_Cliente().get_Nome() ?? ""); + analitico.set_Apolice(x.get_Apolice() ?? ""); + analitico.set_Endosso(x.get_Endosso() ?? ""); + analitico.set_Comissao(x.get_Comissao()); + NegocioCorretora? negocioCorretora = x.get_NegocioCorretora(); + if (!negocioCorretora.HasValue) + { + description = ValidationHelper.GetDescription(x.get_Negocio()); + } + else + { + negocioCorretora = x.get_NegocioCorretora(); + description = (negocioCorretora.HasValue ? ValidationHelper.GetDescription(negocioCorretora.GetValueOrDefault()) : null) ?? ""; + } + analitico.set_Negocio((string)description); + analitico.set_PremioLiquido(x.get_PremioLiquido()); + analitico.set_PremioTotal(x.get_PremioTotal()); + analitico.set_VigenciaFinal(x.get_Vigencia2()); + analitico.set_VigenciaInicial(x.get_Vigencia1()); + analitico.set_Status(ValidationHelper.GetDescription(x.get_Situacao()) ?? ""); + analitico.set_Seguradora(x.get_Controle().get_Seguradora().get_NomeSocial()); + analitico.set_Ramo(x.get_Controle().get_Ramo().get_Nome()); + ClientesAtivosInativos clientesAtivosInativo = new ClientesAtivosInativos(); + clientesAtivosInativo.set_Id(x.get_Controle().get_Cliente().get_Id()); + clientesAtivosInativo.set_Nome(x.get_Controle().get_Cliente().get_Nome()); + analitico.set_Cliente(clientesAtivosInativo); + analitico.set_Documento(x); + return analitico; + }).ToList(); + break; + } + } + if (list.Count != 0) + { + (new HosterWindow(new DialogAnaliticoBi(str, list, str1, strs1), "ANALÍTICO", new double?((double)1260), new double?((double)500), false)).Show(); + } + else + { + await base.ShowMessage("NÃO FOI POSSÍVEL DETALHAR POIS NÃO HÁ DADOS", "OK", "", false); + } + } + + public async Task GerarClientes() + { + long num; + this.IsVisibleClientes = Visibility.Collapsed; + Filtros filtro = new Filtros(); + filtro.set_Inicio(this.InicioClientes); + filtro.set_Fim(this.FimClientes); + num = (Recursos.Usuario.get_IdEmpresa() == (long)1 ? (long)0 : Recursos.Usuario.get_IdEmpresa()); + filtro.set_IdEmpresa(num); + Filtros filtro1 = filtro; + this._clientesAniversariantes = await this._clienteServico.BuscarAniversariantes(filtro1); + this.Aniversariantes = this._clientesAniversariantes.Count; + this._clientesCnh = await this._clienteServico.BuscarVencimentosCnh(filtro1); + this.VencimentoCnh = this._clientesCnh.Count; + this.IsVisibleClientes = Visibility.Visible; + filtro1 = null; + } + + public async Task GerarPendencia() + { + long num; + this.IsVisiblePendencia = Visibility.Collapsed; + List vendedorUsuarios = await (new VendedorUsuarioServico()).FindByVinculo(Recursos.Usuario); + Filtros filtro = new Filtros(); + filtro.set_Inicio(this.Inicio); + filtro.set_Fim(this.Fim); + num = (Recursos.Usuario.get_IdEmpresa() == (long)1 ? (long)0 : Recursos.Usuario.get_IdEmpresa()); + filtro.set_IdEmpresa(num); + List vendedorUsuarios1 = vendedorUsuarios; + filtro.set_Vendedores(( + from x in vendedorUsuarios1 + select x.get_Vendedor().get_Id()).ToList()); + List parcelas = await this._parcelaServico.BuscarParcelasPendentes(filtro, false); + PainelBiViewModel list = this; + List parcelas1 = parcelas; + list._parcelasPendencia = ( + from x in parcelas1 + where x.get_Documento().get_Situacao() != 7 + select x).ToList(); + this.ParcelasPendentes = this._parcelasPendencia.Count; + this.IsVisiblePendencia = Visibility.Visible; + } + + public async Task GerarProducao() + { + long num2; + long num3; + this.IsVisibleProducao = Visibility.Collapsed; + PainelBiViewModel painelBiViewModel = this; + Grafico grafico = new Grafico() + { + Series = new SeriesCollection(), + Formatter = (double value) => value.ToString("C0") + }; + painelBiViewModel.Producao = grafico; + PainelBiViewModel painelBiViewModel1 = this; + Grafico grafico1 = new Grafico() + { + Series = new SeriesCollection(), + Formatter = (double value) => value.ToString("C2") + }; + painelBiViewModel1.Gerada = grafico1; + PainelBiViewModel painelBiViewModel2 = this; + Grafico grafico2 = new Grafico() + { + Series = new SeriesCollection(), + Formatter = (double value) => value.ToString("P2") + }; + painelBiViewModel2.MediaComissao = grafico2; + PainelBiViewModel painelBiViewModel3 = this; + Grafico grafico3 = new Grafico() + { + Series = new SeriesCollection(), + Formatter = (double value) => value.ToString("C2") + }; + painelBiViewModel3.Fechamento = grafico3; + List vendedorUsuarios = await (new VendedorUsuarioServico()).FindByVinculo(Recursos.Usuario); + Filtros filtro = new Filtros(); + filtro.set_Inicio(this.Inicio); + filtro.set_Fim(this.Fim); + num2 = (Recursos.Usuario.get_IdEmpresa() == (long)1 ? (long)0 : Recursos.Usuario.get_IdEmpresa()); + filtro.set_IdEmpresa(num2); + List vendedorUsuarios1 = vendedorUsuarios; + filtro.set_Vendedores(( + from x in vendedorUsuarios1 + select x.get_Vendedor().get_Id()).ToList()); + Filtros filtro1 = filtro; + Filtros filtro2 = new Filtros(); + DateTime inicio = this.Inicio; + filtro2.set_Inicio(inicio.AddYears(-1)); + inicio = this.Fim; + filtro2.set_Fim(inicio.AddYears(-1)); + num3 = (Recursos.Usuario.get_IdEmpresa() == (long)1 ? (long)0 : Recursos.Usuario.get_IdEmpresa()); + filtro2.set_IdEmpresa(num3); + List vendedorUsuarios2 = vendedorUsuarios; + filtro2.set_Vendedores(( + from x in vendedorUsuarios2 + select x.get_Vendedor().get_Id()).ToList()); + Filtros filtro3 = filtro2; + List documentos = await this._apoliceServico.BuscarApolices(filtro1, false, true); + PainelBiViewModel list = this; + List documentos1 = documentos; + list._documentosProducao = ( + from x in documentos1 + where x.get_Situacao() != 7 + select x).ToList(); + this._documentosPendentes = await this._apoliceServico.BuscarApolicesPendentes(filtro1); + List documentos2 = await this._parcelaServico.BuscarFaturas(filtro1, false, true); + List documentos3 = this._documentosProducao; + List documentos4 = documentos2; + documentos3.AddRange( + from x in documentos4 + where x.get_Situacao() != 7 + select x); + PainelBiViewModel painelBiViewModel4 = this; + List documentos5 = this._documentosPendentes; + painelBiViewModel4.ApolicesPendentes = documentos5.Count((Documento x) => { + if (!string.IsNullOrEmpty(x.get_Apolice())) + { + return false; + } + return x.get_Tipo() != 2; + }); + await this.GerarPendencia(); + List documentos6 = await this._apoliceServico.BuscarApolices(filtro3, false, true); + PainelBiViewModel list1 = this; + List documentos7 = documentos6; + list1._documentosFechamento = ( + from x in documentos7 + where x.get_Situacao() != 7 + select x).ToList(); + List documentos8 = await this._parcelaServico.BuscarFaturas(filtro3, false, true); + List documentos9 = this._documentosFechamento; + List documentos10 = documentos8; + documentos9.AddRange( + from x in documentos10 + where x.get_Situacao() != 7 + select x); + this.Cotacoes = await this._apoliceServico.Cotacoes(filtro1); + PainelBiViewModel painelBiViewModel5 = this; + List documentos11 = this._documentosProducao; + painelBiViewModel5.QuatidadeProducao = documentos11.Count((Documento x) => x.get_Tipo() != 2); + PainelBiViewModel painelBiViewModel6 = this; + List documentos12 = this._documentosProducao; + painelBiViewModel6.Faturas = documentos12.Count((Documento x) => x.get_Tipo() == 2); + PainelBiViewModel painelBiViewModel7 = this; + List documentos13 = this._documentosProducao; + painelBiViewModel7.NovosNegocios = documentos13.Count((Documento x) => { + if (x.get_Tipo() != 0) + { + return false; + } + if (x.get_Situacao() == 1) + { + return true; + } + if (x.get_Situacao() != 2) + { + return false; + } + NegocioCorretora? negocioCorretora = x.get_NegocioCorretora(); + return negocioCorretora.GetValueOrDefault() == 0 & negocioCorretora.HasValue; + }); + PainelBiViewModel painelBiViewModel8 = this; + List documentos14 = this._documentosProducao; + painelBiViewModel8.Renovacoes = documentos14.Count((Documento x) => { + if (x.get_Tipo() != 0) + { + return false; + } + if (x.get_Situacao() != 2) + { + return false; + } + if (x.get_NegocioCorretora().GetValueOrDefault() == 1) + { + return true; + } + return x.get_Negocio().GetValueOrDefault() == 1; + }); + PainelBiViewModel painelBiViewModel9 = this; + List documentos15 = this._documentosProducao; + IEnumerable documentos16 = documentos15.Where((Documento x) => { + if (x.get_Situacao() != 3) + { + return false; + } + return x.get_Tipo() == 1; + }); + painelBiViewModel9.Cancelamentos = ( + from x in documentos16 + select x.get_Controle().get_Id()).Distinct().Count(); + PainelBiViewModel painelBiViewModel10 = this; + List documentos17 = this._documentosProducao; + painelBiViewModel10.Endossos = documentos17.Count((Documento x) => x.get_Tipo() == 1); + PainelBiViewModel painelBiViewModel11 = this; + List documentos18 = this._documentosProducao; + painelBiViewModel11.ProducaoTotal = documentos18.Sum((Documento x) => x.get_PremioLiquido()); + PainelBiViewModel painelBiViewModel12 = this; + List documentos19 = this._documentosFechamento; + painelBiViewModel12.ProducaoTotalAnterior = documentos19.Sum((Documento x) => x.get_PremioLiquido()); + PainelBiViewModel painelBiViewModel13 = this; + List documentos20 = this._documentosProducao; + painelBiViewModel13.ComissaoTotal = documentos20.Sum((Documento x) => ((x.get_PremioLiquido() + (x.get_AdicionalComiss() ? x.get_PremioAdicional() : decimal.Zero)) * x.get_Comissao()) * new decimal(1, 0, 0, false, 2)); + List documentos21 = this._documentosProducao; + IEnumerable> nomeSocial = + from x in documentos21 + group x by x.get_Controle().get_Seguradora().get_NomeSocial(); + ( + from x in nomeSocial + orderby x.Sum((Documento p) => p.get_PremioLiquido()) descending + select x).ToList>().ForEach((IGrouping x) => { + ColumnSeries columnSeries = new ColumnSeries(); + columnSeries.set_Title(x.Key); + ChartValues chartValue = new ChartValues(); + chartValue.Add(x.Sum((Documento p) => p.get_PremioLiquido())); + columnSeries.set_Values(chartValue); + columnSeries.set_LabelPoint((ChartPoint chartPoint) => { + IGrouping strs = x; + Func u003cu003e9_13631 = PainelBiViewModel.u003cu003ec.u003cu003e9__136_31; + if (u003cu003e9_13631 == null) + { + u003cu003e9_13631 = (Documento p) => p.get_PremioLiquido(); + PainelBiViewModel.u003cu003ec.u003cu003e9__136_31 = u003cu003e9_13631; + } + return string.Concat("R$ ", strs.Sum(u003cu003e9_13631).ToString("N2")); + }); + columnSeries.set_MaxColumnWidth(double.PositiveInfinity); + this.Producao.Series.Add(columnSeries); + decimal num = x.Sum((Documento p) => ((p.get_PremioLiquido() + (p.get_AdicionalComiss() ? p.get_PremioAdicional() : decimal.Zero)) * p.get_Comissao()) * new decimal(1, 0, 0, false, 2)); + PieSeries pieSeries = new PieSeries(); + pieSeries.set_Title(x.Key); + ChartValues chartValue1 = new ChartValues(); + chartValue1.Add((num > decimal.Zero ? num : num * decimal.MinusOne)); + pieSeries.set_Values(chartValue1); + pieSeries.set_DataLabels(false); + pieSeries.set_LabelPoint((ChartPoint chartPoint) => string.Concat("R$ ", num.ToString("N2"))); + this.Gerada.Series.Add(pieSeries); + decimal num1 = Math.Round(x.Sum((Documento p) => p.get_Comissao()) / x.Count(), 2); + PieSeries pieSeries1 = new PieSeries(); + pieSeries1.set_Title(x.Key); + ChartValues chartValue2 = new ChartValues(); + chartValue2.Add(num1); + pieSeries1.set_Values(chartValue2); + pieSeries1.set_DataLabels(false); + pieSeries1.set_LabelPoint((ChartPoint chartPoint) => string.Format(" Media de Comissão {0}% ", num1)); + this.MediaComissao.Series.Add(pieSeries1); + }); + TimeSpan fim = filtro1.get_Fim() - filtro1.get_Inicio(); + double totalDays = fim.TotalDays; + ChartValues chartValue3 = new ChartValues(); + ChartValues chartValue4 = new ChartValues(); + for (int i = 0; (double)i <= totalDays; i++) + { + inicio = filtro1.get_Inicio(); + DateTime dateTime = inicio.AddDays((double)i); + DateTime dateTime1 = dateTime.AddYears(-1); + IEnumerable vigencia1 = + from s in this._documentosFechamento + where s.get_Vigencia1() == dateTime1 + select s; + decimal num4 = vigencia1.Sum((Documento s) => s.get_PremioLiquido()); + IEnumerable vigencia11 = + from s in this._documentosProducao + where s.get_Vigencia1() == dateTime + select s; + decimal num5 = vigencia11.Sum((Documento s) => s.get_PremioLiquido()); + chartValue3.Add(new DateTimePoint(dateTime, (double)((double)num4))); + chartValue4.Add(new DateTimePoint(dateTime, (double)((double)num5))); + } + LineSeries lineSeries = new LineSeries(); + inicio = filtro3.get_Inicio(); + lineSeries.set_Title(string.Format("{0}", inicio.Year)); + lineSeries.set_Values(chartValue3); + LineSeries lineSeries1 = lineSeries; + LineSeries lineSeries2 = new LineSeries(); + inicio = filtro1.get_Inicio(); + lineSeries2.set_Title(string.Format("{0}", inicio.Year)); + lineSeries2.set_Values(chartValue4); + LineSeries lineSeries3 = lineSeries2; + this.Fechamento.Series.Add(lineSeries1); + this.Fechamento.Series.Add(lineSeries3); + PainelBiViewModel str = this; + str.XFormatter = (double val) => (new DateTime((long)val)).ToString("dd/MM"); + PainelBiViewModel str1 = this; + str1.YFormatter = (double val) => val.ToString("C2"); + this.IsVisibleProducao = Visibility.Visible; + filtro1 = null; + filtro3 = null; + } + + public async Task GerarVencimento() + { + long num; + this.IsVisibleVencimento = Visibility.Collapsed; + List vendedorUsuarios = await (new VendedorUsuarioServico()).FindByVinculo(Recursos.Usuario); + Filtros filtro = new Filtros(); + filtro.set_Inicio(this.InicioVencimento); + filtro.set_Fim(this.FimVencimento); + num = (Recursos.Usuario.get_IdEmpresa() == (long)1 ? (long)0 : Recursos.Usuario.get_IdEmpresa()); + filtro.set_IdEmpresa(num); + List vendedorUsuarios1 = vendedorUsuarios; + filtro.set_Vendedores(( + from x in vendedorUsuarios1 + select x.get_Vendedor().get_Id()).ToList()); + Filtros filtro1 = filtro; + List documentos = await this._apoliceServico.BuscarApolicesVigenciaFinal(filtro1, false); + PainelBiViewModel list = this; + List documentos1 = documentos; + list._documentosVencimento = ( + from x in documentos1 + where x.get_Situacao() != 7 + select x).ToList(); + this.Vencimentos = this._documentosVencimento.Count; + List parcelas = await this._parcelaServico.BuscarParcelas(filtro1, false); + PainelBiViewModel painelBiViewModel = this; + List parcelas1 = parcelas; + painelBiViewModel._parcelasVencimento = ( + from x in parcelas1 + where x.get_Documento().get_Situacao() != 7 + select x).ToList(); + this.ParcelasAVencer = this._parcelasVencimento.Count; + this.IsVisibleVencimento = Visibility.Visible; + filtro1 = null; + } + + private async void LoadInicial() + { + await this.GerarProducao(); + await this.GerarVencimento(); + await this.GerarClientes(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/BI/ProspeccaoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/BI/ProspeccaoViewModel.cs new file mode 100644 index 0000000..4839d95 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/BI/ProspeccaoViewModel.cs @@ -0,0 +1,553 @@ +using ClosedXML.Excel; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; + +namespace Gestor.Application.ViewModels.BI +{ + public class ProspeccaoViewModel : BaseViewModel + { + private readonly ProspeccaoServico _servico; + + private PermissaoUsuario SelectedPermissaoUsuario; + + private ObservableCollection _vendedores; + + private Vendedor _selectedVendedor = new Vendedor(); + + private List _searchStatus = new List() + { + "TODOS", + ValidationHelper.GetDescription((StatusProspeccao)1), + ValidationHelper.GetDescription((StatusProspeccao)5), + ValidationHelper.GetDescription((StatusProspeccao)2), + ValidationHelper.GetDescription((StatusProspeccao)4), + ValidationHelper.GetDescription((StatusProspeccao)3) + }; + + private string _selectedStatusSearch = "AGENDANDO"; + + private StatusProspeccao? _selectedStatus; + + private ObservableCollection _statusProspeccaoPersonalizado; + + private DateTime _inicio = Funcoes.GetNetworkTime().Date; + + private DateTime _fim = Funcoes.GetNetworkTime().Date.AddDays(7); + + private ObservableCollection _prospeccoesFiltradas; + + private Gestor.Model.Domain.Seguros.Prospeccao _selectedProspeccao; + + private ObservableCollection _prospeccao; + + private bool _naoHaDados; + + public DateTime Fim + { + get + { + return this._fim; + } + set + { + this._fim = value; + base.OnPropertyChanged("Fim"); + } + } + + public DateTime Inicio + { + get + { + return this._inicio; + } + set + { + this._inicio = value; + base.OnPropertyChanged("Inicio"); + } + } + + public bool NaoHaDados + { + get + { + return this._naoHaDados; + } + set + { + this._naoHaDados = value; + base.OnPropertyChanged("NaoHaDados"); + } + } + + public ObservableCollection Prospeccao + { + get + { + return this._prospeccao; + } + set + { + this._prospeccao = value; + this.NaoHaDados = (value == null ? true : value.Count == 0); + base.OnPropertyChanged("Prospeccao"); + } + } + + public AutoCompleteFilterPredicate ProspeccaoItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_530 = ProspeccaoViewModel.u003cu003ec.u003cu003e9__53_0; + if (u003cu003e9_530 == null) + { + u003cu003e9_530 = new AutoCompleteFilterPredicate(ProspeccaoViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (((Gestor.Model.Domain.Seguros.Prospeccao)obj).get_Nome().ToUpper().Contains(searchText.ToUpper()) || ((Gestor.Model.Domain.Seguros.Prospeccao)obj).get_Documento().ToString().ToUpper().Contains(searchText.ToUpper()) || ((Gestor.Model.Domain.Seguros.Prospeccao)obj).get_Telefone1().ToString().ToUpper().Contains(searchText.ToUpper()) || ((Gestor.Model.Domain.Seguros.Prospeccao)obj).get_Telefone2().ToString().ToUpper().Contains(searchText.ToUpper()) || ((Gestor.Model.Domain.Seguros.Prospeccao)obj).get_Email().ToString().ToUpper().Contains(searchText.ToUpper())) + { + return true; + } + return ((Gestor.Model.Domain.Seguros.Prospeccao)obj).get_VigenciaFinal().ToString().ToUpper().Contains(searchText.ToUpper()); + }); + ProspeccaoViewModel.u003cu003ec.u003cu003e9__53_0 = u003cu003e9_530; + } + return u003cu003e9_530; + } + } + + public List Prospeccoes + { + get; + set; + } + + public ObservableCollection ProspeccoesFiltradas + { + get + { + return this._prospeccoesFiltradas; + } + set + { + this._prospeccoesFiltradas = value; + base.OnPropertyChanged("ProspeccoesFiltradas"); + } + } + + public List SearchStatus + { + get + { + return this._searchStatus; + } + set + { + this._searchStatus = value; + this.SelectedStatusSearch = value[1]; + base.OnPropertyChanged("SearchStatus"); + } + } + + public Gestor.Model.Domain.Seguros.Prospeccao SelectedProspeccao + { + get + { + return this._selectedProspeccao; + } + set + { + this._selectedProspeccao = value; + base.OnPropertyChanged("SelectedProspeccao"); + } + } + + public StatusProspeccao? SelectedStatus + { + get + { + return this._selectedStatus; + } + set + { + this._selectedStatus = value; + base.OnPropertyChanged("SelectedStatus"); + } + } + + public string SelectedStatusSearch + { + get + { + return this._selectedStatusSearch; + } + set + { + this._selectedStatusSearch = value; + if (value == "AGENDADO") + { + this.SelectedStatus = new StatusProspeccao?(1); + } + else if (value == "GANHO") + { + this.SelectedStatus = new StatusProspeccao?(2); + } + else if (value == "PERDIDO") + { + this.SelectedStatus = new StatusProspeccao?(3); + } + else if (value == "NÃO TRABALHADO") + { + this.SelectedStatus = new StatusProspeccao?(4); + } + else if (value == "EM ANDAMENTO") + { + this.SelectedStatus = new StatusProspeccao?(5); + } + else + { + this.SelectedStatus = null; + } + base.OnPropertyChanged("SelectedStatusSearch"); + } + } + + public Vendedor SelectedVendedor + { + get + { + return this._selectedVendedor; + } + set + { + this._selectedVendedor = value; + base.OnPropertyChanged("SelectedVendedor"); + } + } + + public ObservableCollection StatusProspeccaoPersonalizado + { + get + { + return this._statusProspeccaoPersonalizado; + } + set + { + this._statusProspeccaoPersonalizado = value; + base.OnPropertyChanged("StatusProspeccaoPersonalizado"); + } + } + + public ObservableCollection Vendedores + { + get + { + return this._vendedores; + } + set + { + this._vendedores = value; + base.OnPropertyChanged("Vendedores"); + } + } + + public ProspeccaoViewModel() + { + this._servico = new ProspeccaoServico(); + this.StatusProspeccaoPersonalizado = new ObservableCollection(( + from x in Recursos.StatusProspeccao + where x.get_Ativo() + select x).ToList()); + this.CarregaVendedores(); + this.SelectedStatusSearch = this.SearchStatus[1]; + this.CarregaProspeccoes(); + } + + public async Task BuscaPermissao(string Tipo) + { + bool flag; + ProspeccaoViewModel prospeccaoViewModel = this; + if (Recursos.Usuario.get_Administrador()) + { + flag = true; + } + else if (Tipo == "Alterar" && prospeccaoViewModel.SelectedPermissaoUsuario != null && !prospeccaoViewModel.SelectedPermissaoUsuario.get_Alterar()) + { + flag = false; + } + else if (!(Tipo == "Excluir") || prospeccaoViewModel.SelectedPermissaoUsuario == null || prospeccaoViewModel.SelectedPermissaoUsuario.get_Excluir()) + { + flag = (!(Tipo == "Incluir") || prospeccaoViewModel.SelectedPermissaoUsuario == null || prospeccaoViewModel.SelectedPermissaoUsuario.get_Incluir() ? true : false); + } + else + { + flag = false; + } + return flag; + } + + public async Task CarregaProspeccao() + { + ProspeccaoViewModel observableCollection = this; + if (observableCollection.ProspeccoesFiltradas != null) + { + observableCollection.ProspeccoesFiltradas = new ObservableCollection(observableCollection.ProspeccoesFiltradas.ToList()); + } + } + + public async void CarregaProspeccoes() + { + await this.CarregarProspeccoes(); + } + + public async Task CarregarPermissao() + { + this.SelectedPermissaoUsuario = await this.ServicoPermissUsuario.VerificarPermissao(Recursos.Usuario, 60); + } + + public async Task CarregarProspeccoes() + { + if (this.Inicio <= this.Fim) + { + base.Loading(true); + base.IsVisible = Visibility.Collapsed; + this.Prospeccoes = await this._servico.BuscarProspeccoes(this.SelectedVendedor.get_Id(), this.Inicio, this.Fim, this.SelectedStatus); + ProspeccaoViewModel observableCollection = this; + List prospeccoes = this.Prospeccoes; + observableCollection.ProspeccoesFiltradas = new ObservableCollection( + from x in prospeccoes + orderby x.get_VigenciaFinal() + select x); + this.SelectedProspeccao = this.ProspeccoesFiltradas.FirstOrDefault(); + base.IsVisible = Visibility.Visible; + base.Loading(false); + } + } + + public async Task CarregarVendedores() + { + List vendedorUsuarios = await (new VendedorUsuarioServico()).FindByVinculo(Recursos.Usuario); + List list = ( + from x in vendedorUsuarios + select x.get_Vendedor().get_Id()).ToList(); + List vendedors = new List(); + if (list.Count <= 0 || Recursos.Usuario.get_Administrador()) + { + Vendedor vendedor = new Vendedor(); + vendedor.set_Id((long)0); + vendedor.set_Nome("TODOS OS VENDEDORES"); + vendedors.Add(vendedor); + List vendedors1 = vendedors; + List vendedores = Recursos.Vendedores; + IEnumerable vendedors2 = vendedores.Where((Vendedor x) => { + if (Recursos.Usuario.get_IdEmpresa() != (long)1 && x.get_IdEmpresa() != Recursos.Usuario.get_IdEmpresa()) + { + return false; + } + return x.get_Ativo(); + }); + vendedors1.AddRange(( + from x in vendedors2 + orderby x.get_Nome() + select x).ToList()); + } + else + { + List vendedors3 = vendedors; + IEnumerable vendedors4 = Recursos.Vendedores.Where((Vendedor x) => { + if (Recursos.Usuario.get_IdEmpresa() != (long)1 && x.get_IdEmpresa() != Recursos.Usuario.get_IdEmpresa() || !x.get_Ativo()) + { + return false; + } + return list.Contains(x.get_Id()); + }); + vendedors3.AddRange(( + from x in vendedors4 + orderby x.get_Nome() + select x).ToList()); + } + this.Vendedores = new ObservableCollection(vendedors); + this.SelectedVendedor = this.Vendedores.FirstOrDefault(); + } + + public async void CarregaVendedores() + { + await this.CarregarVendedores(); + } + + public async void Excluir(Gestor.Model.Domain.Seguros.Prospeccao prospeccao) + { + if (await this.BuscaPermissao("Excluir")) + { + if (prospeccao != null) + { + bool tarefa = prospeccao.get_Tarefa() == null; + if (tarefa) + { + tarefa = !await base.ShowMessage("DESEJA EXCLUIR ESSA PROSPECÇÃO?", "SIM", "NÃO", false); + } + bool flag = tarefa; + if (!flag) + { + bool tarefa1 = prospeccao.get_Tarefa() != null; + if (tarefa1) + { + tarefa1 = !await base.ShowMessage(string.Concat("HÁ UMA TAREFA ANEXADA A ESSA PROSPECÇÃO. ESSE PROCEDIMENTO IRÁ EXCLUIR A TAREFA ANEXADA.", Environment.NewLine, "DESEJA REALMENTE PROSSEGUIR?"), "SIM", "NÃO", false); + } + flag = tarefa1; + } + if (!flag) + { + if (await this._servico.Delete(prospeccao)) + { + base.RegistrarAcao(string.Format("EXCLUIU PROSPECÇÃO DO ID: {0}", prospeccao.get_Id()), prospeccao.get_Id(), new TipoTela?(33), string.Format("CLIENTE \"{0}\", ID: {1}", prospeccao.get_Nome(), prospeccao.get_Id())); + await this.CarregarProspeccoes(); + base.ToggleSnackBar("PROSPECÇÃO EXCLUÍDA COM SUCESSO", true); + } + } + } + } + } + + public List Filtrar(string filter) + { + if (this.Prospeccoes == null) + { + return null; + } + this.ProspeccoesFiltradas = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Prospeccoes) : new ObservableCollection(this.Prospeccoes.Where((Gestor.Model.Domain.Seguros.Prospeccao x) => { + if (ValidationHelper.RemoveDiacritics(ValidationHelper.RemoveDiacritics(x.get_Nome()).ToUpper().Trim()).Contains(filter) || x.get_Documento() != null && ValidationHelper.RemoveDiacritics(x.get_Documento().Trim()).Contains(filter) || x.get_Telefone1() != null && ValidationHelper.RemoveDiacritics(x.get_Telefone1().Trim()).Contains(filter) || x.get_Telefone2() != null && ValidationHelper.RemoveDiacritics(x.get_Telefone2().Trim()).Contains(filter) || x.get_Email() != null && ValidationHelper.RemoveDiacritics(x.get_Email().Trim()).Contains(filter)) + { + return true; + } + if (!x.get_VigenciaFinal().HasValue) + { + return false; + } + return ValidationHelper.RemoveDiacritics(x.get_VigenciaFinal().ToString().Trim()).Contains(filter); + }).OrderBy((Gestor.Model.Domain.Seguros.Prospeccao x) => x.get_VigenciaFinal()))); + return this.ProspeccoesFiltradas.ToList(); + } + + internal async Task> FiltrarProspecao(string value) + { + List prospeccaos = await Task.Run>(() => this.Filtrar(value)); + return prospeccaos; + } + + public async Task GerarExcel() + { + string str; + if (this.ProspeccoesFiltradas != null) + { + List prospeccaoToPrints = new List(); + this.ProspeccoesFiltradas.AsEnumerable().ToList().ForEach((Gestor.Model.Domain.Seguros.Prospeccao x) => { + ProspeccaoToPrint prospeccaoToPrint = new ProspeccaoToPrint(); + prospeccaoToPrint.set_Nome(x.get_Nome()); + prospeccaoToPrint.set_Documento(x.get_Documento() ?? ""); + prospeccaoToPrint.set_Nascimento(x.get_Nascimento()); + prospeccaoToPrint.set_Prefixo1(x.get_Prefixo1() ?? ""); + prospeccaoToPrint.set_Telefone1(x.get_Telefone1() ?? ""); + prospeccaoToPrint.set_Email(x.get_Email() ?? ""); + prospeccaoToPrint.set_VigenciaFinal(x.get_VigenciaFinal()); + prospeccaoToPrint.set_Item(x.get_Item() ?? ""); + prospeccaoToPrint.set_Status(x.get_Status()); + prospeccaoToPrint.set_StatusPersonalizadotoPrint((x.get_StatusPersonalizado() == null ? "" : x.get_StatusPersonalizado().get_Nome())); + prospeccaoToPrint.set_Tipo(x.get_Tipo() ?? ""); + object nome = x.get_Vendedor().get_Nome(); + if (nome == null) + { + nome = null; + } + prospeccaoToPrint.set_Vendedor((string)nome); + prospeccaoToPrint.set_Valor(x.get_Valor()); + prospeccaoToPrints.Add(prospeccaoToPrint); + }); + string tempPath = ""; + str = ""; + tempPath = Path.GetTempPath(); + str = string.Format("{0}{1}.xlsx", tempPath, Guid.NewGuid()); + string str1 = "PROSPECÇÃO"; + await Funcoes.GerarXls(new XLWorkbook(), str1, prospeccaoToPrints, new List()).SaveAs(str); + Process.Start(str); + } + else + { + base.ShowMessage("NÃO HÁ DADOS PARA A IMPRESSÃO EM EXCEL", "OK", "", false); + } + str = null; + } + + public async Task Print() + { + if (this.ProspeccoesFiltradas != null) + { + List prospeccaoToPrints = new List(); + this.ProspeccoesFiltradas.AsEnumerable().ToList().ForEach((Gestor.Model.Domain.Seguros.Prospeccao x) => { + ProspeccaoToPrint prospeccaoToPrint = new ProspeccaoToPrint(); + prospeccaoToPrint.set_Nome(x.get_Nome()); + prospeccaoToPrint.set_Documento(x.get_Documento() ?? ""); + prospeccaoToPrint.set_Nascimento(x.get_Nascimento()); + prospeccaoToPrint.set_Prefixo1(x.get_Prefixo1() ?? ""); + prospeccaoToPrint.set_Telefone1(x.get_Telefone1() ?? ""); + prospeccaoToPrint.set_Email(x.get_Email() ?? ""); + prospeccaoToPrint.set_VigenciaFinal(x.get_VigenciaFinal()); + prospeccaoToPrint.set_Item(x.get_Item() ?? ""); + prospeccaoToPrint.set_Status(x.get_Status()); + prospeccaoToPrint.set_StatusPersonalizadotoPrint((x.get_StatusPersonalizado() == null ? "" : x.get_StatusPersonalizado().get_Nome())); + prospeccaoToPrint.set_Tipo(x.get_Tipo() ?? ""); + object nome = x.get_Vendedor().get_Nome(); + if (nome == null) + { + nome = null; + } + prospeccaoToPrint.set_Vendedor((string)nome); + prospeccaoToPrint.set_Valor(x.get_Valor()); + prospeccaoToPrints.Add(prospeccaoToPrint); + }); + List prospeccaoToPrints1 = prospeccaoToPrints; + prospeccaoToPrints = ( + from x in prospeccaoToPrints1 + orderby x.get_Vendedor() + select x).ToList(); + string str = await Funcoes.GenerateTable(prospeccaoToPrints.ToList(), new List(), false, false, "", null); + if (!string.IsNullOrEmpty(str)) + { + TipoRelatorio tipoRelatorio = new TipoRelatorio(); + tipoRelatorio.set_Inicio(this.Inicio); + tipoRelatorio.set_Fim(this.Fim); + tipoRelatorio.set_Nome(string.Concat("PROSPECÇÕES - ", this.SelectedVendedor.get_Nome())); + str = Funcoes.ExportarHtml(tipoRelatorio, str, "60", "landscaoe", false, ""); + string tempPath = Path.GetTempPath(); + string str1 = string.Format("{0}PROSPECÇÃO_{1:ddMMyyyyhhmmss}.html", tempPath, Funcoes.GetNetworkTime()); + StreamWriter streamWriter = new StreamWriter(str1, true, Encoding.UTF8); + streamWriter.Write(str); + streamWriter.Close(); + Process.Start(str1); + } + } + } + + public async Task>> Salvar(Gestor.Model.Domain.Seguros.Prospeccao prospecao) + { + return await base.SalvarProspeccao(prospecao); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/BI/TarefaBIViewModel.cs b/Codemerx/Gestor.Application/ViewModels/BI/TarefaBIViewModel.cs new file mode 100644 index 0000000..33d1096 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/BI/TarefaBIViewModel.cs @@ -0,0 +1,1453 @@ +using Gestor.Application.Actions; +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Application.Views.Seguros; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.MalaDireta; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.BI +{ + public class TarefaBIViewModel : BaseTarefaViewModel + { + private bool _enableAlterarTarefa = true; + + private bool _administrador; + + private DateTime _inicio; + + private DateTime _fim; + + private List _status; + + private string _selectedStatus; + + private Visibility _isVisibleCliente; + + private Visibility _isVisibleApolice; + + private Visibility _isVisibleArquivoDigital; + + private Visibility _isVisibleSinistro; + + private ObservableCollection _usuariosFiltro; + + private ObservableCollection _usuarios; + + private ObservableCollection _tiposTarefa; + + private TipoDeTarefa _selectedTipoTarefa; + + private Usuario _selectedUsuarioFiltro; + + private Usuario _selectedUsuario; + + private DateTime _dataAgendamento; + + private DateTime _horaAgendamento; + + private bool _isAnotacoes; + + private string _descricao; + + private string _historicoInterno; + + private ObservableCollection _tarefas; + + private Tarefa _selectedTarefa; + + private ObservableCollection _telefones; + + private long _cancelTarefa; + + private ObservableCollection _tarefasFiltradas; + + private string _filtro; + + private ObservableCollection _filtroTarefa; + + private GridLength _columnUsuarioPrincipal; + + private GridLength _columnUsuarios; + + public bool Administrador + { + get + { + return this._administrador; + } + set + { + this._administrador = value; + base.OnPropertyChanged("Administrador"); + } + } + + private Gestor.Application.Servicos.Seguros.ClienteServico ClienteServico + { + get; + } + + public GridLength ColumnUsuarioPrincipal + { + get + { + return this._columnUsuarioPrincipal; + } + set + { + this._columnUsuarioPrincipal = value; + base.OnPropertyChanged("ColumnUsuarioPrincipal"); + } + } + + public GridLength ColumnUsuarios + { + get + { + return this._columnUsuarios; + } + set + { + this._columnUsuarios = value; + base.OnPropertyChanged("ColumnUsuarios"); + } + } + + public DateTime DataAgendamento + { + get + { + return this._dataAgendamento; + } + set + { + this._dataAgendamento = value; + if (this.SelectedTarefa != null) + { + this.SelectedTarefa.set_Agendamento(DateTime.Parse(string.Format("{0:d} {1:T}", value, this.SelectedTarefa.get_Agendamento()))); + } + base.OnPropertyChanged("DataAgendamento"); + } + } + + public string Descricao + { + get + { + return this._descricao; + } + set + { + this._descricao = value; + base.OnPropertyChanged("Descricao"); + } + } + + public override bool EnableAlterarTarefa + { + get + { + return this._enableAlterarTarefa; + } + set + { + this._enableAlterarTarefa = this._alterarPermissEnabled & value; + base.OnPropertyChanged("EnableAlterarTarefa"); + } + } + + public string Filtro + { + get + { + return this._filtro; + } + set + { + this._filtro = value; + base.OnPropertyChanged("Filtro"); + } + } + + public ObservableCollection FiltroTarefa + { + get + { + return this._filtroTarefa; + } + set + { + this._filtroTarefa = value; + base.OnPropertyChanged("FiltroTarefa"); + } + } + + public DateTime Fim + { + get + { + return this._fim; + } + set + { + this._fim = value; + this.CarregaTarefas(false); + base.OnPropertyChanged("Fim"); + } + } + + public string HistoricoInterno + { + get + { + return this._historicoInterno; + } + set + { + this._historicoInterno = value; + base.OnPropertyChanged("HistoricoInterno"); + } + } + + public DateTime HoraAgendamento + { + get + { + return this._horaAgendamento; + } + set + { + this._horaAgendamento = value; + if (this.SelectedTarefa != null) + { + this.SelectedTarefa.set_Agendamento(DateTime.Parse(string.Format("{0:d} {1:T}", this.SelectedTarefa.get_Agendamento(), value))); + } + base.OnPropertyChanged("HoraAgendamento"); + } + } + + public DateTime Inicio + { + get + { + return this._inicio; + } + set + { + this._inicio = value; + this.CarregaTarefas(false); + base.OnPropertyChanged("Inicio"); + } + } + + public bool IsAnotacoes + { + get + { + return this._isAnotacoes; + } + set + { + this._isAnotacoes = value; + base.OnPropertyChanged("IsAnotacoes"); + } + } + + public Visibility IsVisibleApolice + { + get + { + return this._isVisibleApolice; + } + set + { + this._isVisibleApolice = value; + base.OnPropertyChanged("IsVisibleApolice"); + } + } + + public Visibility IsVisibleArquivoDigital + { + get + { + return this._isVisibleArquivoDigital; + } + set + { + this._isVisibleArquivoDigital = value; + base.OnPropertyChanged("IsVisibleArquivoDigital"); + } + } + + public Visibility IsVisibleCliente + { + get + { + return this._isVisibleCliente; + } + set + { + this._isVisibleCliente = value; + base.OnPropertyChanged("IsVisibleCliente"); + } + } + + public Visibility IsVisibleSinistro + { + get + { + return this._isVisibleSinistro; + } + set + { + this._isVisibleSinistro = value; + base.OnPropertyChanged("IsVisibleSinistro"); + } + } + + public string SelectedStatus + { + get + { + return this._selectedStatus; + } + set + { + this._selectedStatus = value; + this.CarregaTarefas(false); + base.OnPropertyChanged("SelectedStatus"); + } + } + + public override Tarefa SelectedTarefa + { + get + { + return this._selectedTarefa; + } + set + { + long? nullable; + this._cancelTarefa = (value != null ? value.get_Id() : (long)0); + this.WorkOnSelectedTarefa(value); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + this._selectedTarefa = value; + base.ValidaPermissaoParaEditarTarefa(); + base.OnPropertyChanged("SelectedTarefa"); + } + } + + public TipoDeTarefa SelectedTipoTarefa + { + get + { + return this._selectedTipoTarefa; + } + set + { + this._selectedTipoTarefa = value; + base.OnPropertyChanged("SelectedTipoTarefa"); + } + } + + public Usuario SelectedUsuario + { + get + { + return this._selectedUsuario; + } + set + { + this._selectedUsuario = value; + base.OnPropertyChanged("SelectedUsuario"); + } + } + + public Usuario SelectedUsuarioFiltro + { + get + { + return this._selectedUsuarioFiltro; + } + set + { + this._selectedUsuarioFiltro = value; + this.CarregaTarefas(false); + base.OnPropertyChanged("SelectedUsuarioFiltro"); + } + } + + private new TarefaServico Servico + { + get; + } + + public List Status + { + get + { + return this._status; + } + set + { + this._status = value; + this.CarregaTarefas(false); + base.OnPropertyChanged("Status"); + } + } + + public ObservableCollection Tarefas + { + get + { + return this._tarefas; + } + set + { + this._tarefas = value; + base.OnPropertyChanged("Tarefas"); + } + } + + public ObservableCollection TarefasFiltradas + { + get + { + return this._tarefasFiltradas; + } + set + { + this._tarefasFiltradas = value; + base.IsVisible = (value.Count > 0 ? Visibility.Visible : Visibility.Collapsed); + base.OnPropertyChanged("TarefasFiltradas"); + } + } + + public ObservableCollection Telefones + { + get + { + return this._telefones; + } + set + { + this._telefones = value; + base.OnPropertyChanged("Telefones"); + } + } + + public ObservableCollection TiposTarefa + { + get + { + return this._tiposTarefa; + } + set + { + this._tiposTarefa = value; + base.OnPropertyChanged("TiposTarefa"); + } + } + + public ObservableCollection Usuarios + { + get + { + return this._usuarios; + } + set + { + this._usuarios = value; + base.OnPropertyChanged("Usuarios"); + } + } + + public ObservableCollection UsuariosFiltro + { + get + { + return this._usuariosFiltro; + } + set + { + this._usuariosFiltro = value; + base.OnPropertyChanged("UsuariosFiltro"); + } + } + + public TarefaBIViewModel() + { + this._enableAlterarTarefa = true; + DateTime date = Funcoes.GetNetworkTime().Date; + this._inicio = date.AddDays(-4); + date = Funcoes.GetNetworkTime().Date; + this._fim = date.AddDays(4); + this._status = new List() + { + "TODAS AS TAREFAS", + Gestor.Common.Validation.ValidationHelper.GetDescription((StatusTarefa)0), + Gestor.Common.Validation.ValidationHelper.GetDescription((StatusTarefa)2) + }; + this._isVisibleCliente = Visibility.Collapsed; + this._isVisibleApolice = Visibility.Collapsed; + this._isVisibleArquivoDigital = Visibility.Collapsed; + this._isVisibleSinistro = Visibility.Collapsed; + this._selectedUsuarioFiltro = new Usuario(); + this._selectedUsuario = new Usuario(); + this._dataAgendamento = Funcoes.GetNetworkTime(); + this._horaAgendamento = Funcoes.GetNetworkTime(); + this._isAnotacoes = true; + this._descricao = ""; + this._historicoInterno = ""; + this._tarefasFiltradas = new ObservableCollection(); + this._filtro = ""; + this._filtroTarefa = new ObservableCollection(); + this._columnUsuarioPrincipal = new GridLength(1, GridUnitType.Star); + this._columnUsuarios = new GridLength(0, GridUnitType.Pixel); + base(); + this.Servico = new TarefaServico(); + this.ClienteServico = new Gestor.Application.Servicos.Seguros.ClienteServico(); + this.Administrador = (Recursos.Usuario.get_Id() == 0 ? true : Recursos.Usuario.get_Administrador()); + this.CarregarUsuarios(); + List list = Recursos.Usuarios.Where((Usuario x) => { + if (!Recursos.Configuracoes.Any((ConfiguracaoSistema c) => c.get_Configuracao() == 36) && x.get_IdEmpresa() != Recursos.Usuario.get_IdEmpresa()) + { + return false; + } + return !x.get_Excluido(); + }).OrderBy((Usuario x) => x.get_Nome()).ToList(); + Usuario usuario = new Usuario(); + usuario.set_Nome("TODOS OS USUÁRIOS"); + usuario.set_Id((long)0); + list.Insert(0, usuario); + this.UsuariosFiltro = new ObservableCollection(list); + this.TiposTarefa = new ObservableCollection(( + from x in Recursos.TiposTarefa + where x.get_Ativo() + select x).ToList()); + this.SelectedUsuarioFiltro = this.UsuariosFiltro.FirstOrDefault((Usuario x) => x.get_Id() == Recursos.Usuario.get_Id()) ?? this.UsuariosFiltro.FirstOrDefault(); + this.SelectedStatus = this.Status[1]; + this.CarregaTarefas(true); + } + + public async void Abrir(TipoTarefa tipo) + { + double? nullable; + long? nullable1; + long? nullable2; + switch (tipo) + { + case 0: + { + long idEntidade = this.SelectedTarefa.get_IdEntidade(); + if (this.SelectedTarefa.get_Entidade() == 4) + { + Sinistro sinistro = await base.CarregaSinistroApolice(this.SelectedTarefa.get_IdEntidade()); + if (sinistro != null) + { + ControleSinistro controleSinistro = sinistro.get_ControleSinistro(); + if (controleSinistro != null) + { + Item item = controleSinistro.get_Item(); + if (item != null) + { + Documento documento = item.get_Documento(); + if (documento != null) + { + nullable2 = new long?(documento.get_Id()); + } + else + { + nullable1 = null; + nullable2 = nullable1; + } + } + else + { + nullable1 = null; + nullable2 = nullable1; + } + } + else + { + nullable1 = null; + nullable2 = nullable1; + } + } + else + { + nullable1 = null; + nullable2 = nullable1; + } + nullable1 = nullable2; + idEntidade = nullable1.GetValueOrDefault(); + } + if (idEntidade != 0) + { + nullable = null; + double? nullable3 = nullable; + nullable = null; + (new HosterWindow(new ApoliceView(await base.CarregaApolice(idEntidade), true, false, 0, (long)0, false), string.Concat("CADASTRO DE APÓLICES - ", this.SelectedTarefa.get_Cliente()), nullable3, nullable, false)).Show(); + goto case 1; + } + else + { + break; + } + } + case 1: + { + break; + } + case 2: + { + nullable = null; + double? nullable4 = nullable; + nullable = null; + (new HosterWindow(new ClienteView(await base.CarregaCliente(this.SelectedTarefa.get_IdCliente()), true, null), string.Concat("CADASTRO DE CLIENTES - ", this.SelectedTarefa.get_Cliente()), nullable4, nullable, false)).Show(); + goto case 1; + } + case 3: + { + nullable = null; + double? nullable5 = nullable; + nullable = null; + (new HosterWindow(new ApoliceView(await base.CarregaApoliceParcela(this.SelectedTarefa.get_IdEntidade()), true, false, 0, (long)0, false), string.Concat("CADASTRO DE APÓLICES - ", this.SelectedTarefa.get_Cliente(), " - ", this.SelectedTarefa.get_Referencia()), nullable5, nullable, false)).Show(); + goto case 1; + } + case 4: + { + Sinistro sinistro1 = await base.CarregaSinistroApolice(this.SelectedTarefa.get_IdEntidade()); + if (sinistro1 != null) + { + nullable = null; + double? nullable6 = nullable; + nullable = null; + (new HosterWindow(new SinistroView(sinistro1.get_ControleSinistro().get_Item(), false), string.Concat("CADASTRO DE SINISTROS - ", this.SelectedTarefa.get_Cliente(), " - ", this.SelectedTarefa.get_Referencia()), nullable6, nullable, false)).Show(); + goto case 1; + } + else + { + await base.ShowMessage("SINISTRO NÃO ENCONTRADO!", "OK", "", false); + break; + } + } + default: + { + goto case 1; + } + } + } + + public async void AbrirArquivoDigital() + { + FiltroArquivoDigital filtroArquivoDigital; + if (this.SelectedTarefa.get_IdEntidade() != 0) + { + filtroArquivoDigital = new FiltroArquivoDigital(); + switch (this.SelectedTarefa.get_Entidade()) + { + case 0: + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 2).get_Consultar()) + { + Documento documento = await base.CarregaApolice(this.SelectedTarefa.get_IdEntidade()); + filtroArquivoDigital.set_Id(documento.get_Id()); + filtroArquivoDigital.set_Tipo(2); + filtroArquivoDigital.set_Parente(documento); + goto case 7; + } + else + { + await base.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", Gestor.Common.Validation.ValidationHelper.GetDescription((TipoArquivoDigital)2), "."), "OK", "", false); + break; + } + } + case 1: + case 6: + case 7: + { + base.ShowDrawer(new ArquivoDigitalDrawer(filtroArquivoDigital), 0, false); + break; + } + case 2: + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 1).get_Consultar()) + { + Cliente cliente = await base.CarregaCliente(this.SelectedTarefa.get_IdCliente()); + filtroArquivoDigital.set_Id(cliente.get_Id()); + filtroArquivoDigital.set_Tipo(1); + filtroArquivoDigital.set_Parente(cliente); + goto case 7; + } + else + { + await base.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", Gestor.Common.Validation.ValidationHelper.GetDescription((TipoArquivoDigital)1), "."), "OK", "", false); + break; + } + } + case 3: + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 3).get_Consultar()) + { + Parcela parcela = await base.CarregaParcela(this.SelectedTarefa.get_IdEntidade()); + filtroArquivoDigital.set_Id(parcela.get_Id()); + filtroArquivoDigital.set_Tipo(3); + filtroArquivoDigital.set_Parente(parcela); + filtroArquivoDigital.set_IdApolice(parcela.get_Documento().get_Id()); + goto case 7; + } + else + { + await base.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", Gestor.Common.Validation.ValidationHelper.GetDescription((TipoArquivoDigital)3), "."), "OK", "", false); + break; + } + } + case 4: + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 5).get_Consultar()) + { + Sinistro sinistro = await base.CarregaSinistroApolice(this.SelectedTarefa.get_IdEntidade()); + filtroArquivoDigital.set_Id(sinistro.get_Id()); + filtroArquivoDigital.set_Tipo(5); + filtroArquivoDigital.set_Parente(sinistro); + filtroArquivoDigital.set_IdApolice(sinistro.get_ControleSinistro().get_Item().get_Documento().get_Id()); + goto case 7; + } + else + { + await base.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", Gestor.Common.Validation.ValidationHelper.GetDescription((TipoArquivoDigital)5), "."), "OK", "", false); + break; + } + } + case 5: + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 11).get_Consultar()) + { + Prospeccao prospeccao = await base.CarregarProspeccao(this.SelectedTarefa.get_IdEntidade()); + filtroArquivoDigital.set_Id(prospeccao.get_Id()); + filtroArquivoDigital.set_Tipo(11); + filtroArquivoDigital.set_Parente(prospeccao); + goto case 7; + } + else + { + await base.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", Gestor.Common.Validation.ValidationHelper.GetDescription((TipoArquivoDigital)11), "."), "OK", "", false); + break; + } + } + case 8: + { + break; + } + default: + { + goto case 7; + } + } + } + filtroArquivoDigital = null; + } + + public void AdcionarFiltro() + { + if (string.IsNullOrEmpty(this.Filtro)) + { + return; + } + if (this.FiltroTarefa == null) + { + this.FiltroTarefa = new ObservableCollection(); + } + this.FiltroTarefa.Add(this.Filtro); + this.Filtro = string.Empty; + this.FiltrarTarefa(); + } + + public async Task AdcionarResponsavel() + { + if (!await base.ValidaPermissaoParaEditarTarefa()) + { + await base.ShowMessage("VOCÊ NÃO TEM PERMISSÃO PARA EXCLUIR ESSA TAREFA!", "OK", "", false); + } + else if (this.SelectedUsuario != null) + { + ObservableCollection responsaveis = base.Responsaveis; + ResponsavelTarefa responsavelTarefa = new ResponsavelTarefa(); + responsavelTarefa.set_Usuario(this.SelectedUsuario); + responsavelTarefa.set_IdTarefa(this.SelectedTarefa.get_Id()); + responsaveis.Add(responsavelTarefa); + this.Usuarios.Remove(this.SelectedUsuario); + this.SelectedUsuario = null; + } + } + + public async Task AlterarTarefa() + { + GridLength gridLength; + GridLength gridLength1; + if (this.SelectedTarefa != null) + { + if (await base.ValidaPermissaoParaEditarTarefa()) + { + this.CarregarUsuarios(); + base.Alterar(true); + TarefaBIViewModel tarefaBIViewModel = this; + gridLength = (base.EnableFields ? new GridLength(0, GridUnitType.Pixel) : new GridLength(1, GridUnitType.Star)); + tarefaBIViewModel.ColumnUsuarioPrincipal = gridLength; + TarefaBIViewModel tarefaBIViewModel1 = this; + gridLength1 = (base.EnableFields ? new GridLength(1, GridUnitType.Star) : new GridLength(0, GridUnitType.Pixel)); + tarefaBIViewModel1.ColumnUsuarios = gridLength1; + base.ListaUsuariosResponsaveis(); + base.HasResponsaveis = true; + this.SelectedUsuario = null; + base.Responsaveis.ToList().ForEach((ResponsavelTarefa x) => this.Usuarios.Remove(this.Usuarios.FirstOrDefault((Usuario u) => u.get_Id() == x.get_Usuario().get_Id()))); + } + else + { + await base.ShowMessage("VOCÊ NÃO TEM PERMISSÃO PARA EXCLUIR ESSA TAREFA!", "OK", "", false); + } + } + } + + public async Task Cancelar() + { + if (this._cancelTarefa != 0) + { + long num = this._cancelTarefa; + await this.CarregarTarefas(); + this.SelectedTarefa = this.TarefasFiltradas.FirstOrDefault((Tarefa x) => x.get_Id() == num); + base.Alterar(false); + } + } + + public async Task CarregarTarefas() + { + long id; + bool? nullable; + this.ColumnUsuarioPrincipal = new GridLength(1, GridUnitType.Star); + this.ColumnUsuarios = new GridLength(0, GridUnitType.Pixel); + this.Filtro = string.Empty; + TarefaServico servico = this.Servico; + Usuario selectedUsuarioFiltro = this.SelectedUsuarioFiltro; + if (selectedUsuarioFiltro != null) + { + id = selectedUsuarioFiltro.get_Id(); + } + else + { + id = (long)0; + } + DateTime inicio = this.Inicio; + DateTime fim = this.Fim; + if (this.SelectedStatus == "TODAS AS TAREFAS") + { + nullable = null; + } + else + { + nullable = new bool?(this.SelectedStatus != "PENDENTE"); + } + List tarefas = await servico.BuscarTarefas(id, inicio, fim, nullable); + TarefaBIViewModel observableCollection = this; + List tarefas1 = tarefas; + IEnumerable entidade = + from x in tarefas1 + where x.get_Entidade() != 1 + select x; + observableCollection.Tarefas = new ObservableCollection( + from x in entidade + orderby x.get_Agendamento() + select x); + this.TarefasFiltradas = this.Tarefas; + this.SelectedTarefa = this.TarefasFiltradas.FirstOrDefault(); + if (this.FiltroTarefa.Count > 0) + { + this.FiltrarTarefa(); + } + } + + private void CarregarUsuarios() + { + this.Usuarios = new ObservableCollection(Recursos.Usuarios.Where((Usuario x) => { + if (!Recursos.Configuracoes.Any((ConfiguracaoSistema c) => c.get_Configuracao() == 36) && x.get_IdEmpresa() != Recursos.Usuario.get_IdEmpresa()) + { + return false; + } + return !x.get_Excluido(); + }).OrderBy((Usuario x) => x.get_Nome()).ToList()); + } + + public async void CarregaTarefas(bool permissoes = false) + { + if (permissoes) + { + await base.PermissaoTela(38); + base.Alterar(false); + } + await this.CarregarTarefas(); + } + + public async Task ConcluirTarefa(Tarefa tarefa) + { + Tarefa tarefa1; + if (await base.ValidaPermissaoParaEditarTarefa()) + { + tarefa1 = await this.Servico.Salvar(tarefa); + } + else + { + await base.ShowMessage("VOCÊ NÃO TEM PERMISSÃO PARA EDITAR ESSA TAREFA!", "OK", "", false); + tarefa1 = null; + } + return tarefa1; + } + + public async Task CriarMalaDireta(TipoTarefa tipo) + { + MalaDireta malaDiretum; + switch (tipo) + { + case 0: + { + Documento documento = await base.CarregaApolice(this.SelectedTarefa.get_IdEntidade()); + MalaDireta malaDiretum1 = new MalaDireta(); + malaDiretum1.set_Cliente(documento.get_Controle().get_Cliente()); + malaDiretum1.set_Apolice(documento); + malaDiretum1.set_Tela(2); + malaDiretum = malaDiretum1; + break; + } + case 1: + case 6: + case 7: + { + malaDiretum = null; + break; + } + case 2: + { + Cliente cliente = await base.CarregaCliente(this.SelectedTarefa.get_IdCliente()); + MalaDireta malaDiretum2 = new MalaDireta(); + malaDiretum2.set_Cliente(cliente); + malaDiretum2.set_Tela(1); + malaDiretum = malaDiretum2; + break; + } + case 3: + { + Documento documento1 = await base.CarregaApoliceParcela(this.SelectedTarefa.get_IdEntidade()); + MalaDireta malaDiretum3 = new MalaDireta(); + malaDiretum3.set_Cliente(documento1.get_Controle().get_Cliente()); + malaDiretum3.set_Apolice(documento1); + malaDiretum3.set_Tela(5); + malaDiretum = malaDiretum3; + break; + } + case 4: + { + Sinistro sinistro = await base.CarregaSinistroApolice(this.SelectedTarefa.get_IdEntidade()); + MalaDireta malaDiretum4 = new MalaDireta(); + malaDiretum4.set_Cliente(sinistro.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Cliente()); + malaDiretum4.set_Apolice(sinistro.get_ControleSinistro().get_Item().get_Documento()); + malaDiretum4.set_Sinistro(sinistro); + malaDiretum4.set_Tela(7); + malaDiretum = malaDiretum4; + break; + } + case 5: + { + Prospeccao prospeccao = await base.CarregarProspeccao(this.SelectedTarefa.get_IdEntidade()); + MalaDireta malaDiretum5 = new MalaDireta(); + malaDiretum5.set_Prospeccao(prospeccao); + malaDiretum5.set_Tela(33); + malaDiretum = malaDiretum5; + break; + } + case 8: + { + malaDiretum = null; + break; + } + default: + { + goto case 7; + } + } + return malaDiretum; + } + + public async Task Excluir() + { + bool id; + string titulo; + Tarefa selectedTarefa = this.SelectedTarefa; + if (selectedTarefa != null) + { + id = selectedTarefa.get_Id() == (long)0; + } + else + { + id = false; + } + if (!id) + { + TarefaBIViewModel tarefaBIViewModel = this; + string[] newLine = new string[] { "DESEJA REALMENTE EXCLUIR A TAREFA ", null, null, null, null }; + Tarefa tarefa = this.SelectedTarefa; + if (tarefa != null) + { + titulo = tarefa.get_Titulo(); + } + else + { + titulo = null; + } + newLine[1] = titulo; + newLine[2] = "?"; + newLine[3] = Environment.NewLine; + newLine[4] = "ESSE PROCEDIMENTO É IRREVERSÍVEL"; + if (await tarefaBIViewModel.ShowMessage(string.Concat(newLine), "SIM", "NÃO", false)) + { + if (await this.Servico.Excluir(this.SelectedTarefa.get_Id())) + { + await this.CarregarTarefas(); + Action atualizaTrilhas = Gestor.Application.Actions.Actions.AtualizaTrilhas; + if (atualizaTrilhas != null) + { + atualizaTrilhas(); + } + else + { + } + base.Alterar(false); + } + else + { + base.Alterar(false); + } + } + } + } + + public void ExcluirFiltro(string filtro) + { + this.FiltroTarefa.Remove(filtro); + this.FiltrarTarefa(); + } + + private List Filtrar() + { + List list = this.Tarefas.ToList(); + this.FiltroTarefa.ToList().ForEach((string f) => list = list.Where((Tarefa x) => { + if (Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Titulo()).ToUpper().Contains(Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(f)) || Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Cliente()).ToUpper().Contains(Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(f)) || Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Referencia()).ToUpper().Contains(Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(f)) || x.get_Agendamento().ToString("d").ToUpper().Contains(Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(f)) || x.get_Id().ToString().Contains(Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(f)) || x.get_TipoDeTarefa() != null && Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_TipoDeTarefa().get_Nome()).ToUpper().Contains(Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(f))) + { + return true; + } + if (x.get_Usuario() == null) + { + return false; + } + return x.get_Usuario().get_Nome().ToUpper().Contains(Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(f)); + }).ToList()); + return list; + } + + public void FiltrarTarefa() + { + this.TarefasFiltradas = new ObservableCollection(this.Filtrar()); + this.SelectedTarefa = this.TarefasFiltradas.FirstOrDefault(); + } + + public string GerarHtml() + { + string nome; + string str = " TAREFA
"; + str = string.Concat(str, "
"); + str = string.Concat(str, "

"); + str = string.Concat(str, "TAREFA


"); + str = string.Concat(str, ""); + int num = 0; + string[] cliente = new string[] { str, ""; + str = string.Concat(cliente); + string[] referencia = new string[] { str, ""; + str = string.Concat(referencia); + string[] titulo = new string[] { str, ""; + str = string.Concat(titulo); + string[] strArrays = new string[] { str, ""; + str = string.Concat(strArrays); + string[] nome1 = new string[] { str, ""; + str = string.Concat(nome1); + string[] description = new string[] { str, ""; + str = string.Concat(description); + string[] strArrays1 = new string[] { str, ""; + str = string.Concat(strArrays1); + str = string.Concat(str, "

CLIENTE: "; + cliente[4] = this.SelectedTarefa.get_Cliente(); + cliente[5] = "

REFERÊNCIA: "; + referencia[4] = this.SelectedTarefa.get_Referencia(); + referencia[5] = "

TÍTULO: "; + titulo[4] = this.SelectedTarefa.get_Titulo(); + titulo[5] = "

AGENDAMENTO: "; + DateTime agendamento = this.SelectedTarefa.get_Agendamento(); + strArrays[4] = agendamento.ToString(); + strArrays[5] = "

RESPONSÁVEL PRINCIPAL: "; + nome1[4] = this.SelectedTarefa.get_Usuario().get_Nome(); + nome1[5] = "

STATUS: "; + description[4] = Gestor.Common.Validation.ValidationHelper.GetDescription(this.SelectedTarefa.get_Status()); + description[5] = "

TIPO DE TAREFA: "; + TipoDeTarefa selectedTipoTarefa = this.SelectedTipoTarefa; + if (selectedTipoTarefa != null) + { + nome = selectedTipoTarefa.get_Nome(); + } + else + { + nome = null; + } + strArrays1[4] = nome; + strArrays1[5] = "

"); + if (base.Responsaveis != null && base.Responsaveis.Count > 0) + { + str = string.Concat(str, "

RESPONSÁVEIS VINCULADOS

"); + str = string.Concat(str, "
"); + str = string.Concat(str, ""); + List strs = new List(); + foreach (ResponsavelTarefa responsavei in base.Responsaveis) + { + strs.Add(responsavei.get_Usuario().get_Nome().Trim().ToUpper()); + } + str = string.Concat(str, ""); + str = string.Concat(str, "

", string.Join(", ", strs), "

"); + str = string.Concat(str, "

"); + } + str = string.Concat(str, "

"); + if (this.SelectedTarefa.get_Descricao() != null) + { + str = string.Concat(str, "

ANOTAÇÕES

"); + str = string.Concat(str, "
"); + str = string.Concat(str, ""); + str = string.Concat(str, ""); + str = string.Concat(str, "

", this.SelectedTarefa.get_Descricao().Replace("", "").Replace("", ""), "

"); + str = string.Concat(str, "

"); + } + str = string.Concat(str, "
"); + return str; + } + + public void Print() + { + string str = this.GerarHtml(); + string tempPath = Path.GetTempPath(); + string str1 = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.html", tempPath, (TipoTela)38, Funcoes.GetNetworkTime()); + StreamWriter streamWriter = new StreamWriter(str1, true, Encoding.UTF8); + streamWriter.Write(str); + streamWriter.Close(); + Process.Start(str1); + } + + public async Task>> Salvar(string titulo) + { + List> keyValuePairs; + Usuario usuario; + string str; + if (this.SelectedTarefa != null) + { + DateTime networkTime = Funcoes.GetNetworkTime(); + List configuracoes = Recursos.Configuracoes; + if (configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 45) && this.SelectedTarefa.get_Status() != 2 && this.SelectedTarefa.get_Agendamento() < networkTime) + { + this.SelectedTarefa.set_Agendamento(networkTime); + } + if (this.SelectedTarefa.get_Status() == 2) + { + this.SelectedTarefa.set_Conclusao(new DateTime?(networkTime)); + } + this.SelectedTarefa.set_Responsaveis(base.Responsaveis.ToList()); + Tarefa selectedTarefa = this.SelectedTarefa; + ResponsavelTarefa responsavelTarefa = base.Responsaveis.FirstOrDefault(); + if (responsavelTarefa != null) + { + usuario = responsavelTarefa.get_Usuario(); + } + else + { + usuario = null; + } + selectedTarefa.set_Usuario(usuario); + Tarefa tarefa = this.SelectedTarefa; + List configuracaoSistemas = Recursos.Configuracoes; + tarefa.set_AgendamentoRetroativo(configuracaoSistemas.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 45)); + List> keyValuePairs1 = this.SelectedTarefa.Validate(); + string text = Funcoes.GetText(this.SelectedTarefa.get_Anotacoes()); + string text1 = Funcoes.GetText(this.SelectedTarefa.get_AnotacoesInternas()); + if (string.IsNullOrEmpty(text) && string.IsNullOrEmpty(text1)) + { + keyValuePairs1.Add(new KeyValuePair("Anotações", "OBRIGATÓRIO")); + } + if (keyValuePairs1.Count <= 0) + { + this.SelectedTarefa.set_Anotacoes(Funcoes.AdicionarLog(this.SelectedTarefa.get_Anotacoes())); + this.SelectedTarefa.set_Descricao(string.Concat(this.SelectedTarefa.get_Anotacoes(), "

", this.Descricao, "

")); + Tarefa selectedTarefa1 = this.SelectedTarefa; + str = (string.IsNullOrWhiteSpace(this.SelectedTarefa.get_AnotacoesInternas()) ? this.HistoricoInterno : string.Concat(this.SelectedTarefa.get_AnotacoesInternas(), "

", this.HistoricoInterno, "

")); + selectedTarefa1.set_DescricaoInterna(str); + this.SelectedTarefa.set_TipoDeTarefa(this.SelectedTipoTarefa); + this.SelectedTarefa.set_Titulo(titulo); + this.SelectedTarefa = await this.Servico.Salvar(this.SelectedTarefa); + if (this.Servico.Sucesso) + { + long id = this.SelectedTarefa.get_Id(); + await this.CarregarTarefas(); + TarefaBIViewModel tarefaBIViewModel = this; + Tarefa tarefa1 = this.TarefasFiltradas.FirstOrDefault((Tarefa x) => x.get_Id() == id); + if (tarefa1 == null) + { + tarefa1 = this.TarefasFiltradas.FirstOrDefault(); + } + tarefaBIViewModel.SelectedTarefa = tarefa1; + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + } + else + { + keyValuePairs = null; + } + return keyValuePairs; + } + + private async void WorkOnSelectedTarefa(Tarefa value) + { + Usuario usuario; + ObservableCollection observableCollection; + TipoTelefone tipoTelefone; + TipoTelefone tipoTelefone1; + bool flag; + ObservableCollection observableCollection1; + if (value != null) + { + TarefaBIViewModel tarefaBIViewModel = this; + if (value.get_Usuario() != null) + { + usuario = this.Usuarios.FirstOrDefault((Usuario x) => x.get_Id() == value.get_Usuario().get_Id()); + } + else + { + usuario = null; + } + tarefaBIViewModel.SelectedUsuario = usuario; + this.DataAgendamento = value.get_Agendamento(); + this.HoraAgendamento = value.get_Agendamento(); + this.Descricao = value.get_Descricao(); + this.HistoricoInterno = value.get_DescricaoInterna(); + TarefaBIViewModel tarefaBIViewModel1 = this; + if (value == null) + { + observableCollection = new ObservableCollection(); + } + else + { + observableCollection = (value.get_Responsaveis() == null ? new ObservableCollection() : new ObservableCollection(value.get_Responsaveis())); + } + tarefaBIViewModel1.Responsaveis = observableCollection; + if (!base.Responsaveis.Any()) + { + TarefaBIViewModel tarefaBIViewModel2 = this; + Tarefa tarefa = value; + if (tarefa != null) + { + flag = tarefa.get_Usuario(); + } + else + { + flag = false; + } + if (!flag) + { + observableCollection1 = new ObservableCollection(); + } + else + { + ResponsavelTarefa[] responsavelTarefaArray = new ResponsavelTarefa[1]; + ResponsavelTarefa responsavelTarefa = new ResponsavelTarefa(); + responsavelTarefa.set_Usuario(value.get_Usuario()); + responsavelTarefaArray[0] = responsavelTarefa; + observableCollection1 = new ObservableCollection(responsavelTarefaArray); + } + tarefaBIViewModel2.Responsaveis = observableCollection1; + } + if (value.get_TipoDeTarefa() != null) + { + if (!this.TiposTarefa.All((TipoDeTarefa x) => x.get_Id() != value.get_Id()) || value.get_TipoDeTarefa().get_Ativo()) + { + TarefaBIViewModel observableCollection2 = this; + ObservableCollection tiposTarefa = this.TiposTarefa; + observableCollection2.TiposTarefa = new ObservableCollection(( + from x in tiposTarefa + where x.get_Ativo() + select x).ToList()); + } + else + { + this.TiposTarefa.Add(value.get_TipoDeTarefa()); + } + } + this.SelectedTipoTarefa = value.get_TipoDeTarefa(); + this.IsVisibleCliente = Visibility.Collapsed; + this.IsVisibleApolice = Visibility.Collapsed; + this.IsVisibleSinistro = Visibility.Collapsed; + this.IsVisibleArquivoDigital = Visibility.Collapsed; + TipoTarefa entidade = value.get_Entidade(); + switch (entidade) + { + case 0: + case 3: + { + this.IsVisibleCliente = Visibility.Visible; + this.IsVisibleApolice = Visibility.Visible; + this.IsVisibleArquivoDigital = Visibility.Visible; + goto case 1; + } + case 1: + { + entidade = value.get_Entidade(); + if (entidade == 5) + { + Prospeccao prospeccao = await (new ProspeccaoServico()).BuscarProspeccao(value.get_IdEntidade()); + this.Telefones = new ObservableCollection(); + if (prospeccao != null && prospeccao.get_Telefone1() != null) + { + ObservableCollection telefones = this.Telefones; + TelefoneBase telefoneBase1 = new TelefoneBase(); + tipoTelefone1 = (prospeccao.get_Telefone1().StartsWith("9") ? 3 : 7); + telefoneBase1.set_Tipo(new TipoTelefone?(tipoTelefone1)); + telefoneBase1.set_Numero(prospeccao.get_Telefone1()); + telefoneBase1.set_Prefixo(prospeccao.get_Prefixo1()); + telefones.Add(telefoneBase1); + } + if (prospeccao != null && prospeccao.get_Telefone2() != null) + { + ObservableCollection telefones1 = this.Telefones; + TelefoneBase telefoneBase2 = new TelefoneBase(); + tipoTelefone = (prospeccao.get_Telefone2().StartsWith("9") ? 3 : 7); + telefoneBase2.set_Tipo(new TipoTelefone?(tipoTelefone)); + telefoneBase2.set_Numero(prospeccao.get_Telefone2()); + telefoneBase2.set_Prefixo(prospeccao.get_Prefixo2()); + telefones1.Add(telefoneBase2); + } + } + else if (entidade == 8) + { + this.Telefones = new ObservableCollection(); + } + else + { + ObservableCollection observableCollection3 = await this.ClienteServico.BuscarTelefonesAsync(value.get_IdCliente()); + TarefaBIViewModel tarefaBIViewModel3 = this; + ObservableCollection observableCollection4 = observableCollection3; + IEnumerable clienteTelefones = + from x in observableCollection4 + where Gestor.Model.Helper.ValidationHelper.ValidacaoTelefone(x.get_Numero()) + select x; + tarefaBIViewModel3.Telefones = new ObservableCollection(clienteTelefones.Select((ClienteTelefone x) => { + TelefoneBase telefoneBase = new TelefoneBase(); + telefoneBase.set_Tipo(x.get_Tipo()); + telefoneBase.set_Id(x.get_Id()); + telefoneBase.set_Numero(x.get_Numero()); + telefoneBase.set_Prefixo(x.get_Prefixo()); + return telefoneBase; + }).ToList()); + } + break; + } + case 2: + { + this.IsVisibleCliente = Visibility.Visible; + this.IsVisibleArquivoDigital = Visibility.Visible; + goto case 1; + } + case 4: + { + this.IsVisibleCliente = Visibility.Visible; + this.IsVisibleApolice = Visibility.Visible; + this.IsVisibleSinistro = Visibility.Visible; + this.IsVisibleArquivoDigital = Visibility.Visible; + goto case 1; + } + default: + { + goto case 1; + } + } + } + else + { + base.Responsaveis = new ObservableCollection(); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/CoberturaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/CoberturaViewModel.cs new file mode 100644 index 0000000..fb35f4d --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/CoberturaViewModel.cs @@ -0,0 +1,285 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels +{ + public class CoberturaViewModel : BaseSegurosViewModel + { + private readonly ItemServico _itemServico; + + private Cobertura _selectedCobertura; + + private List _coberturasPadrao; + + private ObservableCollection _coberturas; + + private readonly IComparer _comparerCobertura; + + public ObservableCollection Coberturas + { + get + { + return this._coberturas; + } + set + { + this._coberturas = value; + base.OnPropertyChanged("Coberturas"); + } + } + + public List CoberturasPadrao + { + get + { + return this._coberturasPadrao; + } + set + { + this._coberturasPadrao = value; + base.OnPropertyChanged("CoberturasPadrao"); + } + } + + public Gestor.Model.Domain.Seguros.Item Item + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Ramo Ramo + { + get; + set; + } + + public Cobertura SelectedCobertura + { + get + { + return this._selectedCobertura; + } + set + { + this._selectedCobertura = value; + base.OnPropertyChanged("SelectedCobertura"); + } + } + + public CoberturaViewModel(Gestor.Model.Domain.Seguros.Ramo ramo = null, Gestor.Model.Domain.Seguros.Item item = null) + { + // + // Current member / type: System.Void Gestor.Application.ViewModels.CoberturaViewModel::.ctor(Gestor.Model.Domain.Seguros.Ramo,Gestor.Model.Domain.Seguros.Item) + // File path: C:\AggerSeguros\Gestor.Application.exe + // + // Product version: 0.0.0.0 + // Exception in: System.Void .ctor(Gestor.Model.Domain.Seguros.Ramo,Gestor.Model.Domain.Seguros.Item) + // + // Object reference not set to an instance of an object. + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.FindLowestCommonAncestor(ICollection`1 typeNodes) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 515 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.MergeWithLowestCommonAncestor() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 459 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.ProcessSingleConstraints() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 378 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.InferTypes() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 331 + // at Telerik.JustDecompiler.Decompiler.ExpressionDecompilerStep.Process(DecompilationContext theContext, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\ExpressionDecompilerStep.cs:line 104 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61 + // at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 133 + // + // mailto: JustDecompilePublicFeedback@telerik.com + + } + + public void AdicionaCobertura() + { + Cobertura cobertura = new Cobertura(); + cobertura.set_Item(this.Item); + Cobertura cobertura1 = cobertura; + ValidationHelper.AddSorted(this.Coberturas, cobertura1, this._comparerCobertura); + this.SelectedCobertura = cobertura1; + } + + internal async Task> BuscarCobertura(string value) + { + Func func2 = null; + List coberturaPadraos = await Task.Run>(() => { + List coberturasPadrao = this.CoberturasPadrao; + if (coberturasPadrao == null) + { + return null; + } + Func u003cu003e9_1 = func2; + if (u003cu003e9_1 == null) + { + Func func = (CoberturaPadrao x) => ValidationHelper.RemoveDiacritics(x.get_Descricao().ToUpper().Trim()).Contains(value.ToUpper()); + Func func1 = func; + func2 = func; + u003cu003e9_1 = func1; + } + return coberturasPadrao.Where(u003cu003e9_1).ToList(); + }); + return coberturaPadraos; + } + + public async Task CancelarAlteracao() + { + if (this.Item != null) + { + this.Coberturas = await this._itemServico.BuscarCoberturasPorItemAsync(this.Item.get_Id()); + } + } + + public ObservableCollection CarregaCoberturaPadrao() + { + List list; + List coberturasPadrao = this.CoberturasPadrao; + if (coberturasPadrao != null) + { + list = ( + from x in coberturasPadrao + where x.get_Padrao() + select x).Select((CoberturaPadrao x) => { + Cobertura cobertura = new Cobertura(); + cobertura.set_CoberturaPadrao(x); + cobertura.set_Observacao(x.get_Descricao()); + return cobertura; + }).ToList(); + } + else + { + list = null; + } + ObservableCollection observableCollection = new ObservableCollection(list); + ObservableCollection observableCollection1 = observableCollection; + this.Coberturas = observableCollection; + return observableCollection1; + } + + public void CarregaPadrao() + { + List list; + List coberturasPadrao = this.CoberturasPadrao; + if (coberturasPadrao != null) + { + list = ( + from x in coberturasPadrao + where x.get_Padrao() + select x).Select((CoberturaPadrao x) => { + Cobertura cobertura = new Cobertura(); + cobertura.set_CoberturaPadrao(x); + cobertura.set_Observacao(x.get_Descricao()); + return cobertura; + }).ToList(); + } + else + { + list = null; + } + List coberturas = list; + if (coberturas == null) + { + return; + } + this.Coberturas = new ObservableCollection(coberturas); + } + + public async void ExcluirCobertura(Cobertura cobertura) + { + if (cobertura != null) + { + string[] newLine = new string[] { "DESEJA REALMENTE EXCLUIR A COBERTURA", Environment.NewLine, "\"", cobertura.get_Observacao(), "\"?" }; + if (await base.ShowMessage(string.Concat(newLine), "SIM", "NÃO", false)) + { + this.Coberturas.Remove(cobertura); + } + } + } + + public async Task> LimpaCoberturas() + { + bool flag; + IList list; + if (this.Coberturas == null) + { + flag = false; + } + else + { + ObservableCollection coberturas = this.Coberturas; + flag = coberturas.Any((Cobertura x) => { + if (!(x.get_Franquia() == decimal.Zero) || !(x.get_Lmi() == decimal.Zero)) + { + return false; + } + return x.get_Premio() == decimal.Zero; + }); + } + bool flag1 = flag; + if (flag1) + { + flag1 = await base.ShowMessage("DESEJA LIMPAR AS COBERTURAS SEM VALOR DE FRANQUIA, LMI E PRÊMIO?", "SIM", "NÃO", false); + } + if (flag1) + { + ObservableCollection observableCollection = this.Coberturas; + if (observableCollection != null) + { + list = observableCollection.Where((Cobertura x) => { + if (string.IsNullOrEmpty(x.get_Observacao())) + { + return false; + } + if (x.get_Franquia() != decimal.Zero || x.get_Lmi() != decimal.Zero) + { + return true; + } + return x.get_Premio() != decimal.Zero; + }).ToList(); + } + else + { + list = null; + } + } + else + { + ObservableCollection coberturas1 = this.Coberturas; + if (coberturas1 != null) + { + list = coberturas1.ToList(); + } + else + { + list = null; + } + } + return list; + } + + public async Task SelectionaCoberturas() + { + if (this.Ramo != null) + { + this.CoberturasPadrao = ( + from x in Recursos.Coberturas + where x.get_IdRamo() == this.Ramo.get_Id() + select x).ToList(); + if (this.Item != null) + { + this.Coberturas = await this._itemServico.BuscarCoberturasPorItemAsync(this.Item.get_Id()); + } + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Comissao/ComissaoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Comissao/ComissaoViewModel.cs new file mode 100644 index 0000000..54cff8f --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Comissao/ComissaoViewModel.cs @@ -0,0 +1,3450 @@ +using CsQuery.ExtensionMethods; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Infrastructure.Helpers; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Relatorios.Extrato; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Comissao +{ + public class ComissaoViewModel : BaseSegurosViewModel + { + private readonly ServicoExtrato _servico; + + private readonly ApoliceServico _apoliceServico; + + private readonly ParcelaServico _parcelaServico; + + private readonly VendedorServico _vendedorServico; + + private bool _apelido; + + private bool _baixarVisibility; + + private bool _finalizarVisibility; + + private bool _desconsiderarVisibility; + + private bool _desfazerVisibility; + + private ObservableCollection _seguradoras = new ObservableCollection(); + + private DateTime _inicio; + + private DateTime _fim; + + private bool _baixarPendentes; + + private ObservableCollection _extratos; + + private ObservableCollection _extratosFiltrados; + + private Extrato _selectedExtrato; + + private ObservableCollection _usuarios; + + private Usuario _selectedUsuario; + + private List _statusExtrato; + + private StatusExtrato _selectedStatusExtrato; + + private Seguradora _selectedSeguradora; + + private Gestor.Model.Domain.Seguros.DetalheExtrato _selectedDetalhe; + + private FiltroStatusDocumento _selectedStatus; + + private Cliente _selectedCliente; + + private string _documentoPrincipal; + + private ObservableCollection _detalheExtrato; + + private bool _allSelected; + + private ObservableCollection _detalheExtratoFiltrados; + + private int _quantidade; + + private decimal _totalBaixado; + + private decimal _totalPendente; + + private Visibility _isVisibleCliente; + + private Visibility _isVisibleApolice; + + private Visibility _isVisibleMensagem; + + private Visibility _isVisibleDetalhes; + + private Visibility _isVisibleExtrato; + + private bool _isExpanded; + + private ObservableCollection _apolices; + + private bool _idFatura; + + private Documento _selectedDocumento; + + private Parcela _selectedParcela; + + private ObservableCollection _parcelas; + + private decimal _porcentagemExtrato; + + private decimal _porcentagem; + + private decimal _indiceTotal; + + private decimal _indice; + + private decimal _totaExtratosl; + + private decimal _total; + + private bool _criticando; + + private string _filtro; + + private string _pesquisaPagamento; + + private string _filtroApolice; + + private ObservableCollection _filtroPersonalizado; + + private bool _carregadoDetalhes + { + get; + set; + } + + public bool AllSelected + { + get + { + return this._allSelected; + } + set + { + this._allSelected = value; + base.OnPropertyChanged("AllSelected"); + if (this._carregadoDetalhes) + { + return; + } + this.Selecionar(value); + } + } + + public bool Apelido + { + get + { + return this._apelido; + } + set + { + this._apelido = value; + base.OnPropertyChanged("Apelido"); + } + } + + public ObservableCollection Apolices + { + get + { + return this._apolices; + } + set + { + this._apolices = value; + base.OnPropertyChanged("Apolices"); + } + } + + public bool BaixarPendentes + { + get + { + return this._baixarPendentes; + } + set + { + this._baixarPendentes = value; + base.OnPropertyChanged("BaixarPendentes"); + } + } + + public bool BaixarVisibility + { + get + { + return this._baixarVisibility; + } + set + { + this._baixarVisibility = value; + base.OnPropertyChanged("BaixarVisibility"); + } + } + + public bool Buscando + { + get; + set; + } + + private bool Carregando + { + get; + set; + } + + public bool Criticando + { + get + { + return this._criticando; + } + set + { + this._criticando = value; + base.OnPropertyChanged("Criticando"); + } + } + + public bool DesconsiderarVisibility + { + get + { + return this._desconsiderarVisibility; + } + set + { + this._desconsiderarVisibility = value; + base.OnPropertyChanged("DesconsiderarVisibility"); + } + } + + public bool DesfazerVisibility + { + get + { + return this._desfazerVisibility; + } + set + { + this._desfazerVisibility = value; + base.OnPropertyChanged("DesfazerVisibility"); + } + } + + public ObservableCollection DetalheExtrato + { + get + { + return this._detalheExtrato; + } + set + { + bool hasValue; + decimal zero; + this._detalheExtrato = value; + this.Quantidade = (value != null ? value.Count : 0); + List statusParcelas = new List() + { + 1, + 10, + 13 + }; + this.TotalBaixado = (value != null ? value.Where((Gestor.Model.Domain.Seguros.DetalheExtrato x) => { + if (!x.get_Status().HasValue || !x.get_ValorComissao().HasValue) + { + return false; + } + return statusParcelas.Contains(x.get_Status().Value); + }).Sum((Gestor.Model.Domain.Seguros.DetalheExtrato x) => x.get_ValorComissao().Value) : decimal.Zero); + Extrato selectedExtrato = this.SelectedExtrato; + if (selectedExtrato != null) + { + hasValue = selectedExtrato.get_Bruto().HasValue; + } + else + { + hasValue = false; + } + if (hasValue) + { + decimal? bruto = this.SelectedExtrato.get_Bruto(); + zero = bruto.Value - this.TotalBaixado; + } + else + { + zero = decimal.Zero; + } + this.TotalPendente = zero; + base.OnPropertyChanged("DetalheExtrato"); + } + } + + public ObservableCollection DetalheExtratoFiltrados + { + get + { + return this._detalheExtratoFiltrados; + } + set + { + this._detalheExtratoFiltrados = value; + base.OnPropertyChanged("DetalheExtratoFiltrados"); + } + } + + public string DocumentoPrincipal + { + get + { + return this._documentoPrincipal; + } + set + { + this._documentoPrincipal = value; + base.OnPropertyChanged("DocumentoPrincipal"); + } + } + + public ObservableCollection Extratos + { + get + { + return this._extratos; + } + set + { + this._extratos = value; + if (value == null || value.Count == 0) + { + this.DetalheExtrato = null; + this.DetalheExtratoFiltrados = null; + } + base.OnPropertyChanged("Extratos"); + } + } + + public ObservableCollection ExtratosFiltrados + { + get + { + return this._extratosFiltrados; + } + set + { + bool id; + this._extratosFiltrados = value; + this.BaixarPendentes = (value == null ? false : value.Count > 0); + if (value == null || value.Count <= 0) + { + id = false; + } + else + { + Usuario usuario = Recursos.Usuario; + if (usuario != null) + { + id = usuario.get_Id() > (long)0; + } + else + { + id = false; + } + } + base.EnableButtons = id; + this.IsVisibleExtrato = (value == null || value.Count <= 0 ? Visibility.Collapsed : Visibility.Visible); + base.OnPropertyChanged("ExtratosFiltrados"); + } + } + + public string Filtro + { + get + { + return this._filtro; + } + set + { + this._filtro = value; + base.OnPropertyChanged("Filtro"); + } + } + + public string FiltroApolice + { + get + { + return this._filtroApolice; + } + set + { + this._filtroApolice = value; + base.OnPropertyChanged("FiltroApolice"); + } + } + + public ObservableCollection FiltroPersonalizado + { + get + { + return this._filtroPersonalizado; + } + set + { + this._filtroPersonalizado = value; + base.OnPropertyChanged("FiltroPersonalizado"); + } + } + + public DateTime Fim + { + get + { + return this._fim; + } + set + { + this._fim = value; + base.OnPropertyChanged("Fim"); + } + } + + public bool FinalizarVisibility + { + get + { + return this._finalizarVisibility; + } + set + { + this._finalizarVisibility = value; + base.OnPropertyChanged("FinalizarVisibility"); + } + } + + private List Impostos + { + get; + set; + } + + public decimal Indice + { + get + { + return this._indice; + } + set + { + this._indice = value; + base.OnPropertyChanged("Indice"); + } + } + + public decimal IndiceTotal + { + get + { + return this._indiceTotal; + } + set + { + this._indiceTotal = value; + base.OnPropertyChanged("IndiceTotal"); + } + } + + public DateTime Inicio + { + get + { + return this._inicio; + } + set + { + this._inicio = value; + base.OnPropertyChanged("Inicio"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public bool IsFatura + { + get + { + return this._idFatura; + } + set + { + this._idFatura = value; + base.OnPropertyChanged("IsFatura"); + } + } + + public Visibility IsVisibleApolice + { + get + { + return this._isVisibleApolice; + } + set + { + this._isVisibleApolice = value; + base.OnPropertyChanged("IsVisibleApolice"); + } + } + + public Visibility IsVisibleCliente + { + get + { + return this._isVisibleCliente; + } + set + { + this._isVisibleCliente = value; + base.OnPropertyChanged("IsVisibleCliente"); + } + } + + public Visibility IsVisibleDetalhes + { + get + { + return this._isVisibleDetalhes; + } + set + { + this._isVisibleDetalhes = value; + base.OnPropertyChanged("IsVisibleDetalhes"); + } + } + + public Visibility IsVisibleExtrato + { + get + { + return this._isVisibleExtrato; + } + set + { + this._isVisibleExtrato = value; + base.OnPropertyChanged("IsVisibleExtrato"); + } + } + + public Visibility IsVisibleMensagem + { + get + { + return this._isVisibleMensagem; + } + set + { + this._isVisibleMensagem = value; + base.OnPropertyChanged("IsVisibleMensagem"); + } + } + + public ObservableCollection Parcelas + { + get + { + return this._parcelas; + } + set + { + this._parcelas = value; + base.OnPropertyChanged("Parcelas"); + } + } + + public string PesquisaPagamento + { + get + { + return this._pesquisaPagamento; + } + set + { + this._pesquisaPagamento = value; + base.OnPropertyChanged("PesquisaPagamento"); + } + } + + public decimal Porcentagem + { + get + { + return this._porcentagem; + } + set + { + this._porcentagem = value; + base.OnPropertyChanged("Porcentagem"); + } + } + + public decimal PorcentagemExtrato + { + get + { + return this._porcentagemExtrato; + } + set + { + this._porcentagemExtrato = value; + base.OnPropertyChanged("PorcentagemExtrato"); + } + } + + public int Quantidade + { + get + { + return this._quantidade; + } + set + { + this._quantidade = value; + base.OnPropertyChanged("Quantidade"); + } + } + + public ObservableCollection Seguradoras + { + get + { + return this._seguradoras; + } + set + { + this._seguradoras = value; + this.SelectedSeguradora = this.SelectedSeguradora ?? value.FirstOrDefault(); + base.OnPropertyChanged("Seguradoras"); + } + } + + public Cliente SelectedCliente + { + get + { + return this._selectedCliente; + } + set + { + this.WorkOnSelectedCliente(value); + this._selectedCliente = value; + base.OnPropertyChanged("SelectedCliente"); + } + } + + public Gestor.Model.Domain.Seguros.DetalheExtrato SelectedDetalhe + { + get + { + return this._selectedDetalhe; + } + set + { + this._selectedDetalhe = value; + base.OnPropertyChanged("SelectedDetalhe"); + } + } + + public Documento SelectedDocumento + { + get + { + return this._selectedDocumento; + } + set + { + this._selectedDocumento = value; + this.WorkOnSelectedDocumento(value); + base.OnPropertyChanged("SelectedDocumento"); + } + } + + public Extrato SelectedExtrato + { + get + { + return this._selectedExtrato; + } + set + { + this._selectedExtrato = value; + this.IsVisibleExtrato = (value != null ? Visibility.Visible : Visibility.Collapsed); + base.OnPropertyChanged("SelectedExtrato"); + } + } + + public Parcela SelectedParcela + { + get + { + return this._selectedParcela; + } + set + { + this._selectedParcela = value; + base.OnPropertyChanged("SelectedParcela"); + } + } + + public Seguradora SelectedSeguradora + { + get + { + return this._selectedSeguradora; + } + set + { + this._selectedSeguradora = value; + this.FiltroPersonalizado = new ObservableCollection(); + this.SelecionaSeguradora(value, this.SelectedStatusExtrato, null); + base.OnPropertyChanged("SelectedSeguradora"); + } + } + + public FiltroStatusDocumento SelectedStatus + { + get + { + return this._selectedStatus; + } + set + { + this._selectedStatus = value; + this.WorkOnSelectedStatus(); + base.OnPropertyChanged("SelectedStatus"); + } + } + + public StatusExtrato SelectedStatusExtrato + { + get + { + return this._selectedStatusExtrato; + } + set + { + this._selectedStatusExtrato = value; + this.SelecionaSeguradora(this.SelectedSeguradora, value, null); + base.OnPropertyChanged("SelectedStatusExtrato"); + } + } + + public Usuario SelectedUsuario + { + get + { + return this._selectedUsuario; + } + set + { + this._selectedUsuario = value; + this.SelecionaSeguradora(this.SelectedSeguradora, this.SelectedStatusExtrato, null); + base.OnPropertyChanged("SelectedUsuario"); + } + } + + public List Status + { + get + { + return this._statusExtrato; + } + set + { + this._statusExtrato = value; + base.OnPropertyChanged("Status"); + } + } + + public ObservableCollection TodasApolices + { + get; + set; + } + + public decimal Total + { + get + { + return this._total; + } + set + { + this._total = value; + base.OnPropertyChanged("Total"); + } + } + + public decimal TotalBaixado + { + get + { + return this._totalBaixado; + } + set + { + this._totalBaixado = value; + base.OnPropertyChanged("TotalBaixado"); + } + } + + public decimal TotalExtratos + { + get + { + return this._totaExtratosl; + } + set + { + this._totaExtratosl = value; + base.OnPropertyChanged("TotalExtratos"); + } + } + + public decimal TotalPendente + { + get + { + return this._totalPendente; + } + set + { + this._totalPendente = value; + base.OnPropertyChanged("TotalPendente"); + } + } + + public ObservableCollection Usuarios + { + get + { + return this._usuarios; + } + set + { + this._usuarios = value; + this.SelectedUsuario = this.SelectedUsuario ?? value.FirstOrDefault(); + base.OnPropertyChanged("Usuarios"); + } + } + + public ComissaoViewModel() + { + this._seguradoras = new ObservableCollection(); + DateTime date = Funcoes.GetNetworkTime().Date; + int year = date.Year; + date = Funcoes.GetNetworkTime().Date; + this._inicio = new DateTime(year, date.Month, 1); + this._fim = Funcoes.GetNetworkTime().Date; + this._baixarPendentes = true; + this._extratos = new ObservableCollection(); + this._extratosFiltrados = new ObservableCollection(); + this._usuarios = new ObservableCollection(); + this._statusExtrato = new List() + { + 1, + 2, + 3, + 4 + }; + this._selectedStatusExtrato = 1; + this._documentoPrincipal = ""; + this._isVisibleCliente = Visibility.Collapsed; + this._isVisibleApolice = Visibility.Collapsed; + this._isVisibleMensagem = Visibility.Collapsed; + this._isVisibleDetalhes = Visibility.Collapsed; + this._isVisibleExtrato = Visibility.Collapsed; + this._isExpanded = true; + this._apolices = new ObservableCollection(); + this._selectedDocumento = new Documento(); + this._selectedParcela = new Parcela(); + this._parcelas = new ObservableCollection(); + this.Impostos = new List(); + this._filtro = ""; + this._pesquisaPagamento = ""; + this._filtroApolice = ""; + this._filtroPersonalizado = new ObservableCollection(); + base(); + this._servico = new ServicoExtrato(); + this._apoliceServico = new ApoliceServico(); + this._parcelaServico = new ParcelaServico(); + this._vendedorServico = new VendedorServico(); + this.Apelido = Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 6); + this.SelecionaSeguradoras(); + base.EnableMenu = true; + } + + public void AdcionarFiltro() + { + if (string.IsNullOrEmpty(this.Filtro)) + { + return; + } + if (this.FiltroPersonalizado == null) + { + this.FiltroPersonalizado = new ObservableCollection(); + } + this.FiltroPersonalizado.Add(this.Filtro); + this.Filtro = string.Empty; + this.FiltrarExtrato(); + } + + public async Task AtualizarExtrato() + { + if (this.DetalheExtratoFiltrados != null && this.DetalheExtratoFiltrados.Count != 0) + { + ObservableCollection detalheExtratoFiltrados = this.DetalheExtratoFiltrados; + if (!detalheExtratoFiltrados.All((Gestor.Model.Domain.Seguros.DetalheExtrato x) => !x.get_Selecionado())) + { + base.Loading(true); + this.IsVisibleDetalhes = Visibility.Collapsed; + base.IsVisible = Visibility.Collapsed; + ParcelaServico parcelaServico = this._parcelaServico; + ObservableCollection observableCollection = this.DetalheExtratoFiltrados; + await parcelaServico.UpdateDetalhes(( + from x in observableCollection + where x.get_Selecionado() + select x).ToList()); + base.IsVisible = Visibility.Visible; + this.IsVisibleDetalhes = Visibility.Visible; + base.Loading(false); + base.RegistrarAcao(string.Format("ATUALIZOU EXTRATO DE ID \n{0}\n", this.SelectedExtrato.get_Id()), this.SelectedExtrato.get_Id(), new TipoTela?(35), null); + base.ToggleSnackBar("EXTRATO ATUALIZADO COM SUCESSO", true); + } + else + { + await base.ShowMessage("NECESSÁRIO SELECIONAR QUAL PARCELA DESEJA ATUALIZAR.", "OK", "", false); + } + } + } + + private async Task BaixarComissao(List extrato, bool selecionados = false) + { + bool flag; + try + { + List statusParcelas = new List() + { + 9, + 14, + 16, + 4, + 17, + 15, + 7, + 18 + }; + List statusParcelas1 = statusParcelas; + List statusParcelas2 = new List() + { + 16, + 18 + }; + flag = (selecionados ? false : this.DetalheExtrato.ToList().Any((Gestor.Model.Domain.Seguros.DetalheExtrato x) => statusParcelas2.Contains(x.get_Status().Value))); + bool flag1 = flag; + if (flag1) + { + flag1 = !await base.ShowMessage("O EXTRATO CONTÉM PARCELAS ENCONTRADAS POR APROXIMAÇÃO, DESEJA BAIXÁ-LAS?", "SIM", "NÃO", false); + } + if (flag1) + { + extrato = ( + from parcela in extrato + where !statusParcelas2.Contains(parcela.get_Status().Value) + select parcela).ToList(); + } + List list = extrato.Where((Gestor.Model.Domain.Seguros.DetalheExtrato x) => { + if (!x.get_Status().HasValue) + { + return false; + } + return statusParcelas1.Contains(x.get_Status().Value); + }).ToList(); + if (list.Any()) + { + ComissaoViewModel comissaoViewModel = this; + List detalheExtratos = list; + IOrderedEnumerable cliente = + from x in detalheExtratos + orderby x.get_Cliente() + select x; + IOrderedEnumerable detalheExtratos1 = cliente.ThenBy((Gestor.Model.Domain.Seguros.DetalheExtrato x) => x.get_Apolice()); + IOrderedEnumerable detalheExtratos2 = detalheExtratos1.ThenBy((Gestor.Model.Domain.Seguros.DetalheExtrato x) => x.get_Endosso()); + await comissaoViewModel.BaixarExtrato(detalheExtratos2.ThenBy((Gestor.Model.Domain.Seguros.DetalheExtrato x) => ValidationHelper.ToInt(x.get_NumeroParcela())).ToList()); + } + else + { + this.SelectedExtrato.set_Status(3); + await this._servico.Save(this.SelectedExtrato); + if (this._servico.Sucesso) + { + await base.ShowMessage("NÃO HÁ PARCELAS A BAIXAR NESSE EXTRATO", "OK", "", false); + return; + } + else + { + return; + } + } + } + catch (Exception exception) + { + } + } + + public async Task BaixarExtrato(bool selecionados = false) + { + List list; + if (this.DetalheExtrato != null && this.DetalheExtrato.Count != 0) + { + List detalheExtratos = this.DetalheExtrato.ToList(); + if (!detalheExtratos.All((Gestor.Model.Domain.Seguros.DetalheExtrato x) => x.get_Status().GetValueOrDefault() == 6)) + { + StatusExtrato status = this.SelectedExtrato.get_Status(); + if (selecionados) + { + ObservableCollection detalheExtrato = this.DetalheExtrato; + list = ( + from x in detalheExtrato + where x.get_Selecionado() + select x).ToList(); + } + else + { + list = this.DetalheExtrato.ToList(); + } + await this.BaixarComissao(list, selecionados); + base.RegistrarAcao(string.Format("BAIXOU EXTRATO DE ID \n{0}\n", this.SelectedExtrato.get_Id()), this.SelectedExtrato.get_Id(), new TipoTela?(35), null); + if (this.SelectedExtrato.get_Status() != 3) + { + this.SelectedStatusExtrato = this.SelectedExtrato.get_Status(); + } + this.SelectedExtrato = null; + this.SelecionaSeguradora(this.SelectedSeguradora, status, null); + base.ToggleSnackBar("EXTRATO BAIXADO COM SUCESSO", true); + } + else + { + this.SelectedExtrato.set_Status(3); + await this._servico.Save(this.SelectedExtrato); + if (this._servico.Sucesso) + { + this.SelectedStatusExtrato = 3; + await this.SelecionaExtrato(this.SelectedExtrato); + base.ToggleSnackBar("TODAS AS PARCELAS FORAM DESCONSIDERADAS PELO USUARIO", true); + } + } + } + } + + private async Task BaixarExtrato(List baixar) + { + List documentos; + long num1; + List vendedorParcelas; + decimal? valorComissao; + DateTime? recebimento; + int? nullable; + List list; + StatusParcela? nullable1; + DateTime? nullable2; + bool valueOrDefault; + string str; + string str1; + DateTime? nullable3; + decimal comissao; + SubTipo subTipo; + int valueOrDefault1; + DateTime? nullable4; + string str2; + DateTime? nullable5; + int? nullable6; + decimal? nullable7; + decimal? nullable8; + decimal? comissao1; + bool ordem; + ComissaoViewModel.u003cu003ec__DisplayClass225_0 variable; + Parcela parcela1; + bool flag = true; + await this.CarregarImpostos(); + this._apoliceServico.Sucesso = true; + this._servico.Sucesso = true; + this.Porcentagem = decimal.Zero; + this.Indice = decimal.Zero; + this.Total = baixar.Count; + List detalheExtratos = baixar; + IEnumerable hasValue = + from x in detalheExtratos + where x.get_Documento().HasValue + select x; + List nums = ( + from x in hasValue + select x.get_Documento().Value).ToList(); + List detalheExtratos1 = baixar; + IEnumerable detalheExtratos2 = detalheExtratos1.Where((Gestor.Model.Domain.Seguros.DetalheExtrato x) => { + if (x.get_Documento().HasValue) + { + return false; + } + return x.get_Parcela().HasValue; + }); + List list1 = ( + from x in detalheExtratos2 + select x.get_Parcela().Value).ToList(); + if (nums.Count <= 0) + { + documentos = new List(); + } + else + { + documentos = await this._apoliceServico.BuscarApolicesPorId(nums); + } + List documentos1 = documentos; + if (list1.Count > 0) + { + List documentos2 = documentos1; + documentos = await this._apoliceServico.BuscarApolicesPorIdParcela(list1); + documentos2.AddRange(documentos); + documentos2 = null; + } + ParcelaServico parcelaServico = this._parcelaServico; + List documentos3 = documentos1; + List parcelas = await parcelaServico.BuscarTodasParcelas(( + from x in documentos3 + select x.get_Id()).ToList()); + parcelas.ForEach((Parcela p) => p.set_Documento(documentos1.Find((Documento d) => d.get_Id() == p.get_Documento().get_Id()))); + foreach (Gestor.Model.Domain.Seguros.DetalheExtrato detalheExtrato in baixar) + { + long? documento = detalheExtrato.get_Documento(); + if (!documento.HasValue) + { + documento = detalheExtrato.get_Parcela(); + if (!documento.HasValue) + { + detalheExtrato.set_Status(new StatusParcela?(2)); + await this._servico.Save(detalheExtrato); + continue; + } + } + decimal indice = this.Indice; + this.Indice = indice++; + this.Porcentagem = (this.Indice * new decimal(100)) / this.Total; + bool flag1 = false; + Documento documento1 = null; + documento = detalheExtrato.get_Documento(); + if (documento.HasValue) + { + documento = detalheExtrato.get_Documento(); + num1 = (long)0; + if (documento.GetValueOrDefault() > num1 & documento.HasValue) + { + documento1 = documentos1.Find((Documento d) => d.get_Id() == detalheExtrato.get_Documento().Value); + } + } + if (!documento1.get_Excluido()) + { + if (documento1 != null && documento1.get_TipoRecebimento().GetValueOrDefault() == 1 && documento1.get_Comissao() == decimal.Zero) + { + documento = detalheExtrato.get_Parcela(); + if (documento.HasValue) + { + documento = detalheExtrato.get_Parcela(); + num1 = (long)999; + if (documento.GetValueOrDefault() != num1 | !documento.HasValue) + { + Documento documento2 = documento1; + if (documento2 != null) + { + ordem = documento2.get_Ordem() == 0; + } + else + { + ordem = false; + } + if (ordem) + { + continue; + } + } + } + } + bool flag2 = true; + documento = detalheExtrato.get_Documento(); + if (documento.HasValue) + { + IEnumerable id = + from p in parcelas + where p.get_Documento().get_Id() == detalheExtrato.get_Documento().Value + select p; + list = ( + from p in id + orderby p.get_NumeroParcela() + select p).ToList(); + } + else + { + list = null; + } + List parcelas1 = list; + documento = detalheExtrato.get_Parcela(); + if (!documento.HasValue) + { + if (parcelas1.Count <= 0) + { + VendedorServico vendedorServico = this._vendedorServico; + documento = detalheExtrato.get_Documento(); + vendedorParcelas = await vendedorServico.BuscaRepasse(documento.Value); + } + else + { + vendedorParcelas = await this._vendedorServico.BuscaRepasseParcela(parcelas1.First().get_Id()); + } + List vendedorParcelas1 = vendedorParcelas; + Imposto imposto = this.CarregarImposto(documento1); + valorComissao = detalheExtrato.get_ValorComissao(); + decimal valueOrDefault2 = valorComissao.GetValueOrDefault() * imposto.get_Ir(); + valorComissao = detalheExtrato.get_ValorComissao(); + decimal num2 = valorComissao.GetValueOrDefault() * imposto.get_Iss(); + valorComissao = detalheExtrato.get_ValorComissao(); + decimal valueOrDefault3 = valorComissao.GetValueOrDefault() * imposto.get_Outros(); + valorComissao = detalheExtrato.get_ValorComissao(); + decimal num3 = valorComissao.GetValueOrDefault() * imposto.get_Desconto(); + valorComissao = detalheExtrato.get_ValorComissao(); + decimal valueOrDefault4 = valorComissao.GetValueOrDefault() - (((valueOrDefault2 + num2) + valueOrDefault3) + num3); + if (documento1.get_TipoRecebimento().GetValueOrDefault() == 1) + { + recebimento = null; + nullable3 = recebimento; + } + else + { + recebimento = detalheExtrato.get_Recebimento(); + nullable3 = (!recebimento.HasValue ? this.SelectedExtrato.get_Data() : detalheExtrato.get_Recebimento()); + } + DateTime? nullable9 = nullable3; + if (documento1.get_TipoRecebimento().GetValueOrDefault() == 1) + { + comissao = new decimal(100); + } + else + { + Parcela parcela2 = parcelas1.FirstOrDefault(); + if (parcela2 != null) + { + comissao = parcela2.get_Comissao(); + } + else + { + valorComissao = detalheExtrato.get_Comissao(); + comissao = valorComissao.GetValueOrDefault(new decimal(100)); + } + } + decimal value = comissao; + if (value == new decimal(100)) + { + valorComissao = detalheExtrato.get_Valor(); + if (valorComissao.HasValue) + { + valorComissao = detalheExtrato.get_Comissao(); + if (valorComissao.HasValue) + { + valorComissao = detalheExtrato.get_ValorComissao(); + if (valorComissao.HasValue) + { + valorComissao = detalheExtrato.get_Valor(); + decimal? comissao2 = detalheExtrato.get_Comissao(); + indice = 100; + if (comissao2.HasValue) + { + nullable7 = new decimal?(comissao2.GetValueOrDefault() / indice); + } + else + { + nullable7 = null; + } + decimal? nullable10 = nullable7; + if (valorComissao.HasValue & nullable10.HasValue) + { + nullable8 = new decimal?(valorComissao.GetValueOrDefault() * nullable10.GetValueOrDefault()); + } + else + { + comissao2 = null; + nullable8 = comissao2; + } + comissao2 = nullable8; + decimal value1 = comissao2.Value; + valorComissao = detalheExtrato.get_ValorComissao(); + decimal value2 = valorComissao.Value; + if (Math.Truncate(value1) == Math.Truncate(value2)) + { + Gestor.Model.Domain.Seguros.DetalheExtrato detalheExtrato1 = detalheExtrato; + if (detalheExtrato1 != null) + { + comissao1 = detalheExtrato1.get_Comissao(); + } + else + { + valorComissao = null; + comissao1 = valorComissao; + } + valorComissao = comissao1; + value = valorComissao.Value; + } + } + } + } + } + Parcela parcela3 = new Parcela(); + parcela3.set_Documento(documento1); + parcela3.set_Vencimento(Funcoes.GetNetworkTime().Date); + parcela3.set_Comissao(value); + if (documento1.get_TipoRecebimento().GetValueOrDefault() == 1) + { + subTipo = detalheExtrato.get_SubTipo().GetValueOrDefault(3); + } + else + { + subTipo = 1; + } + parcela3.set_SubTipo(subTipo); + if (documento1.get_TipoRecebimento().GetValueOrDefault() == 1) + { + valueOrDefault1 = 999; + } + else + { + List parcelas2 = parcelas1; + if (parcelas2 != null) + { + Parcela parcela4 = parcelas2.LastOrDefault(); + if (parcela4 != null) + { + nullable6 = new int?(parcela4.get_NumeroParcela()); + } + else + { + nullable = null; + nullable6 = nullable; + } + } + else + { + nullable = null; + nullable6 = nullable; + } + nullable = nullable6; + valueOrDefault1 = nullable.GetValueOrDefault() + 1; + } + parcela3.set_NumeroParcela(valueOrDefault1); + valorComissao = detalheExtrato.get_Valor(); + parcela3.set_Valor(valorComissao.GetValueOrDefault()); + valorComissao = detalheExtrato.get_Valor(); + parcela3.set_ValorRealizado(valorComissao.GetValueOrDefault()); + valorComissao = detalheExtrato.get_ValorComissao(); + parcela3.set_ValorComissao(valorComissao.GetValueOrDefault()); + parcela3.set_Irr(valueOrDefault2); + parcela3.set_Iss(num2); + parcela3.set_Outros(valueOrDefault3); + parcela3.set_Desconto(num3); + parcela3.set_ValorComDesconto(valueOrDefault4); + parcela3.set_DataRecebimento(this.SelectedExtrato.get_Data()); + recebimento = this.SelectedExtrato.get_DataCredito(); + nullable4 = (recebimento.HasValue ? recebimento : this.SelectedExtrato.get_Data()); + parcela3.set_DataCredito(nullable4); + str2 = (documento1.get_TipoRecebimento().GetValueOrDefault() == 1 ? "" : detalheExtrato.get_Endosso()); + parcela3.set_Fatura(str2); + parcela3.set_Emissao(nullable9); + parcela3.set_VigenciaIncial(nullable9); + if (documento1.get_TipoRecebimento().GetValueOrDefault() == 1) + { + recebimento = null; + nullable5 = recebimento; + } + else if (nullable9.HasValue) + { + DateTime dateTime = nullable9.GetValueOrDefault(); + nullable5 = new DateTime?(dateTime.AddMonths(1)); + } + else + { + recebimento = null; + nullable5 = recebimento; + } + parcela3.set_VigenciaFinal(nullable5); + parcela3.set_Extrato(detalheExtrato.get_Extrato().get_Numero()); + parcela3.set_DataCriacao(new DateTime?(DateTime.Now)); + parcela1 = parcela3; + if (documento1.get_Ordem() > 0) + { + VendedorServico vendedorServico1 = this._vendedorServico; + Controle controle = await this._apoliceServico.BuscarControleAsync(documento1.get_Controle().get_Id()); + VendedorServico vendedorServico2 = vendedorServico1; + IList documentos4 = controle.get_Documentos(); + vendedorServico1 = null; + vendedorParcelas1 = await vendedorServico2.BuscaRepasse(documentos4.First((Documento d) => d.get_Ordem() == 0).get_Id()); + List vendedorParcelas2 = vendedorParcelas1; + vendedorParcelas1 = Funcoes.DistinctBy(vendedorParcelas2, (VendedorParcela v) => v.get_TipoVendedor()).ToList(); + } + if (vendedorParcelas1 != null) + { + List vendedorParcelas3 = vendedorParcelas1; + ExtensionMethods.ForEach( + from v in vendedorParcelas3 + where v.get_Repasse() != null + select v, (VendedorParcela v) => { + v.set_Id((long)0); + decimal num = Funcoes.CalculaRepasse(v.get_Repasse(), parcela1, false); + if (v.get_Repasse().get_Forma().GetValueOrDefault() == 1) + { + v.set_DataPrePagamento(parcela1.get_DataRecebimento()); + } + BaseRepasse? @base = v.get_Repasse().get_Base(); + if (@base.HasValue) + { + switch (@base.GetValueOrDefault()) + { + case 1: + { + v.set_DataPrePagamento((documento1.get_TipoRecebimento().GetValueOrDefault() == 2 ? parcela1.get_VigenciaIncial() : new DateTime?(documento1.get_Vigencia1()))); + break; + } + case 2: + { + v.set_DataPrePagamento(parcela1.get_DataCriacao()); + break; + } + case 3: + { + v.set_DataPrePagamento(new DateTime?(parcela1.get_Vencimento())); + break; + } + case 4: + { + v.set_DataPrePagamento((documento1.get_TipoRecebimento().GetValueOrDefault() == 2 ? parcela1.get_Emissao() : documento1.get_Emissao())); + break; + } + case 5: + { + v.set_DataPrePagamento((documento1.get_TipoRecebimento().GetValueOrDefault() == 2 ? parcela1.get_Emissao() : documento1.get_Remessa())); + break; + } + } + } + v.set_ValorRepasse(new decimal?(num)); + v.set_ValorTotal(new decimal?(num)); + v.set_DataPagamento(null); + }); + } + if (vendedorParcelas1 == null || vendedorParcelas1.Count == 0) + { + vendedorParcelas1 = new List() + { + ComissaoViewModel.PropriaCorretora() + }; + } + if (parcela1.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1) + { + parcela1.set_Vendedores(new ObservableCollection(vendedorParcelas1)); + parcela1.set_Extrato(detalheExtrato.get_Extrato().get_Numero()); + Parcela parcela5 = await this._parcelaServico.Save(parcela1, this.Parcelas.ToList(), vendedorParcelas1, true); + parcela1 = parcela5; + if (this._parcelaServico.Sucesso) + { + detalheExtrato.set_Parcela(new long?(parcela1.get_Id())); + flag1 = true; + } + else + { + variable = null; + list1 = null; + parcelas = null; + return; + } + } + } + if (!flag1) + { + documento = detalheExtrato.get_Parcela(); + if (!documento.HasValue) + { + continue; + } + parcela1 = parcelas.Find((Parcela p) => p.get_Id() == detalheExtrato.get_Parcela().Value); + if (parcela1 == null) + { + continue; + } + detalheExtrato.set_Documento(new long?(parcela1.get_Documento().get_Id())); + recebimento = parcela1.get_DataRecebimento(); + if (!recebimento.HasValue) + { + List vendedorParcelas4 = await this._vendedorServico.BuscaRepasseParcela(parcela1.get_Id()); + Imposto imposto1 = this.CarregarImposto(documento1); + valorComissao = detalheExtrato.get_ValorComissao(); + decimal num4 = valorComissao.GetValueOrDefault() * imposto1.get_Ir(); + valorComissao = detalheExtrato.get_ValorComissao(); + decimal valueOrDefault5 = valorComissao.GetValueOrDefault() * imposto1.get_Iss(); + valorComissao = detalheExtrato.get_ValorComissao(); + decimal num5 = valorComissao.GetValueOrDefault() * imposto1.get_Outros(); + valorComissao = detalheExtrato.get_ValorComissao(); + decimal valueOrDefault6 = valorComissao.GetValueOrDefault() * imposto1.get_Desconto(); + valorComissao = detalheExtrato.get_ValorComissao(); + decimal num6 = valorComissao.GetValueOrDefault() - (((num4 + valueOrDefault5) + num5) + valueOrDefault6); + Parcela parcela6 = parcela1; + valorComissao = detalheExtrato.get_Valor(); + parcela6.set_ValorRealizado(valorComissao.GetValueOrDefault()); + Parcela parcela7 = parcela1; + valorComissao = detalheExtrato.get_ValorComissao(); + parcela7.set_ValorComissao(valorComissao.GetValueOrDefault()); + parcela1.set_Irr(num4); + parcela1.set_Iss(valueOrDefault5); + parcela1.set_Outros(num5); + parcela1.set_Desconto(valueOrDefault6); + parcela1.set_ValorComDesconto(num6); + parcela1.set_DataRecebimento(this.SelectedExtrato.get_Data()); + Parcela parcela8 = parcela1; + recebimento = this.SelectedExtrato.get_DataCredito(); + nullable2 = (recebimento.HasValue ? recebimento : this.SelectedExtrato.get_Data()); + parcela8.set_DataCredito(nullable2); + parcela1.set_Extrato(this.SelectedExtrato.get_Numero()); + parcela1.set_Vendedores(new ObservableCollection(vendedorParcelas4)); + documento1 = parcela1.get_Documento(); + List list2 = parcelas1; + if (list2 == null) + { + IEnumerable id1 = + from p in parcelas + where p.get_Documento().get_Id() == documento1.get_Id() + select p; + list2 = ( + from p in id1 + orderby p.get_NumeroParcela() + select p).ToList(); + } + parcelas1 = list2; + parcelas1.ForEach((Parcela p) => { + if (p.get_Id() != parcela1.get_Id()) + { + return; + } + p.set_ValorRealizado(parcela1.get_ValorRealizado()); + p.set_ValorComissao(parcela1.get_ValorComissao()); + p.set_Irr(parcela1.get_Irr()); + p.set_Iss(parcela1.get_Iss()); + p.set_Outros(parcela1.get_Outros()); + p.set_Desconto(parcela1.get_Desconto()); + p.set_ValorComDesconto(parcela1.get_ValorComDesconto()); + p.set_DataRecebimento(parcela1.get_DataRecebimento()); + Parcela parcela = p; + DateTime? dataCredito = parcela1.get_DataCredito(); + parcela.set_DataCredito((dataCredito.HasValue ? dataCredito : parcela1.get_DataRecebimento())); + p.set_Extrato(parcela1.get_Extrato()); + }); + bool flag3 = true; + if (parcela1.get_SubTipo() == 1) + { + List parcelas3 = parcelas1; + Parcela parcela9 = parcelas3.FirstOrDefault((Parcela p) => !p.get_DataRecebimento().HasValue); + if (parcela9 != null && parcela9.get_NumeroParcela() < parcela1.get_NumeroParcela()) + { + detalheExtrato.set_Status(new StatusParcela?(7)); + flag3 = false; + flag2 = false; + } + } + if (flag3) + { + Parcela parcela10 = parcela1; + List parcelas4 = parcelas1; + List list3 = parcela1.get_Vendedores().ToList(); + valorComissao = parcela1.get_Documento().get_Controle().get_Seguradora().get_Tolerancia(); + recebimento = await Funcoes.BaixarComissao(parcela10, parcelas4, list3, valorComissao.GetValueOrDefault(), true).get_DataRecebimento(); + if (!recebimento.HasValue) + { + continue; + } + Documento documento3 = parcela1.get_Documento(); + if (documento3 != null) + { + valueOrDefault = documento3.get_TipoRecebimento().GetValueOrDefault() == 1; + } + else + { + valueOrDefault = false; + } + str = (valueOrDefault ? string.Format("PARCELA {0} BAIXADA POR COMISSÃO AUTOMÁTICA, EXTRATO {1}", parcela1.get_NumeroParcela(), detalheExtrato.get_Extrato().get_Numero()) : string.Concat("FATURA ", parcela1.get_Fatura(), " BAIXADA POR COMISSÃO AUTOMÁTICA, EXTRATO ", detalheExtrato.get_Extrato().get_Numero())); + string str3 = str; + RegistroAcao registroAcao = new RegistroAcao(); + registroAcao.set_Descricao(str3); + registroAcao.set_EntidadeId(parcela1.get_Id()); + registroAcao.set_Tela(new TipoTela?(35)); + RegistroAcao registroAcao1 = registroAcao; + if (documento1.get_Tipo() == 0) + { + str1 = string.Concat("APÓLICE: ", detalheExtrato.get_Apolice()); + } + else if (documento1.get_TipoRecebimento().GetValueOrDefault() == 2) + { + string[] apolice = new string[] { "APÓLICE: ", detalheExtrato.get_Apolice(), Environment.NewLine, "FATURA: ", detalheExtrato.get_Endosso() }; + str1 = string.Concat(apolice); + } + else + { + string[] strArrays = new string[] { "APÓLICE: ", detalheExtrato.get_Apolice(), Environment.NewLine, "ENDOSSO: ", detalheExtrato.get_Endosso() }; + str1 = string.Concat(strArrays); + } + string str4 = str1; + object[] cliente = new object[] { detalheExtrato.get_Cliente(), Environment.NewLine, str4, Environment.NewLine, detalheExtrato.get_NumeroParcela(), detalheExtrato.get_Valor(), detalheExtrato.get_Comissao(), detalheExtrato.get_ValorComissao() }; + string str5 = string.Format("CLIENTE: {0}{1}{2}{3}PARCELA: {4}, VALOR: {5:c2} COMISSÃO: {6:N2}% VALOR COMISSÃO: {7:c2}", cliente); + this._parcelaServico.SalvarAcao(registroAcao1, str5); + } + } + else + { + detalheExtrato.set_Status(new StatusParcela?(5)); + await this._servico.Save(detalheExtrato); + continue; + } + } + if (detalheExtrato.get_Corrigir()) + { + if (!await this._apoliceServico.AtualizarNumero(documento1.get_Id(), detalheExtrato.get_Apolice(), detalheExtrato.get_Endosso(), documento1.get_Tipo())) + { + flag = false; + } + } + StatusParcela? status = detalheExtrato.get_Status(); + if (status.HasValue) + { + StatusParcela statusParcela = status.GetValueOrDefault(); + if (statusParcela == 4) + { + detalheExtrato.set_Status(new StatusParcela?(10)); + goto Label1; + } + else + { + if (statusParcela != 14) + { + goto Label2; + } + detalheExtrato.set_Status(new StatusParcela?(13)); + goto Label1; + } + } + Label2: + Gestor.Model.Domain.Seguros.DetalheExtrato detalheExtrato2 = detalheExtrato; + nullable1 = (flag2 ? new StatusParcela?(1) : detalheExtrato.get_Status()); + detalheExtrato2.set_Status(nullable1); + Label1: + await this._servico.Save(detalheExtrato); + if (this._servico.Sucesso) + { + parcelas1 = null; + } + else + { + variable = null; + list1 = null; + parcelas = null; + return; + } + } + else + { + detalheExtrato.set_Status(new StatusParcela?(2)); + await this._servico.Save(detalheExtrato); + } + } + this.SelectedExtrato.set_Status(3); + await this._servico.Save(this.SelectedExtrato); + if (!flag) + { + await base.ShowMessage("OCORREU UM ERRO AO ATUALIZAR O NÚMERO DA APÓLICE/ENDOSSO DOS DOCUMENTOS BAIXADOS.", "OK", "", false); + } + variable = null; + list1 = null; + parcelas = null; + } + + public async Task BaixarTodosExtratos() + { + Func func1 = null; + if (this.Extratos != null && this.Extratos.Count != 0) + { + StatusExtrato status = this.Extratos[0].get_Status(); + this.PorcentagemExtrato = decimal.Zero; + this.IndiceTotal = decimal.Zero; + this.TotalExtratos = this.Extratos.Count; + List statusParcelas = new List() + { + 9, + 14, + 16, + 4, + 17, + 15, + 18 + }; + List statusParcelas1 = statusParcelas; + await Task.Run(async () => { + ObservableCollection extratos = this.Extratos; + Func u003cu003e9_2281 = ComissaoViewModel.u003cu003ec.u003cu003e9__228_1; + if (u003cu003e9_2281 == null) + { + u003cu003e9_2281 = (Extrato x) => x.get_Data(); + ComissaoViewModel.u003cu003ec.u003cu003e9__228_1 = u003cu003e9_2281; + } + foreach (Extrato extrato in extratos.OrderBy(u003cu003e9_2281)) + { + decimal indiceTotal = this.IndiceTotal; + this.IndiceTotal = indiceTotal++; + this.PorcentagemExtrato = (this.IndiceTotal * new decimal(100)) / this.TotalExtratos; + ObservableCollection observableCollection = await this.CarregarDetalhes(extrato); + Func u003cu003e9_2 = func1; + if (u003cu003e9_2 == null) + { + Func hasValue = (Gestor.Model.Domain.Seguros.DetalheExtrato x) => { + if (!x.get_Status().HasValue) + { + return false; + } + return statusParcelas1.Contains(x.get_Status().Value); + }; + Func func = hasValue; + func1 = hasValue; + u003cu003e9_2 = func; + } + List list = observableCollection.Where(u003cu003e9_2).ToList(); + this.SelectedExtrato = extrato; + ComissaoViewModel u003cu003e4_this = this; + List detalheExtratos = list; + Func u003cu003e9_2283 = ComissaoViewModel.u003cu003ec.u003cu003e9__228_3; + if (u003cu003e9_2283 == null) + { + u003cu003e9_2283 = (Gestor.Model.Domain.Seguros.DetalheExtrato x) => x.get_Cliente(); + ComissaoViewModel.u003cu003ec.u003cu003e9__228_3 = u003cu003e9_2283; + } + IOrderedEnumerable detalheExtratos1 = detalheExtratos.OrderBy(u003cu003e9_2283); + Func u003cu003e9_2284 = ComissaoViewModel.u003cu003ec.u003cu003e9__228_4; + if (u003cu003e9_2284 == null) + { + u003cu003e9_2284 = (Gestor.Model.Domain.Seguros.DetalheExtrato x) => x.get_Apolice(); + ComissaoViewModel.u003cu003ec.u003cu003e9__228_4 = u003cu003e9_2284; + } + IOrderedEnumerable detalheExtratos2 = detalheExtratos1.ThenBy(u003cu003e9_2284); + Func u003cu003e9_2285 = ComissaoViewModel.u003cu003ec.u003cu003e9__228_5; + if (u003cu003e9_2285 == null) + { + u003cu003e9_2285 = (Gestor.Model.Domain.Seguros.DetalheExtrato x) => x.get_Endosso(); + ComissaoViewModel.u003cu003ec.u003cu003e9__228_5 = u003cu003e9_2285; + } + IOrderedEnumerable detalheExtratos3 = detalheExtratos2.ThenBy(u003cu003e9_2285); + Func u003cu003e9_2286 = ComissaoViewModel.u003cu003ec.u003cu003e9__228_6; + if (u003cu003e9_2286 == null) + { + u003cu003e9_2286 = (Gestor.Model.Domain.Seguros.DetalheExtrato x) => x.get_NumeroParcela(); + ComissaoViewModel.u003cu003ec.u003cu003e9__228_6 = u003cu003e9_2286; + } + await u003cu003e4_this.BaixarExtrato(detalheExtratos3.ThenBy(u003cu003e9_2286).ToList()); + } + }); + this.SelecionaSeguradora(this.SelectedSeguradora, status, null); + base.ToggleSnackBar("EXTRATOS BAIXADOS COM SUCESSO", true); + } + } + + public async Task BuscarCriticado(Gestor.Model.Domain.Seguros.DetalheExtrato detalhe) + { + long? parcela; + Parcela parcela1; + if (detalhe != null) + { + this.SelectedDetalhe = this.DetalheExtratoFiltrados.First((Gestor.Model.Domain.Seguros.DetalheExtrato x) => x.get_Id() == detalhe.get_Id()); + if (this.SelectedDetalhe.get_Parcela().HasValue || this.SelectedDetalhe.get_Documento().HasValue) + { + this.Buscando = true; + ParcelaServico parcelaServico = new ParcelaServico(); + parcela1 = null; + Documento documento = null; + if (this.SelectedDetalhe.get_Parcela().HasValue) + { + parcela = this.SelectedDetalhe.get_Parcela(); + parcela1 = await parcelaServico.BuscarParcela(parcela.Value); + if (parcela1 != null) + { + detalhe.set_Documento(new long?(parcela1.get_Documento().get_Id())); + documento = parcela1.get_Documento(); + } + } + if (this.SelectedDetalhe.get_Documento().HasValue && !this.SelectedDetalhe.get_Parcela().HasValue) + { + ApoliceServico apoliceServico = this._apoliceServico; + parcela = this.SelectedDetalhe.get_Documento(); + Documento documento1 = await apoliceServico.BuscarApoliceAsync(parcela.Value, false, false); + documento = documento1; + } + if (documento != null) + { + this.SelectedCliente = documento.get_Controle().get_Cliente(); + await this.SelecionaCliente(documento.get_Controle().get_Cliente()); + this.SelectedDocumento = this.Apolices.FirstOrDefault((Documento x) => x.get_Id() == documento.get_Id()); + await this.SelecionaDocumento(documento); + this.SelecionaParcela(parcela1); + this.Buscando = false; + } + else + { + this.Buscando = false; + } + } + else + { + this.TodasApolices = null; + this.Apolices = null; + this.Parcelas = null; + } + } + parcela1 = null; + } + + public async Task CarregaDetalhes(Extrato extrato) + { + if (extrato != null && extrato.get_Id() != 0) + { + this._carregadoDetalhes = true; + this.AllSelected = false; + this.DetalheExtrato = await this._servico.BuscarDetalhes(extrato.get_Id()); + this.DetalheExtratoFiltrados = this.DetalheExtrato; + this.SelecionaNormal(); + this._carregadoDetalhes = false; + List statusParcelas = new List() + { + 2, + 3 + }; + List statusParcelas1 = new List() + { + 1, + 13, + 10 + }; + List statusParcelas2 = new List() + { + 16, + 9, + 14, + 4, + 17, + 18 + }; + List statusParcelas3 = statusParcelas2; + List statusParcelas4 = new List() + { + 1, + 13, + 10, + 5, + 12, + 6, + 8 + }; + List statusParcelas5 = statusParcelas4; + this.DesfazerVisibility = this.DetalheExtrato.Any((Gestor.Model.Domain.Seguros.DetalheExtrato x) => { + if (!x.get_Status().HasValue) + { + return false; + } + return statusParcelas1.Contains(x.get_Status().Value); + }); + this.DesconsiderarVisibility = this.DetalheExtrato.Any((Gestor.Model.Domain.Seguros.DetalheExtrato x) => { + if (!x.get_Status().HasValue) + { + return false; + } + return statusParcelas.Contains(x.get_Status().Value); + }); + this.BaixarVisibility = this.DetalheExtrato.Any((Gestor.Model.Domain.Seguros.DetalheExtrato x) => { + if (!x.get_Status().HasValue) + { + return false; + } + return statusParcelas3.Contains(x.get_Status().Value); + }); + if (this.SelectedExtrato != null) + { + this.FinalizarVisibility = this.DetalheExtrato.All((Gestor.Model.Domain.Seguros.DetalheExtrato x) => { + if (!x.get_Status().HasValue || !statusParcelas5.Contains(x.get_Status().Value)) + { + return false; + } + if (this.SelectedExtrato.get_Status() == 1) + { + return true; + } + return !this.SelectedExtrato.get_Completo(); + }); + } + } + } + + private async Task> CarregarDetalhes(Extrato extrato) + { + return await this._servico.BuscarDetalhes(extrato.get_Id()); + } + + public Imposto CarregarImposto(Documento documento) + { + return this.Impostos.FirstOrDefault((Imposto x) => { + if (x.get_Seguradora() == null || x.get_Seguradora().get_Id() != documento.get_Controle().get_Seguradora().get_Id() || x.get_Ramo() == null) + { + return false; + } + return x.get_Ramo().get_Id() == documento.get_Controle().get_Ramo().get_Id(); + }) ?? this.Impostos.FirstOrDefault((Imposto x) => { + if (x.get_Seguradora() == null || x.get_Seguradora().get_Id() != documento.get_Controle().get_Seguradora().get_Id()) + { + return false; + } + return x.get_Ramo() == null; + }) ?? this.Impostos.FirstOrDefault((Imposto x) => { + if (x.get_Seguradora() != null || x.get_Ramo() == null) + { + return false; + } + return x.get_Ramo().get_Id() == documento.get_Controle().get_Ramo().get_Id(); + }) ?? this.Impostos.FirstOrDefault((Imposto x) => { + if (x.get_Seguradora() != null) + { + return false; + } + return x.get_Ramo() == null; + }) ?? new Imposto(); + } + + private async Task CarregarImpostos() + { + List impostos = await (new ImpostoServico()).Buscar(new bool?(true)); + ComissaoViewModel comissaoViewModel = this; + List impostos1 = impostos; + if (impostos1 == null) + { + impostos1 = new List(); + } + comissaoViewModel.Impostos = impostos1; + } + + public async Task Criticar(Gestor.Model.Domain.Seguros.DetalheExtrato detalhe, bool critica) + { + long? nullable; + StatusParcela statusParcela; + long? nullable1; + string str; + object obj; + bool subTipo; + StatusParcela statusParcela1; + ComissaoViewModel.u003cu003ec__DisplayClass215_0 variable; + List detalheExtratos; + if (detalhe != null && this.SelectedDocumento != null | !critica) + { + base.Loading(true); + this.IsVisibleDetalhes = Visibility.Collapsed; + detalheExtratos = new List(); + if (critica) + { + List configuracoes = Recursos.Configuracoes; + bool flag = configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 12); + SubTipo? subTipo1 = detalhe.get_SubTipo(); + if (!subTipo1.HasValue || subTipo1.GetValueOrDefault() > 1) + { + Gestor.Model.Domain.Seguros.DetalheExtrato detalheExtrato = detalhe; + if (this.SelectedParcela == null || !flag && this.SelectedParcela.get_SubTipo() == 1) + { + statusParcela = 17; + } + else + { + statusParcela = (this.SelectedParcela.get_DataRecebimento().HasValue ? 5 : 14); + } + detalheExtrato.set_Status(new StatusParcela?(statusParcela)); + detalhe.set_Documento(new long?(this.SelectedDocumento.get_Id())); + Gestor.Model.Domain.Seguros.DetalheExtrato detalheExtrato1 = detalhe; + if (this.SelectedParcela != null && this.SelectedParcela.get_Id() != 0) + { + if (!flag) + { + Parcela selectedParcela = this.SelectedParcela; + if (selectedParcela != null) + { + subTipo = selectedParcela.get_SubTipo() == 1; + } + else + { + subTipo = false; + } + if (subTipo) + { + goto Label1; + } + } + nullable1 = new long?(this.SelectedParcela.get_Id()); + goto Label0; + } + Label1: + nullable = null; + nullable1 = nullable; + Label0: + detalheExtrato1.set_Parcela(nullable1); + } + else + { + ObservableCollection parcelas = this.Parcelas; + Parcela parcela1 = parcelas.FirstOrDefault((Parcela x) => !x.get_DataRecebimento().HasValue); + Gestor.Model.Domain.Seguros.DetalheExtrato detalheExtrato2 = detalhe; + if (parcela1 == null || parcela1.get_NumeroParcela() >= this.SelectedParcela.get_NumeroParcela()) + { + statusParcela1 = (this.SelectedParcela.get_DataRecebimento().HasValue ? 5 : 14); + } + else + { + statusParcela1 = 7; + } + detalheExtrato2.set_Status(new StatusParcela?(statusParcela1)); + detalhe.set_Documento(new long?(this.SelectedDocumento.get_Id())); + detalhe.set_Parcela(new long?(this.SelectedParcela.get_Id())); + IEnumerable detalheExtratos1 = this.DetalheExtrato.Where((Gestor.Model.Domain.Seguros.DetalheExtrato x) => { + if (!(x.get_Cliente() == this.detalhe.get_Cliente()) || !(x.get_Apolice() == this.detalhe.get_Apolice()) || !(x.get_NumeroParcela() != this.detalhe.get_NumeroParcela()) || x.get_SubTipo().GetValueOrDefault() != 1) + { + return false; + } + if (x.get_Status().GetValueOrDefault() == 2) + { + return true; + } + return x.get_Status().GetValueOrDefault() == 3; + }); + detalheExtratos = ( + from x in detalheExtratos1 + orderby x.get_NumeroParcela() + select x).ToList(); + bool count = detalheExtratos.Count > 0; + if (count) + { + count = await base.ShowMessage("DESEJA CRITICAR AUTOMATICAMENTE AS PRÓXIMAS PARCELAS DESTE DOCUMENTO?", "SIM", "NÃO", false); + } + if (!count) + { + detalheExtratos = null; + } + else + { + detalheExtratos.ForEach((Gestor.Model.Domain.Seguros.DetalheExtrato x) => { + int num; + if (!int.TryParse(x.get_NumeroParcela(), out num)) + { + return; + } + Parcela parcela = this.Parcelas.FirstOrDefault((Parcela p) => p.get_NumeroParcela() == int.Parse(x.get_NumeroParcela())); + if (parcela == null) + { + return; + } + x.set_Status(new StatusParcela?((parcela1 == null || parcela1.get_NumeroParcela() >= parcela.get_NumeroParcela() ? (parcela.get_DataRecebimento().HasValue ? 5 : 14) : 7))); + x.set_Documento(new long?(this.SelectedDocumento.get_Id())); + x.set_Parcela(new long?(parcela.get_Id())); + }); + } + } + } + else + { + detalhe.set_Status(new StatusParcela?(6)); + nullable = null; + detalhe.set_Documento(nullable); + nullable = null; + detalhe.set_Parcela(nullable); + } + await this._servico.Save(detalhe); + if (this._servico.Sucesso) + { + if (detalheExtratos != null && detalheExtratos.Count > 0) + { + foreach (Gestor.Model.Domain.Seguros.DetalheExtrato detalheExtrato3 in detalheExtratos) + { + await this._servico.Save(detalheExtrato3); + if (this._servico.Sucesso) + { + continue; + } + variable = null; + detalheExtratos = null; + return; + } + } + await this.CarregaDetalhes(this.SelectedExtrato); + this.IsVisibleDetalhes = Visibility.Visible; + base.Loading(false); + base.ToggleSnackBar("CRÍTICA REALIZADA COM SUCESSO", true); + str = (this.SelectedParcela == null ? "ESPECIAL" : this.SelectedParcela.get_NumeroParcela().ToString()); + string str1 = str; + ComissaoViewModel comissaoViewModel = this; + object[] numeroParcela = new object[] { (critica ? "CRITICOU" : "DESCONSIDEROU"), detalhe.get_NumeroParcela(), detalhe.get_Extrato().get_Numero(), detalhe.get_Extrato().get_Id() }; + string str2 = string.Format("{0} PARCELA NÚMERO \"{1}\" DO EXTRATO NÚMERO \n{2}\n, ID {3}", numeroParcela); + long id = this.SelectedExtrato.get_Id(); + TipoTela? nullable2 = new TipoTela?(35); + obj = (critica ? string.Format("CRITICOU A PARCELA \"{0}\" DO DOCUMENTO DE ID \n{1}\n", str1, this.SelectedDocumento.get_Id()) : ""); + comissaoViewModel.RegistrarAcao(str2, id, nullable2, obj); + } + else + { + base.Loading(false); + } + } + variable = null; + detalheExtratos = null; + } + + public async Task CriticarTodos(long id) + { + ObservableCollection observableCollection = await this._servico.BuscarDetalhes(id); + foreach (Gestor.Model.Domain.Seguros.DetalheExtrato detalheExtrato in observableCollection) + { + if (detalheExtrato.get_Status().GetValueOrDefault() != 2 && detalheExtrato.get_Status().GetValueOrDefault() != 3) + { + continue; + } + detalheExtrato.set_Status(new StatusParcela?(6)); + await this._servico.Save(detalheExtrato); + if (this._servico.Sucesso) + { + continue; + } + observableCollection = null; + return; + } + ObservableCollection observableCollection1 = observableCollection; + if (observableCollection1.All((Gestor.Model.Domain.Seguros.DetalheExtrato x) => x.get_Status().GetValueOrDefault() == 6)) + { + this.SelectedExtrato.set_Status(3); + this.SelectedStatusExtrato = 3; + await this.SelecionaExtrato(this.SelectedExtrato); + } + await this.CarregaDetalhes(this.SelectedExtrato); + base.ToggleSnackBar("CRÍTICA REALIZADA COM SUCESSO", true); + base.RegistrarAcao(string.Format("DESCONSIDEROU TODAS AS PARCELAS COM O STATUS DE DOCUMENTO NÃO ENCONTRADO OU PARCELA NÃO ENCONTRADA DO EXTRATO DE ID \n{0}\n", id), id, new TipoTela?(35), null); + observableCollection = null; + } + + public async Task DesconsiderarSelecionadas() + { + if (this.DetalheExtrato != null && this.DetalheExtrato.Count != 0) + { + List statusParcelas = new List() + { + 1, + 5, + 8, + 10, + 12, + 13, + 21, + 8, + 6 + }; + List statusParcelas1 = statusParcelas; + ObservableCollection detalheExtrato = this.DetalheExtrato; + IEnumerable selecionado = + from parcelas in detalheExtrato + where parcelas.get_Selecionado() + select parcelas; + if (selecionado.Any((Gestor.Model.Domain.Seguros.DetalheExtrato parcelas) => statusParcelas1.Any((StatusParcela status) => { + StatusParcela? nullable = parcelas.get_Status(); + return status == nullable.GetValueOrDefault() & nullable.HasValue; + }))) + { + await base.ShowMessage("HÁ PARCELAS SELECIONADAS QUE JÁ ESTÃO BAIXADAS OU JÁ DESCONSIDERADAS", "OK", "", false); + } + else + { + foreach (Gestor.Model.Domain.Seguros.DetalheExtrato detalheExtrato1 in selecionado) + { + detalheExtrato1.set_Status(new StatusParcela?(6)); + await this._servico.Save(detalheExtrato1); + if (this._servico.Sucesso) + { + continue; + } + return; + } + await this.CarregaDetalhes(this.SelectedExtrato); + } + } + } + + public async Task DesfazerExtrato() + { + ObservableCollection observableCollection; + if (this.DetalheExtrato != null && this.DetalheExtrato.Count != 0) + { + List statusParcelas = new List() + { + 1, + 10, + 12, + 13 + }; + List list = this.DetalheExtrato.Where((Gestor.Model.Domain.Seguros.DetalheExtrato x) => { + if (!x.get_Status().HasValue) + { + return false; + } + return statusParcelas.Contains(x.get_Status().Value); + }).ToList(); + if (list.Count != 0) + { + this.Porcentagem = decimal.Zero; + this.Indice = decimal.Zero; + this.Total = list.Count; + List detalheExtratos4 = new List(); + await Task.Run(async () => { + List detalheExtratos = list; + Func u003cu003e9_2352 = ComissaoViewModel.u003cu003ec.u003cu003e9__235_2; + if (u003cu003e9_2352 == null) + { + u003cu003e9_2352 = (Gestor.Model.Domain.Seguros.DetalheExtrato x) => x.get_Cliente(); + ComissaoViewModel.u003cu003ec.u003cu003e9__235_2 = u003cu003e9_2352; + } + IOrderedEnumerable detalheExtratos1 = detalheExtratos.OrderBy(u003cu003e9_2352); + Func u003cu003e9_2353 = ComissaoViewModel.u003cu003ec.u003cu003e9__235_3; + if (u003cu003e9_2353 == null) + { + u003cu003e9_2353 = (Gestor.Model.Domain.Seguros.DetalheExtrato x) => x.get_Apolice(); + ComissaoViewModel.u003cu003ec.u003cu003e9__235_3 = u003cu003e9_2353; + } + IOrderedEnumerable detalheExtratos2 = detalheExtratos1.ThenBy(u003cu003e9_2353); + Func u003cu003e9_2354 = ComissaoViewModel.u003cu003ec.u003cu003e9__235_4; + if (u003cu003e9_2354 == null) + { + u003cu003e9_2354 = (Gestor.Model.Domain.Seguros.DetalheExtrato x) => x.get_Endosso(); + ComissaoViewModel.u003cu003ec.u003cu003e9__235_4 = u003cu003e9_2354; + } + IOrderedEnumerable detalheExtratos3 = detalheExtratos2.ThenBy(u003cu003e9_2354); + Func u003cu003e9_2355 = ComissaoViewModel.u003cu003ec.u003cu003e9__235_5; + if (u003cu003e9_2355 == null) + { + u003cu003e9_2355 = (Gestor.Model.Domain.Seguros.DetalheExtrato x) => x.get_NumeroParcela(); + ComissaoViewModel.u003cu003ec.u003cu003e9__235_5 = u003cu003e9_2355; + } + foreach (Gestor.Model.Domain.Seguros.DetalheExtrato detalheExtrato in detalheExtratos3.ThenByDescending(u003cu003e9_2355)) + { + decimal indice = this.Indice; + this.Indice = indice++; + this.Porcentagem = (this.Indice * new decimal(100)) / this.Total; + if (!await this.DesfazerParcela(detalheExtrato)) + { + detalheExtratos4.Add(detalheExtrato); + } + } + }); + this.SelectedExtrato.set_Status(1); + await this._servico.Save(this.SelectedExtrato); + if (this._servico.Sucesso) + { + observableCollection = await this.CarregarDetalhes(this.SelectedExtrato); + if (detalheExtratos4.Count <= 0) + { + base.ToggleSnackBar("EXTRATO DESFEITO COM SUCESSO", true); + } + else + { + await base.ShowDetalheExtrato(detalheExtratos4); + } + base.RegistrarAcao(string.Format("DESFEZ EXTRATO DE ID \n{0}\n", this.SelectedExtrato.get_Id()), this.SelectedExtrato.get_Id(), new TipoTela?(35), null); + bool flag = !observableCollection.Any((Gestor.Model.Domain.Seguros.DetalheExtrato x) => { + if (!x.get_Status().HasValue) + { + return false; + } + return statusParcelas.Contains(x.get_Status().Value); + }); + if (flag) + { + flag = await base.ShowMessage("DESEJA EXCLUIR O EXTRATO DESFEITO?", "SIM", "NÃO", false); + } + if (flag) + { + await this.ExcluirExtrato(); + this.SelectedExtrato = null; + } + this.Carregando = true; + this.SelectedStatusExtrato = 1; + this.Carregando = false; + this.SelecionaSeguradora(this.SelectedSeguradora, this.SelectedStatusExtrato, this.SelectedExtrato); + } + } + else + { + await base.ShowMessage("NÃO HÁ PARCELAS PARA SEREM DESFEITAS NO EXTRATO", "OK", "", false); + } + } + observableCollection = null; + } + + public async Task DesfazerParcela(Gestor.Model.Domain.Seguros.DetalheExtrato detalhe) + { + bool flag; + long? parcela; + bool hasValue; + bool flag1; + StatusParcela statusParcela; + Gestor.Model.Domain.Seguros.DetalheExtrato detalheExtrato = detalhe; + if (detalheExtrato != null) + { + parcela = detalheExtrato.get_Parcela(); + hasValue = !parcela.HasValue; + } + else + { + hasValue = true; + } + if (!hasValue) + { + try + { + ParcelaServico parcelaServico = this._parcelaServico; + parcela = detalhe.get_Parcela(); + Parcela parcela1 = await parcelaServico.BuscarParcela(parcela.Value); + if (parcela1 != null) + { + detalhe.set_Documento(new long?(parcela1.get_Documento().get_Id())); + parcela1.set_Extrato(null); + ParcelaServico parcelaServico1 = this._parcelaServico; + parcela = detalhe.get_Documento(); + List parcelas = await parcelaServico1.BuscarParcelas(parcela.Value); + List parcelas1 = parcelas; + IOrderedEnumerable numeroParcela = + from p in parcelas1 + orderby p.get_NumeroParcela() descending + select p; + Parcela parcela2 = numeroParcela.FirstOrDefault((Parcela p) => { + if (!p.get_DataRecebimento().HasValue) + { + return false; + } + return p.get_SubTipo() == 1; + }); + bool flag2 = await this._parcelaServico.TemPagamento(parcela1.get_Id()); + if (parcela1.get_Documento().get_TipoRecebimento().GetValueOrDefault() != 1) + { + List configuracoes = Recursos.Configuracoes; + if (configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 28)) + { + goto Label0; + } + } + if (flag2) + { + flag1 = true; + } + else + { + flag1 = (parcela2 == null ? false : parcela2.get_NumeroParcela() > parcela1.get_NumeroParcela()); + } + flag2 = flag1; + Label0: + if (!flag2 || parcela1.get_Documento().get_Excluido()) + { + VendedorServico vendedorServico = this._vendedorServico; + parcela = detalhe.get_Documento(); + List vendedorParcelas = await vendedorServico.BuscaRepasse(parcela.Value); + await Funcoes.ExcluirBaixa(parcela1, vendedorParcelas, parcelas); + Parcela parcela3 = parcelas.FirstOrDefault((Parcela x) => x.get_NumeroParcela() == int.Parse(detalhe.get_NumeroParcela()) - 1); + Gestor.Model.Domain.Seguros.DetalheExtrato detalheExtrato1 = detalhe; + if (parcela3 != null && !parcela3.get_DataRecebimento().HasValue) + { + statusParcela = 7; + } + else if (detalhe.get_Status().GetValueOrDefault() == 13) + { + statusParcela = 14; + } + else + { + decimal? comissao = detalhe.get_Comissao(); + if (comissao.HasValue) + { + decimal num = parcela1.get_Documento().get_Comissao(); + comissao = detalhe.get_Comissao(); + if ((num == comissao.GetValueOrDefault()) & comissao.HasValue) + { + goto Label2; + } + statusParcela = 4; + goto Label1; + } + Label2: + statusParcela = 9; + } + Label1: + detalheExtrato1.set_Status(new StatusParcela?(statusParcela)); + await this._servico.Save(detalhe); + flag = true; + } + else + { + flag = false; + } + } + else + { + parcela = null; + detalhe.set_Documento(parcela); + parcela = null; + detalhe.set_Parcela(parcela); + detalhe.set_Status(new StatusParcela?(2)); + await this._servico.Save(detalhe); + flag = false; + } + } + catch (Exception exception1) + { + Exception exception = exception1; + (new BaseServico()).Registrar(exception, 292, 3, detalhe, true); + flag = false; + } + } + else + { + flag = false; + } + return flag; + } + + public async Task ExcluirExtrato() + { + if (this.SelectedExtrato != null) + { + List statusParcelas = new List() + { + 1, + 10, + 13 + }; + try + { + if (this.DetalheExtrato.Any((Gestor.Model.Domain.Seguros.DetalheExtrato x) => { + if (!x.get_Status().HasValue) + { + return false; + } + return statusParcelas.Contains(x.get_Status().Value); + })) + { + await base.ShowMessage("O EXTRATO NÃO PODE SER EXCLUÍDO POIS FOI UTILIZADO PARA BAIXAR PARCELAS, DESFAÇA O EXTRATO ANTES DE EXCLUÍ-LO", "OK", "", false); + return; + } + else if (await this._servico.Delete(this.SelectedExtrato)) + { + base.RegistrarAcao(string.Format("EXCLUIU EXTRATO DE ID \n{0}\n", this.SelectedExtrato.get_Id()), this.SelectedExtrato.get_Id(), new TipoTela?(35), null); + this.SelectedExtrato = null; + this.SelecionaSeguradora(this.SelectedSeguradora, 1, null); + base.ToggleSnackBar("EXTRATO EXCLUÍDO COM SUCESSO", true); + } + else + { + return; + } + } + catch (Exception exception) + { + } + } + } + + public void ExcluirFiltro(string filtro) + { + this.FiltroPersonalizado.Remove(filtro); + this.FiltrarExtrato(); + } + + private List Filtrar() + { + List list = this.Extratos.ToList(); + this.FiltroPersonalizado.ToList().ForEach((string f) => { + IEnumerable extratos = list.Where((Extrato x) => { + if (ValidationHelper.RemoveDiacritics(x.get_Seguradora().get_Nome()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(f)) || ValidationHelper.RemoveDiacritics(x.get_Numero()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(f)) || x.get_Data().HasValue && x.get_Data().ToString().Contains(f) || x.get_Bruto().HasValue && x.get_Bruto().ToString().Contains(f) || x.get_Liquido().HasValue && x.get_Liquido().ToString().Contains(f)) + { + return true; + } + if (!x.get_DataCredito().HasValue) + { + return false; + } + return x.get_DataCredito().ToString().Contains(f); + }); + Func u003cu003e9_2542 = ComissaoViewModel.u003cu003ec.u003cu003e9__254_2; + if (u003cu003e9_2542 == null) + { + u003cu003e9_2542 = (Extrato x) => x.get_Numero(); + ComissaoViewModel.u003cu003ec.u003cu003e9__254_2 = u003cu003e9_2542; + } + IOrderedEnumerable extratos1 = extratos.OrderBy(u003cu003e9_2542); + Func u003cu003e9_2543 = ComissaoViewModel.u003cu003ec.u003cu003e9__254_3; + if (u003cu003e9_2543 == null) + { + u003cu003e9_2543 = (Extrato x) => x.get_DataCredito(); + ComissaoViewModel.u003cu003ec.u003cu003e9__254_3 = u003cu003e9_2543; + } + list = extratos1.ThenByDescending(u003cu003e9_2543).ToList(); + }); + return list; + } + + internal async Task> FiltrarApolices(string value) + { + List documentos = await Task.Run>(() => this.FiltrarDocumento(value)); + return documentos; + } + + internal async Task> FiltrarDetalhe(string value) + { + List detalheExtratos = await Task.Run>(() => this.FiltrarDetalheExtrato(value)); + return detalheExtratos; + } + + public List FiltrarDetalheExtrato(string filter) + { + if (this.DetalheExtrato == null) + { + return null; + } + this.DetalheExtratoFiltrados = (string.IsNullOrWhiteSpace(filter) ? this.DetalheExtrato : new ObservableCollection(this.DetalheExtrato.Where((Gestor.Model.Domain.Seguros.DetalheExtrato x) => { + if (ValidationHelper.RemoveDiacritics(x.get_Cliente()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) || x.get_Apolice().Contains(filter)) + { + return true; + } + return x.get_Endosso().Contains(filter); + }).OrderBy((Gestor.Model.Domain.Seguros.DetalheExtrato x) => x.get_Cliente()))); + return this.DetalheExtratoFiltrados.ToList(); + } + + public List FiltrarDetalheExtrato(long id) + { + this.DetalheExtratoFiltrados = new ObservableCollection( + from x in this.DetalheExtrato + where x.get_Id() == id + select x); + return this.DetalheExtratoFiltrados.ToList(); + } + + public List FiltrarDocumento(string filter) + { + this.Apolices = (string.IsNullOrWhiteSpace(filter) ? this.TodasApolices : new ObservableCollection(this.TodasApolices.Where((Documento x) => { + if (x.get_Apolice() != null && x.get_Apolice().ToUpper().Contains(filter.ToUpper()) || x.get_Endosso() != null && x.get_Endosso().ToUpper().Contains(filter.ToUpper()) || x.get_Vigencia1().ToString("d").Contains(filter)) + { + return true; + } + if (!x.get_Vigencia2().HasValue) + { + return false; + } + return x.get_Vigencia2().Value.ToString("d").Contains(filter); + }))); + this.SelectedDocumento = null; + this.SelectedParcela = null; + ObservableCollection apolices = this.Apolices; + if (apolices != null) + { + return apolices.ToList(); + } + return null; + } + + public void FiltrarExtrato() + { + bool count; + this.ExtratosFiltrados = new ObservableCollection(this.Filtrar()); + this.SelectedExtrato = this.ExtratosFiltrados.FirstOrDefault(); + ObservableCollection extratosFiltrados = this.ExtratosFiltrados; + if (extratosFiltrados != null) + { + count = extratosFiltrados.Count > 0; + } + else + { + count = false; + } + this.IsExpanded = count; + } + + public async Task FinalizarExtrato() + { + if (this.DetalheExtrato != null && this.DetalheExtrato.Count != 0) + { + StatusExtrato selectedStatusExtrato = this.SelectedStatusExtrato; + this.SelectedExtrato.set_Status(3); + Extrato extrato = await this._servico.Save(this.SelectedExtrato); + if (this._servico.Sucesso) + { + this.SelectedExtrato = null; + this.SelecionaSeguradora(this.SelectedSeguradora, selectedStatusExtrato, null); + base.ToggleSnackBar("EXTRATO FINALIZADO COM SUCESSO", true); + base.RegistrarAcao(string.Format("FINALIZOU EXTRATO DE ID \n{0}\n", extrato.get_Id()), extrato.get_Id(), new TipoTela?(35), null); + } + } + } + + public async Task GerarHtml() + { + string nome; + ExtratoComissao extratoComissao = new ExtratoComissao(); + Usuario usuario = Auxiliar.get_Usuarios().FirstOrDefault((Usuario x) => x.get_Id() == this.SelectedExtrato.get_IdUsuario()); + if (usuario != null) + { + nome = usuario.get_Nome(); + } + else + { + nome = null; + } + extratoComissao.set_Usuario(nome); + extratoComissao.set_Seguradora(this.SelectedExtrato.get_Seguradora().get_Nome()); + extratoComissao.set_DetalhesExtrato(new ObservableCollection()); + ObservableCollection observableCollection = new ObservableCollection(); + InformacoesExtrato informacoesExtrato = new InformacoesExtrato(); + informacoesExtrato.set_NumeroExtrato(this.SelectedExtrato.get_Numero()); + informacoesExtrato.set_DataExtrato(this.SelectedExtrato.get_Data()); + decimal? bruto = this.SelectedExtrato.get_Bruto(); + informacoesExtrato.set_Bruto(bruto.GetValueOrDefault()); + bruto = this.SelectedExtrato.get_Liquido(); + informacoesExtrato.set_Liquido(bruto.GetValueOrDefault()); + bruto = this.SelectedExtrato.get_Ir(); + informacoesExtrato.set_Ir(bruto.GetValueOrDefault()); + bruto = this.SelectedExtrato.get_Iss(); + informacoesExtrato.set_Iss(bruto.GetValueOrDefault()); + bruto = this.SelectedExtrato.get_Outro(); + informacoesExtrato.set_Outros(bruto.GetValueOrDefault()); + informacoesExtrato.set_Quantidade(this.Quantidade); + informacoesExtrato.set_TotalBaixado(this.TotalBaixado); + informacoesExtrato.set_TotalPendente(this.TotalPendente); + observableCollection.Add(informacoesExtrato); + extratoComissao.set_InformacoesExtrato(observableCollection); + ExtratoComissao extratoComissao1 = extratoComissao; + foreach (Gestor.Model.Domain.Seguros.DetalheExtrato detalheExtratoFiltrado in this.DetalheExtratoFiltrados) + { + DetalhesExtrato detalhesExtrato = new DetalhesExtrato(); + detalhesExtrato.set_Cliente(detalheExtratoFiltrado.get_Cliente()); + detalhesExtrato.set_Apolice(detalheExtratoFiltrado.get_Apolice()); + detalhesExtrato.set_Endosso(detalheExtratoFiltrado.get_Endosso()); + detalhesExtrato.set_Parcela(detalheExtratoFiltrado.get_NumeroParcela()); + detalhesExtrato.set_Pagto(detalheExtratoFiltrado.get_Valor()); + detalhesExtrato.set_Comissao(detalheExtratoFiltrado.get_Comissao()); + detalhesExtrato.set_ValorComissao(detalheExtratoFiltrado.get_ValorComissao()); + detalhesExtrato.set_Status(ValidationHelper.GetDescription(detalheExtratoFiltrado.get_Status())); + extratoComissao1.get_DetalhesExtrato().Add(detalhesExtrato); + } + string str = await Funcoes.GenerateTable(extratoComissao1.get_InformacoesExtrato().ToList(), new List(), false, false, "", null); + string str1 = await Funcoes.GenerateTable(extratoComissao1.get_DetalhesExtrato().ToList(), new List(), false, false, "", null); + string str2 = string.Concat(str, str1); + str = null; + string str3 = Funcoes.CreateCard(string.Concat("SEGURADORA: ", extratoComissao1.get_Seguradora(), "
USUÁRIO IMPORTAÇÃO: ", extratoComissao1.get_Usuario()), str2, false); + TipoRelatorio tipoRelatorio = new TipoRelatorio(); + tipoRelatorio.set_Nome("EXTRATO DE COMISSÃO"); + string str4 = str3; + if (str4 == null) + { + str4 = ""; + } + string str5 = Funcoes.ExportarHtml(tipoRelatorio, str4, "70", "landscape", false, ""); + extratoComissao1 = null; + return str5; + } + + private static VendedorParcela PropriaCorretora() + { + Vendedor vendedor = Recursos.Vendedores.FirstOrDefault((Vendedor x) => { + if (x.get_IdEmpresa() != Recursos.Empresa.get_Id()) + { + return false; + } + return x.get_Corretora(); + }); + VendedorParcela vendedorParcela = new VendedorParcela(); + vendedorParcela.set_Repasse(null); + decimal num = new decimal(); + vendedorParcela.set_ValorRepasse(new decimal?(num)); + vendedorParcela.set_Vendedor(vendedor); + num = new decimal(); + vendedorParcela.set_PorcentagemRepasse(new decimal?(num)); + vendedorParcela.set_TipoVendedor(Recursos.TipoVendedor.First((TipoVendedor x) => x.get_Id() == (long)1)); + return vendedorParcela; + } + + public async Task SelecionaCliente(Cliente value) + { + ObservableCollection observableCollection; + long id; + Visibility visibility; + Visibility visibility1; + List nums; + if (value != null && value.get_Id() != 0) + { + observableCollection = await this._apoliceServico.BuscarApolicesComissao(value.get_Id(), this.SelectedStatus); + this.FiltroApolice = string.Empty; + id = this.SelectedExtrato.get_Seguradora().get_Id(); + if (id <= (long)544) + { + if (id <= (long)310) + { + if (id <= (long)182) + { + if (id > (long)93) + { + if (id - (long)112 > (long)1) + { + goto Label15; + } + nums = new List() + { + (long)112, + (long)113 + }; + goto Label11; + } + else + { + if (id == (long)28) + { + goto Label4; + } + if (id - (long)89 > (long)4) + { + goto Label12; + } + List nums1 = new List() + { + (long)89, + (long)90, + (long)91, + (long)92, + (long)93 + }; + nums = nums1; + goto Label11; + } + } + else if (id > (long)261) + { + if (id - (long)291 <= (long)1 || id == (long)296) + { + goto Label0; + } + if (id == (long)310) + { + goto Label5; + } + } + else + { + if (id == (long)216) + { + goto Label9; + } + if (id - (long)258 <= (long)3) + { + goto Label8; + } + } + } + else if (id <= (long)400) + { + if (id > (long)331) + { + if (id == (long)341) + { + goto Label6; + } + if (id == (long)374) + { + goto Label7; + } + if (id == (long)400) + { + goto Label0; + } + } + else + { + if (id == (long)328) + { + goto Label3; + } + if (id == (long)331) + { + goto Label1; + } + } + } + else if (id > (long)480) + { + if (id != (long)501) + { + goto Label13; + } + List nums2 = new List() + { + (long)498, + (long)499, + (long)500, + (long)501, + (long)502 + }; + nums = nums2; + goto Label11; + } + else + { + if (id == (long)402) + { + goto Label0; + } + if (id != (long)480) + { + goto Label12; + } + List nums3 = new List() + { + (long)475, + (long)476, + (long)477, + (long)478, + (long)479, + (long)480, + (long)481, + (long)482, + (long)483, + (long)484, + (long)485, + (long)486, + (long)487, + (long)558, + (long)580, + (long)664 + }; + nums = nums3; + goto Label11; + } + } + else if (id > (long)630) + { + if (id <= (long)674) + { + if (id > (long)643) + { + if (id == (long)649) + { + goto Label4; + } + if (id == (long)650) + { + goto Label5; + } + if (id == (long)674) + { + goto Label0; + } + } + else + { + if (id == (long)631) + { + goto Label6; + } + long num = id - (long)639; + if (num <= (long)4) + { + switch ((uint)num) + { + case 0: + { + goto Label5; + } + case 2: + case 4: + { + goto Label0; + } + } + } + else + { + } + } + } + else if (id > (long)711) + { + if (id == (long)884) + { + goto Label0; + } + if (id == (long)982) + { + goto Label1; + } + if (id == (long)1006) + { + goto Label2; + } + } + else + { + if (id == (long)694) + { + goto Label0; + } + if (id == (long)711) + { + goto Label3; + } + } + } + else if (id > (long)562) + { + if (id > (long)574) + { + if (id == (long)578) + { + goto Label7; + } + long num1 = id - (long)591; + if (num1 <= (long)7) + { + switch ((uint)num1) + { + case 0: + case 1: + case 3: + { + goto Label4; + } + case 2: + case 5: + case 6: + { + goto Label12; + } + case 4: + { + goto Label1; + } + case 7: + { + goto Label8; + } + } + } + else + { + } + if (id == (long)630) + { + goto Label5; + } + } + else + { + if (id == (long)570) + { + goto Label8; + } + if (id == (long)574) + { + goto Label0; + } + } + } + else if (id > (long)552) + { + if (id - (long)554 <= (long)1) + { + goto Label0; + } + if (id == (long)560) + { + goto Label9; + } + if (id == (long)562) + { + goto Label1; + } + } + else if (id == (long)548 || id == (long)552) + { + goto Label10; + } + List nums4 = new List() + { + this.SelectedExtrato.get_Seguradora().get_Id() + }; + nums = nums4; + goto Label11; + } + ComissaoViewModel.u003cu003ec__DisplayClass211_0 variable = null; + return; + List nums5 = new List() + { + (long)70, + (long)291, + (long)292, + (long)296, + (long)400, + (long)401, + (long)402, + (long)554, + (long)555, + (long)574, + (long)641, + (long)643, + (long)674, + (long)694, + (long)884, + (long)348 + }; + nums = nums5; + goto Label11; + List nums6 = new List() + { + (long)331, + (long)543, + (long)562, + (long)595, + (long)982 + }; + nums = nums6; + goto Label11; + nums = new List() + { + (long)182, + (long)1006 + }; + Label11: + ComissaoViewModel comissaoViewModel = this; + IEnumerable documentos = observableCollection.Where((Documento x) => { + if (x.get_Controle().get_Seguradora() == null) + { + return false; + } + return nums.Contains(x.get_Controle().get_Seguradora().get_Id()); + }); + IOrderedEnumerable vigencia2 = + from x in documentos + orderby x.get_Vigencia2() + select x; + comissaoViewModel.TodasApolices = new ObservableCollection(vigencia2.ThenBy((Documento x) => x.get_Controle().get_Id())); + this.Apolices = this.TodasApolices; + ComissaoViewModel comissaoViewModel1 = this; + visibility = (this.TodasApolices.Count > 0 ? Visibility.Visible : Visibility.Collapsed); + comissaoViewModel1.IsVisibleApolice = visibility; + ComissaoViewModel comissaoViewModel2 = this; + visibility1 = (this.TodasApolices.Count > 0 ? Visibility.Collapsed : Visibility.Visible); + comissaoViewModel2.IsVisibleMensagem = visibility1; + variable = null; + return; + List nums7 = new List() + { + (long)328, + (long)329, + (long)711 + }; + nums = nums7; + goto Label11; + List nums8 = new List() + { + (long)28, + (long)591, + (long)592, + (long)594, + (long)649 + }; + nums = nums8; + goto Label11; + List nums9 = new List() + { + (long)310, + (long)630, + (long)639, + (long)650 + }; + nums = nums9; + goto Label11; + nums = new List() + { + (long)341, + (long)631 + }; + goto Label11; + nums = new List() + { + (long)374, + (long)578 + }; + goto Label11; + List nums10 = new List() + { + (long)258, + (long)259, + (long)260, + (long)261, + (long)570, + (long)598, + (long)472, + (long)595, + (long)741, + (long)982 + }; + nums = nums10; + goto Label11; + nums = new List() + { + (long)560, + (long)216 + }; + goto Label11; + List nums11 = new List() + { + (long)544, + (long)548, + (long)552 + }; + nums = nums11; + goto Label11; + Label13: + if (id == (long)543) + { + goto Label1; + } + if (id == (long)544) + { + goto Label10; + } + goto Label12; + goto Label12; + Label15: + if (id == (long)182) + { + goto Label2; + } + goto Label12; + goto Label12; + } + + public async Task SelecionaDocumento(Documento value) + { + if (value != null && value.get_Id() != 0) + { + this.SelectedDocumento = this.Apolices.FirstOrDefault((Documento x) => x.get_Id() == value.get_Id()); + this.Parcelas = await this._parcelaServico.BuscarParcelasAsync(value.get_Id()); + } + } + + public async Task SelecionaExtrato(Extrato extrato) + { + if (extrato != null && extrato.get_Id() != 0) + { + base.Loading(true); + this.IsVisibleDetalhes = Visibility.Collapsed; + this.SelectedExtrato = extrato; + this.PesquisaPagamento = string.Empty; + await this.CarregaDetalhes(extrato); + this.IsVisibleDetalhes = Visibility.Visible; + base.Loading(false); + } + } + + private void SelecionaNormal() + { + ExtensionMethods.ForEach(this.DetalheExtrato, (Gestor.Model.Domain.Seguros.DetalheExtrato detalhe) => detalhe.IsNormal = detalhe.get_SubTipo().GetValueOrDefault() == 1); + } + + public void SelecionaParcela(Parcela value) + { + if (value == null || value.get_Id() == 0) + { + return; + } + this.SelectedParcela = this.Parcelas.FirstOrDefault((Parcela x) => x.get_Id() == value.get_Id()); + } + + private void Selecionar(bool value) + { + ExtensionMethods.ForEach(this.DetalheExtratoFiltrados, (Gestor.Model.Domain.Seguros.DetalheExtrato x) => x.set_Selecionado(value)); + } + + public async void SelecionaSeguradora(Seguradora value, StatusExtrato status, Extrato extrato = null) + { + StatusExtrato statusExtrato; + ObservableCollection observableCollection; + bool count; + Extrato extrato1; + if (!this.Carregando) + { + if (this.Inicio <= this.Fim) + { + this.Filtro = string.Empty; + this.FiltroApolice = string.Empty; + if (value != null) + { + base.Loading(true); + this.IsVisibleExtrato = Visibility.Collapsed; + this.BaixarPendentes = status == 1; + this.DetalheExtrato = null; + if (status == 2) + { + statusExtrato = 3; + } + else + { + statusExtrato = status; + } + StatusExtrato statusExtrato1 = statusExtrato; + List extratos = await this._servico.BuscarExtrato(value.get_Id(), this.SelectedUsuario.get_Id(), statusExtrato1, this.Inicio, this.Fim); + ComissaoViewModel comissaoViewModel = this; + if (status == 2) + { + List extratos1 = extratos; + observableCollection = new ObservableCollection( + from x in extratos1 + where !x.get_Completo() + select x); + } + else if (status == 3) + { + List extratos2 = extratos; + observableCollection = new ObservableCollection( + from x in extratos2 + where x.get_Completo() + select x); + } + else + { + observableCollection = new ObservableCollection(extratos); + } + comissaoViewModel.Extratos = observableCollection; + this.ExtratosFiltrados = this.Extratos; + if (this.FiltroPersonalizado.Count > 0) + { + this.FiltrarExtrato(); + } + ComissaoViewModel comissaoViewModel1 = this; + ObservableCollection extratosFiltrados = this.ExtratosFiltrados; + if (extratosFiltrados != null) + { + count = extratosFiltrados.Count > 0; + } + else + { + count = false; + } + comissaoViewModel1.IsExpanded = count; + extrato1 = (extrato == null ? this.ExtratosFiltrados.FirstOrDefault() : this.ExtratosFiltrados.FirstOrDefault((Extrato x) => x.get_Id() == extrato.get_Id())); + await this.SelecionaExtrato(extrato1); + base.Loading(false); + if (this.SelectedSeguradora != null) + { + string str = string.Format("CONSULTOU COMISSÃO AUTOMÁTICA NO PERÍODO ENTRE {0:d} E {1:d}", this.Inicio, this.Fim); + long num = (long)0; + TipoTela? nullable = new TipoTela?(35); + object[] nome = new object[] { this.SelectedUsuario.get_Nome(), this.SelectedUsuario.get_Id(), this.SelectedSeguradora.get_Nome(), this.SelectedSeguradora.get_Id(), ValidationHelper.GetDescription(this.SelectedStatusExtrato), ValidationHelper.Join(this.FiltroPersonalizado, ", ") }; + base.RegistrarAcao(str, num, nullable, string.Format("USUÁRIO IMPORTAÇÃO: {0} ({1})\nSEGURADORA: {2} ({3})\nSTATUS: {4}\nPESQUISA PERSONALIZADA: \"{5}\"", nome)); + } + } + else + { + this.Extratos = null; + this.ExtratosFiltrados = null; + this.DetalheExtrato = null; + this.DetalheExtratoFiltrados = null; + this.SelectedExtrato = null; + this.SelectedDetalhe = null; + } + } + else + { + await base.ShowMessage("DATA DE INÍCIO NÃO PODE SER MAR QUE A DATA FINAL", "OK", "", false); + } + } + } + + public void SelecionaSeguradoras() + { + base.Loading(true); + List list = ( + from x in Recursos.Seguradoras + where x.get_Ativo() + orderby x.get_Nome() + select x).ToList(); + Seguradora seguradora = new Seguradora(); + seguradora.set_Id((long)0); + seguradora.set_Nome("TODAS AS SEGURADORAS"); + seguradora.set_NomeSocial("TODAS DAS SEGURADORAS"); + list.Insert(0, seguradora); + List usuarios = ( + from x in Recursos.Usuarios + where !x.get_Excluido() + orderby x.get_IdEmpresa(), x.get_Nome() + select x).ToList(); + Usuario usuario = new Usuario(); + usuario.set_Id((long)0); + usuario.set_Nome("TODOS OS USUÁRIOS"); + usuarios.Insert(0, usuario); + this.Usuarios = new ObservableCollection(usuarios); + this.Seguradoras = new ObservableCollection(list); + base.Loading(false); + } + + private async void WorkOnSelectedCliente(Cliente value) + { + if (value == null || value.get_Id() == 0) + { + this.IsVisibleCliente = Visibility.Collapsed; + this.IsVisibleApolice = Visibility.Collapsed; + this.IsVisibleMensagem = Visibility.Collapsed; + this.DocumentoPrincipal = string.Empty; + this.SelectedDocumento = null; + this.SelectedParcela = null; + } + else + { + this.IsVisibleCliente = Visibility.Visible; + if (!this.Buscando) + { + base.Loading(true); + this.IsVisibleDetalhes = Visibility.Collapsed; + } + if (!this.Buscando) + { + this.Buscando = true; + await this.SelecionaCliente(value); + await this.SelecionaDocumento(this.Apolices.FirstOrDefault()); + this.Buscando = false; + Cliente cliente = value; + TipoDocumento? documentoPrincipal = value.get_DocumentoPrincipal(); + cliente.set_DocumentoPrincipal(new TipoDocumento?(documentoPrincipal.GetValueOrDefault())); + documentoPrincipal = value.get_DocumentoPrincipal(); + if (documentoPrincipal.HasValue) + { + switch (documentoPrincipal.GetValueOrDefault()) + { + case 0: + { + ComissaoViewModel comissaoViewModel = this; + string documento = value.get_Documento(); + if (documento == null) + { + documento = ""; + } + comissaoViewModel.DocumentoPrincipal = documento; + break; + } + case 1: + { + ComissaoViewModel comissaoViewModel1 = this; + string rne = value.get_Rne(); + if (rne == null) + { + rne = ""; + } + comissaoViewModel1.DocumentoPrincipal = rne; + break; + } + case 2: + { + ComissaoViewModel comissaoViewModel2 = this; + string cei = value.get_Cei(); + if (cei == null) + { + cei = ""; + } + comissaoViewModel2.DocumentoPrincipal = cei; + break; + } + } + } + this.IsVisibleDetalhes = Visibility.Visible; + base.Loading(false); + } + } + } + + private void WorkOnSelectedDocumento(Documento value) + { + if (value == null || value.get_Id() == 0 || this.Buscando) + { + return; + } + TipoRecebimento? tipoRecebimento = value.get_TipoRecebimento(); + this.IsFatura = tipoRecebimento.GetValueOrDefault() == 2; + } + + public async void WorkOnSelectedStatus() + { + if (this.SelectedCliente != null) + { + if (!this.Buscando) + { + await this.SelecionaCliente(this.SelectedCliente); + } + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Command/RelayCommand.cs b/Codemerx/Gestor.Application/ViewModels/Command/RelayCommand.cs new file mode 100644 index 0000000..fb3d646 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Command/RelayCommand.cs @@ -0,0 +1,29 @@ +using System; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Windows.Input; + +namespace Gestor.Application.ViewModels.Command +{ + public class RelayCommand : ICommand + { + private Action mAction; + + public RelayCommand(Action action) + { + this.mAction = action; + } + + public bool CanExecute(object parameter) + { + return true; + } + + public void Execute(object parameter) + { + this.mAction(); + } + + public event EventHandler CanExecuteChanged; + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Configuracoes/ConfiguracoesViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Configuracoes/ConfiguracoesViewModel.cs new file mode 100644 index 0000000..b399eb5 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Configuracoes/ConfiguracoesViewModel.cs @@ -0,0 +1,178 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Configuracoes; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Configuracoes +{ + public class ConfiguracoesViewModel : BaseViewModel + { + private bool _hasRows; + + private ObservableCollection _configuracoes; + + private Configuracao _selectedConfiguracao; + + private string _descricao; + + private bool _carregando; + + private ObservableCollection _configuracoesAdicionadas; + + private ConfuguracoesServico _servico + { + get; + set; + } + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.OnPropertyChanged("Carregando"); + } + } + + public ObservableCollection Configuracoes + { + get + { + return this._configuracoes; + } + set + { + this._configuracoes = value; + base.EnableFields = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("Configuracoes"); + } + } + + public ObservableCollection ConfiguracoesAdicionadas + { + get + { + return this._configuracoesAdicionadas; + } + set + { + this._configuracoesAdicionadas = value; + this.HasRows = (value != null ? value.Count > 0 : false); + this.PopularConfiguracoes(value); + base.OnPropertyChanged("ConfiguracoesAdicionadas"); + } + } + + public string Descricao + { + get + { + return this._descricao; + } + set + { + this._descricao = value; + base.OnPropertyChanged("Descricao"); + } + } + + public bool HasRows + { + get + { + return this._hasRows; + } + set + { + this._hasRows = value; + base.OnPropertyChanged("HasRows"); + } + } + + public Configuracao SelectedConfiguracao + { + get + { + return this._selectedConfiguracao; + } + set + { + this._selectedConfiguracao = value; + this.Descricao = ValidationHelper.GetCategory(value); + base.OnPropertyChanged("SelectedConfiguracao"); + } + } + + public ConfiguracoesViewModel() + { + this._servico = new ConfuguracoesServico(); + base.EnableMenu = true; + } + + public async Task BuscarConfiguracoes() + { + List configuracaoSistemas = await this._servico.Buscar(); + List configuracaoSistemas1 = configuracaoSistemas; + Recursos.Configuracoes = ( + from x in configuracaoSistemas1 + orderby ValidationHelper.GetDescription(x.get_Configuracao()) + select x).ToList(); + this.ConfiguracoesAdicionadas = new ObservableCollection(configuracaoSistemas); + } + + public async Task Excluir(ConfiguracaoSistema configuracao) + { + if (await this._servico.Excluir(configuracao)) + { + await this.BuscarConfiguracoes(); + } + } + + private void PopularConfiguracoes(ObservableCollection configuracoes) + { + if (configuracoes == null) + { + return; + } + List configuracaos = new List(); + foreach (Configuracao configuracao in + from x in (Configuracao[])Enum.GetValues(typeof(Configuracao)) + orderby ValidationHelper.GetDescription(x) + select x) + { + if (configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == configuracao)) + { + continue; + } + configuracaos.Add(configuracao); + } + this.Configuracoes = new ObservableCollection(configuracaos); + this.SelectedConfiguracao = this.Configuracoes.FirstOrDefault(); + } + + public async Task Salvar() + { + ConfuguracoesServico confuguracoesServico = this._servico; + ConfiguracaoSistema configuracaoSistema = new ConfiguracaoSistema(); + configuracaoSistema.set_Configuracao(this.SelectedConfiguracao); + if (await confuguracoesServico.Salvar(configuracaoSistema).get_Id() != 0) + { + await this.BuscarConfiguracoes(); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/DashboardViewModel.cs b/Codemerx/Gestor.Application/ViewModels/DashboardViewModel.cs new file mode 100644 index 0000000..8ef9d41 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/DashboardViewModel.cs @@ -0,0 +1,1111 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Relatorios.ClientesAtivosInativos; +using Gestor.Model.Domain.Relatorios.Dashboard; +using Gestor.Model.Domain.Relatorios.Renovacao; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels +{ + public class DashboardViewModel : BaseSegurosViewModel + { + private readonly TarefaServico _servico; + + private readonly ApoliceServico _apoliceServico; + + private readonly ClienteServico _clienteServico; + + private readonly SinistroServico _sinitrosServico; + + private readonly TarefaServico _tarefaServico; + + private bool _renovacoesEnabled; + + private bool _tarefasEnabled; + + private bool _aniversariantesEnabled; + + private bool _sinistrosEnabled; + + private bool _prospeccoesEnabled; + + private bool _notasEnabled; + + private bool _publica; + + private string _quantidadeRenovacoes = "0"; + + private string _quantidadeAniversariantes = "0"; + + private string _quantidadeProspeccao = "0"; + + private string _quantidadeSinisto = "0"; + + private string _quantidadeTarefas = "0"; + + private List _intervalo = new List() + { + "HOJE", + "PRÓXIMOS 3 DIAS", + "PRÓXIMOS 7 DIAS" + }; + + private string _intervaloSelecionado = "HOJE"; + + private bool _isProspectar; + + private ObservableCollection _notas; + + private ObservableCollection _telefones = new ObservableCollection(); + + private string _anotacoes = ""; + + private ObservableCollection _prospeccoes; + + private ObservableCollection _aniversariantes; + + private ObservableCollection _sinistros; + + private ObservableCollection _renovacaoFiltrado; + + private ObservableCollection _tarefas = new ObservableCollection(); + + private List _ramos; + + private Ramo _selectedRamo; + + private List _referencias = new List() + { + "VENCIMENTO DA ÚLTIMA PARCELA", + "VIGÊNCIA INICIAL", + "VIGÊNCIA FINAL" + }; + + private string _referencia = "VENCIMENTO DA ÚLTIMA PARCELA"; + + private int _selectedTile = 1; + + private string _labelProspeccao; + + private List _filtroCliente = new List() + { + "AMBOS", + "CNPJ", + "CPF" + }; + + private string _filtroClientes; + + private Gestor.Model.Domain.Relatorios.Filtros _filtroAniversariantes + { + get; + set; + } + + private Gestor.Model.Domain.Relatorios.Filtros _filtroProspectar + { + get; + set; + } + + private Gestor.Model.Domain.Relatorios.Filtros _filtroRenovacao + { + get; + set; + } + + private Gestor.Model.Domain.Relatorios.Filtros _filtroSinistros + { + get; + set; + } + + private Gestor.Model.Domain.Relatorios.Filtros _filtroTarefas + { + get; + set; + } + + public ObservableCollection Aniversariantes + { + get + { + return this._aniversariantes; + } + set + { + this._aniversariantes = value; + base.OnPropertyChanged("Aniversariantes"); + } + } + + public bool AniversariantesEnabled + { + get + { + return this._aniversariantesEnabled; + } + set + { + this._aniversariantesEnabled = value; + base.OnPropertyChanged("AniversariantesEnabled"); + } + } + + public new string Anotacoes + { + get + { + return this._anotacoes; + } + set + { + this._anotacoes = value; + base.OnPropertyChanged("Anotacoes"); + } + } + + public List FiltroCliente + { + get + { + return this._filtroCliente; + } + set + { + this._filtroCliente = value; + base.OnPropertyChanged("FiltroCliente"); + } + } + + public string FiltroClientes + { + get + { + return this._filtroClientes; + } + set + { + this._filtroClientes = value; + base.OnPropertyChanged("FiltroClientes"); + } + } + + public Gestor.Model.Domain.Relatorios.Filtros Filtros + { + get; + set; + } + + public List Intervalo + { + get + { + return this._intervalo; + } + set + { + this._intervalo = value; + base.OnPropertyChanged("Intervalo"); + } + } + + public string IntervaloSelecionado + { + get + { + return this._intervaloSelecionado; + } + set + { + this._intervaloSelecionado = value; + base.OnPropertyChanged("IntervaloSelecionado"); + } + } + + public bool IsProspectar + { + get + { + return this._isProspectar; + } + set + { + this._isProspectar = value; + base.OnPropertyChanged("IsProspectar"); + } + } + + public string LabelProspeccao + { + get + { + return this._labelProspeccao; + } + set + { + this._labelProspeccao = value; + base.OnPropertyChanged("LabelProspeccao"); + } + } + + public bool Load { get; set; } = true; + + public ObservableCollection Notas + { + get + { + return this._notas; + } + set + { + this._notas = value; + base.OnPropertyChanged("Notas"); + } + } + + public bool NotasEnabled + { + get + { + return this._notasEnabled; + } + set + { + this._notasEnabled = value; + base.OnPropertyChanged("NotasEnabled"); + } + } + + public List Permissoes + { + get; + set; + } + + public ObservableCollection Prospeccoes + { + get + { + return this._prospeccoes; + } + set + { + this._prospeccoes = value; + base.OnPropertyChanged("Prospeccoes"); + } + } + + public bool ProspeccoesEnabled + { + get + { + return this._prospeccoesEnabled; + } + set + { + this._prospeccoesEnabled = value; + base.OnPropertyChanged("ProspeccoesEnabled"); + } + } + + public bool Publica + { + get + { + return this._publica; + } + set + { + this._publica = value; + base.OnPropertyChanged("Publica"); + } + } + + public string QuantidadeAniversariantes + { + get + { + return this._quantidadeAniversariantes; + } + set + { + this._quantidadeAniversariantes = value; + base.OnPropertyChanged("QuantidadeAniversariantes"); + } + } + + public string QuantidadeProspeccao + { + get + { + return this._quantidadeProspeccao; + } + set + { + this._quantidadeProspeccao = value; + base.OnPropertyChanged("QuantidadeProspeccao"); + } + } + + public string QuantidadeRenovacoes + { + get + { + return this._quantidadeRenovacoes; + } + set + { + this._quantidadeRenovacoes = value; + base.OnPropertyChanged("QuantidadeRenovacoes"); + } + } + + public string QuantidadeSinistro + { + get + { + return this._quantidadeSinisto; + } + set + { + this._quantidadeSinisto = value; + base.OnPropertyChanged("QuantidadeSinistro"); + } + } + + public string QuantidadeTarefas + { + get + { + return this._quantidadeTarefas; + } + set + { + this._quantidadeTarefas = value; + base.OnPropertyChanged("QuantidadeTarefas"); + } + } + + public List Ramos + { + get + { + return this._ramos; + } + set + { + this._ramos = value; + base.OnPropertyChanged("Ramos"); + } + } + + public string Referencia + { + get + { + return this._referencia; + } + set + { + this._referencia = value; + base.OnPropertyChanged("Referencia"); + } + } + + public List Referencias + { + get + { + return this._referencias; + } + set + { + this._referencias = value; + base.OnPropertyChanged("Referencias"); + } + } + + public ObservableCollection RenovacaoFiltrado + { + get + { + return this._renovacaoFiltrado; + } + set + { + this._renovacaoFiltrado = value; + base.OnPropertyChanged("RenovacaoFiltrado"); + } + } + + public bool RenovacoesEnabled + { + get + { + return this._renovacoesEnabled; + } + set + { + this._renovacoesEnabled = value; + base.OnPropertyChanged("RenovacoesEnabled"); + } + } + + public List Restricoes + { + get; + set; + } + + public Ramo SelectedRamo + { + get + { + return this._selectedRamo; + } + set + { + this._selectedRamo = value; + base.OnPropertyChanged("SelectedRamo"); + } + } + + public int SelectedTile + { + get + { + return this._selectedTile; + } + set + { + this._selectedTile = value; + this.IsProspectar = (value == 4 ? true : value == 5); + } + } + + public ObservableCollection Sinistros + { + get + { + return this._sinistros; + } + set + { + this._sinistros = value; + base.OnPropertyChanged("Sinistros"); + } + } + + public bool SinistrosEnabled + { + get + { + return this._sinistrosEnabled; + } + set + { + this._sinistrosEnabled = value; + base.OnPropertyChanged("SinistrosEnabled"); + } + } + + public ObservableCollection Tarefas + { + get + { + return this._tarefas; + } + set + { + this._tarefas = value; + base.OnPropertyChanged("Tarefas"); + } + } + + public bool TarefasEnabled + { + get + { + return this._tarefasEnabled; + } + set + { + this._tarefasEnabled = value; + base.OnPropertyChanged("TarefasEnabled"); + } + } + + public ObservableCollection Telefones + { + get + { + return this._telefones; + } + set + { + this._telefones = value; + base.OnPropertyChanged("Telefones"); + } + } + + public DashboardViewModel() + { + this._servico = new TarefaServico(); + this._apoliceServico = new ApoliceServico(); + this._clienteServico = new ClienteServico(); + this._tarefaServico = new TarefaServico(); + this._sinitrosServico = new SinistroServico(); + } + + public async Task BuscarRestricoes() + { + this.Restricoes = await this.ServicoRestriUsuario.BuscarRestricoes(Recursos.Usuario.get_Id()); + this.Permissoes = new List(); + PermissaoUsuario permissaoUsuario = await this.ServicoPermissUsuario.VerificarPermissao(Recursos.Usuario, 38); + if (permissaoUsuario != null) + { + this.Permissoes.Add(permissaoUsuario); + } + } + + public async Task CarregarAniversariantes(bool force = false) + { + List clientesAtivosInativos; + this.AniversariantesEnabled = false; + if (force || !this.CompararFiltros(this._filtroAniversariantes)) + { + this._filtroAniversariantes = this.Filtros; + List vendedorUsuarios = await base.VerificaVinculoVendedor(Recursos.Usuario); + List nums = new List(); + vendedorUsuarios.ForEach((VendedorUsuario v) => nums.Add(v.get_Vendedor().get_Id())); + clientesAtivosInativos = (vendedorUsuarios.Count <= 0 ? await this._clienteServico.BuscarAniversariantes(this.Filtros) : await this._clienteServico.BuscarAniversariantesVinculo(this.Filtros, vendedorUsuarios)); + List clientesAtivosInativos1 = clientesAtivosInativos; + this.QuantidadeAniversariantes = clientesAtivosInativos1.Count.ToString(); + if (clientesAtivosInativos1.Count != 0) + { + this.Aniversariantes = new ObservableCollection(clientesAtivosInativos1); + this.AniversariantesEnabled = true; + } + else + { + this.Aniversariantes = null; + this.AniversariantesEnabled = true; + } + } + else + { + this.AniversariantesEnabled = true; + } + } + + public async Task CarregarFiltros() + { + long num; + List nums = new List(); + List vendedorUsuarios = await base.VerificaVinculoVendedor(Recursos.Usuario); + if (vendedorUsuarios.Count > 0) + { + vendedorUsuarios.ForEach((VendedorUsuario x) => nums.Add(x.get_Vendedor().get_Id())); + } + DateTime today = DateTime.Today; + DateTime dateTime = DateTime.Today; + string intervaloSelecionado = this.IntervaloSelecionado; + if (intervaloSelecionado == "PRÓXIMOS 3 DIAS") + { + dateTime = today.AddDays(3); + } + else if (intervaloSelecionado == "PRÓXIMOS 7 DIAS") + { + dateTime = today.AddDays(7); + } + DashboardViewModel dashboardViewModel = this; + Gestor.Model.Domain.Relatorios.Filtros filtro = new Gestor.Model.Domain.Relatorios.Filtros(); + filtro.set_Inicio(today); + filtro.set_Fim(dateTime); + filtro.set_Vendedores(nums); + num = (Recursos.Usuario.get_IdEmpresa() > (long)1 ? Recursos.Usuario.get_IdEmpresa() : (long)0); + filtro.set_IdEmpresa(num); + filtro.set_Status(new List() + { + (long)1, + (long)2 + }); + dashboardViewModel.Filtros = filtro; + } + + public async Task CarregarNotas() + { + this.NotasEnabled = false; + this.Notas = new ObservableCollection(await this._servico.BuscarNotas(Recursos.Usuario.get_Id())); + this.NotasEnabled = true; + } + + public async Task CarregarProspect(DateTime inicio, DateTime fim) + { + this.ProspeccoesEnabled = false; + Gestor.Model.Domain.Relatorios.Filtros filtro = new Gestor.Model.Domain.Relatorios.Filtros(); + filtro.set_Inicio(inicio); + filtro.set_Fim(fim); + filtro.set_Ramos(new List() + { + this.SelectedRamo.get_Id() + }); + filtro.set_Vendedores(this.Filtros.get_Vendedores()); + filtro.set_Referencia(this.Referencia); + filtro.set_FiltrarDocumento(this.FiltroClientes); + Gestor.Model.Domain.Relatorios.Filtros filtro1 = filtro; + this.LabelProspeccao = string.Concat("CLIENTES QUE NÃO POSSUEM SEGUROS DO RAMO ", this.SelectedRamo.get_Nome(), " "); + string referencia = this.Referencia; + if (referencia == "VIGÊNCIA INICIAL") + { + this.LabelProspeccao = string.Concat(this.LabelProspeccao, "E QUE ESTÃO COM UMA APÓLICE INICIANDO NO PERÍODO"); + } + else if (referencia == "VIGÊNCIA FINAL") + { + this.LabelProspeccao = string.Concat(this.LabelProspeccao, "E QUE ESTÃO COM UMA APÓLICE VENCENDO NO PERÍODO"); + } + else + { + this.LabelProspeccao = string.Concat(this.LabelProspeccao, "E QUE ESTÃO COM A ULTIMA PARCELA VENCENDO NO PERÍODO"); + } + if (this._filtroProspectar == null || !(this._filtroProspectar.get_Inicio() == filtro1.get_Inicio()) || !(this._filtroProspectar.get_Fim() == filtro1.get_Fim()) || this._filtroProspectar.get_Ramos() != filtro1.get_Ramos() || !(this._filtroProspectar.get_Referencia() == filtro1.get_Referencia())) + { + this._filtroProspectar = filtro1; + List prospectars = await this._clienteServico.BuscarProspect(filtro1); + this.QuantidadeProspeccao = prospectars.Count.ToString(); + if (prospectars.Count == 0) + { + this.LabelProspeccao = "NÃO HÁ CLIENTES PARA PROSPECTAR"; + } + this.Prospeccoes = new ObservableCollection(prospectars); + this.ProspeccoesEnabled = true; + } + else + { + this.ProspeccoesEnabled = true; + } + } + + public void CarregarRamos() + { + List nums = new List() + { + (long)1, + (long)2, + (long)6, + (long)7 + }; + this.Ramos = ( + from x in Recursos.Ramos + where nums.Contains(x.get_Id()) + select x).ToList(); + this.SelectedRamo = this.Ramos.Find((Ramo x) => x.get_Id() == (long)1); + } + + public async Task CarregarRenovacoes(bool force = false) + { + List list; + this.RenovacoesEnabled = false; + if (force || !this.CompararFiltros(this._filtroRenovacao)) + { + this._filtroRenovacao = this.Filtros; + List documentos = await this._apoliceServico.BuscarApolicesVigenciaFinal(this.Filtros, false); + IEnumerable tipo = + from x in documentos + where x.get_Tipo() != 3 + select x; + list = tipo.Select((Documento x) => { + object nome; + object obj; + string str; + object nome1; + object obj1; + string str1; + object nome2; + Renovacao renovacao = new Renovacao(); + Cliente cliente = x.get_Controle().get_Cliente(); + if (cliente != null) + { + nome = cliente.get_Nome(); + } + else + { + nome = null; + } + if (nome == null) + { + nome = ""; + } + renovacao.set_Cliente((string)nome); + renovacao.set_Apolice(x.get_Apolice() ?? ""); + renovacao.set_PremioLiquido(x.get_PremioLiquido()); + renovacao.set_PremioTotal(x.get_PremioTotal()); + Negocio? negocio = x.get_Negocio(); + renovacao.set_Negocio((string)((negocio.HasValue ? ValidationHelper.GetDescription(negocio.GetValueOrDefault()) : null) ?? "")); + renovacao.set_VigenciaFinal(x.get_Vigencia2()); + Produto produto = x.get_Controle().get_Produto(); + if (produto != null) + { + obj = produto.get_Nome(); + } + else + { + obj = null; + } + if (obj == null) + { + obj = ""; + } + renovacao.set_Produto((string)obj); + renovacao.set_Ramo(x.get_Controle().get_Ramo().get_Nome() ?? ""); + renovacao.set_Seguradora((!string.IsNullOrWhiteSpace(x.get_Controle().get_Seguradora().get_NomeSocial()) ? x.get_Controle().get_Seguradora().get_NomeSocial() : x.get_Controle().get_Seguradora().get_Nome())); + renovacao.set_Status((x.get_Situacao() == 1 || x.get_Situacao() == 2 ? "NÃO TRABALHADO" : ValidationHelper.GetDescription(x.get_Situacao()) ?? "")); + Vendedor vendedorPrincipal = x.get_VendedorPrincipal(); + if (vendedorPrincipal != null) + { + str = vendedorPrincipal.get_Nome(); + } + else + { + str = null; + } + renovacao.set_Vendedor(str); + Estipulante estipulante1 = x.get_Estipulante1(); + if (estipulante1 != null) + { + nome1 = estipulante1.get_Nome(); + } + else + { + nome1 = null; + } + if (nome1 == null) + { + nome1 = ""; + } + renovacao.set_Estipulante((string)nome1); + renovacao.set_TodosVendedores((x.get_Vendedores() == null || x.get_Vendedores().Count == 0 ? "" : string.Join("; ", + from v in x.get_Vendedores() + select v.get_Nome()))); + renovacao.set_Tipo(x.get_Tipo()); + renovacao.set_Documento(x); + renovacao.set_Comissao(x.get_Comissao()); + renovacao.set_Item((x.get_ItensAtivo() != null ? (x.get_ItensAtivo().Count > 1 ? "APÓLICE COLETIVA" : (x.get_ItensAtivo().Count == 1 ? x.get_ItensAtivo().First().get_Descricao() : "")) : "")); + renovacao.set_TipoDocumento((x.get_Tipo() == 0 ? "APÓLICE" : (x.get_Tipo() == 1 ? "ENDOSSO" : ""))); + renovacao.set_Sinistro((x.get_Sinistro() ? "SIM" : "NÃO")); + renovacao.set_DataControle(x.get_DataControle()); + Status status = x.get_Status(); + if (status != null) + { + obj1 = status.get_Nome(); + } + else + { + obj1 = null; + } + if (obj1 == null) + { + obj1 = ""; + } + renovacao.set_StatusApolice((string)obj1); + renovacao.set_IdEmpresa(x.get_Controle().get_IdEmpresa()); + Empresa empresa = Recursos.Empresas.FirstOrDefault((Empresa e) => e.get_Id() == x.get_Controle().get_IdEmpresa()); + if (empresa != null) + { + str1 = empresa.get_Nome(); + } + else + { + str1 = null; + } + renovacao.set_Empresa(str1); + renovacao.set_QtdSinistro(x.get_ItensAtivo().Sum((Item s) => s.get_Sinistros().Count)); + Banco banco = x.get_Banco(); + if (banco != null) + { + nome2 = banco.get_Nome(); + } + else + { + nome2 = null; + } + if (nome2 == null) + { + nome2 = ""; + } + renovacao.set_Banco((string)nome2); + renovacao.set_Conta(x.get_Conta()); + renovacao.set_Agencia(x.get_Agencia()); + renovacao.set_Pasta(x.get_Pasta()); + renovacao.set_PastaCliente(x.get_Controle().get_Cliente().get_Pasta()); + renovacao.set_Calculos(x.get_Calculos()); + return renovacao; + }).ToList(); + List prospeccaos = await (new ProspeccaoServico()).BuscarProspeccoes(this.Filtros); + IEnumerable prospeccaos1 = + from x in prospeccaos + where x.get_Renovacao() + select x; + List renovacaos = prospeccaos1.Select((Prospeccao x) => { + string nome; + string str; + string nome1; + Renovacao renovacao = new Renovacao(); + renovacao.set_Cliente(x.get_Nome() ?? ""); + renovacao.set_Apolice("PROSPECÇÃO"); + renovacao.set_VigenciaFinal(x.get_VigenciaFinal()); + Renovacao renovacao1 = renovacao; + StatusProspeccao? status = x.get_Status(); + renovacao1.set_Status((string)((status.HasValue ? ValidationHelper.GetDescription(status.GetValueOrDefault()) : null) ?? "")); + Renovacao renovacao2 = renovacao; + Vendedor vendedor = x.get_Vendedor(); + if (vendedor != null) + { + nome = vendedor.get_Nome(); + } + else + { + nome = null; + } + renovacao2.set_Vendedor(nome); + Renovacao renovacao3 = renovacao; + Vendedor vendedor1 = x.get_Vendedor(); + if (vendedor1 != null) + { + str = vendedor1.get_Nome(); + } + else + { + str = null; + } + renovacao3.set_TodosVendedores(str); + renovacao.set_Telefone(string.Concat(new string[] { x.get_Prefixo1(), " ", x.get_Telefone1(), " | ", x.get_Prefixo2(), " ", x.get_Telefone2() })); + renovacao.set_Tipo(3); + renovacao.set_TipoDocumento("PROSPECÇÃO"); + renovacao.set_Item(x.get_Item()); + Renovacao renovacao4 = renovacao; + Produto produto = x.get_Produto(); + if (produto != null) + { + nome1 = produto.get_Nome(); + } + else + { + nome1 = null; + } + renovacao4.set_Produto(nome1); + renovacao.set_Prospeccao(x); + return renovacao; + }).ToList(); + list.AddRange(renovacaos); + this.QuantidadeRenovacoes = list.Count.ToString(); + if (list.Count != 0) + { + DashboardViewModel observableCollection = this; + List renovacaos1 = list; + observableCollection.RenovacaoFiltrado = new ObservableCollection(( + from x in renovacaos1 + orderby x.get_VigenciaFinal() + select x).ToList()); + this.RenovacoesEnabled = true; + } + else + { + this.RenovacaoFiltrado = null; + this.RenovacoesEnabled = true; + } + } + else + { + this.RenovacoesEnabled = true; + } + list = null; + } + + public async Task CarregarSinistros(bool force = false) + { + this.SinistrosEnabled = false; + if (force || !this.CompararFiltros(this._filtroSinistros)) + { + this._filtroSinistros = this.Filtros; + List sinistros = await this._sinitrosServico.BuscarSinistroPendente(this.Filtros); + this.QuantidadeSinistro = sinistros.Count.ToString(); + if (sinistros.Count != 0) + { + this.Sinistros = new ObservableCollection(sinistros); + this.SinistrosEnabled = true; + } + else + { + this.Sinistros = null; + this.SinistrosEnabled = true; + } + } + else + { + this.SinistrosEnabled = true; + } + } + + public async Task CarregarSinistros(DateTime inicio, DateTime fim) + { + this._filtroSinistros.set_Fim(fim); + this._filtroSinistros.set_Inicio(inicio); + List sinistros = await this._sinitrosServico.BuscarSinistroPendente(this._filtroSinistros); + this.QuantidadeSinistro = sinistros.Count.ToString(); + this.Sinistros = new ObservableCollection(sinistros); + } + + public async Task CarregarTarefas(bool force = false) + { + this.TarefasEnabled = false; + if (force || !this.CompararFiltros(this._filtroTarefas)) + { + this._filtroTarefas = this.Filtros; + List tarefas = await this._tarefaServico.BuscarTarefas(Recursos.Usuario.get_Id(), this._filtroTarefas.get_Inicio(), this._filtroTarefas.get_Fim(), new bool?(false)); + this.QuantidadeTarefas = tarefas.Count.ToString(); + if (tarefas.Count != 0) + { + DashboardViewModel observableCollection = this; + List tarefas1 = tarefas; + IEnumerable entidade = + from x in tarefas1 + where x.get_Entidade() != 1 + select x; + observableCollection.Tarefas = new ObservableCollection( + from x in entidade + orderby x.get_Agendamento() + select x); + this.TarefasEnabled = true; + } + else + { + this.Tarefas = null; + this.TarefasEnabled = true; + } + } + else + { + this.TarefasEnabled = true; + } + } + + private bool CompararFiltros(Gestor.Model.Domain.Relatorios.Filtros comparacao) + { + if (comparacao == null) + { + return false; + } + if (this.Filtros == null) + { + return false; + } + if (comparacao.get_Inicio() != this.Filtros.get_Inicio()) + { + return false; + } + if (comparacao.get_Fim() != this.Filtros.get_Fim()) + { + return false; + } + return true; + } + + public async Task ExcluirNota(Tarefa nota) + { + await this._servico.Excluir(nota.get_Id()); + } + + public async Task GerarCsv() + { + string str = string.Concat(Path.GetFileNameWithoutExtension(Path.GetTempFileName()), ".csv"); + List list = this.Prospeccoes.ToList(); + List strs = new List() + { + "Nome", + "Documento", + "Telefone" + }; + string str1 = await Funcoes.GerarCsv(list, strs); + File.WriteAllText(str, str1.ToString(), Encoding.UTF8); + Process.Start(str); + bool flag = true; + str = null; + return flag; + } + + public void LimparProspeccao() + { + } + + public async Task>> Salvar(Tarefa destino) + { + List> keyValuePairs; + Tarefa tarefa = destino; + List configuracoes = Recursos.Configuracoes; + tarefa.set_AgendamentoRetroativo(configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 45)); + List> keyValuePairs1 = destino.Validate(); + if (keyValuePairs1.Count <= 0) + { + await this._servico.Salvar(destino); + if (this._servico.Sucesso) + { + if (this.Publica) + { + long id = destino.get_Usuario().get_Id(); + List usuarios = Recursos.Usuarios; + List tasks = new List(); + foreach (Usuario usuario in usuarios) + { + if (id == usuario.get_Id()) + { + continue; + } + Tarefa tarefa1 = (Tarefa)destino.Clone(); + tarefa1.set_Id((long)0); + tarefa1.set_Usuario(usuario); + tasks.Add(this._servico.Salvar(tarefa1)); + } + await Task.WhenAll(tasks); + } + await this.CarregarNotas(); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + return keyValuePairs; + } + + public async Task SalvarNota(Tarefa nota) + { + return await this._servico.Salvar(nota); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/AdiantamentoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/AdiantamentoViewModel.cs new file mode 100644 index 0000000..72b47ae --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/AdiantamentoViewModel.cs @@ -0,0 +1,310 @@ +using Assinador.Infrastructure.Helpers; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class AdiantamentoViewModel : BaseSegurosViewModel + { + private readonly AdiantamentoServico _servico; + + private readonly Vendedor _selectedVendedor; + + private bool _carregando; + + private ObservableCollection _adiantamento = new ObservableCollection(); + + private Gestor.Model.Domain.Seguros.Adiantamento _selectedAdiantamento = new Gestor.Model.Domain.Seguros.Adiantamento(); + + private bool _logEnabled; + + public Gestor.Model.Domain.Seguros.Adiantamento CancelAdiantamento; + + public ObservableCollection Adiantamento + { + get + { + return this._adiantamento; + } + set + { + this._adiantamento = value; + base.OnPropertyChanged("Adiantamento"); + } + } + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.IsEnabled = !value; + base.EnableMenu = !value; + base.OnPropertyChanged("Carregando"); + } + } + + public bool LogEnabled + { + get + { + return this._logEnabled; + } + set + { + this._logEnabled = value; + base.OnPropertyChanged("LogEnabled"); + } + } + + public Gestor.Model.Domain.Seguros.Adiantamento SelectedAdiantamento + { + get + { + return this._selectedAdiantamento; + } + set + { + long? nullable; + this._selectedAdiantamento = value; + this.CancelAdiantamento = (value == null || value.get_Id() <= (long)0 ? this.CancelAdiantamento : value); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedAdiantamento"); + } + } + + public AdiantamentoViewModel(Vendedor vendedor) + { + this._servico = new AdiantamentoServico(); + this.Seleciona(vendedor); + this._selectedVendedor = vendedor; + } + + public void CancelarAlteracao() + { + this.Carregando = true; + if (this.CancelAdiantamento != null && this.Adiantamento.Any((Gestor.Model.Domain.Seguros.Adiantamento x) => x.get_Id() == this.CancelAdiantamento.get_Id())) + { + DomainBase.Copy(this.Adiantamento.First((Gestor.Model.Domain.Seguros.Adiantamento x) => x.get_Id() == this.CancelAdiantamento.get_Id()), this.CancelAdiantamento); + this.SelectedAdiantamento = this.Adiantamento.First((Gestor.Model.Domain.Seguros.Adiantamento x) => x.get_Id() == this.CancelAdiantamento.get_Id()); + } + base.Alterar(false); + this.Carregando = false; + } + + public async Task CarregarAdiantamento(int index) + { + this.Carregando = true; + this.Adiantamento = new ObservableCollection(await this._servico.BuscarAdiantamentos(this._selectedVendedor.get_Id(), index != 0)); + if (this.Adiantamento == null || this.Adiantamento.Count <= 0) + { + this.LogEnabled = false; + } + else + { + this.SelectedAdiantamento = this.Adiantamento.First(); + this.LogEnabled = true; + } + this.Carregando = false; + } + + public async Task Excluir() + { + bool flag; + object obj; + object obj1; + Gestor.Model.Domain.Seguros.Adiantamento adiantamento; + Gestor.Model.Domain.Seguros.Adiantamento adiantamento1; + if (this.SelectedAdiantamento == null || this.SelectedAdiantamento.get_Id() == 0) + { + flag = false; + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + this.Carregando = true; + if (await this._servico.Delete(this.SelectedAdiantamento)) + { + AdiantamentoViewModel adiantamentoViewModel = this; + string str = string.Concat("EXCLUIU O ADIANTAMENTO DO VENDEDOR \"", this.SelectedAdiantamento.get_Vendedor().get_Nome(), "\""); + long id = this.SelectedAdiantamento.get_Id(); + TipoTela? nullable = new TipoTela?(36); + object[] valor = new object[] { this.SelectedAdiantamento.get_Id(), null, null, null, null }; + obj = (!this.SelectedAdiantamento.get_Data().HasValue ? "-" : string.Format("{0:d}", this.SelectedAdiantamento.get_Data())); + valor[1] = obj; + valor[2] = this.SelectedAdiantamento.get_Valor(); + valor[3] = Functions.GetDescription(this.SelectedAdiantamento.get_TipoPagamento()); + obj1 = (this.SelectedAdiantamento.get_Pago() ? "SIM" : "NÃO"); + valor[4] = obj1; + adiantamentoViewModel.RegistrarAcao(str, id, nullable, string.Format("ID: {0}\nDATA: {1}\nVALOR: {2:c}\nTIPO PAGAMENTO: {3}\nPAGO: {4}", valor)); + int num = this.Adiantamento.IndexOf(this.SelectedAdiantamento); + this.Adiantamento.Remove(this.SelectedAdiantamento); + this.Adiantamento.Remove(this.SelectedAdiantamento); + this.Adiantamento = new ObservableCollection(this.Adiantamento); + if (this.Adiantamento.Count <= 0) + { + this.SelectedAdiantamento = new Gestor.Model.Domain.Seguros.Adiantamento(); + base.Alterar(false); + base.EnableMenu = false; + this.LogEnabled = false; + } + else + { + AdiantamentoViewModel adiantamentoViewModel1 = this; + adiantamento1 = (num < this.Adiantamento.Count ? this.Adiantamento.ElementAt(num) : this.Adiantamento.Last()); + adiantamentoViewModel1.SelectedAdiantamento = adiantamento1; + this.LogEnabled = true; + } + if (this.Adiantamento.Count <= 0) + { + this.SelectedAdiantamento = new Gestor.Model.Domain.Seguros.Adiantamento(); + this.LogEnabled = false; + base.Alterar(false); + } + else + { + AdiantamentoViewModel adiantamentoViewModel2 = this; + adiantamento = (num < this.Adiantamento.Count ? this.Adiantamento.ElementAt(num) : this.Adiantamento.Last()); + adiantamentoViewModel2.SelecionaAdiantamento(adiantamento); + this.LogEnabled = true; + } + this.Carregando = false; + flag = true; + } + else + { + flag = false; + } + } + else + { + flag = false; + } + return flag; + } + + public void Incluir() + { + this.SelectedAdiantamento = new Gestor.Model.Domain.Seguros.Adiantamento(); + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + object obj; + object obj1; + string str1; + if (!string.IsNullOrWhiteSpace(this.SelectedAdiantamento.get_Historico())) + { + this.SelectedAdiantamento.set_Vendedor(this._selectedVendedor); + str = (this.SelectedAdiantamento.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str1 = str; + Gestor.Model.Domain.Seguros.Adiantamento adiantamento = await this._servico.Save(this.SelectedAdiantamento); + if (this._servico.Sucesso) + { + AdiantamentoViewModel adiantamentoViewModel = this; + string str2 = string.Concat(str1, " ADIANTAMENTO DO VENDEDOR \"", adiantamento.get_Vendedor().get_Nome(), "\""); + long id = adiantamento.get_Id(); + TipoTela? nullable = new TipoTela?(36); + object[] valor = new object[] { adiantamento.get_Id(), null, null, null, null }; + obj = (!adiantamento.get_Data().HasValue ? "-" : string.Format("{0:d}", adiantamento.get_Data())); + valor[1] = obj; + valor[2] = adiantamento.get_Valor(); + valor[3] = Functions.GetDescription(adiantamento.get_TipoPagamento()); + obj1 = (adiantamento.get_Pago() ? "SIM" : "NÃO"); + valor[4] = obj1; + adiantamentoViewModel.RegistrarAcao(str2, id, nullable, string.Format("ID: {0}\nDATA: {1}\nVALOR: {2:c}\nTIPO PAGAMENTO: {3}\nPAGO: {4}", valor)); + if (!this.Adiantamento.Any((Gestor.Model.Domain.Seguros.Adiantamento x) => x.get_Id() == adiantamento.get_Id())) + { + this.Adiantamento.Add(adiantamento); + } + else + { + DomainBase.Copy(this.Adiantamento.First((Gestor.Model.Domain.Seguros.Adiantamento x) => x.get_Id() == adiantamento.get_Id()), adiantamento); + } + this.Adiantamento = new ObservableCollection(this.Adiantamento); + this.SelectedAdiantamento = this.Adiantamento.First((Gestor.Model.Domain.Seguros.Adiantamento x) => x.get_Id() == adiantamento.get_Id()); + this.LogEnabled = true; + base.Alterar(false); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = new List>() + { + new KeyValuePair("Historico|HISTÓRICO", "OBRIGATÓRIO") + }; + } + str1 = null; + return keyValuePairs; + } + + private async void Seleciona(Vendedor vendedor) + { + base.Loading(true); + await base.PermissaoTela(15); + await this.SelecionaAdiantamento(vendedor); + base.Loading(false); + } + + public void SelecionaAdiantamento(Gestor.Model.Domain.Seguros.Adiantamento adiantamento) + { + this.SelectedAdiantamento = adiantamento; + } + + private async Task SelecionaAdiantamento(Vendedor vendedor) + { + this.Carregando = true; + List adiantamentos = await (new BaseServico()).BuscarAdiantamentoAsync(vendedor); + IOrderedEnumerable pago = + from x in adiantamentos + orderby x.get_Pago() + select x; + List list = pago.ThenBy((Gestor.Model.Domain.Seguros.Adiantamento x) => x.get_Valor()).ToList(); + this.Adiantamento = new ObservableCollection(list); + if (this.Adiantamento.Count <= 0) + { + this.SelectedAdiantamento = new Gestor.Model.Domain.Seguros.Adiantamento(); + this.LogEnabled = false; + base.Alterar(false); + base.VerificarEnables(new long?(this.SelectedAdiantamento.get_Id())); + base.EnableMenu = false; + } + else + { + this.SelecionaAdiantamento(this.Adiantamento.First()); + this.LogEnabled = true; + } + this.Carregando = false; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/AgendaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/AgendaViewModel.cs new file mode 100644 index 0000000..4701416 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/AgendaViewModel.cs @@ -0,0 +1,427 @@ +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class AgendaViewModel : BaseSegurosViewModel + { + private readonly AgendaServico _servico; + + private Agenda _selectedAgenda; + + private ObservableCollection _telefones = new ObservableCollection(); + + private ObservableCollection _emails = new ObservableCollection(); + + private long _ultimoId; + + public Agenda CancelAgenda; + + private ObservableCollection _agendasFiltradas = new ObservableCollection(); + + private bool _carregando; + + public List Agendas + { + get; + set; + } + + public ObservableCollection AgendasFiltradas + { + get + { + return this._agendasFiltradas; + } + set + { + this._agendasFiltradas = value; + base.OnPropertyChanged("AgendasFiltradas"); + } + } + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.IsEnabled = !value; + base.EnableMenu = !value; + base.OnPropertyChanged("Carregando"); + } + } + + public ObservableCollection Emails + { + get + { + return this._emails; + } + set + { + this._emails = value; + base.OnPropertyChanged("Emails"); + } + } + + public Agenda SelectedAgenda + { + get + { + return this._selectedAgenda; + } + set + { + long? nullable; + this._selectedAgenda = value; + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedAgenda"); + } + } + + public ObservableCollection Telefones + { + get + { + return this._telefones; + } + set + { + this._telefones = value; + base.OnPropertyChanged("Telefones"); + } + } + + public AgendaViewModel() + { + this._servico = new AgendaServico(); + this.Seleciona(); + } + + public void CancelarAlteracao() + { + this.Carregando = true; + if (this.SelectedAgenda.get_Id() != 0) + { + DomainBase.Copy(this.Agendas.First((Agenda x) => x.get_Id() == this.CancelAgenda.get_Id()), this.CancelAgenda); + if (this.AgendasFiltradas.Count <= 0 || !this.AgendasFiltradas.Any((Agenda x) => x.get_Id() == this.CancelAgenda.get_Id())) + { + this.AgendasFiltradas.Add(this.CancelAgenda); + } + else + { + DomainBase.Copy(this.AgendasFiltradas.First((Agenda x) => x.get_Id() == this.CancelAgenda.get_Id()), this.CancelAgenda); + } + this.AgendasFiltradas = new ObservableCollection(this.AgendasFiltradas); + this.SelectedAgenda = this.AgendasFiltradas.First((Agenda x) => x.get_Id() == this.CancelAgenda.get_Id()); + } + else if (this.AgendasFiltradas.Count <= 0 || !this.AgendasFiltradas.Any((Agenda x) => x.get_Id() == this._ultimoId)) + { + if (this.Agendas.Count <= 0 || !this.Agendas.Any((Agenda x) => x.get_Id() == this._ultimoId)) + { + this.SelectedAgenda = new Agenda(); + ObservableCollection observableCollection = new ObservableCollection(); + AgendaTelefone agendaTelefone = new AgendaTelefone(); + agendaTelefone.set_Agenda(this.SelectedAgenda); + agendaTelefone.set_Tipo(new TipoTelefone?(1)); + observableCollection.Add(agendaTelefone); + this.Telefones = observableCollection; + ObservableCollection observableCollection1 = new ObservableCollection(); + AgendaEmail agendaEmail = new AgendaEmail(); + agendaEmail.set_Agenda(this.SelectedAgenda); + observableCollection1.Add(agendaEmail); + this.Emails = observableCollection1; + base.Alterar(false); + this.Carregando = false; + return; + } + this.AgendasFiltradas.Add(this.Agendas.First((Agenda x) => x.get_Id() == this._ultimoId)); + this.SelectedAgenda = this.AgendasFiltradas.First((Agenda x) => x.get_Id() == this._ultimoId); + } + else + { + this.SelectedAgenda = this.AgendasFiltradas.First((Agenda x) => x.get_Id() == this._ultimoId); + } + base.Alterar(false); + this.Carregando = false; + } + + public async Task Excluir() + { + bool flag; + if (this.SelectedAgenda == null || this.SelectedAgenda.get_Id() == 0) + { + flag = false; + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + this.Carregando = true; + if (await this._servico.Delete(this.SelectedAgenda)) + { + int num = this.AgendasFiltradas.IndexOf(this.SelectedAgenda); + this.Agendas.Remove(this.SelectedAgenda); + this.AgendasFiltradas.Remove(this.SelectedAgenda); + this.AgendasFiltradas = new ObservableCollection(this.AgendasFiltradas); + if (this.AgendasFiltradas.Count <= 0) + { + this.SelectedAgenda = new Agenda(); + this.Telefones = new ObservableCollection(); + this.Emails = new ObservableCollection(); + base.Alterar(false); + } + else if (num >= this.AgendasFiltradas.Count) + { + await this.SelecionaAgenda(this.AgendasFiltradas.Last()); + } + else + { + await this.SelecionaAgenda(this.AgendasFiltradas.ElementAt(num)); + } + this.Carregando = false; + flag = true; + } + else + { + base.Alterar(false); + this.Carregando = false; + flag = false; + } + } + else + { + flag = false; + } + return flag; + } + + public void ExcluirEmail(AgendaEmail email) + { + this.Emails.Remove(email); + } + + public void ExcluirTelefone(AgendaTelefone telefone) + { + this.Telefones.Remove(telefone); + } + + internal async Task> Filtrar(string value) + { + List agendas = await Task.Run>(() => this.FiltrarAgenda(value)); + return agendas; + } + + public List FiltrarAgenda(string filter) + { + this.AgendasFiltradas = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Agendas) : new ObservableCollection( + from x in this.Agendas + where ValidationHelper.RemoveDiacritics(x.get_Nome().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby x.get_Nome() + select x)); + return this.AgendasFiltradas.ToList(); + } + + public void Incluir() + { + if (this.SelectedAgenda != null) + { + this._ultimoId = this.SelectedAgenda.get_Id(); + } + this.SelectedAgenda = new Agenda(); + ObservableCollection observableCollection = new ObservableCollection(); + AgendaTelefone agendaTelefone = new AgendaTelefone(); + agendaTelefone.set_Agenda(this.SelectedAgenda); + agendaTelefone.set_Tipo(new TipoTelefone?(1)); + observableCollection.Add(agendaTelefone); + this.Telefones = observableCollection; + ObservableCollection observableCollection1 = new ObservableCollection(); + AgendaEmail agendaEmail = new AgendaEmail(); + agendaEmail.set_Agenda(this.SelectedAgenda); + observableCollection1.Add(agendaEmail); + this.Emails = observableCollection1; + base.Alterar(true); + } + + public void IncluirEmail() + { + if (this.SelectedAgenda == null) + { + return; + } + if (this.Emails == null) + { + this.Emails = new ObservableCollection(); + } + AgendaEmail agendaEmail = new AgendaEmail(); + agendaEmail.set_Agenda(this.SelectedAgenda); + this.Emails.Add(agendaEmail); + base.OnPropertyChanged("IncluirEmail"); + } + + public void IncluirTelefone() + { + if (this.SelectedAgenda == null) + { + return; + } + if (this.Telefones == null) + { + this.Telefones = new ObservableCollection(); + } + AgendaTelefone agendaTelefone = new AgendaTelefone(); + agendaTelefone.set_Agenda(this.SelectedAgenda); + agendaTelefone.set_Tipo(new TipoTelefone?(1)); + this.Telefones.Add(agendaTelefone); + base.OnPropertyChanged("IncluirTelefone"); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + int num; + List> keyValuePairs1 = this.SelectedAgenda.Validate(); + ObservableCollection telefones = this.Telefones; + List list = ( + from x in telefones + where !string.IsNullOrEmpty(x.get_Numero()) + select x).ToList(); + ObservableCollection emails = this.Emails; + List agendaEmails = ( + from x in emails + where !string.IsNullOrEmpty(x.get_Email()) + select x).ToList(); + foreach (AgendaTelefone agendaTelefone in list) + { + keyValuePairs1.AddRange(agendaTelefone.Validate()); + } + foreach (AgendaEmail agendaEmail in agendaEmails) + { + keyValuePairs1.AddRange(agendaEmail.Validate()); + } + if (keyValuePairs1.Count <= 0) + { + this.SelectedAgenda.set_Telefones(new ObservableCollection(list)); + this.SelectedAgenda.set_Emails(new ObservableCollection(agendaEmails)); + if (this.SelectedAgenda.get_Id() != 0) + { + this.SelectedAgenda = await this._servico.Save(this.SelectedAgenda); + if (this._servico.Sucesso) + { + this.Telefones = new ObservableCollection(this.SelectedAgenda.get_Telefones()); + this.Emails = new ObservableCollection(this.SelectedAgenda.get_Emails()); + DomainBase.Copy(this.Agendas.First((Agenda x) => x.get_Id() == this.SelectedAgenda.get_Id()), this.SelectedAgenda); + if (this.AgendasFiltradas.Count <= 0 || !this.AgendasFiltradas.Any((Agenda x) => x.get_Id() == this.SelectedAgenda.get_Id())) + { + this.AgendasFiltradas.Add(this.SelectedAgenda); + } + else + { + DomainBase.Copy(this.AgendasFiltradas.First((Agenda x) => x.get_Id() == this.SelectedAgenda.get_Id()), this.SelectedAgenda); + } + } + else + { + keyValuePairs = null; + return keyValuePairs; + } + } + else + { + this.SelectedAgenda = await this._servico.Save(this.SelectedAgenda); + if (this._servico.Sucesso) + { + this.Telefones = new ObservableCollection(this.SelectedAgenda.get_Telefones()); + this.Emails = new ObservableCollection(this.SelectedAgenda.get_Emails()); + this.Agendas.Add(this.SelectedAgenda); + ObservableCollection agendasFiltradas = this.AgendasFiltradas; + num = (this._ultimoId == 0 ? 0 : this.AgendasFiltradas.IndexOf(this.AgendasFiltradas.First((Agenda x) => x.get_Id() == this._ultimoId))); + agendasFiltradas.Insert(num, this.SelectedAgenda); + } + else + { + keyValuePairs = null; + return keyValuePairs; + } + } + this.AgendasFiltradas = new ObservableCollection(this.AgendasFiltradas); + this.SelectedAgenda = this.AgendasFiltradas.First((Agenda x) => x.get_Id() == this.SelectedAgenda.get_Id()); + base.Alterar(false); + keyValuePairs = null; + } + else + { + keyValuePairs = keyValuePairs1; + } + return keyValuePairs; + } + + private async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(34); + await this.SelecionaAgendas(); + base.Loading(false); + } + + public async Task SelecionaAgenda(Agenda agenda = null) + { + Agenda agenda1; + this.Carregando = true; + AgendaViewModel agendaViewModel = this; + agenda1 = (agenda == null ? this.AgendasFiltradas.FirstOrDefault() : this.AgendasFiltradas.FirstOrDefault((Agenda x) => x.get_Id() == agenda.get_Id())); + agendaViewModel.SelectedAgenda = agenda1; + if (this.SelectedAgenda == null) + { + this.Emails = null; + this.Telefones = null; + } + else + { + this.Emails = await this._servico.BuscarEmailsAsync(this.SelectedAgenda.get_Id()); + this.Telefones = await this._servico.BuscarTelefonesAsync(this.SelectedAgenda.get_Id()); + } + this.Carregando = false; + } + + private async Task SelecionaAgendas() + { + Agenda agenda; + this.Carregando = true; + List agendas = await (new BaseServico()).BuscarAgendasAsync(); + AgendaViewModel list = this; + List agendas1 = agendas; + list.Agendas = ( + from x in agendas1 + orderby x.get_Nome() + select x).ToList(); + this.AgendasFiltradas = new ObservableCollection(this.Agendas); + AgendaViewModel agendaViewModel = this; + agenda = (this.AgendasFiltradas.Count > 0 ? this.AgendasFiltradas.First() : new Agenda()); + agendaViewModel.SelectedAgenda = agenda; + this.Carregando = false; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/Ajuda/AtendimentosViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/Ajuda/AtendimentosViewModel.cs new file mode 100644 index 0000000..6adad6a --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/Ajuda/AtendimentosViewModel.cs @@ -0,0 +1,514 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Model.Ajuda; +using Gestor.Application.Servicos.Ajuda; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.API; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Drawer.Ajuda +{ + public class AtendimentosViewModel : BaseViewModel + { + private readonly AjudaServico _ajudaServico; + + private List _status; + + private string _webbody; + + private Visibility _envioEmailVisibility = Visibility.Collapsed; + + private Visibility _atendimentoVisibility; + + private ObservableCollection _atendimentos; + + private Atendimento _selectedAtendimento; + + private string _nome; + + private string _ddd; + + private string _telefone; + + private string _email; + + private string _assunto; + + private string _idacesso; + + private string _corpo; + + private string _senhaacesso; + + private ObservableCollection _arquivosAnexados = new ObservableCollection(); + + private Gestor.Model.Domain.Common.ArquivoDigital _selectedAnexado = new Gestor.Model.Domain.Common.ArquivoDigital(); + + private string _head; + + public ObservableCollection ArquivosAnexados + { + get + { + return this._arquivosAnexados; + } + set + { + this._arquivosAnexados = value; + base.OnPropertyChanged("ArquivosAnexados"); + } + } + + public string Assunto + { + get + { + return this._assunto; + } + set + { + this._assunto = value; + base.OnPropertyChanged("Assunto"); + } + } + + public ObservableCollection Atendimentos + { + get + { + return this._atendimentos; + } + set + { + this._atendimentos = value; + base.OnPropertyChanged("Atendimentos"); + } + } + + public Visibility AtendimentoVisibility + { + get + { + return this._atendimentoVisibility; + } + set + { + this._atendimentoVisibility = value; + base.OnPropertyChanged("AtendimentoVisibility"); + } + } + + public string Corpo + { + get + { + return this._corpo; + } + set + { + this._corpo = value; + base.OnPropertyChanged("Corpo"); + } + } + + public string Ddd + { + get + { + return this._ddd; + } + set + { + this._ddd = value; + base.OnPropertyChanged("Ddd"); + } + } + + public string Email + { + get + { + return this._email; + } + set + { + this._email = value; + base.OnPropertyChanged("Email"); + } + } + + public Visibility EnvioEmailVisibility + { + get + { + return this._envioEmailVisibility; + } + set + { + this._envioEmailVisibility = value; + base.OnPropertyChanged("EnvioEmailVisibility"); + } + } + + public string Head + { + get + { + return this._head; + } + set + { + this._head = value; + base.OnPropertyChanged("Head"); + } + } + + public Gestor.Model.API.HorarioAtendimento HorarioAtendimento + { + get; + set; + } + + public string IdAcesso + { + get + { + return this._idacesso; + } + set + { + this._idacesso = value; + base.OnPropertyChanged("IdAcesso"); + } + } + + public string Nome + { + get + { + return this._nome; + } + set + { + this._nome = value; + base.OnPropertyChanged("Nome"); + } + } + + public Gestor.Model.Domain.Common.ArquivoDigital SelectedAnexado + { + get + { + return this._selectedAnexado; + } + set + { + this._selectedAnexado = value; + base.OnPropertyChanged("SelectedAnexado"); + } + } + + public Atendimento SelectedAtendimento + { + get + { + return this._selectedAtendimento; + } + set + { + this._selectedAtendimento = value; + this.WorkOnSelectedAtendimento(value); + base.OnPropertyChanged("SelectedAtendimento"); + } + } + + public string SenhaAcesso + { + get + { + return this._senhaacesso; + } + set + { + this._senhaacesso = value; + base.OnPropertyChanged("SenhaAcesso"); + } + } + + public List Status + { + get + { + return this._status; + } + set + { + this._status = value; + base.OnPropertyChanged("Status"); + } + } + + public string Telefone + { + get + { + return this._telefone; + } + set + { + this._telefone = value; + base.OnPropertyChanged("Telefone"); + } + } + + public string WebBody + { + get + { + string str = this._webbody; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._webbody = value; + base.OnPropertyChanged("WebBody"); + } + } + + public AtendimentosViewModel() + { + base.EnableButtons = true; + this._ajudaServico = new AjudaServico(); + this.LoadCombo(); + this.InitialLoad(); + } + + public async void Anexar() + { + List arquivoDigitals = await base.AddAttachments(new List(), new List()); + if (arquivoDigitals != null) + { + arquivoDigitals.AddRange(this.ArquivosAnexados); + this.ArquivosAnexados = new ObservableCollection(arquivoDigitals); + } + } + + public void Delete(Gestor.Model.Domain.Common.ArquivoDigital arquivo) + { + if (this.SelectedAnexado == null) + { + return; + } + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital = this.ArquivosAnexados.First((Gestor.Model.Domain.Common.ArquivoDigital x) => x.get_Descricao() == arquivo.get_Descricao()); + this.ArquivosAnexados.Remove(arquivoDigital); + this.ArquivosAnexados = new ObservableCollection(this.ArquivosAnexados); + } + + public async Task>> Enviar() + { + List> keyValuePairs; + object obj; + try + { + List> keyValuePairs1 = this.Validate(); + if (keyValuePairs1.Count <= 0) + { + CustomerData customerDatum = new CustomerData(); + customerDatum.set_Corretora(Recursos.Empresa.get_Nome()); + customerDatum.set_Name(this.Nome); + customerDatum.set_AreaCode(this.Ddd); + customerDatum.set_Number(this.Telefone); + customerDatum.set_Email(this.Email); + CustomerData customerDatum1 = customerDatum; + object[] corpo = new object[] { this.Corpo, this.IdAcesso, this.SenhaAcesso, ApplicationHelper.Versao, Recursos.Usuario.get_Id(), Recursos.Usuario.get_Login(), JsonConvert.SerializeObject(customerDatum1) }; + string str = string.Format("{0}

ID Acesso: {1}
Senha Acesso: {2}

VERSÃO DO SISTEMA: {3}
USUÁRIO SISTEMA:{4} {5}

{6}

", corpo); + CustomerAttendance customerAttendance = new CustomerAttendance(); + customerAttendance.set_CustomerData(customerDatum1); + customerAttendance.set_Subject(this.Assunto); + customerAttendance.set_Body(str); + ObservableCollection arquivosAnexados = this.ArquivosAnexados; + customerAttendance.set_Attachments(arquivosAnexados.Select((Gestor.Model.Domain.Common.ArquivoDigital x) => { + Attachment attachment = new Attachment(); + attachment.set_Description(x.get_Descricao()); + attachment.set_Extension(x.get_Extensao()); + attachment.set_File(x.get_Arquivo()); + return attachment; + }).ToList()); + this.LimparComponentes(); + this.SelecionaAtendimento(); + if (await Connection.Post("Attendance/Send", customerAttendance) == null) + { + obj = null; + } + else + { + obj = new List>(); + ((List>)obj).Add(new KeyValuePair("fail", "")); + } + keyValuePairs = (List>)obj; + } + else + { + keyValuePairs = keyValuePairs1; + } + } + catch (Exception exception) + { + keyValuePairs = new List>() + { + new KeyValuePair("fail", "") + }; + } + return keyValuePairs; + } + + private async void HabilitarAtendimento(Gestor.Model.API.HorarioAtendimento horario) + { + bool id; + string str; + if (horario == null || horario.get_Autorizado()) + { + AtendimentosViewModel atendimentosViewModel = this; + Usuario usuario = Recursos.Usuario; + if (usuario != null) + { + id = usuario.get_Id() > (long)0; + } + else + { + id = false; + } + atendimentosViewModel.EnableButtons = id; + } + else + { + base.EnableButtons = false; + if (horario.get_InicioDia().HasValue) + { + string[] strArrays = new string[] { " de ", horario.get_InicioDia().DiaDaSemana(), " à ", horario.get_FimDia().DiaDaSemana(), ", das ", horario.get_InicioHora(), "hs às ", horario.get_FimHora(), "hs" }; + str = string.Concat(strArrays); + } + else + { + string[] inicioHora = new string[] { " das ", horario.get_InicioHora(), "hs às ", horario.get_FimHora(), "hs" }; + str = string.Concat(inicioHora); + } + string str1 = str; + string[] newLine = new string[] { "Prezado Cliente,", Environment.NewLine, Environment.NewLine, "Informamos Nosso horário de atendimento e recepção dos mesmos é ", str1, ".", Environment.NewLine, "Infelizmente não realizamos agendamento de data/hora de atendimento, por gentileza realize a solicitação dentro do horário comercial que retornaremos a você." }; + await base.ShowMessage(string.Concat(newLine), "OK", "", false); + } + } + + private async void InitialLoad() + { + base.IsEnabled = false; + this.HorarioAtendimento = await Connection.Get("Attendance", true, false); + this.HabilitarAtendimento(this.HorarioAtendimento); + base.IsEnabled = true; + } + + public void LimparComponentes() + { + this.Nome = Recursos.Usuario.get_Nome(); + this.Ddd = Recursos.Usuario.get_Prefixo(); + this.Telefone = Recursos.Usuario.get_Telefone(); + this.Email = Recursos.Usuario.get_Email(); + this.Assunto = null; + this.IdAcesso = null; + this.SenhaAcesso = null; + this.Corpo = string.Empty; + this.ArquivosAnexados = new ObservableCollection(); + } + + private void LoadCombo() + { + this.Status = new List() + { + "PENDENTES", + "FINALIZADOS" + }; + } + + public void SelecionaAtendimento() + { + if (this.Atendimentos != null && this.Atendimentos.Count > 0) + { + this.SelectedAtendimento = this.Atendimentos[0]; + } + this.AtendimentoVisibility = Visibility.Visible; + this.EnvioEmailVisibility = Visibility.Collapsed; + } + + public List> Validate() + { + List> keyValuePairs = ValidationHelper.AddValue(); + if (string.IsNullOrWhiteSpace(this.Nome)) + { + ValidationHelper.AddValue(keyValuePairs, "Nome", Messages.get_Obrigatorio(), true); + } + if (string.IsNullOrWhiteSpace(this.Ddd)) + { + ValidationHelper.AddValue(keyValuePairs, "Ddd", Messages.get_Obrigatorio(), true); + } + else if (!ValidationHelper.ValidacaoPrefixo(this.Ddd)) + { + ValidationHelper.AddValue(keyValuePairs, "Ddd", Messages.get_Invalido(), true); + } + if (string.IsNullOrWhiteSpace(this.Telefone)) + { + ValidationHelper.AddValue(keyValuePairs, "Telefone", Messages.get_Obrigatorio(), true); + } + else if (!ValidationHelper.ValidacaoTelefone(this.Telefone)) + { + ValidationHelper.AddValue(keyValuePairs, "Telefone", Messages.get_Invalido(), true); + } + if (string.IsNullOrWhiteSpace(this.Email)) + { + ValidationHelper.AddValue(keyValuePairs, "Email", Messages.get_Obrigatorio(), true); + } + else if (!ValidationHelper.ValidacaoEmail(this.Email)) + { + ValidationHelper.AddValue(keyValuePairs, "Email", Messages.get_Invalido(), true); + } + if (string.IsNullOrWhiteSpace(this.Corpo)) + { + ValidationHelper.AddValue(keyValuePairs, "Corpo", Messages.get_Obrigatorio(), true); + } + if (string.IsNullOrWhiteSpace(this.Assunto)) + { + ValidationHelper.AddValue(keyValuePairs, "Assunto", Messages.get_Obrigatorio(), true); + } + return keyValuePairs; + } + + private async void WorkOnSelectedAtendimento(Atendimento value) + { + if (value != null) + { + this.WebBody = await this._ajudaServico.BuscarCorpoAtendimentos(value.IdAtendimento); + } + } + + public async void WorkOnSelectedStatus(string value) + { + this.Atendimentos = await this._ajudaServico.BuscarAtendimentos(value); + this.SelecionaAtendimento(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/Ajuda/BoletosNotasViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/Ajuda/BoletosNotasViewModel.cs new file mode 100644 index 0000000..6f2e250 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/Ajuda/BoletosNotasViewModel.cs @@ -0,0 +1,122 @@ +using Gestor.Application.Model.Ajuda; +using Gestor.Application.Servicos.Ajuda; +using Gestor.Application.ViewModels.Generic; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Drawer.Ajuda +{ + public class BoletosNotasViewModel : BaseViewModel + { + private readonly AjudaServico _ajudaServico; + + private bool _carregando; + + private List _boletos; + + private string _boletoDisponivel; + + private List _status; + + public string BoletoDisponivel + { + get + { + return this._boletoDisponivel; + } + set + { + this._boletoDisponivel = value; + base.OnPropertyChanged("BoletoDisponivel"); + } + } + + public List Boletos + { + get + { + return this._boletos; + } + set + { + this._boletos = value; + base.OnPropertyChanged("Boletos"); + } + } + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.IsEnabled = !value; + base.EnableMenu = !value; + base.OnPropertyChanged("Carregando"); + } + } + + public List Status + { + get + { + return this._status; + } + set + { + this._status = value; + base.OnPropertyChanged("Status"); + } + } + + public BoletosNotasViewModel() + { + this._ajudaServico = new AjudaServico(); + this.LoadCombos(); + this.BoletoDisponivel = "Disponível para impressão a partir de\n10 (dez) dias antes do vencimento"; + } + + private void LoadCombos() + { + this.Status = new List() + { + "PENDENTES", + "BAIXADOS" + }; + } + + public async void WorkOnSelectedStatus(string value) + { + List list; + this.Carregando = true; + this.Boletos = new List(); + List boletos = await this._ajudaServico.BuscarBoletosNotas(value); + BoletosNotasViewModel boletosNotasViewModel = this; + if (value == "BAIXADOS") + { + List boletos1 = boletos; + IEnumerable hasValue = + from x in boletos1 + where x.Pagamento.HasValue + select x; + list = ( + from x in hasValue + orderby x.Pagamento descending + select x).ToList(); + } + else + { + list = boletos; + } + boletosNotasViewModel.Boletos = list; + this.Carregando = false; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/Ajuda/ContratosViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/Ajuda/ContratosViewModel.cs new file mode 100644 index 0000000..fe46bb4 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/Ajuda/ContratosViewModel.cs @@ -0,0 +1,112 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Model.Ajuda; +using Gestor.Application.Servicos.Ajuda; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.License; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Runtime.CompilerServices; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Drawer.Ajuda +{ + public class ContratosViewModel : BaseViewModel + { + private readonly AjudaServico _ajudaServico; + + private bool _carregando; + + private List _contratos; + + private Licenca _selectedContrato; + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.IsEnabled = !value; + base.EnableMenu = !value; + base.OnPropertyChanged("Carregando"); + } + } + + public List Contratos + { + get + { + return this._contratos; + } + set + { + this._contratos = value; + base.OnPropertyChanged("Contratos"); + } + } + + public Licenca SelectedContrato + { + get + { + return this._selectedContrato; + } + set + { + this._selectedContrato = value; + this.WorkOnSelectedContrato(value); + base.OnPropertyChanged("SelectedContrato"); + } + } + + public ContratosViewModel() + { + this._ajudaServico = new AjudaServico(); + this.Contratos = LicenseHelper.Produtos; + } + + internal async void WorkOnSelectedContrato(Licenca value) + { + Contrato contrato = await this._ajudaServico.BuscarContrato(value.get_Produto()); + if (!string.IsNullOrEmpty(contrato.HtmlContrato) || contrato.IdModulo != (long)7) + { + if (string.IsNullOrEmpty(contrato.HtmlContrato) && contrato.IdModulo != (long)7) + { + contrato = await this._ajudaServico.BuscarContrato(1); + } + string empty = string.Empty; + LicenseHelper.Produtos.ForEach((Licenca x) => empty = string.Concat(empty, (string.IsNullOrEmpty(empty) ? ValidationHelper.GetDescription(x.get_Produto()) : string.Concat("/ ", ValidationHelper.GetDescription(x.get_Produto()))))); + contrato.HtmlContrato = contrato.HtmlContrato.Replace("[<NOME>]", Recursos.Empresa.get_Nome()); + contrato.HtmlContrato = contrato.HtmlContrato.Replace("[<ENDERECO>]", Recursos.Empresa.get_Endereco()); + contrato.HtmlContrato = contrato.HtmlContrato.Replace("[<CIDADE>]", Recursos.Empresa.get_Cidade()); + contrato.HtmlContrato = contrato.HtmlContrato.Replace("[<CNPJ>]", Recursos.Empresa.get_Documento()); + contrato.HtmlContrato = contrato.HtmlContrato.Replace("[<NS>]", Recursos.Empresa.get_Serial()); + string htmlContrato = contrato.HtmlContrato; + DateTime date = Funcoes.GetNetworkTime().Date; + contrato.HtmlContrato = htmlContrato.Replace("[<DATA>]", date.ToString("dd/MM/yyyy")); + contrato.HtmlContrato = contrato.HtmlContrato.Replace("[<VALOR>]", "Conforme Mensalidade"); + contrato.HtmlContrato = contrato.HtmlContrato.Replace("[<OUTROS>]", empty.Replace("*", "")); + string tempPath = Path.GetTempPath(); + string str = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.html", tempPath, (new Regex(string.Concat("[", Regex.Escape(string.Concat(new string(Path.GetInvalidFileNameChars()), new string(Path.GetInvalidPathChars()))), "]"))).Replace(ValidationHelper.GetDescription(value.get_Produto()), ""), Funcoes.GetNetworkTime()); + StreamWriter streamWriter = new StreamWriter(str, true, Encoding.UTF8); + streamWriter.Write(contrato.HtmlContrato); + streamWriter.Close(); + Process.Start(str); + } + else + { + Process.Start(string.Format("https://aggilizador.com.br/Contrato.aspx?id={0}", ApplicationHelper.IdFornecedor)); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/Ajuda/InstalacaoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/Ajuda/InstalacaoViewModel.cs new file mode 100644 index 0000000..8ee9f0b --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/Ajuda/InstalacaoViewModel.cs @@ -0,0 +1,281 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Model.Ajuda; +using Gestor.Application.Servicos.Ajuda; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.License; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows.Controls; + +namespace Gestor.Application.ViewModels.Drawer.Ajuda +{ + public class InstalacaoViewModel : BaseViewModel + { + private readonly AjudaServico _ajudaServico; + + private bool _enableExclusao; + + private bool _mostrarAggilizador; + + private string _infoGestor; + + private string _infoAggilizador; + + private bool _carregando; + + private List _agger; + + private ObservableCollection _aggerFiltrado; + + private List _aggilizador; + + public List Agger + { + get + { + return this._agger; + } + set + { + this._agger = value; + base.OnPropertyChanged("Agger"); + } + } + + public ObservableCollection AggerFiltrado + { + get + { + return this._aggerFiltrado; + } + set + { + this._aggerFiltrado = value; + base.OnPropertyChanged("AggerFiltrado"); + } + } + + public List Aggilizador + { + get + { + return this._aggilizador; + } + set + { + this._aggilizador = value; + base.OnPropertyChanged("Aggilizador"); + } + } + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.IsEnabled = !value; + base.EnableMenu = !value; + base.OnPropertyChanged("Carregando"); + } + } + + public bool EnableExclusao + { + get + { + return this._enableExclusao; + } + set + { + this._enableExclusao = value; + base.OnPropertyChanged("EnableExclusao"); + } + } + + public string InfoAggilizador + { + get + { + return this._infoAggilizador; + } + set + { + this._infoAggilizador = value; + base.OnPropertyChanged("InfoAggilizador"); + } + } + + public string InfoGestor + { + get + { + return this._infoGestor; + } + set + { + this._infoGestor = value; + base.OnPropertyChanged("InfoGestor"); + } + } + + public AutoCompleteFilterPredicate InstalacaoItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_370 = InstalacaoViewModel.u003cu003ec.u003cu003e9__37_0; + if (u003cu003e9_370 == null) + { + u003cu003e9_370 = new AutoCompleteFilterPredicate(InstalacaoViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (((Gestor.Application.Model.Ajuda.Instalacao)obj).Maquina.ToUpper().Contains(searchText.ToUpper()) || ((Gestor.Application.Model.Ajuda.Instalacao)obj).Usuario.ToUpper().Contains(searchText.ToUpper())) + { + return true; + } + return ((Gestor.Application.Model.Ajuda.Instalacao)obj).DataIntalacao.ToString().Contains(searchText.ToUpper()); + }); + InstalacaoViewModel.u003cu003ec.u003cu003e9__37_0 = u003cu003e9_370; + } + return u003cu003e9_370; + } + } + + public bool MostrarAggilizador + { + get + { + return this._mostrarAggilizador; + } + set + { + this._mostrarAggilizador = value; + base.OnPropertyChanged("MostrarAggilizador"); + } + } + + public InstalacaoViewModel() + { + Usuario usuario = Recursos.Usuario; + if (usuario != null) + { + id = usuario.get_Id() > (long)0; + } + else + { + id = false; + } + this._enableExclusao = id; + base(); + bool id; + this._ajudaServico = new AjudaServico(); + this.LoadInstalacoes(); + } + + public async void Excluir(long id) + { + if (await this._ajudaServico.ExcluirInstalacao(id)) + { + this.LoadInstalacoes(); + } + } + + internal async Task> Filtrar(string value) + { + List instalacaos = await Task.Run>(() => this.FiltrarInstalacao(value)); + return instalacaos; + } + + public List FiltrarInstalacao(string filter) + { + this.AggerFiltrado = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Agger) : new ObservableCollection(this.Agger.Where((Gestor.Application.Model.Ajuda.Instalacao x) => { + if (ValidationHelper.RemoveDiacritics(x.Maquina.Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) || ValidationHelper.RemoveDiacritics(x.Usuario.Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter))) + { + return true; + } + return x.DataIntalacao.ToString().Contains(ValidationHelper.RemoveDiacritics(filter)); + }))); + return this.AggerFiltrado.ToList(); + } + + private async void LoadInstalacoes() + { + int? nullable; + List instalacaos; + int? nullable1; + int? nullable2; + string str; + this.Carregando = true; + ObservableCollection observableCollection = await this._ajudaServico.BuscarLicencas(); + InstalacaoViewModel list = this; + ObservableCollection observableCollection1 = observableCollection; + list.Agger = ( + from x in observableCollection1 + where !string.IsNullOrEmpty(x.IdGerenciador) + select x).ToList(); + this.AggerFiltrado = new ObservableCollection(this.Agger); + InstalacaoViewModel instalacaoViewModel = this; + List produtos = LicenseHelper.Produtos; + if (produtos.Any((Licenca x) => x.get_Produto() == 81)) + { + instalacaos = new List(); + } + else + { + ObservableCollection observableCollection2 = observableCollection; + instalacaos = ( + from x in observableCollection2 + where !string.IsNullOrEmpty(x.IdAggilizador) + select x).ToList(); + } + instalacaoViewModel.Aggilizador = instalacaos; + InstalacaoViewModel instalacaoViewModel1 = this; + object count = this.Agger.Count; + List licencas = LicenseHelper.Produtos; + Licenca licenca = licencas.FirstOrDefault((Licenca x) => x.get_Produto() == 1); + if (licenca != null) + { + nullable1 = new int?(licenca.get_Quantidade()); + } + else + { + nullable = null; + nullable1 = nullable; + } + instalacaoViewModel1.InfoGestor = string.Format("{0} LICENÇAS INSTALADAS DE {1} LICENÇAS CONTRATADAS.", count, nullable1); + InstalacaoViewModel instalacaoViewModel2 = this; + if (this.Aggilizador.Count > 0) + { + object obj = this.Aggilizador.Count; + List produtos1 = LicenseHelper.Produtos; + Licenca licenca1 = produtos1.FirstOrDefault((Licenca x) => x.get_Produto() == 81); + if (licenca1 != null) + { + nullable2 = new int?(licenca1.get_Quantidade()); + } + else + { + nullable = null; + nullable2 = nullable; + } + str = string.Format("{0} LICENÇAS INSTALADAS DE {1} LICENÇAS CONTRATADAS.", obj, nullable2); + } + else + { + str = ""; + } + instalacaoViewModel2.InfoAggilizador = str; + this.MostrarAggilizador = this.Aggilizador.Count > 0; + this.Carregando = false; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/ArquivoDigitalViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/ArquivoDigitalViewModel.cs new file mode 100644 index 0000000..6963a1e --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/ArquivoDigitalViewModel.cs @@ -0,0 +1,1414 @@ +using Assinador.Model.Domain; +using Assinador.Model.Generic; +using CsQuery.ExtensionMethods.Internal; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Ferramentas; +using Gestor.Common.Security; +using Gestor.Common.Validation; +using Gestor.Model.API; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.MalaDireta; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using Gestor.Model.License; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class ArquivoDigitalViewModel : BaseSegurosViewModel + { + private readonly ClienteServico _servico; + + private Visibility _assinarVisibility = Visibility.Collapsed; + + private Visibility _visibilityWhatsApp = Visibility.Collapsed; + + private bool _carregando; + + private bool _activated = true; + + private bool _adDocumento; + + private Visibility _adDocumentoVisibility; + + private bool _isVisibleSalvar; + + private Visibility _enviarSelecionadosVisibility; + + private Cliente _selectedCliente = new Cliente(); + + private ObservableCollection _telefones = new ObservableCollection(); + + private ObservableCollection _arquivos = new ObservableCollection(); + + private ObservableCollection _arquivosTela = new ObservableCollection(); + + private IndiceArquivoDigital _selectedArquivo = new IndiceArquivoDigital(); + + private ObservableCollection _arquivosAnexados = new ObservableCollection(); + + private Gestor.Model.Domain.Common.ArquivoDigital _selectedAnexado = new Gestor.Model.Domain.Common.ArquivoDigital(); + + private string _titulo = ""; + + private ObservableCollection _emails = new ObservableCollection(); + + private string _assunto; + + private string _corpo; + + private string _nome; + + private string _documento; + + private string _email; + + private string _licencas; + + private string _assinadorKey; + + public bool Activated + { + get + { + return this._activated; + } + set + { + this._activated = value; + base.OnPropertyChanged("Activated"); + } + } + + public bool AdDocumento + { + get + { + return this._adDocumento; + } + set + { + this._adDocumento = value; + this.CarregarArquivos(); + base.OnPropertyChanged("AdDocumento"); + } + } + + public Visibility AdDocumentoVisibility + { + get + { + return this._adDocumentoVisibility; + } + set + { + this._adDocumentoVisibility = value; + base.OnPropertyChanged("AdDocumentoVisibility"); + } + } + + public ObservableCollection Arquivos + { + get + { + return this._arquivos; + } + set + { + this._arquivos = value; + this.ArquivosTela = value; + base.OnPropertyChanged("Arquivos"); + } + } + + public ObservableCollection ArquivosAnexados + { + get + { + return this._arquivosAnexados; + } + set + { + this._arquivosAnexados = value; + this.IsVisibleSalvar = (value == null ? false : value.Count > 0); + base.OnPropertyChanged("ArquivosAnexados"); + } + } + + public ObservableCollection ArquivosTela + { + get + { + return this._arquivosTela; + } + set + { + this._arquivosTela = value; + base.OnPropertyChanged("ArquivosTela"); + } + } + + public Visibility AssinarVisibility + { + get + { + return this._assinarVisibility; + } + set + { + this._assinarVisibility = value; + base.OnPropertyChanged("AssinarVisibility"); + } + } + + public string Assunto + { + get + { + return this._assunto; + } + set + { + this._assunto = value; + base.OnPropertyChanged("Assunto"); + } + } + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.IsEnabled = !value; + base.OnPropertyChanged("Carregando"); + } + } + + public string Corpo + { + get + { + return this._corpo; + } + set + { + this._corpo = value; + base.OnPropertyChanged("Corpo"); + } + } + + public string Documento + { + get + { + return this._documento; + } + set + { + this._documento = value; + base.OnPropertyChanged("Documento"); + } + } + + public string Email + { + get + { + return this._email; + } + set + { + string str; + if (value != null) + { + str = value.Trim(); + } + else + { + str = null; + } + this._email = str; + base.OnPropertyChanged("Email"); + } + } + + public ObservableCollection Emails + { + get + { + return this._emails; + } + set + { + this._emails = value; + base.OnPropertyChanged("Emails"); + } + } + + public Visibility EnviarSelecionadosVisibility + { + get + { + return this._enviarSelecionadosVisibility; + } + set + { + this._enviarSelecionadosVisibility = (!base.Restricao(20) ? value : Visibility.Collapsed); + base.OnPropertyChanged("EnviarSelecionadosVisibility"); + } + } + + private FiltroArquivoDigital Filtro + { + get; + } + + public bool IsVisibleSalvar + { + get + { + return this._isVisibleSalvar; + } + set + { + this._isVisibleSalvar = value; + base.OnPropertyChanged("IsVisibleSalvar"); + } + } + + public string Licencas + { + get + { + return this._licencas; + } + set + { + this._licencas = value; + base.OnPropertyChanged("Licencas"); + } + } + + public string Nome + { + get + { + return this._nome; + } + set + { + this._nome = value; + base.OnPropertyChanged("Nome"); + } + } + + public Gestor.Model.Domain.Common.ArquivoDigital SelectedAnexado + { + get + { + return this._selectedAnexado; + } + set + { + this._selectedAnexado = value; + base.OnPropertyChanged("SelectedAnexado"); + } + } + + public IndiceArquivoDigital SelectedArquivo + { + get + { + return this._selectedArquivo; + } + set + { + this._selectedArquivo = value; + base.OnPropertyChanged("SelectedArquivo"); + } + } + + public Cliente SelectedCliente + { + get + { + return this._selectedCliente; + } + set + { + this._selectedCliente = value; + base.OnPropertyChanged("SelectedCliente"); + } + } + + public ObservableCollection Telefones + { + get + { + return this._telefones; + } + set + { + this._telefones = value; + base.OnPropertyChanged("Telefones"); + } + } + + public string Titulo + { + get + { + return this._titulo; + } + set + { + this._titulo = value; + base.OnPropertyChanged("Titulo"); + } + } + + public Visibility VisibilityWhatsApp + { + get + { + return this._visibilityWhatsApp; + } + set + { + this._visibilityWhatsApp = value; + base.OnPropertyChanged("VisibilityWhatsApp"); + } + } + + public ArquivoDigitalViewModel(FiltroArquivoDigital filtro) + { + this.Filtro = filtro; + this._servico = new ClienteServico(); + this.CarregarArquivos(); + this.VisibilityWhatsApp = (filtro.get_Tipo() == 2 || filtro.get_Tipo() == 3 || filtro.get_Tipo() == 4 || filtro.get_Tipo() == 5 ? Visibility.Visible : Visibility.Collapsed); + this.AdDocumentoVisibility = ((filtro.get_Tipo() == 4 || filtro.get_Tipo() == 3 || filtro.get_Tipo() == 5) && (new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 2).get_Consultar() ? Visibility.Visible : Visibility.Collapsed); + base.EnableMenu = true; + switch (filtro.get_Tipo()) + { + case 0: + case 6: + case 7: + case 8: + case 9: + case 10: + case 12: + case 13: + case 14: + case 15: + case 17: + { + this.EnviarSelecionadosVisibility = Visibility.Collapsed; + return; + } + default: + { + this.EnviarSelecionadosVisibility = Visibility.Visible; + return; + } + } + } + + public async void Anexar() + { + ObservableCollection arquivos = this.Arquivos; + List list = arquivos.Select((IndiceArquivoDigital x) => { + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital = new Gestor.Model.Domain.Common.ArquivoDigital(); + arquivoDigital.set_Descricao(x.get_Descricao()); + arquivoDigital.set_Extensao(x.get_Extensao()); + return arquivoDigital; + }).ToList(); + List arquivoDigitals = await base.AddAttachments(this.ArquivosAnexados.ToList(), list); + if (arquivoDigitals != null) + { + List configuracoes = Recursos.Configuracoes; + if (!configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 47)) + { + arquivoDigitals = await base.ShowDialogAnexar(arquivoDigitals, false); + if (arquivoDigitals == null) + { + return; + } + } + arquivoDigitals.AddRange(this.ArquivosAnexados); + this.ArquivosAnexados = new ObservableCollection(arquivoDigitals); + } + } + + public async Task Assinar(IndiceArquivoDigital indice, bool lote = false) + { + ArquivoParaAssinaturaAssinador arquivoParaAssinaturaAssinador; + object obj; + int num = 0; + try + { + AssinaturaServico assinaturaServico = new AssinaturaServico(); + Gestor.Application.Servicos.ArquivoDigitalServico arquivoDigitalServico = new Gestor.Application.Servicos.ArquivoDigitalServico(); + if (await assinaturaServico.VerificarAssinado(indice.get_Id())) + { + if (!lote) + { + await base.ShowMessage("ARQUIVO JÁ ASSINADO", "OK", "", false); + } + arquivoParaAssinaturaAssinador = null; + return arquivoParaAssinaturaAssinador; + } + else if (await assinaturaServico.VerificarEnviado(indice.get_Id())) + { + arquivoParaAssinaturaAssinador = await assinaturaServico.Reenviar(indice.get_Id()); + return arquivoParaAssinaturaAssinador; + } + else if (this.Nome == null || string.IsNullOrWhiteSpace(this.Nome)) + { + if (!lote) + { + await base.ShowMessage("É NECESSÁRIO QUE O ASSINANTE POSSUA UM NOME VÁLIDO", "OK", "", false); + } + arquivoParaAssinaturaAssinador = null; + return arquivoParaAssinaturaAssinador; + } + else if (this.Documento == null || !Gestor.Common.Validation.ValidationHelper.ValidateDocument(this.Documento)) + { + if (!lote) + { + await base.ShowMessage("É NECESSÁRIO QUE O ASSINANTE POSSUA UM DOCUMENTO VÁLIDO", "OK", "", false); + } + arquivoParaAssinaturaAssinador = null; + return arquivoParaAssinaturaAssinador; + } + else if (this.Documento.Length > 14) + { + if (!lote) + { + await base.ShowMessage("O DOCUMENTO DO ASSINANTE DEVE SER CPF E NÃO CNPJ", "OK", "", false); + } + arquivoParaAssinaturaAssinador = null; + return arquivoParaAssinaturaAssinador; + } + else if (this.Email == null || !Gestor.Model.Helper.ValidationHelper.ValidacaoEmail(this.Email)) + { + if (!lote) + { + await base.ShowMessage("É NECESSÁRIO QUE O ASSINANTE POSSUA UM E-MAIL VÁLIDO", "OK", "", false); + } + arquivoParaAssinaturaAssinador = null; + return arquivoParaAssinaturaAssinador; + } + else + { + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital = await arquivoDigitalServico.BuscarPorId(indice.get_IdArquivoDigital(), indice.get_Bd()); + long id = (long)0; + Gestor.Model.Domain.Seguros.Documento documento = new Gestor.Model.Domain.Seguros.Documento(); + switch (this.Filtro.get_Tipo()) + { + case 2: + { + id = ((Gestor.Model.Domain.Seguros.Documento)this.Filtro.get_Parente()).get_Id(); + break; + } + case 3: + { + id = ((Parcela)this.Filtro.get_Parente()).get_Documento().get_Id(); + break; + } + case 4: + { + id = ((Item)this.Filtro.get_Parente()).get_Documento().get_Id(); + break; + } + case 5: + { + id = ((Sinistro)this.Filtro.get_Parente()).get_ControleSinistro().get_Item().get_Documento().get_Id(); + break; + } + default: + { + arquivoParaAssinaturaAssinador = null; + return arquivoParaAssinaturaAssinador; + } + } + AssinaturaServico assinaturaServico1 = assinaturaServico; + ApoliceAssinador apoliceAssinador = new ApoliceAssinador(); + apoliceAssinador.set_ArquivoId(indice.get_Id()); + apoliceAssinador.set_ClienteId(this.SelectedCliente.get_Id()); + apoliceAssinador.set_Cliente(this.Nome); + apoliceAssinador.set_Email(this.Email); + apoliceAssinador.set_Documento(this.Documento); + apoliceAssinador.set_Id(id); + ArquivoParaAssinaturaAssinador arquivoParaAssinaturaAssinador1 = await assinaturaServico1.Assinar(arquivoDigital, apoliceAssinador); + arquivoParaAssinaturaAssinador = await assinaturaServico.Save(arquivoParaAssinaturaAssinador1); + return arquivoParaAssinaturaAssinador; + } + } + catch (Exception exception) + { + obj = exception; + num = 1; + } + if (num != 1) + { + throw null; + } + Exception exception1 = (Exception)obj; + string[] newLine = new string[] { "ERRO AO ENVIAR PARA ASSINATURA", Environment.NewLine, exception1.Message, Environment.NewLine, "POR FAVOR CONTATE A AGGER ATRAVÉS DO PAINEL DE ATENDIMENTOS" }; + await base.ShowMessage(string.Concat(newLine), "OK", "", false); + arquivoParaAssinaturaAssinador = null; + return arquivoParaAssinaturaAssinador; + } + + private void AtualizaEmpresa() + { + Recursos.Empresa = (new BaseServico()).BuscarEmpresa(Recursos.Usuario.get_IdEmpresa()); + } + + public void Baixar(IndiceArquivoDigital arquivo, bool abrir = false) + { + if (arquivo == null || arquivo.get_IdArquivoDigital() == 0) + { + return; + } + base.Download(arquivo, abrir); + } + + public async Task BaixarTodos() + { + bool flag; + if (this.Arquivos == null || this.Arquivos.Count == 0) + { + flag = false; + } + else + { + flag = await base.DownloadAll(this.Arquivos.ToList(), this.Filtro.get_Id()); + } + return flag; + } + + public async Task CarregaArquivos() + { + TipoArquivoDigital tipo; + bool id; + string email; + object emailResponsavel; + object nomeResponsavel; + object documentoResponsavel; + string str; + string str1; + Cliente cliente; + FiltroArquivoDigital filtro = this.Filtro; + if (filtro != null) + { + id = filtro.get_Id() == (long)0; + } + else + { + id = false; + } + if (!id) + { + this.Carregando = true; + base.IsVisible = Visibility.Collapsed; + this.AssinarVisibility = Visibility.Collapsed; + if (this.Filtro != null) + { + List indiceArquivoDigitals = await this.ArquivoDigitalServico.BuscarPorTipo(this.Filtro.get_Tipo(), this.Filtro.get_Id()); + if (this.AdDocumento) + { + List indiceArquivoDigitals1 = indiceArquivoDigitals; + List indiceArquivoDigitals2 = await this.ArquivoDigitalServico.BuscarPorTipo(2, this.Filtro.get_IdApolice()); + indiceArquivoDigitals1.AddRange(indiceArquivoDigitals2); + indiceArquivoDigitals1 = null; + } + ArquivoDigitalViewModel observableCollection = this; + List indiceArquivoDigitals3 = indiceArquivoDigitals; + observableCollection.Arquivos = new ObservableCollection( + from x in indiceArquivoDigitals3 + orderby x.get_Descricao() + select x); + tipo = this.Filtro.get_Tipo(); + switch (tipo) + { + case 2: + { + this.AssinarVisibility = Visibility.Visible; + Gestor.Model.Domain.Seguros.Documento parente = (Gestor.Model.Domain.Seguros.Documento)this.Filtro.get_Parente(); + this.SelectedCliente = parente.get_Controle().get_Cliente(); + ArquivoDigitalViewModel arquivoDigitalViewModel = this; + str = (parente.get_Apolice() != string.Empty ? string.Concat("ARQUIVO DIGITAL DA APÓLICE \"", parente.get_Apolice(), "\"") : string.Concat("ARQUIVO DIGITAL DA PROPOSTA \"", parente.get_Proposta(), "\"")); + arquivoDigitalViewModel.Titulo = str; + break; + } + case 3: + { + this.AssinarVisibility = Visibility.Visible; + Parcela parcela = (Parcela)this.Filtro.get_Parente(); + this.SelectedCliente = parcela.get_Documento().get_Controle().get_Cliente(); + ArquivoDigitalViewModel arquivoDigitalViewModel1 = this; + str1 = (parcela.get_Documento().get_Apolice() != string.Empty ? string.Format("ARQUIVO DIGITAL DA PARCELA \"{0}\" DA APÓLICE \"{1}\"", parcela.get_NumeroParcela(), parcela.get_Documento().get_Apolice()) : string.Format("ARQUIVO DIGITAL DA PARCELA \"{0}\" DA PROPOSTA \"{1}\"", parcela.get_NumeroParcela(), parcela.get_Documento().get_Proposta())); + arquivoDigitalViewModel1.Titulo = str1; + DetalheExtrato detalheExtrato = await (new ServicoExtrato()).FindByParcelaId(parcela.get_Id()); + if (detalheExtrato == null) + { + break; + } + indiceArquivoDigitals = await this.ArquivoDigitalServico.BuscarPorTipo(7, detalheExtrato.get_Extrato().get_Id()); + List indiceArquivoDigitals4 = indiceArquivoDigitals; + indiceArquivoDigitals4.ForEach((IndiceArquivoDigital x) => x.set_NaoExcluir(true)); + ObservableCollection arquivos = this.Arquivos; + List indiceArquivoDigitals5 = indiceArquivoDigitals; + ExtensionMethods.AddRange(arquivos, new ObservableCollection( + from x in indiceArquivoDigitals5 + orderby x.get_Descricao() + select x)); + break; + } + case 4: + { + this.AssinarVisibility = Visibility.Visible; + Item item = (Item)this.Filtro.get_Parente(); + this.SelectedCliente = item.get_Documento().get_Controle().get_Cliente(); + this.Titulo = string.Concat("ARQUIVO DIGITAL DO ITEM \"", item.get_Descricao(), "\""); + break; + } + case 5: + { + this.AssinarVisibility = Visibility.Visible; + Sinistro sinistro = (Sinistro)this.Filtro.get_Parente(); + this.SelectedCliente = sinistro.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Cliente(); + string[] numero = new string[] { "ARQUIVO DIGITAL DO SINITRO \"", sinistro.get_Numero(), "\" DO ITEM \"", sinistro.get_ControleSinistro().get_Item().get_Descricao(), "\"" }; + this.Titulo = string.Concat(numero); + break; + } + case 6: + { + Vendedor vendedor = (Vendedor)this.Filtro.get_Parente(); + Cliente cliente1 = new Cliente(); + cliente1.set_Id(vendedor.get_Id()); + cliente1.set_Nome(vendedor.get_Nome()); + this.SelectedCliente = cliente1; + this.Titulo = string.Format("ARQUIVO DIGITAL DO VENDEDOR {0} {1}", vendedor.get_Nome(), vendedor.get_Id()); + break; + } + case 7: + { + Extrato extrato = (Extrato)this.Filtro.get_Parente(); + Cliente cliente2 = new Cliente(); + cliente2.set_Nome(string.Concat("EXTRATO ", extrato.get_Numero())); + this.SelectedCliente = cliente2; + this.Titulo = string.Format("ARQUIVO DIGITAL DO EXTRATO {0} ID:{1}", extrato.get_Numero(), extrato.get_Id()); + break; + } + case 8: + { + Seguradora seguradora = (Seguradora)this.Filtro.get_Parente(); + Cliente cliente3 = new Cliente(); + cliente3.set_Id(seguradora.get_Id()); + cliente3.set_Nome(seguradora.get_Nome()); + this.SelectedCliente = cliente3; + this.Titulo = string.Format("ARQUIVO DIGITAL DA SEGURADORA {0} {1}", seguradora.get_Nome(), seguradora.get_Id()); + break; + } + case 9: + { + Lancamento lancamento = (Lancamento)this.Filtro.get_Parente(); + if (!lancamento.get_Historico().Equals("TRANSFERÊNCIA ENTRE CONTAS")) + { + Cliente cliente4 = new Cliente(); + cliente4.set_Id(lancamento.get_Controle().get_Fornecedor().get_Id()); + cliente4.set_Nome(lancamento.get_Controle().get_Fornecedor().get_Nome()); + this.SelectedCliente = cliente4; + this.Titulo = string.Format("ARQUIVO DIGITAL DO LANCAMENTO {0}, PLANO {1}, CENTRO {2}", lancamento.get_Id(), lancamento.get_Controle().get_Plano().get_Nome(), lancamento.get_Controle().get_Centro().get_Descricao()); + break; + } + else + { + await base.ShowMessage("NÃO É POSSIVEL INCLUIR ARQUIVOS EM TRANSFERÊNCIA ENTRE CONTAS", "OK", "", false); + base.CloseDrawer(); + return; + } + } + case 10: + { + Fornecedor fornecedor = (Fornecedor)this.Filtro.get_Parente(); + Cliente cliente5 = new Cliente(); + cliente5.set_Id(fornecedor.get_Id()); + cliente5.set_Nome(fornecedor.get_Nome()); + this.SelectedCliente = cliente5; + this.Titulo = string.Format("ARQUIVO DIGITAL DO FORNECEDOR {0} {1}", fornecedor.get_Nome(), fornecedor.get_Id()); + break; + } + case 11: + { + Prospeccao prospeccao = (Prospeccao)this.Filtro.get_Parente(); + Cliente cliente6 = new Cliente(); + cliente6.set_Id(prospeccao.get_Id()); + cliente6.set_Nome(prospeccao.get_Nome()); + this.SelectedCliente = cliente6; + this.Titulo = string.Format("ARQUIVO DIGITAL DA PROSPECÇÃO {0} {1} {2}", prospeccao.get_Nome(), prospeccao.get_Id(), prospeccao.get_Item()); + break; + } + case 12: + { + Usuario usuario = (Usuario)this.Filtro.get_Parente(); + Cliente cliente7 = new Cliente(); + cliente7.set_Id(usuario.get_Id()); + cliente7.set_Nome(usuario.get_Nome()); + this.SelectedCliente = cliente7; + this.Titulo = string.Format("ARQUIVO DIGITAL DO USUÁRIO {0} {1}", usuario.get_Nome(), usuario.get_Id()); + break; + } + case 13: + { + Empresa empresa = (Empresa)this.Filtro.get_Parente(); + Cliente cliente8 = new Cliente(); + cliente8.set_Id(empresa.get_Id()); + cliente8.set_Nome(empresa.get_Nome()); + this.SelectedCliente = cliente8; + this.Titulo = string.Format("ARQUIVO DIGITAL DA EMPRESA {0} {1}", empresa.get_Nome(), empresa.get_Id()); + break; + } + case 14: + { + Socio socio = (Socio)this.Filtro.get_Parente(); + Cliente cliente9 = new Cliente(); + cliente9.set_Id(socio.get_Id()); + cliente9.set_Nome(socio.get_Nome()); + this.SelectedCliente = cliente9; + this.Titulo = string.Format("ARQUIVO DIGITAL DO SÓCIO {0} {1}", socio.get_Nome(), socio.get_Id()); + break; + } + case 15: + { + Tarefa tarefa = (Tarefa)this.Filtro.get_Parente(); + Cliente cliente10 = new Cliente(); + cliente10.set_Id(tarefa.get_Id()); + cliente10.set_Nome(string.Concat("TAREFA - ", tarefa.get_Titulo())); + this.SelectedCliente = cliente10; + this.Titulo = string.Format("ANEXO DA TAREFA {0} {1}", tarefa.get_Titulo(), tarefa.get_Id()); + break; + } + case 16: + { + NotaFiscal notaFiscal = (NotaFiscal)this.Filtro.get_Parente(); + Cliente cliente11 = new Cliente(); + cliente11.set_Id(notaFiscal.get_Id()); + cliente11.set_Nome(string.Format("NOTA FISCAL - {0} {1:d}", notaFiscal.get_Seguradora().get_NomeSocial(), notaFiscal.get_Data())); + this.SelectedCliente = cliente11; + this.Titulo = string.Format("ANEXO DA NOTA FISCAL {0} {1:d}", notaFiscal.get_Seguradora().get_NomeSocial(), notaFiscal.get_Data()); + break; + } + case 17: + { + Estipulante estipulante = (Estipulante)this.Filtro.get_Parente(); + Cliente cliente12 = new Cliente(); + cliente12.set_Id(estipulante.get_Id()); + cliente12.set_Nome(string.Concat("ESTIPULANTE - ", estipulante.get_Nome())); + this.SelectedCliente = cliente12; + this.Titulo = string.Concat("ANEXO DO ESTIPULANTE ", estipulante.get_Nome()); + break; + } + default: + { + this.SelectedCliente = (Cliente)this.Filtro.get_Parente(); + this.Titulo = string.Concat("ARQUIVO DIGITAL DO CLIENTE \"", this.SelectedCliente.get_Nome(), "\""); + break; + } + } + indiceArquivoDigitals = null; + } + if (this.Filtro != null) + { + tipo = this.Filtro.get_Tipo(); + switch (tipo) + { + case 1: + case 2: + case 3: + case 4: + case 5: + { + cliente = await this._servico.BuscarClienteAsync(this.SelectedCliente.get_Id()); + this.Telefones = await this._servico.BuscarTelefonesAsync(this.SelectedCliente.get_Id()); + ObservableCollection observableCollection1 = await (new ClienteServico()).BuscarEmailsAsync(this.SelectedCliente.get_Id()); + if (this.SelectedCliente.get_Documento() == null || Gestor.Common.Validation.ValidationHelper.OnlyNumber(this.SelectedCliente.get_Documento()).Length <= 11) + { + ArquivoDigitalViewModel arquivoDigitalViewModel2 = this; + ClienteEmail clienteEmail = observableCollection1.FirstOrDefault(); + if (clienteEmail != null) + { + email = clienteEmail.get_Email(); + } + else + { + email = null; + } + arquivoDigitalViewModel2.Email = email; + this.Nome = this.SelectedCliente.get_Nome(); + this.Documento = this.SelectedCliente.get_Documento(); + goto case 8; + } + else + { + ArquivoDigitalViewModel arquivoDigitalViewModel3 = this; + Cliente cliente13 = cliente; + if (cliente13 != null) + { + ResponsavelAssinatura responsavelAssinatura = cliente13.get_ResponsavelAssinatura(); + if (responsavelAssinatura != null) + { + emailResponsavel = responsavelAssinatura.get_EmailResponsavel(); + } + else + { + emailResponsavel = null; + } + } + else + { + emailResponsavel = null; + } + if (emailResponsavel == null) + { + ClienteEmail clienteEmail1 = observableCollection1.FirstOrDefault(); + if (clienteEmail1 != null) + { + emailResponsavel = clienteEmail1.get_Email(); + } + else + { + emailResponsavel = null; + } + } + arquivoDigitalViewModel3.Email = (string)emailResponsavel; + ArquivoDigitalViewModel arquivoDigitalViewModel4 = this; + Cliente cliente14 = cliente; + if (cliente14 != null) + { + ResponsavelAssinatura responsavelAssinatura1 = cliente14.get_ResponsavelAssinatura(); + if (responsavelAssinatura1 != null) + { + nomeResponsavel = responsavelAssinatura1.get_NomeResponsavel(); + } + else + { + nomeResponsavel = null; + } + } + else + { + nomeResponsavel = null; + } + if (nomeResponsavel == null) + { + nomeResponsavel = this.SelectedCliente.get_Nome(); + } + arquivoDigitalViewModel4.Nome = (string)nomeResponsavel; + ArquivoDigitalViewModel arquivoDigitalViewModel5 = this; + Cliente cliente15 = cliente; + if (cliente15 != null) + { + ResponsavelAssinatura responsavelAssinatura2 = cliente15.get_ResponsavelAssinatura(); + if (responsavelAssinatura2 != null) + { + documentoResponsavel = responsavelAssinatura2.get_DocumentoResponsavel(); + } + else + { + documentoResponsavel = null; + } + } + else + { + documentoResponsavel = null; + } + if (documentoResponsavel == null) + { + documentoResponsavel = this.SelectedCliente.get_Documento(); + } + arquivoDigitalViewModel5.Documento = (string)documentoResponsavel; + goto case 8; + } + } + case 6: + case 7: + case 8: + { + cliente = null; + break; + } + case 9: + { + Lancamento parente1 = (Lancamento)this.Filtro.get_Parente(); + ObservableCollection observableCollection2 = new ObservableCollection(); + ClienteTelefone clienteTelefone = new ClienteTelefone(); + clienteTelefone.set_Prefixo(parente1.get_Controle().get_Fornecedor().get_Prefixo1()); + clienteTelefone.set_Numero(parente1.get_Controle().get_Fornecedor().get_Telefone1()); + observableCollection2.Add(clienteTelefone); + ClienteTelefone clienteTelefone1 = new ClienteTelefone(); + clienteTelefone1.set_Prefixo(parente1.get_Controle().get_Fornecedor().get_Prefixo2()); + clienteTelefone1.set_Numero(parente1.get_Controle().get_Fornecedor().get_Telefone2()); + observableCollection2.Add(clienteTelefone1); + this.Telefones = observableCollection2; + goto case 8; + } + case 10: + { + Fornecedor fornecedor1 = (Fornecedor)this.Filtro.get_Parente(); + ObservableCollection observableCollection3 = new ObservableCollection(); + ClienteTelefone clienteTelefone2 = new ClienteTelefone(); + clienteTelefone2.set_Prefixo(fornecedor1.get_Prefixo1()); + clienteTelefone2.set_Numero(fornecedor1.get_Telefone1()); + observableCollection3.Add(clienteTelefone2); + ClienteTelefone clienteTelefone3 = new ClienteTelefone(); + clienteTelefone3.set_Prefixo(fornecedor1.get_Prefixo2()); + clienteTelefone3.set_Numero(fornecedor1.get_Telefone2()); + observableCollection3.Add(clienteTelefone3); + this.Telefones = observableCollection3; + goto case 8; + } + default: + { + if (tipo == 17) + { + Estipulante estipulante1 = (Estipulante)this.Filtro.get_Parente(); + ObservableCollection observableCollection4 = new ObservableCollection(); + ClienteTelefone clienteTelefone4 = new ClienteTelefone(); + clienteTelefone4.set_Prefixo(estipulante1.get_PrimeiroPrefixo()); + clienteTelefone4.set_Numero(estipulante1.get_PrimeiroTelefone()); + observableCollection4.Add(clienteTelefone4); + ClienteTelefone clienteTelefone5 = new ClienteTelefone(); + clienteTelefone5.set_Prefixo(estipulante1.get_SegundoPrefixo()); + clienteTelefone5.set_Numero(estipulante1.get_SegundoTelefone()); + observableCollection4.Add(clienteTelefone5); + this.Telefones = observableCollection4; + goto case 8; + } + else + { + goto case 8; + } + } + } + } + base.IsVisible = Visibility.Visible; + this.Carregando = false; + } + } + + public async void CarregarArquivos() + { + await base.PermissaoTela(6); + await base.PermissaoArquivoDigital(this.Filtro.get_Tipo()); + await this.CarregaArquivos(); + string str = "PRODUTO NÃO CONTRATADO"; + List produtos = LicenseHelper.Produtos; + if (produtos.Any((Licenca x) => x.get_Produto() == 86)) + { + this._assinadorKey = await AssinadorHelper.Key(); + int num = await AssinadorHelper.Licencas(this._assinadorKey); + str = string.Format("{0} LICENÇAS DISPONÍVEIS", num); + } + this.Licencas = str; + base.VerificarEnables(new long?((long)0)); + } + + public string CarregarMensagem() + { + Gestor.Model.Domain.Seguros.Documento parente; + Item item; + string str; + string str1; + this.AtualizaEmpresa(); + if (Recursos.Empresa.get_TipoTelefone1() == 11) + { + str1 = "0300"; + } + else + { + str1 = (Recursos.Empresa.get_TipoTelefone1() == 10 ? "0800" : ""); + } + string str2 = str1; + str2 = string.Concat(new string[] { str2, " ", Recursos.Empresa.get_PrimeiroPrefixo(), " ", Recursos.Empresa.get_PrimeiroTelefone() }); + TipoArquivoDigital tipo = this.Filtro.get_Tipo(); + switch (tipo) + { + case 1: + { + return string.Concat(new string[] { "Prezado(a) ", Gestor.Common.Validation.ValidationHelper.Captalize(this.SelectedCliente.get_Nome()), ", segue o(s) link(s) para download referente ao(s) seu(s) arquivo(s). ", Environment.NewLine, Environment.NewLine, "[*LINK*]", Environment.NewLine, Environment.NewLine, "<|LINKASSINATURA|>", Environment.NewLine, Environment.NewLine, "Para mais informações entre contato conosco pelo ", str2, ".", Environment.NewLine, "Atenciosamente ", Gestor.Common.Validation.ValidationHelper.Captalize(Recursos.Empresa.get_Nome()), "." }); + } + case 2: + { + parente = (Gestor.Model.Domain.Seguros.Documento)this.Filtro.get_Parente(); + str = (string.IsNullOrWhiteSpace(parente.get_Apolice()) ? string.Concat("Proposta Número ", parente.get_Proposta()) : string.Concat("Apólice Número ", parente.get_Apolice())); + string[] strArrays = new string[] { "Prezado(a) ", Gestor.Common.Validation.ValidationHelper.Captalize(this.SelectedCliente.get_Nome()), " segue o(s) link(s) para download do(s) arquivo(s) referente ao seu seguro. ", Environment.NewLine, null }; + strArrays[4] = string.Format("{0}, {1}, {2} de Vigências entre {3:d} e {4:d}. {5}{6}[*LINK*]{7}{8}<|LINKASSINATURA|>Para mais informações entre contato conosco pelo {9}.{10}Atenciosamente {11}.", new object[] { Gestor.Common.Validation.ValidationHelper.Captalize(parente.get_Controle().get_Seguradora().get_Nome()), Gestor.Common.Validation.ValidationHelper.Captalize(parente.get_Controle().get_Ramo().get_Nome()), str, parente.get_Vigencia1(), parente.get_Vigencia2(), Environment.NewLine, Environment.NewLine, Environment.NewLine, Environment.NewLine, str2, Environment.NewLine, Gestor.Common.Validation.ValidationHelper.Captalize(Recursos.Empresa.get_Nome()) }); + return string.Concat(strArrays); + } + case 3: + { + Parcela parcela = (Parcela)this.Filtro.get_Parente(); + parente = parcela.get_Documento(); + str = (string.IsNullOrWhiteSpace(parente.get_Apolice()) ? string.Concat("Proposta Número ", parente.get_Proposta()) : string.Concat("Apólice Número ", parente.get_Apolice())); + string[] strArrays1 = new string[] { "Prezado(a) ", Gestor.Common.Validation.ValidationHelper.Captalize(this.SelectedCliente.get_Nome()), " segue o(s) link(s) para download do(s) arquivo(s) referente a sua parcela. ", Environment.NewLine, null, null }; + strArrays1[4] = string.Format("Parcela {0} de {1}, valor {2:C2} de vencimento {3:d}. {4}", new object[] { parcela.get_NumeroParcela(), parente.get_NumeroParcelas(), parcela.get_Valor(), parcela.get_Vencimento(), Environment.NewLine }); + strArrays1[5] = string.Format("{0}, {1}, {2} de Vigências entre {3:d} e {4:d}. {5}{6}[*LINK*]{7}{8}<|LINKASSINATURA|>Para mais informações entre contato conosco pelo {9}.{10}Atenciosamente {11}.", new object[] { Gestor.Common.Validation.ValidationHelper.Captalize(parente.get_Controle().get_Seguradora().get_Nome()), Gestor.Common.Validation.ValidationHelper.Captalize(parente.get_Controle().get_Ramo().get_Nome()), str, parente.get_Vigencia1(), parente.get_Vigencia2(), Environment.NewLine, Environment.NewLine, Environment.NewLine, Environment.NewLine, str2, Environment.NewLine, Gestor.Common.Validation.ValidationHelper.Captalize(Recursos.Empresa.get_Nome()) }); + return string.Concat(strArrays1); + } + case 4: + { + item = (Item)this.Filtro.get_Parente(); + parente = item.get_Documento(); + str = (string.IsNullOrWhiteSpace(parente.get_Apolice()) ? string.Concat("Proposta Número ", parente.get_Proposta()) : string.Concat("Apólice Número ", parente.get_Apolice())); + string[] strArrays2 = new string[] { "Prezado(a) ", Gestor.Common.Validation.ValidationHelper.Captalize(this.SelectedCliente.get_Nome()), " segue o(s) link(s) para download do(s) arquivo(s) referente ao seu seguro. ", Environment.NewLine, "Item ", item.get_Descricao(), ". ", Environment.NewLine, null }; + strArrays2[8] = string.Format("{0}, {1}, {2} de Vigências entre {3:d} e {4:d}. {5}{6}[*LINK*]{7}{8}<|LINKASSINATURA|>Para mais informações entre contato conosco pelo {9}.{10}Atenciosamente {11}.", new object[] { Gestor.Common.Validation.ValidationHelper.Captalize(parente.get_Controle().get_Seguradora().get_Nome()), Gestor.Common.Validation.ValidationHelper.Captalize(parente.get_Controle().get_Ramo().get_Nome()), str, parente.get_Vigencia1(), parente.get_Vigencia2(), Environment.NewLine, Environment.NewLine, Environment.NewLine, Environment.NewLine, str2, Environment.NewLine, Gestor.Common.Validation.ValidationHelper.Captalize(Recursos.Empresa.get_Nome()) }); + return string.Concat(strArrays2); + } + case 5: + { + Sinistro sinistro = (Sinistro)this.Filtro.get_Parente(); + item = sinistro.get_ControleSinistro().get_Item(); + parente = item.get_Documento(); + str = (string.IsNullOrWhiteSpace(parente.get_Apolice()) ? string.Concat("Proposta Número ", parente.get_Proposta()) : string.Concat("Apólice Número ", parente.get_Apolice())); + string[] strArrays3 = new string[] { "Prezado(a) ", Gestor.Common.Validation.ValidationHelper.Captalize(this.SelectedCliente.get_Nome()), " segue o(s) link(s) para download do(s) arquivo(s) referente ao seu sinistro. ", Environment.NewLine, "Sinistro de número ", sinistro.get_Numero(), " Item sinistrado ", sinistro.get_ItemSinistrado(), ". ", Environment.NewLine, null }; + strArrays3[10] = string.Format("{0}, {1}, {2} de Vigências entre {3:d} e {4:d}. {5}{6}[*LINK*]{7}{8}<|LINKASSINATURA|>Para mais informações entre contato conosco pelo {9}.{10}Atenciosamente {11}.", new object[] { Gestor.Common.Validation.ValidationHelper.Captalize(parente.get_Controle().get_Seguradora().get_Nome()), Gestor.Common.Validation.ValidationHelper.Captalize(parente.get_Controle().get_Ramo().get_Nome()), str, parente.get_Vigencia1(), parente.get_Vigencia2(), Environment.NewLine, Environment.NewLine, Environment.NewLine, Environment.NewLine, str2, Environment.NewLine, Gestor.Common.Validation.ValidationHelper.Captalize(Recursos.Empresa.get_Nome()) }); + return string.Concat(strArrays3); + } + default: + { + if (tipo == 13) + { + break; + } + else + { + goto Label0; + } + } + } + return string.Concat(new string[] { "Prezado(a) ", Gestor.Common.Validation.ValidationHelper.Captalize(this.SelectedCliente.get_Nome()), ", segue o(s) link(s) para download referente ao(s) seu(s) arquivo(s). ", Environment.NewLine, Environment.NewLine, "[*LINK*]", Environment.NewLine, Environment.NewLine, "<|LINKASSINATURA|>", Environment.NewLine, Environment.NewLine, "Para mais informações entre contato conosco pelo ", str2, ".", Environment.NewLine, "Atenciosamente ", Gestor.Common.Validation.ValidationHelper.Captalize(Recursos.Empresa.get_Nome()), "." }); + Label0: + return string.Concat(new string[] { "Prezado(a), segue o(s) link(s) para download referente ao(s) seu(s) arquivo(s).", Environment.NewLine, Environment.NewLine, "[*LINK*]", Environment.NewLine, Environment.NewLine, " Para mais informações entre contato conosco pelo ", str2, ".", Environment.NewLine, "Atenciosamente ", Gestor.Common.Validation.ValidationHelper.Captalize(Recursos.Empresa.get_Nome()), "." }); + } + + public async Task CreateLink(IndiceArquivoDigital indice) + { + DateTime networkTime = Funcoes.GetNetworkTime(); + string str = string.Format("{0}:{1}:F:{2}", networkTime.Ticks, ApplicationHelper.IdFornecedor, indice.get_Id()).Base64Encode(); + return Recursos.ApiArquivo.AddQuery("search", str); + } + + public void Delete(Gestor.Model.Domain.Common.ArquivoDigital arquivo) + { + if (this.SelectedAnexado == null) + { + return; + } + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital = this.ArquivosAnexados.First((Gestor.Model.Domain.Common.ArquivoDigital x) => x.get_Descricao() == arquivo.get_Descricao()); + this.ArquivosAnexados.Remove(arquivoDigital); + this.ArquivosAnexados = new ObservableCollection(this.ArquivosAnexados); + } + + public async void Editar(IndiceArquivoDigital arquivo) + { + if (arquivo != null && arquivo.get_IdArquivoDigital() != 0) + { + await this.ArquivoDigitalServico.Save(arquivo); + } + } + + public async Task EnviarParaAssinatura() + { + bool flag; + object obj; + ObservableCollection arquivosTela = this.ArquivosTela; + if (!arquivosTela.Any((IndiceArquivoDigital x) => x.get_Assinar())) + { + await base.ShowMessage("É NECESSÁRIO SELECIONAR AO MENOS UM ARQUIVO PARA ENVIAR PARA ASSINATURA.", "OK", "", false); + flag = false; + } + else if (!await base.ShowMessage("DESEJA ENVIAR OS ARQUIVOS SELECIONADOS PARA ASSINATURA ELETRÔNICA DO SEGURADO?", "SIM", "NÃO", false)) + { + flag = false; + } + else if (!this.Email.EndsWith(";")) + { + base.Loading(true); + this._assinadorKey = await AssinadorHelper.Key(); + int num = await AssinadorHelper.Licencas(this._assinadorKey); + int num1 = num; + ObservableCollection arquivos = this.Arquivos; + if (num1 >= arquivos.Count((IndiceArquivoDigital x) => { + if (!x.get_Assinar()) + { + return false; + } + return !x.get_EnviadoAssinatura(); + })) + { + AssinadorHelper.Parametros = await AssinaturaServico.BuscarParametrosAssinatura(Recursos.Usuario.get_IdEmpresa()); + int num2 = 0; + ObservableCollection observableCollection = this.ArquivosTela; + int num3 = ( + from x in observableCollection + where x.get_Assinar() + select x).Count(); + ObservableCollection arquivosTela1 = this.ArquivosTela; + foreach (IndiceArquivoDigital indiceArquivoDigital in + from x in arquivosTela1 + where x.get_Assinar() + select x) + { + if (indiceArquivoDigital.get_Assinado()) + { + continue; + } + if (!indiceArquivoDigital.get_EnviadoAssinatura()) + { + ArquivoParaAssinaturaAssinador arquivoParaAssinaturaAssinador = await this.Assinar(indiceArquivoDigital, false); + if (arquivoParaAssinaturaAssinador == null) + { + continue; + } + num--; + indiceArquivoDigital.set_EnviadoAssinatura(true); + indiceArquivoDigital.set_UrlAssinatura(arquivoParaAssinaturaAssinador.get_UrlAssinatura()); + num2++; + indiceArquivoDigital = null; + } + else + { + await (new AssinaturaServico()).Reenviar(indiceArquivoDigital.get_Id()); + } + } + base.Loading(false); + this.Arquivos = new ObservableCollection(this.Arquivos); + await base.ShowMessage(string.Format("{0} DE {1} ARQUIVOS FORAM ENVIADOS PARA ASSINATURA. VOCÊ SERÁ NOTIFICADO QUANDO OS DOCUMENTOS FOREM ASSINADOS", num2, num3), "OK", "", false); + flag = true; + } + else if (base.Restricao(113)) + { + await base.ShowMessage("VOCÊ NÃO POSSUI MAIS LICENÇAS DISPONÍVEIS E O USUÁRIO NÃO PODE CONTRATAR, ENTRE EM CONTATO COM O ADMINISTRADOR DO SISTEMA.", "OK", "", false); + base.Loading(false); + flag = false; + } + else if (await base.ShowMessage("VOCÊ NÃO POSSUI MAIS LICENÇAS DISPONÍVEIS, DESEJA CONTRATAR MAIS?", "SIM", "NÃO", false)) + { + Token token = new Token(); + object[] numeroSerial = new object[] { ApplicationHelper.NumeroSerial, ApplicationHelper.IdFornecedor, Recursos.Usuario.get_Id(), null }; + obj = (ApplicationHelper.Beta ? "1" : "0"); + numeroSerial[3] = obj; + string str = token.Encrypt(string.Format("{0}:{1}:{2}:{3}", numeroSerial)); + Parameters parameter = new Parameters(); + parameter.set_Beta(ApplicationHelper.Beta); + parameter.set_Type(8); + parameter.set_Application("Assinador.Application.exe"); + parameter.set_Directory("Assinador.Application"); + parameter.set_Arguments(str); + parameter.set_Run(true); + (new DownloadWindow(parameter)).Show(); + base.Loading(false); + flag = false; + } + else + { + base.Loading(false); + flag = false; + } + } + else + { + await base.ShowMessage("É NECESSÁRIO QUE O ASSINANTE POSSUA UM E-MAIL VÁLIDO", "OK", "", false); + flag = false; + } + return flag; + } + + public async Task Excluir(IndiceArquivoDigital arquivo) + { + if (arquivo != null && arquivo.get_IdArquivoDigital() != 0) + { + if (await this.ArquivoDigitalServico.DeleteAttachment(arquivo)) + { + await this.CarregaArquivos(); + } + } + } + + public void LimparAnexos() + { + this.ArquivosAnexados = new ObservableCollection(); + } + + public async Task PrepararEnvio() + { + MalaDireta malaDiretum; + Item item; + string str; + Item item1; + string str1; + MalaDireta malaDiretum1; + Gestor.Model.Domain.Seguros.Documento parente; + Parcela parcela; + ObservableCollection arquivos = this.Arquivos; + if (arquivos.Any((IndiceArquivoDigital x) => x.get_Selecionado())) + { + MalaDireta malaDiretum2 = new MalaDireta(); + malaDiretum2.set_Cliente(this.SelectedCliente); + ObservableCollection observableCollection = this.Arquivos; + malaDiretum2.set_ArquivoDigital(( + from x in observableCollection + where x.get_Selecionado() + select x).ToList()); + malaDiretum1 = malaDiretum2; + TipoArquivoDigital tipo = this.Filtro.get_Tipo(); + switch (tipo) + { + case 2: + { + parente = (Gestor.Model.Domain.Seguros.Documento)this.Filtro.get_Parente(); + List items = await base.CarregarItem(parente.get_Controle().get_Id(), 0); + MalaDireta malaDiretum3 = malaDiretum1; + if (items.Count > 1) + { + item = new Item(); + item.set_Id((long)0); + item.set_Descricao("APÓLICE COLETIVA"); + } + else + { + item = items.FirstOrDefault(); + } + malaDiretum3.set_Item(item); + malaDiretum1.set_Apolice(parente); + ArquivoDigitalViewModel arquivoDigitalViewModel = this; + str = (parente.get_Apolice() != string.Empty ? string.Concat("DOCUMENTOS REFERENTES A APÓLICE ", parente.get_Apolice()) : string.Concat("DOCUMENTOS REFERENTES A PROPOSTA ", parente.get_Proposta())); + arquivoDigitalViewModel.Assunto = str; + this.Corpo = string.Concat("PREZADO CLIENTE ", this.SelectedCliente.get_Nome(), ", EM ANEXO OS DOCUMENTOS REFERENTES AO SEU SEGURO."); + malaDiretum1.set_Tela(2); + break; + } + case 3: + { + parcela = (Parcela)this.Filtro.get_Parente(); + malaDiretum1.set_Apolice(parcela.get_Documento()); + malaDiretum1.set_Parcela(parcela); + List items1 = await base.CarregarItem(parcela.get_Documento().get_Controle().get_Id(), 0); + MalaDireta malaDiretum4 = malaDiretum1; + if (items1.Count > 1) + { + item1 = new Item(); + item1.set_Id((long)0); + item1.set_Descricao("APÓLICE COLETIVA"); + } + else + { + item1 = items1.FirstOrDefault(); + } + malaDiretum4.set_Item(item1); + ArquivoDigitalViewModel arquivoDigitalViewModel1 = this; + str1 = (parcela.get_Documento().get_Apolice() != string.Empty ? string.Format("DOCUMENTOS REFERENTE A PARCELA {0} DA APÓLICE {1}", parcela.get_NumeroParcela(), parcela.get_Documento().get_Apolice()) : string.Format("DOCUMENTOS REFERENTE A PARCELA {0} DA PROPOSTA {1}", parcela.get_NumeroParcela(), parcela.get_Documento().get_Proposta())); + arquivoDigitalViewModel1.Assunto = str1; + this.Corpo = string.Concat("PREZADO CLIENTE ", this.SelectedCliente.get_Nome(), ", EM ANEXO OS DOCUMENTOS REFERENTES AS PARCELAS DE SEU SEGURO."); + malaDiretum1.set_Tela(5); + break; + } + case 4: + { + Item parente1 = (Item)this.Filtro.get_Parente(); + malaDiretum1.set_Apolice(parente1.get_Documento()); + malaDiretum1.set_Item(parente1); + this.Assunto = string.Concat("DOCUMENTOS REFERENTES AO ITEM ", parente1.get_Descricao()); + this.Corpo = string.Concat("PREZADO CLIENTE ", this.SelectedCliente.get_Nome(), ", EM ANEXO OS DOCUMENTOS REFERENTES AO SEU BEM."); + malaDiretum1.set_Tela(3); + break; + } + case 5: + { + Sinistro sinistro = (Sinistro)this.Filtro.get_Parente(); + malaDiretum1.set_Sinistro(sinistro); + malaDiretum1.set_Item(sinistro.get_ControleSinistro().get_Item()); + malaDiretum1.set_Apolice(sinistro.get_ControleSinistro().get_Item().get_Documento()); + this.Titulo = string.Concat("DOCUMENTOS REFERENTES AO SINITRO ", sinistro.get_Numero()); + string[] nome = new string[] { "PREZADO CLIENTE ", this.SelectedCliente.get_Nome(), ", EM ANEXO OS DOCUMENTOS REFERENTES SINISTRO DO ITEM ", sinistro.get_ControleSinistro().get_Item().get_Descricao(), "." }; + this.Corpo = string.Concat(nome); + malaDiretum1.set_Tela(7); + break; + } + default: + { + if (tipo == 11) + { + Prospeccao prospeccao = (Prospeccao)this.Filtro.get_Parente(); + malaDiretum1.set_Prospeccao(prospeccao); + malaDiretum1.get_Cliente().set_Id((long)0); + this.Assunto = string.Concat("DOCUMENTOS REFERENTES PROSPECÇÃO ", prospeccao.get_Nome()); + this.Corpo = ""; + malaDiretum1.set_Tela(33); + break; + } + else + { + this.SelectedCliente = (Cliente)this.Filtro.get_Parente(); + this.Titulo = string.Concat("ARQUIVO DIGITAL DO CLIENTE \"", this.SelectedCliente.get_Nome(), "\""); + break; + } + } + } + parente = null; + parcela = null; + malaDiretum = malaDiretum1; + } + else + { + await base.ShowMessage("É NECESSÁRIO SELECIONAR AO MENOS UM ARQUIVO PARA ENVIO.", "OK", "", false); + malaDiretum = null; + } + malaDiretum1 = null; + return malaDiretum; + } + + public async Task SalvarAnexos() + { + if (this.ArquivosAnexados != null && this.ArquivosAnexados.Count != 0) + { + this.Carregando = true; + List list = this.ArquivosAnexados.ToList(); + if (await base.SalvarAttachments(list, this.Filtro.get_Tipo(), this.Filtro.get_Id())) + { + await this.CarregaArquivos(); + this.ArquivosAnexados = new ObservableCollection(); + this.Carregando = false; + } + else + { + this.Carregando = false; + } + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/ExpedicaoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/ExpedicaoViewModel.cs new file mode 100644 index 0000000..2aff10f --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/ExpedicaoViewModel.cs @@ -0,0 +1,196 @@ +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class ExpedicaoViewModel : BaseSegurosViewModel + { + private readonly ExpedicaoServico _servico; + + private readonly Documento _documento; + + private bool _carregando; + + private Expedicao _selectedExpedicao = new Expedicao(); + + private ObservableCollection _expedicoes = new ObservableCollection(); + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.EnableMenu = !value; + base.OnPropertyChanged("Carregando"); + } + } + + public ObservableCollection Expedicoes + { + get + { + return this._expedicoes; + } + set + { + this._expedicoes = value; + base.OnPropertyChanged("Expedicoes"); + } + } + + public Expedicao SelectedExpedicao + { + get + { + return this._selectedExpedicao; + } + set + { + long? nullable; + this._selectedExpedicao = value; + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedExpedicao"); + } + } + + public ExpedicaoViewModel(Documento documento) + { + this._servico = new ExpedicaoServico(); + this._documento = documento; + this.Seleciona(documento); + } + + public async void CancelarAlteracao() + { + Expedicao expedicao; + this.Carregando = true; + long id = this.SelectedExpedicao.get_Id(); + await this.Carregar(this.SelectedExpedicao.get_Apolice()); + ExpedicaoViewModel expedicaoViewModel = this; + if (this.Expedicoes.Count <= 0 || id <= (long)0) + { + expedicao = (this.Expedicoes.Count <= 0 || id != 0 ? new Expedicao() : this.Expedicoes.First()); + } + else + { + expedicao = this.Expedicoes.FirstOrDefault((Expedicao x) => x.get_Id() == id); + } + expedicaoViewModel.SelectedExpedicao = expedicao; + base.Alterar(false); + this.Carregando = false; + } + + private async Task Carregar(Documento documento) + { + this.Expedicoes = new ObservableCollection(await this._servico.BuscarExpedicoes(documento)); + } + + public async Task Excluir() + { + bool flag; + Expedicao expedicao; + if (this.SelectedExpedicao == null || this.SelectedExpedicao.get_Id() == 0) + { + flag = false; + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + this.Carregando = true; + if (await this._servico.Delete(this.SelectedExpedicao)) + { + int num = this.Expedicoes.IndexOf(this.SelectedExpedicao); + this.Expedicoes.Remove(this.SelectedExpedicao); + if (this.Expedicoes.Count <= 0) + { + this.SelectedExpedicao = new Expedicao(); + } + else + { + ExpedicaoViewModel expedicaoViewModel = this; + expedicao = (num < this.Expedicoes.Count ? this.Expedicoes.ElementAt(num) : this.Expedicoes.Last()); + expedicaoViewModel.SelectedExpedicao = expedicao; + } + this.Carregando = false; + flag = true; + } + else + { + this.Carregando = false; + flag = false; + } + } + else + { + flag = false; + } + return flag; + } + + public void Incluir() + { + Expedicao expedicao = new Expedicao(); + expedicao.set_Apolice(this._documento); + this.SelectedExpedicao = expedicao; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + this.SelectedExpedicao = await this._servico.Save(this.SelectedExpedicao); + if (this._servico.Sucesso) + { + long id = this.SelectedExpedicao.get_Id(); + await this.Carregar(this.SelectedExpedicao.get_Apolice()); + this.SelectedExpedicao = this.Expedicoes.FirstOrDefault((Expedicao x) => x.get_Id() == id); + base.Alterar(false); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + return keyValuePairs; + } + + private async void Seleciona(Documento documento) + { + this.Carregando = true; + await base.PermissaoTela(46); + await this.Carregar(documento); + if (this.Expedicoes.Count <= 0) + { + this.SelectedExpedicao = new Expedicao(); + base.Alterar(false); + base.EnableMenu = false; + } + else + { + this.SelectedExpedicao = this.Expedicoes.First(); + } + this.Carregando = false; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/ExtratosViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/ExtratosViewModel.cs new file mode 100644 index 0000000..f07bd68 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/ExtratosViewModel.cs @@ -0,0 +1,5516 @@ +using Gestor.Application.Componentes; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios.ClientesAtivosInativos; +using Gestor.Model.Domain.Seguros; +using NReco.PdfGenerator; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class ExtratosViewModel : BaseSegurosViewModel + { + private readonly ClienteServico _clienteServico = new ClienteServico(); + + private List _documentos; + + private List _prospeccoes; + + private List _clientes; + + private bool _tipoExtratoEnabled = true; + + private bool _extratoResumido; + + private bool _segurosVigentes; + + private Visibility _clientePorPaginaVisibility; + + private bool _clientePorPagina; + + private bool _extratoPorPagina; + + private bool _clientePorPaginaEnabled = true; + + private bool _obsCliente; + + private bool _comissaoDocumento; + + private bool _premioParcela; + + private bool _obsApolice; + + private bool _beneficiariosItens; + + private bool _selecionarItens; + + private bool _endossos; + + private bool _somenteEndosso; + + private Visibility _selecionarItensVisibility; + + private Visibility _endossoVisibility; + + private Visibility _obsDocVisibility; + + private Visibility _segurosVigentesVisibility; + + private bool _obsItem; + + private bool _separarPagina; + + private bool _perfilCondutor; + + private bool _obsClienteEnabled = true; + + private bool _comissaoDocumentoEnabled; + + private bool _obsApoliceEnabled; + + private bool _beneficiariosItensEnabled; + + private bool _obsItemEnabled; + + private bool _separarPaginaEnabled; + + private bool _coberturasEnabled; + + private bool _coberturas; + + private bool _perfilCondutorEnabled; + + private bool _endossoEnabled; + + private bool _esconderResumido; + + private bool _clienteVisibility; + + private bool _documentoVisibility; + + private bool _itemVisibility; + + private bool _perfilVisibility; + + private TipoExtrato _selectedTipoExtrato; + + private bool _carregando; + + private List _itensSelecionados; + + internal Relatorio? TipoDeRelatorio; + + public bool BeneficiariosItens + { + get + { + return this._beneficiariosItens; + } + set + { + this._beneficiariosItens = value; + base.OnPropertyChanged("BeneficiariosItens"); + } + } + + public bool BeneficiariosItensEnabled + { + get + { + return this._beneficiariosItensEnabled; + } + set + { + this._beneficiariosItensEnabled = value; + base.OnPropertyChanged("BeneficiariosItensEnabled"); + } + } + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.IsEnabled = !value; + base.EnableMenu = !value; + base.OnPropertyChanged("Carregando"); + } + } + + public bool ClientePorPagina + { + get + { + return this._clientePorPagina; + } + set + { + this._clientePorPagina = value; + base.OnPropertyChanged("ClientePorPagina"); + } + } + + public bool ClientePorPaginaEnabled + { + get + { + return this._clientePorPaginaEnabled; + } + set + { + this._clientePorPaginaEnabled = value; + base.OnPropertyChanged("ClientePorPaginaEnabled"); + } + } + + public Visibility ClientePorPaginaVisibility + { + get + { + return this._clientePorPaginaVisibility; + } + set + { + this._clientePorPaginaVisibility = value; + base.OnPropertyChanged("ClientePorPaginaVisibility"); + } + } + + public List Clientes + { + get + { + return this._clientes; + } + set + { + this._clientes = value; + base.OnPropertyChanged("Clientes"); + } + } + + public bool ClienteVisibility + { + get + { + return this._clienteVisibility; + } + set + { + this._clienteVisibility = value; + base.OnPropertyChanged("ClienteVisibility"); + } + } + + public bool Coberturas + { + get + { + return this._coberturas; + } + set + { + this._coberturas = value; + base.OnPropertyChanged("Coberturas"); + } + } + + public bool CoberturasEnabled + { + get + { + return this._coberturasEnabled; + } + set + { + this._coberturasEnabled = value; + base.OnPropertyChanged("CoberturasEnabled"); + } + } + + public bool ComissaoDocumento + { + get + { + return this._comissaoDocumento; + } + set + { + this._comissaoDocumento = value; + base.OnPropertyChanged("ComissaoDocumento"); + } + } + + public bool ComissaoDocumentoEnabled + { + get + { + return this._comissaoDocumentoEnabled; + } + set + { + this._comissaoDocumentoEnabled = value; + base.OnPropertyChanged("ComissaoDocumentoEnabled"); + } + } + + public List Documentos + { + get + { + return this._documentos; + } + set + { + this._documentos = value; + base.OnPropertyChanged("Documentos"); + } + } + + public bool DocumentoVisibility + { + get + { + return this._documentoVisibility; + } + set + { + this._documentoVisibility = value; + base.OnPropertyChanged("DocumentoVisibility"); + } + } + + public bool EndossoEnabled + { + get + { + return this._endossoEnabled; + } + set + { + this._endossoEnabled = value; + base.OnPropertyChanged("EndossoEnabled"); + } + } + + public bool Endossos + { + get + { + return this._endossos; + } + set + { + this._endossos = value; + if (this.SomenteEndossos != !value) + { + this.SomenteEndossos = !value; + } + base.OnPropertyChanged("Endossos"); + } + } + + public Visibility EndossoVisibility + { + get + { + return this._endossoVisibility; + } + set + { + this._endossoVisibility = value; + base.OnPropertyChanged("EndossoVisibility"); + } + } + + public bool EsconderResumido + { + get + { + return this._esconderResumido; + } + set + { + this._esconderResumido = value; + base.OnPropertyChanged("EsconderResumido"); + } + } + + public bool ExtratoPorPagina + { + get + { + return this._extratoPorPagina; + } + set + { + this._extratoPorPagina = value; + base.OnPropertyChanged("ExtratoPorPagina"); + } + } + + public bool ExtratoResumido + { + get + { + return this._extratoResumido; + } + set + { + this._extratoResumido = value; + if (!value) + { + this.ClienteVisibility = true; + this.DocumentoVisibility = true; + this.ItemVisibility = true; + this.AjustaTipoSelecionado(this.SelectedTipoExtrato); + } + else + { + this.ClienteVisibility = false; + this.DocumentoVisibility = false; + this.ItemVisibility = this.CoberturasEnabled; + this.SelecionarItensVisibility = Visibility.Collapsed; + this.BeneficiariosItensEnabled = false; + this.ObsItemEnabled = false; + this.SepararPaginaEnabled = false; + } + base.OnPropertyChanged("ExtratoResumido"); + } + } + + public bool ItemVisibility + { + get + { + return this._itemVisibility; + } + set + { + this._itemVisibility = value; + base.OnPropertyChanged("ItemVisibility"); + } + } + + public bool ObsApolice + { + get + { + return this._obsApolice; + } + set + { + this._obsApolice = value; + base.OnPropertyChanged("ObsApolice"); + } + } + + public bool ObsApoliceEnabled + { + get + { + return this._obsApoliceEnabled; + } + set + { + this._obsApoliceEnabled = value; + base.OnPropertyChanged("ObsApoliceEnabled"); + } + } + + public bool ObsCliente + { + get + { + return this._obsCliente; + } + set + { + this._obsCliente = value; + base.OnPropertyChanged("ObsCliente"); + } + } + + public bool ObsClienteEnabled + { + get + { + return this._obsClienteEnabled; + } + set + { + this._obsClienteEnabled = value; + base.OnPropertyChanged("ObsClienteEnabled"); + } + } + + public Visibility ObsDocVisibility + { + get + { + return this._obsDocVisibility; + } + set + { + this._obsDocVisibility = value; + base.OnPropertyChanged("ObsDocVisibility"); + } + } + + public bool ObsItem + { + get + { + return this._obsItem; + } + set + { + this._obsItem = value; + base.OnPropertyChanged("ObsItem"); + } + } + + public bool ObsItemEnabled + { + get + { + return this._obsItemEnabled; + } + set + { + this._obsItemEnabled = value; + base.OnPropertyChanged("ObsItemEnabled"); + } + } + + public bool PerfilCondutor + { + get + { + return this._perfilCondutor; + } + set + { + this._perfilCondutor = value; + base.OnPropertyChanged("PerfilCondutor"); + } + } + + public bool PerfilCondutorEnabled + { + get + { + return this._perfilCondutorEnabled; + } + set + { + this._perfilCondutorEnabled = value; + base.OnPropertyChanged("PerfilCondutorEnabled"); + } + } + + public bool PerfilVisibility + { + get + { + return this._perfilVisibility; + } + set + { + this._perfilVisibility = value; + base.OnPropertyChanged("PerfilVisibility"); + } + } + + public bool PremioParcela + { + get + { + return this._premioParcela; + } + set + { + this._premioParcela = value; + base.OnPropertyChanged("PremioParcela"); + } + } + + public List Prospeccoes + { + get + { + return this._prospeccoes; + } + set + { + this._prospeccoes = value; + base.OnPropertyChanged("Prospeccoes"); + } + } + + public bool SegurosVigentes + { + get + { + return this._segurosVigentes; + } + set + { + this._segurosVigentes = value; + base.OnPropertyChanged("SegurosVigentes"); + } + } + + public Visibility SegurosVigentesVisibility + { + get + { + return this._segurosVigentesVisibility; + } + set + { + this._segurosVigentesVisibility = value; + base.OnPropertyChanged("SegurosVigentesVisibility"); + } + } + + public bool SelecionarItens + { + get + { + return this._selecionarItens; + } + set + { + this._selecionarItens = value; + if (!value) + { + this._itensSelecionados = new List(); + } + base.OnPropertyChanged("SelecionarItens"); + } + } + + public Visibility SelecionarItensVisibility + { + get + { + return this._selecionarItensVisibility; + } + set + { + this._selecionarItensVisibility = value; + base.OnPropertyChanged("SelecionarItensVisibility"); + } + } + + public TipoExtrato SelectedTipoExtrato + { + get + { + return this._selectedTipoExtrato; + } + set + { + this._selectedTipoExtrato = value; + this.AjustaTipoSelecionado(value); + base.OnPropertyChanged("SelectedTipoExtrato"); + } + } + + public bool SepararPagina + { + get + { + return this._separarPagina; + } + set + { + this._separarPagina = value; + base.OnPropertyChanged("SepararPagina"); + } + } + + public bool SepararPaginaEnabled + { + get + { + return this._separarPaginaEnabled; + } + set + { + this._separarPaginaEnabled = value; + base.OnPropertyChanged("SepararPaginaEnabled"); + } + } + + public bool SomenteEndossos + { + get + { + return this._somenteEndosso; + } + set + { + this._somenteEndosso = value; + if (this.Endossos != !value) + { + this.Endossos = !value; + } + base.OnPropertyChanged("SomenteEndossos"); + } + } + + public bool TipoExtratoEnabled + { + get + { + return this._tipoExtratoEnabled; + } + set + { + this._tipoExtratoEnabled = value; + base.OnPropertyChanged("TipoExtratoEnabled"); + } + } + + public ExtratosViewModel() + { + } + + public void AjustaTipoSelecionado(TipoExtrato tipoExtrato) + { + switch (tipoExtrato) + { + case 0: + { + this.ClienteVisibility = true; + this.ClientePorPaginaVisibility = Visibility.Hidden; + this.DocumentoVisibility = false; + this.ItemVisibility = false; + this.PerfilVisibility = false; + this.EsconderResumido = true; + this.SelecionarItensVisibility = Visibility.Collapsed; + this.SegurosVigentesVisibility = Visibility.Collapsed; + this.SegurosVigentes = false; + this.EndossoVisibility = Visibility.Collapsed; + this.ObsDocVisibility = Visibility.Collapsed; + this.ExtratoCliente(); + return; + } + case 1: + { + this.ClienteVisibility = true; + this.ClientePorPaginaVisibility = Visibility.Visible; + this.DocumentoVisibility = true; + this.ItemVisibility = true; + this.PerfilVisibility = true; + this.EsconderResumido = false; + this.SelecionarItensVisibility = (!this.TipoDeRelatorio.HasValue ? Visibility.Visible : Visibility.Collapsed); + this.SegurosVigentesVisibility = Visibility.Collapsed; + this.SegurosVigentes = false; + this.EndossoVisibility = Visibility.Visible; + this.ObsDocVisibility = Visibility.Visible; + this.ApoliceSelecionada(); + return; + } + case 2: + { + this.ClienteVisibility = false; + this.ClientePorPaginaVisibility = Visibility.Collapsed; + this.DocumentoVisibility = true; + this.ItemVisibility = false; + this.PerfilVisibility = true; + this.EsconderResumido = false; + this.SelecionarItensVisibility = Visibility.Collapsed; + this.SegurosVigentesVisibility = Visibility.Visible; + this.EndossoVisibility = Visibility.Collapsed; + this.ObsDocVisibility = Visibility.Collapsed; + this.RelacaoApolices(); + return; + } + default: + { + return; + } + } + } + + private void ApoliceSelecionada() + { + this.SetAllFalse(); + this.ObsClienteEnabled = true; + this.ClientePorPaginaEnabled = true; + this.ComissaoDocumentoEnabled = true; + this.ObsApoliceEnabled = true; + this.BeneficiariosItensEnabled = true; + this.ObsItemEnabled = true; + this.SepararPaginaEnabled = true; + this.PerfilCondutorEnabled = true; + this.EndossoEnabled = true; + this.CoberturasEnabled = true; + } + + private void ExtratoCliente() + { + this.SetAllFalse(); + this.ObsClienteEnabled = true; + } + + public async Task Gerar(Relatorio? tipoRelatorio = null, bool pdf = false) + { + DateTime date; + List items; + int numeroParcela; + DateTime? clienteDesde; + EstadoCivil? estadoCivil; + Sexo? sexo; + TipoTelefone? nullable; + TipoTelefone tipoTelefone; + decimal premioLiquido; + List controleSinistros; + long id; + Patrimonial patrimonial; + Auto auto; + TipoCobertura? tipoCobertura; + int? bonus; + TabelaReferencia? tabelaReferencia; + Vida vida; + RiscosDiversos riscosDiverso; + Aeronautico aeronautico; + Granizo granizo; + string str14; + string str15; + string str16; + string str17; + string str18; + string str19; + string str20; + string str21; + string str22; + string shortDateString; + string str23; + string str24; + string shortDateString1; + string str25; + string str26; + string str27; + string str28; + string str29; + string str30; + string str31; + string str32; + string shortDateString2; + string str33; + string str34; + string str35; + string str36; + string str37; + string str38; + string str39; + string str40; + string str41; + string str42; + string str43; + string str44; + string str45; + string str46; + string str47; + string str48; + string shortDateString3; + string str49; + string str50; + string str51; + string str52; + string str53; + string endosso; + string str54; + string str55; + string str56; + string str57; + string str58; + string str59; + string str60; + string str61; + string str62; + string str63; + string str64; + string str65; + string str66; + string str67; + string str68; + string str69; + string str70; + string str71; + string str72; + string shortDateString4; + string str73; + string shortDateString5; + string str74; + string str75; + string str76; + string str77; + string str78; + string str79; + string str80; + string str81; + string str82; + string str83; + string str84; + string str85; + string str86; + string str87; + string str88; + string str89; + string str90; + string description; + string str91; + string str92; + string str93; + string str94; + string description1; + string str95; + string str96; + string str97; + string str98; + string str99; + string str100; + string str101; + string str102; + string str103; + string str104; + string str105; + string str106; + DateTime? dataReclamacao; + string shortDateString6; + string str107; + string description2; + string str108; + string str109; + string currency; + string str110; + string str111; + string descricao; + string str112; + string str113; + string str114; + string str115; + string str116; + string str117; + string str118; + string shortDateString7; + string str119; + string str120; + string str121; + string str122; + string str123; + string str124; + string str125; + string str126; + string str127; + string str128; + string str129; + string str130; + string str131; + string str132; + string str133; + string str134; + string str135; + string str136; + string str137; + string str138; + string str139; + string str140; + string str141; + string str142; + string str143; + string str144; + string str145; + string str146; + string str147; + string str148; + string str149; + string str150; + string str151; + string str152; + string str153; + string str154; + string str155; + string str156; + string str157; + string str158; + string str159; + string str160; + string str161; + string str162; + string str163; + bool count; + string str164; + string str165; + string str166; + string str167; + string str168; + string str169; + string str170; + string str171; + string str172; + string str173; + string str174; + string str175; + NegocioCorretora negocioCorretora; + string str176; + string str177; + string str178; + string str179; + string shortDateString8; + string str180; + string str181; + string str182; + string str183; + string str184; + string str185; + string shortDateString9; + string str186; + string str187; + string str188; + string str189; + string str190; + string str191; + string str192; + string str193; + string str194; + string str195; + string str196; + string str197; + string str198; + string str199; + string str200; + string str201; + string str202; + string str203; + string str204; + string str205; + string str206; + string str207; + string str208; + string str209; + string str210; + string str211; + string str212; + string str213; + string str214; + string str215; + string str216; + string str217; + string str218; + string str219; + string str220; + string str221; + string str222; + string str223; + string str224; + string shortDateString10; + string str225; + string str226; + string str227; + string str228; + string str229; + string shortDateString11; + string str230; + string shortDateString12; + string str231; + string shortDateString13; + string str232; + string str233; + string str234; + string str235; + string str236; + string str237; + string str238; + string str239; + string str240; + string str241; + string str242; + string str243; + Documento documento; + string str244; + string str245; + string str246; + string shortDateString14; + string str247; + string str248; + string str249; + string str250; + string str251; + string endosso1; + string str252; + string str253; + string str254; + string str255; + string str256; + string str257; + string str258; + string str259; + string str260; + string str261; + string str262; + string str263; + string str264; + string str265; + string str266; + string str267; + string str268; + string str269; + string str270; + string str271; + string str272; + string str273; + string str274; + string str275; + string str276; + string str277; + string description3; + string str278; + string str279; + string str280; + string str281; + string description4; + string str282; + string str283; + string str284; + string str285; + string str286; + string str287; + string str288; + string str289; + string str290; + string str291; + DateTime? dataReclamacao1; + string shortDateString15; + string str292; + string str293; + string str294; + string str295; + string descricao1; + string str296; + string str297; + string str298; + string str299; + string str300; + string str301; + string str302; + string shortDateString16; + string str303; + string str304; + string str305; + string str306; + string str307; + string str308; + string str309; + string str310; + string str311; + string str312; + string str313; + string str314; + string str315; + string str316; + string str317; + string str318; + string str319; + string str320; + string str321; + string str322; + string str323; + string str324; + string str325; + string str326; + string str327; + string str328; + string str329; + string str330; + string str331; + NegocioCorretora negocioCorretora1; + string str332; + string str333; + string str334; + string str335; + string str336; + string str337; + string str338; + string str339; + string str340; + string str341; + string str342; + string str343; + string str344; + string str345; + string str346; + string str347; + string str348; + string str349; + string str350; + string str351; + string str352; + string shortDateString17; + string str353; + string str354; + string str355; + string str356; + string str357; + string str358; + string str359; + string str360; + string str361; + string str362; + string str363; + string str364; + string str365; + string str366; + string str367; + string str368; + string str369; + ExtratosViewModel.u003cu003ec__DisplayClass170_0 variable9 = null; + int num10; + List list; + Item item = null; + Item item1; + string str370; + string str371 = ""; + if (this.Clientes != null && this.Documentos == null) + { + str371 = string.Concat(str371, ""); + str367 = (this.ExtratoResumido ? " RESUMIDO" : ""); + str370 = string.Concat("EXTRATO", str367, " DO CLIENTE"); + str371 = string.Concat(str371, str370); + str371 = string.Concat(str371, "
"); + str371 = string.Concat(str371, ""); + long id1 = (long)0; + this.Clientes.ForEach((Cliente x) => { + TipoTelefone? tipo; + TipoTelefone valueOrDefault; + string str; + string str1; + string upper; + string str2; + string str3; + string str4; + string upper1; + string str5; + string str6; + string str7; + string str8; + int num = 0; + if (id1 != x.get_Id()) + { + id1 = x.get_Id(); + str371 = string.Concat(str371, (!this.ClientePorPagina || !this.ClientePorPaginaEnabled ? "" : "
")); + str371 = string.Concat(str371, "

"); + str370 = string.Concat("EXTRATO", (this.ExtratoResumido ? " RESUMIDO" : ""), " DO CLIENTE: ", x.get_Nome()); + str371 = string.Concat(str371, str370, "


"); + string str9 = (x.get_Atividade() == null ? "NASCIMENTO" : "ABERTURA"); + bool pessoaFisica = x.get_PessoaFisica(); + ExtratosViewModel.u003cu003ec__DisplayClass170_0 cSu0024u003cu003e8_locals1 = variable9; + string[] strArrays = new string[] { str371, ""; + cSu0024u003cu003e8_locals1.html = string.Concat(strArrays); + if (!pessoaFisica) + { + num++; + } + else + { + ExtratosViewModel.u003cu003ec__DisplayClass170_0 variable = variable9; + string[] cSu0024u003cu003e8_locals11 = new string[] { str371, ""; + variable.html = string.Concat(cSu0024u003cu003e8_locals11); + } + str371 = string.Concat(str371, ""); + if (x.get_Atividade() != null) + { + ExtratosViewModel.u003cu003ec__DisplayClass170_0 variable1 = variable9; + string[] nome = new string[] { str371, ""; + variable1.html = string.Concat(nome); + if (!pessoaFisica) + { + num++; + } + } + if (this.SelectedTipoExtrato != 2) + { + str371 = string.Concat(str371, ""); + if (pessoaFisica) + { + ExtratosViewModel.u003cu003ec__DisplayClass170_0 cSu0024u003cu003e8_locals12 = variable9; + string[] strArrays1 = new string[] { str371, ""; + cSu0024u003cu003e8_locals12.html = string.Concat(strArrays1); + } + ExtratosViewModel.u003cu003ec__DisplayClass170_0 variable2 = variable9; + string[] strArrays2 = new string[] { str371, ""; + cSu0024u003cu003e8_locals13.html = string.Concat(strArrays3); + } + if (!string.IsNullOrWhiteSpace(x.get_Identidade())) + { + ExtratosViewModel.u003cu003ec__DisplayClass170_0 variable3 = variable9; + string[] cSu0024u003cu003e8_locals14 = new string[] { str371, ""; + variable3.html = string.Concat(cSu0024u003cu003e8_locals14); + } + if (this.SelectedTipoExtrato != 2 && !this.ExtratoResumido) + { + ExtratosViewModel.u003cu003ec__DisplayClass170_0 variable4 = variable9; + string[] strArrays4 = new string[] { str371, ""; + variable4.html = string.Concat(strArrays4); + } + if ((x.get_Telefones() != null || x.get_Emails() != null) && this.SelectedTipoExtrato != 2) + { + str371 = string.Concat(str371, ""); + if (x.get_Telefones() != null) + { + string str10 = ""; + foreach (ClienteTelefone telefone in x.get_Telefones()) + { + string[] prefixo = new string[] { str10, "
", null, null, null, null, null }; + tipo = telefone.get_Tipo(); + if (tipo.HasValue) + { + valueOrDefault = tipo.GetValueOrDefault(); + upper1 = valueOrDefault.ToString().ToUpper(); + } + else + { + upper1 = null; + } + prefixo[2] = upper1; + prefixo[3] = " ("; + prefixo[4] = telefone.get_Prefixo(); + prefixo[5] = ") "; + prefixo[6] = telefone.get_Numero(); + str10 = string.Concat(prefixo); + } + ExtratosViewModel.u003cu003ec__DisplayClass170_0 cSu0024u003cu003e8_locals15 = variable9; + string[] strArrays5 = new string[] { str371, "
"; + cSu0024u003cu003e8_locals15.html = string.Concat(strArrays5); + } + if (x.get_Emails() != null && !this.ExtratoResumido) + { + string str11 = ""; + foreach (ClienteEmail email in x.get_Emails()) + { + str11 = string.Concat(str11, "
", email.get_Email()); + } + ExtratosViewModel.u003cu003ec__DisplayClass170_0 variable5 = variable9; + string[] cSu0024u003cu003e8_locals16 = new string[] { str371, "
"; + variable5.html = string.Concat(cSu0024u003cu003e8_locals16); + } + num++; + str371 = string.Concat(str371, ""); + } + if (x.get_Enderecos() != null && this.SelectedTipoExtrato != 2) + { + string str12 = ""; + foreach (ClienteEndereco endereco in x.get_Enderecos()) + { + string[] bairro = new string[] { str12, "
", endereco.get_Endereco(), ", ", endereco.get_Numero(), ", ", null, null, null, null, null, null, null, null }; + bairro[6] = (string.IsNullOrWhiteSpace(endereco.get_Complemento()) ? "" : string.Concat(endereco.get_Complemento(), ", ")); + bairro[7] = endereco.get_Bairro(); + bairro[8] = " - "; + bairro[9] = endereco.get_Cidade(); + bairro[10] = " - "; + bairro[11] = endereco.get_Estado(); + bairro[12] = " - "; + bairro[13] = endereco.get_Cep(); + str12 = string.Concat(bairro); + } + ExtratosViewModel.u003cu003ec__DisplayClass170_0 variable6 = variable9; + string[] strArrays6 = new string[] { str371, "
"; + variable6.html = string.Concat(strArrays6); + } + if (x.get_Profissao() != null && this.SelectedTipoExtrato != 2) + { + ExtratosViewModel.u003cu003ec__DisplayClass170_0 cSu0024u003cu003e8_locals17 = variable9; + string[] nome1 = new string[] { str371, ""; + cSu0024u003cu003e8_locals17.html = string.Concat(nome1); + } + if (x.get_Contatos() != null && this.SelectedTipoExtrato != 2 && !this.ExtratoResumido) + { + string str13 = ""; + foreach (MaisContato contato in x.get_Contatos()) + { + string[] nome2 = new string[15]; + nome2[0] = str13; + nome2[1] = "
NOME: "; + nome2[2] = contato.get_Nome(); + nome2[3] = (!string.IsNullOrWhiteSpace(contato.get_Documento()) ? string.Concat(", DOCUMENTO: ", contato.get_Documento()) : ""); + nascimento = contato.get_Nascimento(); + if (nascimento.HasValue) + { + nascimento = contato.get_Nascimento(); + str = string.Concat(", NASCIMENTO: ", (nascimento.HasValue ? nascimento.GetValueOrDefault().ToShortDateString() : null)); + } + else + { + str = ""; + } + nome2[4] = str; + Parentesco? parentesco = contato.get_Parentesco(); + if (parentesco.HasValue) + { + parentesco = contato.get_Parentesco(); + str1 = string.Concat(", PARENTESCO: ", (parentesco.HasValue ? parentesco.GetValueOrDefault().ToString().ToUpper() : null)); + } + else + { + str1 = ""; + } + nome2[5] = str1; + nome2[6] = (!string.IsNullOrWhiteSpace(contato.get_Banco()) || !string.IsNullOrWhiteSpace(contato.get_Agencia()) || !string.IsNullOrWhiteSpace(contato.get_Conta()) ? "
" : ""); + nome2[7] = (!string.IsNullOrWhiteSpace(contato.get_Banco()) ? string.Concat("BANCO: ", contato.get_Banco()) : ""); + nome2[8] = (!string.IsNullOrWhiteSpace(contato.get_Agencia()) ? string.Concat((!string.IsNullOrWhiteSpace(contato.get_Banco()) ? ", AGÊNCIA: " : "AGÊNCIA: "), contato.get_Agencia()) : ""); + nome2[9] = (!string.IsNullOrWhiteSpace(contato.get_Conta()) ? string.Concat((!string.IsNullOrWhiteSpace(contato.get_Banco()) || !string.IsNullOrWhiteSpace(contato.get_Agencia()) ? ", CONTA: " : "CONTA: "), contato.get_Conta()) : ""); + tipo = contato.get_Tipo(); + nome2[10] = (tipo.HasValue || !string.IsNullOrWhiteSpace(contato.get_Prefixo()) && !string.IsNullOrWhiteSpace(contato.get_Telefone()) || !string.IsNullOrWhiteSpace(contato.get_Email()) ? "
" : ""); + tipo = contato.get_Tipo(); + if (tipo.HasValue) + { + tipo = contato.get_Tipo(); + if (tipo.HasValue) + { + valueOrDefault = tipo.GetValueOrDefault(); + upper = valueOrDefault.ToString().ToUpper(); + } + else + { + upper = null; + } + str2 = string.Concat("TIPO DO TELEFONE: ", upper); + } + else + { + str2 = ""; + } + nome2[11] = str2; + if (string.IsNullOrWhiteSpace(contato.get_Prefixo()) || string.IsNullOrWhiteSpace(contato.get_Telefone())) + { + str3 = ""; + } + else + { + tipo = contato.get_Tipo(); + str3 = string.Concat((tipo.HasValue ? ", TELEFONE: (" : "TELEFONE: ("), contato.get_Prefixo(), ") ", contato.get_Telefone()); + } + nome2[12] = str3; + if (!string.IsNullOrWhiteSpace(contato.get_Email())) + { + tipo = contato.get_Tipo(); + str4 = string.Concat((tipo.HasValue || !string.IsNullOrWhiteSpace(contato.get_Prefixo()) && !string.IsNullOrWhiteSpace(contato.get_Telefone()) ? ", EMAIL: " : "EMAIL: "), contato.get_Email()); + } + else + { + str4 = ""; + } + nome2[13] = str4; + nome2[14] = "
"; + str13 = string.Concat(nome2); + } + ExtratosViewModel.u003cu003ec__DisplayClass170_0 variable7 = variable9; + string[] strArrays7 = new string[] { str371, "
"; + variable7.html = string.Concat(strArrays7); + } + if (this.ObsCliente && this.ClienteVisibility && this.ObsClienteEnabled && !string.IsNullOrWhiteSpace(x.get_Observacao()) && this.SelectedTipoExtrato != 2 && !this.ExtratoResumido) + { + x.set_Observacao(string.Concat("
", x.get_Observacao().Replace("\r\n", "
"))); + ExtratosViewModel.u003cu003ec__DisplayClass170_0 cSu0024u003cu003e8_locals18 = variable9; + string[] observacao = new string[] { str371, "
"; + cSu0024u003cu003e8_locals18.html = string.Concat(observacao); + } + if (!string.IsNullOrWhiteSpace(x.get_Pasta()) && this.SelectedTipoExtrato != 2 && !this.ExtratoResumido) + { + ExtratosViewModel.u003cu003ec__DisplayClass170_0 variable8 = variable9; + string[] pasta = new string[] { str371, ""; + variable8.html = string.Concat(pasta); + } + str371 = string.Concat(str371, "

CLIENTE: ", x.get_Nome(), "

CPF/CNPJ: ", x.get_Documento(), "

", str9, ": ", null, null }; + DateTime? nascimento = x.get_Nascimento(); + strArrays[20] = (nascimento.HasValue ? nascimento.GetValueOrDefault().ToShortDateString() : null); + strArrays[21] = "

FALECIDO: "; + cSu0024u003cu003e8_locals11[4] = (x.get_Falecido() ? "SIM" : "NÃO"); + cSu0024u003cu003e8_locals11[5] = "

RAMO DE ATIVIDADE: "; + nome[4] = x.get_Atividade().get_Nome(); + nome[5] = "

ESTADO CIVIL: "; + strArrays1[4] = (x.get_EstadoCivil().HasValue ? x.get_EstadoCivil().ToString().ToUpper() : "-"); + strArrays1[5] = "

SEXO: "; + strArrays1[8] = (x.get_Sexo().HasValue ? x.get_Sexo().ToString().ToUpper() : "-"); + strArrays1[9] = "

HABILITAÇÃO: ", (!string.IsNullOrWhiteSpace(x.get_Habilitacao()) ? x.get_Habilitacao() : "-"), "

CATEGORIA: ", (!string.IsNullOrWhiteSpace(x.get_CategoriaHabilitacao()) ? x.get_CategoriaHabilitacao() : "-"), "

1ª HAB.: ", null, null, null, null, null, null }; + nascimento = x.get_PrimeiraHabilitacao(); + if (nascimento.HasValue) + { + nascimento = x.get_PrimeiraHabilitacao(); + str6 = (nascimento.HasValue ? nascimento.GetValueOrDefault().ToShortDateString() : null); + } + else + { + str6 = "-"; + } + strArrays3[12] = str6; + strArrays3[13] = "

VENCIMENTO: "; + nascimento = x.get_VencimentoHabilitacao(); + if (nascimento.HasValue) + { + nascimento = x.get_VencimentoHabilitacao(); + str7 = (nascimento.HasValue ? nascimento.GetValueOrDefault().ToShortDateString() : null); + } + else + { + str7 = "-"; + } + strArrays3[16] = str7; + strArrays3[17] = "

RG: ", (!string.IsNullOrWhiteSpace(x.get_Identidade()) ? x.get_Identidade() : "-"), "

ORGÃO EMISSOR: ", (!string.IsNullOrWhiteSpace(x.get_Emissor()) ? x.get_Emissor() : "-"), "

ESTADO EMISSOR: ", (!string.IsNullOrWhiteSpace(x.get_EstadoEmissor()) ? x.get_EstadoEmissor() : "-"), "

EXPEDIÇÃO: "; + nascimento = x.get_Expedicao(); + if (nascimento.HasValue) + { + nascimento = x.get_Expedicao(); + str5 = (nascimento.HasValue ? nascimento.GetValueOrDefault().ToShortDateString() : null); + } + else + { + str5 = "-"; + } + cSu0024u003cu003e8_locals14[16] = str5; + cSu0024u003cu003e8_locals14[17] = "

BANCO: ", (x.get_Banco() != null ? x.get_Banco().get_Nome() : "-"), "

AGÊNCIA: ", (!string.IsNullOrWhiteSpace(x.get_Agencia()) ? x.get_Agencia() : "-"), "

CONTA: ", (!string.IsNullOrWhiteSpace(x.get_Conta()) ? x.get_Conta() : "-"), "

TIPO: "; + strArrays4[16] = (!string.IsNullOrWhiteSpace(x.get_TipoConta()) ? x.get_TipoConta() : "-"); + strArrays4[17] = "

CONTATOS: "; + strArrays5[4] = str10; + strArrays5[5] = "

EMAILS: "; + cSu0024u003cu003e8_locals16[4] = str11; + cSu0024u003cu003e8_locals16[5] = "

ENDEREÇOS: "; + strArrays6[4] = str12; + strArrays6[5] = "

PROFISSÃO: "; + nome1[4] = x.get_Profissao().get_Nome(); + nome1[5] = "

MAIS CONTATOS: "; + strArrays7[4] = str13; + strArrays7[5] = "

OBSERVAÇÕES: "; + observacao[4] = x.get_Observacao(); + observacao[5] = "

PASTA: "; + pasta[4] = x.get_Pasta(); + pasta[5] = "

"); + str371 = string.Concat(str371, (this.ClientePorPaginaVisibility != Visibility.Visible || !this.ClientePorPagina || !this.ClientePorPaginaEnabled ? "" : "
")); + } + }); + DateTime networkTime = Funcoes.GetNetworkTime(); + string[] strArrays8 = new string[] { str371, "

", Recursos.Usuario.get_Nome(), " - ", null, null }; + date = networkTime.Date; + strArrays8[4] = date.ToShortDateString(); + strArrays8[5] = "
"; + str371 = string.Concat(strArrays8); + string tempPath = Path.GetTempPath(); + string str372 = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.html", tempPath, (TipoExtrato)0, networkTime); + if (!pdf) + { + StreamWriter streamWriter = new StreamWriter(str372, true, Encoding.UTF8); + streamWriter.Write(str371); + streamWriter.Close(); + } + else + { + str372 = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.pdf", tempPath, (TipoExtrato)0, networkTime); + File.WriteAllBytes(str372, (new NRecoHtmlToPdfConverter()).GeneratePdf(str371)); + } + Process.Start(str372); + ExtratosViewModel extratosViewModel = this; + str368 = (this.ExtratoResumido ? " RESUMIDO" : ""); + if (this.Clientes != null) + { + str369 = (this.Clientes.Count > 1 ? string.Format("DE {0} CLIENTES", this.Clientes.Count) : string.Concat("DO CLIENTE ", this.Clientes[0].get_Nome())); + } + else + { + str369 = ""; + } + string str373 = string.Concat("GEROU O EXTRATO", str368, " ", str369); + long num11 = (long)0; + TipoTela? nullable1 = new TipoTela?(23); + List clientes = this.Clientes; + extratosViewModel.RegistrarAcao(str373, num11, nullable1, string.Concat("NOMES DOS CLIENTES:\n", string.Join("\n", + from x in clientes + select x.get_Nome()), this.GerarOpcoes())); + this.Documentos = null; + this.Clientes = null; + } + else if ((this.Documentos != null || this.Prospeccoes != null) && this.Clientes == null) + { + str371 = ""; + str370 = ""; + switch (this.SelectedTipoExtrato) + { + case 0: + { + str14 = (this.ExtratoResumido ? " RESUMIDO" : ""); + str370 = string.Concat("EXTRATO", str14, " DO CLIENTE"); + break; + } + case 1: + { + str364 = (this.ExtratoResumido ? " RESUMIDO" : ""); + str370 = string.Concat("EXTRATO", str364, " DA APÓLICE SELECIONADA"); + if (!tipoRelatorio.HasValue || tipoRelatorio.GetValueOrDefault() != 4) + { + break; + } + str365 = (this.ExtratoResumido ? " RESUMIDO" : ""); + str370 = string.Concat("EXTRATO", str365, " DO RELATÓRIO DE RENOVAÇÕES"); + break; + } + case 2: + { + str366 = (this.ExtratoResumido ? " RESUMIDO" : ""); + str370 = string.Concat("EXTRATO", str366, " DE RELAÇÃO DE APÓLICES"); + break; + } + } + str371 = string.Concat(str371, str370); + str371 = string.Concat(str371, "
"); + List nums = new List(); + if (this.Documentos != null && this.Documentos.Count > 0) + { + List configuracoes = Recursos.Configuracoes; + bool flag = configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 42); + foreach (Documento documento1 in this.Documentos) + { + Documento documento2 = documento1; + ObservableCollection observableCollection = await (new ParcelaServico()).BuscarParcelasAsync(documento1.get_Id()); + documento2.set_Parcelas(observableCollection); + documento2 = null; + Controle controle = documento1.get_Controle(); + Cliente cliente = await this._clienteServico.BuscarCliente(documento1.get_Controle().get_Cliente().get_Id()); + controle.set_Cliente(cliente); + controle = null; + Cliente cliente1 = documento1.get_Controle().get_Cliente(); + ObservableCollection observableCollection1 = await this._clienteServico.BuscarEnderecosAsync(documento1.get_Controle().get_Cliente().get_Id()); + cliente1.set_Enderecos(observableCollection1); + cliente1 = null; + cliente1 = documento1.get_Controle().get_Cliente(); + ObservableCollection observableCollection2 = await this._clienteServico.BuscarEmailsAsync(documento1.get_Controle().get_Cliente().get_Id()); + cliente1.set_Emails(observableCollection2); + cliente1 = null; + cliente1 = documento1.get_Controle().get_Cliente(); + ObservableCollection observableCollection3 = await this._clienteServico.BuscarTelefonesAsync(documento1.get_Controle().get_Cliente().get_Id()); + cliente1.set_Telefones(observableCollection3); + cliente1 = null; + cliente1 = documento1.get_Controle().get_Cliente(); + ObservableCollection observableCollection4 = await this._clienteServico.BuscarContatosAsync(documento1.get_Controle().get_Cliente().get_Id()); + cliente1.set_Contatos(observableCollection4); + cliente1 = null; + } + bool flag1 = true; + foreach (Documento documento3 in this.Documentos) + { + List items1 = new List(); + items = (!this.Endossos ? await (new ItemServico()).BuscarItens(documento3.get_Controle().get_Id(), 0).ToList() : await (new ItemServico()).BuscarItens(documento3.get_Id(), 2).ToList()); + List items2 = items; + if (this._itensSelecionados == null || this._itensSelecionados.Count <= 0) + { + items1.AddRange(items2); + } + else + { + items2.ForEach((Item x) => { + if (this._itensSelecionados.Any((Item y) => y.get_Id() == x.get_Id())) + { + items1.Add(x); + } + }); + } + List perfils = await (new PerfilServico()).BuscarPerfis(documento3.get_Controle().get_Id()); + long num12 = (long)0; + num10 = 0; + if (!flag1) + { + string str374 = str371; + str363 = (this.ExtratoPorPagina ? "
" : ""); + str371 = string.Concat(str374, str363); + } + if (num12 != documento3.get_Controle().get_Cliente().get_Id()) + { + string str375 = str371; + str40 = (this.ClientePorPaginaVisibility != Visibility.Visible || !this.ClientePorPagina || !this.ClientePorPaginaEnabled || this.ExtratoPorPagina ? "" : "
"); + str371 = string.Concat(str375, str40); + str371 = string.Concat(str371, "

"); + switch (this.SelectedTipoExtrato) + { + case 0: + { + str41 = (this.ExtratoResumido ? " RESUMIDO" : ""); + str370 = string.Concat("EXTRATO", str41, " DO CLIENTE: ", documento3.get_Controle().get_Cliente().get_Nome()); + break; + } + case 1: + { + str359 = (this.ExtratoResumido ? " RESUMIDO" : ""); + str370 = string.Concat("EXTRATO", str359, " DA APÓLICE SELECIONADA: ", documento3.get_Apolice()); + if (tipoRelatorio.HasValue && tipoRelatorio.GetValueOrDefault() == 4) + { + str361 = (this.ExtratoResumido ? " RESUMIDO" : ""); + str370 = string.Concat("EXTRATO", str361, " DA APÓLICE: ", documento3.get_Apolice()); + } + if (!string.IsNullOrEmpty(documento3.get_Endosso()) && !documento3.get_Endosso().Equals("0")) + { + str370 = string.Concat(str370, " E DO ENDOSSO: ", documento3.get_Endosso()); + } + if (!this.SomenteEndossos) + { + break; + } + str360 = (this.ExtratoResumido ? " RESUMIDO" : ""); + str370 = string.Concat("EXTRATO", str360, " DO ENDOSSO: ", documento3.get_Endosso()); + break; + } + case 2: + { + str362 = (this.ExtratoResumido ? " RESUMIDO" : ""); + str370 = string.Concat("EXTRATO", str362, " DE RELAÇÃO DE APÓLICES"); + break; + } + } + str371 = string.Concat(str371, str370, "


"); + str371 = string.Concat(str371, ""); + if (!this.ExtratoResumido) + { + if ((!this.Endossos || !this.SomenteEndossos) && !nums.Any((long x) => x == this.documento.get_Controle().get_Id())) + { + str176 = (documento3.get_Controle().get_Cliente().get_Atividade() == null ? "NASCIMENTO" : "ABERTURA"); + string str376 = str176; + bool flag2 = documento3.get_Controle().get_Cliente().get_PessoaFisica(); + string[] documento4 = new string[24]; + documento4[0] = str371; + documento4[1] = ""; + str371 = string.Concat(strArrays9); + } + str371 = string.Concat(str371, ""); + if (documento3.get_Controle().get_Cliente().get_Atividade() != null) + { + string[] strArrays10 = new string[] { str371, ""); + if (documento3.get_Controle().get_Cliente().get_Profissao() == null || this.SelectedTipoExtrato == 2) + { + numeroParcela = num10; + num10 = numeroParcela + 1; + } + else + { + string[] strArrays13 = new string[] { str371, ""; + str371 = string.Concat(strArrays13); + } + str371 = string.Concat(str371, ""); + } + if (flag2) + { + string[] strArrays14 = new string[18]; + strArrays14[0] = str371; + strArrays14[1] = ""; + str371 = string.Concat(strArrays14); + } + if (!string.IsNullOrWhiteSpace(documento3.get_Controle().get_Cliente().get_Identidade())) + { + string[] strArrays15 = new string[18]; + strArrays15[0] = str371; + strArrays15[1] = ""; + str371 = string.Concat(strArrays15); + } + if (this.SelectedTipoExtrato != 2 && !this.ExtratoResumido) + { + string[] strArrays16 = new string[18]; + strArrays16[0] = str371; + strArrays16[1] = ""; + str371 = string.Concat(strArrays16); + } + if ((documento3.get_Controle().get_Cliente().get_Telefones() != null || documento3.get_Controle().get_Cliente().get_Emails() != null) && this.SelectedTipoExtrato != 2) + { + str371 = string.Concat(str371, ""); + if (documento3.get_Controle().get_Cliente().get_Telefones() != null) + { + string str378 = ""; + foreach (ClienteTelefone clienteTelefone in documento3.get_Controle().get_Cliente().get_Telefones()) + { + string[] numero = new string[] { str378, "
", null, null, null, null, null, null, null, null }; + nullable = clienteTelefone.get_Tipo(); + if (nullable.HasValue) + { + tipoTelefone = nullable.GetValueOrDefault(); + str208 = tipoTelefone.ToString().ToUpper(); + } + else + { + str208 = null; + } + numero[2] = str208; + numero[3] = " ("; + numero[4] = clienteTelefone.get_Prefixo(); + numero[5] = ") "; + numero[6] = clienteTelefone.get_Numero(); + numero[7] = " ("; + numero[8] = clienteTelefone.get_Observacao(); + numero[9] = ") "; + str378 = string.Concat(numero); + } + string[] strArrays17 = new string[] { str371, "
"; + str371 = string.Concat(strArrays17); + } + if (documento3.get_Controle().get_Cliente().get_Emails() != null && !this.ExtratoResumido) + { + string str379 = ""; + foreach (ClienteEmail clienteEmail in documento3.get_Controle().get_Cliente().get_Emails()) + { + str379 = string.Concat(str379, "
", clienteEmail.get_Email()); + } + string[] strArrays18 = new string[] { str371, "
"; + str371 = string.Concat(strArrays18); + } + else if (documento3.get_Controle().get_Cliente().get_Enderecos() != null && this.SelectedTipoExtrato != 2) + { + string str380 = ""; + foreach (ClienteEndereco clienteEndereco in documento3.get_Controle().get_Cliente().get_Enderecos()) + { + string[] cidade = new string[] { str380, "
", clienteEndereco.get_Endereco(), ", ", clienteEndereco.get_Numero(), ", ", null, null, null, null, null, null, null, null }; + str205 = (string.IsNullOrWhiteSpace(clienteEndereco.get_Complemento()) ? "" : string.Concat(clienteEndereco.get_Complemento(), ", ")); + cidade[6] = str205; + cidade[7] = clienteEndereco.get_Bairro(); + cidade[8] = " - "; + cidade[9] = clienteEndereco.get_Cidade(); + cidade[10] = " - "; + cidade[11] = clienteEndereco.get_Estado(); + cidade[12] = " - "; + cidade[13] = clienteEndereco.get_Cep(); + str380 = string.Concat(cidade); + } + string[] strArrays19 = new string[] { str371, "
"; + str371 = string.Concat(strArrays19); + } + numeroParcela = num10; + num10 = numeroParcela + 1; + str371 = string.Concat(str371, ""); + } + if (documento3.get_Controle().get_Cliente().get_Enderecos() != null && this.SelectedTipoExtrato != 2 && documento3.get_Controle().get_Cliente().get_Emails() == null && this.ExtratoResumido) + { + string str381 = ""; + foreach (ClienteEndereco clienteEndereco1 in documento3.get_Controle().get_Cliente().get_Enderecos()) + { + string[] estado = new string[] { str381, "
", clienteEndereco1.get_Endereco(), ", ", clienteEndereco1.get_Numero(), ", ", null, null, null, null, null, null, null, null }; + str203 = (string.IsNullOrWhiteSpace(clienteEndereco1.get_Complemento()) ? "" : string.Concat(clienteEndereco1.get_Complemento(), ", ")); + estado[6] = str203; + estado[7] = clienteEndereco1.get_Bairro(); + estado[8] = " - "; + estado[9] = clienteEndereco1.get_Cidade(); + estado[10] = " - "; + estado[11] = clienteEndereco1.get_Estado(); + estado[12] = " - "; + estado[13] = clienteEndereco1.get_Cep(); + str381 = string.Concat(estado); + } + string[] strArrays20 = new string[] { str371, "
"; + str371 = string.Concat(strArrays20); + } + if (documento3.get_Controle().get_Cliente().get_Contatos() != null && this.SelectedTipoExtrato != 2 && !this.ExtratoResumido) + { + string str382 = ""; + foreach (MaisContato maisContato in documento3.get_Controle().get_Cliente().get_Contatos()) + { + string[] strArrays21 = new string[15]; + strArrays21[0] = str382; + strArrays21[1] = "
NOME: "; + strArrays21[2] = maisContato.get_Nome(); + str185 = (!string.IsNullOrWhiteSpace(maisContato.get_Documento()) ? string.Concat(", DOCUMENTO: ", maisContato.get_Documento()) : ""); + strArrays21[3] = str185; + clienteDesde = maisContato.get_Nascimento(); + if (clienteDesde.HasValue) + { + clienteDesde = maisContato.get_Nascimento(); + if (clienteDesde.HasValue) + { + shortDateString9 = clienteDesde.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString9 = null; + } + str186 = string.Concat(", NASCIMENTO: ", shortDateString9); + } + else + { + str186 = ""; + } + strArrays21[4] = str186; + Parentesco? nullable2 = maisContato.get_Parentesco(); + if (nullable2.HasValue) + { + nullable2 = maisContato.get_Parentesco(); + if (nullable2.HasValue) + { + str187 = nullable2.GetValueOrDefault().ToString().ToUpper(); + } + else + { + str187 = null; + } + str188 = string.Concat(", PARENTESCO: ", str187); + } + else + { + str188 = ""; + } + strArrays21[5] = str188; + str189 = (!string.IsNullOrWhiteSpace(maisContato.get_Banco()) || !string.IsNullOrWhiteSpace(maisContato.get_Agencia()) || !string.IsNullOrWhiteSpace(maisContato.get_Conta()) ? "
" : ""); + strArrays21[6] = str189; + str190 = (!string.IsNullOrWhiteSpace(maisContato.get_Banco()) ? string.Concat("BANCO: ", maisContato.get_Banco()) : ""); + strArrays21[7] = str190; + if (!string.IsNullOrWhiteSpace(maisContato.get_Agencia())) + { + str191 = (!string.IsNullOrWhiteSpace(maisContato.get_Banco()) ? ", AGÊNCIA: " : "AGÊNCIA: "); + str192 = string.Concat(str191, maisContato.get_Agencia()); + } + else + { + str192 = ""; + } + strArrays21[8] = str192; + if (!string.IsNullOrWhiteSpace(maisContato.get_Conta())) + { + str193 = (!string.IsNullOrWhiteSpace(maisContato.get_Banco()) || !string.IsNullOrWhiteSpace(maisContato.get_Agencia()) ? ", CONTA: " : "CONTA: "); + str194 = string.Concat(str193, maisContato.get_Conta()); + } + else + { + str194 = ""; + } + strArrays21[9] = str194; + nullable = maisContato.get_Tipo(); + str195 = (nullable.HasValue || !string.IsNullOrWhiteSpace(maisContato.get_Prefixo()) && !string.IsNullOrWhiteSpace(maisContato.get_Telefone()) || !string.IsNullOrWhiteSpace(maisContato.get_Email()) ? "
" : ""); + strArrays21[10] = str195; + nullable = maisContato.get_Tipo(); + if (nullable.HasValue) + { + nullable = maisContato.get_Tipo(); + if (nullable.HasValue) + { + tipoTelefone = nullable.GetValueOrDefault(); + str196 = tipoTelefone.ToString().ToUpper(); + } + else + { + str196 = null; + } + str197 = string.Concat("TIPO DO TELEFONE: ", str196); + } + else + { + str197 = ""; + } + strArrays21[11] = str197; + if (string.IsNullOrWhiteSpace(maisContato.get_Prefixo()) || string.IsNullOrWhiteSpace(maisContato.get_Telefone())) + { + str198 = ""; + } + else + { + nullable = maisContato.get_Tipo(); + str201 = (nullable.HasValue ? ", TELEFONE: (" : "TELEFONE: ("); + str198 = string.Concat(str201, maisContato.get_Prefixo(), ") ", maisContato.get_Telefone()); + } + strArrays21[12] = str198; + if (!string.IsNullOrWhiteSpace(maisContato.get_Email())) + { + nullable = maisContato.get_Tipo(); + str199 = (nullable.HasValue || !string.IsNullOrWhiteSpace(maisContato.get_Prefixo()) && !string.IsNullOrWhiteSpace(maisContato.get_Telefone()) ? ", EMAIL: " : "EMAIL: "); + str200 = string.Concat(str199, maisContato.get_Email()); + } + else + { + str200 = ""; + } + strArrays21[13] = str200; + strArrays21[14] = "
"; + str382 = string.Concat(strArrays21); + } + string[] strArrays22 = new string[] { str371, "
"; + str371 = string.Concat(strArrays22); + } + if (documento3.get_Controle().get_Cliente().get_Enderecos() != null && !this.ExtratoResumido) + { + string str383 = ""; + foreach (ClienteEndereco clienteEndereco2 in documento3.get_Controle().get_Cliente().get_Enderecos()) + { + string[] cep = new string[] { str383, "
", clienteEndereco2.get_Endereco(), ", ", clienteEndereco2.get_Numero(), ", ", null, null, null, null, null, null, null, null }; + str183 = (string.IsNullOrWhiteSpace(clienteEndereco2.get_Complemento()) ? "" : string.Concat(clienteEndereco2.get_Complemento(), ", ")); + cep[6] = str183; + cep[7] = clienteEndereco2.get_Bairro(); + cep[8] = " - "; + cep[9] = clienteEndereco2.get_Cidade(); + cep[10] = " - "; + cep[11] = clienteEndereco2.get_Estado(); + cep[12] = " - "; + cep[13] = clienteEndereco2.get_Cep(); + str383 = string.Concat(cep); + } + string[] strArrays23 = new string[] { str371, "
"; + str371 = string.Concat(strArrays23); + } + if (this.ObsCliente && this.ClienteVisibility && this.ObsClienteEnabled && !string.IsNullOrWhiteSpace(documento3.get_Controle().get_Cliente().get_Observacao()) && this.SelectedTipoExtrato != 2 && !this.ExtratoResumido) + { + documento3.get_Controle().get_Cliente().set_Observacao(string.Concat("
", documento3.get_Controle().get_Cliente().get_Observacao().Replace("\r\n", "
"))); + string[] strArrays24 = new string[] { str371, "
"; + str371 = string.Concat(strArrays24); + } + if (!string.IsNullOrWhiteSpace(documento3.get_Controle().get_Cliente().get_Pasta()) && this.SelectedTipoExtrato != 2 && !this.ExtratoResumido) + { + string[] strArrays25 = new string[] { str371, ""; + str371 = string.Concat(strArrays25); + } + str371 = string.Concat(str371, "

FALECIDO: "; + str239 = (documento3.get_Controle().get_Cliente().get_Falecido() ? "SIM" : "NÃO"); + strArrays9[4] = str239; + strArrays9[5] = "

ESTADO CIVIL: ", null, null, null, null, null, null, null, null }; + if (documento3.get_Controle().get_Cliente().get_EstadoCivil().HasValue) + { + estadoCivil = documento3.get_Controle().get_Cliente().get_EstadoCivil(); + str233 = estadoCivil.ToString().ToUpper(); + } + else + { + str233 = "-"; + } + strArrays12[2] = str233; + strArrays12[3] = "

SEXO: "; + if (documento3.get_Controle().get_Cliente().get_Sexo().HasValue) + { + sexo = documento3.get_Controle().get_Cliente().get_Sexo(); + str235 = sexo.ToString().ToUpper(); + } + else + { + str235 = "-"; + } + strArrays12[6] = str235; + strArrays12[7] = "

"; + str371 = string.Concat(strArrays12); + } + string str377 = str371; + clienteDesde = documento3.get_Controle().get_Cliente().get_ClienteDesde(); + if (clienteDesde.HasValue) + { + clienteDesde = documento3.get_Controle().get_Cliente().get_ClienteDesde(); + if (clienteDesde.HasValue) + { + shortDateString13 = clienteDesde.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString13 = null; + } + } + else + { + shortDateString13 = "-"; + } + str371 = string.Concat(str377, "

CLIENTE DESDE: ", shortDateString13, "

PROFISSÃO: "; + strArrays13[4] = documento3.get_Controle().get_Cliente().get_Profissao().get_Nome(); + strArrays13[5] = "

HABILITAÇÃO: "; + str226 = (!string.IsNullOrWhiteSpace(documento3.get_Controle().get_Cliente().get_Habilitacao()) ? documento3.get_Controle().get_Cliente().get_Habilitacao() : "-"); + strArrays14[4] = str226; + strArrays14[5] = "

CATEGORIA: "; + str228 = (!string.IsNullOrWhiteSpace(documento3.get_Controle().get_Cliente().get_CategoriaHabilitacao()) ? documento3.get_Controle().get_Cliente().get_CategoriaHabilitacao() : "-"); + strArrays14[8] = str228; + strArrays14[9] = "

1ª HAB.: "; + clienteDesde = documento3.get_Controle().get_Cliente().get_PrimeiraHabilitacao(); + if (clienteDesde.HasValue) + { + clienteDesde = documento3.get_Controle().get_Cliente().get_PrimeiraHabilitacao(); + if (clienteDesde.HasValue) + { + shortDateString11 = clienteDesde.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString11 = null; + } + } + else + { + shortDateString11 = "-"; + } + strArrays14[12] = shortDateString11; + strArrays14[13] = "

VENCIMENTO: "; + clienteDesde = documento3.get_Controle().get_Cliente().get_VencimentoHabilitacao(); + if (clienteDesde.HasValue) + { + clienteDesde = documento3.get_Controle().get_Cliente().get_VencimentoHabilitacao(); + if (clienteDesde.HasValue) + { + shortDateString12 = clienteDesde.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString12 = null; + } + } + else + { + shortDateString12 = "-"; + } + strArrays14[16] = shortDateString12; + strArrays14[17] = "

RG: "; + str219 = (!string.IsNullOrWhiteSpace(documento3.get_Controle().get_Cliente().get_Identidade()) ? documento3.get_Controle().get_Cliente().get_Identidade() : "-"); + strArrays15[4] = str219; + strArrays15[5] = "

ORGÃO EMISSOR: "; + str221 = (!string.IsNullOrWhiteSpace(documento3.get_Controle().get_Cliente().get_Emissor()) ? documento3.get_Controle().get_Cliente().get_Emissor() : "-"); + strArrays15[8] = str221; + strArrays15[9] = "

ESTADO EMISSOR: "; + str223 = (!string.IsNullOrWhiteSpace(documento3.get_Controle().get_Cliente().get_EstadoEmissor()) ? documento3.get_Controle().get_Cliente().get_EstadoEmissor() : "-"); + strArrays15[12] = str223; + strArrays15[13] = "

EXPEDIÇÃO: "; + clienteDesde = documento3.get_Controle().get_Cliente().get_Expedicao(); + if (clienteDesde.HasValue) + { + clienteDesde = documento3.get_Controle().get_Cliente().get_Expedicao(); + if (clienteDesde.HasValue) + { + shortDateString10 = clienteDesde.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString10 = null; + } + } + else + { + shortDateString10 = "-"; + } + strArrays15[16] = shortDateString10; + strArrays15[17] = "

BANCO: "; + str211 = (documento3.get_Controle().get_Cliente().get_Banco() != null ? documento3.get_Controle().get_Cliente().get_Banco().get_Nome() : "-"); + strArrays16[4] = str211; + strArrays16[5] = "

AGÊNCIA: "; + str213 = (!string.IsNullOrWhiteSpace(documento3.get_Controle().get_Cliente().get_Agencia()) ? documento3.get_Controle().get_Cliente().get_Agencia() : "-"); + strArrays16[8] = str213; + strArrays16[9] = "

CONTA: "; + str215 = (!string.IsNullOrWhiteSpace(documento3.get_Controle().get_Cliente().get_Conta()) ? documento3.get_Controle().get_Cliente().get_Conta() : "-"); + strArrays16[12] = str215; + strArrays16[13] = "

TIPO: "; + str217 = (!string.IsNullOrWhiteSpace(documento3.get_Controle().get_Cliente().get_TipoConta()) ? documento3.get_Controle().get_Cliente().get_TipoConta() : "-"); + strArrays16[16] = str217; + strArrays16[17] = "

CONTATOS: "; + strArrays17[4] = str378; + strArrays17[5] = "

EMAILS: "; + strArrays18[4] = str379; + strArrays18[5] = "

ENDEREÇOS: "; + strArrays19[4] = str380; + strArrays19[5] = "

ENDEREÇOS: "; + strArrays20[4] = str381; + strArrays20[5] = "

MAIS CONTATOS: "; + strArrays22[4] = str382; + strArrays22[5] = "

ENDEREÇOS: "; + strArrays23[4] = str383; + strArrays23[5] = "

OBSERVAÇÕES: "; + strArrays24[4] = documento3.get_Controle().get_Cliente().get_Observacao(); + strArrays24[5] = "

PASTA: "; + strArrays25[4] = documento3.get_Controle().get_Cliente().get_Pasta(); + strArrays25[5] = "

"); + if (!flag1) + { + string str384 = str371; + str180 = (this.ClientePorPaginaVisibility != Visibility.Visible || !this.ClientePorPagina || !this.ClientePorPaginaEnabled ? "" : "
"); + str371 = string.Concat(str384, str180); + } + } + else + { + string[] documento5 = new string[14]; + documento5[0] = str371; + documento5[1] = "

CLIENTE: "; + documento5[4] = documento3.get_Controle().get_Cliente().get_Nome(); + documento5[5] = "

RG: "; + str44 = (!string.IsNullOrWhiteSpace(documento3.get_Controle().get_Cliente().get_Identidade()) ? documento3.get_Controle().get_Cliente().get_Identidade() : "-"); + documento5[8] = str44; + documento5[9] = "

CPF/CNPJ: "; + documento5[12] = documento3.get_Controle().get_Cliente().get_Documento(); + documento5[13] = "

"; + str371 = string.Concat(documento5); + } + if (this.SelectedTipoExtrato != null) + { + num10 = 0; + string[] shortDateString18 = new string[58]; + shortDateString18[0] = str371; + shortDateString18[1] = "
"; + str371 = string.Concat(shortDateString18); + if (!documento3.get_NegocioCorretora().HasValue) + { + Documento documento6 = documento3; + negocioCorretora = (documento3.get_Situacao() != 2 || !documento3.get_Negocio().HasValue || documento3.get_Negocio().GetValueOrDefault() != 1 ? 0 : 1); + documento6.set_NegocioCorretora(new NegocioCorretora?(negocioCorretora)); + } + if (this.ComissaoDocumento && this.ComissaoDocumentoEnabled) + { + if (this.SelectedTipoExtrato == 2) + { + string[] strArrays26 = new string[] { str371, ""; + str371 = string.Concat(strArrays26); + } + else + { + string[] description5 = new string[14]; + description5[0] = str371; + description5[1] = ""; + str371 = string.Concat(description5); + } + } + else if (this.SelectedTipoExtrato != 2) + { + string[] description6 = new string[] { str371, ""; + str371 = string.Concat(description6); + } + string[] strArrays27 = new string[14]; + strArrays27[0] = str371; + strArrays27[1] = ""; + str371 = string.Concat(strArrays27); + if (this.SelectedTipoExtrato != 2 && !this.ExtratoResumido) + { + str371 = string.Concat(str371, ""); + string str385 = ""; + if (documento3.get_Estipulante1() != null) + { + str385 = string.Concat(str385, documento3.get_Estipulante1().get_Nome(), ", "); + } + if (documento3.get_Estipulante2() != null) + { + str385 = string.Concat(str385, documento3.get_Estipulante2().get_Nome(), ", "); + } + if (documento3.get_Estipulante3() != null) + { + str385 = string.Concat(str385, documento3.get_Estipulante3().get_Nome(), ", "); + } + if (documento3.get_Estipulante4() != null) + { + str385 = string.Concat(str385, documento3.get_Estipulante4().get_Nome(), ", "); + } + if (documento3.get_Estipulante5() != null) + { + str385 = string.Concat(str385, documento3.get_Estipulante5().get_Nome(), ", "); + } + if (!string.IsNullOrWhiteSpace(str385)) + { + int num13 = str385.LastIndexOf(", ", StringComparison.Ordinal); + str385 = str385.Remove(num13, 2).Insert(num13, "."); + } + string[] strArrays28 = new string[] { str371, ""; + str371 = string.Concat(strArrays28); + } + if (this.SelectedTipoExtrato == 2) + { + string[] strArrays29 = new string[] { str371, ""; + str371 = string.Concat(strArrays29); + } + else + { + string[] strArrays30 = new string[] { str371, ""; + str371 = string.Concat(strArrays30); + if (documento3.get_Controle().get_SeguradoraAnterior() != null && !this.ExtratoResumido) + { + string[] strArrays31 = new string[] { str371, ""; + str371 = string.Concat(strArrays31); + } + } + str371 = string.Concat(str371, "

RAMO: "; + shortDateString18[4] = documento3.get_Controle().get_Ramo().get_Nome(); + shortDateString18[5] = "

VIGÊNCIA INICIAL: "; + date = documento3.get_Vigencia1(); + shortDateString18[8] = date.ToShortDateString(); + shortDateString18[9] = "

VIGÊNCIA FINAL: "; + clienteDesde = documento3.get_Vigencia2(); + if (!clienteDesde.HasValue) + { + shortDateString3 = "-"; + } + else + { + clienteDesde = documento3.get_Vigencia2(); + if (clienteDesde.HasValue) + { + shortDateString3 = clienteDesde.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString3 = null; + } + } + shortDateString18[12] = shortDateString3; + shortDateString18[13] = "

CONTRATO: "; + str50 = (string.IsNullOrWhiteSpace(documento3.get_Apolice()) ? "-" : documento3.get_Apolice()); + shortDateString18[16] = str50; + shortDateString18[17] = "

POSSUI ENDOSSO? "; + str52 = (documento3.get_TemEndosso() ? "SIM" : "NÃO"); + shortDateString18[20] = str52; + shortDateString18[21] = "

ADITAMENTO: "; + if (string.IsNullOrWhiteSpace(documento3.get_Endosso())) + { + if (flag) + { + IList documentos = documento3.get_Controle().get_Documentos(); + if (documentos.Where((Documento x) => { + if (x.get_Excluido()) + { + return false; + } + return x.get_Ordem() != 0; + }).ToList().Count <= 0) + { + goto Label2; + } + IList documentos1 = documento3.get_Controle().get_Documentos(); + endosso = documentos1.Last((Documento x) => { + if (x.get_Excluido()) + { + return false; + } + return x.get_Ordem() != 0; + }).get_Endosso(); + goto Label1; + } + Label2: + endosso = "-"; + } + else + { + endosso = documento3.get_Endosso(); + } + Label1: + shortDateString18[24] = endosso; + shortDateString18[25] = "

APÓLICE ANTERIOR: "; + str55 = (string.IsNullOrWhiteSpace(documento3.get_ApoliceAnterior()) ? "-" : documento3.get_ApoliceAnterior()); + shortDateString18[28] = str55; + shortDateString18[29] = "

BANCO: "; + str57 = (documento3.get_Banco() == null ? "-" : documento3.get_Banco().get_Nome()); + shortDateString18[32] = str57; + shortDateString18[33] = "

AGÊNCIA: "; + str59 = (string.IsNullOrWhiteSpace(documento3.get_Agencia()) ? "-" : documento3.get_Agencia()); + shortDateString18[36] = str59; + shortDateString18[37] = "

CONTA: "; + str61 = (string.IsNullOrWhiteSpace(documento3.get_Conta()) ? "-" : documento3.get_Conta()); + shortDateString18[40] = str61; + shortDateString18[41] = "

NUMERO CARTÃO: "; + str63 = (string.IsNullOrWhiteSpace(documento3.get_NumeroCartao()) ? "-" : documento3.get_NumeroCartao()); + shortDateString18[44] = str63; + shortDateString18[45] = "

VENCIMENTO: "; + str65 = (string.IsNullOrWhiteSpace(documento3.get_VencimentoCartao()) ? "-" : documento3.get_VencimentoCartao()); + shortDateString18[48] = str65; + shortDateString18[49] = "

BANDEIRA: "; + str67 = (!documento3.get_Bandeira().HasValue ? "-" : ValidationHelper.GetDescription(documento3.get_Bandeira())); + shortDateString18[52] = str67; + shortDateString18[53] = "

TITULAR/PROPONENTE: "; + str69 = (string.IsNullOrWhiteSpace(documento3.get_NomeProponente()) ? "-" : documento3.get_NomeProponente()); + shortDateString18[56] = str69; + shortDateString18[57] = "

COMISSÃO: "; + strArrays26[4] = string.Format("{0}%", documento3.get_Comissao()); + strArrays26[5] = "

NEGÓCIO CORRETORA: "; + description5[4] = ValidationHelper.GetDescription(documento3.get_NegocioCorretora()); + description5[5] = "

STATUS DO SEGURO: "; + description5[8] = ValidationHelper.GetDescription(documento3.get_Situacao()); + description5[9] = "

COMISSÃO: "; + description5[12] = string.Format("{0}%", documento3.get_Comissao()); + description5[13] = "

NEGÓCIO CORRETORA: "; + description6[4] = ValidationHelper.GetDescription(documento3.get_NegocioCorretora()); + description6[5] = "

STATUS DO SEGURO: "; + description6[8] = ValidationHelper.GetDescription(documento3.get_Situacao()); + description6[9] = "

VENDEDOR: "; + str71 = (documento3.get_VendedorPrincipal() == null ? "-" : documento3.get_VendedorPrincipal().get_Nome()); + strArrays27[4] = str71; + strArrays27[5] = "

REMESSA: "; + clienteDesde = documento3.get_Remessa(); + if (!clienteDesde.HasValue) + { + shortDateString4 = "-"; + } + else + { + clienteDesde = documento3.get_Remessa(); + if (clienteDesde.HasValue) + { + shortDateString4 = clienteDesde.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString4 = null; + } + } + strArrays27[8] = shortDateString4; + strArrays27[9] = "

EMISSÃO: "; + clienteDesde = documento3.get_Emissao(); + if (!clienteDesde.HasValue) + { + shortDateString5 = "-"; + } + else + { + clienteDesde = documento3.get_Emissao(); + if (clienteDesde.HasValue) + { + shortDateString5 = clienteDesde.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString5 = null; + } + } + strArrays27[12] = shortDateString5; + strArrays27[13] = "

ESTIPULANTE(S): "; + str169 = (string.IsNullOrWhiteSpace(str385) ? "-" : str385); + strArrays28[4] = str169; + strArrays28[5] = "

SEGURADORA: "; + strArrays29[4] = documento3.get_Controle().get_Seguradora().get_Nome(); + strArrays29[5] = "

SEGURADORA: "; + strArrays30[4] = documento3.get_Controle().get_Seguradora().get_Nome(); + strArrays30[5] = "

APÓLICE SINISTRADA: "; + str166 = (documento3.get_Sinistro() ? "SIM" : "NÃO"); + strArrays30[8] = str166; + strArrays30[9] = "

SEGURADORA ANTERIOR: "; + strArrays31[4] = documento3.get_Controle().get_SeguradoraAnterior().get_Nome(); + strArrays31[5] = "

"); + if (!this.ExtratoResumido && (this.PremioParcela || this.ObsApoliceEnabled)) + { + str371 = string.Concat(str371, ""); + if (this.PremioParcela) + { + string[] strArrays32 = new string[24]; + strArrays32[0] = str371; + strArrays32[1] = "

PRÊMIO LÍQUIDO:
"; + premioLiquido = documento3.get_PremioLiquido(); + strArrays32[4] = premioLiquido.ToString("c"); + strArrays32[5] = "

ADICIONAL:
"; + premioLiquido = documento3.get_PremioAdicional(); + strArrays32[8] = premioLiquido.ToString("c"); + strArrays32[9] = "

CUSTO APÓLICE:
"; + premioLiquido = documento3.get_Custo(); + strArrays32[12] = premioLiquido.ToString("c"); + strArrays32[13] = "

I.O.F.:
"; + premioLiquido = documento3.get_Iof(); + strArrays32[16] = premioLiquido.ToString("c"); + strArrays32[17] = "

"); + str371 = string.Concat(str371, "

"); + ObservableCollection parcelas = documento3.get_Parcelas(); + if (parcelas != null) + { + count = parcelas.Count > 0; + } + else + { + count = false; + } + if (count) + { + str371 = string.Concat(str371, ""); + foreach (Parcela parcela in documento3.get_Parcelas()) + { + string[] description7 = new string[] { str371, ""; + str371 = string.Concat(description7); + } + } + } + if (this.ObsApolice && this.ObsApoliceEnabled) + { + string[] strArrays33 = new string[] { str371, ""; + str371 = string.Concat(strArrays33); + } + str371 = string.Concat(str371, "

PARCELA

VENCIMENTO

VALOR

FORMA DE PAGAMENTO

", null, null, null, null, null, null, null, null }; + numeroParcela = parcela.get_NumeroParcela(); + description7[2] = numeroParcela.ToString(); + description7[3] = "

"; + date = parcela.get_Vencimento(); + description7[4] = date.ToShortDateString(); + description7[5] = "

"; + description7[6] = string.Format("{0:c}", parcela.get_Valor()); + description7[7] = "

"; + description7[8] = ValidationHelper.GetDescription(documento3.get_FormaPagamento()); + description7[9] = "

OBSERVAÇÕES: "; + str157 = (string.IsNullOrWhiteSpace(documento3.get_Observacao()) ? "-" : documento3.get_Observacao()); + strArrays33[4] = str157; + strArrays33[5] = "

"); + } + if (this.PerfilCondutor && this.PerfilVisibility && documento3.get_Controle().get_Ramo().get_Id() == (long)5 && this.PerfilCondutorEnabled) + { + List list1 = perfils.ToList(); + foreach (Perfil perfil in list1) + { + num10 = 0; + if (string.IsNullOrEmpty(perfil.get_Nome())) + { + continue; + } + string[] description8 = new string[92]; + description8[0] = str371; + description8[1] = "

"; + description8[4] = string.Format("CONDUTOR {0}: ", list1.IndexOf(perfil) + 1); + description8[5] = ""; + description8[6] = perfil.get_Nome(); + description8[7] = "

CPF: "; + str117 = (string.IsNullOrWhiteSpace(perfil.get_Cpf()) ? "-" : perfil.get_Cpf()); + description8[10] = str117; + description8[11] = "

NASCIMENTO: "; + clienteDesde = perfil.get_Nascimento(); + if (!clienteDesde.HasValue) + { + shortDateString7 = "-"; + } + else + { + clienteDesde = perfil.get_Nascimento(); + if (clienteDesde.HasValue) + { + shortDateString7 = clienteDesde.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString7 = null; + } + } + description8[14] = shortDateString7; + description8[15] = "

ESTADO CIVIL: "; + str120 = (!perfil.get_EstadoCivil().HasValue ? "-" : ValidationHelper.GetDescription(perfil.get_EstadoCivil())); + description8[18] = str120; + description8[19] = "

SEXO: "; + str122 = (!perfil.get_Sexo().HasValue ? "-" : ValidationHelper.GetDescription(perfil.get_Sexo())); + description8[22] = str122; + description8[23] = "

RELAÇÃO SEGURADO/CONDUTOR: "; + description8[26] = ValidationHelper.GetDescription(perfil.get_Relacao()); + description8[27] = "

HABILITAÇÃO: "; + str125 = (string.IsNullOrWhiteSpace(perfil.get_Habilitacao()) ? "-" : perfil.get_Habilitacao()); + description8[30] = str125; + description8[31] = "

TEMPO DE HABILITAÇÃO: "; + str127 = (!perfil.get_TempoHabilitacao().HasValue ? "-" : ValidationHelper.GetDescription(perfil.get_TempoHabilitacao())); + description8[34] = str127; + description8[35] = "

QUATIDADE DE VEÍCULOS: "; + if (!perfil.get_VeiculoResidencia().HasValue) + { + str129 = "-"; + } + else + { + numeroParcela = perfil.get_VeiculoResidencia().Value; + str129 = numeroParcela.ToString(); + } + description8[38] = str129; + description8[39] = "

GARAGEM NA RESIDÊNCIA: "; + str131 = (!perfil.get_GaragemResidencia().HasValue ? "-" : ValidationHelper.GetDescription(perfil.get_GaragemResidencia())); + description8[42] = str131; + description8[43] = "

GARAGEM NO TRABALHO: "; + str133 = (!perfil.get_GaragemTrabalho().HasValue ? "-" : ValidationHelper.GetDescription(perfil.get_GaragemTrabalho())); + description8[46] = str133; + description8[47] = "

GARAGEM NO ESTUDO: "; + str135 = (!perfil.get_GaragemEstudo().HasValue ? "-" : ValidationHelper.GetDescription(perfil.get_GaragemEstudo())); + description8[50] = str135; + description8[51] = "

TIPO DE RESIDÊNCIA: "; + str137 = (!perfil.get_TipoResidencia().HasValue ? "-" : ValidationHelper.GetDescription(perfil.get_TipoResidencia())); + description8[54] = str137; + description8[55] = "

QUILOMETRAGEM MENSAL: "; + str139 = (string.IsNullOrWhiteSpace(perfil.get_KmMensal()) ? "-" : perfil.get_KmMensal()); + description8[58] = str139; + description8[59] = "

DISTÂNCIA ATÉ O TRABALHO: "; + str141 = (!perfil.get_DistanciaResidenciaTrabalho().HasValue ? "-" : ValidationHelper.GetDescription(perfil.get_DistanciaResidenciaTrabalho())); + description8[62] = str141; + description8[63] = "

USO PROFISSIONAL: "; + str143 = (!perfil.get_UsoProfissional().HasValue || !perfil.get_UsoProfissional().Value ? "NÃO" : "SIM"); + description8[66] = str143; + description8[67] = "

USO POR DEPENDENTES: "; + str145 = (!perfil.get_UsoDependentes().HasValue ? "-" : ValidationHelper.GetDescription(perfil.get_UsoDependentes())); + description8[70] = str145; + description8[71] = "

OCUPAÇÃO: "; + str147 = (!perfil.get_Ocupacao().HasValue ? "-" : ValidationHelper.GetDescription(perfil.get_Ocupacao())); + description8[74] = str147; + description8[75] = "

SEGURO VIDA: "; + str149 = (!perfil.get_SeguroVida().HasValue || !perfil.get_SeguroVida().Value ? "NÃO" : "SIM"); + description8[78] = str149; + description8[79] = "

ISENÇÃO DE IMPOSTOS: "; + str151 = (!perfil.get_Isencao().HasValue || !perfil.get_Isencao().Value ? "NÃO" : "SIM"); + description8[82] = str151; + description8[83] = "

ANTIFURTO: "; + str153 = (perfil.get_AntiFurto().HasValue ? ValidationHelper.GetDescription(perfil.get_AntiFurto()) : ""); + description8[86] = str153; + description8[87] = "

COBERTURA ESTENDIDA PARA RESIDENTES HABILITADOS: "; + str155 = (!perfil.get_EstenderCobertura().HasValue || !perfil.get_EstenderCobertura().Value ? "NÃO" : "SIM"); + description8[90] = str155; + description8[91] = "

"; + str371 = string.Concat(description8); + } + } + list = items1.ToList(); + if (list.Count != 0) + { + num10 = 0; + foreach (Item item in list) + { + if (item.get_Sinistros().Count > 0) + { + item1 = item; + controleSinistros = await (new SinistroServico()).BuscarControles(item.get_Id()); + item1.set_Sinistros(controleSinistros); + item1 = null; + } + string str386 = str371; + str75 = (!this.SepararPagina || !this.SepararPaginaEnabled ? "" : "
"); + str371 = string.Concat(str386, str75); + string str387 = str371; + str76 = (this.SelectedTipoExtrato != 2 || list.IndexOf(item) == 0 ? "
" : ""); + str371 = string.Concat(str387, str76); + str371 = string.Concat(str371, ""); + str371 = string.Concat(str371, ""); + str371 = string.Concat(str371, ""); + if (this.SelectedTipoExtrato != 2) + { + id = documento3.get_Controle().get_Ramo().get_Id(); + if (id > (long)5) + { + if (id == (long)15 || id == (long)18) + { + goto Label5; + } + if (id == (long)37) + { + goto Label3; + } + goto Label4; + } + else + { + if (id - (long)1 <= (long)2) + { + goto Label5; + } + if (id == (long)5) + { + goto Label3; + } + goto Label4; + } + Label5: + item1 = item; + patrimonial = await (new ItemServico()).BuscaPatrimonial(item.get_Id()); + item1.set_Patrimonial(patrimonial); + item1 = null; + string[] numero1 = new string[19]; + numero1[0] = str371; + numero1[1] = ""; + str371 = string.Concat(numero1); + } + else + { + string[] descricao2 = new string[] { str371, ""; + str371 = string.Concat(descricao2); + } + Label9: + if (item.get_Sinistros().Count > 0) + { + Item item2 = item; + if (item2 != null) + { + IList sinistros = item2.get_Sinistros(); + if (sinistros != null) + { + ControleSinistro controleSinistro = sinistros.LastOrDefault(); + if (controleSinistro != null) + { + List sinistros1 = controleSinistro.get_Sinistros(); + if (sinistros1 != null) + { + Sinistro sinistro = sinistros1.LastOrDefault(); + if (sinistro != null) + { + dataReclamacao = sinistro.get_DataReclamacao(); + } + else + { + clienteDesde = null; + dataReclamacao = clienteDesde; + } + } + else + { + clienteDesde = null; + dataReclamacao = clienteDesde; + } + } + else + { + clienteDesde = null; + dataReclamacao = clienteDesde; + } + } + else + { + clienteDesde = null; + dataReclamacao = clienteDesde; + } + } + else + { + clienteDesde = null; + dataReclamacao = clienteDesde; + } + DateTime? nullable3 = dataReclamacao; + if (nullable3.HasValue) + { + date = nullable3.Value; + shortDateString6 = date.ToShortDateString(); + } + else + { + shortDateString6 = "-"; + } + string str388 = shortDateString6; + string[] strArrays34 = new string[18]; + strArrays34[0] = str371; + strArrays34[1] = ""; + str371 = string.Concat(strArrays34); + } + str371 = string.Concat(str371, ""); + if (this.SelectedTipoExtrato != 2) + { + string[] strArrays35 = new string[] { str371, ""; + str371 = string.Concat(strArrays35); + id = documento3.get_Controle().get_Ramo().get_Id(); + long num14 = id - (long)1; + if (num14 <= (long)58) + { + switch ((uint)num14) + { + case 0: + case 1: + case 2: + case 14: + case 17: + { + if (!this.ObsItem || !this.ObsItemEnabled) + { + break; + } + string[] strArrays36 = new string[] { str371, ""; + str371 = string.Concat(strArrays36); + break; + } + case 3: + case 7: + case 15: + case 16: + case 18: + case 22: + case 23: + case 25: + case 27: + case 30: + case 32: + case 38: + case 40: + case 43: + case 48: + case 58: + { + item1 = item; + riscosDiverso = await (new ItemServico()).BuscaRiscosDiversos(item.get_Id()); + item1.set_RiscosDiversos(riscosDiverso); + item1 = null; + if (!this.ObsItem || !this.ObsItemEnabled) + { + break; + } + string[] strArrays37 = new string[] { str371, ""; + str371 = string.Concat(strArrays37); + break; + } + case 4: + case 36: + { + if (this.ObsItem && this.ObsItemEnabled) + { + string[] strArrays38 = new string[] { str371, ""; + str371 = string.Concat(strArrays38); + } + string[] strArrays39 = new string[30]; + strArrays39[0] = str371; + strArrays39[1] = ""; + str371 = string.Concat(strArrays39); + break; + } + case 5: + case 6: + case 8: + case 9: + case 52: + { + item1 = item; + vida = await (new ItemServico()).BuscaVida(item.get_Id()); + item1.set_Vida(vida); + item1 = null; + if (!item.get_Sinistrado() || !this.BeneficiariosItens || !this.BeneficiariosItensEnabled) + { + break; + } + string str389 = str371; + str102 = (num10 % 2 == 0 ? "WhiteSmoke" : "White"); + str371 = string.Concat(str389, ""); + break; + } + case 12: + { + item1 = item; + aeronautico = await (new ItemServico()).BuscaAeronautico(item.get_Id()); + item1.set_Aeronautico(aeronautico); + item1 = null; + if (!this.ObsItem || !this.ObsItemEnabled) + { + break; + } + string[] strArrays40 = new string[] { str371, ""; + str371 = string.Concat(strArrays40); + break; + } + case 19: + { + item1 = item; + granizo = await (new ItemServico()).BuscaGranizo(item.get_Id()); + item1.set_Granizo(granizo); + item1 = null; + if (!this.ObsItem || !this.ObsItemEnabled) + { + break; + } + string[] strArrays41 = new string[] { str371, ""; + str371 = string.Concat(strArrays41); + break; + } + } + } + else + { + } + } + str371 = string.Concat(str371, "

"; + numero1[4] = string.Format("ITEM {0}: ", item.get_Ordem()); + numero1[5] = ""; + numero1[6] = item.get_Patrimonial().get_Endereco(); + numero1[7] = ", "; + numero1[8] = item.get_Patrimonial().get_Numero(); + numero1[9] = ", "; + str78 = (string.IsNullOrWhiteSpace(item.get_Patrimonial().get_Complemento()) ? "" : string.Concat(item.get_Patrimonial().get_Complemento(), ", ")); + numero1[10] = str78; + numero1[11] = item.get_Patrimonial().get_Bairro(); + numero1[12] = " - "; + numero1[13] = item.get_Patrimonial().get_Cidade(); + numero1[14] = " - "; + numero1[15] = item.get_Patrimonial().get_Estado(); + numero1[16] = " - "; + numero1[17] = item.get_Patrimonial().get_Cep(); + numero1[18] = "

"; + descricao2[4] = string.Format("ITEM {0}: ", item.get_Ordem()); + descricao2[5] = ""; + descricao2[6] = item.get_Descricao(); + descricao2[7] = "

SINISTRO STATUS: "; + Item item3 = item; + if (item3 != null) + { + IList controleSinistros1 = item3.get_Sinistros(); + if (controleSinistros1 != null) + { + ControleSinistro controleSinistro1 = controleSinistros1.LastOrDefault(); + if (controleSinistro1 != null) + { + List sinistros2 = controleSinistro1.get_Sinistros(); + if (sinistros2 != null) + { + Sinistro sinistro1 = sinistros2.LastOrDefault(); + if (sinistro1 != null) + { + description2 = ValidationHelper.GetDescription(sinistro1.get_StatusSinistro()); + } + else + { + description2 = null; + } + } + else + { + description2 = null; + } + } + else + { + description2 = null; + } + } + else + { + description2 = null; + } + } + else + { + description2 = null; + } + strArrays34[4] = description2; + strArrays34[5] = "

DATA: "; + strArrays34[8] = str388; + strArrays34[9] = "

VALOR: "; + Item item4 = item; + if (item4 != null) + { + IList controleSinistros2 = item4.get_Sinistros(); + if (controleSinistros2 != null) + { + ControleSinistro controleSinistro2 = controleSinistros2.LastOrDefault(); + if (controleSinistro2 != null) + { + List sinistros3 = controleSinistro2.get_Sinistros(); + if (sinistros3 != null) + { + Sinistro sinistro2 = sinistros3.LastOrDefault(); + if (sinistro2 != null) + { + currency = ValidationHelper.ToCurrency(sinistro2.get_Valor(), "pt-BR"); + } + else + { + currency = null; + } + } + else + { + currency = null; + } + } + else + { + currency = null; + } + } + else + { + currency = null; + } + } + else + { + currency = null; + } + strArrays34[12] = currency; + strArrays34[13] = "

QTDE SINISTRO(S): "; + numeroParcela = item.get_Sinistros().Count; + strArrays34[16] = numeroParcela.ToString(); + strArrays34[17] = "

STATUS: "; + str81 = (string.IsNullOrWhiteSpace(item.get_Status()) ? item.get_StatusInclusao() : item.get_Status()); + strArrays35[4] = str81; + strArrays35[5] = "

ATIVO: "; + str83 = (!item.get_Substituido().HasValue ? "SIM" : "NÃO"); + strArrays35[8] = str83; + strArrays35[9] = "

OBSERVAÇÕES: "; + str85 = (string.IsNullOrWhiteSpace(item.get_Patrimonial().get_Item().get_Observacao()) ? "-" : item.get_Patrimonial().get_Item().get_Observacao()); + strArrays36[4] = str85; + strArrays36[5] = "

BENS E INFORMAÇÕES: "; + str87 = (string.IsNullOrWhiteSpace(item.get_Patrimonial().get_Bens()) ? "-" : item.get_Patrimonial().get_Bens()); + strArrays36[8] = str87; + strArrays36[9] = "

OBSERVAÇÕES: "; + str89 = (string.IsNullOrWhiteSpace(item.get_RiscosDiversos().get_Observacao()) ? "-" : item.get_RiscosDiversos().get_Observacao()); + strArrays37[4] = str89; + strArrays37[5] = "

OBSERVAÇÕES: "; + str101 = (string.IsNullOrWhiteSpace(item.get_Auto().get_Observacao()) ? "-" : item.get_Auto().get_Observacao()); + strArrays38[4] = str101; + strArrays38[5] = "

COBERTURA PADRÃO: "; + tipoCobertura = item.get_Auto().get_TipoCobertura(); + if (tipoCobertura.HasValue) + { + description = ValidationHelper.GetDescription(tipoCobertura.GetValueOrDefault()); + } + else + { + description = null; + } + strArrays39[4] = description; + strArrays39[5] = "

BÔNUS: "; + bonus = item.get_Auto().get_Bonus(); + strArrays39[8] = bonus.ToString(); + strArrays39[9] = "

REGIÃO DE CIRCULAÇÃO: "; + str93 = (string.IsNullOrWhiteSpace(item.get_Auto().get_RegiaoCirculacao()) ? "-" : item.get_Auto().get_RegiaoCirculacao()); + strArrays39[12] = str93; + strArrays39[13] = "

TABELA DE REFERÊNCIA: "; + tabelaReferencia = item.get_Auto().get_TabelaReferencia(); + if (tabelaReferencia.HasValue) + { + description1 = ValidationHelper.GetDescription(tabelaReferencia.GetValueOrDefault()); + } + else + { + description1 = null; + } + strArrays39[16] = description1; + strArrays39[17] = "

% DE REFERÊNCIA: "; + strArrays39[20] = string.Format("{0}%", item.get_Auto().get_PorcentagemReferencia()); + strArrays39[21] = "

CÓDIGO FIPE: "; + str97 = (string.IsNullOrWhiteSpace(item.get_Auto().get_Fipe()) ? "-" : item.get_Auto().get_Fipe()); + strArrays39[24] = str97; + strArrays39[25] = "

COR DO VEÍCULO: "; + str99 = (!item.get_Auto().get_Cor().HasValue ? "-" : ValidationHelper.GetDescription(item.get_Auto().get_Cor())); + strArrays39[28] = str99; + strArrays39[29] = "

BENEFICIÁRIOS: "); + string str390 = ""; + foreach (ControleSinistro sinistro3 in item.get_Sinistros()) + { + if (sinistro3.get_Sinistros() == null) + { + continue; + } + foreach (Sinistro sinistro4 in sinistro3.get_Sinistros()) + { + if (string.IsNullOrWhiteSpace(sinistro4.get_SinistroVida().get_Beneficiario())) + { + continue; + } + str390 = string.Concat(str390, sinistro4.get_SinistroVida().get_Beneficiario(), ", "); + } + } + if (!string.IsNullOrWhiteSpace(str390)) + { + int num15 = str390.LastIndexOf(", ", StringComparison.Ordinal); + str390 = str390.Remove(num15, 2).Insert(num15, "."); + } + str371 = string.Concat(str371, str390, "

OBSERVAÇÕES: "; + str104 = (string.IsNullOrWhiteSpace(item.get_Aeronautico().get_Observacao()) ? "-" : item.get_Aeronautico().get_Observacao()); + strArrays40[4] = str104; + strArrays40[5] = "

OBSERVAÇÕES: "; + str106 = (string.IsNullOrWhiteSpace(item.get_Granizo().get_Observacao()) ? "-" : item.get_Granizo().get_Observacao()); + strArrays41[4] = str106; + strArrays41[5] = "

"); + if (this.SelectedTipoExtrato != 2) + { + ObservableCollection observableCollection5 = await (new ItemServico()).BuscarCoberturasPorItemAsync(item.get_Id()); + if (observableCollection5.Count > 0 && this.Coberturas) + { + str371 = string.Concat(str371, "
"); + foreach (Cobertura cobertura in observableCollection5) + { + string[] strArrays42 = new string[] { str371, "" }; + str371 = string.Concat(strArrays42); + } + str371 = string.Concat(str371, "

COBERTURA

FRANQUIA

L.M.I.

PRÊMIO

", cobertura.get_Observacao(), "

", string.Format("{0:c}", cobertura.get_Franquia()), "

", string.Format("{0:c}", cobertura.get_Lmi()), "

", string.Format("{0:c}", cobertura.get_Premio()), "

"); + } + string str391 = str371; + str79 = (!this.SepararPagina || !this.SepararPaginaEnabled ? "" : "
"); + str371 = string.Concat(str391, str79); + } + if (this.SelectedTipoExtrato != 2) + { + num10 = 0; + } + } + } + else + { + str371 = string.Concat(str371, "

ESTA APÓLICE NÃO POSSUI ITENS

"); + } + list = null; + } + else + { + variable9 = null; + return; + } + } + else + { + bool flag3 = documento3.get_Controle().get_Cliente().get_PessoaFisica(); + if ((!this.Endossos || !this.SomenteEndossos) && !nums.Any((long x) => x == this.documento.get_Controle().get_Id())) + { + string[] strArrays43 = new string[] { str371, ""; + str371 = string.Concat(strArrays44); + } + string[] documento7 = new string[] { str371, ""; + str371 = string.Concat(documento7); + if (this.SelectedTipoExtrato != 2) + { + str351 = (documento3.get_Controle().get_Cliente().get_Atividade() == null ? "NASCIMENTO" : "ABERTURA"); + string str392 = str351; + string[] strArrays45 = new string[] { str371, ""; + str371 = string.Concat(strArrays46); + } + } + if (this.SelectedTipoExtrato != 2) + { + string[] strArrays47 = new string[18]; + strArrays47[0] = str371; + strArrays47[1] = ""; + str371 = string.Concat(strArrays47); + } + if (this.SelectedTipoExtrato != 2) + { + str371 = string.Concat(str371, ""); + string str393 = ""; + if (documento3.get_Controle().get_Cliente().get_Telefones() != null) + { + foreach (ClienteTelefone clienteTelefone1 in documento3.get_Controle().get_Cliente().get_Telefones()) + { + string[] numero2 = new string[] { str393, "
", null, null, null, null, null }; + nullable = clienteTelefone1.get_Tipo(); + if (nullable.HasValue) + { + tipoTelefone = nullable.GetValueOrDefault(); + str342 = tipoTelefone.ToString().ToUpper(); + } + else + { + str342 = null; + } + numero2[2] = str342; + numero2[3] = " ("; + numero2[4] = clienteTelefone1.get_Prefixo(); + numero2[5] = ") "; + numero2[6] = clienteTelefone1.get_Numero(); + str393 = string.Concat(numero2); + } + } + string[] strArrays48 = new string[] { str371, "
"; + str371 = string.Concat(strArrays48); + string str394 = ""; + if (documento3.get_Controle().get_Cliente().get_Emails() != null) + { + foreach (ClienteEmail clienteEmail1 in documento3.get_Controle().get_Cliente().get_Emails()) + { + str394 = string.Concat(str394, "
", clienteEmail1.get_Email()); + } + } + string[] strArrays49 = new string[] { str371, "
"; + str371 = string.Concat(strArrays49); + string str395 = ""; + if (documento3.get_Controle().get_Cliente().get_Enderecos() != null) + { + foreach (ClienteEndereco clienteEndereco3 in documento3.get_Controle().get_Cliente().get_Enderecos()) + { + string[] cidade1 = new string[] { str395, "
", clienteEndereco3.get_Endereco(), ", ", clienteEndereco3.get_Numero(), ", ", null, null, null, null, null, null, null, null }; + str341 = (string.IsNullOrWhiteSpace(clienteEndereco3.get_Complemento()) ? "" : string.Concat(clienteEndereco3.get_Complemento(), ", ")); + cidade1[6] = str341; + cidade1[7] = clienteEndereco3.get_Bairro(); + cidade1[8] = " - "; + cidade1[9] = clienteEndereco3.get_Cidade(); + cidade1[10] = " - "; + cidade1[11] = clienteEndereco3.get_Estado(); + cidade1[12] = " - "; + cidade1[13] = clienteEndereco3.get_Cep(); + str395 = string.Concat(cidade1); + } + } + string[] strArrays50 = new string[] { str371, "
"; + str371 = string.Concat(strArrays50); + str371 = string.Concat(str371, ""); + } + str371 = string.Concat(str371, "

RG: "; + str358 = (!string.IsNullOrWhiteSpace(documento3.get_Controle().get_Cliente().get_Identidade()) ? documento3.get_Controle().get_Cliente().get_Identidade() : "-"); + strArrays44[4] = str358; + strArrays44[5] = "

CPF/CNPJ: "; + documento7[4] = documento3.get_Controle().get_Cliente().get_Documento(); + documento7[5] = "

ESTADO CIVIL: "; + if (documento3.get_Controle().get_Cliente().get_EstadoCivil().HasValue) + { + estadoCivil = documento3.get_Controle().get_Cliente().get_EstadoCivil(); + str354 = estadoCivil.ToString().ToUpper(); + } + else + { + str354 = "-"; + } + strArrays46[4] = str354; + strArrays46[5] = "

SEXO: "; + if (documento3.get_Controle().get_Cliente().get_Sexo().HasValue) + { + sexo = documento3.get_Controle().get_Cliente().get_Sexo(); + str356 = sexo.ToString().ToUpper(); + } + else + { + str356 = "-"; + } + strArrays46[8] = str356; + strArrays46[9] = "

BANCO: "; + str344 = (documento3.get_Controle().get_Cliente().get_Banco() != null ? documento3.get_Controle().get_Cliente().get_Banco().get_Nome() : "-"); + strArrays47[4] = str344; + strArrays47[5] = "

AGÊNCIA: "; + str346 = (!string.IsNullOrWhiteSpace(documento3.get_Controle().get_Cliente().get_Agencia()) ? documento3.get_Controle().get_Cliente().get_Agencia() : "-"); + strArrays47[8] = str346; + strArrays47[9] = "

CONTA: "; + str348 = (!string.IsNullOrWhiteSpace(documento3.get_Controle().get_Cliente().get_Conta()) ? documento3.get_Controle().get_Cliente().get_Conta() : "-"); + strArrays47[12] = str348; + strArrays47[13] = "

TIPO: "; + str350 = (!string.IsNullOrWhiteSpace(documento3.get_Controle().get_Cliente().get_TipoConta()) ? documento3.get_Controle().get_Cliente().get_TipoConta() : "-"); + strArrays47[16] = str350; + strArrays47[17] = "

CONTATOS: "; + str336 = (string.IsNullOrEmpty(str393) ? "-" : str393); + strArrays48[4] = str336; + strArrays48[5] = "

EMAILS: "; + str338 = (string.IsNullOrEmpty(str394) ? "-" : str394); + strArrays49[4] = str338; + strArrays49[5] = "

ENDEREÇOS: "; + str340 = (string.IsNullOrEmpty(str395) ? "-" : str395); + strArrays50[4] = str340; + strArrays50[5] = "

"); + string str396 = str371; + str334 = (this.ClientePorPaginaVisibility != Visibility.Visible || !this.ClientePorPagina || !this.ClientePorPaginaEnabled ? "" : "
"); + str371 = string.Concat(str396, str334); + } + else + { + string[] documento8 = new string[14]; + documento8[0] = str371; + documento8[1] = "

CLIENTE: "; + documento8[4] = documento3.get_Controle().get_Cliente().get_Nome(); + documento8[5] = "

RG: "; + str242 = (!string.IsNullOrWhiteSpace(documento3.get_Controle().get_Cliente().get_Identidade()) ? documento3.get_Controle().get_Cliente().get_Identidade() : "-"); + documento8[8] = str242; + documento8[9] = "

CPF/CNPJ: "; + documento8[12] = documento3.get_Controle().get_Cliente().get_Documento(); + documento8[13] = "

"; + str371 = string.Concat(documento8); + } + if (this.SelectedTipoExtrato != null) + { + num10 = 0; + IList documentos2 = documento3.get_Controle().get_Documentos(); + if (documentos2 != null) + { + documento = documentos2.LastOrDefault((Documento x) => { + if (x.get_Excluido()) + { + return false; + } + return x.get_Ordem() != 0; + }); + } + else + { + documento = null; + } + Documento documento9 = documento; + string[] shortDateString19 = new string[26]; + shortDateString19[0] = str371; + shortDateString19[1] = "
"; + str371 = string.Concat(shortDateString19); + if (!documento3.get_NegocioCorretora().HasValue) + { + Documento documento10 = documento3; + negocioCorretora1 = (documento3.get_Situacao() != 2 || !documento3.get_Negocio().HasValue || documento3.get_Negocio().GetValueOrDefault() != 1 ? 0 : 1); + documento10.set_NegocioCorretora(new NegocioCorretora?(negocioCorretora1)); + } + if (this.SelectedTipoExtrato != 2) + { + string[] description9 = new string[] { str371, ""; + str371 = string.Concat(description9); + } + string[] strArrays51 = new string[] { str371, ""; + str371 = string.Concat(strArrays51); + if (this.SelectedTipoExtrato != 2) + { + str371 = string.Concat(str371, ""); + string str397 = ""; + if (documento3.get_Estipulante1() != null) + { + str397 = string.Concat(str397, documento3.get_Estipulante1().get_Nome(), ", "); + } + if (documento3.get_Estipulante2() != null) + { + str397 = string.Concat(str397, documento3.get_Estipulante2().get_Nome(), ", "); + } + if (documento3.get_Estipulante3() != null) + { + str397 = string.Concat(str397, documento3.get_Estipulante3().get_Nome(), ", "); + } + if (documento3.get_Estipulante4() != null) + { + str397 = string.Concat(str397, documento3.get_Estipulante4().get_Nome(), ", "); + } + if (documento3.get_Estipulante5() != null) + { + str397 = string.Concat(str397, documento3.get_Estipulante5().get_Nome(), ", "); + } + if (!string.IsNullOrWhiteSpace(str397)) + { + int num16 = str397.LastIndexOf(", ", StringComparison.Ordinal); + str397 = str397.Remove(num16, 2).Insert(num16, "."); + } + string[] strArrays52 = new string[] { str371, ""; + str371 = string.Concat(strArrays52); + } + if (this.SelectedTipoExtrato == 2) + { + string[] strArrays53 = new string[] { str371, ""; + str371 = string.Concat(strArrays53); + } + else + { + string[] strArrays54 = new string[] { str371, ""; + str371 = string.Concat(strArrays54); + } + string[] description10 = new string[] { str371, ""; + str371 = string.Concat(description10); + str371 = string.Concat(str371, "

RAMO: "; + shortDateString19[4] = documento3.get_Controle().get_Ramo().get_Nome(); + shortDateString19[5] = "

VIGÊNCIA INICIAL: "; + date = documento3.get_Vigencia1(); + shortDateString19[8] = date.ToShortDateString(); + shortDateString19[9] = "

VIGÊNCIA FINAL: "; + clienteDesde = documento3.get_Vigencia2(); + if (!clienteDesde.HasValue) + { + shortDateString14 = "-"; + } + else + { + clienteDesde = documento3.get_Vigencia2(); + if (clienteDesde.HasValue) + { + shortDateString14 = clienteDesde.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString14 = null; + } + } + shortDateString19[12] = shortDateString14; + shortDateString19[13] = "

CONTRATO: "; + str248 = (string.IsNullOrWhiteSpace(documento3.get_Apolice()) ? "-" : documento3.get_Apolice()); + shortDateString19[16] = str248; + shortDateString19[17] = "

POSSUI ENDOSSO? "; + str250 = (documento3.get_TemEndosso() ? "SIM" : "NÃO"); + shortDateString19[20] = str250; + shortDateString19[21] = "

ADITAMENTO: "; + if (string.IsNullOrWhiteSpace(documento3.get_Endosso())) + { + endosso1 = (!flag || documento9 == null ? "-" : documento9.get_Endosso()); + } + else + { + endosso1 = documento3.get_Endosso(); + } + shortDateString19[24] = endosso1; + shortDateString19[25] = "

NEGÓCIO CORRETORA: "; + description9[4] = ValidationHelper.GetDescription(documento3.get_NegocioCorretora()); + description9[5] = "

STATUS DO SEGURO: "; + description9[8] = ValidationHelper.GetDescription(documento3.get_Situacao()); + description9[9] = "

VENDEDOR: "; + str253 = (documento3.get_VendedorPrincipal() == null ? "-" : documento3.get_VendedorPrincipal().get_Nome()); + strArrays51[4] = str253; + strArrays51[5] = "

ESTIPULANTE(S): "; + str329 = (string.IsNullOrWhiteSpace(str397) ? "-" : str397); + strArrays52[4] = str329; + strArrays52[5] = "

SEGURADORA: "; + strArrays53[4] = documento3.get_Controle().get_Seguradora().get_Nome(); + strArrays53[5] = "

SEGURADORA: "; + strArrays54[4] = documento3.get_Controle().get_Seguradora().get_Nome(); + strArrays54[5] = "

APÓLICE SINISTRADA: "; + str327 = (documento3.get_Sinistro() ? "SIM" : "NÃO"); + strArrays54[8] = str327; + strArrays54[9] = "

FORMA PAGAMENTO: "; + description10[4] = ValidationHelper.GetDescription(documento3.get_FormaPagamento()); + description10[5] = "

"); + if (this.PremioParcela || this.ExtratoResumido) + { + str371 = string.Concat(str371, ""); + if (this.ComissaoDocumento && this.ComissaoDocumentoEnabled || this.ExtratoResumido) + { + string[] strArrays55 = new string[] { str371, ""; + str371 = string.Concat(strArrays55); + } + string[] strArrays56 = new string[26]; + strArrays56[0] = str371; + strArrays56[1] = ""; + str371 = string.Concat(strArrays56); + str371 = string.Concat(str371, "

COMISSÃO: "; + strArrays55[4] = string.Format("{0:n2}%", Math.Round(documento3.get_Comissao(), 2)); + strArrays55[5] = "

PRÊMIO LÍQUIDO: "; + strArrays56[4] = string.Format("{0:c}", Math.Round(documento3.get_PremioLiquido(), 2)); + strArrays56[5] = "

ADICIONAL: "; + strArrays56[8] = string.Format("{0:c}", Math.Round(documento3.get_PremioAdicional(), 2)); + strArrays56[9] = "

CUSTO APÓLICE: "; + strArrays56[12] = string.Format("{0:c}", Math.Round(documento3.get_Custo(), 2)); + strArrays56[13] = "

I.O.F.: "; + strArrays56[16] = string.Format("{0:c}", Math.Round(documento3.get_Iof(), 2)); + strArrays56[17] = "

PRÊMIO TOTAL: "; + strArrays56[20] = string.Format("{0:c}", Math.Round(documento3.get_PremioTotal(), 2)); + strArrays56[21] = "

Nº PARCELAS: "; + premioLiquido = documento3.get_NumeroParcelas(); + strArrays56[24] = premioLiquido.ToString(); + strArrays56[25] = "

"); + } + if (this.PerfilCondutor && this.PerfilVisibility && documento3.get_Controle().get_Ramo().get_Id() == (long)5 && this.PerfilCondutorEnabled) + { + List perfils1 = perfils.ToList(); + foreach (Perfil perfil1 in perfils1) + { + num10 = 0; + if (string.IsNullOrEmpty(perfil1.get_Nome())) + { + continue; + } + string[] description11 = new string[60]; + description11[0] = str371; + description11[1] = "

"; + description11[4] = string.Format("CONDUTOR {0}: ", perfils1.IndexOf(perfil1) + 1); + description11[5] = ""; + description11[6] = perfil1.get_Nome(); + description11[7] = "

CPF: "; + str301 = (string.IsNullOrWhiteSpace(perfil1.get_Cpf()) ? "-" : perfil1.get_Cpf()); + description11[10] = str301; + description11[11] = "

NASCIMENTO: "; + clienteDesde = perfil1.get_Nascimento(); + if (!clienteDesde.HasValue) + { + shortDateString16 = "-"; + } + else + { + clienteDesde = perfil1.get_Nascimento(); + if (clienteDesde.HasValue) + { + shortDateString16 = clienteDesde.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString16 = null; + } + } + description11[14] = shortDateString16; + description11[15] = "

ESTADO CIVIL: "; + str304 = (!perfil1.get_EstadoCivil().HasValue ? "-" : ValidationHelper.GetDescription(perfil1.get_EstadoCivil())); + description11[18] = str304; + description11[19] = "

SEXO: "; + str306 = (!perfil1.get_Sexo().HasValue ? "-" : ValidationHelper.GetDescription(perfil1.get_Sexo())); + description11[22] = str306; + description11[23] = "

RELAÇÃO SEGURADO/CONDUTOR: "; + description11[26] = ValidationHelper.GetDescription(perfil1.get_Relacao()); + description11[27] = "

GARAGEM NA RESIDÊNCIA: "; + str309 = (!perfil1.get_GaragemResidencia().HasValue ? "-" : ValidationHelper.GetDescription(perfil1.get_GaragemResidencia())); + description11[30] = str309; + description11[31] = "

GARAGEM NO TRABALHO: "; + str311 = (!perfil1.get_GaragemTrabalho().HasValue ? "-" : ValidationHelper.GetDescription(perfil1.get_GaragemTrabalho())); + description11[34] = str311; + description11[35] = "

GARAGEM NO ESTUDO: "; + str313 = (!perfil1.get_GaragemEstudo().HasValue ? "-" : ValidationHelper.GetDescription(perfil1.get_GaragemEstudo())); + description11[38] = str313; + description11[39] = "

TIPO DE RESIDÊNCIA: "; + str315 = (!perfil1.get_TipoResidencia().HasValue ? "-" : ValidationHelper.GetDescription(perfil1.get_TipoResidencia())); + description11[42] = str315; + description11[43] = "

DISTÂNCIA ATÉ O TRABALHO: "; + str317 = (!perfil1.get_DistanciaResidenciaTrabalho().HasValue ? "-" : ValidationHelper.GetDescription(perfil1.get_DistanciaResidenciaTrabalho())); + description11[46] = str317; + description11[47] = "

USO PROFISSIONAL: "; + str319 = (!perfil1.get_UsoProfissional().HasValue || !perfil1.get_UsoProfissional().Value ? "NÃO" : "SIM"); + description11[50] = str319; + description11[51] = "

USO POR DEPENDENTES: "; + str321 = (!perfil1.get_UsoDependentes().HasValue ? "-" : ValidationHelper.GetDescription(perfil1.get_UsoDependentes())); + description11[54] = str321; + description11[55] = "

ISENÇÃO DE IMPOSTOS: "; + str323 = (!perfil1.get_Isencao().HasValue || !perfil1.get_Isencao().Value ? "NÃO" : "SIM"); + description11[58] = str323; + description11[59] = "

"; + str371 = string.Concat(description11); + } + } + list = items1.ToList(); + if (list.Count != 0) + { + num10 = 0; + foreach (Item item5 in list) + { + if (item5.get_Sinistros().Count > 0) + { + item1 = item5; + controleSinistros = await (new SinistroServico()).BuscarControles(item5.get_Id()); + item1.set_Sinistros(controleSinistros); + item1 = null; + } + string str398 = str371; + str262 = (!this.SepararPagina || !this.SepararPaginaEnabled ? "" : "
"); + str371 = string.Concat(str398, str262); + string str399 = str371; + str263 = (this.SelectedTipoExtrato != 2 || list.IndexOf(item5) == 0 ? "
" : ""); + str371 = string.Concat(str399, str263); + str371 = string.Concat(str371, ""); + str371 = string.Concat(str371, ""); + str371 = string.Concat(str371, ""); + if (this.SelectedTipoExtrato != 2) + { + id = documento3.get_Controle().get_Ramo().get_Id(); + if (id > (long)5) + { + if (id == (long)15 || id == (long)18) + { + goto Label8; + } + if (id == (long)37) + { + goto Label6; + } + goto Label7; + } + else + { + if (id - (long)1 <= (long)2) + { + goto Label8; + } + if (id == (long)5) + { + goto Label6; + } + goto Label7; + } + Label8: + item1 = item5; + patrimonial = await (new ItemServico()).BuscaPatrimonial(item5.get_Id()); + item1.set_Patrimonial(patrimonial); + item1 = null; + string[] estado1 = new string[19]; + estado1[0] = str371; + estado1[1] = ""; + str371 = string.Concat(estado1); + } + else + { + string[] descricao3 = new string[] { str371, ""; + str371 = string.Concat(descricao3); + } + Label10: + if (item5.get_Sinistros().Count > 0) + { + Item item6 = item5; + if (item6 != null) + { + IList controleSinistros3 = item6.get_Sinistros(); + if (controleSinistros3 != null) + { + ControleSinistro controleSinistro3 = controleSinistros3.LastOrDefault(); + if (controleSinistro3 != null) + { + List sinistros4 = controleSinistro3.get_Sinistros(); + if (sinistros4 != null) + { + Sinistro sinistro5 = sinistros4.LastOrDefault(); + if (sinistro5 != null) + { + dataReclamacao1 = sinistro5.get_DataReclamacao(); + } + else + { + clienteDesde = null; + dataReclamacao1 = clienteDesde; + } + } + else + { + clienteDesde = null; + dataReclamacao1 = clienteDesde; + } + } + else + { + clienteDesde = null; + dataReclamacao1 = clienteDesde; + } + } + else + { + clienteDesde = null; + dataReclamacao1 = clienteDesde; + } + } + else + { + clienteDesde = null; + dataReclamacao1 = clienteDesde; + } + DateTime? nullable4 = dataReclamacao1; + if (nullable4.HasValue) + { + date = nullable4.Value; + shortDateString15 = date.ToShortDateString(); + } + else + { + shortDateString15 = "-"; + } + string str400 = shortDateString15; + string[] currency1 = new string[14]; + currency1[0] = str371; + currency1[1] = ""; + str371 = string.Concat(currency1); + } + str371 = string.Concat(str371, ""); + if (this.SelectedTipoExtrato != 2) + { + string[] strArrays57 = new string[] { str371, ""; + str371 = string.Concat(strArrays57); + id = documento3.get_Controle().get_Ramo().get_Id(); + long num17 = id - (long)1; + if (num17 <= (long)58) + { + switch ((uint)num17) + { + case 0: + case 1: + case 2: + case 14: + case 17: + { + if (!this.ObsItem || !this.ObsItemEnabled) + { + break; + } + string[] strArrays58 = new string[] { str371, ""; + str371 = string.Concat(strArrays58); + break; + } + case 3: + case 7: + case 15: + case 16: + case 18: + case 22: + case 23: + case 25: + case 27: + case 30: + case 32: + case 38: + case 40: + case 43: + case 48: + case 58: + { + item1 = item5; + riscosDiverso = await (new ItemServico()).BuscaRiscosDiversos(item5.get_Id()); + item1.set_RiscosDiversos(riscosDiverso); + item1 = null; + if (!this.ObsItem || !this.ObsItemEnabled) + { + break; + } + string[] strArrays59 = new string[] { str371, ""; + str371 = string.Concat(strArrays59); + break; + } + case 4: + case 36: + { + if (this.ObsItem && this.ObsItemEnabled) + { + string[] strArrays60 = new string[] { str371, ""; + str371 = string.Concat(strArrays60); + } + string[] strArrays61 = new string[26]; + strArrays61[0] = str371; + strArrays61[1] = ""; + str371 = string.Concat(strArrays61); + break; + } + case 5: + case 6: + case 8: + case 9: + case 52: + { + item1 = item5; + vida = await (new ItemServico()).BuscaVida(item5.get_Id()); + item1.set_Vida(vida); + item1 = null; + if (!item5.get_Sinistrado() || !this.BeneficiariosItens || !this.BeneficiariosItensEnabled) + { + break; + } + string str401 = str371; + str287 = (num10 % 2 == 0 ? "WhiteSmoke" : "White"); + str371 = string.Concat(str401, ""); + break; + } + case 12: + { + item1 = item5; + aeronautico = await (new ItemServico()).BuscaAeronautico(item5.get_Id()); + item1.set_Aeronautico(aeronautico); + item1 = null; + if (!this.ObsItem || !this.ObsItemEnabled) + { + break; + } + string[] strArrays62 = new string[] { str371, ""; + str371 = string.Concat(strArrays62); + break; + } + case 19: + { + item1 = item5; + granizo = await (new ItemServico()).BuscaGranizo(item5.get_Id()); + item1.set_Granizo(granizo); + item1 = null; + if (!this.ObsItem || !this.ObsItemEnabled) + { + break; + } + string[] strArrays63 = new string[] { str371, ""; + str371 = string.Concat(strArrays63); + break; + } + } + } + else + { + } + } + str371 = string.Concat(str371, "

"; + estado1[4] = string.Format("ITEM {0}: ", item5.get_Ordem()); + estado1[5] = ""; + estado1[6] = item5.get_Patrimonial().get_Endereco(); + estado1[7] = ", "; + estado1[8] = item5.get_Patrimonial().get_Numero(); + estado1[9] = ", "; + str265 = (string.IsNullOrWhiteSpace(item5.get_Patrimonial().get_Complemento()) ? "" : string.Concat(item5.get_Patrimonial().get_Complemento(), ", ")); + estado1[10] = str265; + estado1[11] = item5.get_Patrimonial().get_Bairro(); + estado1[12] = " - "; + estado1[13] = item5.get_Patrimonial().get_Cidade(); + estado1[14] = " - "; + estado1[15] = item5.get_Patrimonial().get_Estado(); + estado1[16] = " - "; + estado1[17] = item5.get_Patrimonial().get_Cep(); + estado1[18] = "

"; + descricao3[4] = string.Format("ITEM {0}: ", item5.get_Ordem()); + descricao3[5] = ""; + descricao3[6] = item5.get_Descricao(); + descricao3[7] = "

SINISTRO STATUS: "; + currency1[4] = ValidationHelper.GetDescription(item5.get_Sinistros().LastOrDefault().get_Sinistros().LastOrDefault().get_StatusSinistro()); + currency1[5] = "

DATA: "; + currency1[8] = str400; + currency1[9] = "

VALOR: "; + currency1[12] = ValidationHelper.ToCurrency(item5.get_Sinistros().LastOrDefault().get_Sinistros().LastOrDefault().get_Valor(), "pt-BR"); + currency1[13] = "

ATIVO: "; + str272 = (!item5.get_Substituido().HasValue ? "SIM" : "NÃO"); + strArrays57[4] = str272; + strArrays57[5] = "

OBSERVAÇÕES: "; + str274 = (string.IsNullOrWhiteSpace(item5.get_Patrimonial().get_Bens()) ? "-" : item5.get_Patrimonial().get_Bens()); + strArrays58[4] = str274; + strArrays58[5] = "

OBSERVAÇÕES: "; + str276 = (string.IsNullOrWhiteSpace(item5.get_RiscosDiversos().get_Observacao()) ? "-" : item5.get_RiscosDiversos().get_Observacao()); + strArrays59[4] = str276; + strArrays59[5] = "

OBSERVAÇÕES: "; + str286 = (string.IsNullOrWhiteSpace(item5.get_Auto().get_Observacao()) ? "-" : item5.get_Auto().get_Observacao()); + strArrays60[4] = str286; + strArrays60[5] = "

COBERTURA PADRÃO: "; + tipoCobertura = item5.get_Auto().get_TipoCobertura(); + if (tipoCobertura.HasValue) + { + description3 = ValidationHelper.GetDescription(tipoCobertura.GetValueOrDefault()); + } + else + { + description3 = null; + } + strArrays61[4] = description3; + strArrays61[5] = "

BÔNUS: "; + bonus = item5.get_Auto().get_Bonus(); + strArrays61[8] = bonus.ToString(); + strArrays61[9] = "

REGIÃO DE CIRCULAÇÃO: "; + str280 = (string.IsNullOrWhiteSpace(item5.get_Auto().get_RegiaoCirculacao()) ? "-" : item5.get_Auto().get_RegiaoCirculacao()); + strArrays61[12] = str280; + strArrays61[13] = "

TABELA DE REFERÊNCIA: "; + tabelaReferencia = item5.get_Auto().get_TabelaReferencia(); + if (tabelaReferencia.HasValue) + { + description4 = ValidationHelper.GetDescription(tabelaReferencia.GetValueOrDefault()); + } + else + { + description4 = null; + } + strArrays61[16] = description4; + strArrays61[17] = "

FIPE: "; + str283 = (string.IsNullOrWhiteSpace(item5.get_Auto().get_Fipe()) ? "-" : item5.get_Auto().get_Fipe()); + strArrays61[20] = str283; + strArrays61[21] = "

% DE REFERÊNCIA: "; + strArrays61[24] = string.Format("{0}%", item5.get_Auto().get_PorcentagemReferencia()); + strArrays61[25] = "

BENEFICIÁRIOS: "); + string str402 = ""; + foreach (ControleSinistro controleSinistro4 in item5.get_Sinistros()) + { + if (controleSinistro4.get_Sinistros() == null) + { + continue; + } + foreach (Sinistro sinistro6 in controleSinistro4.get_Sinistros()) + { + if (string.IsNullOrWhiteSpace(sinistro6.get_SinistroVida().get_Beneficiario())) + { + continue; + } + str402 = string.Concat(str402, sinistro6.get_SinistroVida().get_Beneficiario(), ", "); + } + } + if (!string.IsNullOrWhiteSpace(str402)) + { + int num18 = str402.LastIndexOf(", ", StringComparison.Ordinal); + str402 = str402.Remove(num18, 2).Insert(num18, "."); + } + str371 = string.Concat(str371, str402, "

OBSERVAÇÕES: "; + str289 = (string.IsNullOrWhiteSpace(item5.get_Aeronautico().get_Observacao()) ? "-" : item5.get_Aeronautico().get_Observacao()); + strArrays62[4] = str289; + strArrays62[5] = "

OBSERVAÇÕES: "; + str291 = (string.IsNullOrWhiteSpace(item5.get_Granizo().get_Observacao()) ? "-" : item5.get_Granizo().get_Observacao()); + strArrays63[4] = str291; + strArrays63[5] = "

"); + if (this.SelectedTipoExtrato != 2) + { + ObservableCollection observableCollection6 = await (new ItemServico()).BuscarCoberturasPorItemAsync(item5.get_Id()); + if (observableCollection6.Count > 0 && this.Coberturas) + { + str371 = string.Concat(str371, "
"); + foreach (Cobertura cobertura1 in observableCollection6) + { + numeroParcela = num10; + num10 = numeroParcela + 1; + string[] strArrays64 = new string[18]; + strArrays64[0] = str371; + strArrays64[1] = "

COBERTURA

FRANQUIA

LMI

PRÊMIO

"; + strArrays64[4] = cobertura1.get_Observacao(); + strArrays64[5] = "

"); + } + string str403 = str371; + str266 = (!this.SepararPagina || !this.SepararPaginaEnabled ? "" : "
"); + str371 = string.Concat(str403, str266); + } + if (this.SelectedTipoExtrato != 2) + { + num10 = 0; + } + } + } + else + { + str371 = string.Concat(str371, "

ESTA APÓLICE NÃO POSSUI ITENS

"); + } + list = null; + } + else + { + variable9 = null; + return; + } + } + } + nums.Add(documento3.get_Controle().get_Id()); + flag1 = false; + } + } + if (this.Prospeccoes != null && this.Prospeccoes.Count > 0) + { + foreach (Prospeccao prospecco in this.Prospeccoes) + { + int num19 = 0; + string str404 = str371; + str19 = (this.ClientePorPaginaVisibility != Visibility.Visible || !this.ClientePorPagina || !this.ClientePorPaginaEnabled ? "" : "
"); + str371 = string.Concat(str404, str19); + str371 = string.Concat(str371, "

"); + if (this.SelectedTipoExtrato == null) + { + str39 = (this.ExtratoResumido ? " RESUMIDO" : ""); + str370 = string.Concat("EXTRATO", str39, " DO CLIENTE: ", prospecco.get_Nome()); + } + str371 = string.Concat(str371, str370, "


"); + str371 = string.Concat(str371, ""); + if (!this.ExtratoResumido) + { + string str405 = "NASCIMENTO"; + string[] documento11 = new string[16]; + documento11[0] = str371; + documento11[1] = ""; + str371 = string.Concat(documento11); + if ((prospecco.get_Telefone1() != null || prospecco.get_Email() != null) && this.SelectedTipoExtrato != 2) + { + str371 = string.Concat(str371, ""); + if (prospecco.get_Telefone1() != null) + { + string str406 = ""; + string[] prefixo1 = new string[] { str406, "
(", prospecco.get_Prefixo1(), ") ", prospecco.get_Telefone1() }; + str406 = string.Concat(prefixo1); + if (prospecco.get_Telefone2() != null) + { + string[] prefixo2 = new string[] { str406, "
(", prospecco.get_Prefixo2(), ") ", prospecco.get_Telefone2() }; + str406 = string.Concat(prefixo2); + } + string[] strArrays65 = new string[] { str371, "
"; + str371 = string.Concat(strArrays65); + } + if (prospecco.get_Email() != null && !this.ExtratoResumido) + { + string str407 = ""; + str407 = string.Concat(str407, "
", prospecco.get_Email()); + string[] strArrays66 = new string[] { str371, "
"; + str371 = string.Concat(strArrays66); + } + num19++; + str371 = string.Concat(str371, ""); + } + string str408 = str371; + str23 = (this.ClientePorPaginaVisibility != Visibility.Visible || !this.ClientePorPagina || !this.ClientePorPaginaEnabled ? "" : ""); + str371 = string.Concat(str408, str23); + if (this.SelectedTipoExtrato != null) + { + num19 = 0; + string[] strArrays67 = new string[] { str371, "

CLIENTE: "; + documento11[4] = prospecco.get_Nome(); + documento11[5] = "

CPF/CNPJ: "; + documento11[8] = prospecco.get_Documento(); + documento11[9] = "

"; + documento11[12] = str405; + documento11[13] = ": "; + clienteDesde = prospecco.get_Nascimento(); + if (clienteDesde.HasValue) + { + shortDateString = clienteDesde.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString = null; + } + documento11[14] = shortDateString; + documento11[15] = "

CONTATOS: "; + strArrays65[4] = str406; + strArrays65[5] = "

EMAILS: "; + strArrays66[4] = str407; + strArrays66[5] = "

"; + str371 = string.Concat(strArrays67); + string[] strArrays68 = new string[] { str371, ""; + str371 = string.Concat(strArrays68); + str371 = string.Concat(str371, "

VIGÊNCIA FINAL: "; + clienteDesde = prospecco.get_VigenciaFinal(); + if (!clienteDesde.HasValue) + { + shortDateString1 = "-"; + } + else + { + clienteDesde = prospecco.get_VigenciaFinal(); + if (clienteDesde.HasValue) + { + shortDateString1 = clienteDesde.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString1 = null; + } + } + strArrays67[4] = shortDateString1; + strArrays67[5] = "

VENDEDOR: "; + str26 = (prospecco.get_Vendedor() == null ? "-" : prospecco.get_Vendedor().get_Nome()); + strArrays68[4] = str26; + strArrays68[5] = "

"); + } + else + { + variable9 = null; + return; + } + } + else + { + string[] documento12 = new string[] { str371, ""; + str371 = string.Concat(documento12); + if (this.SelectedTipoExtrato != 2) + { + str371 = string.Concat(str371, ""); + string str409 = ""; + if (prospecco.get_Telefone1() != null) + { + string[] prefixo11 = new string[] { str409, "
(", prospecco.get_Prefixo1(), ") ", prospecco.get_Telefone1() }; + str409 = string.Concat(prefixo11); + } + if (prospecco.get_Telefone2() != null) + { + string[] prefixo21 = new string[] { str409, "
(", prospecco.get_Prefixo2(), ") ", prospecco.get_Telefone2() }; + str409 = string.Concat(prefixo21); + } + string[] strArrays69 = new string[] { str371, "
"; + str371 = string.Concat(strArrays69); + string str410 = ""; + if (prospecco.get_Email() != null) + { + str410 = string.Concat("
", prospecco.get_Email()); + } + string[] strArrays70 = new string[] { str371, "
"; + str371 = string.Concat(strArrays70); + } + str371 = string.Concat(str371, "

CLIENTE: "; + documento12[4] = prospecco.get_Nome(); + documento12[5] = "

CPF/CNPJ: "; + documento12[8] = prospecco.get_Documento(); + documento12[9] = "

CONTATOS: "; + str36 = (string.IsNullOrEmpty(str409) ? "-" : str409); + strArrays69[4] = str36; + strArrays69[5] = "

EMAILS: "; + str38 = (string.IsNullOrEmpty(str410) ? "-" : str410); + strArrays70[4] = str38; + strArrays70[5] = "

"); + string str411 = str371; + str31 = (this.ClientePorPaginaVisibility != Visibility.Visible || !this.ClientePorPagina || !this.ClientePorPaginaEnabled ? "" : "
"); + str371 = string.Concat(str411, str31); + if (this.SelectedTipoExtrato != null) + { + num19 = 0; + string[] strArrays71 = new string[] { str371, "
"; + str371 = string.Concat(strArrays71); + string[] strArrays72 = new string[] { str371, ""; + str371 = string.Concat(strArrays72); + str371 = string.Concat(str371, "

VIGÊNCIA FINAL: "; + clienteDesde = prospecco.get_VigenciaFinal(); + if (!clienteDesde.HasValue) + { + shortDateString2 = "-"; + } + else + { + clienteDesde = prospecco.get_VigenciaFinal(); + if (clienteDesde.HasValue) + { + shortDateString2 = clienteDesde.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString2 = null; + } + } + strArrays71[4] = shortDateString2; + strArrays71[5] = "

VENDEDOR: "; + str34 = (prospecco.get_Vendedor() == null ? "-" : prospecco.get_Vendedor().get_Nome()); + strArrays72[4] = str34; + strArrays72[5] = "

"); + } + else + { + variable9 = null; + return; + } + } + } + } + DateTime dateTime = Funcoes.GetNetworkTime(); + string[] shortDateString20 = new string[] { str371, "

", Recursos.Usuario.get_Nome(), " - ", null, null }; + date = dateTime.Date; + shortDateString20[4] = date.ToShortDateString(); + shortDateString20[5] = "
"; + str371 = string.Concat(shortDateString20); + string tempPath1 = Path.GetTempPath(); + string str412 = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.html", tempPath1, (TipoExtrato)0, dateTime); + if (!pdf) + { + StreamWriter streamWriter1 = new StreamWriter(str412, true, Encoding.UTF8); + streamWriter1.Write(str371); + streamWriter1.Close(); + } + else + { + str412 = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.pdf", tempPath1, (TipoExtrato)0, dateTime); + File.WriteAllBytes(str412, (new NRecoHtmlToPdfConverter()).GeneratePdf(str371)); + } + Process.Start(str412); + if (this.Documentos != null && this.Documentos.Count > 1) + { + ExtratosViewModel extratosViewModel1 = this; + str17 = (this.ExtratoResumido ? " RESUMIDO" : ""); + if (this.Documentos != null) + { + str18 = (this.Documentos.Count > 1 ? string.Format("DE {0} DOCUMENTOS", this.Documentos.Count) : string.Format("DO DOCUMENTO {0}", this.Documentos[0].get_Id())); + } + else + { + str18 = ""; + } + string str413 = string.Concat("GEROU O EXTRATO", str17, " ", str18); + long num24 = (long)0; + TipoTela? nullable5 = new TipoTela?(23); + List documentos3 = this.Documentos; + extratosViewModel1.RegistrarAcao(str413, num24, nullable5, string.Concat("IDS DOS DOCUMENTOS:\n", string.Join("\n", + from x in documentos3 + select x.get_Id()), this.GerarOpcoes())); + } + if (this.Prospeccoes != null && this.Prospeccoes.Count > 1) + { + ExtratosViewModel extratosViewModel2 = this; + str15 = (this.ExtratoResumido ? " RESUMIDO" : ""); + if (this.Prospeccoes != null) + { + str16 = (this.Prospeccoes.Count > 1 ? string.Format("DE {0} PROSPECÇÕES", this.Prospeccoes.Count) : string.Format("DA PROSPÇÃO{0}", this.Prospeccoes[0].get_Id())); + } + else + { + str16 = ""; + } + string str414 = string.Concat("GEROU O EXTRATO", str15, " ", str16); + long num25 = (long)0; + TipoTela? nullable6 = new TipoTela?(23); + List prospeccoes = this.Prospeccoes; + extratosViewModel2.RegistrarAcao(str414, num25, nullable6, string.Concat("IDS DOS DOCUMENTOS:\n", string.Join("\n", + from x in prospeccoes + select x.get_Id()), this.GerarOpcoes())); + } + this.Documentos = null; + this.Clientes = null; + this.Prospeccoes = null; + nums = null; + } + variable9 = null; + return; + Label3: + item1 = item; + auto = await (new ItemServico()).BuscaAuto(item.get_Id()); + item1.set_Auto(auto); + item1 = null; + string[] modelo = new string[26]; + modelo[0] = str371; + modelo[1] = "

"; + modelo[4] = string.Format("ITEM {0}: ", item.get_Ordem()); + modelo[5] = "
"; + Fabricante fabricante = item.get_Auto().get_Fabricante(); + if (fabricante != null) + { + descricao = fabricante.get_Descricao(); + } + else + { + descricao = null; + } + modelo[6] = descricao; + modelo[7] = " "; + modelo[8] = item.get_Auto().get_Modelo(); + modelo[9] = " ("; + modelo[10] = item.get_Auto().get_AnoFabricacao(); + modelo[11] = "/"; + modelo[12] = item.get_Auto().get_AnoModelo(); + modelo[13] = ")
PLACA: "; + modelo[14] = item.get_Auto().get_Placa(); + modelo[15] = ", CHASSI: "; + modelo[16] = item.get_Auto().get_Chassi(); + modelo[17] = "
C.I.: "; + modelo[18] = item.get_Auto().get_Ci(); + modelo[19] = ", RENAVAM: "; + modelo[20] = item.get_Auto().get_Renavam(); + modelo[21] = ", CEP PERNOITE: "; + modelo[22] = item.get_Auto().get_CepPernoite(); + modelo[23] = "
FINANCIADO: "; + str112 = (item.get_Auto().get_Financiado().GetValueOrDefault() ? "SIM" : "NÃO"); + modelo[24] = str112; + modelo[25] = "

"; + str371 = string.Concat(modelo); + goto Label9; + Label4: + string[] descricao4 = new string[] { str371, "

"; + descricao4[4] = string.Format("ITEM {0}: ", item.get_Ordem()); + descricao4[5] = ""; + descricao4[6] = item.get_Descricao(); + descricao4[7] = "

QTDE SINISTRO(S): "; + numeroParcela = item.get_Sinistros().Count; + descricao4[8] = numeroParcela.ToString(); + descricao4[9] = "

"; + str371 = string.Concat(descricao4); + goto Label9; + Label6: + item1 = item; + auto = await (new ItemServico()).BuscaAuto(item.get_Id()); + item1.set_Auto(auto); + item1 = null; + string[] anoFabricacao = new string[26]; + anoFabricacao[0] = str371; + anoFabricacao[1] = "

"; + anoFabricacao[4] = string.Format("ITEM {0}: ", item.get_Ordem()); + anoFabricacao[5] = "
"; + Fabricante fabricante1 = item.get_Auto().get_Fabricante(); + if (fabricante1 != null) + { + descricao1 = fabricante1.get_Descricao(); + } + else + { + descricao1 = null; + } + anoFabricacao[6] = descricao1; + anoFabricacao[7] = " "; + anoFabricacao[8] = item.get_Auto().get_Modelo(); + anoFabricacao[9] = " ("; + anoFabricacao[10] = item.get_Auto().get_AnoFabricacao(); + anoFabricacao[11] = "/"; + anoFabricacao[12] = item.get_Auto().get_AnoModelo(); + anoFabricacao[13] = ")
PLACA: "; + anoFabricacao[14] = item.get_Auto().get_Placa(); + anoFabricacao[15] = ", CHASSI: "; + anoFabricacao[16] = item.get_Auto().get_Chassi(); + anoFabricacao[17] = "
C.I.: "; + anoFabricacao[18] = item.get_Auto().get_Ci(); + anoFabricacao[19] = ", RENAVAM: "; + anoFabricacao[20] = item.get_Auto().get_Renavam(); + anoFabricacao[21] = ", CEP PERNOITE: "; + anoFabricacao[22] = item.get_Auto().get_CepPernoite(); + anoFabricacao[23] = "
FINANCIADO: "; + str296 = (item.get_Auto().get_Financiado().GetValueOrDefault() ? "SIM" : "NÃO"); + anoFabricacao[24] = str296; + anoFabricacao[25] = "

"; + str371 = string.Concat(anoFabricacao); + goto Label10; + Label7: + string[] descricao5 = new string[] { str371, "

"; + descricao5[4] = string.Format("ITEM {0}: ", item.get_Ordem()); + descricao5[5] = ""; + descricao5[6] = item.get_Descricao(); + descricao5[7] = "

"; + str371 = string.Concat(descricao5); + goto Label10; + } + + public string GerarOpcoes() + { + string str = ""; + if (this.ClienteVisibility && this.ObsCliente && this.ObsClienteEnabled) + { + str = string.Concat(str, "\nOBSERVAÇÕES DO CLIENTE"); + } + if (this.ClientePorPaginaVisibility == Visibility.Visible && this.ClientePorPagina && this.ClientePorPaginaEnabled) + { + str = string.Concat(str, "\nSEPARAR CLIENTES POR PÁGINA"); + } + if (this.DocumentoVisibility) + { + if (this.ComissaoDocumentoEnabled && this.ComissaoDocumento) + { + str = string.Concat(str, "\nCOMISSÕES DO DOCUMENTO"); + } + if (this.ObsApoliceEnabled && this.ObsApolice) + { + str = string.Concat(str, "\nOBSERVAÇÕES DA APÓLICE"); + } + if (this.SegurosVigentesVisibility == Visibility.Visible && this.SegurosVigentes) + { + str = string.Concat(str, "\nAPENAS SEGUROS VIGENTES"); + } + } + if (this.ItemVisibility) + { + if (this.SelecionarItensVisibility == Visibility.Visible && this.SelecionarItens) + { + str = string.Concat(str, "\nSELECIONAR ITENS"); + } + if (this.BeneficiariosItensEnabled && this.BeneficiariosItens) + { + str = string.Concat(str, "\nBENEFICIÁRIOS DOS ITENS"); + } + if (this.ObsItemEnabled && this.ObsItem) + { + str = string.Concat(str, "\nOBSERVAÇÕES DO ITEM"); + } + if (this.SepararPaginaEnabled && this.SepararPagina) + { + str = string.Concat(str, "\nSEPARAR ITENS POR PÁGINA"); + } + } + if (this.PerfilCondutor && this.PerfilVisibility && this.PerfilCondutorEnabled) + { + str = string.Concat(str, "\nPERFIL DO CONDUTOR"); + } + if (string.IsNullOrWhiteSpace(str)) + { + return ""; + } + return string.Concat("\n\nOPÇÕES:", str); + } + + public async Task PrepararExtrato(List clientes, List documentos, List prospeccoes, Relatorio? tipoRelatorio = null, List selecionadosDoc = null, List selecionadosPros = null, bool pdf = false) + { + ObservableCollection observableCollection; + ObservableCollection observableCollection1; + ObservableCollection observableCollection2; + ObservableCollection observableCollection3; + ObservableCollection observableCollection4; + bool count; + List documentos1; + bool flag; + List clientes1; + Cliente cliente; + Cliente cliente1; + List documentos2; + this.Carregando = true; + Relatorio? nullable = tipoRelatorio; + if (nullable.GetValueOrDefault() != 0 | !nullable.HasValue && tipoRelatorio.GetValueOrDefault() != 1) + { + if ((documentos == null || documentos.Count == 0) && (prospeccoes == null || prospeccoes.Count == 0)) + { + await base.ShowMessage("É NECESSÁRIO HAVER AO MENOS UM DOCUMENTO OU PROSPECÇÃO", "OK", "", false); + this.Carregando = false; + return; + } + else + { + List documentos3 = documentos; + if (documentos3 != null) + { + count = documentos3.Count > 200; + } + else + { + count = false; + } + if (!count) + { + List prospeccaos = prospeccoes; + if (prospeccaos != null) + { + flag = prospeccaos.Count > 200; + } + else + { + flag = false; + } + if (!flag) + { + goto Label1; + } + } + if (!await base.ShowMessage("A SELEÇÃO DE MUITOS EXTRATOS PODE DEMORAR MAIS DE 30 MINUTOS! CONTINUAR?", "SIM", "NÃO", false)) + { + this.Carregando = false; + return; + } + Label1: + switch (this.SelectedTipoExtrato) + { + case 0: + { + if (selecionadosDoc == null || selecionadosDoc.Count == 0) + { + await base.ShowMessage("É NECESSÁRIO HAVER AO MENOS UM DOCUMENTO SELECIONADO", "OK", "", false); + this.Carregando = false; + return; + } + else + { + clientes1 = new List(); + foreach (Documento documento in documentos) + { + cliente = await (new ClienteServico()).BuscarCliente(documento.get_Controle().get_Cliente().get_Id()); + cliente1 = cliente; + observableCollection = await this._clienteServico.BuscarEnderecosAsync(cliente.get_Id()); + cliente1.set_Enderecos(observableCollection); + cliente1 = null; + cliente1 = cliente; + observableCollection1 = await this._clienteServico.BuscarEmailsAsync(cliente.get_Id()); + cliente1.set_Emails(observableCollection1); + cliente1 = null; + cliente1 = cliente; + observableCollection2 = await this._clienteServico.BuscarTelefonesAsync(cliente.get_Id()); + cliente1.set_Telefones(observableCollection2); + cliente1 = null; + cliente1 = cliente; + observableCollection3 = await this._clienteServico.BuscarContatosAsync(cliente.get_Id()); + cliente1.set_Contatos(observableCollection3); + cliente1 = null; + cliente1 = cliente; + observableCollection4 = await this._clienteServico.BuscarVinculosAsync(cliente.get_Id()); + cliente1.set_Vinculos(observableCollection4); + cliente1 = null; + clientes1.Add(cliente); + cliente = null; + } + this.Clientes = clientes1; + this.Prospeccoes = prospeccoes; + break; + } + } + case 1: + { + if ((selecionadosDoc == null || selecionadosDoc.Count == 0) && (selecionadosPros == null || selecionadosPros.Count == 0)) + { + await base.ShowMessage("É NECESSÁRIO HAVER AO MENOS UM DOCUMENTO SELECIONADO", "OK", "", false); + this.Carregando = false; + return; + } + else + { + this.Documentos = new List(); + this.Prospeccoes = new List(); + if (selecionadosDoc != null) + { + foreach (long num in selecionadosDoc) + { + Documento documento1 = await (new ApoliceServico()).BuscarApoliceAsync(num, false, true); + Documento documento2 = documento1; + documentos1 = (!this.SomenteEndossos || documento2.get_Ordem() == 1 ? new List() + { + documento2 + } : new List()); + List documentos4 = documentos1; + if (this.SomenteEndossos) + { + IEnumerable documentos5 = documento2.get_Controle().get_Documentos().Where((Documento x) => { + if (x.get_Excluido() || x.get_Ordem() == 0) + { + return false; + } + return !documentos4.Any((Documento y) => y.get_Id() == x.get_Id()); + }); + foreach (Documento documento3 in documentos5) + { + documento3.set_Sinistro(documento2.get_Sinistro()); + } + documentos4.AddRange(documentos5); + } + else if (this.Endossos) + { + IEnumerable documentos6 = documento2.get_Controle().get_Documentos().Where((Documento x) => { + if (x.get_Id() == documento2.get_Id()) + { + return false; + } + return !x.get_Excluido(); + }); + foreach (Documento documento4 in documentos6) + { + documento4.set_Sinistro(documento2.get_Sinistro()); + } + documentos4.AddRange(documentos6); + } + if (documento2.get_Controle().get_Documentos().Any((Documento x) => { + if (x.get_Id() == documento2.get_Id() || x.get_Excluido()) + { + return false; + } + return x.get_Ordem() > documento2.get_Ordem(); + })) + { + documento2.set_TemEndosso(true); + } + List configuracoes = Recursos.Configuracoes; + if (configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 31) && documento2.get_TemEndosso()) + { + Documento documento5 = documento2; + IList documentos7 = documento2.get_Controle().get_Documentos(); + IEnumerable excluido = + from x in documentos7 + where !x.get_Excluido() + select x; + documento5.set_PremioTotal(excluido.Sum((Documento x) => x.get_PremioTotal())); + Documento documento6 = documento2; + IList documentos8 = documento2.get_Controle().get_Documentos(); + IEnumerable excluido1 = + from x in documentos8 + where !x.get_Excluido() + select x; + documento6.set_Iof(excluido1.Sum((Documento x) => x.get_Iof())); + Documento documento7 = documento2; + IList documentos9 = documento2.get_Controle().get_Documentos(); + IEnumerable excluido2 = + from x in documentos9 + where !x.get_Excluido() + select x; + documento7.set_Custo(excluido2.Sum((Documento x) => x.get_Custo())); + Documento documento8 = documento2; + IList documentos10 = documento2.get_Controle().get_Documentos(); + IEnumerable excluido3 = + from x in documentos10 + where !x.get_Excluido() + select x; + documento8.set_PremioLiquido(excluido3.Sum((Documento x) => x.get_PremioLiquido())); + Documento documento9 = documento2; + IList documentos11 = documento2.get_Controle().get_Documentos(); + IEnumerable excluido4 = + from x in documentos11 + where !x.get_Excluido() + select x; + documento9.set_PremioAdicional(excluido4.Sum((Documento x) => x.get_PremioAdicional())); + } + List documentos12 = this.Documentos; + List documentos13 = documentos4; + documentos12.AddRange(( + from x in documentos13 + orderby x.get_Ordem() + select x).ToList()); + } + } + if (selecionadosPros != null) + { + foreach (long selecionadosPro in selecionadosPros) + { + Prospeccao prospeccao = await (new ProspeccaoServico()).BuscarProspeccao(selecionadosPro); + this.Prospeccoes.Add(prospeccao); + } + } + if (this.SelecionarItensVisibility == Visibility.Visible && this.SelecionarItens && this.Documentos != null && this.Documentos.Count > 0) + { + ObservableCollection observableCollection5 = await base.ShowSelecionarItensDialog(this.Documentos.First().get_Controle().get_Id()); + ExtratosViewModel list = this; + ObservableCollection observableCollection6 = observableCollection5; + list._itensSelecionados = ( + from x in observableCollection6 + where x.get_Selecionado() + select x).ToList(); + } + if (this.Documentos != null && this.Documentos.Count != 0 || this.Prospeccoes != null && this.Prospeccoes.Count != 0) + { + break; + } + if (!this.SomenteEndossos) + { + await base.ShowMessage("É NECESSÁRIO HAVER AO MENOS UM DOCUMENTO OU PROSPECÇÃO SELECIONADO", "OK", "", false); + } + else + { + await base.ShowMessage("É NECESSÁRIO HAVER AO MENOS UM ENDOSSO OU PROSPECÇÃO SELECIONADO", "OK", "", false); + } + this.Carregando = false; + return; + } + } + case 2: + { + documentos2 = new List(); + ApoliceServico apoliceServico = new ApoliceServico(); + long id = documentos.First().get_Controle().get_Cliente().get_Id(); + FiltroStatusDocumento statusSelecionado = MainViewModel.StatusSelecionado; + List vendedorUsuarios = await base.VerificaVinculoVendedor(Recursos.Usuario); + ObservableCollection observableCollection7 = await apoliceServico.BuscarApolicesAsync(id, statusSelecionado, vendedorUsuarios); + apoliceServico = null; + this.Documentos = new List(observableCollection7); + foreach (Documento documento10 in this.Documentos) + { + foreach (Documento documento11 in documento10.get_Controle().get_Documentos()) + { + if (documento11.get_Tipo() != 1) + { + continue; + } + documentos2.Add(documento11); + documento10.set_TemEndosso(true); + } + } + this.Documentos.AddRange(documentos2); + break; + } + } + documentos2 = null; + clientes1 = null; + } + } + else if (clientes == null || clientes.Count == 0) + { + await base.ShowMessage("É NECESSÁRIO HAVER AO MENOS UM CLIENTE", "OK", "", false); + this.Carregando = false; + return; + } + else + { + if (clientes.Count > 200) + { + if (!await base.ShowMessage("A SELEÇÃO DE MUITOS EXTRATOS PODE DEMORAR MAIS DE 30 MINUTOS! CONTINUAR?", "SIM", "NÃO", false)) + { + this.Carregando = false; + return; + } + } + clientes1 = new List(); + List clientesAtivosInativos = clientes; + foreach (ClientesAtivosInativos clientesAtivosInativo in + from x in clientesAtivosInativos + where x.get_Selecionado() + select x) + { + cliente = await (new ClienteServico()).BuscarCliente(clientesAtivosInativo.get_Id()); + cliente1 = cliente; + observableCollection = await this._clienteServico.BuscarEnderecosAsync(cliente.get_Id()); + cliente1.set_Enderecos(observableCollection); + cliente1 = null; + cliente1 = cliente; + observableCollection1 = await this._clienteServico.BuscarEmailsAsync(cliente.get_Id()); + cliente1.set_Emails(observableCollection1); + cliente1 = null; + cliente1 = cliente; + observableCollection2 = await this._clienteServico.BuscarTelefonesAsync(cliente.get_Id()); + cliente1.set_Telefones(observableCollection2); + cliente1 = null; + cliente1 = cliente; + observableCollection3 = await this._clienteServico.BuscarContatosAsync(cliente.get_Id()); + cliente1.set_Contatos(observableCollection3); + cliente1 = null; + cliente1 = cliente; + observableCollection4 = await this._clienteServico.BuscarVinculosAsync(cliente.get_Id()); + cliente1.set_Vinculos(observableCollection4); + cliente1 = null; + clientes1.Add(cliente); + cliente = null; + } + this.Clientes = clientes1; + clientes1 = null; + } + if (this.SegurosVigentesVisibility == Visibility.Visible && this.SegurosVigentes) + { + ExtratosViewModel extratosViewModel = this; + List documentos14 = this.Documentos; + extratosViewModel.Documentos = documentos14.Where((Documento x) => { + DateTime? vigencia2 = x.get_Vigencia2(); + DateTime dateTime = Funcoes.GetNetworkTime().Date.AddDays(-5); + if ((vigencia2.HasValue ? vigencia2.GetValueOrDefault() <= dateTime : true)) + { + vigencia2 = x.get_Vigencia2(); + if (vigencia2.HasValue) + { + return false; + } + } + return x.get_Situacao() != 7; + }).ToList(); + } + await this.Gerar(tipoRelatorio, pdf); + this.Carregando = false; + } + + private void RelacaoApolices() + { + this.SetAllFalse(); + this.ComissaoDocumentoEnabled = true; + this.PerfilCondutorEnabled = true; + } + + private void SetAllFalse() + { + this.ObsClienteEnabled = false; + this.ClientePorPaginaEnabled = false; + this.ComissaoDocumentoEnabled = false; + this.ObsApoliceEnabled = false; + this.BeneficiariosItensEnabled = false; + this.ObsItemEnabled = false; + this.SepararPaginaEnabled = false; + this.CoberturasEnabled = false; + this.PerfilCondutorEnabled = false; + this.EndossoEnabled = false; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/ImpostoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/ImpostoViewModel.cs new file mode 100644 index 0000000..e2ec7d5 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/ImpostoViewModel.cs @@ -0,0 +1,484 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class ImpostoViewModel : BaseViewModel + { + private bool _carregando; + + private bool _apelido; + + public int Tipo; + + private List _seguradoras; + + private List _ramos; + + private ObservableCollection _impostos = new ObservableCollection(); + + private Imposto _selectedImposto = new Imposto(); + + private Ramo _selectedRamo = new Ramo(); + + private Seguradora _selectedSeguradora = new Seguradora(); + + public bool Apelido + { + get + { + return this._apelido; + } + set + { + this._apelido = value; + base.OnPropertyChanged("Apelido"); + } + } + + public bool? Ativo { get; set; } = new bool?(true); + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.IsEnabled = !value; + base.OnPropertyChanged("Carregando"); + } + } + + public ObservableCollection Impostos + { + get + { + return this._impostos; + } + set + { + this._impostos = value; + base.OnPropertyChanged("Impostos"); + } + } + + public List Ramos + { + get + { + return this._ramos; + } + set + { + this._ramos = value; + base.OnPropertyChanged("Ramos"); + } + } + + public List Seguradoras + { + get + { + return this._seguradoras; + } + set + { + this._seguradoras = value; + base.OnPropertyChanged("Seguradoras"); + } + } + + public Imposto SelectedImposto + { + get + { + return this._selectedImposto; + } + set + { + long? nullable; + this._selectedImposto = value; + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedImposto"); + } + } + + public Ramo SelectedRamo + { + get + { + return this._selectedRamo; + } + set + { + this._selectedRamo = value; + base.OnPropertyChanged("SelectedRamo"); + } + } + + public Seguradora SelectedSeguradora + { + get + { + return this._selectedSeguradora; + } + set + { + this._selectedSeguradora = value; + base.OnPropertyChanged("SelectedSeguradora"); + } + } + + private ImpostoServico Servico + { + get; + } + + public ImpostoViewModel() + { + this.Servico = new ImpostoServico(); + this.Apelido = Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 6); + } + + public void AlterarImposto() + { + base.Alterar(true); + } + + public async Task Cancelar() + { + long id; + Imposto selectedImposto = this.SelectedImposto; + if (selectedImposto != null) + { + id = selectedImposto.get_Id(); + } + else + { + id = (long)0; + } + long num = id; + base.Alterar(false); + await this.Carregar(num); + } + + public async Task Carregar(int tipo, long id) + { + string str; + this.Tipo = tipo; + await base.PermissaoTela(56); + List list = Recursos.Seguradoras.Where((Seguradora x) => { + if (x.get_Ativo()) + { + return true; + } + if (tipo != 0) + { + return false; + } + return x.get_Id() == id; + }).OrderBy((Seguradora x) => { + if (!this.Apelido) + { + return x.get_Nome(); + } + return x.get_NomeSocial(); + }).ToList(); + Seguradora seguradora = new Seguradora(); + seguradora.set_Nome("TODAS SEGURADORAS"); + seguradora.set_NomeSocial("TODAS SEGURADORAS"); + seguradora.set_Id((long)0); + list.Insert(0, seguradora); + this.Seguradoras = list; + this.SelectedSeguradora = this.Seguradoras.First(); + IEnumerable ramos = Recursos.Ramos.Where((Ramo x) => { + if (x.get_Ativo()) + { + return true; + } + if (tipo != 1) + { + return false; + } + return x.get_Id() == id; + }); + List list1 = ( + from x in ramos + orderby x.get_Nome() + select x).ToList(); + Ramo ramo = new Ramo(); + ramo.set_Nome("TODOS OS RAMOS"); + ramo.set_Id((long)0); + list1.Insert(0, ramo); + this.Ramos = list1; + this.SelectedRamo = this.Ramos.First(); + str = (tipo == 1 ? string.Concat("O RAMO \"", this.Ramos.First((Ramo x) => x.get_Id() == id).get_Nome(), "\"") : string.Concat("A SEGURADORA \"", this.Seguradoras.First((Seguradora x) => x.get_Id() == id).get_Nome(), "\"")); + string str1 = str; + base.RegistrarAcao(string.Concat("ACESSOU IMPOSTOS D", str1), id, new TipoTela?(56), string.Format("ID: {0}", id)); + List impostos = await this.Servico.Buscar(new bool?(true)); + if (tipo == 1) + { + impostos = impostos.Where((Imposto x) => { + if (x.get_Ramo() == null || x.get_Ramo().get_Id() != id) + { + return false; + } + return x.get_Seguradora() == null; + }).ToList(); + this.SelectedRamo = this.Ramos.Find((Ramo x) => x.get_Id() == id); + } + else + { + impostos = impostos.Where((Imposto x) => { + if (x.get_Seguradora() == null || x.get_Seguradora().get_Id() != id) + { + return false; + } + return x.get_Ramo() == null; + }).ToList(); + this.SelectedSeguradora = this.Seguradoras.Find((Seguradora x) => x.get_Id() == id); + } + ImpostoViewModel observableCollection = this; + List impostos1 = impostos; + observableCollection.Impostos = new ObservableCollection( + from x in impostos1 + orderby x.get_Ativo() descending + select x); + this.SelectedImposto = this.Impostos.FirstOrDefault(); + } + + public async Task Carregar(long id = 0L) + { + Imposto imposto; + List list = await this.Servico.Buscar(this.Ativo); + if (this.SelectedSeguradora.get_Id() == 0) + { + List impostos = list; + list = ( + from x in impostos + where x.get_Seguradora() == null + select x).ToList(); + } + if (this.SelectedSeguradora.get_Id() > (long)0) + { + list = list.Where((Imposto x) => { + if (x.get_Seguradora() == null) + { + return false; + } + return x.get_Seguradora().get_Id() == this.SelectedSeguradora.get_Id(); + }).ToList(); + } + if (this.SelectedRamo.get_Id() == 0) + { + List impostos1 = list; + list = ( + from x in impostos1 + where x.get_Ramo() == null + select x).ToList(); + } + if (this.SelectedRamo.get_Id() > (long)0) + { + list = list.Where((Imposto x) => { + if (x.get_Ramo() == null) + { + return false; + } + return x.get_Ramo().get_Id() == this.SelectedRamo.get_Id(); + }).ToList(); + } + this.Impostos = new ObservableCollection(list.Where((Imposto x) => { + if (!this.Ativo.HasValue) + { + return true; + } + return x.get_Ativo() == this.Ativo.Value; + }).ToList()); + ImpostoViewModel impostoViewModel = this; + imposto = (id == 0 ? this.Impostos.FirstOrDefault() : this.Impostos.FirstOrDefault((Imposto x) => x.get_Id() == id)); + impostoViewModel.SelectedImposto = imposto; + } + + public void Incluir() + { + Seguradora selectedSeguradora; + Ramo selectedRamo; + Imposto imposto = new Imposto(); + if (this.SelectedSeguradora.get_Id() > (long)0) + { + selectedSeguradora = this.SelectedSeguradora; + } + else + { + selectedSeguradora = null; + } + imposto.set_Seguradora(selectedSeguradora); + if (this.SelectedRamo.get_Id() > (long)0) + { + selectedRamo = this.SelectedRamo; + } + else + { + selectedRamo = null; + } + imposto.set_Ramo(selectedRamo); + imposto.set_Ativo(true); + this.SelectedImposto = imposto; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + string str1; + string str2; + object obj; + string str3; + List> keyValuePairs1 = this.SelectedImposto.Validate(); + keyValuePairs1.AddRange(this.Validate(this.SelectedImposto)); + if (keyValuePairs1.Count <= 0) + { + str = (this.SelectedImposto.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str3 = str; + Imposto imposto = await this.Servico.Salvar(this.SelectedImposto); + if (this.Servico.Sucesso) + { + str1 = (imposto.get_Seguradora() == null ? "TODAS AS SEGURADORAS" : string.Concat(" SEGURADORA ", imposto.get_Seguradora().get_Nome())); + string str4 = str1; + str2 = (imposto.get_Ramo() == null ? "TODOS OS RAMOS" : string.Concat(" RAMO ", imposto.get_Ramo().get_Nome())); + string str5 = str2; + string str6 = string.Concat(" ", str4, " E ", str5); + ImpostoViewModel impostoViewModel = this; + string str7 = string.Concat(str3, " IMPOSTO PARA ", str6); + long id = imposto.get_Id(); + TipoTela? nullable = new TipoTela?(31); + object[] ir = new object[] { imposto.get_Id(), str4, str5, null, null, null, null, null }; + obj = (imposto.get_Ativo() ? "ATIVO" : "INATIVO"); + ir[3] = obj; + ir[4] = imposto.get_Ir(); + ir[5] = imposto.get_Iss(); + ir[6] = imposto.get_Outros(); + ir[7] = imposto.get_Desconto(); + impostoViewModel.RegistrarAcao(str7, id, nullable, string.Format("ID: {0}{1}{2}\nSTATUS: {3}\nIR: {4:p2}\nISS: {5:p2}\nOUTROS: {6:p2}\nDESCONTO: {7:p2}", ir)); + base.Alterar(false); + await this.Carregar(imposto.get_Id()); + keyValuePairs = null; + } + else + { + keyValuePairs = new List>() + { + new KeyValuePair("GRAVAR", "HOUVE UM ERRO AO SALVAR O IMPOSTO SELECIONADO.") + }; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str3 = null; + return keyValuePairs; + } + + public List> Validate(Imposto imposto) + { + List> keyValuePairs = new List>(); + if (imposto == null) + { + return keyValuePairs; + } + if (imposto.get_Ativo() && this.Impostos.Any((Imposto x) => { + long? nullable; + long? nullable1; + long? nullable2; + long? nullable3; + long? nullable4; + if (x.get_Id() != imposto.get_Id()) + { + Seguradora seguradora = x.get_Seguradora(); + if (seguradora != null) + { + nullable1 = new long?(seguradora.get_Id()); + } + else + { + nullable = null; + nullable1 = nullable; + } + long? nullable5 = nullable1; + Seguradora seguradora1 = imposto.get_Seguradora(); + if (seguradora1 != null) + { + nullable2 = new long?(seguradora1.get_Id()); + } + else + { + nullable = null; + nullable2 = nullable; + } + long? nullable6 = nullable2; + if (nullable5.GetValueOrDefault() == nullable6.GetValueOrDefault() & nullable5.HasValue == nullable6.HasValue) + { + Ramo ramo = x.get_Ramo(); + if (ramo != null) + { + nullable3 = new long?(ramo.get_Id()); + } + else + { + nullable = null; + nullable3 = nullable; + } + nullable6 = nullable3; + Ramo ramo1 = imposto.get_Ramo(); + if (ramo1 != null) + { + nullable4 = new long?(ramo1.get_Id()); + } + else + { + nullable = null; + nullable4 = nullable; + } + nullable5 = nullable4; + if (nullable6.GetValueOrDefault() == nullable5.GetValueOrDefault() & nullable6.HasValue == nullable5.HasValue) + { + return x.get_Ativo(); + } + } + } + return false; + })) + { + keyValuePairs.Add(new KeyValuePair("IMPOSTO DUPLICADO", "NÃO É POSSIVEL INSERIR UM NOVO PARAMETRO DE IMPOSTO, POIS JÁ EXISTEM PARAMETROS PARA A MESMA SEGURADORA E RAMO")); + } + return keyValuePairs.Distinct>().ToList>(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/InfoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/InfoViewModel.cs new file mode 100644 index 0000000..1352f12 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/InfoViewModel.cs @@ -0,0 +1,208 @@ +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class InfoViewModel : BaseViewModel + { + private ObservableCollection _contatos = new ObservableCollection(); + + private ObservableCollection _itens = new ObservableCollection(); + + private ObservableCollection _parcelas = new ObservableCollection(); + + private Gestor.Model.Domain.Seguros.Documento _documento; + + private Visibility _ocultarInfos; + + private bool _carregando; + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.IsEnabled = !value; + base.EnableMenu = !value; + base.OnPropertyChanged("Carregando"); + } + } + + public ObservableCollection Contatos + { + get + { + return this._contatos; + } + set + { + this._contatos = value; + base.OnPropertyChanged("Contatos"); + } + } + + public Gestor.Model.Domain.Seguros.Documento Documento + { + get + { + return this._documento; + } + set + { + this._documento = value; + base.OnPropertyChanged("Documento"); + } + } + + public ObservableCollection Itens + { + get + { + return this._itens; + } + set + { + this._itens = value; + base.OnPropertyChanged("Itens"); + } + } + + public Visibility OcultarInfos + { + get + { + return this._ocultarInfos; + } + set + { + this._ocultarInfos = value; + base.OnPropertyChanged("OcultarInfos"); + } + } + + public ObservableCollection Parcelas + { + get + { + return this._parcelas; + } + set + { + this._parcelas = value; + base.OnPropertyChanged("Parcelas"); + } + } + + public InfoViewModel(Gestor.Model.Domain.Seguros.Documento documento, bool ocultarInfos) + { + this.Documento = documento; + this.OcultarInfos = (ocultarInfos ? Visibility.Collapsed : Visibility.Visible); + this.Seleciona(); + } + + public string GerarObs(Gestor.Model.Domain.Seguros.Documento doc) + { + if (doc.get_Tipo() == 0) + { + return string.Format("CLIENTE: {0}{1}CÓDIGO: {2}{3}PROPOSTA: {4}{5}APÓLICE: {6}", new object[] { doc.get_Controle().get_Cliente().get_Nome(), Environment.NewLine, doc.get_Id(), Environment.NewLine, doc.get_Proposta(), Environment.NewLine, doc.get_Apolice() }); + } + return string.Format("CLIENTE: {0}{1}CÓDIGO: {2}{3}PROPOSTA: {4}{5}APÓLICE: {6}{7}PROPOSTA DE ENDOSSO: {8}{9}ENDOSSO: {10}", new object[] { doc.get_Controle().get_Cliente().get_Nome(), Environment.NewLine, doc.get_Id(), Environment.NewLine, doc.get_Proposta(), Environment.NewLine, doc.get_Apolice(), Environment.NewLine, doc.get_PropostaEndosso(), Environment.NewLine, doc.get_Endosso() }); + } + + public async void Seleciona() + { + bool controle; + ObservableCollection observableCollection; + this.Carregando = true; + if (this.Documento != null) + { + this.Documento = await (new ApoliceServico()).BuscarApoliceAsync(this.Documento.get_Id(), false, false); + } + if (this.OcultarInfos == Visibility.Visible && this.Documento != null) + { + ObservableCollection observableCollection1 = await (new ParcelaServico()).BuscarParcelasAsync(this.Documento.get_Id()); + InfoViewModel infoViewModel = this; + if (this.Documento.get_TipoRecebimento().GetValueOrDefault() == 2) + { + ObservableCollection observableCollection2 = observableCollection1; + observableCollection = new ObservableCollection( + from x in observableCollection2 + orderby x.get_VigenciaIncial() descending + select x); + } + else + { + observableCollection = observableCollection1; + } + infoViewModel.Parcelas = observableCollection; + } + Gestor.Model.Domain.Seguros.Documento documento = this.Documento; + if (documento != null) + { + controle = documento.get_Controle(); + } + else + { + controle = false; + } + if (controle) + { + this.Itens = await (new ItemServico()).BuscarItens(this.Documento.get_Controle().get_Id(), 0); + List contatos = new List(); + ClienteServico clienteServico = new ClienteServico(); + if (this.Documento.get_Controle().get_Cliente() != null) + { + ObservableCollection observableCollection3 = await clienteServico.BuscarTelefonesAsync(this.Documento.get_Controle().get_Cliente().get_Id()); + ObservableCollection observableCollection4 = await clienteServico.BuscarEmailsAsync(this.Documento.get_Controle().get_Cliente().get_Id()); + if (observableCollection3 != null) + { + List contatos1 = contatos; + ObservableCollection observableCollection5 = observableCollection3; + contatos1.AddRange(observableCollection5.Select((ClienteTelefone x) => { + Contato contato = new Contato(); + contato.set_Tipo(0); + contato.set_TipoTelefone(new TipoTelefone?(x.get_Tipo().GetValueOrDefault(1))); + contato.set_Numero(string.Concat(x.get_Prefixo(), " ", x.get_Numero())); + return contato; + }).Take(2).ToList()); + } + if (observableCollection4 != null) + { + List contatos2 = contatos; + ObservableCollection observableCollection6 = observableCollection4; + contatos2.AddRange(observableCollection6.Select((ClienteEmail x) => { + Contato contato = new Contato(); + contato.set_Tipo(1); + contato.set_TipoTelefone(null); + contato.set_Numero(x.get_Email()); + return contato; + }).Take(1).ToList()); + } + observableCollection3 = null; + } + this.Contatos = new ObservableCollection(contatos); + contatos = null; + clienteServico = null; + } + this.Carregando = false; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/LogAcaoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/LogAcaoViewModel.cs new file mode 100644 index 0000000..dec7ea3 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/LogAcaoViewModel.cs @@ -0,0 +1,262 @@ +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class LogAcaoViewModel : BaseViewModel + { + private RegistroAcao _log; + + private string _obs; + + public RegistroAcao Log + { + get + { + return this._log; + } + set + { + this._log = value; + base.OnPropertyChanged("Log"); + } + } + + public string Obs + { + get + { + return this._obs; + } + set + { + this._obs = value; + base.OnPropertyChanged("Obs"); + } + } + + private Gestor.Model.Common.Relatorio Relatorio + { + get; + set; + } + + public LogAcaoViewModel(RegistroAcao registro, Gestor.Model.Common.Relatorio relatorio) + { + this.Relatorio = relatorio; + this.CarregarLog(registro); + } + + private void CarregarLog(RegistroAcao registro) + { + string str; + string str1; + string str2; + string str3; + string str4; + string str5; + string str6; + string str7; + string str8; + string str9; + string str10; + if (registro.get_Tela().HasValue || string.IsNullOrEmpty(registro.get_Observacao()) || this.Relatorio == 25) + { + this.Log = registro; + this.Obs = registro.get_Observacao(); + return; + } + this.Log = registro; + Filtros filtro = JsonConvert.DeserializeObject(registro.get_Observacao()); + if (filtro.get_Seguradoras() == null || filtro.get_Seguradoras().Count == 0) + { + str = ""; + } + else + { + string[] newLine = new string[] { "SEGURADORAS FILTRADAS: ", Environment.NewLine, null, null, null }; + newLine[2] = string.Join(Environment.NewLine, + from x in Recursos.Seguradoras + where filtro.get_Seguradoras().Contains(x.get_Id()) + select x.get_NomeSocial()); + newLine[3] = Environment.NewLine; + newLine[4] = Environment.NewLine; + str = string.Concat(newLine); + } + string str11 = str; + if (filtro.get_Status() == null || filtro.get_Status().Count == 0) + { + str1 = ""; + } + else + { + string[] strArrays = new string[] { "STATUS FILTRADOS: ", Environment.NewLine, null, null, null }; + strArrays[2] = string.Join(Environment.NewLine, + from x in filtro.get_Status() + select (int)x); + strArrays[3] = Environment.NewLine; + strArrays[4] = Environment.NewLine; + str1 = string.Concat(strArrays); + } + string str12 = str1; + if (filtro.get_Ramos() == null || filtro.get_Ramos().Count == 0) + { + str2 = ""; + } + else + { + string[] newLine1 = new string[] { "RAMOS FILTRADOS: ", Environment.NewLine, null, null, null }; + newLine1[2] = string.Join(Environment.NewLine, + from x in Recursos.Ramos + where filtro.get_Ramos().Contains(x.get_Id()) + select x.get_Nome()); + newLine1[3] = Environment.NewLine; + newLine1[4] = Environment.NewLine; + str2 = string.Concat(newLine1); + } + string str13 = str2; + if (filtro.get_Vendedores() == null || filtro.get_Vendedores().Count == 0) + { + str3 = ""; + } + else + { + string[] strArrays1 = new string[] { "VENDEDORES FILTRADOS: ", Environment.NewLine, null, null, null }; + strArrays1[2] = string.Join(Environment.NewLine, + from x in Recursos.Vendedores + where filtro.get_Vendedores().Contains(x.get_Id()) + select x.get_Nome()); + strArrays1[3] = Environment.NewLine; + strArrays1[4] = Environment.NewLine; + str3 = string.Concat(strArrays1); + } + string str14 = str3; + if (filtro.get_Estipulantes() == null || filtro.get_Estipulantes().Count == 0) + { + str4 = ""; + } + else + { + string[] newLine2 = new string[] { "ESTIPULANTES FILTRADOS: ", Environment.NewLine, null, null, null }; + newLine2[2] = string.Join(Environment.NewLine, + from x in Recursos.Estipulantes + where filtro.get_Estipulantes().Contains(x.get_Id()) + select x.get_Nome()); + newLine2[3] = Environment.NewLine; + newLine2[4] = Environment.NewLine; + str4 = string.Concat(newLine2); + } + string str15 = str4; + if (filtro.get_Produtos() == null || filtro.get_Produtos().Count == 0) + { + str5 = ""; + } + else + { + string[] strArrays2 = new string[] { "PRODUTOS FILTRADOS: ", Environment.NewLine, null, null, null }; + strArrays2[2] = string.Join(Environment.NewLine, + from x in Recursos.Produtos + where filtro.get_Produtos().Contains(x.get_Id()) + select x.get_Nome()); + strArrays2[3] = Environment.NewLine; + strArrays2[4] = Environment.NewLine; + str5 = string.Concat(strArrays2); + } + string str16 = str5; + if (filtro.get_Negocio() == null || filtro.get_Negocio().Count == 0) + { + str6 = ""; + } + else + { + string[] newLine3 = new string[] { "TIPOS DE NEGÓCIOS FILTRADOS: ", Environment.NewLine, null, null, null }; + newLine3[2] = string.Join(Environment.NewLine, + from x in filtro.get_Negocio() + select (int)x); + newLine3[3] = Environment.NewLine; + newLine3[4] = Environment.NewLine; + str6 = string.Concat(newLine3); + } + string str17 = str6; + if (filtro.get_Usuarios() == null || filtro.get_Usuarios().Count == 0) + { + str7 = ""; + } + else + { + string[] strArrays3 = new string[] { "USUÁRIOS FILTRADOS: ", Environment.NewLine, null, null, null }; + strArrays3[2] = string.Join(Environment.NewLine, + from x in Recursos.Usuarios + where filtro.get_Usuarios().Contains(x.get_Id()) + select x.get_Nome()); + strArrays3[3] = Environment.NewLine; + strArrays3[4] = Environment.NewLine; + str7 = string.Concat(strArrays3); + } + string str18 = str7; + if (filtro.get_Telas() == null || filtro.get_Telas().Count == 0) + { + str8 = ""; + } + else + { + string[] newLine4 = new string[] { "TELAS FILTRADAS: ", Environment.NewLine, null, null, null }; + newLine4[2] = string.Join(Environment.NewLine, + from x in filtro.get_Telas() + select (int)x); + newLine4[3] = Environment.NewLine; + newLine4[4] = Environment.NewLine; + str8 = string.Concat(newLine4); + } + string str19 = str8; + if (filtro.get_Relatorios() == null || filtro.get_Relatorios().Count == 0) + { + str9 = ""; + } + else + { + string[] strArrays4 = new string[] { "RELATÓRIOS FILTRADOS: ", Environment.NewLine, null, null, null }; + strArrays4[2] = string.Join(Environment.NewLine, + from x in filtro.get_Relatorios() + select (int)x); + strArrays4[3] = Environment.NewLine; + strArrays4[4] = Environment.NewLine; + str9 = string.Concat(strArrays4); + } + string str20 = str9; + if (filtro.get_ParcelasEspeciais() != null) + { + if (!filtro.get_ParcelasEspeciais().Any((FiltroTipoParcela x) => x.get_Selecionado())) + { + goto Label1; + } + string[] newLine5 = new string[] { "TIPOS DE PARCELAS FILTRADOS: ", Environment.NewLine, null, null, null }; + newLine5[2] = string.Join(Environment.NewLine, + from x in filtro.get_ParcelasEspeciais() + select x.get_Tipo()); + newLine5[3] = Environment.NewLine; + newLine5[4] = Environment.NewLine; + str10 = string.Concat(newLine5); + goto Label0; + } + Label1: + str10 = ""; + Label0: + string str21 = str10; + string str22 = (filtro.get_IdEmpresa() == 0 ? "" : string.Concat(new string[] { "EMPRESA: ", Environment.NewLine, Recursos.Empresas.Find((Empresa x) => x.get_Id() == filtro.get_IdEmpresa()).get_Nome(), Environment.NewLine, Environment.NewLine })); + string.Format("PERÍODO DE {0:d} ATÉ {1:d}", filtro.get_Inicio(), filtro.get_Fim()); + this.Obs = string.Concat(new string[] { ValidationHelper.GetDescription(registro.get_Relatorio()), Environment.NewLine, Environment.NewLine, str22, str11, str13, str16, str14, str15, str12, str17, str21, str18, str19, str20 }); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/LogEmailViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/LogEmailViewModel.cs new file mode 100644 index 0000000..8a71635 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/LogEmailViewModel.cs @@ -0,0 +1,163 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class LogEmailViewModel : BaseSegurosViewModel + { + private readonly LogServico _servico; + + private Visibility _visibilityDetalhesLog = Visibility.Hidden; + + private bool _mostrarMensagem; + + private ObservableCollection _logs = new ObservableCollection(); + + private LogEmail _selectedLog; + + private List _lists = new List(); + + public List Lists + { + get + { + return this._lists; + } + set + { + this._lists = value; + base.OnPropertyChanged("Lists"); + } + } + + public ObservableCollection Logs + { + get + { + return this._logs; + } + set + { + this._logs = value; + base.OnPropertyChanged("Logs"); + } + } + + public bool MostrarMensagem + { + get + { + return this._mostrarMensagem; + } + set + { + this._mostrarMensagem = value; + base.OnPropertyChanged("MostrarMensagem"); + } + } + + public LogEmail SelectedLog + { + get + { + return this._selectedLog; + } + set + { + this._selectedLog = value; + this.Lists = this.SelectedLog.CriarLogEmail(); + base.OnPropertyChanged("SelectedLog"); + } + } + + public Visibility VisiblityDetalhesLog + { + get + { + return this._visibilityDetalhesLog; + } + set + { + this._visibilityDetalhesLog = value; + base.OnPropertyChanged("VisiblityDetalhesLog"); + } + } + + public LogEmailViewModel(TipoTela tela, long id, bool singleMode) + { + this._servico = new LogServico(); + this.VisiblityDetalhesLog = (Recursos.Configuracoes.Any((ConfiguracaoSistema c) => c.get_Configuracao() == 55) ? Visibility.Visible : Visibility.Hidden); + this.Seleciona(tela, id, singleMode); + } + + public void Imprimir() + { + string str = "LOGS
LOG ENVIO DE E-MAIL"; + foreach (TupleList list in this.Lists) + { + foreach (Tuple tuple in list.get_Tuples()) + { + if (tuple == list.get_Tuples().First>()) + { + str = string.Concat(str, ""); + str = string.Concat(str, "
DESCRIÇÃOE-MAIL ENVIADO
"); + } + bool flag = tuple.Item1.Contains("$"); + string[] item2 = new string[] { str, ""; + str = string.Concat(item2); + str = string.Concat(str, "
"; + item2[4] = tuple.Item1.Replace(" ", " ").Replace("$", ""); + item2[5] = ""; + item2[6] = tuple.Item2; + item2[7] = "
"); + } + } + str = string.Concat(str, "
"); + string tempPath = Path.GetTempPath(); + string str1 = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.html", tempPath, (TipoExtrato)0, Funcoes.GetNetworkTime()); + StreamWriter streamWriter = new StreamWriter(str1, true, Encoding.UTF8); + streamWriter.Write(str); + streamWriter.Close(); + Process.Start(str1); + } + + private async void Seleciona(TipoTela tela, long id, bool singleMode) + { + base.Loading(true); + if (!singleMode) + { + this.Logs = await this._servico.FindByEntity(tela, id); + } + else + { + this.Logs = await this._servico.FindById(id); + } + if (this.Logs.Count <= 0) + { + this.MostrarMensagem = true; + } + else + { + this.SelectedLog = this.Logs[0]; + } + base.Loading(false); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/LogSistemaAntigoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/LogSistemaAntigoViewModel.cs new file mode 100644 index 0000000..5c97aca --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/LogSistemaAntigoViewModel.cs @@ -0,0 +1,42 @@ +using Gestor.Application.ViewModels.Generic; +using System; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class LogSistemaAntigoViewModel : BaseViewModel + { + private string _descricao; + + private string _log; + + public string Descricao + { + get + { + return this._descricao; + } + set + { + this._descricao = value; + base.OnPropertyChanged("Descricao"); + } + } + + public string Log + { + get + { + return this._log; + } + set + { + this._log = value; + base.OnPropertyChanged("Log"); + } + } + + public LogSistemaAntigoViewModel() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/LogViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/LogViewModel.cs new file mode 100644 index 0000000..cdeb60c --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/LogViewModel.cs @@ -0,0 +1,1784 @@ +using ControlzEx; +using CsQuery.ExtensionMethods.Internal; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Validation; +using MaterialDesignThemes.Wpf; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class LogViewModel : BaseSegurosViewModel + { + private readonly LogServico _servico; + + private readonly TipoTela _tipoTela; + + private readonly long _id; + + private Visibility _visibilityDetalhesLog = Visibility.Hidden; + + private bool _mostrar; + + private bool _mostrarMensagem; + + private string _mostrarToolTip = "MOSTRAR TODAS OS CAMPOS"; + + private long _mostrarColuna = (long)120; + + private PackIcon _mostrarIcone; + + private ObservableCollection _logs; + + private string _currentDescription; + + private RegistroLog _selectedLog; + + private List _lists; + + private ObservableCollection _listsAlterados; + + private ObservableCollection _listsAdicionados; + + private ObservableCollection _listsRemovidos; + + private string _textAdicoes; + + public string CurrentDescription + { + get + { + return this._currentDescription; + } + set + { + this._currentDescription = value; + base.OnPropertyChanged("CurrentDescription"); + } + } + + public List Lists + { + get + { + return this._lists; + } + set + { + this._lists = value; + this.SetListaFiltrada(value); + base.OnPropertyChanged("Lists"); + } + } + + public ObservableCollection ListsAdicionados + { + get + { + return this._listsAdicionados; + } + set + { + this._listsAdicionados = value; + base.OnPropertyChanged("ListsAdicionados"); + } + } + + public ObservableCollection ListsAlterados + { + get + { + return this._listsAlterados; + } + set + { + this._listsAlterados = value; + base.OnPropertyChanged("ListsAlterados"); + } + } + + public ObservableCollection ListsRemovidos + { + get + { + return this._listsRemovidos; + } + set + { + this._listsRemovidos = value; + if (this.ListsAlterados != null || this.ListsAdicionados != null || value != null) + { + this.MostrarMensagem = false; + } + else + { + this.MostrarMensagem = true; + } + base.OnPropertyChanged("ListsRemovidos"); + } + } + + public ObservableCollection Logs + { + get + { + return this._logs; + } + set + { + this._logs = value; + base.OnPropertyChanged("Logs"); + } + } + + public bool Mostrar + { + get + { + return this._mostrar; + } + set + { + this._mostrar = value; + if (!value) + { + this.MostrarColuna = (long)240; + this.MostrarToolTip = "MOSTRAR TODOS OS CAMPOS"; + PackIcon packIcon = new PackIcon(); + packIcon.set_Kind(1497); + this.MostrarIcone = packIcon; + } + else + { + this.MostrarColuna = (long)240; + this.MostrarToolTip = "ESCONDER CAMPOS INALTERADOS"; + PackIcon packIcon1 = new PackIcon(); + packIcon1.set_Kind(1492); + this.MostrarIcone = packIcon1; + } + base.OnPropertyChanged("Mostrar"); + } + } + + public long MostrarColuna + { + get + { + return this._mostrarColuna; + } + set + { + this._mostrarColuna = value; + base.OnPropertyChanged("MostrarColuna"); + } + } + + public PackIcon MostrarIcone + { + get + { + return this._mostrarIcone; + } + set + { + this._mostrarIcone = value; + base.OnPropertyChanged("MostrarIcone"); + } + } + + public bool MostrarMensagem + { + get + { + return this._mostrarMensagem; + } + set + { + this._mostrarMensagem = value; + base.OnPropertyChanged("MostrarMensagem"); + } + } + + public string MostrarToolTip + { + get + { + return this._mostrarToolTip; + } + set + { + this._mostrarToolTip = value; + base.OnPropertyChanged("MostrarToolTip"); + } + } + + public RegistroLog SelectedLog + { + get + { + return this._selectedLog; + } + set + { + List tupleLists; + ObservableCollection> observableCollection; + List.Enumerator enumerator; + this._selectedLog = value; + List tupleLists1 = new List(); + try + { + if (!value.get_ModeloNovo()) + { + switch (this._tipoTela) + { + case 1: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 2: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(base.Restricao(14)); + break; + } + case 3: + { + Item item = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()); + if (item.get_Aeronautico() != null) + { + tupleLists1 = Aeronautico.Log(item); + break; + } + else if (item.get_Auto() != null) + { + tupleLists1 = Auto.Log(item); + break; + } + else if (item.get_Granizo() != null) + { + tupleLists1 = Granizo.Log(item); + break; + } + else if (item.get_Patrimonial() != null) + { + tupleLists1 = Patrimonial.Log(item); + break; + } + else if (item.get_RiscosDiversos() == null) + { + if (item.get_Vida() == null) + { + break; + } + tupleLists1 = Vida.Log(item); + break; + } + else + { + tupleLists1 = RiscosDiversos.Log(item); + break; + } + } + case 4: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 5: + { + try + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(base.Restricao(14), base.Restricao(95)); + break; + } + catch + { + tupleLists1 = LogViewModel.DefaultLog(this.SelectedLog.get_Descricao(), this.SelectedLog.get_Acao()); + break; + } + break; + } + case 6: + case 8: + case 20: + case 21: + case 23: + case 25: + case 27: + case 32: + case 35: + case 39: + case 40: + case 44: + case 47: + case 49: + case 50: + case 51: + case 53: + { + tupleLists1 = LogViewModel.DefaultLog(this.SelectedLog.get_Descricao(), this.SelectedLog.get_Acao()); + break; + } + case 7: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 9: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 10: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 11: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 12: + { + Ramo ramo = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()); + List list = ( + from x in Recursos.Coberturas + where x.get_IdRamo() == ramo.get_Id() + orderby x.get_Padrao() descending, x.get_Descricao() + select x).ToList(); + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(list); + break; + } + case 13: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 14: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 15: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 16: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 17: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 18: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 19: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 22: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 24: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 26: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 28: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 29: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 30: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 31: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 33: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 34: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 36: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 37: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(base.Restricao(14), base.Restricao(95)); + break; + } + case 38: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 41: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 42: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 43: + { + List>>>>> tuples = JsonConvert.DeserializeObject>>>>>>(this.SelectedLog.get_Descricao()); + tupleLists = new List(); + foreach (Tuple>>>> tuple in tuples) + { + observableCollection = new ObservableCollection>() + { + new Tuple(string.Concat(tuple.Item1, "$"), "", "") + }; + foreach (Tuple>> item2 in tuple.Item2) + { + observableCollection.Add(new Tuple(string.Concat(" ", item2.Item1, "$"), "", "")); + foreach (Tuple item21 in item2.Item2) + { + observableCollection.Add(new Tuple(string.Concat(" ", item21.Item1), item21.Item2, "")); + } + } + TupleList tupleList = new TupleList(); + tupleList.set_Tuples(observableCollection); + tupleLists.Add(tupleList); + } + enumerator = tupleLists.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + tupleLists1.Add(enumerator.Current); + } + break; + } + finally + { + ((IDisposable)enumerator).Dispose(); + } + break; + } + case 45: + { + List vendedors = JsonConvert.DeserializeObject>(this.SelectedLog.get_Descricao()); + tupleLists = new List(); + observableCollection = new ObservableCollection>() + { + new Tuple("VENDEDORES VINCULADOS$", "", "") + }; + foreach (Vendedor vendedor in vendedors) + { + observableCollection.Add(new Tuple(string.Format(" VENDEDOR {0}", vendedors.IndexOf(vendedor) + 1), vendedor.get_Nome(), "")); + } + TupleList tupleList1 = new TupleList(); + tupleList1.set_Tuples(observableCollection); + tupleLists.Add(tupleList1); + enumerator = tupleLists.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + tupleLists1.Add(enumerator.Current); + } + break; + } + finally + { + ((IDisposable)enumerator).Dispose(); + } + break; + } + case 46: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 48: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 52: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 54: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 55: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 56: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + default: + { + goto case 53; + } + } + } + else + { + switch (value.get_Acao()) + { + case 0: + case 2: + { + tupleLists1 = JsonConvert.DeserializeObject>(this.SelectedLog.get_Descricao()).LogList(base.Restricao(14)); + break; + } + case 1: + { + tupleLists1 = JsonConvert.DeserializeObject>(this.SelectedLog.get_Descricao()).LogList(base.Restricao(14)); + break; + } + } + } + } + catch (Exception exception) + { + } + this.Lists = tupleLists1; + base.OnPropertyChanged("SelectedLog"); + } + } + + public string TextAdicoes + { + get + { + return this._textAdicoes; + } + set + { + this._textAdicoes = value; + base.OnPropertyChanged("TextAdicoes"); + } + } + + public Visibility VisiblityDetalhesLog + { + get + { + return this._visibilityDetalhesLog; + } + set + { + this._visibilityDetalhesLog = value; + base.OnPropertyChanged("VisiblityDetalhesLog"); + } + } + + public LogViewModel(TipoTela tela, long id, List parcelas = null, int numparcela = 0) + { + this._visibilityDetalhesLog = Visibility.Hidden; + this._mostrarToolTip = "MOSTRAR TODAS OS CAMPOS"; + this._mostrarColuna = (long)120; + PackIcon packIcon = new PackIcon(); + packIcon.set_Kind(1497); + this._mostrarIcone = packIcon; + this._logs = new ObservableCollection(); + this._currentDescription = ""; + this._lists = new List(); + this._listsAlterados = new ObservableCollection(); + this._listsAdicionados = new ObservableCollection(); + this._listsRemovidos = new ObservableCollection(); + this._textAdicoes = "INCLUSÃO"; + base(); + this._servico = new LogServico(); + this._tipoTela = tela; + this._id = id; + this.VisiblityDetalhesLog = (Recursos.Configuracoes.Any((ConfiguracaoSistema c) => c.get_Configuracao() == 55) ? Visibility.Visible : Visibility.Hidden); + base.EnableMenu = true; + if (parcelas != null) + { + this.LogParcelas(id, parcelas, numparcela); + return; + } + this.Seleciona(tela, id, null, null); + } + + public int BuscaNumeroParcela(string json) + { + int num; + int num1; + try + { + string[] strArrays = json.Split(new char[] { '}' }).FirstOrDefault((string x) => x.Contains("NumeroParcela")).Split(new char[] { ':' }); + num1 = (int.TryParse(strArrays[(int)strArrays.Length - 1].Replace("\"", ""), out num) ? num : 0); + } + catch + { + num1 = 0; + } + return num1; + } + + private static List DefaultLog(string log, TipoAcao acao) + { + List tupleLists = new List(); + TupleList tupleList = new TupleList(); + tupleList.set_Tuples(new ObservableCollection>() + { + new Tuple(Gestor.Model.Validation.Funcoes.GetDescription(acao), log, "") + }); + tupleLists.Add(tupleList); + return tupleLists; + } + + public void Imprimir() + { + bool count; + bool flag; + bool count1; + bool flag1; + bool count2; + bool flag2; + string str = "LOGS
"; + ObservableCollection listsAlterados = this.ListsAlterados; + if (listsAlterados != null) + { + count = listsAlterados.Count > 0; + } + else + { + count = false; + } + if (count) + { + str = string.Concat(str, "ALTERAÇÃO"); + } + if (this.ListsAlterados != null) + { + foreach (TupleList listsAlterado in this.ListsAlterados) + { + foreach (Tuple tuple in listsAlterado.get_Tuples()) + { + if (tuple == listsAlterado.get_Tuples().First>()) + { + str = string.Concat(str, ""); + if (!this.Mostrar) + { + str = string.Concat(str, ""); + } + str = string.Concat(str, "
DESCRIÇÃOVALOR LOG SELECIONADOVALOR LOG ANTERIOR
"); + } + bool flag3 = tuple.Item1.Contains("$"); + string[] item2 = new string[] { str, ""; + str = string.Concat(item2); + if (!this.Mostrar) + { + str = string.Concat(str, ""); + } + str = string.Concat(str, "
"; + item2[4] = tuple.Item1.Replace(" ", " ").Replace("$", ""); + item2[5] = ""; + item2[8] = tuple.Item2; + item2[9] = "", tuple.Item3, "
"); + } + if ((object)listsAlterado == (object)this.ListsAlterados.Last()) + { + continue; + } + str = string.Concat(str, "
"); + } + } + ObservableCollection listsAdicionados = this.ListsAdicionados; + if (listsAdicionados != null) + { + flag = listsAdicionados.Count > 0; + } + else + { + flag = false; + } + if (flag) + { + ObservableCollection observableCollection = this.ListsAlterados; + if (observableCollection != null) + { + flag2 = observableCollection.Count > 0; + } + else + { + flag2 = false; + } + if (flag2) + { + str = string.Concat(str, "


"); + } + str = string.Concat(str, "INCLUSÃO"); + } + if (this.ListsAdicionados != null) + { + foreach (TupleList listsAdicionado in this.ListsAdicionados) + { + foreach (Tuple tuple1 in listsAdicionado.get_Tuples()) + { + if (tuple1 == listsAdicionado.get_Tuples().First>()) + { + str = string.Concat(str, ""); + if (!this.Mostrar) + { + str = string.Concat(str, ""); + } + str = string.Concat(str, "
DESCRIÇÃOVALOR LOG SELECIONADOVALOR LOG ANTERIOR
"); + } + bool flag4 = tuple1.Item1.Contains("$"); + string[] strArrays = new string[] { str, ""; + str = string.Concat(strArrays); + if (!this.Mostrar) + { + str = string.Concat(str, ""); + } + str = string.Concat(str, "
"; + strArrays[4] = tuple1.Item1.Replace(" ", " ").Replace("$", ""); + strArrays[5] = ""; + strArrays[8] = tuple1.Item2; + strArrays[9] = "", tuple1.Item3, "
"); + } + if ((object)listsAdicionado == (object)this.ListsAdicionados.Last()) + { + continue; + } + str = string.Concat(str, "
"); + } + } + ObservableCollection listsRemovidos = this.ListsRemovidos; + if (listsRemovidos != null) + { + count1 = listsRemovidos.Count > 0; + } + else + { + count1 = false; + } + if (count1) + { + ObservableCollection listsAlterados1 = this.ListsAlterados; + if (listsAlterados1 != null) + { + flag1 = listsAlterados1.Count > 0; + } + else + { + flag1 = false; + } + if (!flag1) + { + ObservableCollection listsAdicionados1 = this.ListsAdicionados; + if (listsAdicionados1 != null) + { + count2 = listsAdicionados1.Count > 0; + } + else + { + count2 = false; + } + if (!count2) + { + goto Label0; + } + } + str = string.Concat(str, "


"); + Label0: + str = string.Concat(str, "EXCLUSÃO"); + } + if (this.ListsRemovidos != null) + { + foreach (TupleList listsRemovido in this.ListsRemovidos) + { + foreach (Tuple tuple2 in listsRemovido.get_Tuples()) + { + if (tuple2 == listsRemovido.get_Tuples().First>()) + { + str = string.Concat(str, ""); + if (!this.Mostrar) + { + str = string.Concat(str, ""); + } + str = string.Concat(str, "
DESCRIÇÃOVALOR LOG SELECIONADOVALOR LOG ANTERIOR
"); + } + bool flag5 = tuple2.Item1.Contains("$"); + string[] item21 = new string[] { str, ""; + str = string.Concat(item21); + if (!this.Mostrar) + { + str = string.Concat(str, ""); + } + str = string.Concat(str, "
"; + item21[4] = tuple2.Item1.Replace(" ", " ").Replace("$", ""); + item21[5] = ""; + item21[8] = tuple2.Item2; + item21[9] = "", tuple2.Item3, "
"); + } + if ((object)listsRemovido == (object)this.ListsRemovidos.Last()) + { + continue; + } + str = string.Concat(str, "
"); + } + } + str = string.Concat(str, "
"); + string tempPath = Path.GetTempPath(); + string str1 = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.html", tempPath, (TipoExtrato)0, Gestor.Application.Helpers.Funcoes.GetNetworkTime()); + StreamWriter streamWriter = new StreamWriter(str1, true, Encoding.UTF8); + streamWriter.Write(str); + streamWriter.Close(); + Process.Start(str1); + base.RegistrarAcao(string.Format("IMPRIMIU O LOG DE ALTERAÇÕES DE {0} DO ID \"{1}\"", Gestor.Model.Validation.Funcoes.GetDescription(this._tipoTela), this._id), this._id, new TipoTela?(this._tipoTela), string.Format("ID ENTIDADE: {0}\nTIPO: {1}", this._id, Gestor.Model.Validation.Funcoes.GetDescription(this._tipoTela))); + } + + private async void LogParcelas(long documento, List parcelas, int numparcela) + { + base.Loading(true); + List nums = new List(); + nums.AddRange(parcelas); + nums.Add(documento); + this.Logs = new ObservableCollection((IEnumerable)await this._servico.BuscaLogParcelas(nums)); + ObservableCollection observableCollection = new ObservableCollection(); + List list = this.Logs.Where((RegistroLog x) => { + if (x.get_ModeloNovo()) + { + return false; + } + return x.get_EntidadeId() == documento; + }).ToList(); + for (int i = list.Count - 1; i >= 0; i--) + { + ObservableCollection observableCollection1 = new ObservableCollection(); + try + { + for (int j = i; j >= 0 && list[j].get_DataHora() < list[i].get_DataHora().AddSeconds(4); j--) + { + Parcela parcela = JsonConvert.DeserializeObject(this.Logs[j].get_Descricao()); + if (parcela != null && (numparcela == 0 || this.BuscaNumeroParcela(this.Logs[j].get_Descricao()) == numparcela)) + { + observableCollection1.Add(parcela); + } + i = j; + } + } + catch (Exception exception1) + { + try + { + List parcelas1 = JsonConvert.DeserializeObject>(this.Logs[i].get_Descricao()); + if (parcelas1 != null && (numparcela == 0 || this.BuscaNumeroParcela(this.Logs[i].get_Descricao()) == numparcela)) + { + ExtensionMethods.AddRange(observableCollection1, parcelas1); + } + } + catch (Exception exception) + { + RegistroLog item = this.Logs[i]; + string descricao = this.Logs[i].get_Descricao(); + if (descricao == null) + { + descricao = ""; + } + item.set_Descricao(descricao); + observableCollection.Insert(0, this.Logs[i]); + goto Label0; + } + } + ObservableCollection observableCollection2 = observableCollection1; + observableCollection1 = new ObservableCollection( + from x in observableCollection2 + orderby x.get_NumeroParcela() + select x); + if (observableCollection1 != null && observableCollection1.Count != 0 && observableCollection1[0].get_Documento() != null) + { + RegistroLog registroLog = list[i]; + Parcelas parcela1 = new Parcelas(); + parcela1.set_ParcelasList(observableCollection1); + parcela1.set_TipoRecebimento(observableCollection1[0].get_Documento().get_TipoRecebimento()); + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(parcela1, jsonSerializerSetting)); + observableCollection.Insert(0, list[i]); + } + Label0: + } + List registroLogs = new List(); + ObservableCollection logs = this.Logs; + List list1 = ( + from x in logs + where x.get_ModeloNovo() + select x).ToList(); + if (numparcela != 0) + { + foreach (RegistroLog registroLog1 in list1) + { + int num = this.BuscaNumeroParcela(registroLog1.get_Descricao()); + if ((num == 0 || num != numparcela) && (numparcela == 0 || parcelas.Count != 1 || registroLog1.get_EntidadeId() == documento)) + { + continue; + } + registroLogs.Add(registroLog1); + } + } + else + { + registroLogs.AddRange(list1); + } + this.Logs = observableCollection; + ExtensionMethods.AddRange(this.Logs, registroLogs); + if (this.Logs.Count <= 0) + { + this.SetListaFiltrada(this.Lists); + } + else + { + this.SelectedLog = this.Logs[0]; + } + base.Loading(false); + } + + public void MostrarCampos() + { + if (this.SelectedLog == null || this.SelectedLog.get_ModeloNovo()) + { + return; + } + this.Mostrar = !this.Mostrar; + this.Lists = this.Lists; + } + + private static int QntEspaco(string str) + { + return Regex.Match(str, "[^\\s]").Index; + } + + private async void Seleciona(TipoTela tela, long id, List parcelas = null, long? parcela = null) + { + base.Loading(true); + this.Logs = new ObservableCollection((IEnumerable)await this._servico.FindByEntityId(tela, id)); + if (tela == 37) + { + ObservableCollection observableCollection = new ObservableCollection(); + ObservableCollection logs = this.Logs; + List list = ( + from x in logs + where !x.get_ModeloNovo() + select x).ToList(); + for (int i = list.Count - 1; i >= 0; i--) + { + ObservableCollection observableCollection1 = new ObservableCollection(); + for (int j = i; j >= 0 && list[j].get_DataHora() < list[i].get_DataHora().AddSeconds(4); j--) + { + observableCollection1.Add(JsonConvert.DeserializeObject(list[j].get_Descricao())); + i = j; + } + ObservableCollection observableCollection2 = observableCollection1; + observableCollection1 = new ObservableCollection( + from x in observableCollection2 + orderby x.get_Id() + select x); + RegistroLog item = list[i]; + VendedorParcelas vendedorParcela = new VendedorParcelas(); + vendedorParcela.set_VendedorParcelasList(observableCollection1); + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + item.set_Descricao(JsonConvert.SerializeObject(vendedorParcela, jsonSerializerSetting)); + observableCollection.Insert(0, list[i]); + } + ObservableCollection logs1 = this.Logs; + List registroLogs = ( + from x in logs1 + where x.get_ModeloNovo() + select x).ToList(); + this.Logs = observableCollection; + ExtensionMethods.AddRange(this.Logs, registroLogs); + } + if (this.Logs.Count <= 0) + { + this.SetListaFiltrada(this.Lists); + } + else + { + this.SelectedLog = this.Logs[0]; + } + base.Loading(false); + } + + public void SetListaFiltrada(List listAtual) + { + List tupleLists; + ObservableCollection> observableCollection; + List.Enumerator enumerator; + ObservableCollection observableCollection1; + ObservableCollection observableCollection2; + ObservableCollection observableCollection3; + if (this.Logs.Count == 0) + { + this.ListsAlterados = null; + this.ListsAdicionados = null; + this.ListsRemovidos = null; + return; + } + if (this.SelectedLog.get_ModeloNovo() && this.SelectedLog.get_Acao() == 1) + { + this.TextAdicoes = "ALTERAÇÕES"; + this.ListsAdicionados = null; + this.ListsRemovidos = null; + this.ListsAlterados = new ObservableCollection(this.Lists); + this.MostrarMensagem = false; + return; + } + if (this.SelectedLog.get_ModeloNovo() && this.SelectedLog.get_Acao() == null) + { + this.TextAdicoes = "INCLUSÕES"; + this.ListsAlterados = null; + this.ListsRemovidos = null; + this.ListsAdicionados = new ObservableCollection(listAtual); + this.MostrarMensagem = false; + return; + } + if (this.SelectedLog.get_ModeloNovo() && this.SelectedLog.get_Acao() == 2) + { + this.TextAdicoes = "EXCLUSÕES"; + this.ListsAlterados = null; + this.ListsAdicionados = null; + this.ListsRemovidos = new ObservableCollection(listAtual); + this.MostrarMensagem = false; + return; + } + if (this.Mostrar || (object)this.Logs.Last() == (object)this.SelectedLog) + { + this.TextAdicoes = ((object)this.Logs.Last() != (object)this.SelectedLog ? "LOG COMPLETO" : "INCLUSÃO"); + this.ListsAlterados = null; + this.ListsAdicionados = new ObservableCollection(listAtual); + this.ListsRemovidos = null; + return; + } + this.TextAdicoes = "INCLUSÃO"; + List tupleLists1 = new List(); + try + { + switch (this._tipoTela) + { + case 1: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 2: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(base.Restricao(14)); + goto case 53; + } + case 3: + { + Item item = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()); + if (item.get_Aeronautico() != null) + { + tupleLists1 = Aeronautico.Log(item); + goto case 53; + } + else if (item.get_Auto() != null) + { + tupleLists1 = Auto.Log(item); + goto case 53; + } + else if (item.get_Granizo() != null) + { + tupleLists1 = Granizo.Log(item); + goto case 53; + } + else if (item.get_Patrimonial() != null) + { + tupleLists1 = Patrimonial.Log(item); + goto case 53; + } + else if (item.get_RiscosDiversos() == null) + { + if (item.get_Vida() == null) + { + goto case 53; + } + tupleLists1 = Vida.Log(item); + goto case 53; + } + else + { + tupleLists1 = RiscosDiversos.Log(item); + goto case 53; + } + } + case 4: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 5: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(base.Restricao(14), base.Restricao(95)); + goto case 53; + } + case 6: + case 8: + case 20: + case 21: + case 23: + case 25: + case 27: + case 32: + case 35: + case 39: + case 40: + case 44: + case 47: + case 49: + case 50: + case 51: + case 53: + { + break; + } + case 7: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 9: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 10: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 11: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 12: + { + Ramo ramo = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()); + List list = ( + from x in Recursos.Coberturas + where x.get_IdRamo() == ramo.get_Id() + orderby x.get_Padrao() descending, x.get_Descricao() + select x).ToList(); + tupleLists1 = ramo.Log(list); + goto case 53; + } + case 13: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 14: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 15: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 16: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 17: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 18: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 19: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 22: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 24: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 26: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 28: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 29: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 30: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 31: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 33: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 34: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 36: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 37: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(base.Restricao(14), base.Restricao(95)); + goto case 53; + } + case 38: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 41: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 42: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 43: + { + List>>>>> tuples = JsonConvert.DeserializeObject>>>>>>(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()); + tupleLists = new List(); + foreach (Tuple>>>> tuple in tuples) + { + observableCollection = new ObservableCollection>() + { + new Tuple(string.Concat(tuple.Item1, "$"), "", "") + }; + foreach (Tuple>> item2 in tuple.Item2) + { + observableCollection.Add(new Tuple(string.Concat(" ", item2.Item1, "$"), "", "")); + foreach (Tuple item21 in item2.Item2) + { + observableCollection.Add(new Tuple(string.Concat(" ", item21.Item1), item21.Item2, "")); + } + } + TupleList tupleList = new TupleList(); + tupleList.set_Tuples(observableCollection); + tupleLists.Add(tupleList); + } + enumerator = tupleLists.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + tupleLists1.Add(enumerator.Current); + } + goto case 53; + } + finally + { + ((IDisposable)enumerator).Dispose(); + } + break; + } + case 45: + { + List vendedors = JsonConvert.DeserializeObject>(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()); + tupleLists = new List(); + observableCollection = new ObservableCollection>() + { + new Tuple("VENDEDORES VINCULADOS$", "", "") + }; + foreach (Vendedor vendedor in vendedors) + { + observableCollection.Add(new Tuple(string.Format(" VENDEDOR {0}", vendedors.IndexOf(vendedor) + 1), vendedor.get_Nome(), "")); + } + TupleList tupleList1 = new TupleList(); + tupleList1.set_Tuples(observableCollection); + tupleLists.Add(tupleList1); + enumerator = tupleLists.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + tupleLists1.Add(enumerator.Current); + } + goto case 53; + } + finally + { + ((IDisposable)enumerator).Dispose(); + } + break; + } + case 46: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 48: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 52: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 54: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 55: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 56: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + default: + { + goto case 53; + } + } + } + catch (Exception exception) + { + } + ObservableCollection observableCollection4 = new ObservableCollection(); + foreach (TupleList tupleList2 in listAtual) + { + int num = -1; + if (tupleLists1.Count - 1 < listAtual.IndexOf(tupleList2)) + { + continue; + } + for (int i = 0; i < tupleList2.get_Tuples().Count; i++) + { + Tuple item1 = tupleList2.get_Tuples()[i]; + if (LogViewModel.QntEspaco(item1.Item1) != 0) + { + List strs = new List(); + int num1 = LogViewModel.QntEspaco(item1.Item1); + for (int j = i; j >= 0; j--) + { + if (LogViewModel.QntEspaco(tupleList2.get_Tuples()[j].Item1) <= num1) + { + strs.Insert(0, tupleList2.get_Tuples()[j].Item1); + num1 = LogViewModel.QntEspaco(tupleList2.get_Tuples()[j].Item1); + } + } + bool flag = false; + int num2 = 0; + Label2: + foreach (string str in strs) + { + if (!flag) + { + int num3 = num2; + while (num3 < tupleLists1[listAtual.IndexOf(tupleList2)].get_Tuples().Count) + { + if (num3 == tupleLists1[listAtual.IndexOf(tupleList2)].get_Tuples().Count - 1 && str != tupleLists1[listAtual.IndexOf(tupleList2)].get_Tuples()[num3].Item1) + { + flag = true; + goto Label2; + } + else if (str != tupleLists1[listAtual.IndexOf(tupleList2)].get_Tuples()[num3].Item1) + { + num3++; + } + else + { + num2 = num3; + goto Label2; + } + } + } + else + { + goto Label1; + } + } + Label1: + if (!flag && item1.Item2 != tupleLists1[listAtual.IndexOf(tupleList2)].get_Tuples()[num2].Item2) + { + if (num < listAtual.IndexOf(tupleList2)) + { + TupleList tupleList3 = new TupleList(); + tupleList3.set_Tuples(new ObservableCollection>()); + observableCollection4.Add(tupleList3); + num = listAtual.IndexOf(tupleList2); + } + int count = observableCollection4.Last().get_Tuples().Count; + int num4 = LogViewModel.QntEspaco(item1.Item1); + for (int k = i - 1; k >= 0; k--) + { + if (LogViewModel.QntEspaco(tupleList2.get_Tuples()[k].Item1) < LogViewModel.QntEspaco(item1.Item1) && LogViewModel.QntEspaco(tupleList2.get_Tuples()[k].Item1) < num4) + { + bool flag1 = false; + int count1 = observableCollection4.Last().get_Tuples().Count - 1; + while (count1 >= 0) + { + if (observableCollection4.Last().get_Tuples()[count1].Item1 != tupleList2.get_Tuples()[k].Item1) + { + count1--; + } + else + { + flag1 = true; + break; + } + } + if (flag1) + { + break; + } + num4 = LogViewModel.QntEspaco(tupleList2.get_Tuples()[k].Item1); + observableCollection4.Last().get_Tuples().Insert(count, new Tuple(tupleList2.get_Tuples()[k].Item1, tupleList2.get_Tuples()[k].Item2, "")); + } + } + observableCollection4.Last().get_Tuples().Add(new Tuple(item1.Item1, item1.Item2, tupleLists1[listAtual.IndexOf(tupleList2)].get_Tuples()[num2].Item2)); + } + } + else if (item1.Item2 != tupleLists1[listAtual.IndexOf(tupleList2)].get_Tuples()[tupleList2.get_Tuples().IndexOf(item1)].Item2) + { + if (num < listAtual.IndexOf(tupleList2)) + { + TupleList tupleList4 = new TupleList(); + tupleList4.set_Tuples(new ObservableCollection>()); + observableCollection4.Add(tupleList4); + num = listAtual.IndexOf(tupleList2); + } + observableCollection4.Last().get_Tuples().Add(new Tuple(item1.Item1, item1.Item2, tupleLists1[listAtual.IndexOf(tupleList2)].get_Tuples()[tupleList2.get_Tuples().IndexOf(item1)].Item2)); + } + } + } + if (observableCollection4.Count == 0) + { + observableCollection1 = null; + } + else + { + observableCollection1 = observableCollection4; + } + this.ListsAlterados = observableCollection1; + observableCollection4 = new ObservableCollection(); + foreach (TupleList tupleList5 in listAtual) + { + int num5 = -1; + if (tupleLists1.Count - 1 < listAtual.IndexOf(tupleList5)) + { + continue; + } + for (int l = 0; l < tupleList5.get_Tuples().Count; l++) + { + Tuple tuple1 = tupleList5.get_Tuples()[l]; + if (LogViewModel.QntEspaco(tuple1.Item1) > 0) + { + List strs1 = new List(); + int num6 = LogViewModel.QntEspaco(tuple1.Item1); + for (int m = l; m >= 0; m--) + { + if (LogViewModel.QntEspaco(tupleList5.get_Tuples()[m].Item1) <= num6) + { + strs1.Insert(0, tupleList5.get_Tuples()[m].Item1); + num6 = LogViewModel.QntEspaco(tupleList5.get_Tuples()[m].Item1); + } + } + bool flag2 = false; + int num7 = 0; + Label4: + foreach (string str1 in strs1) + { + if (!flag2) + { + int num8 = num7; + while (num8 < tupleLists1[listAtual.IndexOf(tupleList5)].get_Tuples().Count) + { + if (num8 == tupleLists1[listAtual.IndexOf(tupleList5)].get_Tuples().Count - 1 && str1 != tupleLists1[listAtual.IndexOf(tupleList5)].get_Tuples()[num8].Item1) + { + flag2 = true; + goto Label4; + } + else if (str1 != tupleLists1[listAtual.IndexOf(tupleList5)].get_Tuples()[num8].Item1) + { + num8++; + } + else + { + num7 = num8; + goto Label4; + } + } + } + else + { + goto Label3; + } + } + Label3: + if (flag2) + { + if (num5 < listAtual.IndexOf(tupleList5)) + { + TupleList tupleList6 = new TupleList(); + tupleList6.set_Tuples(new ObservableCollection>()); + observableCollection4.Add(tupleList6); + num5 = listAtual.IndexOf(tupleList5); + } + int count2 = observableCollection4.Last().get_Tuples().Count; + int num9 = LogViewModel.QntEspaco(tuple1.Item1); + for (int n = l - 1; n >= 0; n--) + { + if (LogViewModel.QntEspaco(tupleList5.get_Tuples()[n].Item1) < LogViewModel.QntEspaco(tuple1.Item1) && LogViewModel.QntEspaco(tupleList5.get_Tuples()[n].Item1) < num9) + { + bool flag3 = false; + int count3 = observableCollection4.Last().get_Tuples().Count - 1; + while (count3 >= 0) + { + if (observableCollection4.Last().get_Tuples()[count3].Item1 != tupleList5.get_Tuples()[n].Item1) + { + count3--; + } + else + { + flag3 = true; + break; + } + } + if (flag3) + { + break; + } + num9 = LogViewModel.QntEspaco(tupleList5.get_Tuples()[n].Item1); + observableCollection4.Last().get_Tuples().Insert(count2, new Tuple(tupleList5.get_Tuples()[n].Item1, tupleList5.get_Tuples()[n].Item2, "")); + } + } + observableCollection4.Last().get_Tuples().Add(new Tuple(tuple1.Item1, tuple1.Item2, "")); + } + } + } + } + if (observableCollection4.Count == 0) + { + observableCollection2 = null; + } + else + { + observableCollection2 = observableCollection4; + } + this.ListsAdicionados = observableCollection2; + observableCollection4 = new ObservableCollection(); + foreach (TupleList tupleList7 in tupleLists1) + { + int num10 = -1; + for (int o = 0; o < tupleList7.get_Tuples().Count; o++) + { + Tuple tuple2 = tupleList7.get_Tuples()[o]; + if (LogViewModel.QntEspaco(tuple2.Item1) > 0) + { + List strs2 = new List(); + int num11 = LogViewModel.QntEspaco(tuple2.Item1); + for (int p = o; p >= 0; p--) + { + if (LogViewModel.QntEspaco(tupleList7.get_Tuples()[p].Item1) <= num11) + { + strs2.Insert(0, tupleList7.get_Tuples()[p].Item1); + num11 = LogViewModel.QntEspaco(tupleList7.get_Tuples()[p].Item1); + } + } + bool flag4 = false; + int num12 = 0; + Label6: + foreach (string str2 in strs2) + { + if (!flag4) + { + if (listAtual.Count - 1 < tupleLists1.IndexOf(tupleList7)) + { + continue; + } + int num13 = num12; + while (num13 < listAtual[tupleLists1.IndexOf(tupleList7)].get_Tuples().Count) + { + if (num13 == listAtual[tupleLists1.IndexOf(tupleList7)].get_Tuples().Count - 1 && str2 != listAtual[tupleLists1.IndexOf(tupleList7)].get_Tuples()[num13].Item1) + { + flag4 = true; + goto Label6; + } + else if (str2 != listAtual[tupleLists1.IndexOf(tupleList7)].get_Tuples()[num13].Item1) + { + num13++; + } + else + { + num12 = num13; + goto Label6; + } + } + } + else + { + goto Label5; + } + } + Label5: + if (flag4) + { + if (num10 < tupleLists1.IndexOf(tupleList7)) + { + TupleList tupleList8 = new TupleList(); + tupleList8.set_Tuples(new ObservableCollection>()); + observableCollection4.Add(tupleList8); + num10 = tupleLists1.IndexOf(tupleList7); + } + int count4 = observableCollection4.Last().get_Tuples().Count; + int num14 = LogViewModel.QntEspaco(tuple2.Item1); + for (int q = o - 1; q >= 0; q--) + { + if (LogViewModel.QntEspaco(tupleList7.get_Tuples()[q].Item1) < LogViewModel.QntEspaco(tuple2.Item1) && LogViewModel.QntEspaco(tupleList7.get_Tuples()[q].Item1) < num14) + { + bool flag5 = false; + int count5 = observableCollection4.Last().get_Tuples().Count - 1; + while (count5 >= 0) + { + if (observableCollection4.Last().get_Tuples()[count5].Item1 != tupleList7.get_Tuples()[q].Item1) + { + count5--; + } + else + { + flag5 = true; + break; + } + } + if (flag5) + { + break; + } + num14 = LogViewModel.QntEspaco(tupleList7.get_Tuples()[q].Item1); + observableCollection4.Last().get_Tuples().Insert(count4, new Tuple(tupleList7.get_Tuples()[q].Item1, tupleList7.get_Tuples()[q].Item2, "")); + } + } + observableCollection4.Last().get_Tuples().Add(new Tuple(tuple2.Item1, "", tuple2.Item2)); + } + } + } + } + if (observableCollection4.Count == 0) + { + observableCollection3 = null; + } + else + { + observableCollection3 = observableCollection4; + } + this.ListsRemovidos = observableCollection3; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/MetaSeguradoraViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/MetaSeguradoraViewModel.cs new file mode 100644 index 0000000..71d96c5 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/MetaSeguradoraViewModel.cs @@ -0,0 +1,258 @@ +using Assinador.Infrastructure.Helpers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class MetaSeguradoraViewModel : BaseSegurosViewModel + { + private readonly MetaSeguradoraServico _servico; + + private readonly Seguradora _selectedSeguradora; + + private MetaSeguradora _selectedMetaSeguradora = new MetaSeguradora(); + + private ObservableCollection _metasSeguradora = new ObservableCollection(); + + private bool _carregando; + + public MetaSeguradora CancelMetaSeguradora; + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.IsEnabled = !value; + base.EnableMenu = !value; + base.OnPropertyChanged("Carregando"); + } + } + + public ObservableCollection MetasSeguradora + { + get + { + return this._metasSeguradora; + } + set + { + this._metasSeguradora = value; + base.OnPropertyChanged("MetasSeguradora"); + } + } + + public MetaSeguradora SelectedMetaSeguradora + { + get + { + return this._selectedMetaSeguradora; + } + set + { + long? nullable; + this._selectedMetaSeguradora = value; + this.CancelMetaSeguradora = (value == null || value.get_Id() <= (long)0 ? this.CancelMetaSeguradora : value); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedMetaSeguradora"); + } + } + + public MetaSeguradoraViewModel(Seguradora seguradora) + { + this._servico = new MetaSeguradoraServico(); + this.Seleciona(seguradora); + this._selectedSeguradora = seguradora; + } + + public void CancelarAlteracao() + { + this.Carregando = true; + if (this.CancelMetaSeguradora != null && this.MetasSeguradora.Any((MetaSeguradora x) => x.get_Id() == this.CancelMetaSeguradora.get_Id())) + { + DomainBase.Copy(this.MetasSeguradora.First((MetaSeguradora x) => x.get_Id() == this.CancelMetaSeguradora.get_Id()), this.CancelMetaSeguradora); + this.SelectedMetaSeguradora = this.MetasSeguradora.First((MetaSeguradora x) => x.get_Id() == this.CancelMetaSeguradora.get_Id()); + } + base.Alterar(false); + this.Carregando = false; + } + + private async Task CarregarMetas(Seguradora seguradora) + { + List metaSeguradoras = await (new BaseServico()).BuscarMetaSeguradoraAsync(seguradora); + MetaSeguradoraViewModel observableCollection = this; + List metaSeguradoras1 = metaSeguradoras; + IOrderedEnumerable mes = + from x in metaSeguradoras1 + orderby x.get_Mes() + select x; + observableCollection.MetasSeguradora = new ObservableCollection(mes.ThenBy((MetaSeguradora x) => x.get_Valor())); + } + + public async Task Excluir() + { + bool flag; + string nome; + MetaSeguradora metaSeguradora; + if (this.SelectedMetaSeguradora == null || this.SelectedMetaSeguradora.get_Id() == 0) + { + flag = false; + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + this.Carregando = true; + if (await this._servico.Delete(this.SelectedMetaSeguradora)) + { + MetaSeguradoraViewModel metaSeguradoraViewModel = this; + Seguradora seguradora = this.SelectedMetaSeguradora.get_Seguradora(); + if (seguradora != null) + { + nome = seguradora.get_Nome(); + } + else + { + nome = null; + } + string str = string.Concat("EXCLUIU META DA SEGURADORA \"", nome, "\""); + long id = this.SelectedMetaSeguradora.get_Id(); + TipoTela? nullable = new TipoTela?(31); + object[] objArray = new object[] { this.SelectedMetaSeguradora.get_Id(), this.SelectedMetaSeguradora.get_Valor(), Functions.GetDescription(this.SelectedMetaSeguradora.get_Mes()), this.SelectedMetaSeguradora.get_Ano() }; + metaSeguradoraViewModel.RegistrarAcao(str, id, nullable, string.Format("ID: {0}\nVALOR: {1:C}\nMÊS: {2}\nANO: {3}", objArray)); + int num = this.MetasSeguradora.IndexOf(this.SelectedMetaSeguradora); + this.MetasSeguradora.Remove(this.SelectedMetaSeguradora); + this.MetasSeguradora.Remove(this.SelectedMetaSeguradora); + this.MetasSeguradora = new ObservableCollection(this.MetasSeguradora); + if (this.MetasSeguradora.Count <= 0) + { + this.SelectedMetaSeguradora = new MetaSeguradora(); + base.Alterar(false); + base.EnableMenu = false; + base.EnableAlterar = false; + base.EnableExcluir = false; + } + else + { + MetaSeguradoraViewModel metaSeguradoraViewModel1 = this; + metaSeguradora = (num < this.MetasSeguradora.Count ? this.MetasSeguradora.ElementAt(num) : this.MetasSeguradora.Last()); + metaSeguradoraViewModel1.SelectedMetaSeguradora = metaSeguradora; + } + this.Carregando = false; + flag = true; + } + else + { + this.Carregando = false; + base.Alterar(false); + flag = false; + } + } + else + { + flag = false; + } + return flag; + } + + public void Incluir() + { + DateTime date = Funcoes.GetNetworkTime().Date; + MetaSeguradora metaSeguradora = new MetaSeguradora(); + metaSeguradora.set_Ano((long)date.Year); + metaSeguradora.set_Mes(date.Month); + this.SelectedMetaSeguradora = metaSeguradora; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + this.SelectedMetaSeguradora.set_Seguradora(this._selectedSeguradora); + str = (this.SelectedMetaSeguradora.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + string str1 = str; + MetaSeguradora metaSeguradora = await this._servico.Save(this.SelectedMetaSeguradora); + if (this._servico.Sucesso) + { + string str2 = string.Concat(str1, " META DA SEGURADORA \"", metaSeguradora.get_Seguradora().get_Nome(), "\""); + long id = metaSeguradora.get_Id(); + TipoTela? nullable = new TipoTela?(31); + object[] objArray = new object[] { metaSeguradora.get_Id(), metaSeguradora.get_Valor(), Functions.GetDescription(metaSeguradora.get_Mes()), metaSeguradora.get_Ano() }; + base.RegistrarAcao(str2, id, nullable, string.Format("ID: {0}\nVALOR: {1:C}\nMÊS: {2}\nANO: {3}", objArray)); + if (!this.MetasSeguradora.Any((MetaSeguradora x) => x.get_Id() == metaSeguradora.get_Id())) + { + this.MetasSeguradora.Add(metaSeguradora); + } + else + { + DomainBase.Copy(this.MetasSeguradora.First((MetaSeguradora x) => x.get_Id() == metaSeguradora.get_Id()), metaSeguradora); + } + this.MetasSeguradora = new ObservableCollection(this.MetasSeguradora); + this.SelectedMetaSeguradora = this.MetasSeguradora.First((MetaSeguradora x) => x.get_Id() == metaSeguradora.get_Id()); + base.Alterar(false); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + str1 = null; + return keyValuePairs; + } + + private async void Seleciona(Seguradora seguradora) + { + base.Loading(true); + await base.PermissaoTela(31); + await this.SelecionaMetasSeguradora(seguradora); + base.Loading(false); + } + + public void SelecionaMetaSeguradora(MetaSeguradora metaSeguradora) + { + this.SelectedMetaSeguradora = metaSeguradora; + } + + private async Task SelecionaMetasSeguradora(Seguradora seguradora) + { + this.Carregando = true; + await this.CarregarMetas(seguradora); + if (this.MetasSeguradora.Count <= 0) + { + this.SelectedMetaSeguradora = new MetaSeguradora(); + base.Alterar(false); + base.EnableMenu = false; + base.EnableAlterar = false; + base.EnableExcluir = false; + } + else + { + this.SelecionaMetaSeguradora(this.MetasSeguradora.First()); + } + this.Carregando = false; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/MetaVendedorViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/MetaVendedorViewModel.cs new file mode 100644 index 0000000..23f8929 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/MetaVendedorViewModel.cs @@ -0,0 +1,244 @@ +using Assinador.Infrastructure.Helpers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class MetaVendedorViewModel : BaseSegurosViewModel + { + private readonly MetaVendedorServico _servico; + + private readonly Vendedor _selectedVendedor; + + private MetaVendedor _selectedMetaVendedor = new MetaVendedor(); + + private ObservableCollection _metasVendedor = new ObservableCollection(); + + private bool _carregando; + + public MetaVendedor CancelMetaVendedor; + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.IsEnabled = !value; + base.EnableMenu = !value; + base.OnPropertyChanged("Carregando"); + } + } + + public ObservableCollection MetasVendedor + { + get + { + return this._metasVendedor; + } + set + { + this._metasVendedor = value; + base.OnPropertyChanged("MetasVendedor"); + } + } + + public MetaVendedor SelectedMetaVendedor + { + get + { + return this._selectedMetaVendedor; + } + set + { + long? nullable; + this._selectedMetaVendedor = value; + this.CancelMetaVendedor = (value == null || value.get_Id() <= (long)0 ? this.CancelMetaVendedor : value); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedMetaVendedor"); + } + } + + public MetaVendedorViewModel(Vendedor vendedor) + { + this._servico = new MetaVendedorServico(); + this.Seleciona(vendedor); + this._selectedVendedor = vendedor; + } + + public void CancelarAlteracao() + { + this.Carregando = true; + if (this.CancelMetaVendedor != null && this.MetasVendedor.Any((MetaVendedor x) => x.get_Id() == this.CancelMetaVendedor.get_Id())) + { + DomainBase.Copy(this.MetasVendedor.First((MetaVendedor x) => x.get_Id() == this.CancelMetaVendedor.get_Id()), this.CancelMetaVendedor); + this.SelectedMetaVendedor = this.MetasVendedor.First((MetaVendedor x) => x.get_Id() == this.CancelMetaVendedor.get_Id()); + } + base.Alterar(false); + this.Carregando = false; + } + + private async Task CarregarMetas(Vendedor vendedor) + { + List metaVendedors = await (new BaseServico()).BuscarMetaVendedorAsync(vendedor); + MetaVendedorViewModel observableCollection = this; + List metaVendedors1 = metaVendedors; + IOrderedEnumerable mes = + from x in metaVendedors1 + orderby x.get_Mes() + select x; + observableCollection.MetasVendedor = new ObservableCollection(mes.ThenBy((MetaVendedor x) => x.get_Valor()).ToList()); + } + + public async Task Excluir() + { + bool flag; + string str; + string str1; + if (this.SelectedMetaVendedor == null || this.SelectedMetaVendedor.get_Id() == 0) + { + flag = false; + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + this.Carregando = true; + str = string.Concat("EXCLUIU META DO VENDEDOR \"", this._selectedVendedor.get_Nome(), "\""); + long id = this.SelectedMetaVendedor.get_Id(); + object[] objArray = new object[] { this.SelectedMetaVendedor.get_Id(), this.SelectedMetaVendedor.get_Valor(), Functions.GetDescription(this.SelectedMetaVendedor.get_Mes()), this.SelectedMetaVendedor.get_Ano() }; + str1 = string.Format("ID: {0}\nVALOR: {1:C}\nMÊS: {2}\nANO: {3}", objArray); + if (await this._servico.Delete(this.SelectedMetaVendedor)) + { + base.RegistrarAcao(str, id, new TipoTela?(30), str1); + await this.CarregarMetas(this._selectedVendedor); + if (this.MetasVendedor.Count <= 0) + { + this.SelectedMetaVendedor = new MetaVendedor(); + base.Alterar(false); + base.EnableMenu = false; + base.EnableAlterar = false; + base.EnableExcluir = false; + } + else + { + this.SelectedMetaVendedor = this.MetasVendedor.First(); + } + this.Carregando = false; + flag = true; + } + else + { + this.Carregando = false; + base.Alterar(false); + flag = false; + } + } + else + { + flag = false; + } + str = null; + str1 = null; + return flag; + } + + public void Incluir() + { + DateTime date = Funcoes.GetNetworkTime().Date; + MetaVendedor metaVendedor = new MetaVendedor(); + metaVendedor.set_Ano((long)date.Year); + metaVendedor.set_Mes(date.Month); + this.SelectedMetaVendedor = metaVendedor; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + this.SelectedMetaVendedor.set_Vendedor(this._selectedVendedor); + this._servico.Sucesso = true; + str = (this.SelectedMetaVendedor.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + string str1 = str; + MetaVendedor metaVendedor = await this._servico.Save(this.SelectedMetaVendedor); + if (this._servico.Sucesso) + { + string str2 = string.Concat(str1, " META DO VENDEDOR \"", metaVendedor.get_Vendedor().get_Nome(), "\""); + long id = metaVendedor.get_Id(); + TipoTela? nullable = new TipoTela?(30); + object[] objArray = new object[] { metaVendedor.get_Id(), metaVendedor.get_Valor(), Functions.GetDescription(metaVendedor.get_Mes()), metaVendedor.get_Ano() }; + base.RegistrarAcao(str2, id, nullable, string.Format("ID: {0}\nVALOR: {1:C}\nMÊS: {2}\nANO: {3}", objArray)); + if (!this.MetasVendedor.Any((MetaVendedor x) => x.get_Id() == metaVendedor.get_Id())) + { + this.MetasVendedor.Add(metaVendedor); + } + else + { + DomainBase.Copy(this.MetasVendedor.First((MetaVendedor x) => x.get_Id() == metaVendedor.get_Id()), metaVendedor); + } + this.MetasVendedor = new ObservableCollection(this.MetasVendedor); + this.SelectedMetaVendedor = this.MetasVendedor.First((MetaVendedor x) => x.get_Id() == metaVendedor.get_Id()); + base.Alterar(false); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + str1 = null; + return keyValuePairs; + } + + private async void Seleciona(Vendedor vendedor) + { + base.Loading(true); + await base.PermissaoTela(30); + await this.SelecionaMetasVendedor(vendedor); + base.Loading(false); + } + + private async Task SelecionaMetasVendedor(Vendedor vendedor) + { + this.Carregando = true; + await this.CarregarMetas(vendedor); + if (this.MetasVendedor.Count <= 0) + { + this.SelectedMetaVendedor = new MetaVendedor(); + base.Alterar(false); + base.EnableMenu = false; + } + else + { + this.SelecionaMetaVendedor(this.MetasVendedor.First()); + } + this.Carregando = false; + } + + public void SelecionaMetaVendedor(MetaVendedor metaVendedor) + { + this.SelectedMetaVendedor = metaVendedor; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/PermissaoUsuarioViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/PermissaoUsuarioViewModel.cs new file mode 100644 index 0000000..3f8c7ac --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/PermissaoUsuarioViewModel.cs @@ -0,0 +1,1939 @@ +using Gestor.Application.Actions; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class PermissaoUsuarioViewModel : BaseSegurosViewModel + { + private readonly UsuarioServico _servicoUsuario; + + private Usuario _selectedUsuario; + + private bool _expandedBis; + + private bool _expandedSeguros; + + private bool _expandedRelatorios; + + private bool _expandedCampos; + + private bool _expandedTotalizacoes; + + private bool _expandedFinanceiros; + + private bool _expandedFerramentas; + + private bool _expandedAjudas; + + private ObservableCollection _seguros; + + private ObservableCollection _ferramentas; + + private ObservableCollection _arquivosDigitais; + + private bool _enableAlterarPermiss = true; + + private ObservableCollection _restricoesBisFiltradas; + + private ObservableCollection _restricoesSegurosFiltradas; + + private ObservableCollection _restricoesRelatoriosFiltrados; + + private ObservableCollection _restricoesTotalizacoesRelatoriosFiltrados; + + private ObservableCollection _restricoesCamposRelatoriosFiltrados; + + private ObservableCollection _restricoesFinanceirosFiltradas; + + private ObservableCollection _restricoesFerramentasFiltradas; + + private ObservableCollection _restricoesAjudasFiltrados; + + private List _restricoesBis; + + private List _restricoesSeguros; + + private List _restricoesRelatorios; + + private List _restricoesTotalizacoesRelatorios; + + private List _restricoesCamposRelatorios; + + private List _restricoesFinanceiros; + + private List _restricoesFerramentas; + + private List _restricoesAjudas; + + private Visibility _restricoesBisVisibility; + + private Visibility _restricoesSegurosVisibility; + + private Visibility _restricoesRelatoriosVisibility; + + private Visibility _restricoesTotalizacoesRelatoriosVisibility; + + private Visibility _restricoesCamposRelatoriosVisibility; + + private Visibility _restricoesFinanceirosVisibility; + + private Visibility _restricoesFerramentasVisibility; + + private Visibility _restricoesAjudasVisibility; + + private List _permissaoAggilizador; + + private Gestor.Model.Common.PermissaoAggilizador _selectedPermissao; + + private bool _admUsuario; + + private bool _importarEnabled; + + private bool _carregando; + + private bool _ativarDesativarPermissoesBool = true; + + private bool _ativarDesativarRestricoesBool = true; + + public bool AdmUsuario + { + get + { + return this._admUsuario; + } + set + { + this._admUsuario = value; + this.ImportarEnabled = !value; + this.SelectedUsuario.set_Administrador(value); + if (value && !this.Carregando) + { + this.AtivarDesativarPermissoes(true); + this.AtivarDesativarRestricoes(false); + } + base.OnPropertyChanged("AdmUsuario"); + } + } + + public ObservableCollection ArquivosDigitais + { + get + { + return this._arquivosDigitais; + } + set + { + this._arquivosDigitais = value; + base.OnPropertyChanged("ArquivosDigitais"); + Gestor.Application.Actions.Actions.OcultarTogglesArquivoDigital(); + } + } + + public bool AtivarDesativarPermissoesBool + { + get + { + return this._ativarDesativarPermissoesBool; + } + set + { + this._ativarDesativarPermissoesBool = value; + base.OnPropertyChanged("AtivarDesativarPermissoesBool"); + } + } + + public bool AtivarDesativarRestricoesBool + { + get + { + return this._ativarDesativarRestricoesBool; + } + set + { + this._ativarDesativarRestricoesBool = value; + base.OnPropertyChanged("AtivarDesativarRestricoesBool"); + } + } + + public bool Carregado + { + get; + set; + } + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.IsEnabled = !value; + base.EnableMenu = !value; + base.OnPropertyChanged("Carregando"); + } + } + + public bool EnableAlterarPermiss + { + get + { + return this._enableAlterarPermiss; + } + set + { + this._enableAlterarPermiss = value; + base.OnPropertyChanged("EnableAlterarPermiss"); + } + } + + public bool ExpandedAjudas + { + get + { + return this._expandedAjudas; + } + set + { + this._expandedAjudas = value; + base.OnPropertyChanged("ExpandedAjudas"); + } + } + + public bool ExpandedBis + { + get + { + return this._expandedBis; + } + set + { + this._expandedBis = value; + base.OnPropertyChanged("ExpandedBis"); + } + } + + public bool ExpandedCampos + { + get + { + return this._expandedCampos; + } + set + { + this._expandedCampos = value; + base.OnPropertyChanged("ExpandedCampos"); + } + } + + public bool ExpandedFerramentas + { + get + { + return this._expandedFerramentas; + } + set + { + this._expandedFerramentas = value; + base.OnPropertyChanged("ExpandedFerramentas"); + } + } + + public bool ExpandedFinanceiros + { + get + { + return this._expandedFinanceiros; + } + set + { + this._expandedFinanceiros = value; + base.OnPropertyChanged("ExpandedFinanceiros"); + } + } + + public bool ExpandedRelatorios + { + get + { + return this._expandedRelatorios; + } + set + { + this._expandedRelatorios = value; + base.OnPropertyChanged("ExpandedRelatorios"); + } + } + + public bool ExpandedSeguros + { + get + { + return this._expandedSeguros; + } + set + { + this._expandedSeguros = value; + base.OnPropertyChanged("ExpandedSeguros"); + } + } + + public bool ExpandedTotalizacoes + { + get + { + return this._expandedTotalizacoes; + } + set + { + this._expandedTotalizacoes = value; + base.OnPropertyChanged("ExpandedTotalizacoes"); + } + } + + public ObservableCollection Ferramentas + { + get + { + return this._ferramentas; + } + set + { + this._ferramentas = value; + base.OnPropertyChanged("Ferramentas"); + if (value != null && this.Seguros != null) + { + if (value.All((PermissaoUsuario x) => { + if (x.get_Tela() == 18 && x.get_Consultar() && x.get_Alterar() || x.get_Tela() == 10 && x.get_Consultar() && x.get_Alterar() && x.get_Incluir() || x.get_Tela() == 12 && x.get_Consultar() && x.get_Alterar() || x.get_Tela() == 13 && x.get_Consultar() && x.get_Alterar() && x.get_Incluir()) + { + return true; + } + if (x.get_Tela() == 18 || x.get_Tela() == 10 || x.get_Tela() == 12 || x.get_Tela() == 13 || !x.get_Consultar() || !x.get_Alterar() || !x.get_Incluir()) + { + return false; + } + return x.get_Excluir(); + })) + { + if (this.Seguros.All((PermissaoUsuario x) => { + if (x.get_Tela() == 21 && x.get_Consultar() || x.get_Tela() == 5 && x.get_Alterar() && x.get_Incluir() && x.get_Excluir()) + { + return true; + } + if (x.get_Tela() == 21 || x.get_Tela() == 5 || !x.get_Consultar() || !x.get_Alterar() || !x.get_Incluir()) + { + return false; + } + return x.get_Excluir(); + })) + { + this.AtivarDesativarPermissoesBool = false; + } + } + } + Gestor.Application.Actions.Actions.OcultarTogglesFerramentas(); + } + } + + public bool ImportarEnabled + { + get + { + return this._importarEnabled; + } + set + { + this._importarEnabled = value; + base.OnPropertyChanged("ImportarEnabled"); + } + } + + public List PermissaoAggilizador + { + get + { + return this._permissaoAggilizador; + } + set + { + this._permissaoAggilizador = value; + base.OnPropertyChanged("PermissaoAggilizador"); + } + } + + public List RestricoesAjudas + { + get + { + return this._restricoesAjudas; + } + set + { + this._restricoesAjudas = value; + base.OnPropertyChanged("RestricoesAjudas"); + } + } + + public ObservableCollection RestricoesAjudasFiltrados + { + get + { + return this._restricoesAjudasFiltrados; + } + set + { + this.RestricoesAjudasVisibility = (value == null || value.Count <= 0 ? Visibility.Collapsed : Visibility.Visible); + this._restricoesAjudasFiltrados = new ObservableCollection( + from x in value.ToList() + orderby ValidationHelper.GetDescription(x.get_Tipo()) + select x); + base.OnPropertyChanged("RestricoesAjudasFiltrados"); + this.AtivarDesativarRestricoes(); + } + } + + public Visibility RestricoesAjudasVisibility + { + get + { + return this._restricoesAjudasVisibility; + } + set + { + this._restricoesAjudasVisibility = value; + base.OnPropertyChanged("RestricoesAjudasVisibility"); + } + } + + public List RestricoesBis + { + get + { + return this._restricoesBis; + } + set + { + this._restricoesBis = value; + base.OnPropertyChanged("RestricoesBis"); + } + } + + public ObservableCollection RestricoesBisFiltradas + { + get + { + return this._restricoesBisFiltradas; + } + set + { + this.RestricoesBisVisibility = (value == null || value.Count <= 0 ? Visibility.Collapsed : Visibility.Visible); + this._restricoesBisFiltradas = new ObservableCollection( + from x in value.ToList() + orderby ValidationHelper.GetDescription(x.get_Tipo()) + select x); + base.OnPropertyChanged("RestricoesBisFiltradas"); + this.AtivarDesativarRestricoes(); + } + } + + public Visibility RestricoesBisVisibility + { + get + { + return this._restricoesBisVisibility; + } + set + { + this._restricoesBisVisibility = value; + base.OnPropertyChanged("RestricoesBisVisibility"); + } + } + + public List RestricoesCamposRelatorios + { + get + { + return this._restricoesCamposRelatorios; + } + set + { + this._restricoesCamposRelatorios = value; + base.OnPropertyChanged("RestricoesCamposRelatorios"); + } + } + + public ObservableCollection RestricoesCamposRelatoriosFiltrados + { + get + { + return this._restricoesCamposRelatoriosFiltrados; + } + set + { + this.RestricoesCamposRelatoriosVisibility = (value == null || value.Count <= 0 ? Visibility.Collapsed : Visibility.Visible); + this._restricoesCamposRelatoriosFiltrados = new ObservableCollection( + from x in value.ToList() + orderby x.get_Relatorio(), x.get_Campo() + select x); + base.OnPropertyChanged("RestricoesCamposRelatoriosFiltrados"); + this.AtivarDesativarRestricoes(); + } + } + + public Visibility RestricoesCamposRelatoriosVisibility + { + get + { + return this._restricoesCamposRelatoriosVisibility; + } + set + { + this._restricoesCamposRelatoriosVisibility = value; + base.OnPropertyChanged("RestricoesCamposRelatoriosVisibility"); + } + } + + public List RestricoesFerramentas + { + get + { + return this._restricoesFerramentas; + } + set + { + this._restricoesFerramentas = value; + base.OnPropertyChanged("RestricoesFerramentas"); + } + } + + public ObservableCollection RestricoesFerramentasFiltradas + { + get + { + return this._restricoesFerramentasFiltradas; + } + set + { + this.RestricoesFerramentasVisibility = (value == null || value.Count <= 0 ? Visibility.Collapsed : Visibility.Visible); + this._restricoesFerramentasFiltradas = new ObservableCollection( + from x in value.ToList() + orderby ValidationHelper.GetDescription(x.get_Tipo()) + select x); + base.OnPropertyChanged("RestricoesFerramentasFiltradas"); + this.AtivarDesativarRestricoes(); + } + } + + public Visibility RestricoesFerramentasVisibility + { + get + { + return this._restricoesFerramentasVisibility; + } + set + { + this._restricoesFerramentasVisibility = value; + base.OnPropertyChanged("RestricoesFerramentasVisibility"); + } + } + + public List RestricoesFinanceiros + { + get + { + return this._restricoesFinanceiros; + } + set + { + this._restricoesFinanceiros = value; + base.OnPropertyChanged("RestricoesFinanceiros"); + } + } + + public ObservableCollection RestricoesFinanceirosFiltradas + { + get + { + return this._restricoesFinanceirosFiltradas; + } + set + { + this.RestricoesFinanceirosVisibility = (value == null || value.Count <= 0 ? Visibility.Collapsed : Visibility.Visible); + this._restricoesFinanceirosFiltradas = new ObservableCollection( + from x in value.ToList() + orderby ValidationHelper.GetDescription(x.get_Tipo()) + select x); + base.OnPropertyChanged("RestricoesFinanceirosFiltradas"); + this.AtivarDesativarRestricoes(); + } + } + + public Visibility RestricoesFinanceirosVisibility + { + get + { + return this._restricoesFinanceirosVisibility; + } + set + { + this._restricoesFinanceirosVisibility = value; + base.OnPropertyChanged("RestricoesFinanceirosVisibility"); + } + } + + public List RestricoesRelatorios + { + get + { + return this._restricoesRelatorios; + } + set + { + this._restricoesRelatorios = value; + base.OnPropertyChanged("RestricoesRelatorios"); + } + } + + public ObservableCollection RestricoesRelatoriosFiltrados + { + get + { + return this._restricoesRelatoriosFiltrados; + } + set + { + this.RestricoesRelatoriosVisibility = (value == null || value.Count <= 0 ? Visibility.Collapsed : Visibility.Visible); + this._restricoesRelatoriosFiltrados = new ObservableCollection( + from x in value.ToList() + orderby ValidationHelper.GetDescription(x.get_Tipo()) + select x); + base.OnPropertyChanged("RestricoesRelatoriosFiltrados"); + this.AtivarDesativarRestricoes(); + } + } + + public Visibility RestricoesRelatoriosVisibility + { + get + { + return this._restricoesRelatoriosVisibility; + } + set + { + this._restricoesRelatoriosVisibility = value; + base.OnPropertyChanged("RestricoesRelatoriosVisibility"); + } + } + + public List RestricoesSeguros + { + get + { + return this._restricoesSeguros; + } + set + { + this._restricoesSeguros = value; + base.OnPropertyChanged("RestricoesSeguros"); + } + } + + public ObservableCollection RestricoesSegurosFiltradas + { + get + { + return this._restricoesSegurosFiltradas; + } + set + { + this.RestricoesSegurosVisibility = (value == null || value.Count <= 0 ? Visibility.Collapsed : Visibility.Visible); + this._restricoesSegurosFiltradas = new ObservableCollection( + from x in value.ToList() + orderby ValidationHelper.GetDescription(x.get_Tipo()) + select x); + base.OnPropertyChanged("RestricoesSegurosFiltradas"); + this.AtivarDesativarRestricoes(); + } + } + + public Visibility RestricoesSegurosVisibility + { + get + { + return this._restricoesSegurosVisibility; + } + set + { + this._restricoesSegurosVisibility = value; + base.OnPropertyChanged("RestricoesSegurosVisibility"); + } + } + + public List RestricoesTotalizacoesRelatorios + { + get + { + return this._restricoesTotalizacoesRelatorios; + } + set + { + this._restricoesTotalizacoesRelatorios = value; + base.OnPropertyChanged("RestricoesTotalizacoesRelatorios"); + } + } + + public ObservableCollection RestricoesTotalizacoesRelatoriosFiltrados + { + get + { + return this._restricoesTotalizacoesRelatoriosFiltrados; + } + set + { + this.RestricoesTotalizacoesRelatoriosVisibility = (value == null || value.Count <= 0 ? Visibility.Collapsed : Visibility.Visible); + this._restricoesTotalizacoesRelatoriosFiltrados = new ObservableCollection( + from x in value.ToList() + orderby ValidationHelper.GetDescription(x.get_Tipo()) + select x); + base.OnPropertyChanged("RestricoesTotalizacoesRelatoriosFiltrados"); + this.AtivarDesativarRestricoes(); + } + } + + public Visibility RestricoesTotalizacoesRelatoriosVisibility + { + get + { + return this._restricoesTotalizacoesRelatoriosVisibility; + } + set + { + this._restricoesTotalizacoesRelatoriosVisibility = value; + base.OnPropertyChanged("RestricoesTotalizacoesRelatoriosVisibility"); + } + } + + public ObservableCollection Seguros + { + get + { + return this._seguros; + } + set + { + this._seguros = value; + base.OnPropertyChanged("Seguros"); + if (value != null && this.Ferramentas != null) + { + if (value.All((PermissaoUsuario x) => { + if (x.get_Tela() == 21 && x.get_Consultar() || x.get_Tela() == 5 && x.get_Alterar() && x.get_Incluir() && x.get_Excluir()) + { + return true; + } + if (x.get_Tela() == 21 || x.get_Tela() == 5 || !x.get_Consultar() || !x.get_Alterar() || !x.get_Incluir()) + { + return false; + } + return x.get_Excluir(); + })) + { + if (this.Ferramentas.All((PermissaoUsuario x) => { + if (x.get_Tela() == 18 && x.get_Consultar() && x.get_Alterar() || x.get_Tela() == 10 && x.get_Consultar() && x.get_Alterar() && x.get_Incluir() || x.get_Tela() == 12 && x.get_Consultar() && x.get_Alterar() || x.get_Tela() == 13 && x.get_Consultar() && x.get_Alterar() && x.get_Incluir()) + { + return true; + } + if (x.get_Tela() == 18 || x.get_Tela() == 10 || x.get_Tela() == 12 || x.get_Tela() == 13 || !x.get_Consultar() || !x.get_Alterar() || !x.get_Incluir()) + { + return false; + } + return x.get_Excluir(); + })) + { + this.AtivarDesativarPermissoesBool = false; + } + } + } + Gestor.Application.Actions.Actions.OcultarTogglesSeguros(); + } + } + + public Gestor.Model.Common.PermissaoAggilizador SelectedPermissao + { + get + { + return this._selectedPermissao; + } + set + { + this._selectedPermissao = value; + base.OnPropertyChanged("SelectedPermissao"); + } + } + + public Usuario SelectedUsuario + { + get + { + return this._selectedUsuario; + } + set + { + this._selectedUsuario = value; + base.OnPropertyChanged("SelectedUsuario"); + } + } + + public PermissaoUsuarioViewModel(Usuario usuario) + { + this.SelectedUsuario = usuario; + this._servicoUsuario = new UsuarioServico(); + this.CarregarModulos(usuario); + this.EnableAlterarPermiss = Recursos.Usuario.get_Id() > (long)0; + } + + public void AtivarDesativarPermissoes(bool permiss) + { + Gestor.Model.Common.PermissaoAggilizador permissaoAggilizador; + this.AtivarDesativarPermissoesBool = !permiss; + this.Seguros.ToList().ForEach((PermissaoUsuario x) => { + x.set_Consultar(permiss); + x.set_Incluir(permiss); + x.set_Alterar(permiss); + x.set_Excluir(permiss); + }); + this.Ferramentas.ToList().ForEach((PermissaoUsuario x) => { + x.set_Consultar(permiss); + x.set_Incluir(permiss); + x.set_Alterar(permiss); + x.set_Excluir(permiss); + }); + this.ArquivosDigitais.ToList().ForEach((PermissaoArquivoDigital x) => { + x.set_Consultar(permiss); + x.set_Incluir(permiss); + x.set_Excluir(permiss); + }); + if (permiss) + { + permissaoAggilizador = this.PermissaoAggilizador.FirstOrDefault((Gestor.Model.Common.PermissaoAggilizador x) => x.get_Descricao() == "ADMINISTRADOR"); + } + else + { + permissaoAggilizador = null; + } + this.SelectedPermissao = permissaoAggilizador; + this.Seguros = new ObservableCollection(this.Seguros); + this.Ferramentas = new ObservableCollection(this.Ferramentas); + this.ArquivosDigitais = new ObservableCollection(this.ArquivosDigitais); + } + + public void AtivarDesativarRestricoes(bool restricao) + { + this.AtivarDesativarRestricoesBool = !restricao; + foreach (RestricaoUsuario restricoesBisFiltrada in this.RestricoesBisFiltradas) + { + restricoesBisFiltrada.set_Restricao(restricao); + } + foreach (RestricaoUsuario restricoesSegurosFiltrada in this.RestricoesSegurosFiltradas) + { + restricoesSegurosFiltrada.set_Restricao(restricao); + } + foreach (RestricaoUsuario restricoesRelatoriosFiltrado in this.RestricoesRelatoriosFiltrados) + { + restricoesRelatoriosFiltrado.set_Restricao(restricao); + } + foreach (RestricaoUsuario restricoesTotalizacoesRelatoriosFiltrado in this.RestricoesTotalizacoesRelatoriosFiltrados) + { + restricoesTotalizacoesRelatoriosFiltrado.set_Restricao(restricao); + } + foreach (RestricaoUsuarioCamposRelatorios restricoesCamposRelatoriosFiltrado in this.RestricoesCamposRelatoriosFiltrados) + { + restricoesCamposRelatoriosFiltrado.set_Restricao(restricao); + } + foreach (RestricaoUsuario restricoesFinanceirosFiltrada in this.RestricoesFinanceirosFiltradas) + { + restricoesFinanceirosFiltrada.set_Restricao(restricao); + } + foreach (RestricaoUsuario restricoesFerramentasFiltrada in this.RestricoesFerramentasFiltradas) + { + restricoesFerramentasFiltrada.set_Restricao(restricao); + } + foreach (RestricaoUsuario restricoesAjudasFiltrado in this.RestricoesAjudasFiltrados) + { + restricoesAjudasFiltrado.set_Restricao(restricao); + } + this.RestricoesBisFiltradas = new ObservableCollection(this.RestricoesBisFiltradas); + this.RestricoesSegurosFiltradas = new ObservableCollection(this.RestricoesSegurosFiltradas); + this.RestricoesRelatoriosFiltrados = new ObservableCollection(this.RestricoesRelatoriosFiltrados); + this.RestricoesTotalizacoesRelatoriosFiltrados = new ObservableCollection(this.RestricoesTotalizacoesRelatoriosFiltrados); + this.RestricoesCamposRelatoriosFiltrados = new ObservableCollection(this.RestricoesCamposRelatoriosFiltrados); + this.RestricoesFinanceirosFiltradas = new ObservableCollection(this.RestricoesFinanceirosFiltradas); + this.RestricoesFerramentasFiltradas = new ObservableCollection(this.RestricoesFerramentasFiltradas); + this.RestricoesAjudasFiltrados = new ObservableCollection(this.RestricoesAjudasFiltrados); + } + + public void AtivarDesativarRestricoes() + { + if (this.RestricoesBisFiltradas != null && this.RestricoesAjudasFiltrados != null && this.RestricoesSegurosFiltradas != null && this.RestricoesRelatoriosFiltrados != null && this.RestricoesFinanceirosFiltradas != null && this.RestricoesFerramentasFiltradas != null && this.RestricoesTotalizacoesRelatoriosFiltrados != null && this.RestricoesCamposRelatoriosFiltrados != null) + { + if (this.RestricoesBisFiltradas.All((RestricaoUsuario x) => x.get_Restricao())) + { + if (this.RestricoesAjudasFiltrados.All((RestricaoUsuario x) => x.get_Restricao())) + { + if (this.RestricoesSegurosFiltradas.All((RestricaoUsuario x) => x.get_Restricao())) + { + if (this.RestricoesRelatoriosFiltrados.All((RestricaoUsuario x) => x.get_Restricao())) + { + if (this.RestricoesFinanceirosFiltradas.All((RestricaoUsuario x) => x.get_Restricao())) + { + if (this.RestricoesFerramentasFiltradas.All((RestricaoUsuario x) => x.get_Restricao())) + { + if (this.RestricoesTotalizacoesRelatoriosFiltrados.All((RestricaoUsuario x) => x.get_Restricao())) + { + if (this.RestricoesCamposRelatoriosFiltrados.All((RestricaoUsuarioCamposRelatorios x) => x.get_Restricao())) + { + this.AtivarDesativarRestricoesBool = false; + } + } + } + } + } + } + } + } + } + } + + private async void CarregarModulos(Usuario usuario) + { + await this.Modulos(usuario); + this.Carregado = true; + } + + public bool CopiarPermissoes(Tuple, Usuario, List, List, List> copiarPermiss) + { + Gestor.Model.Common.PermissaoAggilizador permissaoAggilizador1; + if (copiarPermiss.Item1.Count <= 0) + { + this.Seguros.ToList().ForEach((PermissaoUsuario x) => { + x.set_Consultar(false); + x.set_Incluir(false); + x.set_Alterar(false); + x.set_Excluir(false); + x.set_Usuario(this._selectedUsuario); + }); + this.Ferramentas.ToList().ForEach((PermissaoUsuario x) => { + x.set_Consultar(false); + x.set_Incluir(false); + x.set_Alterar(false); + x.set_Excluir(false); + x.set_Usuario(this._selectedUsuario); + }); + } + else + { + copiarPermiss.Item1.ForEach((PermissaoUsuario x) => { + this.Seguros.ToList().ForEach((PermissaoUsuario y) => { + if (x.get_Tela() != y.get_Tela()) + { + return; + } + y.set_Consultar(x.get_Consultar()); + y.set_Incluir(x.get_Incluir()); + y.set_Alterar(x.get_Alterar()); + y.set_Excluir(x.get_Excluir()); + y.set_Usuario(this._selectedUsuario); + }); + this.Ferramentas.ToList().ForEach((PermissaoUsuario y) => { + if (x.get_Tela() != y.get_Tela()) + { + return; + } + y.set_Consultar(x.get_Consultar()); + y.set_Incluir(x.get_Incluir()); + y.set_Alterar(x.get_Alterar()); + y.set_Excluir(x.get_Excluir()); + y.set_Usuario(this._selectedUsuario); + }); + }); + } + if (copiarPermiss.Item4.Count <= 0) + { + this.ArquivosDigitais.ToList().ForEach((PermissaoArquivoDigital x) => { + x.set_Consultar(false); + x.set_Incluir(false); + x.set_Excluir(false); + x.set_Usuario(this._selectedUsuario); + }); + } + else + { + copiarPermiss.Item4.ForEach((PermissaoArquivoDigital x) => this.ArquivosDigitais.ToList().ForEach((PermissaoArquivoDigital y) => { + if (x.get_Tela() != y.get_Tela()) + { + return; + } + y.set_Consultar(x.get_Consultar()); + y.set_Incluir(x.get_Incluir()); + y.set_Excluir(x.get_Excluir()); + y.set_Usuario(this._selectedUsuario); + })); + } + if (copiarPermiss.Item2.get_PermissaoAggilizador().HasValue) + { + permissaoAggilizador1 = this.PermissaoAggilizador.FirstOrDefault((Gestor.Model.Common.PermissaoAggilizador x) => { + long id = x.get_Id(); + long? permissaoAggilizador = copiarPermiss.Item2.get_PermissaoAggilizador(); + return id == permissaoAggilizador.GetValueOrDefault() & permissaoAggilizador.HasValue; + }); + } + else + { + permissaoAggilizador1 = null; + } + this.SelectedPermissao = permissaoAggilizador1; + copiarPermiss.Item3.ForEach((RestricaoUsuario x) => { + foreach (RestricaoUsuario restricoesBi in this.RestricoesBis) + { + if (restricoesBi.get_Tipo() != x.get_Tipo()) + { + continue; + } + restricoesBi.set_Restricao(x.get_Restricao()); + restricoesBi.set_Usuario(this._selectedUsuario); + } + foreach (RestricaoUsuario restricoesSeguro in this.RestricoesSeguros) + { + if (restricoesSeguro.get_Tipo() != x.get_Tipo()) + { + continue; + } + restricoesSeguro.set_Restricao(x.get_Restricao()); + restricoesSeguro.set_Usuario(this._selectedUsuario); + } + foreach (RestricaoUsuario restricoesRelatorio in this.RestricoesRelatorios) + { + if (restricoesRelatorio.get_Tipo() != x.get_Tipo()) + { + continue; + } + restricoesRelatorio.set_Restricao(x.get_Restricao()); + restricoesRelatorio.set_Usuario(this._selectedUsuario); + } + foreach (RestricaoUsuario restricoesTotalizacoesRelatorio in this.RestricoesTotalizacoesRelatorios) + { + if (restricoesTotalizacoesRelatorio.get_Tipo() != x.get_Tipo()) + { + continue; + } + restricoesTotalizacoesRelatorio.set_Restricao(x.get_Restricao()); + restricoesTotalizacoesRelatorio.set_Usuario(this._selectedUsuario); + } + foreach (RestricaoUsuario restricoesFinanceiro in this.RestricoesFinanceiros) + { + if (restricoesFinanceiro.get_Tipo() != x.get_Tipo()) + { + continue; + } + restricoesFinanceiro.set_Restricao(x.get_Restricao()); + restricoesFinanceiro.set_Usuario(this._selectedUsuario); + } + foreach (RestricaoUsuario restricoesFerramenta in this.RestricoesFerramentas) + { + if (restricoesFerramenta.get_Tipo() != x.get_Tipo()) + { + continue; + } + restricoesFerramenta.set_Restricao(x.get_Restricao()); + restricoesFerramenta.set_Usuario(this._selectedUsuario); + } + foreach (RestricaoUsuario restricoesAjuda in this.RestricoesAjudas) + { + if (restricoesAjuda.get_Tipo() != x.get_Tipo()) + { + continue; + } + restricoesAjuda.set_Restricao(x.get_Restricao()); + restricoesAjuda.set_Usuario(this._selectedUsuario); + } + }); + copiarPermiss.Item5.ForEach((RestricaoUsuarioCamposRelatorios x) => { + foreach (RestricaoUsuarioCamposRelatorios restricoesCamposRelatorio in this.RestricoesCamposRelatorios) + { + if (!(restricoesCamposRelatorio.get_Campo() == x.get_Campo()) || restricoesCamposRelatorio.get_Relatorio() != x.get_Relatorio()) + { + continue; + } + restricoesCamposRelatorio.set_Restricao(x.get_Restricao()); + restricoesCamposRelatorio.set_Usuario(this._selectedUsuario); + } + }); + base.RegistrarAcao(string.Concat("IMPORTOU PERMISSÕES/RESTRIÇÕES DO USUÁRIO \"", copiarPermiss.Item2.get_Nome(), "\""), this.SelectedUsuario.get_Id(), new TipoTela?(43), string.Format("ID USUÁRIO: {0}", copiarPermiss.Item2.get_Id())); + return true; + } + + public void DesabilitarArquivoDigital(PermissaoArquivoDigital desabilitar) + { + PermissaoArquivoDigital permissaoArquivoDigital = this.ArquivosDigitais.First((PermissaoArquivoDigital x) => x.get_Tela() == desabilitar.get_Tela()); + if (!permissaoArquivoDigital.get_Incluir() && !permissaoArquivoDigital.get_Excluir()) + { + return; + } + permissaoArquivoDigital.set_Incluir(false); + permissaoArquivoDigital.set_Excluir(false); + this.ArquivosDigitais = new ObservableCollection(this.ArquivosDigitais); + } + + public void DesabilitarConsulta(PermissaoUsuario desabilitar, string source) + { + if (source != "Ferramentas") + { + PermissaoUsuario permissaoUsuario = this.Seguros.First((PermissaoUsuario x) => x.get_Tela() == desabilitar.get_Tela()); + if (!permissaoUsuario.get_Incluir() && !permissaoUsuario.get_Alterar() && !permissaoUsuario.get_Excluir()) + { + return; + } + permissaoUsuario.set_Alterar(false); + permissaoUsuario.set_Incluir(false); + permissaoUsuario.set_Excluir(false); + this.Seguros = new ObservableCollection(this.Seguros); + return; + } + PermissaoUsuario permissaoUsuario1 = this.Ferramentas.First((PermissaoUsuario x) => x.get_Tela() == desabilitar.get_Tela()); + if (!permissaoUsuario1.get_Incluir() && !permissaoUsuario1.get_Alterar() && !permissaoUsuario1.get_Excluir()) + { + return; + } + permissaoUsuario1.set_Alterar(false); + permissaoUsuario1.set_Incluir(false); + permissaoUsuario1.set_Excluir(false); + this.Ferramentas = new ObservableCollection(this.Ferramentas); + } + + public async Task ExportarPermissoes(List usuarios) + { + object obj; + List usuarios1 = usuarios; + foreach (Usuario usuario in + from x in usuarios1 + where x.get_Selecionado() + select x) + { + await this.Salvar(new long?(usuario.get_Id()), false); + } + PermissaoUsuarioViewModel permissaoUsuarioViewModel = this; + string nome = this.SelectedUsuario.get_Nome(); + object count = usuarios.Count; + obj = (usuarios.Count == 1 ? "" : "S"); + string str = string.Format("EXPORTOU PERMISSÕES/RESTRIÇÕES DO USUÁRIO \"{0}\" PARA {1} USUÁRIO{2}", nome, count, obj); + long id = this.SelectedUsuario.get_Id(); + TipoTela? nullable = new TipoTela?(43); + List usuarios2 = usuarios; + permissaoUsuarioViewModel.RegistrarAcao(str, id, nullable, string.Concat("IDS E NOMES DOS USUÁRIOS: ", string.Join("\n", + from x in usuarios2 + select string.Format("{0}: \"{1}\"", x.get_Id(), x.get_Nome())))); + return true; + } + + internal async Task> FiltrarRestricoesAjuda(string value) + { + List restricaoUsuarios = await Task.Run>(() => this.FiltrarRestricoesAjudas(value)); + return restricaoUsuarios; + } + + public List FiltrarRestricoesAjudas(string filter) + { + this.RestricoesAjudasFiltrados = (filter == "" ? new ObservableCollection(this.RestricoesAjudas) : new ObservableCollection( + from x in this.RestricoesAjudas + where ValidationHelper.RemoveDiacritics(ValidationHelper.GetDescription(x.get_Tipo()).Trim()).ToUpper().Contains(filter.ToUpper()) + select x)); + this.ExpandedAjudas = (this.RestricoesAjudasFiltrados.Count <= 0 ? false : filter != ""); + if (filter == "") + { + return null; + } + return this.RestricoesAjudasFiltrados.ToList(); + } + + internal async Task> FiltrarRestricoesBi(string value) + { + List restricaoUsuarios = await Task.Run>(() => this.FiltrarRestricoesBis(value)); + return restricaoUsuarios; + } + + public List FiltrarRestricoesBis(string filter) + { + this.RestricoesBisFiltradas = (filter == "" ? new ObservableCollection(this.RestricoesBis) : new ObservableCollection( + from x in this.RestricoesBis + where ValidationHelper.RemoveDiacritics(ValidationHelper.GetDescription(x.get_Tipo()).Trim()).ToUpper().Contains(filter.ToUpper()) + select x)); + this.ExpandedBis = (this.RestricoesBisFiltradas.Count <= 0 ? false : filter != ""); + if (filter == "") + { + return null; + } + return this.RestricoesBisFiltradas.ToList(); + } + + internal async Task> FiltrarRestricoesCamposRelatorio(string value) + { + List restricaoUsuarioCamposRelatorios = await Task.Run>(() => this.FiltrarRestricoesCamposRelatorios(value)); + return restricaoUsuarioCamposRelatorios; + } + + public List FiltrarRestricoesCamposRelatorios(string filter) + { + this.RestricoesCamposRelatoriosFiltrados = (filter == "" ? new ObservableCollection(this.RestricoesCamposRelatorios) : new ObservableCollection(this.RestricoesCamposRelatorios.Where((RestricaoUsuarioCamposRelatorios x) => { + if (ValidationHelper.RemoveDiacritics(x.get_Campo().ToUpper().Trim()).Contains(filter.ToUpper())) + { + return true; + } + return ValidationHelper.RemoveDiacritics(ValidationHelper.GetDescription(x.get_Relatorio()).Trim()).ToUpper().Contains(filter.ToUpper()); + }))); + this.ExpandedCampos = (this.RestricoesCamposRelatoriosFiltrados.Count <= 0 ? false : filter != ""); + if (filter == "") + { + return null; + } + return this.RestricoesCamposRelatoriosFiltrados.ToList(); + } + + internal async Task> FiltrarRestricoesFerramenta(string value) + { + List restricaoUsuarios = await Task.Run>(() => this.FiltrarRestricoesFerramentas(value)); + return restricaoUsuarios; + } + + public List FiltrarRestricoesFerramentas(string filter) + { + this.RestricoesFerramentasFiltradas = (filter == "" ? new ObservableCollection(this.RestricoesFerramentas) : new ObservableCollection( + from x in this.RestricoesFerramentas + where ValidationHelper.RemoveDiacritics(ValidationHelper.GetDescription(x.get_Tipo()).Trim()).ToUpper().Contains(filter.ToUpper()) + select x)); + this.ExpandedFerramentas = (this.RestricoesFerramentasFiltradas.Count <= 0 ? false : filter != ""); + if (filter == "") + { + return null; + } + return this.RestricoesFerramentasFiltradas.ToList(); + } + + internal async Task> FiltrarRestricoesFinanceiro(string value) + { + List restricaoUsuarios = await Task.Run>(() => this.FiltrarRestricoesFinanceiros(value)); + return restricaoUsuarios; + } + + public List FiltrarRestricoesFinanceiros(string filter) + { + this.RestricoesFinanceirosFiltradas = (filter == "" ? new ObservableCollection(this.RestricoesFinanceiros) : new ObservableCollection( + from x in this.RestricoesFinanceiros + where ValidationHelper.RemoveDiacritics(ValidationHelper.GetDescription(x.get_Tipo()).Trim()).ToUpper().Contains(filter.ToUpper()) + select x)); + this.ExpandedFinanceiros = (this.RestricoesFinanceirosFiltradas.Count <= 0 ? false : filter != ""); + if (filter == "") + { + return null; + } + return this.RestricoesFinanceirosFiltradas.ToList(); + } + + internal async Task> FiltrarRestricoesRelatorio(string value) + { + List restricaoUsuarios = await Task.Run>(() => this.FiltrarRestricoesRelatorios(value)); + return restricaoUsuarios; + } + + public List FiltrarRestricoesRelatorios(string filter) + { + this.RestricoesRelatoriosFiltrados = (filter == "" ? new ObservableCollection(this.RestricoesRelatorios) : new ObservableCollection( + from x in this.RestricoesRelatorios + where ValidationHelper.RemoveDiacritics(ValidationHelper.GetDescription(x.get_Tipo()).Trim()).ToUpper().Contains(filter.ToUpper()) + select x)); + this.ExpandedRelatorios = (this.RestricoesRelatoriosFiltrados.Count <= 0 ? false : filter != ""); + if (filter == "") + { + return null; + } + return this.RestricoesRelatoriosFiltrados.ToList(); + } + + internal async Task> FiltrarRestricoesSeguro(string value) + { + List restricaoUsuarios = await Task.Run>(() => this.FiltrarRestricoesSeguros(value)); + return restricaoUsuarios; + } + + public List FiltrarRestricoesSeguros(string filter) + { + this.RestricoesSegurosFiltradas = (filter == "" ? new ObservableCollection(this.RestricoesSeguros) : new ObservableCollection( + from x in this.RestricoesSeguros + where ValidationHelper.RemoveDiacritics(ValidationHelper.GetDescription(x.get_Tipo()).Trim()).ToUpper().Contains(filter.ToUpper()) + select x)); + this.ExpandedSeguros = (this.RestricoesSegurosFiltradas.Count <= 0 ? false : filter != ""); + if (filter == "") + { + return null; + } + return this.RestricoesSegurosFiltradas.ToList(); + } + + internal async Task> FiltrarRestricoesTotalizacoesRelatorio(string value) + { + List restricaoUsuarios = await Task.Run>(() => this.FiltrarRestricoesTotalizacoesRelatorios(value)); + return restricaoUsuarios; + } + + public List FiltrarRestricoesTotalizacoesRelatorios(string filter) + { + this.RestricoesTotalizacoesRelatoriosFiltrados = (filter == "" ? new ObservableCollection(this.RestricoesTotalizacoesRelatorios) : new ObservableCollection( + from x in this.RestricoesTotalizacoesRelatorios + where ValidationHelper.RemoveDiacritics(ValidationHelper.GetDescription(x.get_Tipo()).Trim()).ToUpper().Contains(filter.ToUpper()) + select x)); + this.ExpandedTotalizacoes = (this.RestricoesTotalizacoesRelatoriosFiltrados.Count <= 0 ? false : filter != ""); + if (filter == "") + { + return null; + } + return this.RestricoesTotalizacoesRelatoriosFiltrados.ToList(); + } + + private async Task> GetPermissoes(Usuario usuario, string modulo) + { + List permissaoUsuarios = new List(); + IEnumerable tipoTelas = Enum.GetValues(typeof(TipoTela)).Cast(); + IEnumerable str = + from v in tipoTelas + select v.ToString(); + List list = ( + from x in str + orderby x + select x).ToList(); + List permissaoUsuarios1 = await this.ServicoPermissUsuario.PermissUsuario(usuario); + list.ForEach((string x) => { + TipoTela tipoTela = (TipoTela)Enum.Parse(typeof(TipoTela), x); + if (!string.Equals(ValidationHelper.GetCategory(tipoTela), modulo, StringComparison.CurrentCultureIgnoreCase)) + { + return; + } + long id = (long)0; + bool consultar = true; + bool incluir = true; + bool alterar = true; + bool excluir = true; + if (permissaoUsuarios1.Count > 0 && permissaoUsuarios1.Any((PermissaoUsuario y) => y.get_Tela() == tipoTela)) + { + id = permissaoUsuarios1.First((PermissaoUsuario y) => y.get_Tela() == tipoTela).get_Id(); + consultar = permissaoUsuarios1.First((PermissaoUsuario y) => y.get_Tela() == tipoTela).get_Consultar(); + incluir = permissaoUsuarios1.First((PermissaoUsuario y) => y.get_Tela() == tipoTela).get_Incluir(); + alterar = permissaoUsuarios1.First((PermissaoUsuario y) => y.get_Tela() == tipoTela).get_Alterar(); + excluir = permissaoUsuarios1.First((PermissaoUsuario y) => y.get_Tela() == tipoTela).get_Excluir(); + } + PermissaoUsuario permissaoUsuario = new PermissaoUsuario(); + permissaoUsuario.set_Id(id); + permissaoUsuario.set_Tela(tipoTela); + permissaoUsuario.set_Consultar(consultar); + permissaoUsuario.set_Incluir(incluir); + permissaoUsuario.set_Alterar(alterar); + permissaoUsuario.set_Excluir(excluir); + permissaoUsuarios.Add(permissaoUsuario); + }); + List permissaoUsuarios2 = permissaoUsuarios; + list = null; + return permissaoUsuarios2; + } + + private async Task> GetPermissoesArquivoDigital(Usuario usuario) + { + List permissaoArquivoDigitals = new List(); + IEnumerable tipoArquivoDigitals = Enum.GetValues(typeof(TipoArquivoDigital)).Cast(); + IEnumerable str = + from v in tipoArquivoDigitals + select v.ToString(); + List list = ( + from x in str + orderby x + select x).ToList(); + List permissaoArquivoDigitals1 = await this.ServicoPermissArquivoDigital.PermissArquivoDigital(usuario); + list.ForEach((string x) => { + TipoArquivoDigital tipoArquivoDigital = (TipoArquivoDigital)Enum.Parse(typeof(TipoArquivoDigital), x); + long id = (long)0; + bool consultar = true; + bool incluir = true; + bool excluir = true; + if (permissaoArquivoDigitals1.Count > 0 && permissaoArquivoDigitals1.Any((PermissaoArquivoDigital y) => y.get_Tela() == tipoArquivoDigital)) + { + id = permissaoArquivoDigitals1.First((PermissaoArquivoDigital y) => y.get_Tela() == tipoArquivoDigital).get_Id(); + consultar = permissaoArquivoDigitals1.First((PermissaoArquivoDigital y) => y.get_Tela() == tipoArquivoDigital).get_Consultar(); + incluir = permissaoArquivoDigitals1.First((PermissaoArquivoDigital y) => y.get_Tela() == tipoArquivoDigital).get_Incluir(); + excluir = permissaoArquivoDigitals1.First((PermissaoArquivoDigital y) => y.get_Tela() == tipoArquivoDigital).get_Excluir(); + } + PermissaoArquivoDigital permissaoArquivoDigital = new PermissaoArquivoDigital(); + permissaoArquivoDigital.set_Id(id); + permissaoArquivoDigital.set_Tela(tipoArquivoDigital); + permissaoArquivoDigital.set_Consultar(consultar); + permissaoArquivoDigital.set_Incluir(incluir); + permissaoArquivoDigital.set_Excluir(excluir); + permissaoArquivoDigitals.Add(permissaoArquivoDigital); + }); + List permissaoArquivoDigitals2 = permissaoArquivoDigitals; + list = null; + return permissaoArquivoDigitals2; + } + + private async Task> GetRestricoes(Usuario usuario, string modulo) + { + List restricaoUsuarios = new List(); + IEnumerable tipoRestricaos = Enum.GetValues(typeof(TipoRestricao)).Cast(); + IEnumerable str = + from v in tipoRestricaos + select v.ToString(); + List list = ( + from x in str + orderby x + select x).ToList(); + List restricaoUsuarios1 = await this.ServicoRestriUsuario.BuscarRestricoes(usuario.get_Id()); + List restricaoUsuarios2 = restricaoUsuarios1; + list.ForEach((string x) => { + TipoRestricao tipoRestricao = (TipoRestricao)Enum.Parse(typeof(TipoRestricao), x); + if (!string.Equals(ValidationHelper.GetCategory(tipoRestricao), modulo, StringComparison.CurrentCultureIgnoreCase)) + { + return; + } + string help = ValidationHelper.GetHelp(tipoRestricao); + long id = (long)0; + bool restricao = false; + if (restricaoUsuarios2.Count > 0 && restricaoUsuarios2.Any((RestricaoUsuario y) => y.get_Tipo() == tipoRestricao)) + { + id = restricaoUsuarios2.First((RestricaoUsuario y) => y.get_Tipo() == tipoRestricao).get_Id(); + restricao = restricaoUsuarios2.First((RestricaoUsuario y) => y.get_Tipo() == tipoRestricao).get_Restricao(); + } + RestricaoUsuario restricaoUsuario = new RestricaoUsuario(); + restricaoUsuario.set_Id(id); + restricaoUsuario.set_Tipo(tipoRestricao); + restricaoUsuario.set_Restricao(restricao); + restricaoUsuario.set_Ajuda(help); + restricaoUsuarios.Add(restricaoUsuario); + }); + List restricaoUsuarios3 = restricaoUsuarios; + list = null; + return restricaoUsuarios3; + } + + private async Task> GetRestricoesCamposRelatorios(Usuario usuario) + { + List restricaoUsuarioCamposRelatorios = new List(); + List parametrosRelatorios = new List(); + foreach (Relatorio relatorio in Enum.GetValues(typeof(Relatorio)).Cast()) + { + switch (relatorio) + { + case 0: + case 1: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 2: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 3: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 4: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 5: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 6: + case 16: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 7: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 8: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 9: + case 10: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 11: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 12: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 13: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 14: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 15: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 17: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 18: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 19: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 20: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 23: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 27: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + default: + { + continue; + } + } + } + List restricaoUsuarioCamposRelatorios1 = await this.ServicoRestriUsuario.BuscarRestricoesCamposRelatorios(usuario.get_Id()); + List restricaoUsuarioCamposRelatorios2 = restricaoUsuarioCamposRelatorios1; + parametrosRelatorios.ForEach((ParametrosRelatorio x) => { + long id = (long)0; + bool restricao = false; + if (restricaoUsuarioCamposRelatorios2.Count > 0 && restricaoUsuarioCamposRelatorios2.Any((RestricaoUsuarioCamposRelatorios y) => { + if (y.get_Campo() != x.get_Header()) + { + return false; + } + return y.get_Relatorio() == x.get_Relatorio(); + })) + { + id = restricaoUsuarioCamposRelatorios2.First((RestricaoUsuarioCamposRelatorios y) => { + if (y.get_Campo() != x.get_Header()) + { + return false; + } + return y.get_Relatorio() == x.get_Relatorio(); + }).get_Id(); + restricao = restricaoUsuarioCamposRelatorios2.First((RestricaoUsuarioCamposRelatorios y) => { + if (y.get_Campo() != x.get_Header()) + { + return false; + } + return y.get_Relatorio() == x.get_Relatorio(); + }).get_Restricao(); + } + RestricaoUsuarioCamposRelatorios restricaoUsuarioCamposRelatorio = new RestricaoUsuarioCamposRelatorios(); + restricaoUsuarioCamposRelatorio.set_Id(id); + restricaoUsuarioCamposRelatorio.set_Campo(x.get_Header()); + restricaoUsuarioCamposRelatorio.set_Relatorio(x.get_Relatorio()); + restricaoUsuarioCamposRelatorio.set_Restricao(restricao); + restricaoUsuarioCamposRelatorios.Add(restricaoUsuarioCamposRelatorio); + }); + List restricaoUsuarioCamposRelatorios3 = restricaoUsuarioCamposRelatorios; + parametrosRelatorios = null; + return restricaoUsuarioCamposRelatorios3; + } + + public void HabilitarArquivoDigital(PermissaoArquivoDigital habilitar) + { + PermissaoArquivoDigital permissaoArquivoDigital = this.ArquivosDigitais.First((PermissaoArquivoDigital x) => x.get_Tela() == habilitar.get_Tela()); + if (permissaoArquivoDigital.get_Consultar()) + { + return; + } + permissaoArquivoDigital.set_Consultar(true); + this.ArquivosDigitais = new ObservableCollection(this.ArquivosDigitais); + } + + public void HabilitarConsulta(PermissaoUsuario habilitar, string source) + { + if (source != "Ferramentas") + { + PermissaoUsuario permissaoUsuario = this.Seguros.First((PermissaoUsuario x) => x.get_Tela() == habilitar.get_Tela()); + if (permissaoUsuario.get_Consultar()) + { + return; + } + permissaoUsuario.set_Consultar(true); + this.Seguros = new ObservableCollection(this.Seguros); + return; + } + PermissaoUsuario permissaoUsuario1 = this.Ferramentas.First((PermissaoUsuario x) => x.get_Tela() == habilitar.get_Tela()); + if (permissaoUsuario1.get_Consultar()) + { + return; + } + permissaoUsuario1.set_Consultar(true); + this.Ferramentas = new ObservableCollection(this.Ferramentas); + } + + private async Task Modulos(Usuario usuario) + { + Gestor.Model.Common.PermissaoAggilizador permissaoAggilizador1; + Usuario usuario1 = usuario; + this.Carregando = true; + Usuario usuario2 = await this._servicoUsuario.BuscarUsuarioPorId(usuario1.get_Id()); + usuario1 = usuario2; + this.Seguros = new ObservableCollection(await this.GetPermissoes(usuario1, "seguros")); + this.Ferramentas = new ObservableCollection(await this.GetPermissoes(usuario1, "ferramentas")); + this.ArquivosDigitais = new ObservableCollection(await this.GetPermissoesArquivoDigital(usuario1)); + this.PermissaoAggilizador = new List((IEnumerable)await this._servicoUsuario.BuscarPermissaoAggilizador()); + this.RestricoesBis = await this.GetRestricoes(usuario1, "b.i."); + this.RestricoesBisFiltradas = new ObservableCollection(this.RestricoesBis); + this.RestricoesSeguros = await this.GetRestricoes(usuario1, "seguros"); + this.RestricoesSegurosFiltradas = new ObservableCollection(this.RestricoesSeguros); + this.RestricoesRelatorios = await this.GetRestricoes(usuario1, "relatorios"); + this.RestricoesRelatoriosFiltrados = new ObservableCollection(this.RestricoesRelatorios); + this.RestricoesFinanceiros = await this.GetRestricoes(usuario1, "financeiro"); + this.RestricoesFinanceirosFiltradas = new ObservableCollection(this.RestricoesFinanceiros); + this.RestricoesFerramentas = await this.GetRestricoes(usuario1, "ferramentas"); + this.RestricoesFerramentasFiltradas = new ObservableCollection(this.RestricoesFerramentas); + this.RestricoesAjudas = await this.GetRestricoes(usuario1, "ajuda"); + this.RestricoesAjudasFiltrados = new ObservableCollection(this.RestricoesAjudas); + this.RestricoesTotalizacoesRelatorios = await this.GetRestricoes(usuario1, "totalizacoesRelatorios"); + this.RestricoesTotalizacoesRelatoriosFiltrados = new ObservableCollection(this.RestricoesTotalizacoesRelatorios); + this.RestricoesCamposRelatorios = await this.GetRestricoesCamposRelatorios(usuario1); + this.RestricoesCamposRelatoriosFiltrados = new ObservableCollection(this.RestricoesCamposRelatorios); + this.Carregando = false; + this.AdmUsuario = usuario1.get_Administrador(); + PermissaoUsuarioViewModel permissaoUsuarioViewModel = this; + if (!usuario1.get_PermissaoAggilizador().HasValue) + { + List permissaoAggilizadors = this.PermissaoAggilizador; + permissaoAggilizador1 = permissaoAggilizadors.FirstOrDefault((Gestor.Model.Common.PermissaoAggilizador x) => x.get_Id() == (long)2); + } + else + { + permissaoAggilizador1 = this.PermissaoAggilizador.FirstOrDefault((Gestor.Model.Common.PermissaoAggilizador x) => { + long id = x.get_Id(); + long? permissaoAggilizador = usuario1.get_PermissaoAggilizador(); + return id == permissaoAggilizador.GetValueOrDefault() & permissaoAggilizador.HasValue; + }); + } + permissaoUsuarioViewModel.SelectedPermissao = permissaoAggilizador1; + } + + public async Task Salvar(long? idUsuario = null, bool registrar = true) + { + bool flag; + bool alterar; + long num; + long id; + List permissaoUsuarios; + List restricaoUsuarioCamposRelatorios; + PermissaoUsuario permissaoUsuario1 = this.ServicoPermissUsuario.BuscarPermissao(Recursos.Usuario, 43); + if (permissaoUsuario1 != null) + { + alterar = !permissaoUsuario1.get_Alterar(); + } + else + { + alterar = false; + } + if (!alterar || Recursos.Usuario.get_Administrador()) + { + UsuarioServico usuarioServico = this._servicoUsuario; + long? nullable = idUsuario; + num = (nullable.HasValue ? nullable.GetValueOrDefault() : this._selectedUsuario.get_Id()); + Usuario usuario = await usuarioServico.BuscarUsuarioPorId(num); + List permissaoUsuarios1 = new List(); + List permissaoUsuarios2 = permissaoUsuarios1; + List permissoes = await this.GetPermissoes(usuario, "seguros"); + permissaoUsuarios2.AddRange(permissoes); + permissaoUsuarios2 = null; + permissaoUsuarios2 = permissaoUsuarios1; + permissoes = await this.GetPermissoes(usuario, "ferramentas"); + permissaoUsuarios2.AddRange(permissoes); + permissaoUsuarios2 = null; + List permissaoArquivoDigitals = new List(); + List permissaoArquivoDigitals1 = permissaoArquivoDigitals; + permissaoArquivoDigitals1.AddRange(await this.GetPermissoesArquivoDigital(usuario)); + permissaoArquivoDigitals1 = null; + List list = this.ArquivosDigitais.Select((PermissaoArquivoDigital x) => { + PermissaoArquivoDigital permissaoArquivoDigital = new PermissaoArquivoDigital(); + permissaoArquivoDigital.set_Id((permissaoArquivoDigitals.Count == 0 ? (long)0 : permissaoArquivoDigitals.First((PermissaoArquivoDigital y) => y.get_Tela() == x.get_Tela()).get_Id())); + permissaoArquivoDigital.set_Tela(x.get_Tela()); + permissaoArquivoDigital.set_Consultar(x.get_Consultar()); + permissaoArquivoDigital.set_Incluir(x.get_Incluir()); + permissaoArquivoDigital.set_Excluir(x.get_Excluir()); + permissaoArquivoDigital.set_Usuario(usuario); + return permissaoArquivoDigital; + }).ToList(); + permissaoUsuarios = new List(); + List list1 = this.Seguros.Select((PermissaoUsuario x) => { + PermissaoUsuario permissaoUsuario = new PermissaoUsuario(); + permissaoUsuario.set_Id((permissaoUsuarios1.Count == 0 ? (long)0 : permissaoUsuarios1.First((PermissaoUsuario y) => y.get_Tela() == x.get_Tela()).get_Id())); + permissaoUsuario.set_Tela(x.get_Tela()); + permissaoUsuario.set_Consultar(x.get_Consultar()); + permissaoUsuario.set_Incluir(x.get_Incluir()); + permissaoUsuario.set_Alterar(x.get_Alterar()); + permissaoUsuario.set_Excluir(x.get_Excluir()); + permissaoUsuario.set_Usuario(usuario); + return permissaoUsuario; + }).ToList(); + permissaoUsuarios.AddRange(list1); + list1 = this.Ferramentas.Select((PermissaoUsuario x) => { + PermissaoUsuario permissaoUsuario = new PermissaoUsuario(); + permissaoUsuario.set_Id((permissaoUsuarios1.Count == 0 ? (long)0 : permissaoUsuarios1.First((PermissaoUsuario y) => y.get_Tela() == x.get_Tela()).get_Id())); + permissaoUsuario.set_Tela(x.get_Tela()); + permissaoUsuario.set_Consultar(x.get_Consultar()); + permissaoUsuario.set_Incluir(x.get_Incluir()); + permissaoUsuario.set_Alterar(x.get_Alterar()); + permissaoUsuario.set_Excluir(x.get_Excluir()); + permissaoUsuario.set_Usuario(usuario); + return permissaoUsuario; + }).ToList(); + permissaoUsuarios.AddRange(list1); + Usuario usuario1 = usuario; + Gestor.Model.Common.PermissaoAggilizador selectedPermissao = this.SelectedPermissao; + if (selectedPermissao != null) + { + id = selectedPermissao.get_Id(); + } + else + { + id = (long)0; + } + usuario1.set_PermissaoAggilizador(new long?(id)); + usuario.set_Administrador(this.AdmUsuario); + await this.ServicoPermissArquivoDigital.SavePermiss(list, permissaoArquivoDigitals); + if (this.ServicoPermissArquivoDigital.Sucesso) + { + await this.ServicoPermissUsuario.SavePermiss(permissaoUsuarios, permissaoUsuarios1); + if (this.ServicoPermissUsuario.Sucesso) + { + await this._servicoUsuario.Save(usuario); + if (this._servicoUsuario.Sucesso) + { + if (Recursos.Usuario.get_Id() == this._selectedUsuario.get_Id()) + { + Recursos.Usuario = usuario; + } + List restricaoUsuarios = new List(); + List restricaoUsuarios1 = restricaoUsuarios; + List restricoes = await this.GetRestricoes(usuario, "b.i."); + restricaoUsuarios1.AddRange(restricoes); + restricaoUsuarios1 = null; + restricaoUsuarios1 = restricaoUsuarios; + restricoes = await this.GetRestricoes(usuario, "seguros"); + restricaoUsuarios1.AddRange(restricoes); + restricaoUsuarios1 = null; + restricaoUsuarios1 = restricaoUsuarios; + restricoes = await this.GetRestricoes(usuario, "relatorios"); + restricaoUsuarios1.AddRange(restricoes); + restricaoUsuarios1 = null; + restricaoUsuarios1 = restricaoUsuarios; + restricoes = await this.GetRestricoes(usuario, "financeiro"); + restricaoUsuarios1.AddRange(restricoes); + restricaoUsuarios1 = null; + restricaoUsuarios1 = restricaoUsuarios; + restricoes = await this.GetRestricoes(usuario, "ferramentas"); + restricaoUsuarios1.AddRange(restricoes); + restricaoUsuarios1 = null; + restricaoUsuarios1 = restricaoUsuarios; + restricoes = await this.GetRestricoes(usuario, "ajuda"); + restricaoUsuarios1.AddRange(restricoes); + restricaoUsuarios1 = null; + restricaoUsuarios1 = restricaoUsuarios; + restricoes = await this.GetRestricoes(usuario, "totalizacoesRelatorios"); + restricaoUsuarios1.AddRange(restricoes); + restricaoUsuarios1 = null; + restricaoUsuarios1 = restricaoUsuarios; + restricoes = await this.GetRestricoes(usuario, "camposRelatorios"); + restricaoUsuarios1.AddRange(restricoes); + restricaoUsuarios1 = null; + List restricaoUsuarioCamposRelatorios1 = new List(); + List restricaoUsuarioCamposRelatorios2 = restricaoUsuarioCamposRelatorios1; + restricaoUsuarioCamposRelatorios2.AddRange(await this.GetRestricoesCamposRelatorios(usuario)); + restricaoUsuarioCamposRelatorios2 = null; + List restricaoUsuarios2 = new List(); + restricaoUsuarioCamposRelatorios = new List(); + List list2 = this.RestricoesBis.Select((RestricaoUsuario x) => { + RestricaoUsuario restricaoUsuario = new RestricaoUsuario(); + restricaoUsuario.set_Id((restricaoUsuarios.Count == 0 ? (long)0 : restricaoUsuarios.First((RestricaoUsuario y) => y.get_Tipo() == x.get_Tipo()).get_Id())); + restricaoUsuario.set_Tipo(x.get_Tipo()); + restricaoUsuario.set_Restricao(x.get_Restricao()); + restricaoUsuario.set_Usuario(usuario); + return restricaoUsuario; + }).ToList(); + restricaoUsuarios2.AddRange(list2); + list2 = this.RestricoesSeguros.Select((RestricaoUsuario x) => { + RestricaoUsuario restricaoUsuario = new RestricaoUsuario(); + restricaoUsuario.set_Id((restricaoUsuarios.Count == 0 ? (long)0 : restricaoUsuarios.First((RestricaoUsuario y) => y.get_Tipo() == x.get_Tipo()).get_Id())); + restricaoUsuario.set_Tipo(x.get_Tipo()); + restricaoUsuario.set_Restricao(x.get_Restricao()); + restricaoUsuario.set_Usuario(usuario); + return restricaoUsuario; + }).ToList(); + restricaoUsuarios2.AddRange(list2); + list2 = this.RestricoesRelatorios.Select((RestricaoUsuario x) => { + RestricaoUsuario restricaoUsuario = new RestricaoUsuario(); + restricaoUsuario.set_Id((restricaoUsuarios.Count == 0 ? (long)0 : restricaoUsuarios.First((RestricaoUsuario y) => y.get_Tipo() == x.get_Tipo()).get_Id())); + restricaoUsuario.set_Tipo(x.get_Tipo()); + restricaoUsuario.set_Restricao(x.get_Restricao()); + restricaoUsuario.set_Usuario(usuario); + return restricaoUsuario; + }).ToList(); + restricaoUsuarios2.AddRange(list2); + list2 = this.RestricoesTotalizacoesRelatorios.Select((RestricaoUsuario x) => { + RestricaoUsuario restricaoUsuario = new RestricaoUsuario(); + restricaoUsuario.set_Id((restricaoUsuarios.Count == 0 ? (long)0 : restricaoUsuarios.First((RestricaoUsuario y) => y.get_Tipo() == x.get_Tipo()).get_Id())); + restricaoUsuario.set_Tipo(x.get_Tipo()); + restricaoUsuario.set_Restricao(x.get_Restricao()); + restricaoUsuario.set_Usuario(usuario); + return restricaoUsuario; + }).ToList(); + restricaoUsuarios2.AddRange(list2); + list2 = this.RestricoesFinanceiros.Select((RestricaoUsuario x) => { + RestricaoUsuario restricaoUsuario = new RestricaoUsuario(); + restricaoUsuario.set_Id((restricaoUsuarios.Count == 0 ? (long)0 : restricaoUsuarios.First((RestricaoUsuario y) => y.get_Tipo() == x.get_Tipo()).get_Id())); + restricaoUsuario.set_Tipo(x.get_Tipo()); + restricaoUsuario.set_Restricao(x.get_Restricao()); + restricaoUsuario.set_Usuario(usuario); + return restricaoUsuario; + }).ToList(); + restricaoUsuarios2.AddRange(list2); + list2 = this.RestricoesFerramentas.Select((RestricaoUsuario x) => { + RestricaoUsuario restricaoUsuario = new RestricaoUsuario(); + restricaoUsuario.set_Id((restricaoUsuarios.Count == 0 ? (long)0 : restricaoUsuarios.First((RestricaoUsuario y) => y.get_Tipo() == x.get_Tipo()).get_Id())); + restricaoUsuario.set_Tipo(x.get_Tipo()); + restricaoUsuario.set_Restricao(x.get_Restricao()); + restricaoUsuario.set_Usuario(usuario); + return restricaoUsuario; + }).ToList(); + restricaoUsuarios2.AddRange(list2); + list2 = this.RestricoesAjudas.Select((RestricaoUsuario x) => { + RestricaoUsuario restricaoUsuario = new RestricaoUsuario(); + restricaoUsuario.set_Id((restricaoUsuarios.Count == 0 ? (long)0 : restricaoUsuarios.First((RestricaoUsuario y) => y.get_Tipo() == x.get_Tipo()).get_Id())); + restricaoUsuario.set_Tipo(x.get_Tipo()); + restricaoUsuario.set_Restricao(x.get_Restricao()); + restricaoUsuario.set_Usuario(usuario); + return restricaoUsuario; + }).ToList(); + restricaoUsuarios2.AddRange(list2); + List list3 = this.RestricoesCamposRelatorios.Select((RestricaoUsuarioCamposRelatorios x) => { + RestricaoUsuarioCamposRelatorios restricaoUsuarioCamposRelatorio = new RestricaoUsuarioCamposRelatorios(); + restricaoUsuarioCamposRelatorio.set_Id((restricaoUsuarioCamposRelatorios1.Count == 0 ? (long)0 : restricaoUsuarioCamposRelatorios1.First((RestricaoUsuarioCamposRelatorios y) => { + if (y.get_Campo() != x.get_Campo()) + { + return false; + } + return y.get_Relatorio() == x.get_Relatorio(); + }).get_Id())); + restricaoUsuarioCamposRelatorio.set_Campo(x.get_Campo()); + restricaoUsuarioCamposRelatorio.set_Restricao(x.get_Restricao()); + restricaoUsuarioCamposRelatorio.set_Relatorio(x.get_Relatorio()); + restricaoUsuarioCamposRelatorio.set_Usuario(usuario); + return restricaoUsuarioCamposRelatorio; + }).ToList(); + restricaoUsuarioCamposRelatorios.AddRange(list3); + await this.ServicoRestriUsuario.SaveRestri(restricaoUsuarios2, restricaoUsuarios); + if (this.ServicoRestriUsuario.Sucesso) + { + await this.ServicoRestriUsuario.SaveRestriCamposRelatorios(restricaoUsuarioCamposRelatorios, restricaoUsuarioCamposRelatorios1); + if (this.ServicoRestriUsuario.Sucesso) + { + if (registrar) + { + base.RegistrarAcao(string.Concat("ALTEROU PERMISSÕES/RESTRIÇÕES DO USUÁRIO \"", this.SelectedUsuario.get_Nome(), "\""), this.SelectedUsuario.get_Id(), new TipoTela?(43), "ACESSE O LOG DE ALTERAÇÕES NA TELA DE PERMISSÕES/RESTRIÇÕES PARA VER EXATAMENTE O QUE FOI ALTERADO."); + } + flag = true; + } + else + { + flag = false; + } + } + else + { + flag = false; + } + } + else + { + flag = false; + } + } + else + { + flag = false; + } + } + else + { + flag = false; + } + } + else + { + await base.ShowMessage("VOCÊ NÃO TEM PERMISSÃO PARA ALTERAR PERMISSÕES!", "OK", "", false); + flag = false; + } + permissaoUsuarios = null; + restricaoUsuarioCamposRelatorios = null; + return flag; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/TarefaDrawerViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/TarefaDrawerViewModel.cs new file mode 100644 index 0000000..6a68199 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/TarefaDrawerViewModel.cs @@ -0,0 +1,1283 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class TarefaDrawerViewModel : BaseTarefaViewModel + { + private bool _enableMenu = true; + + private GridLength _dados = new GridLength(0, GridUnitType.Pixel); + + private GridLength _grid = new GridLength(1, GridUnitType.Star); + + private GridLength _anotacoesLength = new GridLength(0, GridUnitType.Pixel); + + private GridLength _descricaoLength = new GridLength(1, GridUnitType.Star); + + private GridLength _anotacoesInternasLength = new GridLength(0, GridUnitType.Pixel); + + private GridLength _descricaoInternaLength = new GridLength(1, GridUnitType.Star); + + private bool _enableAlterarTarefa = true; + + private Visibility _visibilityMenu; + + private bool _isVisibleDescricao; + + private bool _isSelected; + + private bool _concluido; + + private bool _carregando; + + private string _tituloTarefas; + + private string _titulo; + + private string _subTitulo; + + private Gestor.Model.Domain.Ferramentas.Tarefa _tarefa = new Gestor.Model.Domain.Ferramentas.Tarefa(); + + private ObservableCollection _tarefasFiltradas = new ObservableCollection(); + + private List _tarefas = new List(); + + private bool _isAnotacoes = true; + + private Gestor.Model.Domain.Ferramentas.Tarefa _selectedTarefa; + + private ObservableCollection _usuarios; + + private ObservableCollection _tiposTarefa; + + private List _telefones; + + private DateTime _dataAgendamento = Funcoes.GetNetworkTime(); + + private DateTime _horaAgendamento = Funcoes.GetNetworkTime(); + + private Usuario _selectedUsuario; + + private TipoDeTarefa _selectedTipoTarefa; + + private Gestor.Model.Domain.Common.ArquivoDigital _selectedAnexado = new Gestor.Model.Domain.Common.ArquivoDigital(); + + private ObservableCollection _arquivosAnexados = new ObservableCollection(); + + private List _arquivosFinais = new List(); + + private bool _inclusaoArquivoDigitalEnable = true; + + public GridLength AnotacoesInternasLength + { + get + { + return this._anotacoesInternasLength; + } + set + { + this._anotacoesInternasLength = value; + base.OnPropertyChanged("AnotacoesInternasLength"); + } + } + + public GridLength AnotacoesLength + { + get + { + return this._anotacoesLength; + } + set + { + this._anotacoesLength = value; + base.OnPropertyChanged("AnotacoesLength"); + } + } + + public ObservableCollection ArquivosAnexados + { + get + { + return this._arquivosAnexados; + } + set + { + this._arquivosAnexados = value; + base.OnPropertyChanged("ArquivosAnexados"); + } + } + + public List ArquivosFinais + { + get + { + return this._arquivosFinais; + } + set + { + this._arquivosFinais = value; + base.OnPropertyChanged("ArquivosFinais"); + } + } + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.IsEnabled = !value; + base.OnPropertyChanged("Carregando"); + } + } + + public bool Concluido + { + get + { + return this._concluido; + } + set + { + this._concluido = value; + base.OnPropertyChanged("Concluido"); + } + } + + public GridLength Dados + { + get + { + return this._dados; + } + set + { + this._dados = value; + base.OnPropertyChanged("Dados"); + } + } + + public DateTime DataAgendamento + { + get + { + return this._dataAgendamento; + } + set + { + this._dataAgendamento = value; + if (this.SelectedTarefa != null) + { + this.SelectedTarefa.set_Agendamento(DateTime.Parse(string.Format("{0:d} {1:T}", value, this.SelectedTarefa.get_Agendamento()))); + } + base.OnPropertyChanged("DataAgendamento"); + } + } + + public GridLength DescricaoInternaLength + { + get + { + return this._descricaoInternaLength; + } + set + { + this._descricaoInternaLength = value; + base.OnPropertyChanged("DescricaoInternaLength"); + } + } + + public GridLength DescricaoLength + { + get + { + return this._descricaoLength; + } + set + { + this._descricaoLength = value; + base.OnPropertyChanged("DescricaoLength"); + } + } + + public override bool EnableAlterarTarefa + { + get + { + return this._enableAlterarTarefa; + } + set + { + this._enableAlterarTarefa = this._alterarPermissEnabled & value; + base.OnPropertyChanged("EnableAlterarTarefa"); + } + } + + public GridLength Grid + { + get + { + return this._grid; + } + set + { + this._grid = value; + base.OnPropertyChanged("Grid"); + } + } + + public DateTime HoraAgendamento + { + get + { + return this._horaAgendamento; + } + set + { + this._horaAgendamento = value; + if (this.SelectedTarefa != null) + { + this.SelectedTarefa.set_Agendamento(DateTime.Parse(string.Format("{0:d} {1:T}", this.SelectedTarefa.get_Agendamento(), value))); + } + base.OnPropertyChanged("HoraAgendamento"); + } + } + + public long IdCliente + { + get; + set; + } + + public bool InclusaoArquivoDigitalEnable + { + get + { + return this._inclusaoArquivoDigitalEnable; + } + set + { + this._inclusaoArquivoDigitalEnable = value; + base.OnPropertyChanged("InclusaoArquivoDigitalEnable"); + } + } + + private int Index { get; set; } = 1; + + public bool IsAnotacoes + { + get + { + return this._isAnotacoes; + } + set + { + this._isAnotacoes = value; + base.OnPropertyChanged("IsAnotacoes"); + } + } + + public bool IsSelected + { + get + { + return this._isSelected; + } + set + { + this._isSelected = value; + base.OnPropertyChanged("IsSelected"); + } + } + + public bool IsVisibleDescricao + { + get + { + return this._isVisibleDescricao; + } + set + { + this._isVisibleDescricao = value; + base.OnPropertyChanged("IsVisibleDescricao"); + } + } + + public Gestor.Model.Domain.Common.ArquivoDigital SelectedAnexado + { + get + { + return this._selectedAnexado; + } + set + { + this._selectedAnexado = value; + base.OnPropertyChanged("SelectedAnexado"); + } + } + + public override Gestor.Model.Domain.Ferramentas.Tarefa SelectedTarefa + { + get + { + return this._selectedTarefa; + } + set + { + DateTime agendamento; + DateTime dateTime; + bool status; + ObservableCollection observableCollection; + bool tipoDeTarefa; + TipoDeTarefa tipoDeTarefa1; + long? nullable; + bool usuario; + ObservableCollection observableCollection1; + DateTime networkTime = Funcoes.GetNetworkTime(); + this.IsSelected = value != null; + this._selectedTarefa = value; + Gestor.Model.Domain.Ferramentas.Tarefa tarefa = value; + if (tarefa != null) + { + agendamento = tarefa.get_Agendamento(); + } + else + { + agendamento = networkTime; + } + this.DataAgendamento = agendamento; + Gestor.Model.Domain.Ferramentas.Tarefa tarefa1 = value; + if (tarefa1 != null) + { + dateTime = tarefa1.get_Agendamento(); + } + else + { + dateTime = networkTime; + } + this.HoraAgendamento = dateTime; + this.IsVisibleDescricao = value != null; + Gestor.Model.Domain.Ferramentas.Tarefa tarefa2 = value; + if (tarefa2 != null) + { + status = tarefa2.get_Status() == 2; + } + else + { + status = false; + } + this.Concluido = status; + if (value == null) + { + observableCollection = new ObservableCollection(); + } + else + { + observableCollection = (value.get_Responsaveis() == null ? new ObservableCollection() : new ObservableCollection(value.get_Responsaveis())); + } + base.Responsaveis = observableCollection; + if (!base.Responsaveis.Any()) + { + Gestor.Model.Domain.Ferramentas.Tarefa tarefa3 = value; + if (tarefa3 != null) + { + usuario = tarefa3.get_Usuario(); + } + else + { + usuario = false; + } + if (!usuario) + { + observableCollection1 = new ObservableCollection(); + } + else + { + ResponsavelTarefa[] responsavelTarefaArray = new ResponsavelTarefa[1]; + ResponsavelTarefa responsavelTarefa = new ResponsavelTarefa(); + responsavelTarefa.set_Usuario(value.get_Usuario()); + responsavelTarefaArray[0] = responsavelTarefa; + observableCollection1 = new ObservableCollection(responsavelTarefaArray); + } + base.Responsaveis = observableCollection1; + } + if (value != null && value.get_Id() > (long)0) + { + this.AlterarTamanho(false); + } + if (value != null) + { + this.AnotacoesLength = new GridLength(0, GridUnitType.Pixel); + this.AnotacoesInternasLength = new GridLength(0, GridUnitType.Pixel); + this.DescricaoLength = (string.IsNullOrWhiteSpace(value.get_Descricao()) ? new GridLength(0, GridUnitType.Pixel) : new GridLength(1, GridUnitType.Star)); + this.DescricaoInternaLength = (string.IsNullOrWhiteSpace(value.get_DescricaoInterna()) ? new GridLength(0, GridUnitType.Pixel) : new GridLength(1, GridUnitType.Star)); + } + Gestor.Model.Domain.Ferramentas.Tarefa tarefa4 = value; + if (tarefa4 != null) + { + tipoDeTarefa = tarefa4.get_TipoDeTarefa(); + } + else + { + tipoDeTarefa = false; + } + if (tipoDeTarefa) + { + if (!this.TiposTarefa.All((TipoDeTarefa x) => x.get_Id() != value.get_Id()) || value.get_TipoDeTarefa().get_Ativo()) + { + this.TiposTarefa = new ObservableCollection(( + from x in this.TiposTarefa + where x.get_Ativo() + select x).ToList()); + } + else + { + this.TiposTarefa.Add(value.get_TipoDeTarefa()); + } + } + Gestor.Model.Domain.Ferramentas.Tarefa tarefa5 = value; + if (tarefa5 != null) + { + tipoDeTarefa1 = tarefa5.get_TipoDeTarefa(); + } + else + { + tipoDeTarefa1 = null; + } + this.SelectedTipoTarefa = tipoDeTarefa1; + if (base.EnableIncluir || base.EnableFields || base.EnableButtons) + { + Gestor.Model.Domain.Ferramentas.Tarefa tarefa6 = value; + if (tarefa6 != null) + { + nullable = new long?(tarefa6.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + } + base.ValidaPermissaoParaEditarTarefa(); + base.OnPropertyChanged("SelectedTarefa"); + } + } + + public TipoDeTarefa SelectedTipoTarefa + { + get + { + return this._selectedTipoTarefa; + } + set + { + this._selectedTipoTarefa = value; + base.OnPropertyChanged("SelectedTipoTarefa"); + } + } + + public Usuario SelectedUsuario + { + get + { + return this._selectedUsuario; + } + set + { + this._selectedUsuario = value; + base.OnPropertyChanged("SelectedUsuario"); + } + } + + private new TarefaServico Servico + { + get; + } + + public string SubTitulo + { + get + { + return this._subTitulo; + } + set + { + this._subTitulo = value; + base.OnPropertyChanged("SubTitulo"); + } + } + + public Gestor.Model.Domain.Ferramentas.Tarefa Tarefa + { + get + { + return this._tarefa; + } + set + { + this._tarefa = value; + base.OnPropertyChanged("Tarefa"); + } + } + + public List Tarefas + { + get + { + return this._tarefas; + } + set + { + this._tarefas = value; + base.OnPropertyChanged("Tarefas"); + } + } + + public ObservableCollection TarefasFiltradas + { + get + { + return this._tarefasFiltradas; + } + set + { + this._tarefasFiltradas = value; + base.OnPropertyChanged("TarefasFiltradas"); + } + } + + public List Telefones + { + get + { + return this._telefones; + } + set + { + this._telefones = value; + base.OnPropertyChanged("Telefones"); + } + } + + public ObservableCollection TiposTarefa + { + get + { + return this._tiposTarefa; + } + set + { + this._tiposTarefa = value; + base.OnPropertyChanged("TiposTarefa"); + } + } + + public string Titulo + { + get + { + return this._titulo; + } + set + { + this._titulo = value; + base.OnPropertyChanged("Titulo"); + } + } + + public string TituloTarefas + { + get + { + return this._tituloTarefas; + } + set + { + this._tituloTarefas = value; + base.OnPropertyChanged("TituloTarefas"); + } + } + + public ObservableCollection Usuarios + { + get + { + return this._usuarios; + } + set + { + this._usuarios = value; + base.OnPropertyChanged("Usuarios"); + } + } + + public Visibility VisibilityMenu + { + get + { + return this._visibilityMenu; + } + set + { + this._visibilityMenu = value; + base.OnPropertyChanged("VisibilityMenu"); + } + } + + public TarefaDrawerViewModel(Gestor.Model.Domain.Ferramentas.Tarefa tarefa, bool enableMenu) + { + this.Servico = new TarefaServico(); + this.Tarefa = tarefa; + this._enableMenu = enableMenu; + this.CarregarUsuarios(); + this.TiposTarefa = new ObservableCollection(( + from x in Recursos.TiposTarefa + where x.get_Ativo() + select x).ToList()); + DateTime? conclusao = tarefa.get_Conclusao(); + this.SelecionarTarefas(tarefa, new bool?(conclusao.HasValue)); + this.TituloTarefas = (tarefa.get_Conclusao().HasValue ? "TAREFAS CONCLUÍDAS" : "TAREFAS PENDENTES"); + base.EnableMenu = true; + } + + public void AdcionarResponsavel() + { + if (this.SelectedUsuario == null) + { + return; + } + ObservableCollection responsaveis = base.Responsaveis; + ResponsavelTarefa responsavelTarefa = new ResponsavelTarefa(); + responsavelTarefa.set_Usuario(this.SelectedUsuario); + responsavelTarefa.set_IdTarefa(this.SelectedTarefa.get_Id()); + responsaveis.Add(responsavelTarefa); + this.Usuarios.Remove(this.SelectedUsuario); + this.SelectedUsuario = null; + } + + public void AlterarTamanho(bool alterar) + { + if (!alterar) + { + if (this.TituloTarefas.Contains("TODAS")) + { + this.TituloTarefas = "TODAS TAREFAS DO CLIENTE"; + } + else if (this.TituloTarefas.Contains("PENDENTES")) + { + this.TituloTarefas = "TAREFAS PENDENTES"; + } + else if (this.TituloTarefas.Contains("CONCLUÍDAS")) + { + this.TituloTarefas = "TAREFAS CONCLUÍDAS"; + } + } + this.Grid = (alterar ? new GridLength(0, GridUnitType.Star) : new GridLength(1, GridUnitType.Star)); + this.Dados = (alterar ? new GridLength(1, GridUnitType.Star) : new GridLength(360, GridUnitType.Pixel)); + } + + public void AlterarTarefa() + { + string descricao; + string descricaoInterna; + this.CarregarUsuarios(); + if (this.SelectedTarefa == null) + { + return; + } + this.EnableAlterarTarefa = false; + this.AlterarTamanho(true); + this.TituloTarefas = string.Concat(this.TituloTarefas, " (ALTERANDO \"", this.SelectedTarefa.get_Titulo(), "\")"); + base.Alterar(true); + this.AnotacoesLength = new GridLength(1, GridUnitType.Star); + this.AnotacoesInternasLength = new GridLength(1, GridUnitType.Star); + Gestor.Model.Domain.Ferramentas.Tarefa selectedTarefa = this.SelectedTarefa; + if (selectedTarefa != null) + { + descricao = selectedTarefa.get_Descricao(); + } + else + { + descricao = null; + } + this.DescricaoLength = (string.IsNullOrWhiteSpace(descricao) ? new GridLength(0, GridUnitType.Pixel) : new GridLength(1, GridUnitType.Star)); + Gestor.Model.Domain.Ferramentas.Tarefa tarefa = this.SelectedTarefa; + if (tarefa != null) + { + descricaoInterna = tarefa.get_DescricaoInterna(); + } + else + { + descricaoInterna = null; + } + this.DescricaoInternaLength = (string.IsNullOrWhiteSpace(descricaoInterna) ? new GridLength(0, GridUnitType.Pixel) : new GridLength(1, GridUnitType.Star)); + this.TarefasFiltradas = new ObservableCollection() + { + this.SelectedTarefa + }; + base.ListaUsuariosResponsaveis(); + base.Responsaveis.ToList().ForEach((ResponsavelTarefa x) => this.Usuarios.Remove(x.get_Usuario())); + } + + public async void Anexar() + { + this.InclusaoArquivoDigitalEnable = false; + List arquivoDigitals = await base.AddAttachments(this.ArquivosAnexados.ToList(), new List()); + await Task.Run(async () => { + await Task.Delay(200); + this.InclusaoArquivoDigitalEnable = true; + }); + if (arquivoDigitals != null) + { + arquivoDigitals.AddRange(this.ArquivosAnexados); + this.ArquivosAnexados = new ObservableCollection(arquivoDigitals); + } + arquivoDigitals = null; + } + + public async Task Cancelar() + { + long id; + this.CarregarUsuarios(); + this.AlterarTamanho(false); + Gestor.Model.Domain.Ferramentas.Tarefa selectedTarefa = this.SelectedTarefa; + if (selectedTarefa != null) + { + id = selectedTarefa.get_Id(); + } + else + { + id = (long)0; + } + long num = id; + await this.CarregarTarefas(this.Index); + base.Alterar(false); + await base.ValidaPermissaoParaEditarTarefa(); + if (num != 0) + { + this.SelectedTarefa = this.TarefasFiltradas.FirstOrDefault((Gestor.Model.Domain.Ferramentas.Tarefa x) => x.get_Id() == num); + } + } + + public async void CarregarInformacoes(Gestor.Model.Domain.Ferramentas.Tarefa tarefa) + { + string str; + string str1; + ClienteServico clienteServico = new ClienteServico(); + TarefaDrawerViewModel tarefaDrawerViewModel = this; + str = (tarefa.get_IdEntidade() != 0 ? "TODAS AS TAREFAS PENDENTES DO CLIENTE" : ""); + tarefaDrawerViewModel.SubTitulo = str; + this.IdCliente = tarefa.get_IdCliente(); + this.Titulo = tarefa.get_Cliente(); + ObservableCollection observableCollection = await clienteServico.BuscarTelefonesAsync(tarefa.get_IdCliente()); + TarefaDrawerViewModel list = this; + ObservableCollection observableCollection1 = observableCollection; + IEnumerable clienteTelefones = + from x in observableCollection1 + where Gestor.Model.Helper.ValidationHelper.ValidacaoTelefone(x.get_Numero()) + select x; + list.Telefones = clienteTelefones.Select((ClienteTelefone x) => { + TelefoneBase telefoneBase = new TelefoneBase(); + telefoneBase.set_Tipo(x.get_Tipo()); + telefoneBase.set_Id(x.get_Id()); + telefoneBase.set_Numero(x.get_Numero()); + telefoneBase.set_Prefixo(x.get_Prefixo()); + return telefoneBase; + }).ToList(); + if (tarefa.get_IdEntidade() != 0) + { + TipoTarefa entidade = tarefa.get_Entidade(); + if (entidade == null) + { + Documento documento = await (new ApoliceServico()).BuscarApoliceAsync(tarefa.get_IdEntidade(), false, false); + this.IdCliente = documento.get_Controle().get_Cliente().get_Id(); + this.Titulo = documento.get_Controle().get_Cliente().get_Nome(); + TarefaDrawerViewModel tarefaDrawerViewModel1 = this; + if (documento.get_Tipo() != 0 || string.IsNullOrWhiteSpace(documento.get_Apolice())) + { + str1 = (documento.get_Tipo() > 0 ? string.Concat("APÓLICE NÚMERO ", documento.get_Apolice(), " ENDOSSO ", documento.get_Endosso()) : string.Concat("PROPOSTA NÚMERO ", documento.get_Proposta())); + } + else + { + str1 = string.Concat("APÓLICE NÚMERO ", documento.get_Apolice()); + } + tarefaDrawerViewModel1.SubTitulo = str1; + observableCollection = await clienteServico.BuscarTelefonesAsync(documento.get_Controle().get_Cliente().get_Id()); + TarefaDrawerViewModel list1 = this; + ObservableCollection observableCollection2 = observableCollection; + IEnumerable clienteTelefones1 = + from x in observableCollection2 + where Gestor.Model.Helper.ValidationHelper.ValidacaoTelefone(x.get_Numero()) + select x; + list1.Telefones = clienteTelefones1.Select((ClienteTelefone x) => { + TelefoneBase telefoneBase = new TelefoneBase(); + telefoneBase.set_Tipo(x.get_Tipo()); + telefoneBase.set_Id(x.get_Id()); + telefoneBase.set_Numero(x.get_Numero()); + telefoneBase.set_Prefixo(x.get_Prefixo()); + return telefoneBase; + }).ToList(); + } + else if (entidade == 4) + { + Sinistro sinistro = await (new SinistroServico()).BuscarSinistro(tarefa.get_IdEntidade()); + if (sinistro != null) + { + this.IdCliente = sinistro.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Cliente().get_Id(); + this.Titulo = sinistro.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Cliente().get_Nome(); + this.SubTitulo = string.Concat("SINISTRO ", sinistro.get_Numero(), " ITEM ", sinistro.get_ItemSinistrado()); + observableCollection = await clienteServico.BuscarTelefonesAsync(this.IdCliente); + TarefaDrawerViewModel list2 = this; + ObservableCollection observableCollection3 = observableCollection; + IEnumerable clienteTelefones2 = + from x in observableCollection3 + where Gestor.Model.Helper.ValidationHelper.ValidacaoTelefone(x.get_Numero()) + select x; + list2.Telefones = clienteTelefones2.Select((ClienteTelefone x) => { + TelefoneBase telefoneBase = new TelefoneBase(); + telefoneBase.set_Tipo(x.get_Tipo()); + telefoneBase.set_Id(x.get_Id()); + telefoneBase.set_Numero(x.get_Numero()); + telefoneBase.set_Prefixo(x.get_Prefixo()); + return telefoneBase; + }).ToList(); + } + else + { + clienteServico = null; + return; + } + } + } + clienteServico = null; + } + + public async Task CarregarTarefas(int index) + { + List tarefas; + Gestor.Model.Domain.Ferramentas.Tarefa tarefa; + if (this.Tarefa.get_IdEntidade() != 0) + { + this.Carregando = true; + Gestor.Model.Domain.Ferramentas.Tarefa tarefa1 = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa1.set_Cliente(this.Tarefa.get_Cliente()); + tarefa1.set_IdCliente(this.Tarefa.get_IdCliente()); + tarefa1.set_Entidade(this.Tarefa.get_Entidade()); + tarefa1.set_IdEntidade(this.Tarefa.get_IdEntidade()); + Gestor.Model.Domain.Ferramentas.Tarefa tarefa2 = tarefa1; + this.Index = index; + int num = index; + if (num == 1) + { + this.CarregarInformacoes(tarefa2); + tarefas = await this.Servico.BuscarTarefas(this.Tarefa.get_Entidade(), this.Tarefa.get_IdEntidade(), new bool?(false)); + } + else if (num == 2) + { + tarefa2.set_Entidade(2); + this.CarregarInformacoes(tarefa2); + tarefas = await this.Servico.BuscarTarefasCliente(this.Tarefa.get_IdCliente()); + } + else + { + this.CarregarInformacoes(tarefa2); + tarefas = await this.Servico.BuscarTarefas(this.Tarefa.get_Entidade(), this.Tarefa.get_IdEntidade(), new bool?(true)); + } + TarefaDrawerViewModel list = this; + List tarefas1 = tarefas; + list.Tarefas = ( + from x in tarefas1 + orderby x.get_Agendamento() descending + select x).ToList(); + this.TarefasFiltradas = new ObservableCollection(this.Tarefas); + TarefaDrawerViewModel tarefaDrawerViewModel = this; + if (this.TarefasFiltradas == null || this.TarefasFiltradas.Count == 0) + { + tarefa = null; + } + else + { + tarefa = (tarefa2.get_Id() != 0 ? this.TarefasFiltradas.FirstOrDefault((Gestor.Model.Domain.Ferramentas.Tarefa x) => x.get_Id() == tarefa2.get_Id()) : this.TarefasFiltradas.First()); + } + tarefaDrawerViewModel.SelectedTarefa = tarefa; + this.Carregando = false; + } + } + + public async Task CarregarTarefas(Gestor.Model.Domain.Ferramentas.Tarefa tarefa, bool? concluido) + { + Gestor.Model.Domain.Ferramentas.Tarefa tarefa1; + this.Carregando = true; + if (tarefa.get_IdEntidade() != 0) + { + List tarefas = await this.Servico.BuscarTarefas(tarefa.get_Entidade(), tarefa.get_IdEntidade(), concluido); + TarefaDrawerViewModel list = this; + List tarefas1 = tarefas; + list.Tarefas = ( + from x in tarefas1 + orderby x.get_Agendamento() + select x).ToList(); + this.TarefasFiltradas = new ObservableCollection(this.Tarefas); + TarefaDrawerViewModel tarefaDrawerViewModel = this; + if (this.TarefasFiltradas == null || this.TarefasFiltradas.Count == 0) + { + tarefa1 = null; + } + else + { + tarefa1 = (tarefa.get_Id() != 0 ? this.TarefasFiltradas.FirstOrDefault((Gestor.Model.Domain.Ferramentas.Tarefa x) => x.get_Id() == tarefa.get_Id()) : this.TarefasFiltradas.First()); + } + tarefaDrawerViewModel.SelectedTarefa = tarefa1; + } + else if (tarefa.get_Id() > (long)0) + { + this.SelectedTarefa = await this.Servico.BuscarTarefa(tarefa.get_Id()); + } + this.Carregando = false; + } + + private void CarregarUsuarios() + { + this.Usuarios = new ObservableCollection(Recursos.Usuarios.Where((Usuario x) => { + if (!Recursos.Configuracoes.Any((ConfiguracaoSistema c) => c.get_Configuracao() == 36) && x.get_IdEmpresa() != Recursos.Usuario.get_IdEmpresa() || x.get_Excluido()) + { + return false; + } + long? permissaoAggilizador = x.get_PermissaoAggilizador(); + long num = (long)4; + return !(permissaoAggilizador.GetValueOrDefault() == num & permissaoAggilizador.HasValue); + }).OrderBy((Usuario x) => x.get_Nome()).ToList()); + } + + public void Delete(Gestor.Model.Domain.Common.ArquivoDigital arquivo) + { + if (this.SelectedAnexado == null) + { + return; + } + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital = this.ArquivosAnexados.First((Gestor.Model.Domain.Common.ArquivoDigital x) => x.get_Descricao() == arquivo.get_Descricao()); + this.ArquivosAnexados.Remove(arquivoDigital); + this.ArquivosAnexados = new ObservableCollection(this.ArquivosAnexados); + } + + public async void Editar(IndiceArquivoDigital arquivo) + { + if (arquivo != null && arquivo.get_IdArquivoDigital() != 0) + { + await this.ArquivoDigitalServico.Save(arquivo); + } + } + + public async Task Excluir(Gestor.Model.Domain.Ferramentas.Tarefa item) + { + bool flag; + string titulo; + if (this.VisibilityMenu != Visibility.Collapsed) + { + string[] strArrays = new string[] { "DESEJA REALMENTE EXCLUIR A TAREFA ", item.get_Titulo(), "?", Environment.NewLine, "ESSE PROCEDIMENTO É IRREVERSÍVEL" }; + if (await base.ShowMessage(string.Concat(strArrays), "SIM", "NÃO", false)) + { + titulo = item.get_Titulo(); + long id = item.get_Id(); + if (await this.Servico.Excluir(item.get_Id())) + { + base.RegistrarAcao("EXCLUIU TAREFA", item.get_Id(), new TipoTela?(38), string.Format("TAREFA \"{0}\", ID: {1}", titulo, id)); + await this.CarregarTarefas(this.Index); + base.Alterar(false); + flag = true; + } + else + { + base.Alterar(false); + flag = true; + } + } + else + { + flag = false; + } + } + else + { + await base.ShowMessage("NÃO É POSSÍVEL EXCLUIR TAREFA PELO RELATÓRIO!", "OK", "", false); + flag = false; + } + titulo = null; + return flag; + } + + public string GerarHtml() + { + string nome; + string str = " TAREFA
"; + str = string.Concat(str, "
"); + str = string.Concat(str, "

"); + str = string.Concat(str, "TAREFA


"); + str = string.Concat(str, ""); + int num = 0; + string[] cliente = new string[] { str, ""; + str = string.Concat(cliente); + string[] referencia = new string[] { str, ""; + str = string.Concat(referencia); + string[] titulo = new string[] { str, ""; + str = string.Concat(titulo); + string[] strArrays = new string[] { str, ""; + str = string.Concat(strArrays); + string[] nome1 = new string[] { str, ""; + str = string.Concat(nome1); + string[] description = new string[] { str, ""; + str = string.Concat(description); + string[] strArrays1 = new string[] { str, ""; + str = string.Concat(strArrays1); + str = string.Concat(str, "

CLIENTE: "; + cliente[4] = this.SelectedTarefa.get_Cliente(); + cliente[5] = "

REFERÊNCIA: "; + referencia[4] = this.SelectedTarefa.get_Referencia(); + referencia[5] = "

TÍTULO: "; + titulo[4] = this.SelectedTarefa.get_Titulo(); + titulo[5] = "

AGENDAMENTO: "; + DateTime agendamento = this.SelectedTarefa.get_Agendamento(); + strArrays[4] = agendamento.ToString(); + strArrays[5] = "

RESPONSÁVEL PRINCIPAL: "; + nome1[4] = this.SelectedTarefa.get_Usuario().get_Nome(); + nome1[5] = "

STATUS: "; + description[4] = Gestor.Common.Validation.ValidationHelper.GetDescription(this.SelectedTarefa.get_Status()); + description[5] = "

TIPO DE TAREFA: "; + TipoDeTarefa selectedTipoTarefa = this.SelectedTipoTarefa; + if (selectedTipoTarefa != null) + { + nome = selectedTipoTarefa.get_Nome(); + } + else + { + nome = null; + } + strArrays1[4] = nome; + strArrays1[5] = "

"); + if (base.Responsaveis != null && base.Responsaveis.Count > 0) + { + str = string.Concat(str, "

RESPONSÁVEIS VINCULADOS

"); + str = string.Concat(str, "
"); + str = string.Concat(str, ""); + List strs = new List(); + foreach (ResponsavelTarefa responsavei in base.Responsaveis) + { + strs.Add(responsavei.get_Usuario().get_Nome().Trim().ToUpper()); + } + str = string.Concat(str, ""); + str = string.Concat(str, "

", string.Join(", ", strs), "

"); + str = string.Concat(str, "

"); + } + str = string.Concat(str, "

"); + if (this.SelectedTarefa.get_Descricao() != null) + { + str = string.Concat(str, "

ANOTAÇÕES

"); + str = string.Concat(str, "
"); + str = string.Concat(str, ""); + str = string.Concat(str, ""); + str = string.Concat(str, "

", this.SelectedTarefa.get_Descricao().Replace("", "").Replace("", ""), "

"); + str = string.Concat(str, "

"); + } + str = string.Concat(str, "
"); + return str; + } + + public async Task Incluir() + { + TarefaDrawerViewModel observableCollection = this; + observableCollection.CarregarUsuarios(); + observableCollection.Responsaveis = new ObservableCollection(); + TarefaDrawerViewModel tarefaDrawerViewModel = observableCollection; + Gestor.Model.Domain.Ferramentas.Tarefa tarefa = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa.set_IdCliente(observableCollection.IdCliente); + tarefa.set_Cliente(observableCollection.Titulo); + tarefa.set_Referencia(observableCollection.SubTitulo); + tarefa.set_Entidade(observableCollection.Tarefa.get_Entidade()); + tarefa.set_IdEntidade(observableCollection.Tarefa.get_IdEntidade()); + tarefa.set_Trilha(observableCollection.Tarefa.get_Trilha()); + tarefa.set_Status(0); + tarefa.set_Agendamento(Funcoes.GetNetworkTime().AddHours(1)); + tarefa.set_UsuarioCadastro(Recursos.Usuario); + ObservableCollection usuarios = observableCollection.Usuarios; + tarefa.set_Usuario(usuarios.FirstOrDefault((Usuario x) => x.get_Id() == Recursos.Usuario.get_Id())); + tarefa.set_Restrito(new bool?(false)); + tarefa.set_Responsaveis(observableCollection.Responsaveis.ToList()); + tarefaDrawerViewModel.SelectedTarefa = tarefa; + observableCollection.ArquivosFinais = new List(); + observableCollection.AlterarTamanho(true); + observableCollection.TituloTarefas = string.Concat(observableCollection.TituloTarefas, " (INCLUINDO)"); + observableCollection.Alterar(true); + observableCollection.AnotacoesLength = new GridLength(1, GridUnitType.Star); + observableCollection.AnotacoesInternasLength = new GridLength(1, GridUnitType.Star); + observableCollection.DescricaoLength = new GridLength(0, GridUnitType.Pixel); + observableCollection.DescricaoInternaLength = new GridLength(0, GridUnitType.Pixel); + observableCollection.EnableAlterarTarefa = false; + } + + public void LimparAnexos() + { + this.ArquivosAnexados = new ObservableCollection(); + } + + public void Print() + { + string str = this.GerarHtml(); + string tempPath = Path.GetTempPath(); + string str1 = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.html", tempPath, (TipoTela)38, Funcoes.GetNetworkTime()); + StreamWriter streamWriter = new StreamWriter(str1, true, Encoding.UTF8); + streamWriter.Write(str); + streamWriter.Close(); + Process.Start(str1); + base.RegistrarAcao("IMPRIMIU A TAREFA", this.SelectedTarefa.get_Id(), new TipoTela?(38), string.Format("TAREFA \"{0}\", ID: {1}", this.SelectedTarefa.get_Titulo(), this.SelectedTarefa.get_Id())); + } + + public async Task>> Salvar(string anotacoes, string anotacoesInternas) + { + List> keyValuePairs; + Usuario usuario; + DateTime networkTime = Funcoes.GetNetworkTime(); + List configuracoes = Recursos.Configuracoes; + if (configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 45) && this.SelectedTarefa.get_Status() != 2 && this.SelectedTarefa.get_Agendamento() < networkTime) + { + this.SelectedTarefa.set_Agendamento(networkTime); + } + if (this.SelectedTarefa.get_Status() == 2) + { + this.SelectedTarefa.set_Conclusao(new DateTime?(networkTime)); + } + if (this.SelectedTarefa.get_Status() == null) + { + this.SelectedTarefa.set_Conclusao(null); + } + this.SelectedTarefa.set_Responsaveis(base.Responsaveis.ToList()); + Gestor.Model.Domain.Ferramentas.Tarefa selectedTarefa = this.SelectedTarefa; + ResponsavelTarefa responsavelTarefa = base.Responsaveis.FirstOrDefault(); + if (responsavelTarefa != null) + { + usuario = responsavelTarefa.get_Usuario(); + } + else + { + usuario = null; + } + selectedTarefa.set_Usuario(usuario); + Gestor.Model.Domain.Ferramentas.Tarefa tarefa = this.SelectedTarefa; + List configuracaoSistemas = Recursos.Configuracoes; + tarefa.set_AgendamentoRetroativo(configuracaoSistemas.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 45)); + List> keyValuePairs1 = this.SelectedTarefa.Validate(); + if (this.SelectedTarefa.get_Descricao() == null && string.IsNullOrWhiteSpace(anotacoes) && string.IsNullOrWhiteSpace(anotacoesInternas)) + { + keyValuePairs1.Add(new KeyValuePair("ANOTAÇÕES", "OBRIGATÓRIO")); + } + if (keyValuePairs1.Count <= 0) + { + if (!string.IsNullOrWhiteSpace(anotacoes)) + { + this.SelectedTarefa.set_Anotacoes(Funcoes.AdicionarLog(this.SelectedTarefa.get_Anotacoes())); + this.SelectedTarefa.set_Descricao(string.Concat(this.SelectedTarefa.get_Anotacoes(), "

", this.SelectedTarefa.get_Descricao(), "

")); + } + if (!string.IsNullOrWhiteSpace(anotacoesInternas)) + { + this.SelectedTarefa.set_AnotacoesInternas(Funcoes.AdicionarLog(this.SelectedTarefa.get_AnotacoesInternas())); + this.SelectedTarefa.set_DescricaoInterna(string.Concat(this.SelectedTarefa.get_AnotacoesInternas(), "

", this.SelectedTarefa.get_DescricaoInterna(), "

")); + } + this.SelectedTarefa.set_TipoDeTarefa(this.SelectedTipoTarefa); + bool id = this.SelectedTarefa.get_Id() == (long)0; + this.SelectedTarefa = await this.Servico.Salvar(this.SelectedTarefa); + string str = (id ? "INCLUIU" : "ALTEROU"); + base.RegistrarAcao(string.Concat(str, " TAREFA"), this.SelectedTarefa.get_Id(), new TipoTela?(38), string.Format("TAREFA \"{0}\", ID: {1}", this.SelectedTarefa.get_Titulo(), this.SelectedTarefa.get_Id())); + if (id) + { + foreach (Gestor.Model.Domain.Common.ArquivoDigital arquivosFinai in this.ArquivosFinais) + { + arquivosFinai.set_IdTarefa(this.SelectedTarefa.get_Id()); + } + await this.ArquivoDigitalServico.Insert(this.ArquivosFinais); + } + if (this.Servico.Sucesso) + { + long num = this.SelectedTarefa.get_Id(); + await this.CarregarTarefas(this.Index); + this.SelectedTarefa = this.TarefasFiltradas.FirstOrDefault((Gestor.Model.Domain.Ferramentas.Tarefa x) => x.get_Id() == num); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + return keyValuePairs; + } + + public void SalvarAnexos() + { + this.ArquivosFinais = this.ArquivosAnexados.ToList(); + } + + public async void SelecionarTarefas(Gestor.Model.Domain.Ferramentas.Tarefa tarefa, bool? concluido) + { + await base.PermissaoTela(38); + this.CarregarInformacoes(tarefa); + await this.CarregarTarefas(tarefa, concluido); + if (tarefa.get_Id() != 0 && !this._enableMenu) + { + this.VisibilityMenu = Visibility.Collapsed; + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/ValoresApoliceViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/ValoresApoliceViewModel.cs new file mode 100644 index 0000000..df49b81 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/ValoresApoliceViewModel.cs @@ -0,0 +1,345 @@ +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Windows; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class ValoresApoliceViewModel : BaseSegurosViewModel + { + private Visibility _isVisibleEspecial; + + private Visibility _isVisibleVendedores; + + private decimal _prevista; + + private decimal _recebida; + + private decimal _recebidaEspecial; + + private decimal _pendente; + + private decimal _repasse; + + private decimal _repasseEspecial; + + private decimal _paga; + + private decimal _pagaEspecial; + + private string _apoliceLabel = "DESCRIÇÃO DE VALORES"; + + private string _apoliceDescricao = "VALORES BASEADOS NO DOCUMENTO SELECIONADO ATÉ O MOMENTO, OS VALORES PODEM SER DIFERENTES EM CASO DE ALTERAÇÕES POR OUTROS USUÁRIOS."; + + private Documento _selectedDocumento; + + private ObservableCollection _pagamentos; + + public string ApoliceDescricao + { + get + { + return this._apoliceDescricao; + } + set + { + this._apoliceDescricao = value; + base.OnPropertyChanged("ApoliceDescricao"); + } + } + + public string ApoliceLabel + { + get + { + return this._apoliceLabel; + } + set + { + this._apoliceLabel = value; + base.OnPropertyChanged("ApoliceLabel"); + } + } + + public Visibility IsVisibleEspecial + { + get + { + return this._isVisibleEspecial; + } + set + { + this._isVisibleEspecial = value; + base.OnPropertyChanged("IsVisibleEspecial"); + } + } + + public Visibility IsVisibleVendedores + { + get + { + return this._isVisibleVendedores; + } + set + { + this._isVisibleVendedores = value; + base.OnPropertyChanged("IsVisibleVendedores"); + } + } + + public decimal Paga + { + get + { + return this._paga; + } + set + { + this._paga = value; + base.OnPropertyChanged("Paga"); + } + } + + public decimal PagaEspecial + { + get + { + return this._pagaEspecial; + } + set + { + this._pagaEspecial = value; + base.OnPropertyChanged("PagaEspecial"); + } + } + + public ObservableCollection Pagamentos + { + get + { + return this._pagamentos; + } + set + { + this._pagamentos = value; + base.OnPropertyChanged("Pagamentos"); + } + } + + public decimal Pendente + { + get + { + return this._pendente; + } + set + { + this._pendente = value; + base.OnPropertyChanged("Pendente"); + } + } + + public decimal Prevista + { + get + { + return this._prevista; + } + set + { + this._prevista = value; + base.OnPropertyChanged("Prevista"); + } + } + + public decimal Recebida + { + get + { + return this._recebida; + } + set + { + this._recebida = value; + base.OnPropertyChanged("Recebida"); + } + } + + public decimal RecebidaEspecial + { + get + { + return this._recebidaEspecial; + } + set + { + this._recebidaEspecial = value; + base.OnPropertyChanged("RecebidaEspecial"); + } + } + + public decimal Repasse + { + get + { + return this._repasse; + } + set + { + this._repasse = value; + base.OnPropertyChanged("Repasse"); + } + } + + public decimal RepasseEspecial + { + get + { + return this._repasseEspecial; + } + set + { + this._repasseEspecial = value; + base.OnPropertyChanged("RepasseEspecial"); + } + } + + public Documento SelectedDocumento + { + get + { + return this._selectedDocumento; + } + set + { + this._selectedDocumento = value; + base.OnPropertyChanged("SelectedDocumento"); + } + } + + public ValoresApoliceViewModel(Documento documento) + { + base.EnableMenu = true; + this.Seleciona(documento); + } + + private void CalculaComissao() + { + if (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() != 1) + { + this.Prevista = ( + from x in this.SelectedDocumento.get_Parcelas() + where x.get_SubTipo() == 1 + select x).Sum((Parcela x) => x.get_ValorLiquidoFatura() * (x.get_Comissao() < decimal.One ? x.get_Comissao() : (x.get_Comissao() > new decimal(100) ? decimal.One : x.get_Comissao() * new decimal(1, 0, 0, false, 2)))); + } + else + { + decimal num = (this.SelectedDocumento.get_AdicionalComiss() ? this.SelectedDocumento.get_PremioLiquido() + this.SelectedDocumento.get_PremioAdicional() : this.SelectedDocumento.get_PremioLiquido()); + decimal comissao = this.SelectedDocumento.get_Comissao() * new decimal(1, 0, 0, false, 2); + this.Prevista = num * comissao; + } + this.Recebida = ( + from x in this.SelectedDocumento.get_Parcelas() + where x.get_SubTipo() == 1 + select x).Sum((Parcela x) => x.get_ValorComissao()); + this.Pendente = this.Prevista - this.Recebida; + this.Repasse = ( + from x in this.SelectedDocumento.get_Pagamentos() + where x.get_Parcela().get_SubTipo() == 1 + select x).Sum((VendedorParcela x) => x.get_ValorRepasse().GetValueOrDefault()); + this.Paga = this.SelectedDocumento.get_Pagamentos().Where((VendedorParcela x) => { + if (x.get_Parcela().get_SubTipo() != 1) + { + return false; + } + return x.get_DataPrePagamento().HasValue; + }).Sum((VendedorParcela x) => x.get_ValorRepasse().GetValueOrDefault()); + } + + private void CalculaEspecial() + { + if (this.SelectedDocumento.get_Parcelas().All((Parcela x) => x.get_SubTipo() == 1)) + { + this.IsVisibleEspecial = Visibility.Collapsed; + return; + } + this.RecebidaEspecial = ( + from x in this.SelectedDocumento.get_Parcelas() + where x.get_SubTipo() != 1 + select x).Sum((Parcela x) => x.get_ValorComissao()); + this.RepasseEspecial = ( + from x in this.SelectedDocumento.get_Pagamentos() + where x.get_Parcela().get_SubTipo() != 1 + select x).Sum((VendedorParcela x) => x.get_ValorRepasse().GetValueOrDefault()); + this.PagaEspecial = this.SelectedDocumento.get_Pagamentos().Where((VendedorParcela x) => { + if (x.get_Parcela().get_SubTipo() == 1) + { + return false; + } + return x.get_DataPrePagamento().HasValue; + }).Sum((VendedorParcela x) => x.get_ValorRepasse().GetValueOrDefault()); + } + + private void CalculaRepasse() + { + if (this.SelectedDocumento.get_Pagamentos().All((VendedorParcela x) => x.get_Vendedor().get_Corretora())) + { + this.IsVisibleVendedores = Visibility.Collapsed; + return; + } + List list = ( + from x in this.SelectedDocumento.get_Pagamentos() + where !x.get_Vendedor().get_Corretora() + group x by x.get_Vendedor().get_Id()).Select, VendedorParcela>((IGrouping x) => { + VendedorParcela vendedorParcela = new VendedorParcela(); + vendedorParcela.set_Repasse(x.First().get_Repasse()); + vendedorParcela.set_Documento(this.SelectedDocumento); + vendedorParcela.set_ValorTotal(x.First().get_ValorTotal()); + vendedorParcela.set_Vendedor(x.First().get_Vendedor()); + vendedorParcela.set_ValorTotalPago(x.Where((VendedorParcela y) => { + if (y.get_Parcela().get_SubTipo() != 1) + { + return false; + } + return y.get_DataPrePagamento().HasValue; + }).Sum((VendedorParcela y) => y.get_ValorRepasse())); + vendedorParcela.set_ValorRepasseB(( + from y in x + where y.get_Parcela().get_SubTipo() != 1 + select y).Sum((VendedorParcela y) => y.get_ValorRepasse())); + vendedorParcela.set_ValorRepasse(x.Where((VendedorParcela y) => { + if (y.get_Parcela().get_SubTipo() == 1) + { + return false; + } + return y.get_DataPrePagamento().HasValue; + }).Sum((VendedorParcela y) => y.get_ValorRepasse())); + decimal? porcentagemRepasse = x.First().get_PorcentagemRepasse(); + vendedorParcela.set_PorcentagemRepasse((porcentagemRepasse.HasValue ? new decimal?(porcentagemRepasse.GetValueOrDefault() / 100) : null)); + vendedorParcela.set_TipoVendedor(x.First().get_TipoVendedor()); + return vendedorParcela; + }).ToList(); + this.Pagamentos = new ObservableCollection(list); + } + + public void Seleciona(Documento documento) + { + this.SelectedDocumento = documento; + if (this.SelectedDocumento.get_Tipo() != 1) + { + this.ApoliceLabel = (!this.SelectedDocumento.get_Emissao().HasValue ? string.Concat("VALORES DA PROPOSTA ", this.SelectedDocumento.get_Proposta()) : string.Concat("VALORES DA APÓLICE ", this.SelectedDocumento.get_Apolice())); + this.ApoliceDescricao = (!this.SelectedDocumento.get_Emissao().HasValue ? string.Concat("VALORES BASEADOS NA PROPOSTA ", this.SelectedDocumento.get_Proposta(), " ATÉ O MOMENTO, OS VALORES PODEM SER DIFERENTES EM CASO DE ALTERAÇÕES POR OUTROS USUÁRIOS.") : string.Concat("VALORES BASEADOS NA APÓLICE ", this.SelectedDocumento.get_Apolice(), " ATÉ O MOMENTO, OS VALORES PODEM SER DIFERENTES EM CASO DE ALTERAÇÕES POR OUTROS USUÁRIOS.")); + } + this.CalculaComissao(); + this.CalculaEspecial(); + this.CalculaRepasse(); + base.RegistrarAcao(string.Format("CONSULTOU MAIS INFORMAÇÕES DOS VALORES DO DOCUMENTO DE ID {0}", documento.get_Id()), documento.get_Id(), new TipoTela?(21), null); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/ValoresParcelaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/ValoresParcelaViewModel.cs new file mode 100644 index 0000000..867e88d --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/ValoresParcelaViewModel.cs @@ -0,0 +1,583 @@ +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Aggilizador; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class ValoresParcelaViewModel : BaseSegurosViewModel + { + private ParcelaPendente _pendecia; + + private Visibility _isVisiblePendencia = Visibility.Collapsed; + + private Visibility _isVisibleFatura; + + private Visibility _isVisibleVendedores; + + private decimal _prevista; + + private decimal _ir; + + private decimal _iss; + + private string _repassePago; + + private decimal _recebidaLiquida; + + private decimal _recebida; + + private decimal _recebidaEspecial; + + private decimal _pendente; + + private decimal _repasse; + + private decimal _repasseEspecial; + + private decimal _paga; + + private decimal _pagaEspecial; + + private string _apoliceLabel = "DESCRIÇÃO DE VALORES"; + + private string _apoliceDescricao = "VALORES BASEADOS NO DOCUMENTO SELECIONADO ATÉ O MOMENTO, OS VALORES PODEM SER DIFERENTES EM CASO DE ALTERAÇÕES POR OUTROS USUÁRIOS."; + + private Parcela _selectedParcela; + + private string _statusBaixa; + + private string _statusParc; + + private Visibility _isVisiblestatusparc = Visibility.Collapsed; + + private ObservableCollection _pagamentos; + + public string ApoliceDescricao + { + get + { + return this._apoliceDescricao; + } + set + { + this._apoliceDescricao = value; + base.OnPropertyChanged("ApoliceDescricao"); + } + } + + public string ApoliceLabel + { + get + { + return this._apoliceLabel; + } + set + { + this._apoliceLabel = value; + base.OnPropertyChanged("ApoliceLabel"); + } + } + + public decimal Ir + { + get + { + return this._ir; + } + set + { + this._ir = value; + base.OnPropertyChanged("Ir"); + } + } + + public decimal Iss + { + get + { + return this._iss; + } + set + { + this._iss = value; + base.OnPropertyChanged("Iss"); + } + } + + public Visibility IsVisibleFatura + { + get + { + return this._isVisibleFatura; + } + set + { + this._isVisibleFatura = value; + base.OnPropertyChanged("IsVisibleFatura"); + } + } + + public Visibility IsVisiblePendencia + { + get + { + return this._isVisiblePendencia; + } + set + { + this._isVisiblePendencia = value; + base.OnPropertyChanged("IsVisiblePendencia"); + } + } + + public Visibility IsVisibleStatusParc + { + get + { + return this._isVisiblestatusparc; + } + set + { + this._isVisiblestatusparc = value; + base.OnPropertyChanged("IsVisibleStatusParc"); + } + } + + public Visibility IsVisibleVendedores + { + get + { + return this._isVisibleVendedores; + } + set + { + this._isVisibleVendedores = value; + base.OnPropertyChanged("IsVisibleVendedores"); + } + } + + public decimal Paga + { + get + { + return this._paga; + } + set + { + this._paga = value; + base.OnPropertyChanged("Paga"); + } + } + + public decimal PagaEspecial + { + get + { + return this._pagaEspecial; + } + set + { + this._pagaEspecial = value; + base.OnPropertyChanged("PagaEspecial"); + } + } + + public ObservableCollection Pagamentos + { + get + { + return this._pagamentos; + } + set + { + this._pagamentos = value; + base.OnPropertyChanged("Pagamentos"); + } + } + + public ParcelaPendente Pendecia + { + get + { + return this._pendecia; + } + set + { + this._pendecia = value; + this.IsVisiblePendencia = (value == null ? Visibility.Collapsed : Visibility.Visible); + base.OnPropertyChanged("Pendecia"); + } + } + + public decimal Pendente + { + get + { + return this._pendente; + } + set + { + if (value >= new decimal(1, 0, 0, false, 2)) + { + this._pendente = value; + } + else + { + this._pendente = new decimal(); + } + base.OnPropertyChanged("Pendente"); + } + } + + public decimal Prevista + { + get + { + return this._prevista; + } + set + { + this._prevista = value; + base.OnPropertyChanged("Prevista"); + } + } + + public decimal Recebida + { + get + { + return this._recebida; + } + set + { + this._recebida = value; + base.OnPropertyChanged("Recebida"); + } + } + + public decimal RecebidaEspecial + { + get + { + return this._recebidaEspecial; + } + set + { + this._recebidaEspecial = value; + base.OnPropertyChanged("RecebidaEspecial"); + } + } + + public decimal RecebidaLiquida + { + get + { + return this._recebidaLiquida; + } + set + { + this._recebidaLiquida = value; + base.OnPropertyChanged("RecebidaLiquida"); + } + } + + public decimal Repasse + { + get + { + return this._repasse; + } + set + { + this._repasse = value; + base.OnPropertyChanged("Repasse"); + } + } + + public decimal RepasseEspecial + { + get + { + return this._repasseEspecial; + } + set + { + this._repasseEspecial = value; + base.OnPropertyChanged("RepasseEspecial"); + } + } + + public string RepassePago + { + get + { + return this._repassePago; + } + set + { + this._repassePago = value; + base.OnPropertyChanged("RepassePago"); + } + } + + public Parcela SelectedParcela + { + get + { + return this._selectedParcela; + } + set + { + this._selectedParcela = value; + base.OnPropertyChanged("SelectedParcela"); + } + } + + public string StatusBaixa + { + get + { + return this._statusBaixa; + } + set + { + this._statusBaixa = value; + base.OnPropertyChanged("StatusBaixa"); + } + } + + public string StatusParc + { + get + { + return this._statusParc; + } + set + { + this._statusParc = value; + base.OnPropertyChanged("StatusParc"); + } + } + + public ValoresParcelaViewModel(Parcela parcela, Documento documento) + { + this.Seleciona(parcela, documento); + } + + private async void BuscarPendencia() + { + this.Pendecia = await (new BaseServico()).BuscarParcelaPendente(this.SelectedParcela.get_IdParcelaPendente()); + } + + private void CalculaComissao(Documento documento) + { + decimal valor; + if (this.SelectedParcela.get_SubTipo() != 1) + { + valor = this.SelectedParcela.get_Valor(); + } + else if (documento.get_NumeroParcelas() == decimal.Zero) + { + valor = decimal.Zero; + } + else + { + valor = (documento.get_AdicionalComiss() ? (documento.get_PremioLiquido() + documento.get_PremioAdicional()) / documento.get_NumeroParcelas() : documento.get_PremioLiquido() / documento.get_NumeroParcelas()); + } + decimal num = valor; + this.Prevista = (this.SelectedParcela.get_ValorLiquidoFatura() != decimal.Zero ? (this.SelectedParcela.get_ValorLiquidoFatura() * this.SelectedParcela.get_Comissao()) * new decimal(1, 0, 0, false, 2) : (num * this.SelectedParcela.get_Comissao()) * new decimal(1, 0, 0, false, 2)); + this.Recebida = this.SelectedParcela.get_ValorComissao(); + this.Pendente = this.Prevista - this.Recebida; + this.Repasse = this.SelectedParcela.get_Vendedores().Where((VendedorParcela x) => { + if (this.SelectedParcela.get_SubTipo() == 1) + { + return x.get_Parcela().get_SubTipo() == 1; + } + return x.get_Parcela().get_SubTipo() != 1; + }).Sum((VendedorParcela x) => x.get_ValorRepasse().GetValueOrDefault()); + this.Paga = this.SelectedParcela.get_Vendedores().Where((VendedorParcela x) => { + if (this.SelectedParcela.get_SubTipo() == 1) + { + return x.get_Parcela().get_SubTipo() == 1; + } + if (x.get_Parcela().get_SubTipo() == 1) + { + return false; + } + return x.get_DataPrePagamento().HasValue; + }).Sum((VendedorParcela x) => x.get_ValorRepasse().GetValueOrDefault()); + this.Ir = this.SelectedParcela.get_Irr(); + this.Iss = this.SelectedParcela.get_Iss(); + this.RecebidaLiquida = this.SelectedParcela.get_ValorComDesconto(); + } + + private void CalculaRepasse() + { + if (this.SelectedParcela.get_Vendedores().All((VendedorParcela x) => x.get_Vendedor().get_Corretora())) + { + this.IsVisibleVendedores = Visibility.Collapsed; + return; + } + List list = ( + from x in this.SelectedParcela.get_Vendedores() + where !x.get_Vendedor().get_Corretora() + group x by x.get_Vendedor().get_Id()).Select, VendedorParcela>((IGrouping x) => { + VendedorParcela vendedorParcela = new VendedorParcela(); + vendedorParcela.set_Repasse(x.First().get_Repasse()); + vendedorParcela.set_Documento(this.SelectedParcela.get_Documento()); + vendedorParcela.set_ValorTotal(x.First().get_ValorTotal()); + vendedorParcela.set_Vendedor(x.First().get_Vendedor()); + vendedorParcela.set_ValorTotalPago(x.Where((VendedorParcela y) => { + if (y.get_Parcela().get_SubTipo() != 1) + { + return false; + } + return y.get_DataPrePagamento().HasValue; + }).Sum((VendedorParcela y) => y.get_ValorRepasse())); + vendedorParcela.set_ValorRepasseB(( + from y in x + where y.get_Parcela().get_SubTipo() != 1 + select y).Sum((VendedorParcela y) => y.get_ValorRepasse())); + vendedorParcela.set_ValorRepasse(x.Where((VendedorParcela y) => { + if (y.get_Parcela().get_SubTipo() == 1) + { + return false; + } + return y.get_DataPrePagamento().HasValue; + }).Sum((VendedorParcela y) => y.get_ValorRepasse())); + decimal? porcentagemRepasse = x.First().get_PorcentagemRepasse(); + vendedorParcela.set_PorcentagemRepasse((porcentagemRepasse.HasValue ? new decimal?(porcentagemRepasse.GetValueOrDefault() / 100) : null)); + vendedorParcela.set_TipoVendedor(x.First().get_TipoVendedor()); + return vendedorParcela; + }).ToList(); + this.Pagamentos = new ObservableCollection(list); + } + + public async void Seleciona(Parcela parcela, Documento documento) + { + StatusPagamento? statusPagamento; + Visibility visibility; + string str; + string str1; + this.SelectedParcela = parcela; + ValoresParcelaViewModel valoresParcelaViewModel = this; + visibility = (this.SelectedParcela.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 2 ? Visibility.Visible : Visibility.Collapsed); + valoresParcelaViewModel.IsVisibleFatura = visibility; + this.ApoliceLabel = string.Format("VALORES DA PARCELA {0} VENCIMENTO {1:d}", this.SelectedParcela.get_NumeroParcela(), parcela.get_Vencimento()); + this.ApoliceDescricao = string.Format("VALORES BASEADOS NA PARCELA {0} ATÉ O MOMENTO, OS VALORES PODEM SER DIFERENTES EM CASO DE ALTERAÇÕES POR OUTROS USUÁRIOS.", this.SelectedParcela.get_NumeroParcela()); + this.StatusBaixa = "PENDENTE"; + this.RepassePago = "REPASSE A SER PAGO"; + if (this.SelectedParcela.get_DataRecebimento().HasValue) + { + ValoresParcelaViewModel valoresParcelaViewModel1 = this; + if (this.SelectedParcela.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 2) + { + str = "BAIXA MANUAL"; + } + else + { + str = (this.SelectedParcela.get_ValorRealizado() == decimal.Zero ? "BAIXA ESGOTAMENTO" : "BAIXA MANUAL"); + } + valoresParcelaViewModel1.StatusBaixa = str; + DetalheExtrato detalheExtrato = await (new ServicoExtrato()).FindByParcelaId(this.SelectedParcela.get_Id()); + if (detalheExtrato != null) + { + StatusParcela? status = detalheExtrato.get_Status(); + if (status.HasValue) + { + StatusParcela valueOrDefault = status.GetValueOrDefault(); + if (valueOrDefault != 1) + { + if (valueOrDefault != 5) + { + switch (valueOrDefault) + { + case 10: + case 13: + { + goto Label1; + } + case 11: + { + this.CalculaComissao(documento); + this.CalculaRepasse(); + if (this.SelectedParcela.get_IdParcelaPendente() > (long)0) + { + statusPagamento = this.SelectedParcela.get_StatusPagamento(); + if (statusPagamento.GetValueOrDefault() != 0 | !statusPagamento.HasValue) + { + this.BuscarPendencia(); + } + } + return; + } + case 12: + { + break; + } + default: + { + this.CalculaComissao(documento); + this.CalculaRepasse(); + if (this.SelectedParcela.get_IdParcelaPendente() > (long)0) + { + statusPagamento = this.SelectedParcela.get_StatusPagamento(); + if (statusPagamento.GetValueOrDefault() != 0 | !statusPagamento.HasValue) + { + this.BuscarPendencia(); + } + } + return; + } + } + } + this.RepassePago = "REPASSE PAGO"; + this.StatusBaixa = "BAIXA MANUAL"; + this.CalculaComissao(documento); + this.CalculaRepasse(); + if (this.SelectedParcela.get_IdParcelaPendente() > (long)0) + { + statusPagamento = this.SelectedParcela.get_StatusPagamento(); + if (statusPagamento.GetValueOrDefault() != 0 | !statusPagamento.HasValue) + { + this.BuscarPendencia(); + } + } + return; + } + Label1: + this.IsVisibleStatusParc = Visibility.Visible; + this.StatusParc = ValidationHelper.GetDescription(detalheExtrato.get_Status()); + this.RepassePago = "REPASSE PAGO"; + ValoresParcelaViewModel valoresParcelaViewModel2 = this; + str1 = (this.SelectedParcela.get_ValorRealizado() == decimal.Zero ? "BAIXA AUTOMATICA ESGOTAMENTO" : "BAIXA AUTOMATICA"); + valoresParcelaViewModel2.StatusBaixa = str1; + } + } + } + this.CalculaComissao(documento); + this.CalculaRepasse(); + if (this.SelectedParcela.get_IdParcelaPendente() > (long)0) + { + statusPagamento = this.SelectedParcela.get_StatusPagamento(); + if (statusPagamento.GetValueOrDefault() != 0 | !statusPagamento.HasValue) + { + this.BuscarPendencia(); + } + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/VinculoVendedorViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/VinculoVendedorViewModel.cs new file mode 100644 index 0000000..bba206b --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/VinculoVendedorViewModel.cs @@ -0,0 +1,307 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class VinculoVendedorViewModel : BaseSegurosViewModel + { + private readonly VendedorUsuarioServico _servicoVendedorUsuario; + + private readonly VendedorServico _servicoVendedor; + + public readonly Usuario SelectedUsuario; + + private bool _isVisibleVinculado; + + private bool _enableAlterarVinculo; + + private bool _isVisibleVendedor = true; + + private List _vinculado; + + private List _vinculadoFiltro; + + private List _vendedor; + + private List _vendedorFiltro; + + public bool EnableAlterarVinculo + { + get + { + return this._enableAlterarVinculo; + } + set + { + this._enableAlterarVinculo = value; + base.OnPropertyChanged("EnableAlterarVinculo"); + } + } + + public bool IsVisibleVendedor + { + get + { + return this._isVisibleVendedor; + } + set + { + this._isVisibleVendedor = value; + base.OnPropertyChanged("IsVisibleVendedor"); + } + } + + public bool IsVisibleVinculado + { + get + { + return this._isVisibleVinculado; + } + set + { + this._isVisibleVinculado = value; + base.OnPropertyChanged("IsVisibleVinculado"); + } + } + + public List Vendedor + { + get + { + return this._vendedor; + } + set + { + this._vendedor = value; + this.IsVisibleVendedor = (value == null ? false : value.Count > 0); + base.OnPropertyChanged("Vendedor"); + } + } + + public List VendedorFiltro + { + get + { + return this._vendedorFiltro; + } + set + { + this._vendedorFiltro = value; + base.OnPropertyChanged("VendedorFiltro"); + } + } + + public List Vinculado + { + get + { + return this._vinculado; + } + set + { + this._vinculado = value; + this.IsVisibleVinculado = (value == null ? false : value.Count > 0); + base.OnPropertyChanged("Vinculado"); + } + } + + public List VinculadoFiltro + { + get + { + return this._vinculadoFiltro; + } + set + { + this._vinculadoFiltro = value; + base.OnPropertyChanged("VinculadoFiltro"); + } + } + + public VinculoVendedorViewModel(Usuario usuario) + { + this.SelectedUsuario = usuario; + this._servicoVendedorUsuario = new VendedorUsuarioServico(); + this._servicoVendedor = new VendedorServico(); + this.Load(usuario); + this.EnableAlterarVinculo = Recursos.Usuario.get_Id() > (long)0; + base.EnableMenu = true; + } + + private async Task AwaitLoad(Usuario usuario) + { + this.Vinculado = await this.GetVinculo(usuario); + this.Vendedor = await this.GetVendedor(usuario); + this.VinculadoFiltro = this.Vinculado; + this.VendedorFiltro = this.Vendedor; + } + + internal async Task BuscarVinculoVendedor(string value) + { + await Task.Run(() => this.FiltrarVinculoVendedor(value)); + } + + internal void FiltrarVinculoVendedor(string filter) + { + this.Vinculado = (string.IsNullOrEmpty(filter) ? this.VinculadoFiltro : new List( + from x in this.VinculadoFiltro + where Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Vendedor().get_Nome().ToUpper().Trim()).Contains(filter.ToUpper()) + select x)); + this.Vendedor = (string.IsNullOrEmpty(filter) ? this.VendedorFiltro : new List( + from x in this.VendedorFiltro + where Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Vendedor().get_Nome().ToUpper().Trim()).Contains(filter.ToUpper()) + select x)); + } + + private async Task> GetVendedor(Usuario usuario) + { + List list; + List vinculoVendedors; + List vendedors = await this._servicoVendedor.BuscarVendedoresAtivosAsync(); + if (vendedors != null) + { + list = ( + from x in vendedors + where x.get_IdEmpresa() == usuario.get_IdEmpresa() + select x).ToList(); + } + else + { + list = null; + } + vendedors = list; + if (vendedors == null || vendedors.Count == 0) + { + vinculoVendedors = null; + } + else + { + IEnumerable vendedors1 = + from vendedor in vendedors + where this.Vinculado.All((VinculoVendedor x) => x.get_Vendedor().get_Id() != vendedor.get_Id()) + select vendedor; + vinculoVendedors = vendedors1.Select((Gestor.Model.Domain.Seguros.Vendedor vendedor) => { + VinculoVendedor vinculoVendedor = new VinculoVendedor(); + vinculoVendedor.set_Id((long)0); + vinculoVendedor.set_Vendedor(vendedor); + vinculoVendedor.set_Vinculado(false); + return vinculoVendedor; + }).ToList(); + } + List vinculoVendedors1 = vinculoVendedors; + return vinculoVendedors1; + } + + private async Task> GetVinculo(Usuario usuario) + { + List vinculoVendedors = new List(); + await this._servicoVendedorUsuario.FindByVinculo(usuario).ForEach((VendedorUsuario x) => { + VinculoVendedor vinculoVendedor = new VinculoVendedor(); + vinculoVendedor.set_Id(x.get_Id()); + vinculoVendedor.set_Vendedor(x.get_Vendedor()); + vinculoVendedor.set_Vinculado(true); + vinculoVendedors.Add(vinculoVendedor); + }); + List vinculoVendedors1 = vinculoVendedors; + return vinculoVendedors1; + } + + private async void Load(Usuario usuario) + { + await this.AwaitLoad(usuario); + } + + public async Task Salvar() + { + string str; + List vinculado = this.Vinculado; + List list = ( + from x in vinculado + where !x.get_Vinculado() + select x).Select((VinculoVendedor x) => { + VendedorUsuario vendedorUsuario = new VendedorUsuario(); + vendedorUsuario.set_Id(x.get_Id()); + vendedorUsuario.set_Vendedor(x.get_Vendedor()); + vendedorUsuario.set_Usuario(this.SelectedUsuario); + return vendedorUsuario; + }).ToList(); + if (list.Count > 0) + { + if (!await this._servicoVendedorUsuario.Delete(list)) + { + return; + } + } + List vendedor = this.Vendedor; + List vendedorUsuarios = ( + from x in vendedor + where x.get_Vinculado() + select x).Select((VinculoVendedor x) => { + VendedorUsuario vendedorUsuario = new VendedorUsuario(); + vendedorUsuario.set_Id(x.get_Id()); + vendedorUsuario.set_Vendedor(x.get_Vendedor()); + vendedorUsuario.set_Usuario(this.SelectedUsuario); + return vendedorUsuario; + }).ToList(); + if (vendedorUsuarios.Count > 0) + { + await this._servicoVendedorUsuario.SaveOrUpdate(vendedorUsuarios); + } + await this.AwaitLoad(this.SelectedUsuario); + using (UnitOfWork commited = Instancia.Commited) + { + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(0); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(Funcoes.GetNetworkTime()); + List vinculoVendedors = this.Vinculado; + List vendedors = ( + from x in vinculoVendedors + select x.get_Vendedor()).ToList(); + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(vendedors, jsonSerializerSetting)); + registroLog.set_EntidadeId(this.SelectedUsuario.get_Id()); + registroLog.set_Tela(45); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + this._servicoVendedorUsuario.SaveLog(registroLog, commited); + commited.Commit(); + } + base.RegistrarAcao(string.Concat("ALTEROU VÍNCULOS DE VENDEDOR DO USUÁRIO \"", this.SelectedUsuario.get_Nome(), "\""), this.SelectedUsuario.get_Id(), new TipoTela?(45), string.Format("ID: {0}\n\nACESSE O LOG DE ALTERAÇÕES NA TELA DE VÍNCULO DE VENDEDOR PARA VER EXATAMENTE O QUE FOI ALTERADO.", this.SelectedUsuario.get_Id())); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/CadastroEmailViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/CadastroEmailViewModel.cs new file mode 100644 index 0000000..2294490 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/CadastroEmailViewModel.cs @@ -0,0 +1,362 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Helpers; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class CadastroEmailViewModel : BaseSegurosViewModel + { + private readonly EmailServico _servico; + + public Credencial CancelCredencial; + + private Credencial _selectedCredencial; + + private ObservableCollection _credenciaisFiltrados = new ObservableCollection(); + + private bool _isExpanded; + + public List Credenciais + { + get; + set; + } + + public ObservableCollection CredenciaisFiltrados + { + get + { + return this._credenciaisFiltrados; + } + set + { + this._credenciaisFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("CredenciaisFiltrados"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public Credencial SelectedCredencial + { + get + { + return this._selectedCredencial; + } + set + { + long? nullable; + this._selectedCredencial = value; + this.WorkOnSelectedCredencial(value, true); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedCredencial"); + } + } + + public CadastroEmailViewModel() + { + this._servico = new EmailServico(); + base.EnableMenu = true; + this.Seleciona(); + } + + public async Task CancelarAlteracao() + { + long id; + await this.CarregarCredenciais(); + if (!this.CredenciaisFiltrados.Any()) + { + this.SelectedCredencial = new Credencial(); + base.Alterar(false); + base.EnableMenu = false; + } + else + { + Credencial cancelCredencial = this.CancelCredencial; + if (cancelCredencial != null) + { + id = cancelCredencial.get_Id(); + } + else + { + id = (long)0; + } + long num = id; + this.SelectedCredencial = this.CredenciaisFiltrados.FirstOrDefault((Credencial x) => x.get_Id() == num); + } + base.Alterar(false); + } + + private async Task CarregarCredenciais() + { + List credencials = await (new BaseServico()).BuscarCredenciais(); + foreach (Credencial credencial in credencials) + { + if (credencial.get_Email().Contains("@gmail.com")) + { + credencial.set_Tipo(1); + } + credencial.set_Senha(EncryptionHelper.Decrypt(credencial.get_Senha())); + } + CadastroEmailViewModel list = this; + List credencials1 = credencials; + list.Credenciais = ( + from x in credencials1 + orderby x.get_Descricao() + select x).ToList(); + this.CredenciaisFiltrados = new ObservableCollection(this.Credenciais); + } + + public async Task EnviarTesteEmail() + { + bool flag; + if (this.SelectedCredencial != null) + { + TipoEmail tipo = this.SelectedCredencial.get_Tipo(); + if (tipo != null) + { + if (tipo - 1 <= 1) + { + if (string.IsNullOrWhiteSpace(this.SelectedCredencial.get_Email())) + { + await base.ShowMessage("NECESSÁRIO PREENCHER O E-MAIL PARA ENVIAR UM E-MAIL DE TESTE", "OK", "", false); + flag = false; + return flag; + } + } + } + else if (string.IsNullOrWhiteSpace(this.SelectedCredencial.get_Email()) || !this.SelectedCredencial.get_Porta().HasValue || string.IsNullOrWhiteSpace(this.SelectedCredencial.get_Dominio())) + { + await base.ShowMessage("NECESSÁRIO PREENCHER O E-MAIL, PORTA E DOMÍNIO PARA ENVIAR UM E-MAIL DE TESTE", "OK", "", false); + flag = false; + return flag; + } + MailHelper mailHelper = new MailHelper(); + Destinatario destinatario = new Destinatario(); + destinatario.set_Assunto("TESTE ENVIO E-MAIL"); + destinatario.set_Corpo("TESTE DE ENVIO DE E-MAIL"); + destinatario.set_Email(this.SelectedCredencial.get_Email()); + destinatario.set_Nome(this.SelectedCredencial.get_Descricao()); + Destinatario destinatario1 = destinatario; + LogEnvio logEnvio = await mailHelper.SendAsync(this.SelectedCredencial, destinatario1, null, null, 0, false); + if (logEnvio.get_Enviado()) + { + flag = true; + } + else + { + await base.ShowMessage(logEnvio.get_Erro(), "OK", "", false); + flag = false; + } + } + else + { + await base.ShowMessage("NECESSÁRIO CRIAR UM E-MAIL DE ENVIO PARA PROSSEGUIR.", "OK", "", false); + flag = false; + } + return flag; + } + + public async Task Excluir() + { + if (this.SelectedCredencial != null && this.SelectedCredencial.get_Id() != 0) + { + if (await base.ShowMessage(string.Concat("DESEJA REALMENTE EXCLUIR O E-MAIL ", this.SelectedCredencial.get_Email(), " PERMANENTEMENTE?"), "SIM", "NÃO", false)) + { + base.Loading(true); + if (await this._servico.Delete(this.SelectedCredencial)) + { + base.RegistrarAcao(string.Concat("EXCLUIU E-MAIL \"", this.SelectedCredencial.get_Email(), "\""), this.SelectedCredencial.get_Id(), new TipoTela?(17), string.Format("E-MAIL: {0}\nID: {1}", this.SelectedCredencial.get_Email(), this.SelectedCredencial.get_Id())); + await this.CarregarCredenciais(); + if (!this.CredenciaisFiltrados.Any()) + { + this.SelectedCredencial = new Credencial(); + base.Alterar(false); + base.EnableMenu = false; + } + else + { + this.SelectedCredencial = this.CredenciaisFiltrados.FirstOrDefault(); + } + base.Loading(false); + base.ToggleSnackBar("E-MAIL EXCLUÍDO COM SUCESSO", true); + } + else + { + base.Loading(false); + } + } + } + } + + internal async Task> Filtrar(string value) + { + List credencials = await Task.Run>(() => this.FiltrarCredenciais(value)); + return credencials; + } + + public List FiltrarCredenciais(string filter) + { + this.CredenciaisFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Credenciais) : new ObservableCollection( + from x in this.Credenciais + where ValidationHelper.RemoveDiacritics(x.get_Descricao().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + select x)); + this.SelectedCredencial = this.CredenciaisFiltrados.FirstOrDefault(); + return this.CredenciaisFiltrados.ToList(); + } + + public void Incluir() + { + Credencial credencial = new Credencial(); + credencial.set_IdEmpresa(Recursos.Usuario.get_IdEmpresa()); + credencial.set_IdUsuario(Recursos.Usuario.get_Id()); + this.SelectedCredencial = credencial; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + string str1; + List> keyValuePairs1 = this.SelectedCredencial.Validate(); + keyValuePairs1.AddRange(this.Validate()); + if (keyValuePairs1.Count <= 0) + { + this.SelectedCredencial.set_Assinatura(this.SelectedCredencial.get_Assinatura().GetBody()); + this.SelectedCredencial.set_Cabecalho(this.SelectedCredencial.get_Cabecalho().GetBody()); + if (this.SelectedCredencial.get_Senha() == null) + { + this.SelectedCredencial.set_Senha(""); + } + str = (this.SelectedCredencial.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str1 = str; + Credencial credencial = await this._servico.Save(this.SelectedCredencial); + if (this._servico.Sucesso) + { + base.RegistrarAcao(string.Concat(str1, " E-MAIL \"", credencial.get_Email(), "\""), credencial.get_Id(), new TipoTela?(17), string.Format("E-MAIL: {0}\nID: {1}", credencial.get_Email(), credencial.get_Id())); + await this.CarregarCredenciais(); + this.SelectedCredencial = this.CredenciaisFiltrados.FirstOrDefault((Credencial x) => x.get_Id() == credencial.get_Id()); + base.Alterar(false); + base.ToggleSnackBar("E-MAIL SALVO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str1 = null; + return keyValuePairs; + } + + private async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(17); + base.Loading(false); + } + + public async Task SelecionaCredenciais() + { + base.Loading(true); + await this.CarregarCredenciais(); + this.SelectedCredencial = this.CredenciaisFiltrados.FirstOrDefault(); + base.Loading(false); + } + + public void SelecionaCredencial(Credencial credencial) + { + this.SelectedCredencial = this.CredenciaisFiltrados.First((Credencial x) => x.get_Id() == credencial.get_Id()); + } + + public List> Validate() + { + List> keyValuePairs = new List>(); + if (this.Credenciais.Any((Credencial x) => { + if (x.get_Id() == this.SelectedCredencial.get_Id()) + { + return false; + } + return x.get_Descricao() == this.SelectedCredencial.get_Descricao(); + })) + { + keyValuePairs.Add(new KeyValuePair("Descricao", "UM E-MAIL COM A MESMA DESCRIÇÃO/NOME JÁ EXISTE.")); + } + return keyValuePairs; + } + + private void WorkOnSelectedCredencial(Credencial value, bool registrar = true) + { + long? nullable; + this.CancelCredencial = (value == null || value.get_Id() == 0 ? this.CancelCredencial : (Credencial)value.Clone()); + if (value == null || value.get_Id() == 0) + { + return; + } + if (this.LastAccessId == value.get_Id() && this.LastAccessTela == 17) + { + return; + } + if (registrar) + { + base.RegistrarAcao(string.Concat("ACESSOU E-MAIL \"", value.get_Email(), "\""), value.get_Id(), new TipoTela?(17), string.Format("ID E-MAIL: {0}", value.get_Id())); + } + this.LastAccessId = value.get_Id(); + this.LastAccessTela = 17; + Credencial selectedCredencial = this.SelectedCredencial; + if (selectedCredencial != null) + { + nullable = new long?(selectedCredencial.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long id = value.get_Id(); + if (nullable1.GetValueOrDefault() != id | !nullable1.HasValue) + { + this.SelectedCredencial = this.CredenciaisFiltrados.FirstOrDefault((Credencial x) => x.get_Id() == value.get_Id()); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/CadastroParceiroViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/CadastroParceiroViewModel.cs new file mode 100644 index 0000000..9b8f08c --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/CadastroParceiroViewModel.cs @@ -0,0 +1,413 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class CadastroParceiroViewModel : BaseSegurosViewModel + { + private readonly ParceiroServico _servico; + + private Parceiro _selectedParceiro; + + private ObservableCollection _parceirosFiltrados = new ObservableCollection(); + + private bool _isExpanded; + + public Parceiro CancelParceiro; + + private Item _selectedItem = new Item(); + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public List Parceiros + { + get; + set; + } + + public ObservableCollection ParceirosFiltrados + { + get + { + return this._parceirosFiltrados; + } + set + { + this._parceirosFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("ParceirosFiltrados"); + } + } + + public Item SelectedItem + { + get + { + return this._selectedItem; + } + set + { + this._selectedItem = value; + base.OnPropertyChanged("SelectedItem"); + } + } + + public Parceiro SelectedParceiro + { + get + { + return this._selectedParceiro; + } + set + { + long? nullable; + this._selectedParceiro = value; + this.WorkOnSelectedParceiro(value, true); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedParceiro"); + } + } + + public CadastroParceiroViewModel(Parceiro parceiro) + { + this._servico = new ParceiroServico(); + base.EnableMenu = true; + this.Seleciona(parceiro); + } + + public void CancelarAlteracao() + { + if (this.CancelParceiro == null || !this.Parceiros.Any((Parceiro x) => x.get_Id() == this.CancelParceiro.get_Id())) + { + this.Incluir(); + } + else + { + DomainBase.Copy(this.Parceiros.First((Parceiro x) => x.get_Id() == this.CancelParceiro.get_Id()), this.CancelParceiro); + if (this.ParceirosFiltrados.Count <= 0 || !this.ParceirosFiltrados.Any((Parceiro x) => x.get_Id() == this.CancelParceiro.get_Id())) + { + this.ParceirosFiltrados.Add(this.CancelParceiro); + } + else + { + DomainBase.Copy(this.ParceirosFiltrados.First((Parceiro x) => x.get_Id() == this.CancelParceiro.get_Id()), this.CancelParceiro); + } + this.ParceirosFiltrados = new ObservableCollection(this.ParceirosFiltrados); + this.SelecionarParceiro(this.ParceirosFiltrados.First((Parceiro x) => x.get_Id() == this.CancelParceiro.get_Id())); + } + base.Alterar(false); + } + + public async void Excluir() + { + string complemento; + Parceiro parceiro; + if (this.SelectedParceiro != null && this.SelectedParceiro.get_Id() != 0) + { + if (await (new BaseServico()).ParceiroUtilizado(this.SelectedParceiro.get_Id())) + { + await base.ShowMessage("PARCEIRO NÃO PODE SER EXCLUÍDO POIS ESTÁ SENDO UTILIZADO.", "OK", "", false); + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + base.Loading(true); + if (await this._servico.Delete(this.SelectedParceiro)) + { + CadastroParceiroViewModel cadastroParceiroViewModel = this; + string str = string.Concat("EXCLUIU O PARCEIRO \"", this.SelectedParceiro.get_Nome(), "\""); + long id = this.SelectedParceiro.get_Id(); + TipoTela? nullable = new TipoTela?(22); + string[] cgccpf = new string[] { "DOCUMENTO: ", this.SelectedParceiro.get_Cgccpf(), "\nTELEFONE 1: (", this.SelectedParceiro.get_Ddd1(), ") ", this.SelectedParceiro.get_Telefone1(), "\nTELEFONE 2: (", this.SelectedParceiro.get_Ddd2(), ") ", this.SelectedParceiro.get_Telefone2(), "\nTELEFONE 3: (", this.SelectedParceiro.get_Ddd3(), ") ", this.SelectedParceiro.get_Telefone3(), "\nE-MAIL: ", this.SelectedParceiro.get_Email(), "\n\nENDEREÇO: ", this.SelectedParceiro.get_Endereco(), ", ", this.SelectedParceiro.get_Numero(), ", ", null, null, null, null, null, null, null, null, null }; + if (string.IsNullOrWhiteSpace(this.SelectedParceiro.get_Complemento())) + { + complemento = "-"; + } + else + { + complemento = this.SelectedParceiro.get_Complemento(); + if (complemento == null) + { + complemento = ""; + } + } + cgccpf[21] = complemento; + cgccpf[22] = ", "; + cgccpf[23] = this.SelectedParceiro.get_Bairro(); + cgccpf[24] = ", "; + cgccpf[25] = this.SelectedParceiro.get_Cidade(); + cgccpf[26] = "/"; + cgccpf[27] = this.SelectedParceiro.get_Uf(); + cgccpf[28] = " - "; + cgccpf[29] = this.SelectedParceiro.get_Cep(); + cadastroParceiroViewModel.RegistrarAcao(str, id, nullable, string.Concat(cgccpf)); + int num = this.ParceirosFiltrados.IndexOf(this.SelectedParceiro); + this.Parceiros.Remove(this.SelectedParceiro); + this.ParceirosFiltrados.Remove(this.SelectedParceiro); + this.ParceirosFiltrados = new ObservableCollection(this.ParceirosFiltrados); + if (this.ParceirosFiltrados.Count <= 0) + { + this.Incluir(); + base.Alterar(false); + base.EnableMenu = false; + } + else + { + CadastroParceiroViewModel cadastroParceiroViewModel1 = this; + parceiro = (num < this.ParceirosFiltrados.Count ? this.ParceirosFiltrados.ElementAt(num) : this.ParceirosFiltrados.Last()); + cadastroParceiroViewModel1.SelecionarParceiro(parceiro); + } + base.Loading(false); + base.ToggleSnackBar("PARCEIRO EXCLUÍDO COM SUCESSO", true); + } + else + { + base.Loading(false); + } + } + } + } + + internal async Task> Filtrar(string value) + { + List parceiros = await Task.Run>(() => this.FiltrarParceiro(value)); + return parceiros; + } + + public List FiltrarParceiro(string filter) + { + this.ParceirosFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Parceiros) : new ObservableCollection( + from x in this.Parceiros + where ValidationHelper.RemoveDiacritics(x.get_Nome().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + select x)); + return this.ParceirosFiltrados.ToList(); + } + + public void Incluir() + { + this.SelectedParceiro = new Parceiro(); + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + string complemento; + string str1; + List> keyValuePairs1 = this.SelectedParceiro.Validate(); + if (keyValuePairs1.Count <= 0) + { + str = (this.SelectedParceiro.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str1 = str; + Parceiro parceiro = await this._servico.Save(this.SelectedParceiro); + if (this._servico.Sucesso) + { + CadastroParceiroViewModel cadastroParceiroViewModel = this; + string str2 = string.Concat(str1, " PARCEIRO \"", parceiro.get_Nome(), "\""); + long id = parceiro.get_Id(); + TipoTela? nullable = new TipoTela?(22); + string[] cgccpf = new string[] { "DOCUMENTO: ", parceiro.get_Cgccpf(), "\nTELEFONE 1: (", parceiro.get_Ddd1(), ") ", parceiro.get_Telefone1(), "\nTELEFONE 2: (", parceiro.get_Ddd2(), ") ", parceiro.get_Telefone2(), "\nTELEFONE 3: (", parceiro.get_Ddd3(), ") ", parceiro.get_Telefone3(), "\nE-MAIL: ", parceiro.get_Email(), "\n\nENDEREÇO: ", parceiro.get_Endereco(), ", ", parceiro.get_Numero(), ", ", null, null, null, null, null, null, null, null, null }; + if (string.IsNullOrWhiteSpace(parceiro.get_Complemento())) + { + complemento = "-"; + } + else + { + complemento = parceiro.get_Complemento(); + if (complemento == null) + { + complemento = ""; + } + } + cgccpf[21] = complemento; + cgccpf[22] = ", "; + cgccpf[23] = parceiro.get_Bairro(); + cgccpf[24] = ", "; + cgccpf[25] = parceiro.get_Cidade(); + cgccpf[26] = "/"; + cgccpf[27] = parceiro.get_Uf(); + cgccpf[28] = " - "; + cgccpf[29] = parceiro.get_Cep(); + cadastroParceiroViewModel.RegistrarAcao(str2, id, nullable, string.Concat(cgccpf)); + if (!this.Parceiros.Any((Parceiro x) => x.get_Id() == parceiro.get_Id())) + { + this.Parceiros.Add(parceiro); + } + else + { + DomainBase.Copy(this.Parceiros.First((Parceiro x) => x.get_Id() == parceiro.get_Id()), parceiro); + } + if (!this.ParceirosFiltrados.Any((Parceiro x) => x.get_Id() == parceiro.get_Id())) + { + this.ParceirosFiltrados.Add(parceiro); + } + else + { + DomainBase.Copy(this.ParceirosFiltrados.First((Parceiro x) => x.get_Id() == parceiro.get_Id()), parceiro); + } + this.ParceirosFiltrados = new ObservableCollection(this.ParceirosFiltrados); + Recursos.Parceiros = this.Parceiros; + this.WorkOnSelectedParceiro(parceiro, false); + base.Alterar(false); + base.ToggleSnackBar("PARCEIRO SALVO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str1 = null; + return keyValuePairs; + } + + private async void Seleciona(Parceiro parceiro) + { + base.Loading(true); + await base.PermissaoTela(22); + await this.SelecionaParceiro(parceiro); + base.Loading(false); + } + + private async Task SelecionaParceiro(Parceiro parceiro = null) + { + base.Loading(true); + List parceiros = await (new BaseServico()).BuscarParceirosAsync(); + CadastroParceiroViewModel list = this; + List parceiros1 = parceiros; + list.Parceiros = ( + from x in parceiros1 + orderby x.get_Nome() + select x).ToList(); + this.ParceirosFiltrados = new ObservableCollection(this.Parceiros); + CadastroParceiroViewModel cadastroParceiroViewModel = this; + Parceiro parceiro1 = parceiro; + if (parceiro1 == null) + { + parceiro1 = this.ParceirosFiltrados.FirstOrDefault(); + } + cadastroParceiroViewModel.SelecionarParceiro(parceiro1); + base.Loading(false); + } + + public async void SelecionarParceiro(Parceiro parceiro) + { + if (parceiro != null) + { + Parceiro parceiro1 = await this._servico.BuscarParceiro(parceiro.get_Id()); + DomainBase.Copy(this.ParceirosFiltrados.First((Parceiro x) => x.get_Id() == parceiro.get_Id()), parceiro1); + this.SelectedParceiro = this.ParceirosFiltrados.First((Parceiro x) => x.get_Id() == parceiro.get_Id()); + } + else + { + this.SelectedParceiro = null; + } + } + + private async void WorkOnSelectedParceiro(Parceiro value, bool registrar = true) + { + Parceiro parceiro; + long? nullable; + string complemento; + CadastroParceiroViewModel cadastroParceiroViewModel = this; + parceiro = (value == null || value.get_Id() == 0 ? this.CancelParceiro : (Parceiro)value.Clone()); + cadastroParceiroViewModel.CancelParceiro = parceiro; + if (value != null && value.get_Id() != 0 && (this.LastAccessId != value.get_Id() || this.LastAccessTela != 22)) + { + if (registrar) + { + CadastroParceiroViewModel cadastroParceiroViewModel1 = this; + string str = string.Concat("ACESSOU PARCEIRO \"", value.get_Nome(), "\""); + long id = value.get_Id(); + TipoTela? nullable1 = new TipoTela?(22); + string[] cgccpf = new string[] { "DOCUMENTO: ", value.get_Cgccpf(), "\nTELEFONE 1: (", value.get_Ddd1(), ") ", value.get_Telefone1(), "\nTELEFONE 2: (", value.get_Ddd2(), ") ", value.get_Telefone2(), "\nTELEFONE 3: (", value.get_Ddd3(), ") ", value.get_Telefone3(), "\nE-MAIL: ", value.get_Email(), "\n\nENDEREÇO: ", value.get_Endereco(), ", ", value.get_Numero(), ", ", null, null, null, null, null, null, null, null, null }; + if (string.IsNullOrWhiteSpace(value.get_Complemento())) + { + complemento = "-"; + } + else + { + complemento = value.get_Complemento(); + if (complemento == null) + { + complemento = ""; + } + } + cgccpf[21] = complemento; + cgccpf[22] = ", "; + cgccpf[23] = value.get_Bairro(); + cgccpf[24] = ", "; + cgccpf[25] = value.get_Cidade(); + cgccpf[26] = "/"; + cgccpf[27] = value.get_Uf(); + cgccpf[28] = " - "; + cgccpf[29] = value.get_Cep(); + cadastroParceiroViewModel1.RegistrarAcao(str, id, nullable1, string.Concat(cgccpf)); + } + this.LastAccessId = value.get_Id(); + this.LastAccessTela = 22; + Parceiro selectedParceiro = this.SelectedParceiro; + if (selectedParceiro != null) + { + nullable = new long?(selectedParceiro.get_Id()); + } + else + { + nullable = null; + } + long? nullable2 = nullable; + long num = value.get_Id(); + if (nullable2.GetValueOrDefault() != num | !nullable2.HasValue) + { + Parceiro parceiro1 = await this._servico.BuscarParceiro(value.get_Id()); + DomainBase.Copy(this.SelectedParceiro, parceiro1); + Parceiro selectedParceiro1 = this.SelectedParceiro; + if (selectedParceiro1 != null) + { + selectedParceiro1.Initialize(); + } + else + { + } + this.Initialized = true; + } + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/ComboModelo.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/ComboModelo.cs new file mode 100644 index 0000000..97b1ae0 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/ComboModelo.cs @@ -0,0 +1,43 @@ +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.MalaDireta; +using System; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class ComboModelo : BaseViewModel + { + private Gestor.Model.Domain.MalaDireta.ModeloMalaDireta _modeloMalaDireta = new Gestor.Model.Domain.MalaDireta.ModeloMalaDireta(); + + private bool _indisponivel; + + public bool Indisponivel + { + get + { + return this._indisponivel; + } + set + { + this._indisponivel = value; + base.OnPropertyChanged("Indisponivel"); + } + } + + public Gestor.Model.Domain.MalaDireta.ModeloMalaDireta ModeloMalaDireta + { + get + { + return this._modeloMalaDireta; + } + set + { + this._modeloMalaDireta = value; + base.OnPropertyChanged("ModeloMalaDireta"); + } + } + + public ComboModelo() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/ComboVariavel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/ComboVariavel.cs new file mode 100644 index 0000000..6fd4392 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/ComboVariavel.cs @@ -0,0 +1,45 @@ +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.MalaDireta; +using System; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class ComboVariavel : BaseViewModel + { + private Gestor.Model.Domain.MalaDireta.VariaveisMalaDireta _variaveisMalaDireta; + + private bool _indisponivel; + + public bool Indisponivel + { + get + { + return this._indisponivel; + } + set + { + this._indisponivel = value; + base.OnPropertyChanged("Indisponivel"); + } + } + + public Gestor.Model.Domain.MalaDireta.VariaveisMalaDireta VariaveisMalaDireta + { + get + { + return this._variaveisMalaDireta; + } + set + { + this._variaveisMalaDireta = value; + base.OnPropertyChanged("VariaveisMalaDireta"); + } + } + + public ComboVariavel(Gestor.Model.Domain.MalaDireta.VariaveisMalaDireta variaveisMalaDireta, bool indisponivel) + { + this.VariaveisMalaDireta = variaveisMalaDireta; + this.Indisponivel = indisponivel; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/DownloadViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/DownloadViewModel.cs new file mode 100644 index 0000000..66da49e --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/DownloadViewModel.cs @@ -0,0 +1,550 @@ +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.API; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using IWshRuntimeLibrary; +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.ComponentModel; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.IO.Compression; +using System.Linq; +using System.Net; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Media; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class DownloadViewModel : BaseSegurosViewModel + { + private const string _path = "c:\\AggerSeguros\\"; + + private string _head; + + private string _total; + + private string _progresso; + + private decimal _porcentagem; + + private bool _processando = true; + + private Geometry _maximizeRestore = Geometry.Parse((string)System.Windows.Application.Current.Resources["Maximize"]); + + private string CurrentVersion + { + get; + set; + } + + public string Head + { + get + { + return this._head; + } + set + { + this._head = value; + base.OnPropertyChanged("Head"); + } + } + + public Geometry MaximizeRestore + { + get + { + return this._maximizeRestore; + } + set + { + this._maximizeRestore = value; + base.OnPropertyChanged("MaximizeRestore"); + } + } + + private Gestor.Model.API.Parameters Parameters + { + get; + set; + } + + public decimal Porcentagem + { + get + { + return this._porcentagem; + } + set + { + this._porcentagem = value; + this.Progresso = string.Format("{0}% de {1} MB", value, this.Total); + base.OnPropertyChanged("Porcentagem"); + } + } + + public bool Processando + { + get + { + return this._processando; + } + set + { + this._processando = value; + base.OnPropertyChanged("Processando"); + } + } + + public string Progresso + { + get + { + return this._progresso; + } + set + { + this._progresso = value; + base.OnPropertyChanged("Progresso"); + } + } + + public string Total + { + get + { + return this._total; + } + set + { + this._total = value; + base.OnPropertyChanged("Total"); + } + } + + public DownloadViewModel(Gestor.Model.API.Parameters parameters) + { + this.Parameters = parameters; + base.IsEnabled = false; + this.Head = string.Concat("ATUALIZAÇÃO ", this.Parameters.get_Directory().ToUpper()); + } + + public async Task Atualizar() + { + System.Version version; + string str; + FileVersionInfo versionInfo; + str = (this.Parameters.get_Beta() ? "Beta" : "Released"); + string str1 = str; + int type = this.Parameters.get_Type(); + if (type == 7) + { + try + { + Gestor.Model.API.Version version1 = await Gestor.Application.Helpers.Connection.Get(string.Format("Update/{0}/{1}", str1, this.Parameters.get_Type()), true, false); + if (File.Exists("c:\\AggerSeguros\\Agger.Gestor.exe")) + { + versionInfo = FileVersionInfo.GetVersionInfo("c:\\AggerSeguros\\Agger.Gestor.exe"); + } + else + { + versionInfo = null; + } + FileVersionInfo fileVersionInfo = versionInfo; + if (fileVersionInfo == null || !System.Version.TryParse(fileVersionInfo.FileVersion, out version) || !(version >= System.Version.Parse(version1.get_VersaoAplicacao()))) + { + await this.AtualizarGestor(version1, true); + } + else + { + Funcoes.Destroy(); + str1 = null; + return; + } + } + catch (Exception exception) + { + Funcoes.Destroy(); + } + } + else if (type != 88) + { + if (type == 99) + { + Gestor.Model.API.Version version2 = await Gestor.Application.Helpers.Connection.Get(string.Format("Update/Released/{0}", this.Parameters.get_Type()), true, false); + await this.Atualizar(version2); + } + else + { + this.CurrentVersion = await this.GetCurrentVersion(this.Parameters.get_Directory()); + Gestor.Model.API.Version version3 = await Gestor.Application.Helpers.Connection.Get(string.Format("Update/{0}/{1}", str1, this.Parameters.get_Type()), true, false); + if (!this.VerificarVersao(version3)) + { + await this.Atualizar(version3); + } + else + { + this.Open(); + } + } + } + else if (File.Exists("c:\\AggerSeguros\\Aggilizador.Application.exe")) + { + this.Parameters.set_Application("Aggilizador.Application.exe"); + this.Open(); + } + else + { + this.Parameters.set_Arguments(""); + await this.AtualizarAggilizador(); + } + str1 = null; + } + + public async Task Atualizar(Gestor.Model.API.Version version) + { + string str; + string str1; + if (this.CheckFreeSpace()) + { + string str2 = string.Concat("c:\\AggerSeguros\\", version.get_Name()); + if (Directory.Exists(str2)) + { + Directory.Delete(str2, true); + } + while (Directory.Exists(str2)) + { + Thread.Sleep(500); + } + Directory.CreateDirectory(str2); + using (WebClient webClient = new WebClient()) + { + webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(this.DownloadFileComplete); + webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(this.DownloadProgressCallback); + this.CurrentVersion = version.get_Name(); + str = (this.Parameters.get_Type() == 99 ? string.Concat(version.get_Uri(), "/", version.get_Name(), ".exe") : string.Concat(version.get_Uri(), "/", version.get_Name(), ".zip")); + string str3 = str; + str1 = (this.Parameters.get_Type() == 99 ? string.Concat(str2, ".exe") : string.Concat(str2, "//", version.get_Name(), ".zip")); + string str4 = str1; + Stream stream = webClient.OpenRead(str3); + double num = Math.Round((double)((float)long.Parse(webClient.ResponseHeaders["Content-Length"]) / 1024f / 1024f), 2); + this.Total = num.ToString(CultureInfo.InvariantCulture); + if (stream != null) + { + stream.Dispose(); + } + else + { + } + await webClient.DownloadFileTaskAsync(str3, str4); + webClient.Dispose(); + } + webClient = null; + } + else + { + LogError logError = new LogError(); + logError.set_IdFornecedor(ApplicationHelper.IdFornecedor); + logError.set_Fornecedor(Recursos.Empresa.get_Nome()); + logError.set_UsuarioLogado(Recursos.Usuario.get_Nome()); + logError.set_IdUsuarioLogado(Recursos.Usuario.get_Id()); + logError.set_Versao(ApplicationHelper.Versao.ToString()); + logError.set_Data(Funcoes.GetNetworkTime()); + logError.set_IdErro(1001); + logError.set_Erro(string.Concat(Gestor.Common.Validation.ValidationHelper.GetDescription((TipoErro)1001), " - ", version.get_Name())); + logError.set_HResult(0); + logError.set_HelpLink(""); + logError.set_Message(""); + logError.set_Source(""); + logError.set_StackTrace(""); + logError.set_Maquina(Environment.MachineName); + logError.set_UsuarioMaquina(Environment.UserName); + Erro.RegistrarErro(logError, true); + } + } + + public async Task AtualizarAggilizador() + { + if (this.CheckFreeSpace()) + { + using (WebClient webClient = new WebClient()) + { + webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(this.DownloadFileComplete); + webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(this.DownloadProgressCallback); + string str = "https://update.aggilizador.com.br/stable/Instalador.exe"; + string str1 = string.Concat("c:\\AggerSeguros\\", this.Parameters.get_Application()); + Stream stream = webClient.OpenRead(str); + double num = Math.Round((double)((float)long.Parse(webClient.ResponseHeaders["Content-Length"]) / 1024f / 1024f), 2); + this.Total = num.ToString(CultureInfo.InvariantCulture); + if (stream != null) + { + stream.Dispose(); + } + else + { + } + await webClient.DownloadFileTaskAsync(str, str1); + webClient.Dispose(); + } + webClient = null; + } + else + { + LogError logError = new LogError(); + logError.set_IdFornecedor(ApplicationHelper.IdFornecedor); + logError.set_Fornecedor(Recursos.Empresa.get_Nome()); + logError.set_UsuarioLogado(Recursos.Usuario.get_Nome()); + logError.set_IdUsuarioLogado(Recursos.Usuario.get_Id()); + logError.set_Versao(ApplicationHelper.Versao.ToString()); + logError.set_Data(Funcoes.GetNetworkTime()); + logError.set_IdErro(1001); + logError.set_Erro(string.Concat(Gestor.Common.Validation.ValidationHelper.GetDescription((TipoErro)1001), " - AGGILIZADOR")); + logError.set_HResult(0); + logError.set_HelpLink(""); + logError.set_Message(""); + logError.set_Source(""); + logError.set_StackTrace(""); + logError.set_Maquina(Environment.MachineName); + logError.set_UsuarioMaquina(Environment.UserName); + Erro.RegistrarErro(logError, true); + } + } + + public async Task AtualizarGestor(Gestor.Model.API.Version version, bool criarAtalho = false) + { + string str = "c:\\AggerSeguros\\"; + using (WebClient webClient = new WebClient()) + { + webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(this.DownloadFileCompleteGestor); + webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(this.DownloadProgressCallback); + this.CurrentVersion = version.get_Name(); + string str1 = string.Concat(version.get_Uri(), "/", version.get_Name(), ".zip"); + string str2 = string.Concat(str, version.get_Name(), ".zip"); + Stream stream = webClient.OpenRead(str1); + double num = Math.Round((double)((float)long.Parse(webClient.ResponseHeaders["Content-Length"]) / 1024f / 1024f), 2); + this.Total = num.ToString(CultureInfo.InvariantCulture); + if (stream != null) + { + stream.Dispose(); + } + else + { + } + await webClient.DownloadFileTaskAsync(str1, str2); + webClient.Dispose(); + } + webClient = null; + if (criarAtalho) + { + this.CriarAtalho(); + } + } + + private bool CheckFreeSpace() + { + DriveInfo driveInfo = new DriveInfo("C"); + if (!driveInfo.IsReady) + { + return false; + } + return driveInfo.AvailableFreeSpace > (long)314572800; + } + + private void CriarAtalho() + { + WshShell variable = (WshShell)Activator.CreateInstance(Marshal.GetTypeFromCLSID(new Guid("72C24DD5-D70A-438B-8A42-98424B88AFB8"))); + string str = "c:\\AggerSeguros\\"; + string str1 = "Agger.Gestor.exe"; + string str2 = "Agger Gestor"; + try + { + IWshShortcut variable1 = variable.CreateShortcut(string.Concat(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "\\Agger Gestor.lnk")) as IWshShortcut; + if (variable1 != null) + { + variable1.TargetPath = string.Concat(str, str1); + variable1.WindowStyle = 1; + variable1.Description = str2; + variable1.WorkingDirectory = str; + variable1.IconLocation = string.Concat(str, str1, ",0"); + variable1.Save(); + } + } + catch (Exception exception) + { + } + try + { + IWshShortcut variable2 = variable.CreateShortcut(string.Concat(Environment.GetFolderPath(Environment.SpecialFolder.Programs), "\\Agger Gestor.lnk")) as IWshShortcut; + if (variable2 != null) + { + variable2.TargetPath = string.Concat(str, str1); + variable2.WindowStyle = 1; + variable2.Description = str2; + variable2.WorkingDirectory = str; + variable2.IconLocation = string.Concat(str, str1, ",0"); + variable2.Save(); + } + } + catch (Exception exception1) + { + } + try + { + IWshShortcut variable3 = variable.CreateShortcut(string.Concat(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "\\Agger Gestor.lnk")) as IWshShortcut; + if (variable3 != null) + { + variable3.TargetPath = string.Concat(str, str1); + variable3.WindowStyle = 1; + variable3.Description = str2; + variable3.WorkingDirectory = str; + variable3.IconLocation = string.Concat(str, str1, ",0"); + variable3.Save(); + } + } + catch (Exception exception2) + { + } + try + { + IWshShortcut variable4 = variable.CreateShortcut(string.Concat(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu), "\\Agger Gestor.lnk")) as IWshShortcut; + if (variable4 != null) + { + variable4.TargetPath = string.Concat(str, str1); + variable4.WindowStyle = 1; + variable4.Description = str2; + variable4.WorkingDirectory = str; + variable4.IconLocation = string.Concat(str, str1, ",0"); + variable4.Save(); + } + } + catch (Exception exception3) + { + } + } + + private void DownloadFileComplete(object sender, AsyncCompletedEventArgs e) + { + this.Processando = true; + this.Porcentagem = decimal.Zero; + this.Extract(); + this.Open(); + } + + private void DownloadFileCompleteGestor(object sender, AsyncCompletedEventArgs e) + { + this.Processando = true; + this.Porcentagem = decimal.Zero; + this.ExtractGestor(); + Funcoes.Destroy(); + } + + private void DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e) + { + this.Processando = false; + this.Porcentagem = e.ProgressPercentage; + } + + public void Extract() + { + if (this.Parameters.get_Type() == 99 || this.Parameters.get_Type() == 88) + { + return; + } + string str = string.Concat("c:\\AggerSeguros\\", this.CurrentVersion); + string str1 = string.Concat(str, "\\", this.CurrentVersion, ".zip"); + string.Concat(str, "\\", this.Parameters.get_Application()); + ZipFile.ExtractToDirectory(str1, str); + File.Delete(str1); + } + + public void ExtractGestor() + { + string str = string.Concat("c:\\AggerSeguros\\", this.CurrentVersion, ".zip"); + ZipArchive zipArchive = ZipFile.OpenRead(str); + try + { + foreach (ZipArchiveEntry entry in zipArchive.get_Entries()) + { + string fullPath = Path.GetFullPath(Path.Combine("c:\\AggerSeguros\\", entry.get_FullName())); + fullPath.StartsWith("c:\\AggerSeguros\\", StringComparison.OrdinalIgnoreCase); + if (entry.get_Name() != "") + { + entry.ExtractToFile(fullPath, true); + } + else + { + Directory.CreateDirectory(Path.GetDirectoryName(fullPath)); + } + } + zipArchive.Dispose(); + File.Delete(str); + } + catch (Exception exception) + { + } + } + + private async Task GetCurrentVersion(string name) + { + string str1 = await Task.Run(() => { + string[] directories = Directory.GetDirectories("c:\\AggerSeguros\\"); + List nums = new List(); + string[] strArrays = directories; + for (int i = 0; i < (int)strArrays.Length; i++) + { + string str = strArrays[i]; + if (str.IndexOf(name, StringComparison.Ordinal) > -1) + { + System.Text.RegularExpressions.Match match = (new Regex("(^[A-Za-z]+)(.)([A-Za-z]+)(\\d+)", RegexOptions.IgnoreCase)).Match(str.Replace("c:\\AggerSeguros\\", "")); + if (match.Success) + { + nums.Add(long.Parse(match.Groups[4].Value)); + } + } + } + nums.Reverse(); + if (nums.Count == 0) + { + return ""; + } + return string.Format("{0}{1}", name, nums.First()); + }); + return str1; + } + + public void Open() + { + if (!this.Parameters.get_Run()) + { + Funcoes.Destroy(); + return; + } + string str = Path.Combine((this.Parameters.get_Type() == 99 || this.Parameters.get_Type() == 88 ? "c:\\AggerSeguros\\" : string.Concat("c:\\AggerSeguros\\", this.CurrentVersion)), this.Parameters.get_Application()); + try + { + Process.Start(str, this.Parameters.get_Arguments()); + } + catch + { + } + Funcoes.Destroy(); + } + + private bool VerificarVersao(Gestor.Model.API.Version versao) + { + bool flag = File.Exists(string.Concat("c:\\AggerSeguros\\\\", this.CurrentVersion, "\\", this.Parameters.get_Application())); + return (versao.get_Name() == this.CurrentVersion) & flag; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/EmpresaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/EmpresaViewModel.cs new file mode 100644 index 0000000..6f528ac --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/EmpresaViewModel.cs @@ -0,0 +1,512 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Command; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Helpers; +using Gestor.Common.Validation; +using Gestor.Model.API; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Forms; +using System.Windows.Input; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class EmpresaViewModel : BaseSegurosViewModel + { + private readonly EmpresaServico _servico; + + public Empresa CancelEmpresa; + + private Empresa _selectedEmpresa = new Empresa(); + + private string _logoLabel = "ANEXAR LOGOTIPO"; + + private bool _passWordReadOnly; + + private bool _enableConsultaEspaco = true; + + private double _espaco; + + private string _senha; + + private string _confirmaSenha; + + private ObservableCollection _empresasFiltradas = new ObservableCollection(); + + private bool _isExpanded; + + private Visibility _confirmacaoSenha { get; set; } = Visibility.Collapsed; + + private Visibility _visualizacaoMatriz { get; set; } = Visibility.Collapsed; + + public Visibility ConfirmacaoSenha + { + get + { + return this._confirmacaoSenha; + } + set + { + this._confirmacaoSenha = value; + base.OnPropertyChanged("ConfirmacaoSenha"); + } + } + + public string ConfirmaSenha + { + get + { + return this._confirmaSenha; + } + set + { + this._confirmaSenha = value; + base.OnPropertyChanged("ConfirmaSenha"); + } + } + + public ICommand ConsultarEspacoCommand + { + get; + set; + } + + public List Empresas + { + get; + set; + } + + public ObservableCollection EmpresasFiltradas + { + get + { + return this._empresasFiltradas; + } + set + { + this._empresasFiltradas = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("EmpresasFiltradas"); + } + } + + public bool EnableConsultaEspaco + { + get + { + return this._enableConsultaEspaco; + } + set + { + this._enableConsultaEspaco = value; + base.OnPropertyChanged("EnableConsultaEspaco"); + } + } + + public double Espaco + { + get + { + return this._espaco; + } + set + { + this._espaco = value; + base.OnPropertyChanged("Espaco"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public string LogoLabel + { + get + { + return this._logoLabel; + } + set + { + this._logoLabel = value; + base.OnPropertyChanged("LogoLabel"); + } + } + + public bool PassWordReadOnly + { + get + { + return this._passWordReadOnly; + } + set + { + bool flag; + if (!value) + { + flag = false; + } + else + { + flag = (Recursos.Usuario.get_Administrador() ? true : Recursos.Usuario.get_Id() == (long)0); + } + this._passWordReadOnly = flag; + base.OnPropertyChanged("PassWordReadOnly"); + } + } + + public Empresa SelectedEmpresa + { + get + { + return this._selectedEmpresa; + } + set + { + string str; + long? nullable; + this._selectedEmpresa = value; + if (value != null) + { + string senhaAdmin = value.get_SenhaAdmin(); + if (senhaAdmin != null) + { + str = EncryptionHelper.Decrypt(senhaAdmin); + } + else + { + str = null; + } + } + else + { + str = null; + } + this.Senha = str; + this.ConfirmaSenha = string.Empty; + this.WorkOnSelectedEmpresa(value, true); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedEmpresa"); + } + } + + public string Senha + { + get + { + return this._senha; + } + set + { + this._senha = value; + base.OnPropertyChanged("Senha"); + } + } + + public Visibility VisualizacaoMatriz + { + get + { + return this._visualizacaoMatriz; + } + set + { + this._visualizacaoMatriz = value; + base.OnPropertyChanged("VisualizacaoMatriz"); + } + } + + public EmpresaViewModel() + { + this.ConsultarEspacoCommand = new RelayCommand(async () => await this.ConsultaEspacoUsadoClienteInGb()); + this._servico = new EmpresaServico(); + base.EnableMenu = true; + this.PassWordReadOnly = (!Recursos.Usuario.get_Administrador() ? false : base.EnableFields); + this.Seleciona(); + } + + public async Task AnexarLogo() + { + string fileName = ""; + using (OpenFileDialog openFileDialog = new OpenFileDialog()) + { + openFileDialog.Multiselect = false; + openFileDialog.Filter = "Imagens|*.jpg;*.jpeg;*.png;"; + openFileDialog.InitialDirectory = Environment.SpecialFolder.Desktop.ToString(); + if (DialogResult.OK == openFileDialog.ShowDialog()) + { + fileName = openFileDialog.FileName; + } + else + { + return; + } + } + int num = 0; + try + { + using (MemoryStream memoryStream = new MemoryStream(File.ReadAllBytes(fileName))) + { + byte[] numArray = new byte[checked((IntPtr)memoryStream.Length)]; + memoryStream.Position = (long)0; + memoryStream.Read(numArray, 0, (int)numArray.Length); + this.SelectedEmpresa.set_Logo(numArray); + } + } + catch (Exception exception) + { + num = 1; + } + if (num == 1) + { + string[] newLine = new string[] { "NÃO FOI POSSÍVEL CARREGAR O ARQUIVO ", fileName, ".", Environment.NewLine, "O ARQUIVO ESTÁ INACESSÍVEL OU SENDO UTILIZADO POR OUTRO PROCESSO." }; + await base.ShowMessage(string.Concat(newLine), "OK", "", false); + } + } + + public void CancelarAlteracao() + { + if (this.CancelEmpresa == null || !this.Empresas.Any((Empresa x) => x.get_Id() == this.CancelEmpresa.get_Id())) + { + this.Incluir(); + } + else + { + DomainBase.Copy(this.Empresas.First((Empresa x) => x.get_Id() == this.CancelEmpresa.get_Id()), this.CancelEmpresa); + if (this.EmpresasFiltradas.Count <= 0 || !this.EmpresasFiltradas.Any((Empresa x) => x.get_Id() == this.CancelEmpresa.get_Id())) + { + this.EmpresasFiltradas.Add(this.CancelEmpresa); + } + else + { + DomainBase.Copy(this.EmpresasFiltradas.First((Empresa x) => x.get_Id() == this.CancelEmpresa.get_Id()), this.CancelEmpresa); + } + this.EmpresasFiltradas = new ObservableCollection(this.EmpresasFiltradas); + this.SelectedEmpresa = this.EmpresasFiltradas.First((Empresa x) => x.get_Id() == this.CancelEmpresa.get_Id()); + } + base.Alterar(false); + } + + public async Task ConsultaEspacoUsadoClienteInGb() + { + this.EnableConsultaEspaco = false; + base.Loading(true); + double num = await this._servico.ConsultaEspacoBancoInGb(); + double num1 = 0; + if (Connection.ConnectionAddress.get_UsaAzureStorage()) + { + double num2 = await Connection.EspacoUsadoAzureInBytes(""); + if (num2 > 0) + { + num1 = num2 / 1024 / 1024 / 1024; + } + } + this.Espaco = num + num1; + if (this.Espaco == 0) + { + this.EnableConsultaEspaco = true; + } + base.Loading(false); + } + + internal async Task> Filtrar(string value) + { + List empresas = await Task.Run>(() => this.FiltrarEmpresa(value)); + return empresas; + } + + public List FiltrarEmpresa(string filter) + { + this.EmpresasFiltradas = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Empresas) : new ObservableCollection( + from x in this.Empresas + where ValidationHelper.RemoveDiacritics(x.get_Nome().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby x.get_Nome() + select x)); + return this.EmpresasFiltradas.ToList(); + } + + public void Incluir() + { + this.SelectedEmpresa = new Empresa(); + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + string str1; + List> keyValuePairs1 = this.SelectedEmpresa.Validate(); + if (this.VisualizacaoMatriz != Visibility.Collapsed && this.ConfirmaSenha != this.Senha) + { + keyValuePairs1.Add(new KeyValuePair("SenhaAdmin|SENHA ADM", "A SENHA E A CONFIRMAÇÃO DA SENHA DEVEM SER IGUAIS.")); + } + if (keyValuePairs1.Count <= 0) + { + if (this.SelectedEmpresa.get_Id() == (long)1) + { + this.SelectedEmpresa.set_SenhaAdmin(EncryptionHelper.Encrypt(this.Senha)); + } + str = (this.SelectedEmpresa.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str1 = str; + Empresa empresa = await this._servico.Save(this.SelectedEmpresa); + if (this._servico.Sucesso) + { + base.RegistrarAcao(string.Concat(str1, " EMPRESA \"", empresa.get_Nome(), "\""), empresa.get_Id(), new TipoTela?(18), string.Format("EMPRESA \"{0}\", ID: {1}", empresa.get_Nome(), empresa.get_Id())); + if (!this.Empresas.Any((Empresa x) => x.get_Id() == empresa.get_Id())) + { + this.Empresas.Add(empresa); + } + else + { + DomainBase.Copy(this.Empresas.First((Empresa x) => x.get_Id() == empresa.get_Id()), empresa); + } + if (!this.EmpresasFiltradas.Any((Empresa x) => x.get_Id() == empresa.get_Id())) + { + this.EmpresasFiltradas.Add(empresa); + } + else + { + DomainBase.Copy(this.EmpresasFiltradas.First((Empresa x) => x.get_Id() == empresa.get_Id()), empresa); + } + this.EmpresasFiltradas = new ObservableCollection(this.EmpresasFiltradas); + Recursos.Empresas = this.Empresas; + this.WorkOnSelectedEmpresa(empresa, false); + base.Alterar(false); + base.ToggleSnackBar("EMPRESA SALVA COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str1 = null; + return keyValuePairs; + } + + private async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(18); + await this.SelecionaEmpresas(); + base.Loading(false); + } + + public async void SelecionaEmpresa(Empresa empresa) + { + Empresa empresa1 = await this._servico.BuscarEmpresaPorId(empresa.get_Id()); + DomainBase.Copy(this.EmpresasFiltradas.First((Empresa x) => x.get_Id() == empresa.get_Id()), empresa1); + this.SelectedEmpresa = this.EmpresasFiltradas.First((Empresa x) => x.get_Id() == empresa.get_Id()); + } + + private async Task SelecionaEmpresas() + { + base.Loading(true); + List empresas = await (new BaseServico()).BuscarEmpresasAsync(); + EmpresaViewModel list = this; + List empresas1 = empresas; + IEnumerable empresas2 = empresas1.Where((Empresa x) => { + if (Recursos.Usuario.get_IdEmpresa() == (long)1) + { + return true; + } + return x.get_Id() == Recursos.Usuario.get_IdEmpresa(); + }); + list.Empresas = ( + from x in empresas2 + orderby x.get_Nome() + select x).ToList(); + this.EmpresasFiltradas = new ObservableCollection(this.Empresas); + if (this.EmpresasFiltradas.Count <= 0) + { + this.SelectedEmpresa = new Empresa(); + base.Alterar(false); + base.EnableMenu = false; + } + else + { + this.SelecionaEmpresa(this.EmpresasFiltradas.First()); + } + base.Loading(false); + } + + private void WorkOnSelectedEmpresa(Empresa value, bool registrar = true) + { + long? nullable; + bool logo; + this.CancelEmpresa = (value == null || value.get_Id() == 0 ? this.CancelEmpresa : (Empresa)value.Clone()); + if (value == null || value.get_Id() == 0 || this.LastAccessId == value.get_Id() && this.LastAccessTela == 18) + { + return; + } + if (registrar) + { + base.RegistrarAcao(string.Concat("ACESSOU EMPRESA \"", value.get_Nome(), "\""), value.get_Id(), new TipoTela?(18), string.Format("ID EMPRESA: {0}", value.get_Id())); + } + this.LastAccessId = value.get_Id(); + this.LastAccessTela = 18; + Empresa selectedEmpresa = this.SelectedEmpresa; + if (selectedEmpresa != null) + { + nullable = new long?(selectedEmpresa.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long id = value.get_Id(); + if (nullable1.GetValueOrDefault() != id | !nullable1.HasValue) + { + this.SelectedEmpresa = this.EmpresasFiltradas.FirstOrDefault((Empresa x) => x.get_Id() == value.get_Id()); + } + Empresa empresa = this.SelectedEmpresa; + if (empresa != null) + { + logo = empresa.get_Logo(); + } + else + { + logo = false; + } + this.LogoLabel = (!logo ? "ANEXAR LOGOTIPO" : "ALTERAR LOGOTIPO"); + this.VisualizacaoMatriz = (this.SelectedEmpresa.get_Id() == (long)1 ? Visibility.Visible : Visibility.Collapsed); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/EstipulanteViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/EstipulanteViewModel.cs new file mode 100644 index 0000000..a084abd --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/EstipulanteViewModel.cs @@ -0,0 +1,380 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class EstipulanteViewModel : BaseSegurosViewModel + { + private readonly EstipulanteServico _servico; + + public Estipulante CancelEstipulante; + + private Estipulante _selectedEstipulante = new Estipulante(); + + private ObservableCollection _estipulantesFiltrados = new ObservableCollection(); + + private bool _isExpanded; + + public List Estipulantes + { + get; + set; + } + + public ObservableCollection EstipulantesFiltrados + { + get + { + return this._estipulantesFiltrados; + } + set + { + this._estipulantesFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("EstipulantesFiltrados"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public Estipulante SelectedEstipulante + { + get + { + return this._selectedEstipulante; + } + set + { + long? nullable; + this._selectedEstipulante = value; + this.WorkOnSelectedEstipulante(value, true); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedEstipulante"); + if (value == null) + { + return; + } + this.SelectedEstipulante.Initialize(); + } + } + + public EstipulanteViewModel() + { + this._servico = new EstipulanteServico(); + base.EnableMenu = true; + this.Seleciona(); + } + + public void CancelarAlteracao() + { + if (this.CancelEstipulante == null || !this.Estipulantes.Any((Estipulante x) => x.get_Id() == this.CancelEstipulante.get_Id())) + { + this.Incluir(); + } + else + { + DomainBase.Copy(this.Estipulantes.First((Estipulante x) => x.get_Id() == this.CancelEstipulante.get_Id()), this.CancelEstipulante); + if (this.EstipulantesFiltrados.Count <= 0 || !this.EstipulantesFiltrados.Any((Estipulante x) => x.get_Id() == this.CancelEstipulante.get_Id())) + { + this.EstipulantesFiltrados.Add(this.CancelEstipulante); + } + else + { + DomainBase.Copy(this.EstipulantesFiltrados.First((Estipulante x) => x.get_Id() == this.CancelEstipulante.get_Id()), this.CancelEstipulante); + } + this.EstipulantesFiltrados = new ObservableCollection(this.EstipulantesFiltrados); + this.SelectedEstipulante = this.EstipulantesFiltrados.First((Estipulante x) => x.get_Id() == this.CancelEstipulante.get_Id()); + } + base.Alterar(false); + } + + public async void Excluir() + { + Estipulante estipulante; + if (this.SelectedEstipulante != null && this.SelectedEstipulante.get_Id() != 0) + { + base.Loading(true); + List documentos = await (new BaseServico()).BuscarDocumentosPorEstipulante(this.SelectedEstipulante.get_Id()); + base.Loading(false); + if (documentos.Count > 0) + { + string str = "ESTIPULANTE NÃO PODE SER EXCLUÍDO POIS ESTÁ VINCULADO AOS SEGUINTES DOCUMENTOS:"; + foreach (Documento documento in documentos) + { + if (!string.IsNullOrWhiteSpace(documento.get_Apolice())) + { + object[] newLine = new object[] { Environment.NewLine, documentos.IndexOf(documento) + 1, documento.get_Proposta(), documento.get_Apolice() }; + str = string.Concat(str, string.Format("{0}DOCUMENTO {1} (NÚMERO DA PROPOSTA: {2}, NÚMERO DA APÓLICE: {3})", newLine)); + } + else + { + str = string.Concat(str, string.Format("{0}DOCUMENTO {1} (NÚMERO DA PROPOSTA: {2})", Environment.NewLine, documentos.IndexOf(documento) + 1, documento.get_Proposta())); + } + } + await base.ShowMessage(str, "OK", "", false); + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + base.Loading(true); + if (await this._servico.Delete(this.SelectedEstipulante)) + { + base.RegistrarAcao(string.Concat("EXCLUIU ESTIPULANTE \"", this.SelectedEstipulante.get_Nome(), "\""), this.SelectedEstipulante.get_Id(), new TipoTela?(9), string.Format("ESTIPULANTE \"{0}\", ID: {1}", this.SelectedEstipulante.get_Nome(), this.SelectedEstipulante.get_Id())); + int num = this.EstipulantesFiltrados.IndexOf(this.SelectedEstipulante); + this.Estipulantes.Remove(this.SelectedEstipulante); + this.EstipulantesFiltrados.Remove(this.SelectedEstipulante); + this.EstipulantesFiltrados = new ObservableCollection(this.EstipulantesFiltrados); + if (this.EstipulantesFiltrados.Count <= 0) + { + this.SelectedEstipulante = new Estipulante(); + base.Alterar(false); + base.EnableMenu = false; + } + else + { + EstipulanteViewModel estipulanteViewModel = this; + estipulante = (num < this.EstipulantesFiltrados.Count ? this.EstipulantesFiltrados.ElementAt(num) : this.EstipulantesFiltrados.Last()); + estipulanteViewModel.SelectedEstipulante = estipulante; + } + Recursos.Estipulantes = await (new BaseServico()).BuscarEstipulantesAsync(); + base.Loading(false); + base.ToggleSnackBar("ESTIPULANTE EXCLUÍDO COM SUCESSO", true); + } + else + { + base.Loading(false); + } + } + } + } + + internal async Task> Filtrar(string value) + { + List estipulantes = await Task.Run>(() => this.FiltrarEstipulante(value)); + return estipulantes; + } + + public List FiltrarEstipulante(string filter) + { + this.EstipulantesFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Estipulantes) : new ObservableCollection( + from x in this.Estipulantes + where ValidationHelper.RemoveDiacritics(x.get_Nome().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby x.get_Ativo() descending, x.get_Nome() + select x)); + this.SelectedEstipulante = this.EstipulantesFiltrados.FirstOrDefault(); + return this.EstipulantesFiltrados.ToList(); + } + + public void Incluir() + { + Estipulante estipulante = new Estipulante(); + estipulante.set_IdEmpresa(Recursos.Usuario.get_IdEmpresa()); + estipulante.set_Ativo(true); + this.SelectedEstipulante = estipulante; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + string str1; + List> keyValuePairs1 = this.SelectedEstipulante.Validate(); + List> keyValuePairs2 = keyValuePairs1; + keyValuePairs2.AddRange(await this.Validate()); + keyValuePairs2 = null; + if (keyValuePairs1.Count <= 0) + { + str = (this.SelectedEstipulante.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str1 = str; + Estipulante estipulante = await this._servico.Save(this.SelectedEstipulante); + if (this._servico.Sucesso) + { + base.RegistrarAcao(string.Concat(str1, " ESTIPULANTE \"", estipulante.get_Nome(), "\""), estipulante.get_Id(), new TipoTela?(9), string.Format("ESTIPULANTE \"{0}\", ID: {1}", estipulante.get_Nome(), estipulante.get_Id())); + if (!this.Estipulantes.Any((Estipulante x) => x.get_Id() == estipulante.get_Id())) + { + this.Estipulantes.Add(estipulante); + } + else + { + DomainBase.Copy(this.Estipulantes.First((Estipulante x) => x.get_Id() == estipulante.get_Id()), estipulante); + } + if (!this.EstipulantesFiltrados.Any((Estipulante x) => x.get_Id() == estipulante.get_Id())) + { + this.EstipulantesFiltrados.Add(estipulante); + } + else + { + DomainBase.Copy(this.EstipulantesFiltrados.First((Estipulante x) => x.get_Id() == estipulante.get_Id()), estipulante); + } + this.EstipulantesFiltrados = new ObservableCollection(this.EstipulantesFiltrados); + Recursos.Estipulantes = this.Estipulantes; + this.WorkOnSelectedEstipulante(estipulante, false); + base.Alterar(false); + this.SelectedEstipulante.Initialize(); + base.ToggleSnackBar("ESTIPULANTE SALVO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + keyValuePairs1 = null; + str1 = null; + return keyValuePairs; + } + + private async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(9); + await this.SelecionaEstipulantes(); + base.Loading(false); + } + + public async void SelecionaEstipulante(Estipulante estipulante) + { + Estipulante estipulante1 = await this._servico.BuscarEstipulantePorId(estipulante.get_Id()); + DomainBase.Copy(this.EstipulantesFiltrados.First((Estipulante x) => x.get_Id() == estipulante.get_Id()), estipulante1); + this.SelectedEstipulante = this.EstipulantesFiltrados.First((Estipulante x) => x.get_Id() == estipulante.get_Id()); + } + + private async Task SelecionaEstipulantes() + { + base.Loading(true); + List estipulantes = await (new BaseServico()).BuscarEstipulantesAsync(); + EstipulanteViewModel list = this; + List estipulantes1 = estipulantes; + IEnumerable estipulantes2 = estipulantes1.Where((Estipulante x) => { + if (Recursos.Usuario.get_IdEmpresa() == (long)1) + { + return true; + } + return Recursos.Usuario.get_IdEmpresa() == x.get_IdEmpresa(); + }); + IOrderedEnumerable ativo = + from x in estipulantes2 + orderby x.get_Ativo() descending + select x; + list.Estipulantes = ativo.ThenBy((Estipulante x) => x.get_Nome()).ToList(); + this.EstipulantesFiltrados = new ObservableCollection(this.Estipulantes); + if (this.EstipulantesFiltrados.Count <= 0) + { + this.SelectedEstipulante = new Estipulante(); + base.Alterar(false); + base.EnableMenu = false; + } + else + { + this.SelecionaEstipulante(this.EstipulantesFiltrados.First()); + } + Recursos.Estipulantes = estipulantes; + base.Loading(false); + } + + public async Task>> Validate() + { + List estipulantes; + List> keyValuePairs = new List>(); + bool flag = !string.IsNullOrEmpty(this.SelectedEstipulante.get_Nome()); + if (!ValidationHelper.ValidateDocument(this.SelectedEstipulante.get_Documento())) + { + estipulantes = new List(); + } + else + { + estipulantes = await (new BaseServico()).BuscarEstipulante(this.SelectedEstipulante.get_Documento()); + } + List estipulantes1 = estipulantes; + string nome = ""; + if (estipulantes1.Count > 0) + { + estipulantes1.ForEach((Estipulante x) => { + if (x.get_Id() == this.SelectedEstipulante.get_Id()) + { + return; + } + if (!string.IsNullOrEmpty(this.SelectedEstipulante.get_Documento()) && x.get_Documento() == this.SelectedEstipulante.get_Documento()) + { + flag = false; + nome = x.get_Nome(); + } + }); + } + if (!flag) + { + keyValuePairs.Add(new KeyValuePair("Documento", string.Concat("O DOCUMENTO ESTÁ CADASTRADO PARA O ESTIPULANTE ", nome, "."))); + } + List> keyValuePairs1 = keyValuePairs; + keyValuePairs = null; + return keyValuePairs1; + } + + private void WorkOnSelectedEstipulante(Estipulante value, bool registrar = true) + { + long? nullable; + this.CancelEstipulante = (value == null || value.get_Id() == 0 ? this.CancelEstipulante : (Estipulante)value.Clone()); + if (value == null || value.get_Id() == 0 || this.LastAccessId == value.get_Id() && this.LastAccessTela == 9) + { + return; + } + if (registrar) + { + base.RegistrarAcao(string.Concat("ACESSOU ESTIPULANTE \"", value.get_Nome(), "\""), value.get_Id(), new TipoTela?(9), string.Format("ID ESTIPULANTE: {0}", value.get_Id())); + } + this.LastAccessId = value.get_Id(); + this.LastAccessTela = 9; + Estipulante selectedEstipulante = this.SelectedEstipulante; + if (selectedEstipulante != null) + { + nullable = new long?(selectedEstipulante.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long id = value.get_Id(); + if (nullable1.GetValueOrDefault() != id | !nullable1.HasValue) + { + this.SelectedEstipulante = this.EstipulantesFiltrados.FirstOrDefault((Estipulante x) => x.get_Id() == value.get_Id()); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/EtiquetaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/EtiquetaViewModel.cs new file mode 100644 index 0000000..c19b97e --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/EtiquetaViewModel.cs @@ -0,0 +1,1163 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class EtiquetaViewModel : BaseSegurosViewModel + { + private bool _allSelectedChanging; + + private List _tiposEtiqueta = new List() + { + "CLIENTE", + "APÓLICE" + }; + + private string _tipoEtiqueta = "CLIENTE"; + + private bool? _allSelected; + + private ObservableCollection _apolicesFiltrados = new ObservableCollection(); + + private bool _duasColunas = true; + + private bool _tresColunas; + + private bool _umaPagina; + + private bool _mostrarNascimento; + + private int _pular; + + private object _visibilityColunas; + + private bool _mostrarApolice = true; + + private bool _mostrarVendedor = true; + + private bool _mostrarItem = true; + + public bool? AllSelected + { + get + { + return this._allSelected; + } + set + { + bool? nullable = value; + bool? nullable1 = this._allSelected; + if (nullable.GetValueOrDefault() == nullable1.GetValueOrDefault() & nullable.HasValue == nullable1.HasValue) + { + return; + } + this._allSelected = value; + this.AllSelectedChanged(); + this.Apolices = new List(this.Apolices); + base.OnPropertyChanged("AllSelected"); + } + } + + public List Apolices + { + get; + set; + } + + public ObservableCollection ApolicesFiltrados + { + get + { + return this._apolicesFiltrados; + } + set + { + this._apolicesFiltrados = value; + foreach (Documento apolicesFiltrado in this.ApolicesFiltrados) + { + apolicesFiltrado.add_PropertyChanged(new PropertyChangedEventHandler(this.EntryOnPropertyChanged)); + } + base.OnPropertyChanged("ApolicesFiltrados"); + } + } + + public bool DuasColunas + { + get + { + return this._duasColunas; + } + set + { + this._duasColunas = value; + base.OnPropertyChanged("DuasColunas"); + } + } + + public Visibility ExibirControlesEtiquetaApolice + { + get + { + if (this.TipoEtiqueta != "APÓLICE") + { + return Visibility.Collapsed; + } + return Visibility.Visible; + } + } + + public Visibility ExibirControlesEtiquetaCliente + { + get + { + if (this.TipoEtiqueta != "CLIENTE") + { + return Visibility.Collapsed; + } + return Visibility.Visible; + } + } + + public bool MostrarApolice + { + get + { + return this._mostrarApolice; + } + set + { + this._mostrarApolice = value; + base.OnPropertyChanged("MostrarApolice"); + } + } + + public bool MostrarItem + { + get + { + return this._mostrarItem; + } + set + { + this._mostrarItem = value; + base.OnPropertyChanged("MostrarItem"); + } + } + + public bool MostrarNascimento + { + get + { + return this._mostrarNascimento; + } + set + { + this._mostrarNascimento = value; + base.OnPropertyChanged("MostrarNascimento"); + } + } + + public bool MostrarVendedor + { + get + { + return this._mostrarVendedor; + } + set + { + this._mostrarVendedor = value; + base.OnPropertyChanged("MostrarVendedor"); + } + } + + public int Pular + { + get + { + return this._pular; + } + set + { + this._pular = value; + base.OnPropertyChanged("Pular"); + } + } + + public string TipoEtiqueta + { + get + { + return this._tipoEtiqueta; + } + set + { + this._tipoEtiqueta = value; + base.OnPropertyChanged("TipoEtiqueta"); + base.OnPropertyChanged("ExibirControlesEtiquetaApolice"); + base.OnPropertyChanged("ExibirControlesEtiquetaCliente"); + } + } + + public List TiposEtiqueta + { + get + { + return this._tiposEtiqueta; + } + set + { + this._tiposEtiqueta = value; + base.OnPropertyChanged("TiposEtiqueta"); + } + } + + public bool TresColunas + { + get + { + return this._tresColunas; + } + set + { + this._tresColunas = value; + base.OnPropertyChanged("TresColunas"); + } + } + + public bool UmaPagina + { + get + { + return this._umaPagina; + } + set + { + this._umaPagina = value; + this.VisibilityColunas = (value ? Visibility.Collapsed : Visibility.Visible); + base.OnPropertyChanged("UmaPagina"); + } + } + + public object VisibilityColunas + { + get + { + return this._visibilityColunas; + } + set + { + this._visibilityColunas = value; + base.OnPropertyChanged("VisibilityColunas"); + } + } + + public EtiquetaViewModel() + { + } + + private void AllSelectedChanged() + { + if (this._allSelectedChanging) + { + return; + } + try + { + this._allSelectedChanging = true; + if (this.AllSelected.HasValue) + { + foreach (Documento apolice in this.Apolices) + { + apolice.set_Selecionado(this.AllSelected.Value); + } + } + } + finally + { + this._allSelectedChanging = false; + } + } + + public async Task CarregarDados(List list, bool apenasCliente) + { + ObservableCollection observableCollection; + List documentos = list.ToList(); + List clientes = documentos.Select((Documento x) => { + Cliente cliente = new Cliente(); + cliente.set_Id(x.get_Controle().get_Cliente().get_Id()); + return cliente; + }).ToList(); + ClienteServico clienteServico = new ClienteServico(); + ItemServico itemServico = new ItemServico(); + List clientes1 = clientes; + List clienteEnderecos = await clienteServico.BuscarEnderecosPorCliente(( + from x in clientes1 + where x.get_Id() > (long)0 + select x).ToList()); + if (!apenasCliente) + { + observableCollection = await itemServico.BuscarItens(list.ToList()); + } + else + { + observableCollection = null; + } + ObservableCollection observableCollection1 = observableCollection; + foreach (Documento documento in list) + { + if (( + from y in clienteEnderecos + where y.get_Cliente().get_Id() == documento.get_Controle().get_Cliente().get_Id() + select y).Count() == 0) + { + continue; + } + if (documento.get_Controle().get_Cliente().get_Id() > (long)0) + { + Cliente cliente2 = documento.get_Controle().get_Cliente(); + List clienteEnderecos1 = ( + from y in clienteEnderecos + where y.get_Cliente().get_Id() == documento.get_Controle().get_Cliente().get_Id() + select y).ToList(); + cliente2.set_Enderecos(new ObservableCollection( + from y in clienteEnderecos1 + orderby y.get_Ordem() + select y)); + } + if (apenasCliente) + { + continue; + } + documento.set_ItensAtivo(( + from y in observableCollection1 + where y.get_Documento().get_Id() == documento.get_Id() + select y).ToList()); + } + this.TipoEtiqueta = (apenasCliente ? "CLIENTE" : "APÓLICE"); + EtiquetaViewModel etiquetaViewModel = this; + List documentos1 = list; + IEnumerable documentos2 = documentos1.Where((Documento x) => { + bool enderecos; + Cliente cliente = x.get_Controle().get_Cliente(); + if (cliente != null) + { + enderecos = cliente.get_Enderecos(); + } + else + { + enderecos = false; + } + if (!enderecos) + { + return false; + } + Cliente cliente1 = x.get_Controle().get_Cliente(); + if (cliente1 == null) + { + return false; + } + return cliente1.get_Enderecos().Count() > 0; + }); + etiquetaViewModel.Apolices = ( + from x in documentos2 + orderby x.get_Controle().get_Cliente().get_Nome() + select x).ToList(); + this.ApolicesFiltrados = new ObservableCollection(this.Apolices); + this.AllSelected = new bool?(true); + this.RecheckAllSelected(); + itemServico = null; + clienteEnderecos = null; + } + + public void EmitirEtiquetas() + { + double num; + DateTime? nascimento; + DateTime valueOrDefault; + string str; + string str1; + object obj; + string str2; + string str3; + string complemento; + string str4; + string str5; + string str6; + string cidade; + string str7; + string estado; + string str8; + string str9; + string str10; + object obj1; + string str11; + string str12; + string complemento1; + string str13; + string str14; + string str15; + string str16; + string str17; + object obj2; + object obj3; + object obj4; + string upper; + object obj5; + object obj6; + object obj7; + string upper1; + string str18 = ""; + List list = ( + from x in this.Apolices + where x.get_Selecionado() + select x).ToList(); + string tipoEtiqueta = this.TipoEtiqueta; + if (tipoEtiqueta == "CLIENTE") + { + list = this.Apolices.Where((Documento x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Controle().get_Cliente().get_Enderecos() != null; + }).ToList(); + if (!this.UmaPagina) + { + int num1 = 0; + int num2 = 0; + double num3 = 0; + if (this.DuasColunas) + { + num1 = 10; + num2 = 2; + num3 = 10.52; + } + else if (this.TresColunas) + { + num1 = 10; + num2 = 3; + num3 = 6.82; + } + this.Pular = this.Pular % (num1 * num2); + int pular = this.Pular; + str18 = "ETIQUETAS
"; + int num4 = 0; + while (num4 < list.Count) + { + str18 = string.Concat(str18, "
"); + bool flag = (num4 == 0 ? true : num4 == num1 * num2); + str18 = string.Concat(str18, ""); + for (int i = 0; i < num1 * num2; i += num2) + { + str18 = string.Concat(str18, ""); + if (this.DuasColunas) + { + str18 = string.Concat(str18, ""); + for (int j = 0; j < num2; j++) + { + str18 = string.Concat(str18, ""); + if (j < num2 - 1) + { + if (this.DuasColunas) + { + str18 = string.Concat(str18, ""); + } + } + str18 = string.Concat(str18, "
"); + } + else if (this.TresColunas) + { + str18 = string.Concat(str18, ""); + } + str18 = string.Concat(str18, ""); + if (i + j >= this.Pular) + { + if (num4 < list.Count) + { + Documento item = list[num4]; + if (this.MostrarNascimento) + { + item.get_Controle().get_Cliente().set_Nascimento((new ClienteServico()).BuscarNascimento(item.get_Controle().get_Cliente().get_Id())); + } + if (item.get_Controle().get_Cliente().get_Enderecos().Count() > 0) + { + string[] strArrays = new string[] { str18, item.get_Controle().get_Cliente().get_Nome().Trim(), " ", null, null, null, null, null }; + nascimento = item.get_Controle().get_Cliente().get_Nascimento(); + if (!nascimento.HasValue || !this.MostrarNascimento) + { + str = ""; + } + else + { + nascimento = item.get_Controle().get_Cliente().get_Nascimento(); + if (nascimento.HasValue) + { + valueOrDefault = nascimento.GetValueOrDefault(); + str = valueOrDefault.ToString("dd/MM"); + } + else + { + str = null; + } + } + strArrays[3] = str; + strArrays[4] = "
"; + if (item.get_Controle().get_Cliente().get_Id() == 0) + { + str1 = ""; + } + else + { + string[] strArrays1 = new string[10]; + ClienteEndereco clienteEndereco = item.get_Controle().get_Cliente().get_Enderecos().FirstOrDefault(); + if (clienteEndereco != null) + { + string endereco = clienteEndereco.get_Endereco(); + if (endereco != null) + { + str2 = endereco.Trim(); + } + else + { + str2 = null; + } + } + else + { + str2 = null; + } + strArrays1[0] = str2; + strArrays1[1] = ", "; + ClienteEndereco clienteEndereco1 = item.get_Controle().get_Cliente().get_Enderecos().FirstOrDefault(); + if (clienteEndereco1 != null) + { + string numero = clienteEndereco1.get_Numero(); + if (numero != null) + { + str3 = numero.Trim(); + } + else + { + str3 = null; + } + } + else + { + str3 = null; + } + strArrays1[2] = str3; + ClienteEndereco clienteEndereco2 = item.get_Controle().get_Cliente().get_Enderecos().FirstOrDefault(); + if (clienteEndereco2 != null) + { + complemento = clienteEndereco2.get_Complemento(); + } + else + { + complemento = null; + } + if (!string.IsNullOrWhiteSpace(complemento)) + { + ClienteEndereco clienteEndereco3 = item.get_Controle().get_Cliente().get_Enderecos().FirstOrDefault(); + if (clienteEndereco3 != null) + { + str4 = clienteEndereco3.get_Complemento().Trim(); + } + else + { + str4 = null; + } + str5 = string.Concat("
", str4); + } + else + { + str5 = ""; + } + strArrays1[3] = str5; + strArrays1[4] = "
"; + ClienteEndereco clienteEndereco4 = item.get_Controle().get_Cliente().get_Enderecos().FirstOrDefault(); + if (clienteEndereco4 != null) + { + string bairro = clienteEndereco4.get_Bairro(); + if (bairro != null) + { + str6 = bairro.Trim(); + } + else + { + str6 = null; + } + } + else + { + str6 = null; + } + strArrays1[5] = str6; + strArrays1[6] = " - "; + ClienteEndereco clienteEndereco5 = item.get_Controle().get_Cliente().get_Enderecos().FirstOrDefault(); + if (clienteEndereco5 != null) + { + cidade = clienteEndereco5.get_Cidade(); + } + else + { + cidade = null; + } + if (!string.IsNullOrEmpty(cidade)) + { + ClienteEndereco clienteEndereco6 = item.get_Controle().get_Cliente().get_Enderecos().FirstOrDefault(); + if (clienteEndereco6 != null) + { + str7 = clienteEndereco6.get_Cidade().Trim(); + } + else + { + str7 = null; + } + } + else + { + str7 = ""; + } + strArrays1[7] = str7; + strArrays1[8] = "/"; + ClienteEndereco clienteEndereco7 = item.get_Controle().get_Cliente().get_Enderecos().FirstOrDefault(); + if (clienteEndereco7 != null) + { + estado = clienteEndereco7.get_Estado(); + } + else + { + estado = null; + } + if (!string.IsNullOrEmpty(estado)) + { + ClienteEndereco clienteEndereco8 = item.get_Controle().get_Cliente().get_Enderecos().FirstOrDefault(); + if (clienteEndereco8 != null) + { + str8 = clienteEndereco8.get_Estado().Trim(); + } + else + { + str8 = null; + } + } + else + { + str8 = ""; + } + strArrays1[9] = str8; + str1 = string.Concat(strArrays1); + } + strArrays[5] = str1; + strArrays[6] = "
"; + if (item.get_Controle().get_Cliente().get_Id() == 0) + { + obj = ""; + } + else + { + ClienteEndereco clienteEndereco9 = item.get_Controle().get_Cliente().get_Enderecos().FirstOrDefault(); + if (clienteEndereco9 != null) + { + obj = clienteEndereco9.get_Cep().Trim(); + } + else + { + obj = null; + } + if (obj == null) + { + obj = ""; + } + } + strArrays[7] = (string)obj; + str18 = string.Concat(strArrays); + } + num4++; + } + this.Pular = 0; + } + str18 = string.Concat(str18, "
"); + } + else if (this.TresColunas) + { + str18 = string.Concat(str18, ""); + } + } + str18 = string.Concat(str18, "
"); + str18 = string.Concat(str18, "
"); + } + this.Pular = (pular + list.Count) % (num1 * num2); + } + else + { + str18 = "ETIQUETAS"; + for (int k = 0; k < list.Count; k++) + { + str18 = string.Concat(str18, "
" : "30%'>")); + str18 = string.Concat(str18, "
"); + str18 = string.Concat(str18, ""); + str18 = string.Concat(str18, ""); + num = 10.7; + str18 = string.Concat(str18, ""); + str18 = string.Concat(str18, ""); + str18 = string.Concat(str18, "
"); + Documento documento = list[k]; + if (this.MostrarNascimento) + { + documento.get_Controle().get_Cliente().set_Nascimento((new ClienteServico()).BuscarNascimento(documento.get_Controle().get_Cliente().get_Id())); + } + string[] strArrays2 = new string[] { str18, documento.get_Controle().get_Cliente().get_Nome().Trim(), " ", null, null, null, null, null, null }; + nascimento = documento.get_Controle().get_Cliente().get_Nascimento(); + if (!nascimento.HasValue || !this.MostrarNascimento) + { + str9 = ""; + } + else + { + nascimento = documento.get_Controle().get_Cliente().get_Nascimento(); + if (nascimento.HasValue) + { + valueOrDefault = nascimento.GetValueOrDefault(); + str9 = valueOrDefault.ToString("dd/MM"); + } + else + { + str9 = null; + } + } + strArrays2[3] = str9; + strArrays2[4] = "
"; + if (documento.get_Controle().get_Cliente().get_Id() == 0) + { + str10 = ""; + } + else + { + string[] strArrays3 = new string[10]; + ClienteEndereco clienteEndereco10 = ( + from x in documento.get_Controle().get_Cliente().get_Enderecos() + orderby x.get_Ordem() + select x).FirstOrDefault(); + if (clienteEndereco10 != null) + { + string endereco1 = clienteEndereco10.get_Endereco(); + if (endereco1 != null) + { + str11 = endereco1.Trim(); + } + else + { + str11 = null; + } + } + else + { + str11 = null; + } + strArrays3[0] = str11; + strArrays3[1] = ", "; + ClienteEndereco clienteEndereco11 = documento.get_Controle().get_Cliente().get_Enderecos().FirstOrDefault(); + if (clienteEndereco11 != null) + { + string numero1 = clienteEndereco11.get_Numero(); + if (numero1 != null) + { + str12 = numero1.Trim(); + } + else + { + str12 = null; + } + } + else + { + str12 = null; + } + strArrays3[2] = str12; + ClienteEndereco clienteEndereco12 = documento.get_Controle().get_Cliente().get_Enderecos().FirstOrDefault(); + if (clienteEndereco12 != null) + { + complemento1 = clienteEndereco12.get_Complemento(); + } + else + { + complemento1 = null; + } + if (!string.IsNullOrWhiteSpace(complemento1)) + { + ClienteEndereco clienteEndereco13 = documento.get_Controle().get_Cliente().get_Enderecos().FirstOrDefault(); + if (clienteEndereco13 != null) + { + string complemento2 = clienteEndereco13.get_Complemento(); + if (complemento2 != null) + { + str13 = complemento2.Trim(); + } + else + { + str13 = null; + } + } + else + { + str13 = null; + } + str14 = string.Concat("
", str13); + } + else + { + str14 = ""; + } + strArrays3[3] = str14; + strArrays3[4] = "
"; + ClienteEndereco clienteEndereco14 = documento.get_Controle().get_Cliente().get_Enderecos().FirstOrDefault(); + if (clienteEndereco14 != null) + { + string bairro1 = clienteEndereco14.get_Bairro(); + if (bairro1 != null) + { + str15 = bairro1.Trim(); + } + else + { + str15 = null; + } + } + else + { + str15 = null; + } + strArrays3[5] = str15; + strArrays3[6] = " - "; + ClienteEndereco clienteEndereco15 = documento.get_Controle().get_Cliente().get_Enderecos().FirstOrDefault(); + if (clienteEndereco15 != null) + { + string cidade1 = clienteEndereco15.get_Cidade(); + if (cidade1 != null) + { + str16 = cidade1.Trim(); + } + else + { + str16 = null; + } + } + else + { + str16 = null; + } + strArrays3[7] = str16; + strArrays3[8] = "/"; + ClienteEndereco clienteEndereco16 = documento.get_Controle().get_Cliente().get_Enderecos().FirstOrDefault(); + if (clienteEndereco16 != null) + { + string estado1 = clienteEndereco16.get_Estado(); + if (estado1 != null) + { + str17 = estado1.Trim(); + } + else + { + str17 = null; + } + } + else + { + str17 = null; + } + strArrays3[9] = str17; + str10 = string.Concat(strArrays3); + } + strArrays2[5] = str10; + strArrays2[6] = "
"; + if (documento.get_Controle().get_Cliente().get_Id() == 0) + { + obj1 = ""; + } + else + { + ClienteEndereco clienteEndereco17 = ( + from x in documento.get_Controle().get_Cliente().get_Enderecos() + orderby x.get_Ordem() + select x).FirstOrDefault(); + if (clienteEndereco17 != null) + { + obj1 = clienteEndereco17.get_Cep().Trim(); + } + else + { + obj1 = null; + } + if (obj1 == null) + { + obj1 = ""; + } + } + strArrays2[7] = (string)obj1; + strArrays2[8] = "
"; + str18 = string.Concat(strArrays2); + str18 = string.Concat(str18, "
"); + str18 = string.Concat(str18, "
"); + str18 = string.Concat(str18, "
"); + } + } + base.RegistrarAcao(string.Format("EMITIU ETIQUETA DE {0} CLIENTE{1}", list.Count, (list.Count == 1 ? "" : "S")), (long)0, new TipoTela?(59), string.Concat("IDS E NOMES DOS CLIENTES:\n", string.Join("\n", + from x in list + select string.Concat(x.get_Controle().get_Cliente().get_Id().ToString(), ": \"", x.get_Controle().get_Cliente().get_Nome(), "\"")))); + } + else if (tipoEtiqueta == "APÓLICE") + { + if (!this.UmaPagina) + { + int num5 = 0; + int num6 = 0; + double num7 = 0; + if (this.DuasColunas) + { + num5 = 10; + num6 = 2; + num7 = 10.52; + } + else if (this.TresColunas) + { + num5 = 10; + num6 = 3; + num7 = 6.87; + } + this.Pular = this.Pular % (num5 * num6); + int pular1 = this.Pular; + str18 = "ETIQUETAS
"; + int num8 = 0; + while (num8 < list.Count) + { + str18 = string.Concat(str18, "
"); + str18 = string.Concat(str18, ""); + for (int l = 0; l < num5 * num6; l += num6) + { + str18 = string.Concat(str18, ""); + for (int m = 0; m < num6; m++) + { + str18 = string.Concat(str18, ""); + } + } + str18 = string.Concat(str18, "
"); + if (l + m >= this.Pular) + { + if (num8 < list.Count) + { + Documento item1 = list[num8]; + string[] strArrays4 = new string[] { str18, item1.get_Controle().get_Cliente().get_Nome().Trim(), "
", null, null, null, null }; + if (this.MostrarItem) + { + if (item1.get_ItensAtivo().Count > 1) + { + obj2 = "APÓLICE COLETIVA
"; + } + else + { + Item item2 = item1.get_ItensAtivo().FirstOrDefault(); + if (item2 != null) + { + upper = item2.get_Descricao().ToUpper(); + } + else + { + upper = null; + } + obj2 = string.Concat(upper, "
"); + } + if (obj2 == null) + { + obj2 = ""; + } + } + else + { + obj2 = null; + } + strArrays4[3] = (string)obj2; + if (this.MostrarApolice) + { + obj3 = (item1.get_Apolice() == "PROSPECÇÃO" ? string.Format("{0:d} - APÓLICE: {1}
", item1.get_Vigencia2(), item1.get_Apolice()) : string.Concat(string.Format("{0:d} - {1:d} - APÓLICE: {2}", item1.get_Vigencia1(), item1.get_Vigencia2(), item1.get_Apolice()), (string.IsNullOrEmpty(item1.get_Endosso()) ? "
" : string.Concat(" /", item1.get_Endosso(), "
")))) ?? ""; + } + else + { + obj3 = null; + } + strArrays4[4] = (string)obj3; + strArrays4[5] = (item1.get_Apolice() == "PROSPECÇÃO" ? "" : string.Concat(item1.get_Controle().get_Seguradora().get_Nome(), " - ", item1.get_Controle().get_Ramo().get_Nome(), "
")); + if (this.MostrarVendedor) + { + obj4 = (item1.get_VendedorPrincipal() == null ? "" : string.Concat("VENDEDOR: ", item1.get_VendedorPrincipal().get_Nome())) ?? ""; + } + else + { + obj4 = null; + } + strArrays4[6] = (string)obj4; + str18 = string.Concat(strArrays4); + num8++; + } + this.Pular = 0; + } + str18 = string.Concat(str18, "
"); + str18 = string.Concat(str18, "
"); + } + this.Pular = (pular1 + list.Count) % (num5 * num6); + } + else + { + str18 = "ETIQUETAS"; + for (int n = 0; n < list.Count; n++) + { + str18 = string.Concat(str18, "
" : "30%'>")); + str18 = string.Concat(str18, "
"); + str18 = string.Concat(str18, ""); + str18 = string.Concat(str18, ""); + num = 10.7; + str18 = string.Concat(str18, ""); + str18 = string.Concat(str18, ""); + str18 = string.Concat(str18, "
"); + Documento documento1 = list[n]; + string[] strArrays5 = new string[] { str18, documento1.get_Controle().get_Cliente().get_Nome().Trim(), "
", null, null, null, null }; + if (this.MostrarItem) + { + if (documento1.get_ItensAtivo().Count > 1) + { + obj5 = "APÓLICE COLETIVA
"; + } + else + { + Item item3 = documento1.get_ItensAtivo().FirstOrDefault(); + if (item3 != null) + { + upper1 = item3.get_Descricao().ToUpper(); + } + else + { + upper1 = null; + } + obj5 = string.Concat(upper1, "
"); + } + if (obj5 == null) + { + obj5 = ""; + } + } + else + { + obj5 = null; + } + strArrays5[3] = (string)obj5; + if (this.MostrarApolice) + { + obj6 = (documento1.get_Apolice() == "PROSPECÇÃO" ? string.Format("{0:d} - APÓLICE: {1}
", documento1.get_Vigencia2(), documento1.get_Apolice()) : string.Concat(string.Format("{0:d} - {1:d} - APÓLICE: {2}", documento1.get_Vigencia1(), documento1.get_Vigencia2(), documento1.get_Apolice()), (string.IsNullOrEmpty(documento1.get_Endosso()) ? "
" : string.Concat(" /", documento1.get_Endosso(), "
")))) ?? ""; + } + else + { + obj6 = null; + } + strArrays5[4] = (string)obj6; + strArrays5[5] = (documento1.get_Apolice() == "PROSPECÇÃO" ? "" : string.Concat(documento1.get_Controle().get_Seguradora().get_Nome(), " - ", documento1.get_Controle().get_Ramo().get_Nome(), "
")); + if (this.MostrarVendedor) + { + obj7 = (documento1.get_VendedorPrincipal() == null ? "" : string.Concat("VENDEDOR: ", documento1.get_VendedorPrincipal().get_Nome())) ?? ""; + } + else + { + obj7 = null; + } + strArrays5[6] = (string)obj7; + str18 = string.Concat(strArrays5); + str18 = string.Concat(str18, "
"); + str18 = string.Concat(str18, "
"); + str18 = string.Concat(str18, "
"); + } + } + base.RegistrarAcao(string.Format("EMITIU ETIQUETA DE {0} DOCUMENTO{1}", list.Count, (list.Count == 1 ? "" : "S")), (long)0, new TipoTela?(59), string.Concat("IDS DOS DOCUMENTOS:\n", string.Join(", ", + from x in list + select x.get_Id()))); + } + str18 = string.Concat(str18, ""); + string tempPath = Path.GetTempPath(); + string str19 = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.html", tempPath, (TipoExtrato)0, Funcoes.GetNetworkTime()); + StreamWriter streamWriter = new StreamWriter(str19, true, Encoding.UTF8); + streamWriter.Write(str18); + streamWriter.Close(); + Process.Start(str19); + } + + private void EntryOnPropertyChanged(object sender, PropertyChangedEventArgs args) + { + if (args.PropertyName == "Selecionado") + { + this.RecheckAllSelected(); + } + } + + internal async Task> Filtrar(string value) + { + List documentos = await Task.Run>(() => this.FiltrarApolice(value)); + return documentos; + } + + public List FiltrarApolice(string filter) + { + this.ApolicesFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Apolices) : new ObservableCollection( + from x in this.Apolices + where ValidationHelper.RemoveDiacritics(x.get_Controle().get_Cliente().get_Nome().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby x.get_Controle().get_Cliente().get_Nome() descending, x.get_Id() + select x)); + return this.ApolicesFiltrados.ToList(); + } + + private void RecheckAllSelected() + { + if (this._allSelectedChanging) + { + return; + } + try + { + this._allSelectedChanging = true; + if (this.Apolices.All((Documento e) => e.get_Selecionado())) + { + this.AllSelected = new bool?(true); + } + else if (!this.Apolices.All((Documento e) => !e.get_Selecionado())) + { + this.AllSelected = null; + } + else + { + this.AllSelected = new bool?(false); + } + } + finally + { + this._allSelectedChanging = false; + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/IncluirRamoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/IncluirRamoViewModel.cs new file mode 100644 index 0000000..89f3758 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/IncluirRamoViewModel.cs @@ -0,0 +1,110 @@ +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class IncluirRamoViewModel : BaseSegurosViewModel + { + private Ramo _selectedRamo; + + private Ramo _adicionarRamo; + + private List _ramosAdicionadas; + + private ObservableCollection _ramos; + + private string _filtro; + + public Ramo AdicionarRamo + { + get + { + return this._adicionarRamo; + } + set + { + this._adicionarRamo = value; + base.OnPropertyChanged("AdicionarRamo"); + } + } + + public string Filtro + { + get + { + return this._filtro; + } + set + { + this._filtro = value; + base.OnPropertyChanged("Filtro"); + } + } + + public ObservableCollection Ramos + { + get + { + return this._ramos; + } + set + { + this._ramos = value; + base.OnPropertyChanged("Ramos"); + } + } + + public List RamosAdicionadas + { + get + { + return this._ramosAdicionadas; + } + set + { + this._ramosAdicionadas = value; + base.OnPropertyChanged("RamosAdicionadas"); + } + } + + public Ramo SelectedRamo + { + get + { + return this._selectedRamo; + } + set + { + this._selectedRamo = value; + base.OnPropertyChanged("SelectedRamo"); + } + } + + public IncluirRamoViewModel(List ramos) + { + this.RamosAdicionadas = ramos; + } + + public async void Pesquisar() + { + if (!string.IsNullOrWhiteSpace(this.Filtro) && this.Filtro.Length >= 3) + { + string str = Uri.EscapeDataString(this.Filtro); + List ramos = await Connection.Get>(string.Concat("Ramos/search?ramo=", str), true, false); + this.Ramos = new ObservableCollection( + from x in ramos + where this.RamosAdicionadas.All((Ramo y) => y.get_Id() != x.get_Id()) + select x); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/IncluirSeguradoraViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/IncluirSeguradoraViewModel.cs new file mode 100644 index 0000000..ebeed40 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/IncluirSeguradoraViewModel.cs @@ -0,0 +1,110 @@ +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class IncluirSeguradoraViewModel : BaseSegurosViewModel + { + private Seguradora _selectedSeguradora; + + private Seguradora _adicionarSeguradora; + + private List _seguradorasAdicionadas; + + private ObservableCollection _seguradoras; + + private string _filtro; + + public Seguradora AdicionarSeguradora + { + get + { + return this._adicionarSeguradora; + } + set + { + this._adicionarSeguradora = value; + base.OnPropertyChanged("AdicionarSeguradora"); + } + } + + public string Filtro + { + get + { + return this._filtro; + } + set + { + this._filtro = value; + base.OnPropertyChanged("Filtro"); + } + } + + public ObservableCollection Seguradoras + { + get + { + return this._seguradoras; + } + set + { + this._seguradoras = value; + base.OnPropertyChanged("Seguradoras"); + } + } + + public List SeguradorasAdicionadas + { + get + { + return this._seguradorasAdicionadas; + } + set + { + this._seguradorasAdicionadas = value; + base.OnPropertyChanged("SeguradorasAdicionadas"); + } + } + + public Seguradora SelectedSeguradora + { + get + { + return this._selectedSeguradora; + } + set + { + this._selectedSeguradora = value; + base.OnPropertyChanged("SelectedSeguradora"); + } + } + + public IncluirSeguradoraViewModel(List seguradoras) + { + this.SeguradorasAdicionadas = seguradoras; + } + + public async void Pesquisar() + { + if (!string.IsNullOrWhiteSpace(this.Filtro) && this.Filtro.Length >= 3) + { + string str = Uri.EscapeDataString(this.Filtro); + List seguradoras = await Connection.Get>(string.Concat("Seguradoras/search?cia=", str), true, false); + this.Seguradoras = new ObservableCollection( + from x in seguradoras + where this.SeguradorasAdicionadas.All((Seguradora y) => y.get_Id() != x.get_Id()) + select x); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/MalaDiretaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/MalaDiretaViewModel.cs new file mode 100644 index 0000000..0009fb4 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/MalaDiretaViewModel.cs @@ -0,0 +1,821 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.MalaDireta; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class MalaDiretaViewModel : BaseSegurosViewModel + { + private readonly MalaDiretaServico _servico; + + private readonly FiltroArquivoDigital _filtro; + + private ObservableCollection _malaDireta = new ObservableCollection(); + + private ObservableCollection _variaveis = new ObservableCollection(); + + private bool _enableCredencial; + + private ObservableCollection _modelos = new ObservableCollection(); + + private ComboModelo _selectedModelo = new ComboModelo(); + + private ComboVariavel _selectedVariavel; + + private string _assunto; + + private string _corpo; + + private ObservableCollection _credenciais = new ObservableCollection(); + + private Credencial _selectedCredencial = new Credencial(); + + private ObservableCollection _arquivos = new ObservableCollection(); + + private ObservableCollection _arquivosAnexados = new ObservableCollection(); + + private Gestor.Model.Domain.Common.ArquivoDigital _selectedAnexado = new Gestor.Model.Domain.Common.ArquivoDigital(); + + private Visibility _visibilitySalvarAnexos = Visibility.Hidden; + + private bool _enviarOriginal; + + private bool _salvarArquivoDigital; + + private bool _assinatura; + + public bool _confirmarLeitura; + + public ObservableCollection Arquivos + { + get + { + return this._arquivos; + } + set + { + this._arquivos = value; + base.OnPropertyChanged("Arquivos"); + } + } + + public ObservableCollection ArquivosAnexados + { + get + { + return this._arquivosAnexados; + } + set + { + this._arquivosAnexados = value; + base.OnPropertyChanged("ArquivosAnexados"); + } + } + + public bool Assinatura + { + get + { + return this._assinatura; + } + set + { + this._assinatura = value; + base.OnPropertyChanged("Assinatura"); + } + } + + public string Assunto + { + get + { + return this._assunto; + } + set + { + this._assunto = value; + base.OnPropertyChanged("Assunto"); + } + } + + public bool ConfirmarLeitura + { + get + { + return this._confirmarLeitura; + } + set + { + this._confirmarLeitura = value; + } + } + + public string Corpo + { + get + { + return this._corpo; + } + set + { + this._corpo = value; + base.OnPropertyChanged("Corpo"); + } + } + + public ObservableCollection Credenciais + { + get + { + return this._credenciais; + } + set + { + this._credenciais = value; + base.OnPropertyChanged("Credenciais"); + } + } + + public bool EnableCredencial + { + get + { + return this._enableCredencial; + } + set + { + this._enableCredencial = value; + base.OnPropertyChanged("EnableCredencial"); + } + } + + public bool Enviado + { + get; + set; + } + + public bool EnviarOriginal + { + get + { + return this._enviarOriginal; + } + set + { + this._enviarOriginal = value; + base.OnPropertyChanged("EnviarOriginal"); + } + } + + public ObservableCollection MalaDireta + { + get + { + return this._malaDireta; + } + set + { + this._malaDireta = value; + base.OnPropertyChanged("MalaDireta"); + } + } + + public ObservableCollection Modelos + { + get + { + return this._modelos; + } + set + { + Func func = null; + List list = ( + from variavel in (VariaveisMalaDireta[])Enum.GetValues(typeof(VariaveisMalaDireta)) + select ValidationHelper.GetEntity(variavel)).ToList(); + List strs = ( + from x in this.Variaveis + where !x.Indisponivel + select x into v + select ValidationHelper.GetEntity(v.VariaveisMalaDireta)).ToList(); + List comboModelos = new List(); + foreach (ComboModelo comboModelo in value) + { + IEnumerable strs1 = list.Where(new Func(comboModelo.ModeloMalaDireta.get_Corpo().Contains)); + Func func1 = func; + if (func1 == null) + { + Func func2 = (string s) => strs.Contains(s); + Func func3 = func2; + func = func2; + func1 = func3; + } + if (!strs1.All(func1)) + { + comboModelos.Add(new ComboModelo() + { + ModeloMalaDireta = comboModelo.ModeloMalaDireta, + Indisponivel = true + }); + } + else + { + comboModelos.Add(comboModelo); + } + } + this._modelos = new ObservableCollection( + from x in comboModelos + orderby x.Indisponivel, x.ModeloMalaDireta.get_Assunto() + select x); + base.OnPropertyChanged("Modelos"); + } + } + + public bool SalvarArquivoDigital + { + get + { + return this._salvarArquivoDigital; + } + set + { + this._salvarArquivoDigital = value; + base.OnPropertyChanged("SalvarArquivoDigital"); + } + } + + public Gestor.Model.Domain.Common.ArquivoDigital SelectedAnexado + { + get + { + return this._selectedAnexado; + } + set + { + this._selectedAnexado = value; + base.OnPropertyChanged("SelectedAnexado"); + } + } + + public Credencial SelectedCredencial + { + get + { + return this._selectedCredencial; + } + set + { + this._selectedCredencial = value; + base.OnPropertyChanged("SelectedCredencial"); + } + } + + public ComboModelo SelectedModelo + { + get + { + return this._selectedModelo; + } + set + { + long? nullable; + ModeloMalaDireta modeloMalaDireta; + this._selectedModelo = value; + if (value != null) + { + nullable = new long?(value.ModeloMalaDireta.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + if (value != null) + { + modeloMalaDireta = value.ModeloMalaDireta; + } + else + { + modeloMalaDireta = null; + } + this.WorkOnSelectedModelo(modeloMalaDireta); + base.OnPropertyChanged("SelectedModelo"); + } + } + + public ComboVariavel SelectedVariavel + { + get + { + return this._selectedVariavel; + } + set + { + this._selectedVariavel = value; + base.OnPropertyChanged("SelectedVariavel"); + } + } + + public ObservableCollection Variaveis + { + get + { + return this._variaveis; + } + set + { + this._variaveis = new ObservableCollection( + from x in value + orderby x.Indisponivel, x.VariaveisMalaDireta.ToString() + select x); + base.OnPropertyChanged("Variaveis"); + } + } + + public Visibility VisibilitySalvarAnexos + { + get + { + return this._visibilitySalvarAnexos; + } + set + { + this._visibilitySalvarAnexos = value; + base.OnPropertyChanged("VisibilitySalvarAnexos"); + } + } + + public MalaDiretaViewModel(FiltroArquivoDigital filtro = null) + { + this._servico = new MalaDiretaServico(); + this._filtro = filtro; + this.BuscarCredenciais(); + } + + public async void Anexar() + { + ObservableCollection arquivos = this.Arquivos; + List list = arquivos.Select((IndiceArquivoDigital x) => { + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital = new Gestor.Model.Domain.Common.ArquivoDigital(); + arquivoDigital.set_Descricao(x.get_Descricao()); + arquivoDigital.set_Extensao(x.get_Extensao()); + return arquivoDigital; + }).ToList(); + List arquivoDigitals = await base.AddAttachments(this.ArquivosAnexados.ToList(), list); + if (arquivoDigitals != null) + { + arquivoDigitals.AddRange(this.ArquivosAnexados); + this.ArquivosAnexados = new ObservableCollection(arquivoDigitals); + } + } + + private async void BuscarCredenciais() + { + Credencial credencial; + await base.PermissaoTela(39); + base.VerificarEnables(null); + List credencials = await (new BaseServico()).BuscarCredenciais(); + MalaDiretaViewModel observableCollection = this; + List credencials1 = credencials; + observableCollection.Credenciais = new ObservableCollection( + from x in credencials1 + orderby x.get_Descricao() + select x); + this.EnableCredencial = !base.Restricao(110); + MalaDiretaViewModel malaDiretaViewModel = this; + if (this.EnableCredencial) + { + ObservableCollection credenciais = this.Credenciais; + credencial = credenciais.FirstOrDefault((Credencial x) => x.get_IdUsuario() == Recursos.Usuario.get_Id()); + if (credencial == null) + { + credencial = this.Credenciais.FirstOrDefault(); + } + } + else + { + ObservableCollection credenciais1 = this.Credenciais; + credencial = credenciais1.FirstOrDefault((Credencial x) => x.get_IdUsuario() == Recursos.Usuario.get_Id()); + } + malaDiretaViewModel.SelectedCredencial = credencial; + } + + public void CancelarAlteracao() + { + base.Alterar(false); + this.SelectedModelo = null; + } + + public async Task CarregarEmails(List maladireta, string assunto = null, string corpo = null) + { + Visibility visibility; + ComboVariavel comboVariavel; + ComboVariavel comboVariavel1; + ComboVariavel comboVariavel2; + ComboVariavel comboVariavel3; + ComboVariavel comboVariavel4; + ComboVariavel comboVariavel5; + ComboVariavel comboVariavel6; + ComboVariavel comboVariavel7; + ClienteServico clienteServico = new ClienteServico(); + List malaDiretas = maladireta; + IEnumerable malaDiretas1 = + from x in malaDiretas + where x.get_Cliente() != null + select x; + List nums = ( + from x in malaDiretas1 + select x.get_Cliente().get_Id()).ToList(); + MalaDiretaViewModel malaDiretaViewModel = this; + visibility = (nums.Count > 1 ? Visibility.Hidden : Visibility.Visible); + malaDiretaViewModel.VisibilitySalvarAnexos = visibility; + List clienteEmails = await clienteServico.BuscarEmailsPorCliente(nums); + List malaDiretas2 = new List(); + maladireta.ForEach((Gestor.Model.Domain.MalaDireta.MalaDireta x) => { + bool flag; + if (x.get_Cliente() != null) + { + MalaDiretaViewModel u003cu003e4_this = this; + if (this.Assinatura) + { + flag = true; + } + else if (x.get_ArquivoDigital() == null) + { + flag = false; + } + else + { + List arquivoDigital = x.get_ArquivoDigital(); + Func u003cu003e9_8417 = MalaDiretaViewModel.u003cu003ec.u003cu003e9__84_17; + if (u003cu003e9_8417 == null) + { + u003cu003e9_8417 = (IndiceArquivoDigital a) => { + if (string.IsNullOrEmpty(a.get_UrlAssinatura())) + { + return false; + } + return !a.get_Assinado(); + }; + MalaDiretaViewModel.u003cu003ec.u003cu003e9__84_17 = u003cu003e9_8417; + } + flag = arquivoDigital.Any(u003cu003e9_8417); + } + u003cu003e4_this.Assinatura = flag; + List list = ( + from e in clienteEmails + where e.get_Cliente().get_Id() == this.x.get_Cliente().get_Id() + select e).ToList(); + int num = 0; + Func u003cu003e9_8419 = MalaDiretaViewModel.u003cu003ec.u003cu003e9__84_19; + if (u003cu003e9_8419 == null) + { + u003cu003e9_8419 = (ClienteEmail o) => o.get_Ordem().GetValueOrDefault(); + MalaDiretaViewModel.u003cu003ec.u003cu003e9__84_19 = u003cu003e9_8419; + } + list.OrderBy(u003cu003e9_8419).ToList().ForEach((ClienteEmail e) => { + x.set_Selecionado((!string.IsNullOrWhiteSpace(x.get_Email()) ? false : x.get_Cliente().get_MalaDireta().GetValueOrDefault(true))); + if (num <= 0) + { + x.set_Email(e.get_Email()); + x.set_Ordem(e.get_Ordem().GetValueOrDefault()); + Gestor.Model.Domain.MalaDireta.MalaDireta malaDiretum = new Gestor.Model.Domain.MalaDireta.MalaDireta(); + DomainBase.Copy(malaDiretum, x); + malaDiretas2.Add(malaDiretum); + } + else + { + Gestor.Model.Domain.MalaDireta.MalaDireta malaDiretum1 = new Gestor.Model.Domain.MalaDireta.MalaDireta(); + DomainBase.Copy(malaDiretum1, x); + malaDiretum1.set_Email(e.get_Email()); + malaDiretum1.set_Selecionado(false); + malaDiretas2.Add(malaDiretum1); + } + num++; + }); + } + if (x.get_Prospeccao() == null) + { + return; + } + Gestor.Model.Domain.MalaDireta.MalaDireta malaDiretum2 = new Gestor.Model.Domain.MalaDireta.MalaDireta(); + Gestor.Model.Domain.MalaDireta.MalaDireta malaDiretum3 = x; + Cliente cliente = x.get_Cliente(); + if (cliente == null) + { + cliente = new Cliente(); + cliente.set_Nome(x.get_Prospeccao().get_Nome()); + cliente.set_Documento(x.get_Prospeccao().get_Documento()); + } + malaDiretum3.set_Cliente(cliente); + if (string.IsNullOrEmpty(x.get_Cliente().get_Documento())) + { + x.get_Cliente().set_Documento(x.get_Prospeccao().get_Documento()); + } + x.set_Email(x.get_Prospeccao().get_Email()); + x.set_Ordem(0); + x.set_Selecionado(true); + DomainBase.Copy(malaDiretum2, x); + malaDiretas2.Add(malaDiretum2); + }); + MalaDiretaViewModel observableCollection = this; + List malaDiretas3 = malaDiretas2; + IOrderedEnumerable nome = + from x in malaDiretas3 + orderby x.get_Cliente().get_Nome() + select x; + observableCollection.MalaDireta = new ObservableCollection(nome.ThenBy((Gestor.Model.Domain.MalaDireta.MalaDireta x) => x.get_Ordem())); + this.Variaveis.Add(new ComboVariavel(18, false)); + this.Variaveis.Add(new ComboVariavel(0, false)); + this.Variaveis.Add(new ComboVariavel(1, false)); + this.Variaveis.Add(new ComboVariavel(2, false)); + ObservableCollection variaveis = this.Variaveis; + ObservableCollection malaDireta = this.MalaDireta; + comboVariavel = (malaDireta.Any((Gestor.Model.Domain.MalaDireta.MalaDireta x) => x.get_Cliente().get_VencimentoHabilitacao().HasValue) ? new ComboVariavel(16, false) : new ComboVariavel(16, true)); + variaveis.Add(comboVariavel); + ObservableCollection malaDireta1 = this.MalaDireta; + if (!malaDireta1.Any((Gestor.Model.Domain.MalaDireta.MalaDireta x) => x.get_Cliente().get_Nascimento().HasValue)) + { + this.Variaveis.Add(new ComboVariavel(14, true)); + this.Variaveis.Add(new ComboVariavel(15, true)); + } + else + { + this.Variaveis.Add(new ComboVariavel(14, false)); + this.Variaveis.Add(new ComboVariavel(15, false)); + } + ObservableCollection variaveis1 = this.Variaveis; + ObservableCollection observableCollection1 = this.MalaDireta; + comboVariavel1 = (observableCollection1.Any((Gestor.Model.Domain.MalaDireta.MalaDireta x) => { + if (x.get_ArquivoDigital() == null) + { + return false; + } + return x.get_ArquivoDigital().Any((IndiceArquivoDigital z) => !string.IsNullOrWhiteSpace(z.get_UrlAssinatura())); + }) ? new ComboVariavel(17, false) : new ComboVariavel(17, true)); + variaveis1.Add(comboVariavel1); + ObservableCollection malaDireta2 = this.MalaDireta; + if (!malaDireta2.All((Gestor.Model.Domain.MalaDireta.MalaDireta x) => x.get_Apolice() != null)) + { + this.Variaveis.Add(new ComboVariavel(19, true)); + this.Variaveis.Add(new ComboVariavel(3, true)); + this.Variaveis.Add(new ComboVariavel(4, true)); + this.Variaveis.Add(new ComboVariavel(7, true)); + this.Variaveis.Add(new ComboVariavel(8, true)); + this.Variaveis.Add(new ComboVariavel(5, true)); + this.Variaveis.Add(new ComboVariavel(6, true)); + } + else + { + this.Variaveis.Add(new ComboVariavel(3, false)); + this.Variaveis.Add(new ComboVariavel(4, false)); + this.Variaveis.Add(new ComboVariavel(7, false)); + ObservableCollection variaveis2 = this.Variaveis; + ObservableCollection observableCollection2 = this.MalaDireta; + comboVariavel7 = (observableCollection2.Any((Gestor.Model.Domain.MalaDireta.MalaDireta x) => x.get_Apolice().get_Vigencia2().HasValue) ? new ComboVariavel(8, false) : new ComboVariavel(8, true)); + variaveis2.Add(comboVariavel7); + this.Variaveis.Add(new ComboVariavel(19, false)); + this.Variaveis.Add(new ComboVariavel(23, false)); + this.Variaveis.Add(new ComboVariavel(24, false)); + ObservableCollection malaDireta3 = this.MalaDireta; + if (!malaDireta3.Any((Gestor.Model.Domain.MalaDireta.MalaDireta x) => x.get_Apolice().get_Controle() != null)) + { + this.Variaveis.Add(new ComboVariavel(5, true)); + this.Variaveis.Add(new ComboVariavel(6, true)); + } + else + { + this.Variaveis.Add(new ComboVariavel(5, false)); + this.Variaveis.Add(new ComboVariavel(6, false)); + } + } + ObservableCollection observableCollection3 = this.MalaDireta; + if (!observableCollection3.All((Gestor.Model.Domain.MalaDireta.MalaDireta x) => x.get_Parcela() != null)) + { + this.Variaveis.Add(new ComboVariavel(9, true)); + this.Variaveis.Add(new ComboVariavel(10, true)); + this.Variaveis.Add(new ComboVariavel(13, true)); + } + else + { + this.Variaveis.Add(new ComboVariavel(9, false)); + this.Variaveis.Add(new ComboVariavel(10, false)); + this.Variaveis.Add(new ComboVariavel(13, false)); + } + ObservableCollection variaveis3 = this.Variaveis; + ObservableCollection malaDireta4 = this.MalaDireta; + comboVariavel2 = (malaDireta4.All((Gestor.Model.Domain.MalaDireta.MalaDireta x) => x.get_Item() != null) ? new ComboVariavel(11, false) : new ComboVariavel(11, true)); + variaveis3.Add(comboVariavel2); + ObservableCollection variaveis4 = this.Variaveis; + ObservableCollection observableCollection4 = this.MalaDireta; + comboVariavel3 = (observableCollection4.All((Gestor.Model.Domain.MalaDireta.MalaDireta x) => x.get_Sinistro() != null) ? new ComboVariavel(12, false) : new ComboVariavel(12, true)); + variaveis4.Add(comboVariavel3); + this.Variaveis = new ObservableCollection(this.Variaveis); + ObservableCollection variaveis5 = this.Variaveis; + ObservableCollection malaDireta5 = this.MalaDireta; + comboVariavel4 = (malaDireta5.Any((Gestor.Model.Domain.MalaDireta.MalaDireta x) => { + Documento apolice = x.get_Apolice(); + if (apolice == null) + { + return false; + } + apolice.get_PremioLiquido(); + return true; + }) ? new ComboVariavel(20, false) : new ComboVariavel(20, true)); + variaveis5.Add(comboVariavel4); + ObservableCollection observableCollection5 = this.Variaveis; + ObservableCollection malaDireta6 = this.MalaDireta; + comboVariavel5 = (malaDireta6.Any((Gestor.Model.Domain.MalaDireta.MalaDireta x) => { + Documento apolice = x.get_Apolice(); + if (apolice == null) + { + return false; + } + apolice.get_PremioTotal(); + return true; + }) ? new ComboVariavel(21, false) : new ComboVariavel(21, true)); + observableCollection5.Add(comboVariavel5); + ObservableCollection variaveis6 = this.Variaveis; + ObservableCollection observableCollection6 = this.MalaDireta; + comboVariavel6 = (observableCollection6.Any((Gestor.Model.Domain.MalaDireta.MalaDireta x) => { + Documento apolice = x.get_Apolice(); + if (apolice == null) + { + return false; + } + return apolice.get_FormaPagamento().HasValue; + }) ? new ComboVariavel(22, false) : new ComboVariavel(22, true)); + variaveis6.Add(comboVariavel6); + await this.CarregarModelos(null); + if (assunto != null) + { + this.Assunto = assunto; + } + if (corpo != null) + { + this.Corpo = corpo; + } + } + + private async Task CarregarModelos(ModeloMalaDireta modelo = null) + { + List modeloMalaDiretas = await this._servico.BuscarModelos(); + List comboModelos = new List(); + foreach (ModeloMalaDireta modeloMalaDiretum in modeloMalaDiretas) + { + comboModelos.Add(new ComboModelo() + { + ModeloMalaDireta = modeloMalaDiretum + }); + } + this.Modelos = new ObservableCollection(comboModelos); + if (modelo != null) + { + this.SelectedModelo = this.Modelos.FirstOrDefault((ComboModelo x) => x.ModeloMalaDireta.get_Id() == modelo.get_Id()); + } + } + + public void Delete(Gestor.Model.Domain.Common.ArquivoDigital arquivo) + { + if (this.SelectedAnexado == null) + { + return; + } + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital = this.ArquivosAnexados.First((Gestor.Model.Domain.Common.ArquivoDigital x) => x.get_Descricao() == arquivo.get_Descricao()); + this.ArquivosAnexados.Remove(arquivoDigital); + this.ArquivosAnexados = new ObservableCollection(this.ArquivosAnexados); + } + + public async Task Enviar() + { + bool flag; + if (string.IsNullOrWhiteSpace(this.Corpo) || string.IsNullOrWhiteSpace(this.Assunto)) + { + await base.ShowMessage("NECESSÁRIO CONTER ASSUNTO E MENSAGEM PARA PROSSEGUIR.", "OK", "", false); + flag = false; + } + else if (this.SelectedCredencial == null || this.SelectedCredencial.get_Id() == 0) + { + await base.ShowMessage("NECESSÁRIO SELECIONAR O E-MAIL DE ENVIO PARA PROSSEGUIR.", "OK", "", false); + flag = false; + } + else + { + ObservableCollection malaDireta = this.MalaDireta; + List list = ( + from x in malaDireta + where x.get_Selecionado() + select x).ToList(); + if (list.Count != 0) + { + await base.ShowEnviarEmailsDialog(list, this.Assinatura, this.EnviarOriginal, this.ArquivosAnexados.ToList(), this.Assunto, this.Corpo, this.SelectedCredencial, this._filtro, this.SalvarArquivoDigital, this.ConfirmarLeitura); + this.Enviado = true; + flag = true; + } + else + { + await base.ShowMessage("NECESSÁRIO SELECIONAR AO MENOS UM DESTINATÁRIO PARA PROSSEGUIR.", "OK", "", false); + flag = false; + } + } + return flag; + } + + public async void Excluir() + { + if (this.SelectedModelo != null && this.SelectedModelo.ModeloMalaDireta.get_Id() != 0) + { + if (await base.ShowMessage("DESEJA REALMENTE EXCLUIR O MODELO?", "SIM", "NÃO", false)) + { + if (await this._servico.Delete(this.SelectedModelo.ModeloMalaDireta)) + { + base.RegistrarAcao(string.Concat("EXCLUIU MODELO ", this.SelectedModelo.ModeloMalaDireta.get_Assunto()), this.SelectedModelo.ModeloMalaDireta.get_Id(), new TipoTela?(39), null); + await this.CarregarModelos(null); + this.SelectedModelo = null; + base.ToggleSnackBar("MODELO EXCLUÍDO COM SUCESSO", true); + } + } + } + } + + public void Incluir() + { + this.SelectedModelo = new ComboModelo(); + this.Corpo = string.Empty; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + if (this.SelectedModelo != null) + { + this.SelectedModelo.ModeloMalaDireta.set_Assunto(this.Assunto); + this.SelectedModelo.ModeloMalaDireta.set_Corpo(this.Corpo); + } + else + { + ComboModelo comboModelo = new ComboModelo(); + ModeloMalaDireta modeloMalaDiretum = new ModeloMalaDireta(); + modeloMalaDiretum.set_Assunto(this.Assunto); + modeloMalaDiretum.set_Corpo(this.Corpo); + comboModelo.ModeloMalaDireta = modeloMalaDiretum; + this.SelectedModelo = comboModelo; + } + List> keyValuePairs1 = this.SelectedModelo.ModeloMalaDireta.Validate(); + if (keyValuePairs1.Count <= 0) + { + ModeloMalaDireta modeloMalaDiretum1 = await this._servico.Save(this.SelectedModelo.ModeloMalaDireta); + if (this._servico.Sucesso) + { + base.Alterar(false); + await this.CarregarModelos(modeloMalaDiretum1); + base.ToggleSnackBar("MODELO SALVO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + return keyValuePairs; + } + + public void Selecionar() + { + this.MalaDireta.ToList().ForEach((Gestor.Model.Domain.MalaDireta.MalaDireta x) => x.set_Selecionado(!x.get_Selecionado())); + this.MalaDireta = new ObservableCollection(this.MalaDireta); + } + + private void WorkOnSelectedModelo(ModeloMalaDireta value) + { + if (value == null) + { + return; + } + this.Corpo = this.SelectedModelo.ModeloMalaDireta.get_Corpo(); + this.Assunto = this.SelectedModelo.ModeloMalaDireta.get_Assunto(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/ManutencaoPagamentosViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/ManutencaoPagamentosViewModel.cs new file mode 100644 index 0000000..5270c3f --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/ManutencaoPagamentosViewModel.cs @@ -0,0 +1,821 @@ +using CsQuery.ExtensionMethods; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Data; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class ManutencaoPagamentosViewModel : BaseSegurosViewModel + { + private Visibility _filtrosPersonalizados = Visibility.Collapsed; + + private Visibility _visibilityFiltroPersonalizado = Visibility.Collapsed; + + private List _filtroRelatorioPersonalizado; + + private Gestor.Model.Domain.Relatorios.FiltroPersonalizado _filtroPersonalizado; + + private Type _tipoString = typeof(string); + + private Type _tipoEnum = typeof(Enum); + + private Type _tipoDateTime = typeof(DateTime); + + private Type _tipoDecimal = typeof(decimal); + + private Type _tipoInt = typeof(int); + + private Type _tipoLong = typeof(long); + + private string _valorIncial = ""; + + private string _valorFinal = ""; + + private bool _semValor; + + private Visibility _visibilitySemValor = Visibility.Collapsed; + + private ObservableCollection _filtroPersonalizadoSelecionado; + + private ObservableCollection _filtroRelatorioSelecionado = new ObservableCollection(); + + private ObservableCollection _vendedores = new ObservableCollection(); + + private Vendedor _selectedVendedor; + + private bool _enableExcluirManutPagamento; + + private ObservableCollection _pagamentos; + + private ListCollectionView _view; + + private bool _allSelected; + + private string _selectedFiltro; + + private ObservableCollection _filtros; + + private DateTime? _inicio; + + private DateTime? _fim; + + private List _todosPagamentos; + + public bool AllSelected + { + get + { + return this._allSelected; + } + set + { + this._allSelected = value; + base.OnPropertyChanged("AllSelected"); + this.Selecionar(value); + } + } + + public bool EnableExcluirManutPagamento + { + get + { + return this._enableExcluirManutPagamento; + } + set + { + this._enableExcluirManutPagamento = value; + base.OnPropertyChanged("EnableExcluirManutPagamento"); + } + } + + public Gestor.Model.Domain.Relatorios.FiltroPersonalizado FiltroPersonalizado + { + get + { + return this._filtroPersonalizado; + } + set + { + char chr; + this._filtroPersonalizado = value; + this.VisibilitySemValor = (value != null ? Visibility.Visible : Visibility.Collapsed); + base.OnPropertyChanged("FiltroPersonalizado"); + if (value == null) + { + return; + } + string name = value.get_Tipo().Name; + if (name != null) + { + switch (name.Length) + { + case 3: + { + if (name == "int") + { + break; + } + return; + } + case 4: + { + chr = name[0]; + if (chr == 'E') + { + if (name == "Enum") + { + this.ValorInicial = null; + this.ValorFinal = null; + return; + } + return; + } + else + { + if (chr != 'l') + { + return; + } + if (name == "long") + { + break; + } + return; + } + } + case 5: + { + chr = name[3]; + if (chr == '3') + { + if (name == "int32") + { + break; + } + return; + } + else + { + if (chr != '6') + { + return; + } + if (name == "int64") + { + break; + } + return; + } + } + case 6: + { + if (name != "String") + { + return; + } + this.ValorInicial = ""; + this.ValorFinal = ""; + return; + } + case 7: + { + if (name != "Decimal") + { + return; + } + this.ValorInicial = "0,00"; + this.ValorFinal = "0,00"; + return; + } + case 8: + { + if (name == "DateTime") + { + this.ValorInicial = null; + this.ValorFinal = null; + return; + } + return; + } + default: + { + return; + } + } + this.ValorInicial = "0"; + this.ValorFinal = "0"; + } + } + } + + public ObservableCollection FiltroPersonalizadoSelecionado + { + get + { + return this._filtroPersonalizadoSelecionado; + } + set + { + this._filtroPersonalizadoSelecionado = value; + base.OnPropertyChanged("FiltroPersonalizadoSelecionado"); + } + } + + public ObservableCollection FiltroRelatorioSelecionado + { + get + { + return this._filtroRelatorioSelecionado; + } + set + { + this._filtroRelatorioSelecionado = value; + base.OnPropertyChanged("FiltroRelatorioSelecionado"); + } + } + + public ObservableCollection Filtros + { + get + { + return this._filtros; + } + set + { + this._filtros = value; + base.OnPropertyChanged("Filtros"); + } + } + + public Visibility FiltrosPersonalizados + { + get + { + return this._filtrosPersonalizados; + } + set + { + this._filtrosPersonalizados = value; + base.OnPropertyChanged("FiltrosPersonalizados"); + } + } + + public DateTime? Fim + { + get + { + return this._fim; + } + set + { + if (value.HasValue && value.Value < new DateTime(1754, 1, 1)) + { + value = new DateTime?(new DateTime(1754, 1, 1)); + } + if (value.HasValue && value.Value > new DateTime(9999, 12, 31)) + { + value = new DateTime?(new DateTime(9999, 12, 31)); + } + this._fim = value; + base.OnPropertyChanged("Fim"); + } + } + + public DateTime? Inicio + { + get + { + return this._inicio; + } + set + { + if (value.HasValue && value.Value < new DateTime(1754, 1, 1)) + { + value = new DateTime?(new DateTime(1754, 1, 1)); + } + if (value.HasValue && value.Value > new DateTime(9999, 12, 31)) + { + value = new DateTime?(new DateTime(9999, 12, 31)); + } + this._inicio = value; + base.OnPropertyChanged("Inicio"); + } + } + + public ObservableCollection Pagamentos + { + get + { + return this._pagamentos; + } + set + { + this._pagamentos = value; + this.View = new ListCollectionView(value); + this.View.GroupDescriptions.Add(new PropertyGroupDescription("Pagamento")); + this.View.GroupDescriptions.Add(new PropertyGroupDescription("Vendedor")); + base.OnPropertyChanged("Pagamentos"); + } + } + + public List RelatorioFiltroPersonalizado + { + get + { + return this._filtroRelatorioPersonalizado; + } + set + { + this._filtroRelatorioPersonalizado = value; + base.OnPropertyChanged("RelatorioFiltroPersonalizado"); + } + } + + public string SelectedFiltro + { + get + { + return this._selectedFiltro; + } + set + { + this._selectedFiltro = value; + base.OnPropertyChanged("SelectedFiltro"); + } + } + + public Vendedor SelectedVendedor + { + get + { + return this._selectedVendedor; + } + set + { + this._selectedVendedor = value; + base.OnPropertyChanged("SelectedVendedor"); + } + } + + public bool SemValor + { + get + { + return this._semValor; + } + set + { + this._semValor = value; + if (value) + { + this.ValorInicial = null; + this.ValorFinal = null; + } + base.OnPropertyChanged("SemValor"); + } + } + + public Type TipoDateTime + { + get + { + return this._tipoDateTime; + } + set + { + this._tipoDateTime = value; + base.OnPropertyChanged("TipoDateTime"); + } + } + + public Type TipoDecimal + { + get + { + return this._tipoDecimal; + } + set + { + this._tipoDecimal = value; + base.OnPropertyChanged("TipoDecimal"); + } + } + + public Type TipoEnum + { + get + { + return this._tipoEnum; + } + set + { + this._tipoEnum = value; + base.OnPropertyChanged("TipoEnum"); + } + } + + public Type TipoInt + { + get + { + return this._tipoInt; + } + set + { + this._tipoInt = value; + base.OnPropertyChanged("TipoInt"); + } + } + + public Type TipoLong + { + get + { + return this._tipoLong; + } + set + { + this._tipoLong = value; + base.OnPropertyChanged("TipoLong"); + } + } + + public Type TipoString + { + get + { + return this._tipoString; + } + set + { + this._tipoString = value; + base.OnPropertyChanged("TipoString"); + } + } + + private List TodosPagamentos + { + get + { + return this._todosPagamentos; + } + set + { + this.FiltrosPersonalizados = (value == null || !value.Any() ? Visibility.Collapsed : Visibility.Visible); + this._todosPagamentos = value; + } + } + + public string ValorFinal + { + get + { + return this._valorFinal; + } + set + { + this._valorFinal = value; + base.OnPropertyChanged("ValorFinal"); + } + } + + public string ValorInicial + { + get + { + return this._valorIncial; + } + set + { + this._valorIncial = value; + base.OnPropertyChanged("ValorInicial"); + } + } + + public ObservableCollection Vendedores + { + get + { + return this._vendedores; + } + set + { + this._vendedores = value; + this.SelectedVendedor = this.SelectedVendedor ?? value.FirstOrDefault(); + base.OnPropertyChanged("Vendedores"); + } + } + + public ListCollectionView View + { + get + { + return this._view; + } + set + { + this._view = value; + base.OnPropertyChanged("View"); + } + } + + public Visibility VisibilityFiltroPersonalizado + { + get + { + return this._visibilityFiltroPersonalizado; + } + set + { + this._visibilityFiltroPersonalizado = value; + base.OnPropertyChanged("VisibilityFiltroPersonalizado"); + } + } + + public Visibility VisibilitySemValor + { + get + { + return this._visibilitySemValor; + } + set + { + this._visibilitySemValor = value; + base.OnPropertyChanged("VisibilitySemValor"); + } + } + + public ManutencaoPagamentosViewModel() + { + this._filtrosPersonalizados = Visibility.Collapsed; + this._visibilityFiltroPersonalizado = Visibility.Collapsed; + this._tipoString = typeof(string); + this._tipoEnum = typeof(Enum); + this._tipoDateTime = typeof(DateTime); + this._tipoDecimal = typeof(decimal); + this._tipoInt = typeof(int); + this._tipoLong = typeof(long); + this._valorIncial = ""; + this._valorFinal = ""; + this._visibilitySemValor = Visibility.Collapsed; + this._filtroRelatorioSelecionado = new ObservableCollection(); + this._vendedores = new ObservableCollection(); + Usuario usuario = Recursos.Usuario; + if (usuario != null) + { + id = usuario.get_Id() > (long)0; + } + else + { + id = false; + } + this._enableExcluirManutPagamento = id; + this._inicio = new DateTime?(Funcoes.GetNetworkTime()); + DateTime networkTime = Funcoes.GetNetworkTime(); + this._fim = new DateTime?(networkTime.AddDays(7)); + base(); + bool id; + this.Filtros = new ObservableCollection() + { + "DATA DE EMISSÃO DO RECEBIMENTO", + "DATA DE EMISSÃO DO RECIBO DE PAGAMENTO" + }; + this.SelectedFiltro = this.Filtros.First(); + List list = ( + from x in Recursos.Vendedores + where x.get_Ativo() + orderby x.get_Nome() + select x).ToList(); + Vendedor vendedor = new Vendedor(); + vendedor.set_Id((long)0); + vendedor.set_Nome("TODAS OS VENDEDORES"); + list.Insert(0, vendedor); + this.Vendedores = new ObservableCollection(list); + this.RelatorioFiltroPersonalizado = Funcoes.PopularFiltroPersonalizado(); + } + + public async void AdcionarFiltroPersonalizado() + { + string str; + DateTime dateTime; + decimal num; + int num1; + long num2; + List filtroPersonalizados; + List filtroPersonalizados1; + if (this.FiltroPersonalizado != null) + { + if (this.SemValor) + { + filtroPersonalizados = (this.FiltroPersonalizadoSelecionado == null ? new List() : ( + from x in this.FiltroPersonalizadoSelecionado + where x.get_Propriedade() == this.FiltroPersonalizado.get_Propriedade() + select x).ToList()); + List filtroPersonalizados2 = filtroPersonalizados; + if (filtroPersonalizados2.Count > 0) + { + filtroPersonalizados2.ForEach((Gestor.Model.Domain.Relatorios.FiltroPersonalizado x) => this.FiltroPersonalizadoSelecionado.Remove(x)); + } + str = string.Concat(this.FiltroPersonalizado.get_Nome(), ": EM BRANCO"); + } + else + { + filtroPersonalizados1 = (this.FiltroPersonalizadoSelecionado == null ? new List() : this.FiltroPersonalizadoSelecionado.Where((Gestor.Model.Domain.Relatorios.FiltroPersonalizado x) => { + if (x.get_Propriedade() != this.FiltroPersonalizado.get_Propriedade()) + { + return false; + } + return x.get_SemValor(); + }).ToList()); + List filtroPersonalizados3 = filtroPersonalizados1; + if (filtroPersonalizados3.Count > 0) + { + filtroPersonalizados3.ForEach((Gestor.Model.Domain.Relatorios.FiltroPersonalizado x) => this.FiltroPersonalizadoSelecionado.Remove(x)); + } + string name = this.FiltroPersonalizado.get_Tipo().Name; + if (name == "DateTime") + { + if (!DateTime.TryParse(this.ValorInicial, out dateTime) || !DateTime.TryParse(this.ValorFinal, out dateTime) || DateTime.Parse(this.ValorInicial) > DateTime.Parse(this.ValorFinal)) + { + await base.ShowMessage("O VALOR DE INTERVALO DEVE SER PREENCHIDO CORRETAMENTE.", "OK", "", false); + return; + } + else + { + str = string.Format("{0}: {1:d} até {2:d}", this.FiltroPersonalizado.get_Nome(), DateTime.Parse(this.ValorInicial), DateTime.Parse(this.ValorFinal)); + } + } + else if (name == "Decimal") + { + if (!decimal.TryParse(this.ValorInicial, out num) || !decimal.TryParse(this.ValorFinal, out num) || Math.Abs(decimal.Parse(this.ValorInicial)) > Math.Abs(decimal.Parse(this.ValorFinal))) + { + await base.ShowMessage("O VALOR DE INTERVALO DEVE SER PREENCHIDO CORRETAMENTE.", "OK", "", false); + return; + } + else + { + str = string.Format("{0}: {1:n2} até {2:n2}", this.FiltroPersonalizado.get_Nome(), decimal.Parse(this.ValorInicial), decimal.Parse(this.ValorFinal)); + } + } + else if (name == "Int32") + { + if (!int.TryParse(this.ValorInicial, out num1) || !int.TryParse(this.ValorFinal, out num1) || int.Parse(this.ValorInicial) > int.Parse(this.ValorFinal)) + { + await base.ShowMessage("O VALOR DE INTERVALO DEVE SER PREENCHIDO CORRETAMENTE.", "OK", "", false); + return; + } + else + { + str = string.Format("{0}: {1:n0} até {2:n0}", this.FiltroPersonalizado.get_Nome(), int.Parse(this.ValorInicial), int.Parse(this.ValorFinal)); + } + } + else if (name != "Int64") + { + if (!string.IsNullOrEmpty(this.ValorInicial)) + { + str = string.Concat(this.FiltroPersonalizado.get_Nome(), " = ", this.ValorInicial); + } + else + { + await base.ShowMessage("O VALOR DEVE SER PREENCHIDO CORRETAMENTE.", "OK", "", false); + return; + } + } + else if (!long.TryParse(this.ValorInicial, out num2) || !long.TryParse(this.ValorFinal, out num2) || long.Parse(this.ValorInicial) > (long)int.Parse(this.ValorFinal)) + { + await base.ShowMessage("O VALOR DE INTERVALO DEVE SER PREENCHIDO CORRETAMENTE.", "OK", "", false); + return; + } + else + { + str = string.Format("{0}: {1:n0} até {2:n0}", this.FiltroPersonalizado.get_Nome(), long.Parse(this.ValorInicial), long.Parse(this.ValorFinal)); + } + } + if (this.FiltroPersonalizadoSelecionado == null) + { + this.FiltroPersonalizadoSelecionado = new ObservableCollection(); + } + ObservableCollection filtroPersonalizadoSelecionado = this.FiltroPersonalizadoSelecionado; + Gestor.Model.Domain.Relatorios.FiltroPersonalizado filtroPersonalizado = new Gestor.Model.Domain.Relatorios.FiltroPersonalizado(); + filtroPersonalizado.set_Nome(this.FiltroPersonalizado.get_Nome()); + filtroPersonalizado.set_Propriedade(this.FiltroPersonalizado.get_Propriedade()); + filtroPersonalizado.set_Tipo(this.FiltroPersonalizado.get_Tipo()); + filtroPersonalizado.set_ValorIncial(this.ValorInicial); + filtroPersonalizado.set_ValorFinal(this.ValorFinal); + filtroPersonalizado.set_SemValor(this.SemValor); + filtroPersonalizado.set_Descricao(str); + filtroPersonalizadoSelecionado.Add(filtroPersonalizado); + this.FiltroPersonalizado = null; + this.ValorInicial = string.Empty; + this.ValorFinal = string.Empty; + this.PesquisaPersonalizada(); + } + } + + public async Task Buscar() + { + if (this.Inicio.HasValue && this.Fim.HasValue) + { + this.FiltroPersonalizadoSelecionado = null; + this.VisibilityFiltroPersonalizado = Visibility.Visible; + Gestor.Model.Domain.Relatorios.Filtros filtro = new Gestor.Model.Domain.Relatorios.Filtros(); + filtro.set_Inicio(this.Inicio.Value); + filtro.set_Fim(this.Fim.Value); + Gestor.Model.Domain.Relatorios.Filtros filtro1 = filtro; + if (this.SelectedVendedor.get_Id() > (long)0) + { + filtro1.set_Vendedores(new List() + { + this.SelectedVendedor.get_Id() + }); + } + if (this.SelectedFiltro == "DATA DE EMISSÃO DO RECEBIMENTO") + { + filtro1.set_Referencia("DATA PREVISÃO"); + } + else + { + filtro1.set_Referencia("DATA PAGAMENTO"); + } + this.TodosPagamentos = await (new VendedorServico()).BuscarPagos(filtro1); + this.Pagamentos = new ObservableCollection(this.TodosPagamentos); + string[] shortDateString = new string[] { "CONSULTOU OS PAGAMENTOS DE \"", null, null, null, null, null }; + DateTime value = this.Inicio.Value; + shortDateString[1] = value.ToShortDateString(); + shortDateString[2] = "\" A \""; + value = this.Fim.Value; + shortDateString[3] = value.ToShortDateString(); + shortDateString[4] = "\" POR "; + shortDateString[5] = this.SelectedFiltro; + base.RegistrarAcao(string.Concat(shortDateString), (long)0, new TipoTela?(58), null); + } + } + + public async Task Excluir() + { + object obj; + string str; + ObservableCollection pagamentos = this.Pagamentos; + List list = ( + from x in pagamentos + where x.get_Selecionado() + select x).ToList(); + if (list.Count != 0) + { + str = "PAGAMENTOS EXCLUÍDOS:"; + foreach (ManutencaoPagamentos manutencaoPagamento in list) + { + str = string.Concat(str, string.Format("\nID: {0}, NÚMERO: {1}, ID DOCUMENTO: {2}", manutencaoPagamento.get_Id(), manutencaoPagamento.get_Parcela(), manutencaoPagamento.get_IdDocumento())); + VendedorParcela vendedorParcela = await (new VendedorServico()).BuscarVendedorParcelaCompleto(manutencaoPagamento.get_Id()); + vendedorParcela.set_DataPagamento(null); + await (new ParcelaServico()).Save(vendedorParcela); + } + ManutencaoPagamentosViewModel manutencaoPagamentosViewModel = this; + object count = list.Count; + obj = (list.Count > 1 ? "S" : ""); + manutencaoPagamentosViewModel.RegistrarAcao(string.Format("EXCLUIU {0} PAGAMENTO{1}", count, obj), (long)0, new TipoTela?(58), str); + for (int i = this.Pagamentos.Count - 1; i >= 0; i--) + { + if (this.Pagamentos[i].get_Selecionado()) + { + this.Pagamentos.RemoveAt(i); + } + } + base.ToggleSnackBar("PAGAMENTOS EXCLUÍDOS COM SUCESSO.", true); + } + list = null; + str = null; + } + + public void PesquisaPersonalizada() + { + this.Pagamentos = new ObservableCollection(this.TodosPagamentos.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), false)); + } + + public void Selecionar(bool value) + { + if (this.Pagamentos == null || this.Pagamentos.Count == 0) + { + return; + } + ExtensionMethods.ForEach(this.Pagamentos, (ManutencaoPagamentos x) => x.set_Selecionado(value)); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/NotaFiscalViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/NotaFiscalViewModel.cs new file mode 100644 index 0000000..61ee285 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/NotaFiscalViewModel.cs @@ -0,0 +1,482 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Globalization; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class NotaFiscalViewModel : BaseSegurosViewModel + { + private readonly NotaFiscalServico _servico; + + private readonly ServicoExtrato _servicoExtrato; + + private bool _apelido; + + private List _estipulantes; + + private List _seguradoras; + + private ObservableCollection _notasFiscaisFiltrados = new ObservableCollection(); + + private bool _isExpanded; + + private string _numExtrato; + + private NotaFiscal _selectedNotaFiscal; + + public NotaFiscal CancelNotaFiscal; + + public bool Apelido + { + get + { + return this._apelido; + } + set + { + this._apelido = value; + base.OnPropertyChanged("Apelido"); + } + } + + public List Estipulantes + { + get + { + return this._estipulantes; + } + set + { + this._estipulantes = value; + base.OnPropertyChanged("Estipulantes"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public List NotasFiscais + { + get; + set; + } + + public ObservableCollection NotasFiscaisFiltrados + { + get + { + return this._notasFiscaisFiltrados; + } + set + { + this._notasFiscaisFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("NotasFiscaisFiltrados"); + } + } + + public string NumExtrato + { + get + { + return this._numExtrato; + } + set + { + this._numExtrato = value; + base.OnPropertyChanged("NumExtrato"); + } + } + + public List Seguradoras + { + get + { + return this._seguradoras; + } + set + { + this._seguradoras = value; + base.OnPropertyChanged("Seguradoras"); + } + } + + public NotaFiscal SelectedNotaFiscal + { + get + { + return this._selectedNotaFiscal; + } + set + { + long? nullable; + this._selectedNotaFiscal = value; + this.WorkOnSelectedNotaFiscal(value, true); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedNotaFiscal"); + } + } + + public NotaFiscalViewModel() + { + this._servicoExtrato = new ServicoExtrato(); + this._servico = new NotaFiscalServico(); + this.Seguradoras = ( + from x in Recursos.Seguradoras + where x.get_Ativo() + select x).ToList(); + this.Estipulantes = ( + from e in Recursos.Estipulantes + where e.get_Ativo() + select e).ToList(); + this.Apelido = Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 6); + base.EnableMenu = true; + this.Seleciona(); + } + + public async Task BuscarImposto() + { + decimal iss; + List impostos = await (new ImpostoServico()).Buscar(new bool?(true)); + Imposto imposto = impostos.FirstOrDefault((Imposto x) => { + if (x.get_Seguradora() == null || x.get_Seguradora().get_Id() != this.SelectedNotaFiscal.get_Seguradora().get_Id()) + { + return false; + } + return x.get_Ramo() == null; + }); + if (imposto == null) + { + List impostos1 = impostos; + imposto = impostos1.FirstOrDefault((Imposto x) => { + if (x.get_Seguradora() != null) + { + return false; + } + return x.get_Ramo() == null; + }); + } + if (imposto != null) + { + iss = imposto.get_Iss(); + } + else + { + iss = decimal.Zero; + } + return iss; + } + + public void CancelarAlteracao() + { + if (this.CancelNotaFiscal == null || !this.NotasFiscais.Any((NotaFiscal x) => x.get_Id() == this.CancelNotaFiscal.get_Id())) + { + this.Incluir(); + } + else + { + DomainBase.Copy(this.NotasFiscais.First((NotaFiscal x) => x.get_Id() == this.CancelNotaFiscal.get_Id()), this.CancelNotaFiscal); + if (this.NotasFiscaisFiltrados.Count <= 0 || !this.NotasFiscaisFiltrados.Any((NotaFiscal x) => x.get_Id() == this.CancelNotaFiscal.get_Id())) + { + this.NotasFiscaisFiltrados.Add(this.CancelNotaFiscal); + } + else + { + DomainBase.Copy(this.NotasFiscaisFiltrados.First((NotaFiscal x) => x.get_Id() == this.CancelNotaFiscal.get_Id()), this.CancelNotaFiscal); + } + this.NotasFiscaisFiltrados = new ObservableCollection(this.NotasFiscaisFiltrados); + this.SelectedNotaFiscal = this.NotasFiscaisFiltrados.First((NotaFiscal x) => x.get_Id() == this.CancelNotaFiscal.get_Id()); + } + base.Alterar(false); + } + + public async void Excluir() + { + object obj; + if (this.SelectedNotaFiscal != null && this.SelectedNotaFiscal.get_Id() != 0) + { + if (await base.ShowMessage(string.Concat("DESEJA REALMENTE EXCLUIR A NOTA FISCAL DA ", this.SelectedNotaFiscal.get_Seguradora().get_Nome(), "?"), "SIM", "NÃO", false)) + { + base.Loading(true); + if (await this._servico.Delete(this.SelectedNotaFiscal)) + { + NotaFiscalViewModel notaFiscalViewModel = this; + string str = string.Format("EXCLUIU NOTA FISCAL DE ID \"{0}\"", this.SelectedNotaFiscal.get_Id()); + long id = this.SelectedNotaFiscal.get_Id(); + TipoTela? nullable = new TipoTela?(55); + object[] nome = new object[] { this.SelectedNotaFiscal.get_Seguradora().get_Nome(), null, null, null, null }; + obj = (!this.SelectedNotaFiscal.get_Data().HasValue ? "-" : string.Format("{0:d}", this.SelectedNotaFiscal.get_Data())); + nome[1] = obj; + nome[2] = this.SelectedNotaFiscal.get_ValorBruto(); + nome[3] = this.SelectedNotaFiscal.get_Iss(); + nome[4] = this.SelectedNotaFiscal.get_ValorLiquido(); + notaFiscalViewModel.RegistrarAcao(str, id, nullable, string.Format("SEGURADORA: {0}\nDATA: {1}\nBRUTO: {2:c}\nISS: {3:c}\nLÍQUIDO: {4:c}", nome)); + await this.SelecionaNotaFiscal(); + base.Loading(false); + base.ToggleSnackBar("RECIBO EXCLUÍDO COM SUCESSO", true); + } + else + { + base.Loading(false); + } + } + } + } + + public async Task> Filtrar(string value) + { + List notaFiscals = await Task.Run>(() => this.FiltrarNotaFiscal(value)); + return notaFiscals; + } + + public List FiltrarNotaFiscal(string filter) + { + this.NotasFiscaisFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.NotasFiscais) : new ObservableCollection(this.NotasFiscais.Where((NotaFiscal x) => { + if (ValidationHelper.RemoveDiacritics(x.get_Seguradora().get_Nome().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) || ValidationHelper.RemoveDiacritics(x.get_ValorBruto().ToString(CultureInfo.InvariantCulture).Trim()).Contains(ValidationHelper.RemoveDiacritics(filter))) + { + return true; + } + return ValidationHelper.RemoveDiacritics(x.get_Data().ToString().Trim()).Contains(ValidationHelper.RemoveDiacritics(filter)); + }).OrderBy((NotaFiscal x) => x.get_Seguradora().get_Nome()))); + return this.NotasFiscaisFiltrados.ToList(); + } + + public void Incluir() + { + NotaFiscal notaFiscal = new NotaFiscal(); + notaFiscal.set_Seguradora(new Seguradora()); + notaFiscal.set_Estipulante(new Estipulante()); + notaFiscal.set_Iss(decimal.Zero); + notaFiscal.set_ValorLiquido(decimal.Zero); + notaFiscal.set_ValorBruto(decimal.Zero); + notaFiscal.set_Extrato(""); + this.SelectedNotaFiscal = notaFiscal; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + long? nullable; + bool valueOrDefault; + object obj; + string str1; + List> keyValuePairs1 = this.SelectedNotaFiscal.Validate(); + if (keyValuePairs1.Count <= 0) + { + str = (this.SelectedNotaFiscal.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str1 = str; + NotaFiscal selectedNotaFiscal = this.SelectedNotaFiscal; + if (selectedNotaFiscal != null) + { + Estipulante estipulante = selectedNotaFiscal.get_Estipulante(); + if (estipulante != null) + { + nullable = new long?(estipulante.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long num = (long)0; + valueOrDefault = nullable1.GetValueOrDefault() <= num & nullable1.HasValue; + } + else + { + valueOrDefault = false; + } + if (valueOrDefault) + { + this.SelectedNotaFiscal.set_Estipulante(null); + } + NotaFiscal notaFiscal = await this._servico.Save(this.SelectedNotaFiscal); + if (this._servico.Sucesso) + { + NotaFiscalViewModel notaFiscalViewModel = this; + string str2 = string.Format("{0} NOTA FISCAL DE ID \"{1}\"", str1, notaFiscal.get_Id()); + long id = notaFiscal.get_Id(); + TipoTela? nullable2 = new TipoTela?(55); + object[] nome = new object[] { notaFiscal.get_Seguradora().get_Nome(), null, null, null, null }; + obj = (!notaFiscal.get_Data().HasValue ? "-" : string.Format("{0:d}", notaFiscal.get_Data())); + nome[1] = obj; + nome[2] = notaFiscal.get_ValorBruto(); + nome[3] = notaFiscal.get_Iss(); + nome[4] = notaFiscal.get_ValorLiquido(); + notaFiscalViewModel.RegistrarAcao(str2, id, nullable2, string.Format("SEGURADORA: {0}\nDATA: {1}\nBRUTO: {2:c}\nISS: {3:c}\nLÍQUIDO: {4:c}", nome)); + if (!this.NotasFiscais.Any((NotaFiscal x) => x.get_Id() == notaFiscal.get_Id())) + { + this.NotasFiscais.Add(notaFiscal); + } + else + { + DomainBase.Copy(this.NotasFiscais.First((NotaFiscal x) => x.get_Id() == notaFiscal.get_Id()), notaFiscal); + } + if (!this.NotasFiscaisFiltrados.Any((NotaFiscal x) => x.get_Id() == notaFiscal.get_Id())) + { + this.NotasFiscaisFiltrados.Add(notaFiscal); + } + else + { + DomainBase.Copy(this.NotasFiscaisFiltrados.First((NotaFiscal x) => x.get_Id() == notaFiscal.get_Id()), notaFiscal); + } + this.NotasFiscaisFiltrados = new ObservableCollection(this.NotasFiscaisFiltrados); + this.WorkOnSelectedNotaFiscal(notaFiscal, false); + base.Alterar(false); + base.ToggleSnackBar("NOTA FISCAL SALVA COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str1 = null; + return keyValuePairs; + } + + public async Task SalvarLote(List notas) + { + foreach (NotaFiscal nota in notas) + { + bool hasValue = nota.get_IdExtrato().HasValue; + if (hasValue) + { + NotaFiscalServico notaFiscalServico = this._servico; + long? idExtrato = nota.get_IdExtrato(); + hasValue = await notaFiscalServico.Cadatrada(idExtrato.Value); + } + if (hasValue) + { + continue; + } + this.SelectedNotaFiscal = nota; + await this.Salvar(); + } + base.ToggleSnackBar("NOTAS FISCAIS SALVAS COM SUCESSO", true); + } + + private async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(55); + await this.SelecionaNotaFiscal(); + base.Loading(false); + } + + public async Task SelecionaNotaFiscal() + { + base.Loading(true); + List notaFiscals = await this._servico.BuscarNotasFiscais(); + NotaFiscalViewModel list = this; + List notaFiscals1 = notaFiscals; + list.NotasFiscais = ( + from x in notaFiscals1 + orderby x.get_Seguradora().get_Nome() + select x).ToList(); + this.NotasFiscaisFiltrados = new ObservableCollection(this.NotasFiscais); + this.SelectedNotaFiscal = this.NotasFiscaisFiltrados.FirstOrDefault(); + base.Loading(false); + } + + private async Task WorkOnSelectedNotaFiscal(NotaFiscal value, bool registrar = true) + { + string str; + long? idExtrato; + NotaFiscal notaFiscal; + long? nullable; + object obj; + NotaFiscalViewModel notaFiscalViewModel = this; + notaFiscal = (value == null || value.get_Id() == 0 ? this.CancelNotaFiscal : (NotaFiscal)value.Clone()); + notaFiscalViewModel.CancelNotaFiscal = notaFiscal; + if (value != null && value.get_Id() != 0 && (this.LastAccessId != value.get_Id() || this.LastAccessTela != 55)) + { + if (registrar) + { + NotaFiscalViewModel notaFiscalViewModel1 = this; + string str1 = string.Format("ACESSOU NOTA FISCAL DE ID \"{0}\"", value.get_Id()); + long id = value.get_Id(); + TipoTela? nullable1 = new TipoTela?(55); + object[] nome = new object[] { value.get_Seguradora().get_Nome(), null, null, null, null }; + obj = (!value.get_Data().HasValue ? "-" : string.Format("{0:d}", value.get_Data())); + nome[1] = obj; + nome[2] = value.get_ValorBruto(); + nome[3] = value.get_Iss(); + nome[4] = value.get_ValorLiquido(); + notaFiscalViewModel1.RegistrarAcao(str1, id, nullable1, string.Format("SEGURADORA: {0}\nDATA: {1}\nBRUTO: {2:c}\nISS: {3:c}\nLÍQUIDO: {4:c}", nome)); + } + this.LastAccessId = value.get_Id(); + this.LastAccessTela = 55; + if (string.IsNullOrEmpty(this.SelectedNotaFiscal.get_Extrato())) + { + NotaFiscal selectedNotaFiscal = this.SelectedNotaFiscal; + idExtrato = this.SelectedNotaFiscal.get_IdExtrato(); + if (!idExtrato.HasValue) + { + str = ""; + } + else + { + str = await this._servicoExtrato.BuscarNumExtrato(this.SelectedNotaFiscal.get_IdExtrato()); + } + selectedNotaFiscal.set_Extrato(str); + selectedNotaFiscal = null; + } + NotaFiscal selectedNotaFiscal1 = this.SelectedNotaFiscal; + if (selectedNotaFiscal1 != null) + { + nullable = new long?(selectedNotaFiscal1.get_Id()); + } + else + { + nullable = null; + } + idExtrato = nullable; + long num = value.get_Id(); + if (idExtrato.GetValueOrDefault() != num | !idExtrato.HasValue) + { + this.SelectedNotaFiscal = this.NotasFiscaisFiltrados.FirstOrDefault((NotaFiscal x) => x.get_Id() == value.get_Id()); + } + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/ProdutoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/ProdutoViewModel.cs new file mode 100644 index 0000000..40f14ae --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/ProdutoViewModel.cs @@ -0,0 +1,303 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class ProdutoViewModel : BaseSegurosViewModel + { + private readonly ProdutoServico _servico; + + private Produto _selectedProduto; + + public Produto CancelProduto; + + private ObservableCollection _produtosFiltrados = new ObservableCollection(); + + private bool _isExpanded; + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public List Produtos + { + get; + set; + } + + public ObservableCollection ProdutosFiltrados + { + get + { + return this._produtosFiltrados; + } + set + { + this._produtosFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("ProdutosFiltrados"); + } + } + + public Produto SelectedProduto + { + get + { + return this._selectedProduto; + } + set + { + long? nullable; + this._selectedProduto = value; + this.WorkOnSelectedProduto(value, true); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedProduto"); + } + } + + public ProdutoViewModel() + { + this._servico = new ProdutoServico(); + base.EnableMenu = true; + this.Seleciona(); + } + + public void CancelarAlteracao() + { + if (this.CancelProduto == null || !this.Produtos.Any((Produto x) => x.get_Id() == this.CancelProduto.get_Id())) + { + this.Incluir(); + } + else + { + DomainBase.Copy(this.Produtos.First((Produto x) => x.get_Id() == this.CancelProduto.get_Id()), this.CancelProduto); + if (this.ProdutosFiltrados.Count <= 0 || !this.ProdutosFiltrados.Any((Produto x) => x.get_Id() == this.CancelProduto.get_Id())) + { + this.ProdutosFiltrados.Add(this.CancelProduto); + } + else + { + DomainBase.Copy(this.ProdutosFiltrados.First((Produto x) => x.get_Id() == this.CancelProduto.get_Id()), this.CancelProduto); + } + this.ProdutosFiltrados = new ObservableCollection(this.ProdutosFiltrados); + this.SelectedProduto = this.ProdutosFiltrados.First((Produto x) => x.get_Id() == this.CancelProduto.get_Id()); + } + base.Alterar(false); + } + + internal async Task> Filtrar(string value) + { + List produtos = await Task.Run>(() => this.FiltrarProduto(value)); + return produtos; + } + + public List FiltrarProduto(string filter) + { + this.ProdutosFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Produtos) : new ObservableCollection( + from x in this.Produtos + where ValidationHelper.RemoveDiacritics(x.get_Nome().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby x.get_Ativo() descending, x.get_Nome() + select x)); + this.SelectedProduto = this.ProdutosFiltrados.FirstOrDefault(); + return this.ProdutosFiltrados.ToList(); + } + + public void Incluir() + { + Produto produto = new Produto(); + produto.set_Ativo(true); + this.SelectedProduto = produto; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + string str1; + List> keyValuePairs1 = this.SelectedProduto.Validate(); + List> keyValuePairs2 = keyValuePairs1; + keyValuePairs2.AddRange(await this.Validate()); + keyValuePairs2 = null; + if (keyValuePairs1.Count <= 0) + { + str = (this.SelectedProduto.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str1 = str; + Produto produto = await this._servico.Save(this.SelectedProduto); + if (this._servico.Sucesso) + { + base.RegistrarAcao(string.Concat(str1, " PRODUTO \"", produto.get_Nome(), "\""), produto.get_Id(), new TipoTela?(10), string.Format("PRODUTO \"{0}\", ID: {1}", produto.get_Nome(), produto.get_Id())); + if (!this.Produtos.Any((Produto x) => x.get_Id() == produto.get_Id())) + { + this.Produtos.Add(produto); + } + else + { + DomainBase.Copy(this.Produtos.First((Produto x) => x.get_Id() == produto.get_Id()), produto); + } + if (!this.ProdutosFiltrados.Any((Produto x) => x.get_Id() == produto.get_Id())) + { + this.ProdutosFiltrados.Add(produto); + } + else + { + DomainBase.Copy(this.ProdutosFiltrados.First((Produto x) => x.get_Id() == produto.get_Id()), produto); + } + this.ProdutosFiltrados = new ObservableCollection(this.ProdutosFiltrados); + List produtos = this.Produtos; + Recursos.Produtos = ( + from x in produtos + orderby x.get_Nome() + select x).ToList(); + this.WorkOnSelectedProduto(produto, false); + base.Alterar(false); + base.ToggleSnackBar("PRODUTO SALVO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + keyValuePairs1 = null; + str1 = null; + return keyValuePairs; + } + + private async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(10); + await this.SelecionaProdutos(); + base.Loading(false); + } + + public void SelecionaProduto(Produto produto) + { + this.SelectedProduto = produto; + } + + private async Task SelecionaProdutos() + { + base.Loading(true); + List produtos = await (new BaseServico()).BuscarProdutosAsync(); + ProdutoViewModel list = this; + List produtos1 = produtos; + IOrderedEnumerable ativo = + from x in produtos1 + orderby x.get_Ativo() descending + select x; + list.Produtos = ativo.ThenBy((Produto x) => x.get_Nome()).ToList(); + this.ProdutosFiltrados = new ObservableCollection(this.Produtos); + this.SelectedProduto = this.ProdutosFiltrados.FirstOrDefault(); + List produtos2 = this.Produtos; + Recursos.Produtos = ( + from x in produtos2 + orderby x.get_Nome() + select x).ToList(); + base.Loading(false); + base.Loading(true); + } + + public async Task>> Validate() + { + List> keyValuePairs; + List> keyValuePairs1; + if (!string.IsNullOrWhiteSpace(this.SelectedProduto.get_Nome())) + { + keyValuePairs1 = new List>(); + bool flag = true; + List produtos = await (new BaseServico()).BuscarProduto(this.SelectedProduto.get_Nome()); + if (produtos.Count > 0) + { + produtos.ForEach((Produto x) => { + if (x.get_Id() == this.SelectedProduto.get_Id()) + { + return; + } + if (x.get_Nome() == this.SelectedProduto.get_Nome()) + { + flag = false; + } + }); + } + if (!flag) + { + keyValuePairs1.Add(new KeyValuePair("Nome", "UM PRODUTO COM O MESMO NOME JÁ EXISTE.")); + } + keyValuePairs = keyValuePairs1; + } + else + { + keyValuePairs = new List>(); + } + keyValuePairs1 = null; + return keyValuePairs; + } + + private void WorkOnSelectedProduto(Produto value, bool registrar = true) + { + long? nullable; + this.CancelProduto = (value == null || value.get_Id() == 0 ? this.CancelProduto : (Produto)value.Clone()); + if (value == null || value.get_Id() == 0 || this.LastAccessId == value.get_Id() && this.LastAccessTela == 10) + { + return; + } + if (registrar) + { + base.RegistrarAcao(string.Concat("ACESSOU PRODUTO \"", value.get_Nome(), "\""), value.get_Id(), new TipoTela?(10), string.Format("ID PRODUTO: {0}", value.get_Id())); + } + this.LastAccessId = value.get_Id(); + this.LastAccessTela = 10; + Produto selectedProduto = this.SelectedProduto; + if (selectedProduto != null) + { + nullable = new long?(selectedProduto.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long id = value.get_Id(); + if (nullable1.GetValueOrDefault() != id | !nullable1.HasValue) + { + this.SelectedProduto = this.ProdutosFiltrados.FirstOrDefault((Produto x) => x.get_Id() == value.get_Id()); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/ProtocoloDocumentosViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/ProtocoloDocumentosViewModel.cs new file mode 100644 index 0000000..027f344 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/ProtocoloDocumentosViewModel.cs @@ -0,0 +1,399 @@ +using Assinador.Infrastructure.Helpers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Ferramentas; +using Gestor.Application.Views.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class ProtocoloDocumentosViewModel : BaseSegurosViewModel + { + private Cliente _selectedCliente = new Cliente(); + + private ObservableCollection _apolicesFiltradas = new ObservableCollection(); + + private ObservableCollection _apolicesAdicionadas = new ObservableCollection(); + + private FiltroStatusDocumento _selectedStatus; + + public ObservableCollection ApolicesAdicionadas + { + get + { + return this._apolicesAdicionadas; + } + set + { + this._apolicesAdicionadas = value; + base.OnPropertyChanged("ApolicesAdicionadas"); + } + } + + public ObservableCollection ApolicesFiltradas + { + get + { + return this._apolicesFiltradas; + } + set + { + this._apolicesFiltradas = value; + base.OnPropertyChanged("ApolicesFiltradas"); + } + } + + public Cliente SelectedCliente + { + get + { + return this._selectedCliente; + } + set + { + this._selectedCliente = value; + if (this.SelectedCliente != null && this.SelectedCliente.get_Id() != 0 && (this.LastAccessId != this.SelectedCliente.get_Id() || this.LastAccessTela != 59)) + { + this.SelecionarDocumentos(); + this.LastAccessId = this.SelectedCliente.get_Id(); + this.LastAccessTela = 59; + } + base.OnPropertyChanged("SelectedCliente"); + } + } + + public FiltroStatusDocumento SelectedStatus + { + get + { + return this._selectedStatus; + } + set + { + this._selectedStatus = value; + this.SelectedCliente = this.SelectedCliente; + this.SelecionarDocumentos(); + base.OnPropertyChanged("SelectedStatus"); + } + } + + public ProtocoloDocumentosViewModel() + { + } + + public async void AdicionarEtiqueta(Documento documento) + { + ObservableCollection apolicesAdicionadas = this.ApolicesAdicionadas; + ProtocoloEtiqueta protocoloEtiquetum = new ProtocoloEtiqueta(); + ProtocoloEtiqueta protocoloEtiquetum1 = protocoloEtiquetum; + Documento documento1 = await (new ApoliceServico()).BuscarApoliceAsync(documento.get_Id(), false, false); + protocoloEtiquetum1.Documento = documento1; + protocoloEtiquetum.Tipo = 1; + apolicesAdicionadas.Add(protocoloEtiquetum); + apolicesAdicionadas = null; + protocoloEtiquetum1 = null; + protocoloEtiquetum = null; + ProtocoloDocumentosViewModel observableCollection = this; + ObservableCollection apolicesAdicionadas1 = this.ApolicesAdicionadas; + observableCollection.ApolicesAdicionadas = new ObservableCollection( + from x in apolicesAdicionadas1 + orderby x.Documento.get_Id() + select x); + } + + public async void AdicionarEtiquetaCliente() + { + if (this.SelectedCliente != null && this.SelectedCliente.get_Id() != 0) + { + bool flag = this.ApolicesAdicionadas.Any((ProtocoloEtiqueta x) => { + if (x.Documento.get_Controle().get_Cliente().get_Id() != this.SelectedCliente.get_Id()) + { + return false; + } + return x.Tipo == 1; + }); + if (flag) + { + flag = !await base.ShowMessage("JÁ EXISTE UMA ETIQUETA ADICIONADA PARA O CLIENTE SELECIONADO, DESEJA ADICIONAR NOVAMENTE?", "SIM", "NÃO", false); + } + if (!flag) + { + ObservableCollection apolicesAdicionadas = this.ApolicesAdicionadas; + ProtocoloEtiqueta protocoloEtiquetum = new ProtocoloEtiqueta(); + Documento documento = new Documento(); + Controle controle = new Controle(); + controle.set_Cliente(this.SelectedCliente); + documento.set_Controle(controle); + protocoloEtiquetum.Documento = documento; + protocoloEtiquetum.Tipo = 1; + apolicesAdicionadas.Add(protocoloEtiquetum); + ProtocoloDocumentosViewModel observableCollection = this; + ObservableCollection apolicesAdicionadas1 = this.ApolicesAdicionadas; + IOrderedEnumerable tipo = + from x in apolicesAdicionadas1 + orderby x.Tipo + select x; + observableCollection.ApolicesAdicionadas = new ObservableCollection(tipo.ThenBy((ProtocoloEtiqueta x) => x.Documento.get_Controle().get_Cliente().get_Id())); + } + } + } + + public async void AdicionarEtiquetaCorretora() + { + ProtocoloDocumentosViewModel protocoloDocumentosViewModel = this; + ClienteEndereco clienteEndereco = new ClienteEndereco(); + clienteEndereco.set_Endereco(Recursos.Empresa.get_Endereco()); + clienteEndereco.set_Bairro(Recursos.Empresa.get_Bairro()); + clienteEndereco.set_Numero(Recursos.Empresa.get_Numero()); + clienteEndereco.set_Complemento(Recursos.Empresa.get_Complemento()); + clienteEndereco.set_Cidade(Recursos.Empresa.get_Cidade()); + clienteEndereco.set_Estado(Recursos.Empresa.get_Estado()); + clienteEndereco.set_Cep(Recursos.Empresa.get_Cep()); + ObservableCollection observableCollection = new ObservableCollection() + { + clienteEndereco + }; + ObservableCollection apolicesAdicionadas = protocoloDocumentosViewModel.ApolicesAdicionadas; + ProtocoloEtiqueta protocoloEtiquetum = new ProtocoloEtiqueta(); + Documento documento = new Documento(); + Controle controle = new Controle(); + Cliente cliente = new Cliente(); + cliente.set_Nome(Recursos.Empresa.get_Nome()); + cliente.set_Id((long)-1); + cliente.set_Enderecos(observableCollection); + controle.set_Cliente(cliente); + documento.set_Controle(controle); + protocoloEtiquetum.Documento = documento; + protocoloEtiquetum.Tipo = 1; + apolicesAdicionadas.Add(protocoloEtiquetum); + ProtocoloDocumentosViewModel observableCollection1 = protocoloDocumentosViewModel; + ObservableCollection apolicesAdicionadas1 = protocoloDocumentosViewModel.ApolicesAdicionadas; + IOrderedEnumerable tipo = + from x in apolicesAdicionadas1 + orderby x.Tipo + select x; + observableCollection1.ApolicesAdicionadas = new ObservableCollection(tipo.ThenBy((ProtocoloEtiqueta x) => x.Documento.get_Controle().get_Cliente().get_Id())); + } + + public async void AdicionarProtocolo(Documento documento) + { + bool flag = this.ApolicesAdicionadas.Any((ProtocoloEtiqueta x) => { + if (x.Documento.get_Id() != documento.get_Id()) + { + return false; + } + return x.Tipo == 0; + }); + if (flag) + { + flag = !await base.ShowMessage("JÁ EXISTE UM PROTOCOLO ADICIONADO PARA O DOCUMENTO SELECIONADO, DESEJA ADICIONAR NOVAMENTE?", "SIM", "NÃO", false); + } + if (!flag) + { + ObservableCollection apolicesAdicionadas = this.ApolicesAdicionadas; + ProtocoloEtiqueta protocoloEtiquetum = new ProtocoloEtiqueta(); + ProtocoloEtiqueta protocoloEtiquetum1 = protocoloEtiquetum; + Documento documento1 = await (new ApoliceServico()).BuscarApoliceAsync(documento.get_Id(), false, false); + protocoloEtiquetum1.Documento = documento1; + protocoloEtiquetum.Tipo = 0; + apolicesAdicionadas.Add(protocoloEtiquetum); + apolicesAdicionadas = null; + protocoloEtiquetum1 = null; + protocoloEtiquetum = null; + ProtocoloDocumentosViewModel observableCollection = this; + ObservableCollection apolicesAdicionadas1 = this.ApolicesAdicionadas; + observableCollection.ApolicesAdicionadas = new ObservableCollection( + from x in apolicesAdicionadas1 + orderby x.Documento.get_Id() + select x); + } + } + + public async void Imprimir(TipoProtocoloEtiqueta tipo) + { + if (this.ApolicesAdicionadas.Count != 0) + { + TipoProtocoloEtiqueta tipoProtocoloEtiquetum = tipo; + if (tipoProtocoloEtiquetum == null) + { + ObservableCollection apolicesAdicionadas = this.ApolicesAdicionadas; + if (!apolicesAdicionadas.All((ProtocoloEtiqueta x) => x.Tipo != 0)) + { + ObservableCollection observableCollection = this.ApolicesAdicionadas; + if (observableCollection.Any((ProtocoloEtiqueta x) => x.Tipo == 0)) + { + ProtocoloDocumentosViewModel protocoloDocumentosViewModel = this; + ObservableCollection apolicesAdicionadas1 = this.ApolicesAdicionadas; + IEnumerable protocoloEtiquetas = + from x in apolicesAdicionadas1 + where x.Tipo == 0 + select x; + List documentos = await protocoloDocumentosViewModel.ShowProtocoloDialog(( + from x in protocoloEtiquetas + select x.Documento).ToList()); + if (documentos != null) + { + bool flag = await base.ShowMessage(string.Concat("DESEJA EMITIR DOIS PROTOCOLOS POR PÁGINA?", Environment.NewLine, "A QUANTIDADE DE INFORMÃÇÕES PODE IMPEDIR QUE ESSA FUNÇÃO FUNCIONE CORRETAMENTE"), "SIM", "NÃO", false); + this.PrepararProtocolo(documentos, flag); + documentos = null; + } + else + { + return; + } + } + } + else + { + await base.ShowMessage(string.Concat("NECESSÁRIO ADICIONAR DOCUMENTOS PARA EMISSÃO DE ", Functions.GetDescription(tipo)), "OK", "", false); + return; + } + } + else if (tipoProtocoloEtiquetum == 1) + { + ObservableCollection observableCollection1 = this.ApolicesAdicionadas; + if (!observableCollection1.All((ProtocoloEtiqueta x) => x.Tipo != 1)) + { + ObservableCollection apolicesAdicionadas2 = this.ApolicesAdicionadas; + if (apolicesAdicionadas2.Any((ProtocoloEtiqueta x) => { + if (x.Tipo != 1) + { + return false; + } + return x.Documento.get_Id() == (long)0; + })) + { + ObservableCollection observableCollection2 = this.ApolicesAdicionadas; + if (observableCollection2.Any((ProtocoloEtiqueta x) => { + if (x.Tipo != 1) + { + return false; + } + return x.Documento.get_Id() != (long)0; + })) + { + await base.ShowMessage("COMO EXISTEM ETIQUETAS DE CLIENTES E DOCUMENTOS,\nPRIMEIRO CONFIGURE AS DE SOMENTE CLIENTE.\nDEPOIS DE GERAR AS ETIQUETAS DE CLIENTE, CONFIGURAR AS DE DOCUMENTOS", "OK", "", false); + } + ObservableCollection apolicesAdicionadas3 = this.ApolicesAdicionadas; + IEnumerable protocoloEtiquetas1 = apolicesAdicionadas3.Where((ProtocoloEtiqueta x) => { + if (x.Tipo != 1) + { + return false; + } + return x.Documento.get_Id() == (long)0; + }); + (new HosterWindow(new EtiquetaView(( + from x in protocoloEtiquetas1 + select x.Documento).ToList(), true), "ETIQUETAS", new double?((double)900), new double?((double)600), false)).Show(); + } + ObservableCollection observableCollection3 = this.ApolicesAdicionadas; + if (observableCollection3.Any((ProtocoloEtiqueta x) => { + if (x.Tipo != 1) + { + return false; + } + return x.Documento.get_Id() != (long)0; + })) + { + ObservableCollection apolicesAdicionadas4 = this.ApolicesAdicionadas; + IEnumerable protocoloEtiquetas2 = apolicesAdicionadas4.Where((ProtocoloEtiqueta x) => { + if (x.Tipo != 1) + { + return false; + } + return x.Documento.get_Id() != (long)0; + }); + (new HosterWindow(new EtiquetaView(( + from x in protocoloEtiquetas2 + select x.Documento).ToList(), false), "ETIQUETAS", new double?((double)900), new double?((double)600), false)).Show(); + } + } + else + { + await base.ShowMessage(string.Concat("NECESSÁRIO ADICIONAR DOCUMENTOS PARA EMISSÃO DE ", Functions.GetDescription(tipo)), "OK", "", false); + return; + } + } + } + else + { + await base.ShowMessage(string.Concat("NECESSÁRIO ADICIONAR DOCUMENTOS PARA EMISSÃO DE ", Functions.GetDescription(tipo)), "OK", "", false); + } + } + + public async void PrepararProtocolo(List documentos, bool doisPorPagina) + { + if (await base.ShowMessage("DESEJA EMITIR O CHECKLIST?", "SIM", "NÃO", false)) + { + await base.EmitirCheckList(documentos); + } + if (documentos != null) + { + List documentos1 = documentos; + List> list = ( + from x in documentos1 + select new Tuple(x.get_Id(), x.get_ObsProtocolo())).ToList>(); + await base.EmitirProtocolos(list, doisPorPagina, documentos); + } + } + + public void Remover(ProtocoloEtiqueta documento) + { + this.ApolicesAdicionadas.Remove(documento); + this.SelecionarDocumentos(); + } + + public async void SelecionarDocumentos() + { + long? nullable; + object obj; + object nome; + long num; + base.Loading(true); + if (this.SelectedCliente != null) + { + this.ApolicesFiltradas = await (new ApoliceServico()).BuscarApolicesComissao(this.SelectedCliente.get_Id(), this.SelectedStatus); + ProtocoloDocumentosViewModel protocoloDocumentosViewModel = this; + obj = (this.SelectedStatus == 4 ? "TODOS OS DOCUMENTOS" : string.Concat("OS ", Functions.GetDescription(this.SelectedStatus))); + Cliente selectedCliente = this.SelectedCliente; + if (selectedCliente != null) + { + nome = selectedCliente.get_Nome(); + } + else + { + nome = null; + } + Cliente cliente = this.SelectedCliente; + if (cliente != null) + { + nullable = new long?(cliente.get_Id()); + } + else + { + nullable = null; + } + string str = string.Format("CONSULTOU {0} DO CLIENTE {1} ({2})", obj, nome, nullable); + num = (this.SelectedCliente == null ? (long)0 : this.SelectedCliente.get_Id()); + protocoloDocumentosViewModel.RegistrarAcao(str, num, new TipoTela?(59), null); + base.Loading(false); + } + else + { + base.Loading(false); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/ProtocoloEtiqueta.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/ProtocoloEtiqueta.cs new file mode 100644 index 0000000..7e46a89 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/ProtocoloEtiqueta.cs @@ -0,0 +1,26 @@ +using Gestor.Model.Common; +using Gestor.Model.Domain.Seguros; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class ProtocoloEtiqueta + { + public Gestor.Model.Domain.Seguros.Documento Documento + { + get; + set; + } + + public TipoProtocoloEtiqueta Tipo + { + get; + set; + } + + public ProtocoloEtiqueta() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/QualificacaoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/QualificacaoViewModel.cs new file mode 100644 index 0000000..c259f93 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/QualificacaoViewModel.cs @@ -0,0 +1,122 @@ +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class QualificacaoViewModel : BaseSegurosViewModel + { + private readonly QualificacaoServico _servico; + + private Qualificacao _selectedQualificacao; + + public Qualificacao CancelQualificacao; + + public Qualificacao SelectedQualificacao + { + get + { + return this._selectedQualificacao; + } + set + { + if (value == null || value.get_Id() == 0) + { + Qualificacao qualificacao = new Qualificacao(); + qualificacao.set_Liquido1(decimal.Zero); + qualificacao.set_Liquido2(new decimal(1000)); + qualificacao.set_Liquido3(new decimal(5000)); + qualificacao.set_Comissao1(new decimal(10)); + qualificacao.set_Comissao2(new decimal(15)); + qualificacao.set_Comissao3(new decimal(20)); + qualificacao.set_Resultado1(new decimal(100)); + qualificacao.set_Resultado2(new decimal(200)); + qualificacao.set_Resultado3(new decimal(300)); + qualificacao.set_Id((long)1); + value = qualificacao; + } + this._selectedQualificacao = value; + base.VerificarEnables(new long?(value.get_Id())); + base.OnPropertyChanged("SelectedQualificacao"); + } + } + + public QualificacaoViewModel() + { + this._servico = new QualificacaoServico(); + this.Seleciona(); + } + + public void CancelarAlteracao() + { + base.Loading(true); + if (this.SelectedQualificacao.get_Id() != 0) + { + this.SelectedQualificacao = this.CancelQualificacao; + } + else + { + this.SelectedQualificacao = null; + base.Alterar(false); + base.EnableMenu = false; + base.Loading(false); + } + base.Alterar(false); + base.Loading(false); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + if (await this._servico.BuscarQualificacaoAsync().get_Id() == 0) + { + this.SelectedQualificacao.set_Id((long)0); + } + List> keyValuePairs1 = this.SelectedQualificacao.Validate(); + if (keyValuePairs1.Count <= 0) + { + this.SelectedQualificacao = await this._servico.Save(this.SelectedQualificacao); + if (this._servico.Sucesso) + { + base.RegistrarAcao("ALTEROU QUALIFICAÇÃO", (long)0, new TipoTela?(48), null); + base.Alterar(false); + base.ToggleSnackBar("QUALIFICACAO SALVA COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + return keyValuePairs; + } + + private async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(48); + await this.SelecionaQualificacao(); + base.Loading(false); + } + + private async Task SelecionaQualificacao() + { + base.Loading(true); + this.SelectedQualificacao = await this._servico.BuscarQualificacaoAsync(); + base.RegistrarAcao("ACESSOU QUALIFICAÇÃO", (long)0, new TipoTela?(48), null); + base.Loading(false); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/RamoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/RamoViewModel.cs new file mode 100644 index 0000000..09ab1ea --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/RamoViewModel.cs @@ -0,0 +1,332 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class RamoViewModel : BaseSegurosViewModel + { + private readonly RamoServico _servico; + + private Ramo _selectedRamo = new Ramo(); + + private decimal _iof; + + private ObservableCollection _ramosFiltrados = new ObservableCollection(); + + private bool _isExpanded; + + private List _coberturas = new List(); + + private ObservableCollection _coberturasFiltradas = new ObservableCollection(); + + public Ramo CancelRamo; + + public List Coberturas + { + get + { + return this._coberturas; + } + set + { + this._coberturas = value; + base.OnPropertyChanged("Coberturas"); + } + } + + public ObservableCollection CoberturasFiltradas + { + get + { + return this._coberturasFiltradas; + } + set + { + this._coberturasFiltradas = value; + base.OnPropertyChanged("CoberturasFiltradas"); + } + } + + public decimal Iof + { + get + { + return this._iof; + } + set + { + this._iof = value; + base.OnPropertyChanged("Iof"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public List Ramos + { + get; + set; + } + + public ObservableCollection RamosFiltrados + { + get + { + return this._ramosFiltrados; + } + set + { + this._ramosFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("RamosFiltrados"); + } + } + + public Ramo SelectedRamo + { + get + { + return this._selectedRamo; + } + set + { + long? nullable; + this._selectedRamo = value; + this.WorkOnSelectedRamo(value, true); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedRamo"); + } + } + + public RamoViewModel() + { + this._servico = new RamoServico(); + base.EnableMenu = true; + this.Seleciona(); + } + + public void CancelarAlteracao() + { + if (this.CancelRamo != null && this.Ramos.Any((Ramo x) => x.get_Id() == this.CancelRamo.get_Id())) + { + DomainBase.Copy(this.Ramos.First((Ramo x) => x.get_Id() == this.CancelRamo.get_Id()), this.CancelRamo); + if (this.RamosFiltrados.Count <= 0 || !this.RamosFiltrados.Any((Ramo x) => x.get_Id() == this.CancelRamo.get_Id())) + { + this.RamosFiltrados.Add(this.CancelRamo); + } + else + { + DomainBase.Copy(this.RamosFiltrados.First((Ramo x) => x.get_Id() == this.CancelRamo.get_Id()), this.CancelRamo); + } + this.RamosFiltrados = new ObservableCollection(this.RamosFiltrados); + this.SelectedRamo = this.RamosFiltrados.First((Ramo x) => x.get_Id() == this.CancelRamo.get_Id()); + } + base.Alterar(false); + } + + internal async Task> Filtrar(string value) + { + List ramos = await Task.Run>(() => this.FiltrarRamo(value)); + return ramos; + } + + internal async Task> FiltrarCobertura(string value) + { + List coberturaPadraos = await Task.Run>(() => this.FiltrarCoberturaRamo(value)); + return coberturaPadraos; + } + + public List FiltrarCoberturaRamo(string filter) + { + this.CoberturasFiltradas = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Coberturas) : new ObservableCollection( + from x in this.Coberturas + where ValidationHelper.RemoveDiacritics(x.get_Descricao().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + select x)); + return this.CoberturasFiltradas.ToList(); + } + + public List FiltrarRamo(string filter) + { + this.RamosFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Ramos) : new ObservableCollection( + from x in this.Ramos + where ValidationHelper.RemoveDiacritics(x.get_Nome().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby x.get_Ativo() descending, x.get_Nome() + select x)); + return this.RamosFiltrados.ToList(); + } + + public async void Incluir(Ramo ramo) + { + ramo.set_Ativo(true); + await this._servico.Insert(ramo); + if (this._servico.Sucesso) + { + await this.SelecionaRamos(ramo); + } + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + string str1; + this.SelectedRamo.set_Iof(this.Iof); + List> keyValuePairs1 = this.SelectedRamo.Validate(); + if (keyValuePairs1.Count <= 0) + { + Ramo selectedRamo = this.SelectedRamo; + selectedRamo.set_Iof(selectedRamo.get_Iof() * new decimal(100)); + str = (this.SelectedRamo.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str1 = str; + Ramo ramo = await this._servico.Save(this.SelectedRamo, this.Coberturas); + Ramo ramo1 = ramo; + if (this._servico.Sucesso) + { + base.RegistrarAcao(string.Concat(str1, " RAMO \"", ramo1.get_Nome(), "\""), ramo1.get_Id(), new TipoTela?(12), string.Format("RAMO \"{0}\", ID: {1}", ramo1.get_Nome(), ramo1.get_Id())); + if (!this.Ramos.Any((Ramo x) => x.get_Id() == ramo1.get_Id())) + { + this.Ramos.Add(ramo1); + } + else + { + DomainBase.Copy(this.Ramos.First((Ramo x) => x.get_Id() == ramo1.get_Id()), ramo1); + } + if (!this.RamosFiltrados.Any((Ramo x) => x.get_Id() == ramo1.get_Id())) + { + this.RamosFiltrados.Add(ramo1); + } + else + { + DomainBase.Copy(this.RamosFiltrados.First((Ramo x) => x.get_Id() == ramo1.get_Id()), ramo1); + } + this.RamosFiltrados = new ObservableCollection(this.RamosFiltrados); + Recursos.Ramos = this.Ramos; + await RamoViewModel.SelecionaCoberturas(); + this.WorkOnSelectedRamo(ramo1, false); + base.Alterar(false); + base.ToggleSnackBar("RAMO SALVO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str1 = null; + return keyValuePairs; + } + + public async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(12); + await this.SelecionaRamos(null); + base.Loading(false); + } + + private static async Task SelecionaCoberturas() + { + Recursos.Coberturas = await (new BaseServico()).BuscaCoberturas(); + } + + public void SelecionaRamo(Ramo ramo) + { + this.SelectedRamo = ramo; + } + + private async Task SelecionaRamos(Ramo ramo = null) + { + Ramo ramo1; + base.Loading(true); + await RamoViewModel.SelecionaCoberturas(); + List ramos = await (new BaseServico()).BuscarRamosAsync(); + RamoViewModel list = this; + List ramos1 = ramos; + IOrderedEnumerable ativo = + from x in ramos1 + orderby x.get_Ativo() descending + select x; + list.Ramos = ativo.ThenBy((Ramo x) => x.get_Nome()).ToList(); + this.RamosFiltrados = new ObservableCollection(this.Ramos); + RamoViewModel ramoViewModel = this; + ramo1 = (ramo == null ? this.RamosFiltrados.First() : this.RamosFiltrados.FirstOrDefault((Ramo x) => x.get_Id() == ramo.get_Id())); + ramoViewModel.SelectedRamo = ramo1; + Recursos.Ramos = ramos; + base.Loading(false); + } + + private void WorkOnSelectedRamo(Ramo value, bool registrar = true) + { + long? nullable; + this.CancelRamo = (value == null || value.get_Id() == 0 ? this.CancelRamo : (Ramo)value.Clone()); + if (value == null || value.get_Id() == 0 || this.LastAccessId == value.get_Id() && this.LastAccessTela == 12) + { + return; + } + this.Coberturas = ( + from x in Recursos.Coberturas + where x.get_IdRamo() == value.get_Id() + orderby x.get_Padrao() descending, x.get_Descricao() + select x).ToList(); + this.CoberturasFiltradas = new ObservableCollection(this.Coberturas); + this.Iof = value.get_Iof() * new decimal(1, 0, 0, false, 2); + if (registrar) + { + base.RegistrarAcao(string.Concat("ACESSOU RAMO \"", value.get_Nome(), "\""), value.get_Id(), new TipoTela?(12), string.Format("ID RAMO: {0}", value.get_Id())); + } + this.LastAccessId = value.get_Id(); + this.LastAccessTela = 12; + Ramo selectedRamo = this.SelectedRamo; + if (selectedRamo != null) + { + nullable = new long?(selectedRamo.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long id = value.get_Id(); + if (nullable1.GetValueOrDefault() != id | !nullable1.HasValue) + { + this.SelectedRamo = this.RamosFiltrados.FirstOrDefault((Ramo x) => x.get_Id() == value.get_Id()); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/ReciboViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/ReciboViewModel.cs new file mode 100644 index 0000000..e00947c --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/ReciboViewModel.cs @@ -0,0 +1,769 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Drawing; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class ReciboViewModel : BaseSegurosViewModel + { + private readonly ReciboServico _servico; + + public Recibo CancelRecibo; + + private Recibo _selectedRecibo = new Recibo(); + + private DateTime? _horaRecibo; + + private ObservableCollection _recibosFiltrados = new ObservableCollection(); + + private bool _isExpanded; + + private Cliente _pagante; + + private Cliente _recebedor; + + public DateTime? HoraRecibo + { + get + { + return this._horaRecibo; + } + set + { + DateTime? nullable; + this._horaRecibo = value; + if (!value.HasValue) + { + return; + } + Recibo selectedRecibo = this.SelectedRecibo; + DateTime? dataRecibo = this.SelectedRecibo.get_DataRecibo(); + if (dataRecibo.HasValue) + { + dataRecibo = this.SelectedRecibo.get_DataRecibo(); + nullable = new DateTime?(DateTime.Parse(string.Format("{0:d} {1:T}", dataRecibo.Value, value))); + } + else + { + dataRecibo = null; + nullable = dataRecibo; + } + selectedRecibo.set_DataRecibo(nullable); + base.OnPropertyChanged("HoraRecibo"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public Cliente Pagante + { + get + { + return this._pagante; + } + set + { + this._pagante = value; + this.WorkOnSelectedPagante(value); + base.OnPropertyChanged("Pagante"); + } + } + + public Cliente Recebedor + { + get + { + return this._recebedor; + } + set + { + this._recebedor = value; + this.WorkOnSelectedRecebedor(value); + base.OnPropertyChanged("Recebedor"); + } + } + + public List Recibos + { + get; + set; + } + + public ObservableCollection RecibosFiltrados + { + get + { + return this._recibosFiltrados; + } + set + { + this._recibosFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("RecibosFiltrados"); + } + } + + public Recibo SelectedRecibo + { + get + { + return this._selectedRecibo; + } + set + { + long? nullable; + this._selectedRecibo = value; + this.WorkOnSelectedRecibo(value, true); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + if (!value.get_DataRecibo().HasValue) + { + value.set_DataRecibo(new DateTime?(DateTime.Now)); + } + if (value != null) + { + this.HoraRecibo = value.get_DataRecibo(); + } + base.OnPropertyChanged("SelectedRecibo"); + } + } + + public ReciboViewModel() + { + this._servico = new ReciboServico(); + base.EnableMenu = true; + this.Seleciona(); + } + + public void CancelarAlteracao() + { + if (this.CancelRecibo == null || !this.Recibos.Any((Recibo x) => x.get_Id() == this.CancelRecibo.get_Id())) + { + this.Incluir(); + } + else + { + DomainBase.Copy(this.Recibos.First((Recibo x) => x.get_Id() == this.CancelRecibo.get_Id()), this.CancelRecibo); + if (this.RecibosFiltrados.Count <= 0 || !this.RecibosFiltrados.Any((Recibo x) => x.get_Id() == this.CancelRecibo.get_Id())) + { + this.RecibosFiltrados.Add(this.CancelRecibo); + } + else + { + DomainBase.Copy(this.RecibosFiltrados.First((Recibo x) => x.get_Id() == this.CancelRecibo.get_Id()), this.CancelRecibo); + } + this.RecibosFiltrados = new ObservableCollection(this.RecibosFiltrados); + this.SelectedRecibo = this.RecibosFiltrados.First((Recibo x) => x.get_Id() == this.CancelRecibo.get_Id()); + } + base.Alterar(false); + } + + public async void Excluir() + { + string description; + object obj; + if (this.SelectedRecibo != null && this.SelectedRecibo.get_Id() != 0) + { + if (await base.ShowMessage("DESEJA REALMENTE EXCLUIR O RECIBO PERMANENTEMENTE?", "SIM", "NÃO", false)) + { + base.Loading(true); + if (await this._servico.Delete(this.SelectedRecibo)) + { + ReciboViewModel reciboViewModel = this; + string str = string.Format("EXCLUIU RECIBO DE NÚMERO \"{0}\"", this.SelectedRecibo.get_Id()); + long id = this.SelectedRecibo.get_Id(); + TipoTela? nullable = new TipoTela?(42); + object[] valor = new object[9]; + if (this.SelectedRecibo.get_Tipo().HasValue) + { + TipoRecibo? tipo = this.SelectedRecibo.get_Tipo(); + description = ValidationHelper.GetDescription(tipo.Value); + if (description == null) + { + description = ""; + } + } + else + { + description = "-"; + } + valor[0] = description; + TipoPagamento? pagamento = this.SelectedRecibo.get_Pagamento(); + if (pagamento.HasValue) + { + obj = ValidationHelper.GetDescription(pagamento.GetValueOrDefault()); + } + else + { + obj = null; + } + valor[1] = obj; + valor[2] = this.SelectedRecibo.get_Valor(); + valor[3] = this.SelectedRecibo.get_DataRecibo(); + valor[4] = this.SelectedRecibo.get_Pagante(); + valor[5] = this.SelectedRecibo.get_DocumentoPagante(); + valor[6] = this.SelectedRecibo.get_Recebedor(); + valor[7] = this.SelectedRecibo.get_DocumentoRecebedor(); + valor[8] = this.SelectedRecibo.get_Referente(); + reciboViewModel.RegistrarAcao(str, id, nullable, string.Format("TIPO: {0}\nPAGAMENTO: {1}\nVALOR: {2:c}\nDATA RECIBO: {3:G}\nPAGANTE: {4}, {5}\nRECEBEDOR: {6}, {7}\nREFERENTE: \"{8}\"", valor)); + await this.SelecionaRecibo(); + base.Loading(false); + base.ToggleSnackBar("RECIBO EXCLUÍDO COM SUCESSO", true); + } + else + { + base.Loading(false); + } + } + } + } + + internal async Task> Filtrar(string value) + { + List recibos = await Task.Run>(() => this.FiltrarRecibo(value)); + return recibos; + } + + public List FiltrarRecibo(string filter) + { + this.RecibosFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Recibos) : new ObservableCollection(this.Recibos.Where((Recibo x) => { + if (ValidationHelper.RemoveDiacritics(x.get_Pagante().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter))) + { + return true; + } + return ValidationHelper.RemoveDiacritics(x.get_Recebedor()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)); + }))); + return this.RecibosFiltrados.ToList(); + } + + private static string GetImage(byte[] bytes, string extensao) + { + string str; + try + { + Image image = Image.FromStream(new MemoryStream(bytes)); + string str1 = (extensao.ToUpper().Contains("JPG") ? string.Concat("data:image/jpeg;base64,", Convert.ToBase64String(bytes, Base64FormattingOptions.None)) : string.Concat("data:image/png;base64,", Convert.ToBase64String(bytes, Base64FormattingOptions.None))); + string[] strArrays = new string[] { ""; + str = string.Concat(strArrays); + } + catch (Exception exception) + { + str = ""; + } + return str; + } + + public void Incluir() + { + this.SelectedRecibo = new Recibo(); + base.Alterar(true); + } + + private bool IsImage(string extensao) + { + if (extensao == null) + { + return false; + } + if (extensao.ToLower().Contains("jpg")) + { + return true; + } + if (extensao.ToLower().Contains("jpeg")) + { + return true; + } + if (extensao.ToLower().Contains("png")) + { + return true; + } + return false; + } + + public async void Print() + { + bool referente; + byte[] arquivo; + string str; + string str1; + string str2; + string upper; + string str3; + string str4; + string upper1; + string description; + object obj; + string extensao; + string extensao1; + long? nullable; + string bd; + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital; + string image; + string str5; + Recibo selectedRecibo = this.SelectedRecibo; + if (selectedRecibo != null) + { + referente = selectedRecibo.get_Referente(); + } + else + { + referente = false; + } + if (referente && this.SelectedRecibo.get_Recebedor() != null) + { + arquivoDigital = null; + List indiceArquivoDigitals = await this.ArquivoDigitalServico.BuscarPorTipo(13, Recursos.Empresa.get_Id()); + if (indiceArquivoDigitals != null) + { + List indiceArquivoDigitals1 = indiceArquivoDigitals; + if (indiceArquivoDigitals1.Any((IndiceArquivoDigital x) => x.get_Descricao() == "LOGO")) + { + List indiceArquivoDigitals2 = indiceArquivoDigitals; + IndiceArquivoDigital indiceArquivoDigital = indiceArquivoDigitals2.FirstOrDefault((IndiceArquivoDigital x) => x.get_Descricao() == "LOGO"); + if (indiceArquivoDigital != null) + { + nullable = new long?(indiceArquivoDigital.get_IdArquivoDigital()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + List indiceArquivoDigitals3 = indiceArquivoDigitals; + IndiceArquivoDigital indiceArquivoDigital1 = indiceArquivoDigitals3.FirstOrDefault((IndiceArquivoDigital x) => x.get_Descricao() == "LOGO"); + if (indiceArquivoDigital1 != null) + { + bd = indiceArquivoDigital1.get_Bd(); + } + else + { + bd = null; + } + string str6 = bd; + if (nullable1.HasValue) + { + arquivoDigital = await this.ArquivoDigitalServico.BuscarPorId(nullable1.Value, str6); + } + } + } + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital1 = arquivoDigital; + if (arquivoDigital1 != null) + { + arquivo = arquivoDigital1.get_Arquivo(); + } + else + { + arquivo = null; + } + byte[] numArray = arquivo; + image = ""; + if (numArray != null && numArray.Length != 0) + { + ReciboViewModel reciboViewModel = this; + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital2 = arquivoDigital; + if (arquivoDigital2 != null) + { + extensao = arquivoDigital2.get_Extensao(); + } + else + { + extensao = null; + } + if (reciboViewModel.IsImage(extensao)) + { + byte[] numArray1 = numArray; + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital3 = arquivoDigital; + if (arquivoDigital3 != null) + { + extensao1 = arquivoDigital3.get_Extensao(); + } + else + { + extensao1 = null; + } + image = ReciboViewModel.GetImage(numArray1, extensao1); + } + } + string longDatePattern = (new CultureInfo("pt-PT", false)).DateTimeFormat.LongDatePattern; + DateTime? dataRecibo = this.SelectedRecibo.get_DataRecibo(); + if (dataRecibo.HasValue) + { + DateTime valueOrDefault = dataRecibo.GetValueOrDefault(); + str = valueOrDefault.ToString(longDatePattern, new CultureInfo("pt-PT")); + } + else + { + str = null; + } + str5 = str; + bool flag = await base.ShowMessage("DESEJA IMPRIMIR DUAS VIAS DO RECIBO?", "SIM", "NÃO", false); + int num = (!flag ? 1 : 2); + flag = !string.IsNullOrEmpty(image); + if (flag) + { + flag = await base.ShowMessage("DESEJA IMPRIMIR O LOGO DA CORRETORA NO RECIBO?\nPARA ADICIONAR UM LOGO, É NECESSÁRIO COLOCÁ-LO NO ARQUIVO\nDIGITAL NA TELA DE EMPRESA E FILIAIS COM DESCRIÇÃO \"LOGO\"", "SIM", "NÃO", false); + } + bool flag1 = flag; + string str7 = "RECIBO"; + for (int i = 0; i < num; i++) + { + if (!flag1) + { + str7 = string.Concat(str7, "
"); + } + else + { + str7 = string.Concat(str7, "
", image, "
"); + str7 = string.Concat(str7, "
"); + } + str7 = string.Concat(str7, string.Format("
N° {0}

", this.SelectedRecibo.get_Id())); + str7 = string.Concat(str7, "R E C I B O

"); + if (this.SelectedRecibo.get_Tipo().GetValueOrDefault() != 1) + { + str1 = (this.SelectedRecibo.get_DocumentoPagante() == null || this.SelectedRecibo.get_DocumentoPagante().Clear().Length < 12 ? "EU" : "A"); + string str8 = str1; + str2 = (this.SelectedRecibo.get_DocumentoPagante() == null || this.SelectedRecibo.get_DocumentoPagante().Clear().Length < 12 ? "CPF" : "CNPJ"); + string str9 = str2; + string str10 = (str8 == "EU" ? "O" : "A"); + string str11 = (str8 == "EU" ? "PAGUEI" : "PAGOU"); + object[] pagante = new object[] { str8, this.SelectedRecibo.get_Pagante(), str10, str9, this.SelectedRecibo.get_DocumentoPagante(), str10, str11, this.SelectedRecibo.get_DataRecibo(), this.SelectedRecibo.get_Valor(), ValidationHelper.GetDescription(this.SelectedRecibo.get_Pagamento()), this.SelectedRecibo.get_Recebedor(), this.SelectedRecibo.get_DocumentoRecebedor(), this.SelectedRecibo.get_Referente().ToUpper() }; + str7 = string.Concat(str7, string.Format("PELO PRESENTE, {0}, {1}, INSCRIT{2} NO {3} SOB Nº {4}, DECLAR{5} QUE {6}, NA DATA DE HOJE, {7:dd/MM/yyyy HH:mm}, O VALOR DE R$ {8:0.00} POR MEIO DE {9}, PARA {10}, INSCRITO NO CPF/CNPJ SOB Nº {11}, REFERENTE À(AO) {12}. DANDO-LHE POR ESTE RECIBO A DEVIDA QUITAÇÃO.
", pagante)); + string[] cidade = new string[] { str7, "
", Recursos.Empresa.get_Cidade(), ", ", null, null }; + string str12 = str5; + if (str12 != null) + { + upper = str12.ToUpper(); + } + else + { + upper = null; + } + cidade[4] = upper; + cidade[5] = ".

"; + str7 = string.Concat(cidade); + string[] recebedor = new string[] { str7, "_________________________________
ASSINATURA ", this.SelectedRecibo.get_Recebedor(), "
", this.SelectedRecibo.get_DocumentoRecebedor() }; + str7 = string.Concat(recebedor); + } + else + { + str3 = (this.SelectedRecibo.get_DocumentoRecebedor() == null || this.SelectedRecibo.get_DocumentoRecebedor().Clear().Length < 12 ? "EU" : "A"); + string str13 = str3; + str4 = (this.SelectedRecibo.get_DocumentoRecebedor() == null || this.SelectedRecibo.get_DocumentoRecebedor().Clear().Length < 12 ? "CPF" : "CNPJ"); + string str14 = str4; + string str15 = (str13 == "EU" ? "O" : "A"); + string str16 = (str13 == "EU" ? "RECEBI" : "RECEBEU"); + object[] objArray = new object[] { str13, this.SelectedRecibo.get_Recebedor(), str15, str14, this.SelectedRecibo.get_DocumentoRecebedor(), str15, str16, this.SelectedRecibo.get_DataRecibo(), this.SelectedRecibo.get_Valor(), ValidationHelper.GetDescription(this.SelectedRecibo.get_Pagamento()), this.SelectedRecibo.get_Pagante(), this.SelectedRecibo.get_DocumentoPagante(), this.SelectedRecibo.get_Referente().ToUpper() }; + str7 = string.Concat(str7, string.Format("PELO PRESENTE, {0}, {1}, INSCRIT{2} NO {3} SOB Nº {4}, DECLAR{5} QUE {6}, NA DATA DE HOJE, {7:dd/MM/yyyy HH:mm}, O VALOR DE R$ {8:0.00} POR MEIO DE {9}, DE {10}, INSCRITO NO CPF/CNPJ SOB Nº {11}, REFERENTE À(AO) {12}. DANDO-LHE POR ESTE RECIBO A DEVIDA QUITAÇÃO.
", objArray)); + string[] strArrays = new string[] { str7, "", Recursos.Empresa.get_Cidade(), ", ", null, null }; + string str17 = str5; + if (str17 != null) + { + upper1 = str17.ToUpper(); + } + else + { + upper1 = null; + } + strArrays[4] = upper1; + strArrays[5] = ".

"; + str7 = string.Concat(strArrays); + string[] recebedor1 = new string[] { str7, "_________________________________
ASSINATURA ", this.SelectedRecibo.get_Recebedor(), "
", this.SelectedRecibo.get_DocumentoRecebedor() }; + str7 = string.Concat(recebedor1); + } + str7 = string.Concat(str7, "
"); + } + str7 = string.Concat(str7, " "); + string tempPath = Path.GetTempPath(); + string str18 = string.Format("{0}_{1:ddMMyyyyhhmmss}.html", tempPath, Funcoes.GetNetworkTime()); + StreamWriter streamWriter = new StreamWriter(str18, true, Encoding.UTF8); + streamWriter.Write(str7); + streamWriter.Close(); + Process.Start(str18); + ReciboViewModel reciboViewModel1 = this; + string str19 = string.Format("IMPRIMIU O RECIBO DE NÚMERO \"{0}\"", this.SelectedRecibo.get_Id()); + long id = this.SelectedRecibo.get_Id(); + TipoTela? nullable2 = new TipoTela?(42); + object[] valor = new object[9]; + if (this.SelectedRecibo.get_Tipo().HasValue) + { + TipoRecibo? tipo = this.SelectedRecibo.get_Tipo(); + description = ValidationHelper.GetDescription(tipo.Value); + if (description == null) + { + description = ""; + } + } + else + { + description = "-"; + } + valor[0] = description; + TipoPagamento? pagamento = this.SelectedRecibo.get_Pagamento(); + if (pagamento.HasValue) + { + obj = ValidationHelper.GetDescription(pagamento.GetValueOrDefault()); + } + else + { + obj = null; + } + valor[1] = obj; + valor[2] = this.SelectedRecibo.get_Valor(); + valor[3] = this.SelectedRecibo.get_DataRecibo(); + valor[4] = this.SelectedRecibo.get_Pagante(); + valor[5] = this.SelectedRecibo.get_DocumentoPagante(); + valor[6] = this.SelectedRecibo.get_Recebedor(); + valor[7] = this.SelectedRecibo.get_DocumentoRecebedor(); + valor[8] = this.SelectedRecibo.get_Referente(); + reciboViewModel1.RegistrarAcao(str19, id, nullable2, string.Format("TIPO: {0}\nPAGAMENTO: {1}\nVALOR: {2:c}\nDATA RECIBO: {3:G}\nPAGANTE: {4}, {5}\nRECEBEDOR: {6}, {7}\nREFERENTE: \"{8}\"", valor)); + } + arquivoDigital = null; + image = null; + str5 = null; + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + string description; + object obj; + string str1; + List> keyValuePairs1 = this.SelectedRecibo.Validate(); + if (keyValuePairs1.Count <= 0) + { + str = (this.SelectedRecibo.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str1 = str; + Recibo recibo = await this._servico.Save(this.SelectedRecibo); + if (this._servico.Sucesso) + { + ReciboViewModel reciboViewModel = this; + string str2 = string.Format("{0} RECIBO DE NÚMERO \"{1}\"", str1, recibo.get_Id()); + long id = recibo.get_Id(); + TipoTela? nullable = new TipoTela?(42); + object[] valor = new object[9]; + if (recibo.get_Tipo().HasValue) + { + TipoRecibo? tipo = recibo.get_Tipo(); + description = ValidationHelper.GetDescription(tipo.Value); + if (description == null) + { + description = ""; + } + } + else + { + description = "-"; + } + valor[0] = description; + TipoPagamento? pagamento = recibo.get_Pagamento(); + if (pagamento.HasValue) + { + obj = ValidationHelper.GetDescription(pagamento.GetValueOrDefault()); + } + else + { + obj = null; + } + valor[1] = obj; + valor[2] = recibo.get_Valor(); + valor[3] = recibo.get_DataRecibo(); + valor[4] = recibo.get_Pagante(); + valor[5] = recibo.get_DocumentoPagante(); + valor[6] = recibo.get_Recebedor(); + valor[7] = recibo.get_DocumentoRecebedor(); + valor[8] = recibo.get_Referente(); + reciboViewModel.RegistrarAcao(str2, id, nullable, string.Format("TIPO: {0}\nPAGAMENTO: {1}\nVALOR: {2:c}\nDATA RECIBO: {3:G}\nPAGANTE: {4}, {5}\nRECEBEDOR: {6}, {7}\nREFERENTE: \"{8}\"", valor)); + if (!this.Recibos.Any((Recibo x) => x.get_Id() == recibo.get_Id())) + { + this.Recibos.Add(recibo); + } + else + { + DomainBase.Copy(this.Recibos.First((Recibo x) => x.get_Id() == recibo.get_Id()), recibo); + } + if (!this.RecibosFiltrados.Any((Recibo x) => x.get_Id() == recibo.get_Id())) + { + this.RecibosFiltrados.Add(recibo); + } + else + { + DomainBase.Copy(this.RecibosFiltrados.First((Recibo x) => x.get_Id() == recibo.get_Id()), recibo); + } + this.RecibosFiltrados = new ObservableCollection(this.RecibosFiltrados); + this.WorkOnSelectedRecibo(recibo, false); + base.Alterar(false); + base.ToggleSnackBar("RECIBO SALVO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str1 = null; + return keyValuePairs; + } + + private async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(42); + await this.SelecionaRecibo(); + base.Loading(false); + } + + private async Task SelecionaRecibo() + { + base.Loading(true); + List recibos = await this._servico.BuscarRecibos(); + this.Recibos = recibos.ToList(); + this.RecibosFiltrados = new ObservableCollection(this.Recibos); + if (this.RecibosFiltrados.Count <= 0) + { + this.SelectedRecibo = new Recibo(); + base.Alterar(false); + base.EnableMenu = false; + } + else + { + this.SelectedRecibo = this.RecibosFiltrados.First(); + } + base.Loading(false); + } + + private void WorkOnSelectedPagante(Cliente value) + { + if (value != null) + { + this.SelectedRecibo.set_Pagante(Regex.Replace(value.get_NomeSocial(), "\\-\\s\\d.*", "").Trim()); + this.SelectedRecibo.set_DocumentoPagante(value.get_Documento()); + this.SelectedRecibo = this.SelectedRecibo; + } + } + + private void WorkOnSelectedRecebedor(Cliente value) + { + if (value != null) + { + this.SelectedRecibo.set_Recebedor(Regex.Replace(value.get_NomeSocial(), "\\-\\s\\d.*", "").Trim()); + this.SelectedRecibo.set_DocumentoRecebedor(value.get_Documento()); + this.SelectedRecibo = this.SelectedRecibo; + } + } + + private void WorkOnSelectedRecibo(Recibo value, bool registrar = true) + { + long? nullable; + string description; + object obj; + this.CancelRecibo = (value == null || value.get_Id() == 0 ? this.CancelRecibo : (Recibo)value.Clone()); + if (value == null || value.get_Id() == 0 || this.LastAccessId == value.get_Id() && this.LastAccessTela == 42) + { + return; + } + if (registrar) + { + string str = string.Format("ACESSOU RECIBO DE NÚMERO \"{0}\"", value.get_Id()); + long id = value.get_Id(); + TipoTela? nullable1 = new TipoTela?(42); + object[] valor = new object[9]; + if (value.get_Tipo().HasValue) + { + TipoRecibo? tipo = value.get_Tipo(); + description = ValidationHelper.GetDescription(tipo.Value) ?? ""; + } + else + { + description = "-"; + } + valor[0] = description; + TipoPagamento? pagamento = value.get_Pagamento(); + if (pagamento.HasValue) + { + obj = ValidationHelper.GetDescription(pagamento.GetValueOrDefault()); + } + else + { + obj = null; + } + valor[1] = obj; + valor[2] = value.get_Valor(); + valor[3] = value.get_DataRecibo(); + valor[4] = value.get_Pagante(); + valor[5] = value.get_DocumentoPagante(); + valor[6] = value.get_Recebedor(); + valor[7] = value.get_DocumentoRecebedor(); + valor[8] = value.get_Referente(); + base.RegistrarAcao(str, id, nullable1, string.Format("TIPO: {0}\nPAGAMENTO: {1}\nVALOR: {2:c}\nDATA RECIBO: {3:G}\nPAGANTE: {4}, {5}\nRECEBEDOR: {6}, {7}\nREFERENTE: \"{8}\"", valor)); + } + this.LastAccessId = value.get_Id(); + this.LastAccessTela = 42; + Recibo selectedRecibo = this.SelectedRecibo; + if (selectedRecibo != null) + { + nullable = new long?(selectedRecibo.get_Id()); + } + else + { + nullable = null; + } + long? nullable2 = nullable; + long num = value.get_Id(); + if (nullable2.GetValueOrDefault() != num | !nullable2.HasValue) + { + this.SelectedRecibo = this.RecibosFiltrados.FirstOrDefault((Recibo x) => x.get_Id() == value.get_Id()); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/SeguradoraViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/SeguradoraViewModel.cs new file mode 100644 index 0000000..f7daced --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/SeguradoraViewModel.cs @@ -0,0 +1,621 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class SeguradoraViewModel : BaseSegurosViewModel + { + private readonly SeguradoraServico _servico; + + private bool _apelido; + + private Seguradora _selectedSeguradora; + + private SeguradoraEndereco _selectedEndereco = new SeguradoraEndereco(); + + private ObservableCollection _contatos = new ObservableCollection(); + + private ObservableCollection _enderecos = new ObservableCollection(); + + private SeguradoraContato _selectedTelefone = new SeguradoraContato(); + + private Visibility _tipoTelefone; + + private Visibility _telefone; + + private Visibility _prefixo; + + private ObservableCollection _configFiltrados = new ObservableCollection(); + + public Seguradora CancelSeguradora; + + public ObservableCollection CancelEnderecos; + + public ObservableCollection CancelContatos; + + private ObservableCollection _seguradorasFiltradas = new ObservableCollection(); + + private bool _isExpanded; + + public bool Apelido + { + get + { + return this._apelido; + } + set + { + this._apelido = value; + base.OnPropertyChanged("Apelido"); + } + } + + public List Config + { + get; + set; + } + + public ObservableCollection ConfigFiltrados + { + get + { + return this._configFiltrados; + } + set + { + this._configFiltrados = value; + base.OnPropertyChanged("ConfigFiltrados"); + } + } + + public ObservableCollection Contatos + { + get + { + return this._contatos; + } + set + { + this._contatos = value; + base.OnPropertyChanged("Contatos"); + } + } + + public ObservableCollection Enderecos + { + get + { + return this._enderecos; + } + set + { + this._enderecos = value; + base.OnPropertyChanged("Enderecos"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public string Pesquisa + { + get; + set; + } + + public Visibility PrefixoVisibility + { + get + { + return this._prefixo; + } + set + { + if (this.SelectedTelefone.get_TipoContato() != 2) + { + this._prefixo = Visibility.Visible; + } + else + { + this._prefixo = Visibility.Collapsed; + } + base.OnPropertyChanged("PrefixoVisibility"); + } + } + + public List Seguradoras + { + get; + set; + } + + public ObservableCollection SeguradorasFiltradas + { + get + { + return this._seguradorasFiltradas; + } + set + { + this._seguradorasFiltradas = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("SeguradorasFiltradas"); + } + } + + public SeguradoraEndereco SelectedEndereco + { + get + { + return this._selectedEndereco; + } + set + { + this._selectedEndereco = value; + base.OnPropertyChanged("SelectedEndereco"); + } + } + + public Seguradora SelectedSeguradora + { + get + { + return this._selectedSeguradora; + } + set + { + long? nullable; + this._selectedSeguradora = value; + this.WorkOnSelectedSeguradora(value, true); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedSeguradora"); + } + } + + public SeguradoraContato SelectedTelefone + { + get + { + return this._selectedTelefone; + } + set + { + this._selectedTelefone = value; + base.OnPropertyChanged("SelectedTelefone"); + } + } + + public Visibility TelefoneVisibility + { + get + { + return this._telefone; + } + set + { + if (this.SelectedTelefone.get_TipoContato() != 2) + { + this._telefone = Visibility.Visible; + } + else + { + this._telefone = Visibility.Collapsed; + } + base.OnPropertyChanged("TelefoneVisibility"); + } + } + + public Visibility TipoTelefoneVisibility + { + get + { + return this._tipoTelefone; + } + set + { + if (this.SelectedTelefone.get_TipoContato() != 2) + { + this._tipoTelefone = Visibility.Visible; + } + else + { + this._tipoTelefone = Visibility.Collapsed; + } + base.OnPropertyChanged("TipoTelefoneVisibility"); + } + } + + public decimal Tolerancia + { + get; + set; + } + + public SeguradoraViewModel() + { + this._servico = new SeguradoraServico(); + this.Apelido = Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 6); + base.EnableMenu = true; + this.Seleciona(); + } + + public void CancelarAlteracao() + { + if (this.CancelSeguradora != null && this.Seguradoras.Any((Seguradora x) => x.get_Id() == this.CancelSeguradora.get_Id())) + { + DomainBase.Copy(this.Seguradoras.First((Seguradora x) => x.get_Id() == this.CancelSeguradora.get_Id()), this.CancelSeguradora); + if (this.SeguradorasFiltradas.Count <= 0 || !this.SeguradorasFiltradas.Any((Seguradora x) => x.get_Id() == this.CancelSeguradora.get_Id())) + { + this.SeguradorasFiltradas.Add(this.CancelSeguradora); + } + else + { + DomainBase.Copy(this.SeguradorasFiltradas.First((Seguradora x) => x.get_Id() == this.CancelSeguradora.get_Id()), this.CancelSeguradora); + } + this.SeguradorasFiltradas = new ObservableCollection(this.SeguradorasFiltradas); + this.ConfigFiltrados = new ObservableCollection(this.ConfigFiltrados); + this.SelectedSeguradora = this.SeguradorasFiltradas.First((Seguradora x) => x.get_Id() == this.CancelSeguradora.get_Id()); + this.Enderecos = this.CancelEnderecos; + this.Contatos = this.CancelContatos; + } + base.Alterar(false); + } + + public void Clonar() + { + this.CancelSeguradora = (Seguradora)this.SelectedSeguradora.Clone(); + this.CancelEnderecos = new ObservableCollection(this.Enderecos); + this.CancelContatos = new ObservableCollection(this.Contatos); + } + + public void ExcluirEndereco(SeguradoraEndereco endereco) + { + this.Enderecos.Remove(endereco); + } + + public void ExcluirTelefone(SeguradoraContato contato) + { + this.Contatos.Remove(contato); + } + + internal async Task> Filtrar(string value) + { + List seguradoras = await Task.Run>(() => this.FiltrarSeguradora(value)); + return seguradoras; + } + + internal async Task> FiltrarConfig(string value) + { + List configExtratoImports = await Task.Run>(() => this.FiltrarDescricao(value)); + return configExtratoImports; + } + + public List FiltrarDescricao(string filter) + { + this.ConfigFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Config) : new ObservableCollection( + from x in this.Config + where ValidationHelper.RemoveDiacritics(x.get_Descricao().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby x.get_Descricao() + select x)); + return this.ConfigFiltrados.ToList(); + } + + public List FiltrarSeguradora(string filter) + { + this.Pesquisa = filter; + this.SeguradorasFiltradas = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Seguradoras) : new ObservableCollection(this.Seguradoras.Where((Seguradora x) => { + if (ValidationHelper.RemoveDiacritics(x.get_Nome().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter))) + { + return true; + } + return ValidationHelper.RemoveDiacritics(x.get_NomeSocial()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)); + }).OrderByDescending((Seguradora x) => x.get_Ativo()).ThenBy((Seguradora x) => x.get_Nome()))); + return this.SeguradorasFiltradas.ToList(); + } + + public async void Incluir(Seguradora seguradora) + { + seguradora.set_Tolerancia(new decimal?(2)); + seguradora.set_ToleranciaPremio(new decimal?(2)); + seguradora.set_Ativo(true); + await this._servico.Insert(seguradora); + if (this._servico.Sucesso) + { + await this.SelecionaSeguradoras(seguradora); + } + } + + public void IncluirEndereco() + { + if (this.SelectedSeguradora == null) + { + return; + } + if (this.Enderecos == null) + { + this.Enderecos = new ObservableCollection(); + } + SeguradoraEndereco seguradoraEndereco = new SeguradoraEndereco(); + seguradoraEndereco.set_Empresa(Recursos.Empresa); + seguradoraEndereco.set_Seguradora(this.SelectedSeguradora); + seguradoraEndereco.set_Tipo(4); + SeguradoraEndereco seguradoraEndereco1 = seguradoraEndereco; + this.Enderecos.Add(seguradoraEndereco1); + this.SelectedEndereco = seguradoraEndereco1; + } + + public void IncluirTelefone() + { + if (this.SelectedSeguradora == null) + { + return; + } + if (this.Contatos == null) + { + this.Contatos = new ObservableCollection(); + } + SeguradoraContato seguradoraContato = new SeguradoraContato(); + seguradoraContato.set_Empresa(Recursos.Empresa); + seguradoraContato.set_Seguradora(this.SelectedSeguradora); + seguradoraContato.set_Tipo(new TipoTelefone?(2)); + SeguradoraContato seguradoraContato1 = seguradoraContato; + this.Contatos.Add(seguradoraContato1); + this.SelectedTelefone = seguradoraContato1; + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + List> keyValuePairs1 = this.SelectedSeguradora.Validate(); + keyValuePairs1.AddRange(this.Validate(this.Contatos.ToList())); + keyValuePairs1.AddRange(this.Validate(this.Enderecos.ToList())); + if (keyValuePairs1.Count <= 0) + { + Seguradora selectedSeguradora = this.SelectedSeguradora; + ObservableCollection contatos = this.Contatos; + selectedSeguradora.set_Contatos(contatos.Where((SeguradoraContato x) => { + if (!string.IsNullOrEmpty(x.get_NomeContato())) + { + return true; + } + return x.get_TipoContato() == 1; + }).ToList()); + Seguradora seguradora = this.SelectedSeguradora; + ObservableCollection enderecos = this.Enderecos; + seguradora.set_Enderecos(( + from x in enderecos + where !string.IsNullOrEmpty(x.get_Bairro()) + select x).ToList()); + Seguradora seguradora1 = await this._servico.Save(this.SelectedSeguradora, this.Config, false); + Seguradora seguradora2 = seguradora1; + str = (this.SelectedSeguradora.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + string str1 = str; + if (this._servico.Sucesso) + { + base.RegistrarAcao(string.Concat(str1, " SEGURADORA \"", seguradora2.get_Nome(), "\""), seguradora2.get_Id(), new TipoTela?(13), string.Format("SEGURADORA \"{0}\", ID: {1}", seguradora2.get_Nome(), seguradora2.get_Id())); + await this.SelecionaSeguradoras(null); + this.FiltrarSeguradora(this.Pesquisa); + SeguradoraViewModel seguradoraViewModel = this; + Seguradora seguradora3 = this.SeguradorasFiltradas.FirstOrDefault((Seguradora x) => x.get_Id() == seguradora2.get_Id()); + if (seguradora3 == null) + { + seguradora3 = this.SeguradorasFiltradas.FirstOrDefault(); + } + seguradoraViewModel.SelectedSeguradora = seguradora3; + base.Alterar(false); + base.ToggleSnackBar("SEGURADORA SALVA COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + return keyValuePairs; + } + + private async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(13); + await this.SelecionaSeguradoras(null); + base.Loading(false); + } + + public async void SelecionaSeguradora(Seguradora seguradora) + { + base.Loading(true); + this.SelectedSeguradora = seguradora; + this.Contatos = await this._servico.BuscarContatos(this.SelectedSeguradora.get_Id()); + this.Enderecos = await this._servico.BuscarEnderecos(this.SelectedSeguradora.get_Id()); + this.Config = await this._servico.BuscarConfig(this.SelectedSeguradora.get_Id()); + this.ConfigFiltrados = new ObservableCollection(this.Config); + base.Loading(false); + } + + private async Task SelecionaSeguradoras(Seguradora seguradora = null) + { + base.Loading(true); + List seguradoras = await (new BaseServico()).BuscarSeguradorasAsync(); + SeguradoraViewModel list = this; + List seguradoras1 = seguradoras; + IOrderedEnumerable ativo = + from x in seguradoras1 + orderby x.get_Ativo() descending + select x; + list.Seguradoras = ativo.ThenBy((Seguradora x) => x.get_Nome()).ToList(); + this.SeguradorasFiltradas = new ObservableCollection(this.Seguradoras); + if (seguradora != null) + { + this.SelecionaSeguradora(this.SeguradorasFiltradas.FirstOrDefault((Seguradora x) => x.get_Id() == seguradora.get_Id())); + } + else if (this.SeguradorasFiltradas.Count <= 0) + { + this.SelectedSeguradora = new Seguradora(); + base.Alterar(false); + base.EnableMenu = false; + } + else + { + this.SelecionaSeguradora(this.SeguradorasFiltradas.First()); + } + Recursos.Seguradoras = seguradoras; + base.Loading(false); + } + + public List> Validate(List endereco) + { + List> keyValuePairs = new List>(); + if (endereco != null) + { + endereco.ForEach((SeguradoraEndereco x) => keyValuePairs.AddRange(x.Validate())); + } + return keyValuePairs.Distinct>().ToList>(); + } + + public List> Validate(List contatos) + { + List list; + List> keyValuePairs = new List>(); + if (contatos != null) + { + contatos.ForEach((SeguradoraContato x) => keyValuePairs.AddRange(x.Validate())); + } + if (contatos != null) + { + list = ( + from x in contatos + where x.get_TipoContato() == 1 + select x).ToList(); + } + else + { + list = null; + } + List seguradoraContatos = list; + if (seguradoraContatos == null) + { + return keyValuePairs; + } + if (seguradoraContatos.Count > 4) + { + keyValuePairs.Add(new KeyValuePair("ASSISTÊNCIAS 24 HORAS", "NÃO É POSSÍVEL ADICIONAR MAIS QUE 4 NUMEROS DE ASSISTÊNCIA 24 HORAS")); + } + return keyValuePairs.Distinct>().ToList>(); + } + + private void WorkOnSelectedSeguradora(Seguradora value, bool registrar = true) + { + decimal? nullable; + bool contatos; + bool enderecos; + long? nullable1; + decimal? tolerancia; + this.CancelSeguradora = (value == null || value.get_Id() == 0 ? this.CancelSeguradora : (Seguradora)value.Clone()); + this.CancelEnderecos = new ObservableCollection(this.Enderecos); + this.CancelContatos = new ObservableCollection(this.Contatos); + if (value == null || value.get_Id() == 0 || this.LastAccessId == value.get_Id() && this.LastAccessTela == 13) + { + return; + } + Seguradora selectedSeguradora = this.SelectedSeguradora; + if (selectedSeguradora != null) + { + contatos = selectedSeguradora.get_Contatos(); + } + else + { + contatos = false; + } + if (contatos) + { + this.Contatos = new ObservableCollection(this.SelectedSeguradora.get_Contatos()); + } + Seguradora seguradora = this.SelectedSeguradora; + if (seguradora != null) + { + enderecos = seguradora.get_Enderecos(); + } + else + { + enderecos = false; + } + if (enderecos) + { + this.Enderecos = new ObservableCollection(this.SelectedSeguradora.get_Enderecos()); + } + if (registrar) + { + base.RegistrarAcao(string.Concat("ACESSOU SEGURADORA \"", value.get_Nome(), "\""), value.get_Id(), new TipoTela?(13), string.Format("ID SEGURADORA: {0}", value.get_Id())); + } + this.LastAccessId = value.get_Id(); + this.LastAccessTela = 13; + Seguradora selectedSeguradora1 = this.SelectedSeguradora; + if (selectedSeguradora1 != null) + { + nullable1 = new long?(selectedSeguradora1.get_Id()); + } + else + { + nullable1 = null; + } + long? nullable2 = nullable1; + long id = value.get_Id(); + if (nullable2.GetValueOrDefault() != id | !nullable2.HasValue) + { + this.SelectedSeguradora = this.SeguradorasFiltradas.FirstOrDefault((Seguradora x) => x.get_Id() == value.get_Id()); + } + Seguradora seguradora1 = this.SelectedSeguradora; + if (seguradora1 != null) + { + tolerancia = seguradora1.get_Tolerancia(); + } + else + { + nullable = null; + tolerancia = nullable; + } + nullable = tolerancia; + this.Tolerancia = nullable.GetValueOrDefault(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/SocioViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/SocioViewModel.cs new file mode 100644 index 0000000..d946d89 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/SocioViewModel.cs @@ -0,0 +1,358 @@ +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class SocioViewModel : BaseSegurosViewModel + { + private readonly SocioServico _servico; + + public Socio CancelSocio; + + private ObservableCollection _empresas = new ObservableCollection(); + + private Empresa _selectedEmpresa; + + private Socio _selectedSocio = new Socio(); + + private ObservableCollection _sociosFiltradas = new ObservableCollection(); + + private bool _isExpanded; + + private bool _isLoading; + + public ObservableCollection Empresas + { + get + { + return this._empresas; + } + set + { + this._empresas = value; + base.OnPropertyChanged("Empresas"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public bool IsLoading + { + get + { + return this._isLoading; + } + set + { + this._isLoading = value; + base.OnPropertyChanged("IsLoading"); + } + } + + public Empresa SelectedEmpresa + { + get + { + return this._selectedEmpresa; + } + set + { + this._selectedEmpresa = value; + this.WorkOnSelectedEmpresa(value); + base.OnPropertyChanged("SelectedEmpresa"); + } + } + + public Socio SelectedSocio + { + get + { + return this._selectedSocio; + } + set + { + long? nullable; + this._selectedSocio = value; + this.WorkOnSelectedSocio(value, true); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedSocio"); + } + } + + public List Socios + { + get; + set; + } + + public ObservableCollection SociosFiltradas + { + get + { + return this._sociosFiltradas; + } + set + { + this._sociosFiltradas = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("SociosFiltradas"); + } + } + + public SocioViewModel() + { + this._servico = new SocioServico(); + base.EnableMenu = true; + this.Seleciona(); + } + + public void CancelarAlteracao() + { + if (this.CancelSocio == null || !this.Socios.Any((Socio x) => x.get_Id() == this.CancelSocio.get_Id())) + { + this.Incluir(); + } + else + { + DomainBase.Copy(this.Socios.First((Socio x) => x.get_Id() == this.CancelSocio.get_Id()), this.CancelSocio); + if (this.SociosFiltradas.Count <= 0 || !this.SociosFiltradas.Any((Socio x) => x.get_Id() == this.CancelSocio.get_Id())) + { + this.SociosFiltradas.Add(this.CancelSocio); + } + else + { + DomainBase.Copy(this.SociosFiltradas.First((Socio x) => x.get_Id() == this.CancelSocio.get_Id()), this.CancelSocio); + } + this.SociosFiltradas = new ObservableCollection(this.SociosFiltradas); + this.SelectedSocio = this.SociosFiltradas.First((Socio x) => x.get_Id() == this.CancelSocio.get_Id()); + } + base.Alterar(false); + } + + public async void Excluir() + { + Socio socio; + if (this.SelectedSocio != null && this.SelectedSocio.get_Id() != 0) + { + if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + base.Loading(true); + this.IsLoading = true; + if (await this._servico.Delete(this.SelectedSocio)) + { + string str = string.Concat("EXCLUIU SÓCIO \"", this.SelectedSocio.get_Nome(), "\""); + long id = this.SelectedSocio.get_Id(); + TipoTela? nullable = new TipoTela?(19); + object[] objArray = new object[] { this.SelectedSocio.get_Id(), this.SelectedSocio.get_Prefixo(), this.SelectedSocio.get_Telefone(), this.SelectedSocio.get_Email() }; + base.RegistrarAcao(str, id, nullable, string.Format("ID: {0}\nTELEFONE: ({1}) {2}\nE-MAIL: {3}", objArray)); + int num = this.SociosFiltradas.IndexOf(this.SelectedSocio); + this.Socios.Remove(this.SelectedSocio); + this.SociosFiltradas.Remove(this.SelectedSocio); + this.SociosFiltradas = new ObservableCollection(this.SociosFiltradas); + if (this.SociosFiltradas.Count <= 0) + { + this.SelectedSocio = new Socio(); + base.Alterar(false); + } + else + { + SocioViewModel socioViewModel = this; + socio = (num < this.SociosFiltradas.Count ? this.SociosFiltradas.ElementAt(num) : this.SociosFiltradas.Last()); + socioViewModel.SelectedSocio = socio; + } + base.Loading(false); + this.IsLoading = false; + base.ToggleSnackBar("SÓCIO EXCLUÍDO COM SUCESSO", true); + } + else + { + base.Loading(false); + this.IsLoading = false; + } + } + } + } + + internal async Task> Filtrar(string value) + { + List socios = await Task.Run>(() => this.FiltrarSocio(value)); + return socios; + } + + public List FiltrarSocio(string filter) + { + this.SociosFiltradas = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Socios) : new ObservableCollection( + from x in this.Socios + where ValidationHelper.RemoveDiacritics(x.get_Nome().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby x.get_Nome() + select x)); + return this.SociosFiltradas.ToList(); + } + + public void Incluir() + { + Socio socio = new Socio(); + socio.set_IdEmpresa(this.SelectedEmpresa.get_Id()); + this.SelectedSocio = socio; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + string str1; + List> keyValuePairs1 = this.SelectedSocio.Validate(); + if (keyValuePairs1.Count <= 0) + { + str = (this.SelectedSocio.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str1 = str; + Socio socio = await this._servico.Save(this.SelectedSocio); + if (this._servico.Sucesso) + { + string str2 = string.Concat(str1, " SÓCIO \"", socio.get_Nome(), "\""); + long id = socio.get_Id(); + TipoTela? nullable = new TipoTela?(19); + object[] objArray = new object[] { socio.get_Id(), socio.get_Prefixo(), socio.get_Telefone(), socio.get_Email() }; + base.RegistrarAcao(str2, id, nullable, string.Format("ID: {0}\nTELEFONE: ({1}) {2}\nE-MAIL: {3}", objArray)); + if (!this.Socios.Any((Socio x) => x.get_Id() == socio.get_Id())) + { + this.Socios.Add(socio); + } + else + { + DomainBase.Copy(this.Socios.First((Socio x) => x.get_Id() == socio.get_Id()), socio); + } + if (!this.SociosFiltradas.Any((Socio x) => x.get_Id() == socio.get_Id())) + { + this.SociosFiltradas.Add(socio); + } + else + { + DomainBase.Copy(this.SociosFiltradas.First((Socio x) => x.get_Id() == socio.get_Id()), socio); + } + this.SociosFiltradas = new ObservableCollection(this.SociosFiltradas); + this.WorkOnSelectedSocio(socio, false); + base.Alterar(false); + base.ToggleSnackBar("SÓCIO SALVO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str1 = null; + return keyValuePairs; + } + + private async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(19); + this.Empresas = new ObservableCollection(await (new EmpresaServico()).BuscarEmpresas()); + base.Loading(false); + this.SelectedEmpresa = this.Empresas.FirstOrDefault(); + } + + private async Task SelecionaSocios(long? id) + { + this.Socios = null; + this.SociosFiltradas = null; + if (id.HasValue) + { + long? nullable = id; + long num = (long)0; + if (!(nullable.GetValueOrDefault() == num & nullable.HasValue)) + { + base.Loading(true); + List socios = await (new BaseServico()).BuscarSociosAsync(id.Value); + SocioViewModel list = this; + List socios1 = socios; + list.Socios = ( + from x in socios1 + orderby x.get_Nome() + select x).ToList(); + this.SociosFiltradas = new ObservableCollection(this.Socios); + this.SelectedSocio = this.SociosFiltradas.FirstOrDefault(); + base.Loading(false); + return; + } + } + } + + private async void WorkOnSelectedEmpresa(Empresa value) + { + if (value != null && value.get_Id() != 0) + { + await this.SelecionaSocios(new long?(value.get_Id())); + } + } + + private void WorkOnSelectedSocio(Socio value, bool registrar = true) + { + long? nullable; + this.CancelSocio = (value == null || value.get_Id() == 0 ? this.CancelSocio : (Socio)value.Clone()); + if (value == null || value.get_Id() == 0 || this.LastAccessId == value.get_Id() && this.LastAccessTela == 19) + { + return; + } + if (registrar) + { + base.RegistrarAcao(string.Concat("ACESSOU SÓCIO \"", value.get_Nome(), "\""), value.get_Id(), new TipoTela?(19), string.Format("ID: {0}\nTELEFONE: ({1}) {2}\nE-MAIL: {3}", new object[] { value.get_Id(), value.get_Prefixo(), value.get_Telefone(), value.get_Email() })); + } + this.LastAccessId = value.get_Id(); + this.LastAccessTela = 19; + Socio selectedSocio = this.SelectedSocio; + if (selectedSocio != null) + { + nullable = new long?(selectedSocio.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long id = value.get_Id(); + if (nullable1.GetValueOrDefault() != id | !nullable1.HasValue) + { + this.SelectedSocio = this.SociosFiltradas.FirstOrDefault((Socio x) => x.get_Id() == value.get_Id()); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/StatusProspeccaoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/StatusProspeccaoViewModel.cs new file mode 100644 index 0000000..4643cd1 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/StatusProspeccaoViewModel.cs @@ -0,0 +1,326 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class StatusProspeccaoViewModel : BaseSegurosViewModel + { + private readonly StatusProspeccaoServico _servico; + + private readonly ProspeccaoServico _servicoProspeccao; + + public StatusDeProspeccao CancelStatusProspeccao; + + private ObservableCollection _statusProspeccaoFiltrados = new ObservableCollection(); + + private bool _isExpanded; + + private StatusDeProspeccao _selectedStatusProspeccao; + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public StatusDeProspeccao SelectedStatusProspeccao + { + get + { + return this._selectedStatusProspeccao; + } + set + { + long? nullable; + this._selectedStatusProspeccao = value; + this.WorkOnSelectedStatusProspeccao(value, true); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedStatusProspeccao"); + } + } + + public List StatusProspeccao + { + get; + set; + } + + public ObservableCollection StatusProspeccaoFiltrados + { + get + { + return this._statusProspeccaoFiltrados; + } + set + { + this._statusProspeccaoFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("StatusProspeccaoFiltrados"); + } + } + + public StatusProspeccaoViewModel() + { + this._servico = new StatusProspeccaoServico(); + this._servicoProspeccao = new ProspeccaoServico(); + base.EnableMenu = true; + this.Seleciona(); + } + + public void CancelarAlteracao() + { + if (this.CancelStatusProspeccao == null || !this.StatusProspeccao.Any((StatusDeProspeccao x) => x.get_Id() == this.CancelStatusProspeccao.get_Id())) + { + this.Incluir(); + } + else + { + DomainBase.Copy(this.StatusProspeccao.First((StatusDeProspeccao x) => x.get_Id() == this.CancelStatusProspeccao.get_Id()), this.CancelStatusProspeccao); + if (this.StatusProspeccaoFiltrados.Count <= 0 || !this.StatusProspeccaoFiltrados.Any((StatusDeProspeccao x) => x.get_Id() == this.CancelStatusProspeccao.get_Id())) + { + this.StatusProspeccaoFiltrados.Add(this.CancelStatusProspeccao); + } + else + { + DomainBase.Copy(this.StatusProspeccaoFiltrados.First((StatusDeProspeccao x) => x.get_Id() == this.CancelStatusProspeccao.get_Id()), this.CancelStatusProspeccao); + } + this.StatusProspeccaoFiltrados = new ObservableCollection(this.StatusProspeccaoFiltrados); + this.SelectedStatusProspeccao = this.StatusProspeccaoFiltrados.First((StatusDeProspeccao x) => x.get_Id() == this.CancelStatusProspeccao.get_Id()); + } + base.Alterar(false); + } + + public async void Excluir() + { + object obj; + if (this.SelectedStatusProspeccao != null && this.SelectedStatusProspeccao.get_Id() != 0) + { + if (await this._servicoProspeccao.BuscarProspeccoesPorStatus(this.SelectedStatusProspeccao).Count > 0) + { + await base.ShowMessage(string.Concat("O STATUS ", this.SelectedStatusProspeccao.get_Nome(), ", NÃO PODE SER EXCLUÍDO, POIS ESTÁ CADASTRADO EM UMA PROSPECÇÃO"), "OK", "", false); + } + else if (await base.ShowMessage(string.Concat("DESEJA REALMENTE EXCLUIR O STATUS DE PROSPECÇÃO ", this.SelectedStatusProspeccao.get_Nome(), "?"), "SIM", "NÃO", false)) + { + base.Loading(true); + this.SelectedStatusProspeccao.set_Excluido(true); + this.SelectedStatusProspeccao.set_Ativo(false); + await this._servico.Save(this.SelectedStatusProspeccao); + if (this._servico.Sucesso) + { + StatusProspeccaoViewModel statusProspeccaoViewModel = this; + string str = string.Concat("EXCLUIU STATUS DE PROSPECÇÃO \"", this.SelectedStatusProspeccao.get_Nome(), "\""); + long id = this.SelectedStatusProspeccao.get_Id(); + TipoTela? nullable = new TipoTela?(57); + object id1 = this.SelectedStatusProspeccao.get_Id(); + obj = (this.SelectedStatusProspeccao.get_Ativo() ? "SIM" : "NÃO"); + statusProspeccaoViewModel.RegistrarAcao(str, id, nullable, string.Format("ID: {0}\nATIVO: {1}\nDESCRIÇÃO: \"{2}\"", id1, obj, this.SelectedStatusProspeccao.get_Descricao())); + this.StatusProspeccao.Remove(this.SelectedStatusProspeccao); + this.StatusProspeccaoFiltrados.Remove(this.SelectedStatusProspeccao); + Recursos.StatusProspeccao.Remove(this.SelectedStatusProspeccao); + this.SelectedStatusProspeccao = this.StatusProspeccaoFiltrados.FirstOrDefault(); + await this.SelecionaStatusProspeccao(); + base.Loading(false); + base.ToggleSnackBar("STATUS DE PROSPECÇÃO EXCLUÍDO COM SUCESSO", true); + } + else + { + base.Loading(false); + } + } + } + } + + public async Task> Filtrar(string value) + { + List statusDeProspeccaos = await Task.Run>(() => this.FiltrarStatusProspeccao(value)); + return statusDeProspeccaos; + } + + public List FiltrarStatusProspeccao(string filter) + { + this.StatusProspeccaoFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.StatusProspeccao) : new ObservableCollection( + from x in this.StatusProspeccao + where ValidationHelper.RemoveDiacritics(x.get_Nome().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby x.get_Ativo() descending, x.get_Nome() + select x)); + this.SelectedStatusProspeccao = this.StatusProspeccaoFiltrados.FirstOrDefault(); + return this.StatusProspeccaoFiltrados.ToList(); + } + + public void Incluir() + { + StatusDeProspeccao statusDeProspeccao = new StatusDeProspeccao(); + statusDeProspeccao.set_Ativo(true); + statusDeProspeccao.set_Excluido(false); + this.SelectedStatusProspeccao = statusDeProspeccao; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + object obj; + string str1; + List> keyValuePairs1 = this.SelectedStatusProspeccao.Validate(); + keyValuePairs1.AddRange(this.Validate()); + if (keyValuePairs1.Count <= 0) + { + str = (this.SelectedStatusProspeccao.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str1 = str; + StatusDeProspeccao statusDeProspeccao = await this._servico.Save(this.SelectedStatusProspeccao); + if (this._servico.Sucesso) + { + StatusProspeccaoViewModel statusProspeccaoViewModel = this; + string str2 = string.Concat(str1, " STATUS DE PROSPECÇÃO \"", statusDeProspeccao.get_Nome(), "\""); + long id = statusDeProspeccao.get_Id(); + TipoTela? nullable = new TipoTela?(57); + object id1 = statusDeProspeccao.get_Id(); + obj = (statusDeProspeccao.get_Ativo() ? "SIM" : "NÃO"); + statusProspeccaoViewModel.RegistrarAcao(str2, id, nullable, string.Format("ID: {0}\nATIVO: {1}\nDESCRIÇÃO: \"{2}\"", id1, obj, statusDeProspeccao.get_Descricao())); + if (!this.StatusProspeccao.Any((StatusDeProspeccao x) => x.get_Id() == statusDeProspeccao.get_Id())) + { + this.StatusProspeccao.Add(statusDeProspeccao); + } + else + { + DomainBase.Copy(this.StatusProspeccao.First((StatusDeProspeccao x) => x.get_Id() == statusDeProspeccao.get_Id()), statusDeProspeccao); + } + if (!this.StatusProspeccaoFiltrados.Any((StatusDeProspeccao x) => x.get_Id() == statusDeProspeccao.get_Id())) + { + this.StatusProspeccaoFiltrados.Add(statusDeProspeccao); + } + else + { + DomainBase.Copy(this.StatusProspeccaoFiltrados.First((StatusDeProspeccao x) => x.get_Id() == statusDeProspeccao.get_Id()), statusDeProspeccao); + } + this.StatusProspeccaoFiltrados = new ObservableCollection(this.StatusProspeccaoFiltrados); + this.WorkOnSelectedStatusProspeccao(statusDeProspeccao, false); + Recursos.StatusProspeccao = this.StatusProspeccao; + base.Alterar(false); + base.ToggleSnackBar("STATUS DE PROSPECÇÃO SALVO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str1 = null; + return keyValuePairs; + } + + private async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(57); + await this.SelecionaStatusProspeccao(); + base.Loading(false); + } + + private async Task SelecionaStatusProspeccao() + { + base.Loading(true); + List statusDeProspeccaos = await this._servico.BuscarProspeccoes(); + StatusProspeccaoViewModel list = this; + List statusDeProspeccaos1 = statusDeProspeccaos; + IEnumerable excluido = + from x in statusDeProspeccaos1 + where !x.get_Excluido() + select x; + IOrderedEnumerable ativo = + from x in excluido + orderby x.get_Ativo() descending + select x; + list.StatusProspeccao = ativo.ThenBy((StatusDeProspeccao x) => x.get_Nome()).ToList(); + this.StatusProspeccaoFiltrados = new ObservableCollection(this.StatusProspeccao); + this.SelectedStatusProspeccao = this.StatusProspeccaoFiltrados.FirstOrDefault(); + base.Loading(false); + } + + public List> Validate() + { + List> keyValuePairs = new List>(); + if (string.IsNullOrWhiteSpace(this.SelectedStatusProspeccao.get_Nome())) + { + return keyValuePairs; + } + if (this.StatusProspeccao.Any((StatusDeProspeccao x) => { + if (!x.get_Nome().Contains(this.SelectedStatusProspeccao.get_Nome())) + { + return false; + } + return x.get_Id() != this.SelectedStatusProspeccao.get_Id(); + })) + { + keyValuePairs.Add(new KeyValuePair("Nome", "UM STATUS DE PROSPECÇÃO COM O MESMO NOME JÁ EXISTE.")); + } + return keyValuePairs; + } + + private void WorkOnSelectedStatusProspeccao(StatusDeProspeccao value, bool registrar = true) + { + long? nullable; + this.CancelStatusProspeccao = (value == null || value.get_Id() == 0 ? this.CancelStatusProspeccao : (StatusDeProspeccao)value.Clone()); + if (value == null || value.get_Id() == 0 || this.LastAccessId == value.get_Id() && this.LastAccessTela == 57) + { + return; + } + if (registrar) + { + base.RegistrarAcao(string.Concat("ACESSOU STATUS DE PROSPECÇÃO \"", value.get_Nome(), "\""), value.get_Id(), new TipoTela?(57), string.Format("ID: {0}\nATIVO: {1}\nDESCRIÇÃO: \"{2}\"", value.get_Id(), (value.get_Ativo() ? "SIM" : "NÃO"), value.get_Descricao())); + } + this.LastAccessId = value.get_Id(); + this.LastAccessTela = 57; + StatusDeProspeccao selectedStatusProspeccao = this.SelectedStatusProspeccao; + if (selectedStatusProspeccao != null) + { + nullable = new long?(selectedStatusProspeccao.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long id = value.get_Id(); + if (nullable1.GetValueOrDefault() != id | !nullable1.HasValue) + { + this.SelectedStatusProspeccao = this.StatusProspeccaoFiltrados.FirstOrDefault((StatusDeProspeccao x) => x.get_Id() == value.get_Id()); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/StatusViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/StatusViewModel.cs new file mode 100644 index 0000000..93b36c1 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/StatusViewModel.cs @@ -0,0 +1,367 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class StatusViewModel : BaseSegurosViewModel + { + private readonly StatusServico _servico; + + private Gestor.Model.Domain.Seguros.Status _selectedStatus; + + public Gestor.Model.Domain.Seguros.Status CancelStatus; + + private ObservableCollection _statusFiltrados = new ObservableCollection(); + + private bool _isExpanded; + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public Gestor.Model.Domain.Seguros.Status SelectedStatus + { + get + { + return this._selectedStatus; + } + set + { + long? nullable; + this._selectedStatus = value; + this.WorkOnSelectedStatus(value, true); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedStatus"); + } + } + + public List Status + { + get; + set; + } + + public ObservableCollection StatusFiltrados + { + get + { + return this._statusFiltrados; + } + set + { + this._statusFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("StatusFiltrados"); + } + } + + public StatusViewModel() + { + this._servico = new StatusServico(); + base.EnableMenu = true; + this.Seleciona(); + } + + public void CancelarAlteracao() + { + if (this.CancelStatus == null || !this.Status.Any((Gestor.Model.Domain.Seguros.Status x) => x.get_Id() == this.CancelStatus.get_Id())) + { + this.Incluir(); + } + else + { + DomainBase.Copy(this.Status.First((Gestor.Model.Domain.Seguros.Status x) => x.get_Id() == this.CancelStatus.get_Id()), this.CancelStatus); + if (this.StatusFiltrados.Count <= 0 || !this.StatusFiltrados.Any((Gestor.Model.Domain.Seguros.Status x) => x.get_Id() == this.CancelStatus.get_Id())) + { + this.StatusFiltrados.Add(this.CancelStatus); + } + else + { + DomainBase.Copy(this.StatusFiltrados.First((Gestor.Model.Domain.Seguros.Status x) => x.get_Id() == this.CancelStatus.get_Id()), this.CancelStatus); + } + this.StatusFiltrados = new ObservableCollection(this.StatusFiltrados); + this.SelectedStatus = this.StatusFiltrados.First((Gestor.Model.Domain.Seguros.Status x) => x.get_Id() == this.CancelStatus.get_Id()); + } + base.Alterar(false); + } + + public async void Excluir() + { + object obj; + Gestor.Model.Domain.Seguros.Status statu; + if (this.SelectedStatus != null && this.SelectedStatus.get_Id() != 0) + { + base.Loading(true); + List documentos = await (new BaseServico()).BuscarDocumentosPorStatus(this.SelectedStatus.get_Id()); + base.Loading(false); + if (documentos.Count > 0) + { + string str = "ESTIPULANTE NÃO PODE SER EXCLUÍDO POIS ESTÁ VINCULADO AOS SEGUINTES DOCUMENTOS:"; + foreach (Documento documento in documentos) + { + if (!string.IsNullOrWhiteSpace(documento.get_Apolice())) + { + object[] newLine = new object[] { Environment.NewLine, documentos.IndexOf(documento) + 1, documento.get_Proposta(), documento.get_Apolice() }; + str = string.Concat(str, string.Format("{0}DOCUMENTO {1} (NÚMERO DA PROPOSTA: {2}, NÚMERO DA APÓLICE: {3})", newLine)); + } + else + { + str = string.Concat(str, string.Format("{0}DOCUMENTO {1} (NÚMERO DA PROPOSTA: {2})", Environment.NewLine, documentos.IndexOf(documento) + 1, documento.get_Proposta())); + } + } + await base.ShowMessage(str, "OK", "", false); + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + base.Loading(true); + if (await this._servico.Delete(this.SelectedStatus)) + { + StatusViewModel statusViewModel = this; + string str1 = string.Concat("EXCLUIU STATUS \"", this.SelectedStatus.get_Nome(), "\""); + long id = this.SelectedStatus.get_Id(); + TipoTela? nullable = new TipoTela?(11); + object id1 = this.SelectedStatus.get_Id(); + obj = (this.SelectedStatus.get_Ativo() ? "SIM" : "NÃO"); + statusViewModel.RegistrarAcao(str1, id, nullable, string.Format("ID: {0}\nATIVO: {1}", id1, obj)); + int num = this.StatusFiltrados.IndexOf(this.SelectedStatus); + this.Status.Remove(this.SelectedStatus); + this.StatusFiltrados.Remove(this.SelectedStatus); + this.StatusFiltrados = new ObservableCollection(this.StatusFiltrados); + if (this.StatusFiltrados.Count <= 0) + { + this.SelectedStatus = new Gestor.Model.Domain.Seguros.Status(); + base.Alterar(false); + base.EnableMenu = false; + } + else + { + StatusViewModel statusViewModel1 = this; + statu = (num < this.StatusFiltrados.Count ? this.StatusFiltrados.ElementAt(num) : this.StatusFiltrados.Last()); + statusViewModel1.SelectedStatus = statu; + } + base.Loading(false); + base.ToggleSnackBar("ESTIPULANTE EXCLUÍDO COM SUCESSO", true); + } + else + { + base.Loading(false); + } + } + } + } + + internal async Task> Filtrar(string value) + { + List statuses = await Task.Run>(() => this.FiltrarStatus(value)); + return statuses; + } + + public List FiltrarStatus(string filter) + { + this.StatusFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Status) : new ObservableCollection( + from x in this.Status + where ValidationHelper.RemoveDiacritics(x.get_Nome().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby x.get_Ativo() descending, x.get_Nome() + select x)); + return this.StatusFiltrados.ToList(); + } + + public void Incluir() + { + Gestor.Model.Domain.Seguros.Status statu = new Gestor.Model.Domain.Seguros.Status(); + statu.set_Ativo(true); + this.SelectedStatus = statu; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + object obj; + string str1; + List> keyValuePairs1 = this.SelectedStatus.Validate(); + List> keyValuePairs2 = keyValuePairs1; + keyValuePairs2.AddRange(await this.Validate()); + keyValuePairs2 = null; + if (keyValuePairs1.Count <= 0) + { + str = (this.SelectedStatus.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str1 = str; + Gestor.Model.Domain.Seguros.Status statu = await this._servico.Save(this.SelectedStatus); + if (this._servico.Sucesso) + { + StatusViewModel statusViewModel = this; + string str2 = string.Concat(str1, " STATUS ID \"", statu.get_Nome(), "\""); + long id = statu.get_Id(); + TipoTela? nullable = new TipoTela?(11); + object id1 = statu.get_Id(); + obj = (statu.get_Ativo() ? "SIM" : "NÃO"); + statusViewModel.RegistrarAcao(str2, id, nullable, string.Format("ID: {0}\nATIVO: {1}", id1, obj)); + if (!this.Status.Any((Gestor.Model.Domain.Seguros.Status x) => x.get_Id() == statu.get_Id())) + { + this.Status.Add(statu); + } + else + { + DomainBase.Copy(this.Status.First((Gestor.Model.Domain.Seguros.Status x) => x.get_Id() == statu.get_Id()), statu); + } + if (!this.StatusFiltrados.Any((Gestor.Model.Domain.Seguros.Status x) => x.get_Id() == statu.get_Id())) + { + this.StatusFiltrados.Add(statu); + } + else + { + DomainBase.Copy(this.StatusFiltrados.First((Gestor.Model.Domain.Seguros.Status x) => x.get_Id() == statu.get_Id()), statu); + } + this.StatusFiltrados = new ObservableCollection(this.StatusFiltrados); + this.WorkOnSelectedStatus(statu, false); + Recursos.Status = this.Status; + base.Alterar(false); + base.ToggleSnackBar("STATUS SALVO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + keyValuePairs1 = null; + str1 = null; + return keyValuePairs; + } + + private async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(11); + await this.SelecionaStatuses(); + base.Loading(false); + } + + public async void SelecionaStatus(Gestor.Model.Domain.Seguros.Status status) + { + Gestor.Model.Domain.Seguros.Status statu = await this._servico.BuscarStatusPorId(status.get_Id()); + DomainBase.Copy(this.StatusFiltrados.First((Gestor.Model.Domain.Seguros.Status x) => x.get_Id() == status.get_Id()), statu); + this.SelectedStatus = this.StatusFiltrados.First((Gestor.Model.Domain.Seguros.Status x) => x.get_Id() == status.get_Id()); + } + + private async Task SelecionaStatuses() + { + base.Loading(true); + List statuses = await (new BaseServico()).BuscarStatusAsync(); + StatusViewModel list = this; + List statuses1 = statuses; + IOrderedEnumerable ativo = + from x in statuses1 + orderby x.get_Ativo() descending + select x; + list.Status = ativo.ThenBy((Gestor.Model.Domain.Seguros.Status x) => x.get_Nome()).ToList(); + this.StatusFiltrados = new ObservableCollection(this.Status); + this.SelectedStatus = this.StatusFiltrados.FirstOrDefault(); + Recursos.Status = this.Status; + base.Loading(false); + } + + public async Task>> Validate() + { + List> keyValuePairs; + List> keyValuePairs1; + if (!string.IsNullOrWhiteSpace(this.SelectedStatus.get_Nome())) + { + keyValuePairs1 = new List>(); + bool flag = true; + List statuses = await (new BaseServico()).BuscarStatus(this.SelectedStatus.get_Nome()); + if (statuses.Count > 0) + { + statuses.ForEach((Gestor.Model.Domain.Seguros.Status x) => { + if (x.get_Id() == this.SelectedStatus.get_Id()) + { + return; + } + if (x.get_Nome() == this.SelectedStatus.get_Nome()) + { + flag = false; + } + }); + } + if (!flag) + { + keyValuePairs1.Add(new KeyValuePair("Nome", "UM STATUS COM O MESMO NOME JÁ EXISTE.")); + } + keyValuePairs = keyValuePairs1; + } + else + { + keyValuePairs = new List>(); + } + keyValuePairs1 = null; + return keyValuePairs; + } + + private void WorkOnSelectedStatus(Gestor.Model.Domain.Seguros.Status value, bool registrar = true) + { + long? nullable; + this.CancelStatus = (value == null || value.get_Id() == 0 ? this.CancelStatus : (Gestor.Model.Domain.Seguros.Status)value.Clone()); + if (value == null || value.get_Id() == 0 || this.LastAccessId == value.get_Id() && this.LastAccessTela == 11) + { + return; + } + if (registrar) + { + base.RegistrarAcao(string.Concat("ACESSOU STATUS \"", value.get_Nome(), "\""), value.get_Id(), new TipoTela?(11), string.Format("ID: {0}\nATIVO: {1}", value.get_Id(), (value.get_Ativo() ? "SIM" : "NÃO"))); + } + this.LastAccessId = value.get_Id(); + this.LastAccessTela = 11; + Gestor.Model.Domain.Seguros.Status selectedStatus = this.SelectedStatus; + if (selectedStatus != null) + { + nullable = new long?(selectedStatus.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long id = value.get_Id(); + if (nullable1.GetValueOrDefault() != id | !nullable1.HasValue) + { + this.SelectedStatus = this.StatusFiltrados.FirstOrDefault((Gestor.Model.Domain.Seguros.Status x) => x.get_Id() == value.get_Id()); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/TipoTarefaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/TipoTarefaViewModel.cs new file mode 100644 index 0000000..07b51e1 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/TipoTarefaViewModel.cs @@ -0,0 +1,325 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class TipoTarefaViewModel : BaseSegurosViewModel + { + private readonly TipoTarefaServico _servico; + + private readonly TarefaServico _servicoTarefa; + + public TipoDeTarefa CancelTipoTarefa; + + private ObservableCollection _tiposTarefaFiltrados = new ObservableCollection(); + + private bool _isExpanded; + + private TipoDeTarefa _selectedTipoTarefa; + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public TipoDeTarefa SelectedTipoTarefa + { + get + { + return this._selectedTipoTarefa; + } + set + { + long? nullable; + this._selectedTipoTarefa = value; + this.WorkOnSelectedTipoTarefa(value, true); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedTipoTarefa"); + } + } + + public List TiposTarefa + { + get; + set; + } + + public ObservableCollection TiposTarefaFiltrados + { + get + { + return this._tiposTarefaFiltrados; + } + set + { + this._tiposTarefaFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("TiposTarefaFiltrados"); + } + } + + public TipoTarefaViewModel() + { + this._servico = new TipoTarefaServico(); + this._servicoTarefa = new TarefaServico(); + base.EnableMenu = true; + this.Seleciona(); + } + + public void CancelarAlteracao() + { + if (this.CancelTipoTarefa == null || !this.TiposTarefa.Any((TipoDeTarefa x) => x.get_Id() == this.CancelTipoTarefa.get_Id())) + { + this.Incluir(); + } + else + { + DomainBase.Copy(this.TiposTarefa.First((TipoDeTarefa x) => x.get_Id() == this.CancelTipoTarefa.get_Id()), this.CancelTipoTarefa); + if (this.TiposTarefaFiltrados.Count <= 0 || !this.TiposTarefaFiltrados.Any((TipoDeTarefa x) => x.get_Id() == this.CancelTipoTarefa.get_Id())) + { + this.TiposTarefaFiltrados.Add(this.CancelTipoTarefa); + } + else + { + DomainBase.Copy(this.TiposTarefaFiltrados.First((TipoDeTarefa x) => x.get_Id() == this.CancelTipoTarefa.get_Id()), this.CancelTipoTarefa); + } + this.TiposTarefaFiltrados = new ObservableCollection(this.TiposTarefaFiltrados); + this.SelectedTipoTarefa = this.TiposTarefaFiltrados.First((TipoDeTarefa x) => x.get_Id() == this.CancelTipoTarefa.get_Id()); + } + base.Alterar(false); + } + + public async void Excluir() + { + object obj; + if (this.SelectedTipoTarefa != null && this.SelectedTipoTarefa.get_Id() != 0) + { + if (await this._servicoTarefa.BuscarTarefasPorTipo(this.SelectedTipoTarefa).Count > 0) + { + await base.ShowMessage(string.Concat("O TIPO ", this.SelectedTipoTarefa.get_Nome(), ", NÃO PODE SER EXCLUÍDO, POIS ESTÁ CADASTRADO EM UMA TAREFA"), "OK", "", false); + } + else if (await base.ShowMessage(string.Concat("DESEJA REALMENTE EXCLUIR O TIPO DE TAREFA ", this.SelectedTipoTarefa.get_Nome(), "?"), "SIM", "NÃO", false)) + { + base.Loading(true); + this.SelectedTipoTarefa.set_Excluido(true); + this.SelectedTipoTarefa.set_Ativo(false); + await this._servico.Save(this.SelectedTipoTarefa); + if (this._servico.Sucesso) + { + TipoTarefaViewModel tipoTarefaViewModel = this; + string str = string.Concat("EXCLUIU TIPO DE TAREFA \"", this.SelectedTipoTarefa.get_Nome(), "\""); + long id = this.SelectedTipoTarefa.get_Id(); + TipoTela? nullable = new TipoTela?(52); + object id1 = this.SelectedTipoTarefa.get_Id(); + obj = (this.SelectedTipoTarefa.get_Ativo() ? "SIM" : "NÃO"); + tipoTarefaViewModel.RegistrarAcao(str, id, nullable, string.Format("ID: {0}\nATIVO: {1}\nDESCRIÇÃO: \"{2}\"", id1, obj, this.SelectedTipoTarefa.get_Descricao())); + this.TiposTarefa.Remove(this.SelectedTipoTarefa); + this.TiposTarefaFiltrados.Remove(this.SelectedTipoTarefa); + Recursos.TiposTarefa.Remove(this.SelectedTipoTarefa); + this.SelectedTipoTarefa = this.TiposTarefaFiltrados.FirstOrDefault(); + await this.SelecionaTipoTarefa(); + base.Loading(false); + base.ToggleSnackBar("TIPO DE TAREFA EXCLUÍDO COM SUCESSO", true); + } + else + { + base.Loading(false); + } + } + } + } + + public async Task> Filtrar(string value) + { + List tipoDeTarefas = await Task.Run>(() => this.FiltrarTipoTarefa(value)); + return tipoDeTarefas; + } + + public List FiltrarTipoTarefa(string filter) + { + this.TiposTarefaFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.TiposTarefa) : new ObservableCollection( + from x in this.TiposTarefa + where ValidationHelper.RemoveDiacritics(x.get_Nome().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby x.get_Ativo() descending, x.get_Nome() + select x)); + this.SelectedTipoTarefa = this.TiposTarefaFiltrados.FirstOrDefault(); + return this.TiposTarefaFiltrados.ToList(); + } + + public void Incluir() + { + TipoDeTarefa tipoDeTarefa = new TipoDeTarefa(); + tipoDeTarefa.set_Ativo(true); + tipoDeTarefa.set_Excluido(false); + this.SelectedTipoTarefa = tipoDeTarefa; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + object obj; + string str1; + List> keyValuePairs1 = this.SelectedTipoTarefa.Validate(); + keyValuePairs1.AddRange(this.Validate()); + if (keyValuePairs1.Count <= 0) + { + str = (this.SelectedTipoTarefa.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str1 = str; + TipoDeTarefa tipoDeTarefa = await this._servico.Save(this.SelectedTipoTarefa); + if (this._servico.Sucesso) + { + TipoTarefaViewModel tipoTarefaViewModel = this; + string str2 = string.Concat(str1, " TIPO DE TAREFA \"", tipoDeTarefa.get_Nome(), "\""); + long id = tipoDeTarefa.get_Id(); + TipoTela? nullable = new TipoTela?(52); + object id1 = tipoDeTarefa.get_Id(); + obj = (tipoDeTarefa.get_Ativo() ? "SIM" : "NÃO"); + tipoTarefaViewModel.RegistrarAcao(str2, id, nullable, string.Format("ID: {0}\nATIVO: {1}\nDESCRIÇÃO: \"{2}\"", id1, obj, tipoDeTarefa.get_Descricao())); + if (!this.TiposTarefa.Any((TipoDeTarefa x) => x.get_Id() == tipoDeTarefa.get_Id())) + { + this.TiposTarefa.Add(tipoDeTarefa); + } + else + { + DomainBase.Copy(this.TiposTarefa.First((TipoDeTarefa x) => x.get_Id() == tipoDeTarefa.get_Id()), tipoDeTarefa); + } + if (!this.TiposTarefaFiltrados.Any((TipoDeTarefa x) => x.get_Id() == tipoDeTarefa.get_Id())) + { + this.TiposTarefaFiltrados.Add(tipoDeTarefa); + } + else + { + DomainBase.Copy(this.TiposTarefaFiltrados.First((TipoDeTarefa x) => x.get_Id() == tipoDeTarefa.get_Id()), tipoDeTarefa); + } + this.TiposTarefaFiltrados = new ObservableCollection(this.TiposTarefaFiltrados); + this.WorkOnSelectedTipoTarefa(tipoDeTarefa, false); + Recursos.TiposTarefa = this.TiposTarefa; + base.Alterar(false); + base.ToggleSnackBar("TIPO DE TAREFA SALVO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str1 = null; + return keyValuePairs; + } + + private async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(52); + await this.SelecionaTipoTarefa(); + base.Loading(false); + } + + private async Task SelecionaTipoTarefa() + { + base.Loading(true); + List tipoDeTarefas = await this._servico.BuscarTarefas(); + TipoTarefaViewModel list = this; + List tipoDeTarefas1 = tipoDeTarefas; + IEnumerable excluido = + from x in tipoDeTarefas1 + where !x.get_Excluido() + select x; + IOrderedEnumerable ativo = + from x in excluido + orderby x.get_Ativo() descending + select x; + list.TiposTarefa = ativo.ThenBy((TipoDeTarefa x) => x.get_Nome()).ToList(); + this.TiposTarefaFiltrados = new ObservableCollection(this.TiposTarefa); + this.SelectedTipoTarefa = this.TiposTarefaFiltrados.FirstOrDefault(); + base.Loading(false); + } + + public List> Validate() + { + List> keyValuePairs = new List>(); + if (string.IsNullOrWhiteSpace(this.SelectedTipoTarefa.get_Nome())) + { + return keyValuePairs; + } + if (this.TiposTarefa.Any((TipoDeTarefa x) => { + if (!x.get_Nome().Contains(this.SelectedTipoTarefa.get_Nome())) + { + return false; + } + return x.get_Id() != this.SelectedTipoTarefa.get_Id(); + })) + { + keyValuePairs.Add(new KeyValuePair("Nome", "UM TIPO DE TAREFA COM O MESMO NOME JÁ EXISTE.")); + } + return keyValuePairs; + } + + private void WorkOnSelectedTipoTarefa(TipoDeTarefa value, bool registrar = true) + { + long? nullable; + this.CancelTipoTarefa = (value == null || value.get_Id() == 0 ? this.CancelTipoTarefa : (TipoDeTarefa)value.Clone()); + if (value == null || value.get_Id() == 0 || this.LastAccessId == value.get_Id() && this.LastAccessTela == 52) + { + return; + } + if (registrar) + { + base.RegistrarAcao(string.Concat("ACESSOU TIPO DE TAREFA \"", value.get_Nome(), "\""), value.get_Id(), new TipoTela?(52), string.Format("ID: {0}\nATIVO: {1}\nDESCRIÇÃO: \"{2}\"", value.get_Id(), (value.get_Ativo() ? "SIM" : "NÃO"), value.get_Descricao())); + } + this.LastAccessId = value.get_Id(); + this.LastAccessTela = 52; + TipoDeTarefa selectedTipoTarefa = this.SelectedTipoTarefa; + if (selectedTipoTarefa != null) + { + nullable = new long?(selectedTipoTarefa.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long id = value.get_Id(); + if (nullable1.GetValueOrDefault() != id | !nullable1.HasValue) + { + this.SelectedTipoTarefa = this.TiposTarefaFiltrados.FirstOrDefault((TipoDeTarefa x) => x.get_Id() == value.get_Id()); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/TipoVendedorViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/TipoVendedorViewModel.cs new file mode 100644 index 0000000..c4ff8bc --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/TipoVendedorViewModel.cs @@ -0,0 +1,338 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class TipoVendedorViewModel : BaseSegurosViewModel + { + private readonly TipoVendedorServico _servico; + + public TipoVendedor CancelTipoVendedor; + + private Visibility _ativoVisibility = Visibility.Collapsed; + + private TipoVendedor _selectedTipoVendedor = new TipoVendedor(); + + private ObservableCollection _tipoVendedoresFiltrados = new ObservableCollection(); + + private bool _isExpanded; + + public Visibility AtivoVisibility + { + get + { + return this._ativoVisibility; + } + set + { + this._ativoVisibility = value; + base.OnPropertyChanged("AtivoVisibility"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public TipoVendedor SelectedTipoVendedor + { + get + { + return this._selectedTipoVendedor; + } + set + { + long? nullable; + this._selectedTipoVendedor = value; + this.WorkOnSelectedTipoVendedor(value, true); + this.AtivoVisibility = ((value != null ? value.get_Id() != (long)1 : true) ? Visibility.Visible : Visibility.Collapsed); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedTipoVendedor"); + } + } + + public List TipoVendedores + { + get; + set; + } + + public ObservableCollection TipoVendedoresFiltrados + { + get + { + return this._tipoVendedoresFiltrados; + } + set + { + this._tipoVendedoresFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("TipoVendedoresFiltrados"); + } + } + + public TipoVendedorViewModel() + { + this._servico = new TipoVendedorServico(); + base.EnableMenu = true; + this.Seleciona(); + } + + public void CancelarAlteracao() + { + if (this.CancelTipoVendedor == null || !this.TipoVendedores.Any((TipoVendedor x) => x.get_Id() == this.CancelTipoVendedor.get_Id())) + { + this.Incluir(); + } + else + { + DomainBase.Copy(this.TipoVendedores.First((TipoVendedor x) => x.get_Id() == this.CancelTipoVendedor.get_Id()), this.CancelTipoVendedor); + if (this.TipoVendedoresFiltrados.Count <= 0 || !this.TipoVendedoresFiltrados.Any((TipoVendedor x) => x.get_Id() == this.CancelTipoVendedor.get_Id())) + { + this.TipoVendedoresFiltrados.Add(this.CancelTipoVendedor); + } + else + { + DomainBase.Copy(this.TipoVendedoresFiltrados.First((TipoVendedor x) => x.get_Id() == this.CancelTipoVendedor.get_Id()), this.CancelTipoVendedor); + } + this.TipoVendedoresFiltrados = new ObservableCollection(this.TipoVendedoresFiltrados); + this.SelectedTipoVendedor = this.TipoVendedoresFiltrados.First((TipoVendedor x) => x.get_Id() == this.CancelTipoVendedor.get_Id()); + } + base.Alterar(false); + } + + public async void Excluir() + { + object obj; + TipoVendedor tipoVendedor; + if (this.SelectedTipoVendedor != null && this.SelectedTipoVendedor.get_Id() != 0 && this.SelectedTipoVendedor.get_Id() != (long)1) + { + if (await (new BaseServico()).TipoVendedorUtilizado(this.SelectedTipoVendedor.get_Id())) + { + await base.ShowMessage("TIPO VENDEDOR NÃO PODE SER EXCLUÍDO POIS ESTÁ SENDO UTILIZADO.", "OK", "", false); + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + base.Loading(true); + if (await this._servico.Delete(this.SelectedTipoVendedor)) + { + TipoVendedorViewModel tipoVendedorViewModel = this; + string str = string.Concat("EXCLUIU TIPO VENDEDOR \"", this.SelectedTipoVendedor.get_Descricao(), "\""); + long id = this.SelectedTipoVendedor.get_Id(); + TipoTela? nullable = new TipoTela?(14); + object id1 = this.SelectedTipoVendedor.get_Id(); + obj = (!this.SelectedTipoVendedor.get_Ativo().HasValue || !this.SelectedTipoVendedor.get_Ativo().Value ? "NÃO" : "SIM"); + tipoVendedorViewModel.RegistrarAcao(str, id, nullable, string.Format("ID: {0}\nATIVO: {1}", id1, obj)); + int num = this.TipoVendedoresFiltrados.IndexOf(this.SelectedTipoVendedor); + this.TipoVendedores.Remove(this.SelectedTipoVendedor); + this.TipoVendedoresFiltrados.Remove(this.SelectedTipoVendedor); + this.TipoVendedoresFiltrados = new ObservableCollection(this.TipoVendedoresFiltrados); + if (this.TipoVendedoresFiltrados.Count <= 0) + { + this.SelectedTipoVendedor = new TipoVendedor(); + base.Alterar(false); + base.EnableMenu = false; + } + else + { + TipoVendedorViewModel tipoVendedorViewModel1 = this; + tipoVendedor = (num < this.TipoVendedoresFiltrados.Count ? this.TipoVendedoresFiltrados.ElementAt(num) : this.TipoVendedoresFiltrados.Last()); + tipoVendedorViewModel1.SelectedTipoVendedor = tipoVendedor; + } + Recursos.TipoVendedor = this.TipoVendedores; + base.Loading(false); + base.ToggleSnackBar("TIPO VENDEDOR EXCLUÍDO COM SUCESSO", true); + } + else + { + base.Loading(false); + } + } + } + } + + internal async Task> Filtrar(string value) + { + List tipoVendedors = await Task.Run>(() => this.FiltrarTipoVendedor(value)); + return tipoVendedors; + } + + public List FiltrarTipoVendedor(string filter) + { + this.TipoVendedoresFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.TipoVendedores) : new ObservableCollection( + from x in this.TipoVendedores + where ValidationHelper.RemoveDiacritics(x.get_Descricao().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby x.get_Ativo() descending, x.get_Descricao() + select x)); + this.SelectedTipoVendedor = this.TipoVendedoresFiltrados.FirstOrDefault(); + return this.TipoVendedoresFiltrados.ToList(); + } + + public void Incluir() + { + TipoVendedor tipoVendedor = new TipoVendedor(); + tipoVendedor.set_Ativo(new bool?(true)); + tipoVendedor.set_Inserido(new bool?(false)); + this.SelectedTipoVendedor = tipoVendedor; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + object obj; + string str1; + List> keyValuePairs1 = this.SelectedTipoVendedor.Validate(); + if (keyValuePairs1.Count <= 0) + { + str = (this.SelectedTipoVendedor.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str1 = str; + TipoVendedor tipoVendedor = await this._servico.Save(this.SelectedTipoVendedor); + if (this._servico.Sucesso) + { + TipoVendedorViewModel tipoVendedorViewModel = this; + string str2 = string.Concat(str1, " TIPO VENDEDOR \"", tipoVendedor.get_Descricao(), "\""); + long id = tipoVendedor.get_Id(); + TipoTela? nullable = new TipoTela?(14); + object id1 = tipoVendedor.get_Id(); + obj = (!tipoVendedor.get_Ativo().HasValue || !tipoVendedor.get_Ativo().Value ? "NÃO" : "SIM"); + tipoVendedorViewModel.RegistrarAcao(str2, id, nullable, string.Format("ID: {0}\nATIVO: {1}", id1, obj)); + if (!this.TipoVendedores.Any((TipoVendedor x) => x.get_Id() == tipoVendedor.get_Id())) + { + this.TipoVendedores.Add(tipoVendedor); + } + else + { + DomainBase.Copy(this.TipoVendedores.First((TipoVendedor x) => x.get_Id() == tipoVendedor.get_Id()), tipoVendedor); + } + if (!this.TipoVendedoresFiltrados.Any((TipoVendedor x) => x.get_Id() == tipoVendedor.get_Id())) + { + this.TipoVendedoresFiltrados.Add(tipoVendedor); + } + else + { + DomainBase.Copy(this.TipoVendedoresFiltrados.First((TipoVendedor x) => x.get_Id() == tipoVendedor.get_Id()), tipoVendedor); + } + this.TipoVendedoresFiltrados = new ObservableCollection(this.TipoVendedoresFiltrados); + this.WorkOnSelectedTipoVendedor(tipoVendedor, false); + Recursos.TipoVendedor = this.TipoVendedores; + base.Alterar(false); + base.ToggleSnackBar("TIPO VENDEDOR SALVO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str1 = null; + return keyValuePairs; + } + + public async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(14); + await this.SelecionaTipoVendedores(); + base.Loading(false); + } + + public void SelecionaTipoVendedor(TipoVendedor tipoVendedor) + { + this.SelectedTipoVendedor = tipoVendedor; + } + + private async Task SelecionaTipoVendedores() + { + base.Loading(true); + List tipoVendedors = await (new BaseServico()).BuscarTipoVendedoresAsync(); + TipoVendedorViewModel list = this; + List tipoVendedors1 = tipoVendedors; + IOrderedEnumerable ativo = + from x in tipoVendedors1 + orderby x.get_Ativo() descending + select x; + list.TipoVendedores = ativo.ThenBy((TipoVendedor x) => x.get_Descricao()).ToList(); + this.TipoVendedoresFiltrados = new ObservableCollection(this.TipoVendedores); + if (this.TipoVendedoresFiltrados.Count <= 0) + { + this.SelectedTipoVendedor = new TipoVendedor(); + base.Alterar(false); + base.EnableMenu = false; + } + else + { + this.SelecionaTipoVendedor(this.TipoVendedoresFiltrados.First()); + } + Recursos.TipoVendedor = tipoVendedors; + base.Loading(false); + } + + private void WorkOnSelectedTipoVendedor(TipoVendedor value, bool registrar = true) + { + long? nullable; + this.CancelTipoVendedor = (value == null || value.get_Id() == 0 ? this.CancelTipoVendedor : (TipoVendedor)value.Clone()); + if (value == null || value.get_Id() == 0 || this.LastAccessId == value.get_Id() && this.LastAccessTela == 14) + { + return; + } + if (registrar) + { + base.RegistrarAcao(string.Concat("ACESSOU TIPO VENDEDOR \"", value.get_Descricao(), "\""), value.get_Id(), new TipoTela?(14), string.Format("ID: {0}\nATIVO: {1}", value.get_Id(), (!value.get_Ativo().HasValue || !value.get_Ativo().Value ? "NÃO" : "SIM"))); + } + this.LastAccessId = value.get_Id(); + this.LastAccessTela = 14; + TipoVendedor selectedTipoVendedor = this.SelectedTipoVendedor; + if (selectedTipoVendedor != null) + { + nullable = new long?(selectedTipoVendedor.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long id = value.get_Id(); + if (nullable1.GetValueOrDefault() != id | !nullable1.HasValue) + { + this.SelectedTipoVendedor = this.TipoVendedoresFiltrados.FirstOrDefault((TipoVendedor x) => x.get_Id() == value.get_Id()); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/UsuarioViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/UsuarioViewModel.cs new file mode 100644 index 0000000..7f04040 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/UsuarioViewModel.cs @@ -0,0 +1,826 @@ +using Agger.Registro; +using Gestor.Application.Actions; +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Helpers; +using Gestor.Common.Security; +using Gestor.Common.Validation; +using Gestor.Model.API; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using MaterialDesignThemes.Wpf; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Net.Http; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class UsuarioViewModel : BaseSegurosViewModel + { + private readonly UsuarioServico _servico; + + private readonly PermissaoUsuarioServico _permissaoUsuarioServico; + + public Usuario CancelUsuario; + + private string _inicioAcesso; + + private string _fimAcesso; + + private Usuario _selectedUsuario; + + private Empresa _selectedFilial; + + private bool _cartaoCriado; + + private ObservableCollection _usuariosFiltrados = new ObservableCollection(); + + private bool _isExpanded; + + private bool _enableGrid = true; + + private Visibility _horarioAcessoVisible; + + private List _empresas = Recursos.Empresas; + + private string _confirmaSenha; + + private string _labelCartao; + + public Visibility AddUsuarioCentralSeguradoVisibility { get; set; } = (string.IsNullOrEmpty(Connection.UrlCentralSegurado) ? Visibility.Collapsed : Visibility.Visible); + + public bool CartaoCriado + { + get + { + return this._cartaoCriado; + } + set + { + this._cartaoCriado = value; + base.OnPropertyChanged("CartaoCriado"); + } + } + + public string ConfirmaSenha + { + get + { + return this._confirmaSenha; + } + set + { + this._confirmaSenha = value; + base.OnPropertyChanged("ConfirmaSenha"); + } + } + + public static DrawerHost Drawer + { + get; + set; + } + + public List Empresas + { + get + { + return this._empresas; + } + set + { + this._empresas = value; + base.OnPropertyChanged("Empresas"); + } + } + + public bool EnableGrid + { + get + { + return this._enableGrid; + } + set + { + this._enableGrid = value; + base.OnPropertyChanged("EnableGrid"); + } + } + + public string FimAcesso + { + get + { + return this._fimAcesso; + } + set + { + this._fimAcesso = value; + base.OnPropertyChanged("FimAcesso"); + } + } + + public Visibility HorarioAcessoVisible + { + get + { + return this._horarioAcessoVisible; + } + set + { + this._horarioAcessoVisible = value; + base.OnPropertyChanged("HorarioAcessoVisible"); + } + } + + public string InicioAcesso + { + get + { + return this._inicioAcesso; + } + set + { + this._inicioAcesso = value; + base.OnPropertyChanged("InicioAcesso"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public string LabelCartao + { + get + { + return this._labelCartao; + } + set + { + this._labelCartao = value; + base.OnPropertyChanged("LabelCartao"); + } + } + + public List PermissaoUsuario + { + get; + set; + } + + public Empresa SelectedFilial + { + get + { + return this._selectedFilial; + } + set + { + this._selectedFilial = value; + base.OnPropertyChanged("SelectedFilial"); + } + } + + public Usuario SelectedUsuario + { + get + { + return this._selectedUsuario; + } + set + { + long? nullable; + this._selectedUsuario = value; + this.WorkOnSelectedUsuario(value, true); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedUsuario"); + } + } + + private string SenhaOriginal + { + get; + set; + } + + public List Usuarios + { + get; + set; + } + + public ObservableCollection UsuariosFiltrados + { + get + { + return this._usuariosFiltrados; + } + set + { + this._usuariosFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("UsuariosFiltrados"); + } + } + + public UsuarioViewModel() + { + this._servico = new UsuarioServico(); + this._permissaoUsuarioServico = new PermissaoUsuarioServico(); + base.EnableMenu = true; + } + + public async Task AddUsuarioAdiministadorCentralSegurado() + { + string str; + string str1; + string str2; + string str3; + string str4; + string str5; + string str6; + string str7; + if (this.SelectedUsuario != null) + { + base.Loading(true); + str7 = "USUÁRIO CADASTRADO/ALTERADO COM SUCESSO!"; + try + { + str = (this.SelectedUsuario.get_Telefone() == null ? string.Empty : string.Concat("(", this.SelectedUsuario.get_Prefixo(), ") ", this.SelectedUsuario.get_Telefone())); + string str8 = str; + Token token = new Token(); + UsuarioCentralSegurado usuarioCentralSegurado = new UsuarioCentralSegurado(); + usuarioCentralSegurado.set_Id(""); + usuarioCentralSegurado.set_Senha(""); + usuarioCentralSegurado.set_Serial(token.Encrypt(Recursos.Empresa.get_Serial())); + usuarioCentralSegurado.set_FornecedorId(ApplicationHelper.IdFornecedor); + usuarioCentralSegurado.set_Nome(token.Encrypt(this.SelectedUsuario.get_Nome())); + usuarioCentralSegurado.set_Documento(token.Encrypt(this.SelectedUsuario.get_Documento().Clear())); + usuarioCentralSegurado.set_Email(token.Encrypt(this.SelectedUsuario.get_Email())); + usuarioCentralSegurado.set_IdEmpresa(this.SelectedUsuario.get_IdEmpresa()); + usuarioCentralSegurado.set_Telefone(token.Encrypt(str8)); + str1 = (this.SelectedUsuario.get_Cidade() != null ? token.Encrypt(this.SelectedUsuario.get_Endereco()) : string.Empty); + usuarioCentralSegurado.set_Rua(str1); + str2 = (this.SelectedUsuario.get_Cidade() != null ? token.Encrypt(this.SelectedUsuario.get_Numero()) : string.Empty); + usuarioCentralSegurado.set_Numero(str2); + str3 = (this.SelectedUsuario.get_Cidade() != null ? token.Encrypt(this.SelectedUsuario.get_Bairro()) : string.Empty); + usuarioCentralSegurado.set_Bairro(str3); + str4 = (this.SelectedUsuario.get_Cidade() != null ? token.Encrypt(this.SelectedUsuario.get_Cidade()) : string.Empty); + usuarioCentralSegurado.set_Cidade(str4); + str5 = (this.SelectedUsuario.get_Cidade() != null ? token.Encrypt(this.SelectedUsuario.get_Estado()) : string.Empty); + usuarioCentralSegurado.set_Estado(str5); + str6 = (this.SelectedUsuario.get_Cidade() != null ? token.Encrypt(this.SelectedUsuario.get_Cep()) : string.Empty); + usuarioCentralSegurado.set_Cep(str6); + usuarioCentralSegurado.set_Corretora(token.Encrypt(Recursos.Empresa.get_Nome())); + usuarioCentralSegurado.set_UriCorretora(token.Encrypt(Connection.UrlCentralSegurado)); + usuarioCentralSegurado.set_Admin(this.SelectedUsuario.get_AdministradorCentralSegurado()); + UsuarioCentralSegurado usuarioCentralSegurado1 = usuarioCentralSegurado; + using (HttpClient httpClient = new HttpClient()) + { + StringContent stringContent = new StringContent(JsonConvert.SerializeObject(usuarioCentralSegurado1), Encoding.UTF8, "application/json"); + Uri centralSegurado = Address.get_CentralSegurado(); + string[] strArrays = new string[] { "Usuario" }; + Uri uri = centralSegurado.Append(strArrays); + string[] strArrays1 = new string[] { "AddAggerApp" }; + Uri uri1 = uri.Append(strArrays1); + HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(uri1, stringContent); + await this._servico.AddCentralSegurado(this.SelectedUsuario.get_Id(), httpResponseMessage.get_IsSuccessStatusCode()); + if (!httpResponseMessage.get_IsSuccessStatusCode()) + { + string str9 = await httpResponseMessage.get_Content().ReadAsStringAsync(); + str7 = string.Concat("HOUVE(RAM) O(S) SEGUINTE(S) ERROS: ", str9.Replace(";", ", ").ToUpper()); + } + httpResponseMessage = null; + } + httpClient = null; + } + catch + { + str7 = "HOUVERAM ERROS AO CADASTRAR/ALTERAR O USUÁRIO!"; + } + base.Loading(false); + await base.ShowMessage(str7, "OK", "", false); + } + str7 = null; + } + + public async Task AlterarUsuario() + { + if (this.SelectedUsuario != null) + { + Usuario usuario = await this._servico.BuscarUsuarioPorId(this.SelectedUsuario.get_Id()); + this.SenhaOriginal = (new Token()).AggerDecrypt(usuario.get_Senha()); + await this.SelecionaUsuario(this.SelectedUsuario); + } + } + + public async void AtualizaUsuario() + { + if (!base.EnableFields) + { + await this.CarregarUsuarios(); + } + } + + private async Task BuscaAlteracaoUsuarios(long idUsuario) + { + bool flag; + bool valueOrDefault; + bool flag1; + bool? nullable; + Usuario usuario = await (new UsuarioServico()).BuscarUsuarioPorId(idUsuario); + if (usuario == null) + { + valueOrDefault = false; + } + else + { + if (usuario != null) + { + nullable = new bool?(usuario.get_AdministradorCentralSegurado()); + } + else + { + nullable = null; + } + bool? nullable1 = nullable; + bool administradorCentralSegurado = this.SelectedUsuario.get_AdministradorCentralSegurado(); + valueOrDefault = !(nullable1.GetValueOrDefault() == administradorCentralSegurado & nullable1.HasValue); + } + bool flag2 = valueOrDefault; + flag1 = (flag2 || !this.SelectedUsuario.get_AdministradorCentralSegurado() ? false : this.SelectedUsuario.get_Id() == (long)0); + bool flag3 = flag1; + List usuarios = this.Usuarios; + IEnumerable administradorCentralSegurado1 = + from x in usuarios + where x.get_AdministradorCentralSegurado() + select x; + List list = ( + from x in administradorCentralSegurado1 + orderby x.get_Nome() + select x).ToList(); + if (flag2 && !flag3 && list.Count == 0) + { + if (!await base.ShowMessage("ESTE USUÁRIO É O ÚNICO ADM DA CENTRAL DO SEGURADO.\nTEM CERTEZA QUE DESEJA REMOVER?", "SIM", "CANCELAR", false)) + { + this.CancelarAlteracao(); + flag = false; + return flag; + } + } + if (!(flag3 | flag2) || !string.IsNullOrEmpty(Connection.UrlCentralSegurado)) + { + flag = flag2 | flag3; + } + else + { + if (this.SelectedUsuario != null) + { + this.SelectedUsuario.set_AdministradorCentralSegurado(false); + } + await base.ShowMessage("NÃO FOI POSSÍVEL ADICIONAR UM USUÁRIO ADM CENTRAL SEGURADO, POR FAVOR ENTRE EM CONTATO COM O SUPORTE AGGER. \nURL AUSENTE!", "OK", "", false); + flag = false; + } + return flag; + } + + private async Task BuscaPermissao() + { + this.PermissaoUsuario = await this._permissaoUsuarioServico.PermissUsuario(Recursos.Usuario); + } + + public async Task CancelarAlteracao() + { + long id; + await this.CarregarUsuarios(); + if (!this.UsuariosFiltrados.Any()) + { + this.SelectedUsuario = new Usuario(); + base.Alterar(false); + base.EnableMenu = false; + } + else + { + Usuario cancelUsuario = this.CancelUsuario; + if (cancelUsuario != null) + { + id = cancelUsuario.get_Id(); + } + else + { + id = (long)0; + } + long num = id; + this.SelectedUsuario = this.UsuariosFiltrados.FirstOrDefault((Usuario x) => x.get_Id() == num); + } + base.Alterar(false); + this.ConfirmaSenha = ""; + } + + private async Task CarregarUsuarios() + { + List usuarios = await (new BaseServico()).CarregarUsuarios(); + UsuarioViewModel list = this; + List usuarios1 = usuarios; + IEnumerable usuarios2 = usuarios1.Where((Usuario x) => { + if (x.get_Excluido()) + { + return false; + } + long? permissaoAggilizador = x.get_PermissaoAggilizador(); + long num = (long)4; + return !(permissaoAggilizador.GetValueOrDefault() == num & permissaoAggilizador.HasValue); + }); + list.Usuarios = ( + from x in usuarios2 + orderby x.get_Nome() + select x).ToList(); + this.UsuariosFiltrados = new ObservableCollection(this.Usuarios); + await this.BuscaPermissao(); + } + + public async Task CriarCartao(bool dadosUsuario) + { + await base.ShowMessage("CARTÃO CRIADO/ATUALIZADO COM SUCESSO", "OK", "", false); + } + + public async Task Excluir() + { + if (this.SelectedUsuario != null && this.SelectedUsuario.get_Id() != 0) + { + if (await (new VendedorUsuarioServico()).FindVinculoByUsuario(this.SelectedUsuario.get_Id())) + { + await base.ShowMessage("O USUÁRIO POSSUI VÍNCULO DE VENDEDOR, REMOVA O VÍNCULO ANTES DE EXCLUIR.", "OK", "", false); + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + base.Loading(true); + if (await this._servico.Delete(this.SelectedUsuario)) + { + base.RegistrarAcao(string.Concat("EXCLUIU USUÁRIO \"", this.SelectedUsuario.get_Nome(), "\""), this.SelectedUsuario.get_Id(), new TipoTela?(16), string.Format("ID: {0}", this.SelectedUsuario.get_Id())); + await this.CarregarUsuarios(); + if (!this.UsuariosFiltrados.Any()) + { + this.SelectedUsuario = new Usuario(); + base.Alterar(false); + base.EnableMenu = false; + } + else + { + this.SelectedUsuario = this.UsuariosFiltrados.FirstOrDefault(); + } + base.Loading(false); + base.ToggleSnackBar("USUÁRIO EXCLUÍDO COM SUCESSO", true); + } + else + { + base.Loading(false); + } + } + } + } + + internal async Task> Filtrar(string value) + { + List usuarios = await Task.Run>(() => this.FiltrarUsuario(value)); + return usuarios; + } + + public List FiltrarUsuario(string filter) + { + this.UsuariosFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Usuarios) : new ObservableCollection( + from x in this.Usuarios + where ValidationHelper.RemoveDiacritics(x.get_Nome().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby !x.get_Excluido() descending, x.get_Nome() + select x)); + return this.UsuariosFiltrados.ToList(); + } + + public void Incluir() + { + Usuario usuario = new Usuario(); + usuario.set_IdEmpresa(Recursos.Usuario.get_IdEmpresa()); + usuario.set_Segunda(new bool?(true)); + usuario.set_Terca(new bool?(true)); + usuario.set_Quarta(new bool?(true)); + usuario.set_Quinta(new bool?(true)); + usuario.set_Sexta(new bool?(true)); + usuario.set_Sabado(new bool?(true)); + usuario.set_Domingo(new bool?(true)); + usuario.set_Excluido(false); + usuario.set_FiltroInicial(new TipoFiltroCliente?(0)); + this.SelectedUsuario = usuario; + this.SenhaOriginal = null; + base.Alterar(true); + } + + public async Task OpenPermissao() + { + bool selectedUsuario = this.SelectedUsuario == null; + if (selectedUsuario) + { + selectedUsuario = await base.ShowMessage("É NECESSÁRIO SELECIONAR UM USUÁRIO!", "OK", "", false); + } + if (!selectedUsuario) + { + Gestor.Application.Actions.Actions.AtualizaUsuario = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.AtualizaUsuario, new Action(this.AtualizaUsuario)); + Gestor.Application.Actions.Actions.AtualizaUsuario = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.AtualizaUsuario, new Action(this.AtualizaUsuario)); + base.ShowDrawer(new PermissaoUsuarioDrawer(this.SelectedUsuario), 0, false); + } + } + + public async Task OpenVinculo() + { + bool selectedUsuario = this.SelectedUsuario == null; + if (selectedUsuario) + { + selectedUsuario = await base.ShowMessage("É NECESSÁRIO SELECIONAR UM USUÁRIO!", "OK", "", false); + } + if (!selectedUsuario) + { + base.ShowDrawer(new VinculoVendedorDrawer(this.SelectedUsuario), 0, true); + } + } + + public async Task>> Salvar() + { + List> keyValuePairs; + DateTime dateTime; + DateTime dateTime1; + string str; + long num; + string str1; + string str2; + if (!DateTime.TryParse(this.InicioAcesso, out dateTime) || !DateTime.TryParse(this.FimAcesso, out dateTime1)) + { + DateTime? nullable = null; + this.SelectedUsuario.set_InicioAcesso(nullable); + nullable = null; + this.SelectedUsuario.set_FimAcesso(nullable); + } + else + { + this.SelectedUsuario.set_InicioAcesso(new DateTime?(dateTime)); + this.SelectedUsuario.set_FimAcesso(new DateTime?(dateTime1)); + } + Usuario selectedUsuario = this.SelectedUsuario; + str = (!string.IsNullOrEmpty(this.SelectedUsuario.get_Senha()) ? this.SelectedUsuario.get_Senha() : this.SenhaOriginal); + selectedUsuario.set_Senha(str); + List> keyValuePairs1 = this.SelectedUsuario.Validate(); + List> keyValuePairs2 = keyValuePairs1; + keyValuePairs2.AddRange(await this.Validate()); + keyValuePairs2 = null; + if (keyValuePairs1.Count <= 0) + { + this.SelectedUsuario.set_Senha((new Token()).AggerEncrypt(this.SelectedUsuario.get_Senha())); + Usuario usuario = this.SelectedUsuario; + num = (this.SelectedUsuario.get_IdEmpresa() == 0 ? Recursos.Usuario.get_IdEmpresa() : this.SelectedUsuario.get_IdEmpresa()); + usuario.set_IdEmpresa(num); + bool flag = await this.BuscaAlteracaoUsuarios(this.SelectedUsuario.get_Id()); + str1 = (this.SelectedUsuario.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str2 = str1; + Usuario usuario1 = await this._servico.Save(this.SelectedUsuario); + if (this._servico.Sucesso) + { + base.RegistrarAcao(string.Concat(str2, " USUÁRIO \"", usuario1.get_Nome(), "\""), usuario1.get_Id(), new TipoTela?(16), string.Format("ID: {0}", usuario1.get_Id())); + if (flag) + { + await this.AddUsuarioAdiministadorCentralSegurado(); + } + await this.CarregarUsuarios(); + this.SelectedUsuario = this.UsuariosFiltrados.FirstOrDefault((Usuario x) => x.get_Id() == usuario1.get_Id()); + Recursos.Usuarios = this.Usuarios; + this.ConfirmaSenha = ""; + base.Alterar(false); + base.ToggleSnackBar("USUÁRIO SALVO COM SUCESSO", true); + this.IsExpanded = true; + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + keyValuePairs1 = null; + str2 = null; + return keyValuePairs; + } + + public async Task Seleciona() + { + Visibility visibility; + UsuarioViewModel usuarioViewModel = this; + visibility = (base.Restricao(94) ? Visibility.Collapsed : Visibility.Visible); + usuarioViewModel.HorarioAcessoVisible = visibility; + await base.PermissaoTela(16); + await this.SelecionaUsuarios(); + } + + public async Task SelecionaUsuario(Usuario usuario) + { + Usuario usuario1 = await this._servico.BuscarUsuarioPorId(usuario.get_Id()); + bool? segunda = usuario1.get_Segunda(); + usuario1.set_Segunda(new bool?(segunda.GetValueOrDefault(true))); + segunda = usuario1.get_Terca(); + usuario1.set_Terca(new bool?(segunda.GetValueOrDefault(true))); + segunda = usuario1.get_Quarta(); + usuario1.set_Quarta(new bool?(segunda.GetValueOrDefault(true))); + segunda = usuario1.get_Quinta(); + usuario1.set_Quinta(new bool?(segunda.GetValueOrDefault(true))); + segunda = usuario1.get_Sexta(); + usuario1.set_Sexta(new bool?(segunda.GetValueOrDefault(true))); + segunda = usuario1.get_Sabado(); + usuario1.set_Sabado(new bool?(segunda.GetValueOrDefault(true))); + segunda = usuario1.get_Domingo(); + usuario1.set_Domingo(new bool?(segunda.GetValueOrDefault(true))); + if (Recursos.Usuario.get_Id() == usuario.get_Id()) + { + usuario1.set_Senha((new Token()).AggerDecrypt(usuario1.get_Senha())); + this.SenhaOriginal = usuario1.get_Senha(); + this.ConfirmaSenha = ""; + DomainBase.Copy(this.UsuariosFiltrados.First((Usuario x) => x.get_Id() == usuario.get_Id()), usuario1); + } + this.SelectedUsuario = this.UsuariosFiltrados.First((Usuario x) => x.get_Id() == usuario.get_Id()); + } + + private async Task SelecionaUsuarios() + { + this.EnableGrid = false; + base.Loading(true); + await this.CarregarUsuarios(); + if (this.UsuariosFiltrados.Count <= 0) + { + Usuario usuario = new Usuario(); + usuario.set_Segunda(new bool?(true)); + usuario.set_Terca(new bool?(true)); + usuario.set_Quarta(new bool?(true)); + usuario.set_Quinta(new bool?(true)); + usuario.set_Sexta(new bool?(true)); + usuario.set_Sabado(new bool?(true)); + usuario.set_Domingo(new bool?(true)); + this.SelectedUsuario = usuario; + base.Alterar(false); + base.EnableMenu = false; + } + else + { + await this.SelecionaUsuario(this.UsuariosFiltrados.First()); + } + base.Loading(false); + this.EnableGrid = true; + } + + public async Task>> Validate() + { + List usuarios; + List> keyValuePairs = new List>(); + if (this.SenhaOriginal == null || this.SenhaOriginal != this.SelectedUsuario.get_Senha()) + { + string senha = (new Token()).Decrypt(this.SelectedUsuario.get_Senha()); + if (senha == null) + { + senha = this.SelectedUsuario.get_Senha(); + } + string str = senha; + if (string.IsNullOrWhiteSpace(this.ConfirmaSenha)) + { + keyValuePairs.Add(new KeyValuePair("ConfirmaSenha|CONFIRMAÇÃO SENHA", "OBRIGATÓRIO")); + } + else if (!string.Equals(this.ConfirmaSenha, str)) + { + keyValuePairs.Add(new KeyValuePair("ConfirmaSenha|CONFIRMAÇÃO SENHA", "INVÁLIDO")); + } + } + if (string.IsNullOrWhiteSpace(this.SelectedUsuario.get_Login())) + { + usuarios = new List(); + } + else + { + usuarios = await (new BaseServico()).BuscarUsuarioPorLoginInteiro(this.SelectedUsuario.get_Login()); + } + foreach (Usuario usuario in usuarios) + { + if (usuario.get_Id() == this.SelectedUsuario.get_Id()) + { + continue; + } + keyValuePairs.Add(new KeyValuePair("Login", string.Concat("O LOGIN JÁ ESTÁ CADASTRADO PARA O USUÁRIO \"", usuario.get_Nome(), "\"."))); + } + if (this.SelectedUsuario.get_InicioAcesso().HasValue && !this.SelectedUsuario.get_FimAcesso().HasValue) + { + keyValuePairs.Add(new KeyValuePair("FIM DO ACESSO", "NECESSÁRIO PREENCHER O CAMPO FIM DO ACESSO!")); + } + if (!this.SelectedUsuario.get_InicioAcesso().HasValue && this.SelectedUsuario.get_FimAcesso().HasValue) + { + keyValuePairs.Add(new KeyValuePair("INÍCIO DO ACESSO", "NECESSÁRIO PREENCHER O CAMPO INÍCIO DO ACESSO!")); + } + bool flag = !string.IsNullOrWhiteSpace(this.SelectedUsuario.get_Documento()); + if (flag) + { + flag = await (new BaseServico()).BuscarUsuarioMesmoDocumento(ValidationHelper.OnlyNumber(this.SelectedUsuario.get_Documento()), this.SelectedUsuario.get_Id(), this.SelectedUsuario.get_IdEmpresa()); + } + if (flag) + { + keyValuePairs.Add(new KeyValuePair("Documento", "O DOCUMENTO JÁ ESTÁ SENDO USADO EM OUTRO USUÁRIO")); + } + List> keyValuePairs1 = keyValuePairs; + keyValuePairs = null; + return keyValuePairs1; + } + + public async Task VerificaUsuarioAdmCentralSegurado() + { + await this.BuscaAlteracaoUsuarios(this.SelectedUsuario.get_Id()); + } + + private void WorkOnSelectedUsuario(Usuario value, bool registrar = true) + { + long? nullable; + this.CartaoCriado = false; + this.CancelUsuario = (value == null || value.get_Id() == 0 ? this.CancelUsuario : (Usuario)value.Clone()); + if (value == null || value.get_Id() == 0) + { + return; + } + value.set_Senha(EncryptionHelper.Decrypt(value.get_Senha())); + if (this.LastAccessId == value.get_Id() && this.LastAccessTela == 16) + { + return; + } + if (registrar) + { + base.RegistrarAcao(string.Concat("ACESSOU USUÁRIO \"", value.get_Nome(), "\""), value.get_Id(), new TipoTela?(16), string.Format("ID USUÁRIO: {0}", value.get_Id())); + } + this.LastAccessId = value.get_Id(); + this.LastAccessTela = 16; + Usuario selectedUsuario = this.SelectedUsuario; + if (selectedUsuario != null) + { + nullable = new long?(selectedUsuario.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long id = value.get_Id(); + if (nullable1.GetValueOrDefault() != id | !nullable1.HasValue) + { + this.SelectedUsuario = this.UsuariosFiltrados.FirstOrDefault((Usuario x) => x.get_Id() == value.get_Id()); + } + if (this.SelectedUsuario.get_InicioAcesso().HasValue && this.SelectedUsuario.get_FimAcesso().HasValue) + { + DateTime? inicioAcesso = this.SelectedUsuario.get_InicioAcesso(); + DateTime dateTime = inicioAcesso.Value; + this.InicioAcesso = dateTime.ToString("HH:mm"); + inicioAcesso = this.SelectedUsuario.get_FimAcesso(); + dateTime = inicioAcesso.Value; + this.FimAcesso = dateTime.ToString("HH:mm"); + } + if (!this.SelectedUsuario.get_InicioAcesso().HasValue && !this.SelectedUsuario.get_FimAcesso().HasValue) + { + this.InicioAcesso = null; + this.FimAcesso = null; + } + this.CartaoCriado = !string.IsNullOrEmpty(value.get_Visita()); + this.LabelCartao = (this.CartaoCriado ? "ATUALIZAR CARTÃO" : "CRIAR CARTÃO"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/VendedorViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/VendedorViewModel.cs new file mode 100644 index 0000000..32b04c4 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/VendedorViewModel.cs @@ -0,0 +1,913 @@ +using CsQuery.ExtensionMethods.Internal; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class VendedorViewModel : BaseSegurosViewModel + { + private readonly VendedorServico _servico; + + public Vendedor CancelVendedor; + + private Vendedor _selectedVendedor; + + private GridLength _gridHeight = new GridLength(1, GridUnitType.Star); + + private GridLength _gridHeight2 = new GridLength(0); + + private ObservableCollection _vendedoresFiltrados = new ObservableCollection(); + + private bool _isExpanded; + + private VendedorTelefone _selectedTelefone = new VendedorTelefone(); + + private ObservableCollection _telefones = new ObservableCollection(); + + private Repasse _selectedRepasse = new Repasse(); + + private ObservableCollection _repasses = new ObservableCollection(); + + private string _pesquisa; + + private Visibility _mostrarRamo; + + private ObservableCollection _ramos = new ObservableCollection(); + + private Visibility _visualizacaoPropriaCorretora { get; set; } = Visibility.Collapsed; + + public bool CoCorretagemAtiva { get; set; } = Recursos.Configuracoes.Any(new Func((// + // Current member / type: System.Boolean Gestor.Application.ViewModels.Ferramentas.VendedorViewModel::CoCorretagemAtiva() + // File path: C:\AggerSeguros\Gestor.Application.exe + // + // Product version: 0.0.0.0 + // Exception in: System.Boolean CoCorretagemAtiva() + // + // Object reference not set to an instance of an object. + // at Telerik.JustDecompiler.Languages.BaseImperativeLanguageWriter.GetArgumentName(ParameterReference parameter) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Languages\BaseImperativeLanguageWriter.cs:line 2276 + // at Telerik.JustDecompiler.Languages.BaseImperativeLanguageWriter.VisitLambdaParameterExpression(LambdaParameterExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Languages\BaseImperativeLanguageWriter.cs:line 4496 + // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 351 + // at Telerik.JustDecompiler.Languages.BaseLanguageWriter.Write(Action writeEntity) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Languages\BaseLanguageWriter.cs:line 339 + // at Telerik.JustDecompiler.Languages.BaseImperativeLanguageWriter.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Languages\BaseImperativeLanguageWriter.cs:line 1133 + // at Telerik.JustDecompiler.Languages.BaseImperativeLanguageWriter.VisitMethodParametersInternal(IList`1 list, Boolean isExtensionMethod) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Languages\BaseImperativeLanguageWriter.cs:line 2769 + // at Telerik.JustDecompiler.Languages.CSharp.CSharpWriter.VisitLambdaExpression(LambdaExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Languages\CSharp\CSharpWriter.cs:line 1077 + // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 351 + // at Telerik.JustDecompiler.Languages.BaseLanguageWriter.Write(Action writeEntity) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Languages\BaseLanguageWriter.cs:line 339 + // at Telerik.JustDecompiler.Languages.BaseImperativeLanguageWriter.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Languages\BaseImperativeLanguageWriter.cs:line 1133 + // at Telerik.JustDecompiler.Languages.BaseImperativeLanguageWriter.VisitDelegateCreationExpression(DelegateCreationExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Languages\BaseImperativeLanguageWriter.cs:line 4667 + // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 351 + // at Telerik.JustDecompiler.Languages.BaseLanguageWriter.Write(Action writeEntity) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Languages\BaseLanguageWriter.cs:line 339 + // at Telerik.JustDecompiler.Languages.BaseImperativeLanguageWriter.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Languages\BaseImperativeLanguageWriter.cs:line 1133 + // at Telerik.JustDecompiler.Languages.BaseImperativeLanguageWriter.VisitMethodParametersInternal(IList`1 list, Boolean isExtensionMethod) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Languages\BaseImperativeLanguageWriter.cs:line 2769 + // at Telerik.JustDecompiler.Languages.BaseImperativeLanguageWriter.VisitMethodInvocationExpression(MethodInvocationExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Languages\BaseImperativeLanguageWriter.cs:line 2750 + // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 351 + // at Telerik.JustDecompiler.Languages.BaseLanguageWriter.Write(Action writeEntity) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Languages\BaseLanguageWriter.cs:line 339 + // at Telerik.JustDecompiler.Languages.BaseImperativeLanguageWriter.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Languages\BaseImperativeLanguageWriter.cs:line 1133 + // at Telerik.JustDecompiler.Languages.BaseImperativeLanguageWriter.WriteInitializedAutoProperty(PropertyDefinition property, Expression assignment) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Languages\BaseImperativeLanguageWriter.cs:line 1457 + // at Telerik.JustDecompiler.Languages.BaseImperativeLanguageWriter.Write(PropertyDefinition property) + // at Telerik.JustDecompiler.Languages.BaseLanguageWriter.WriteInternal(IMemberDefinition member) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Languages\BaseLanguageWriter.cs:line 583 + // + // mailto: JustDecompilePublicFeedback@telerik.com + + + public GridLength GridHeight + { + get + { + return this._gridHeight; + } + set + { + this._gridHeight = value; + base.OnPropertyChanged("GridHeight"); + } + } + + public GridLength GridHeight2 + { + get + { + return this._gridHeight2; + } + set + { + this._gridHeight2 = value; + base.OnPropertyChanged("GridHeight2"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public Visibility MostrarRamo + { + get + { + return this._mostrarRamo; + } + set + { + this._mostrarRamo = value; + base.OnPropertyChanged("MostrarRamo"); + } + } + + public string Pesquisa + { + get + { + return this._pesquisa; + } + set + { + this._pesquisa = value; + base.OnPropertyChanged("Pesquisa"); + } + } + + public ObservableCollection Ramos + { + get + { + return this._ramos; + } + set + { + this._ramos = value; + base.OnPropertyChanged("Ramos"); + } + } + + public ObservableCollection Repasses + { + get + { + return this._repasses; + } + set + { + if (value != null && value.Count > 0) + { + foreach (Repasse repasse in value) + { + if (repasse.get_Ramo() != null) + { + continue; + } + repasse.set_Ramo(new Ramo()); + } + } + this._repasses = value; + base.OnPropertyChanged("Repasses"); + } + } + + public Repasse SelectedRepasse + { + get + { + return this._selectedRepasse; + } + set + { + this._selectedRepasse = value; + base.OnPropertyChanged("SelectedRepasse"); + } + } + + public VendedorTelefone SelectedTelefone + { + get + { + return this._selectedTelefone; + } + set + { + this._selectedTelefone = value; + base.OnPropertyChanged("SelectedTelefone"); + } + } + + public Vendedor SelectedVendedor + { + get + { + return this._selectedVendedor; + } + set + { + long? nullable; + this._selectedVendedor = value; + this.WorkOnSelectedVendedor(value, true); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedVendedor"); + } + } + + public ObservableCollection Telefones + { + get + { + return this._telefones; + } + set + { + this._telefones = value; + base.OnPropertyChanged("Telefones"); + } + } + + public List TiposRepasseFiltrados + { + get + { + return Enum.GetValues(typeof(TipoRepasse)).Cast().Where((TipoRepasse tipo) => { + TipoAttribute tipoAttribute = (TipoAttribute)typeof(TipoRepasse).GetField(tipo.ToString()).GetCustomAttributes(typeof(TipoAttribute), false).FirstOrDefault(); + if (tipoAttribute == null || tipoAttribute.get_Tipo() == "0" || this.CoCorretagemAtiva) + { + return true; + } + TipoRepasse? nullable = this.SelectedRepasse.get_Tipo(); + return tipo == nullable.GetValueOrDefault() & nullable.HasValue; + }).ToList(); + } + } + + public List Vendedores + { + get; + set; + } + + public ObservableCollection VendedoresFiltrados + { + get + { + return this._vendedoresFiltrados; + } + set + { + this._vendedoresFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("VendedoresFiltrados"); + } + } + + public Visibility VisualizacaoPropriaCorretora + { + get + { + return this._visualizacaoPropriaCorretora; + } + set + { + this._visualizacaoPropriaCorretora = value; + base.OnPropertyChanged("VisualizacaoPropriaCorretora"); + } + } + + public VendedorViewModel() + { + this._servico = new VendedorServico(); + base.EnableMenu = true; + this.Seleciona(); + } + + public async Task AtivarInativarRepasse(Repasse repasse) + { + bool id; + Ramo ramo; + object obj; + string str; + if (repasse != null && repasse.get_Id() != 0) + { + str = (repasse.get_Ativo() ? "INATIVOU REPASSE" : "ATIVOU REPASSE"); + repasse.set_Ativo(!repasse.get_Ativo()); + Repasse repasse1 = repasse; + Ramo ramo1 = repasse.get_Ramo(); + if (ramo1 != null) + { + id = ramo1.get_Id() == (long)0; + } + else + { + id = false; + } + if (id) + { + ramo = null; + } + else + { + ramo = repasse.get_Ramo(); + } + repasse1.set_Ramo(ramo); + repasse = await this._servico.Save(repasse); + long num = this.SelectedVendedor.get_Id(); + VendedorViewModel vendedorViewModel = this; + string str1 = string.Concat(str, " \"", this.SelectedVendedor.get_Nome(), "\""); + long id1 = this.SelectedVendedor.get_Id(); + TipoTela? nullable = new TipoTela?(15); + object[] objArray = new object[] { repasse.get_Id(), repasse.get_ValorNovo(), repasse.get_ValorRenovacao(), null }; + obj = (repasse.get_Ativo() ? "SIM" : "NÃO"); + objArray[3] = obj; + vendedorViewModel.RegistrarAcao(str1, id1, nullable, string.Format("ID: {0}\nVALOR NOVO: {1:N2}\nVALOR RENOVAÇÃO: {2:N2}\nATIVO: {3}", objArray)); + this.Pesquisa = string.Empty; + this.SelectedVendedor = null; + await this.SelecionaVendedores(false); + this.SelectedVendedor = this.VendedoresFiltrados.FirstOrDefault((Vendedor x) => x.get_Id() == num); + Recursos.Vendedores = this.Vendedores; + base.Alterar(false); + base.ToggleSnackBar("REPASSE SALVO COM SUCESSO", true); + } + str = null; + } + + public async Task AtivarInativarVendedor(Vendedor vendedor) + { + object nome; + object obj; + string str; + Vendedor vendedor1 = vendedor; + if (vendedor1 != null && vendedor1.get_Id() != 0) + { + str = (vendedor1.get_Ativo() ? "INATIVOU VENDEDOR" : "ATIVOU VENDEDOR"); + vendedor1.set_Ativo(!vendedor1.get_Ativo()); + Vendedor vendedor2 = await this._servico.Save(vendedor1, this.Repasses.ToList()); + vendedor1 = vendedor2; + VendedorViewModel vendedorViewModel = this; + string str1 = string.Concat(str, " \"", vendedor1.get_Nome(), "\""); + long id = vendedor1.get_Id(); + TipoTela? nullable = new TipoTela?(15); + object[] agencia = new object[] { vendedor1.get_Id(), Recursos.Empresas.First((Empresa x) => x.get_Id() == (vendedor1.get_IdEmpresa() == 0 ? (long)1 : vendedor1.get_IdEmpresa())).get_Nome(), vendedor1.get_Documento(), null, null, null, null, null }; + Banco banco = vendedor1.get_Banco(); + if (banco != null) + { + nome = banco.get_Nome(); + } + else + { + nome = null; + } + agencia[3] = nome; + agencia[4] = vendedor1.get_Agencia(); + agencia[5] = vendedor1.get_Conta(); + agencia[6] = vendedor1.get_Desconto(); + obj = (vendedor1.get_Ativo() ? "SIM" : "NÃO"); + agencia[7] = obj; + vendedorViewModel.RegistrarAcao(str1, id, nullable, string.Format("ID: {0}\nFILIAL DO VENDEDOR: {1}\nDOCUMENTO: {2}\nBANCO: {3}\nAGÊNCIA: {4}\nCONTA: {5}\nDESCONTO: {6:N2}\nATIVO: {7}", agencia)); + this.Pesquisa = string.Empty; + this.SelectedVendedor = null; + await this.SelecionaVendedores(false); + this.SelectedVendedor = this.VendedoresFiltrados.FirstOrDefault((Vendedor x) => x.get_Id() == vendedor1.get_Id()); + Recursos.Vendedores = this.Vendedores; + base.Alterar(false); + base.ToggleSnackBar("VENDEDOR SALVO COM SUCESSO", true); + } + str = null; + } + + public void CancelarAlteracao() + { + if (this.CancelVendedor == null || !this.Vendedores.Any((Vendedor x) => x.get_Id() == this.CancelVendedor.get_Id())) + { + this.Incluir(); + } + else + { + DomainBase.Copy(this.Vendedores.First((Vendedor x) => x.get_Id() == this.CancelVendedor.get_Id()), this.CancelVendedor); + if (this.VendedoresFiltrados.Count <= 0 || !this.VendedoresFiltrados.Any((Vendedor x) => x.get_Id() == this.CancelVendedor.get_Id())) + { + this.VendedoresFiltrados.Add(this.CancelVendedor); + } + else + { + DomainBase.Copy(this.VendedoresFiltrados.First((Vendedor x) => x.get_Id() == this.CancelVendedor.get_Id()), this.CancelVendedor); + } + this.VendedoresFiltrados = new ObservableCollection(this.VendedoresFiltrados); + this.SelectedVendedor = this.VendedoresFiltrados.First((Vendedor x) => x.get_Id() == this.CancelVendedor.get_Id()); + } + base.Alterar(false); + } + + public void ExcluirTelefone(VendedorTelefone telefone) + { + this.Telefones.Remove(telefone); + } + + public async Task ExcluirVinculo(VinculoRepasse vinculo) + { + if (await base.ShowMessage("DESEJA REALMENTE EXCLUIR O VÍNCULO DO REPASSE SELECIONADO?", "SIM", "NÃO", false)) + { + await this._servico.Delete(vinculo); + this.Repasses = new ObservableCollection((IEnumerable)await this._servico.BuscaRepassesPorIdVendedor(this.SelectedVendedor.get_Id())); + base.ToggleSnackBar("VINCULO EXCLUÍDO COM SUCESSO", true); + } + } + + internal async Task> Filtrar(string value) + { + List vendedors = await Task.Run>(() => this.FiltrarVendedor(value)); + return vendedors; + } + + public List FiltrarVendedor(string filter) + { + this.VendedoresFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Vendedores) : new ObservableCollection( + from x in this.Vendedores + where ValidationHelper.RemoveDiacritics(x.get_Nome().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby x.get_Ativo() descending, x.get_Nome() + select x)); + this.SelectedVendedor = this.VendedoresFiltrados.FirstOrDefault(); + return this.VendedoresFiltrados.ToList(); + } + + public void Incluir() + { + Vendedor vendedor = new Vendedor(); + vendedor.set_Ativo(true); + vendedor.set_Desconto(new decimal?(new decimal())); + this.SelectedVendedor = vendedor; + this.Telefones = new ObservableCollection(); + this.Repasses = new ObservableCollection(); + base.Alterar(true); + } + + public void IncluirRepasse() + { + if (this.SelectedVendedor == null) + { + return; + } + if (this.Repasses == null) + { + this.Repasses = new ObservableCollection(); + } + Repasse repasse = new Repasse(); + repasse.set_Vendedor(this.SelectedVendedor); + repasse.set_Forma(new FormaRepasse?(1)); + repasse.set_Incidencia(new TipoIncidencia?(1)); + repasse.set_Tipo(new TipoRepasse?(2)); + repasse.set_Ativo(true); + repasse.set_Ramo(this.Ramos.First()); + Repasse repasse1 = repasse; + this.Repasses.Insert(0, repasse1); + this.SelectedRepasse = repasse1; + } + + public void IncluirTelefone() + { + if (this.SelectedVendedor == null) + { + return; + } + if (this.Telefones == null) + { + this.Telefones = new ObservableCollection(); + } + VendedorTelefone vendedorTelefone = new VendedorTelefone(); + vendedorTelefone.set_Vendedor(this.SelectedVendedor); + vendedorTelefone.set_Tipo(new TipoTelefone?(1)); + VendedorTelefone vendedorTelefone1 = vendedorTelefone; + this.Telefones.Add(vendedorTelefone1); + this.SelectedTelefone = vendedorTelefone1; + } + + public async Task>> Salvar() + { + List> keyValuePairs1; + string str; + object nome; + object obj; + VendedorViewModel.u003cu003ec__DisplayClass55_0 variable; + List list; + string str1; + this.SelectedVendedor.set_Telefones(this.Telefones.ToList()); + List> keyValuePairs2 = this.SelectedVendedor.Validate(); + List> keyValuePairs3 = keyValuePairs2; + keyValuePairs3.AddRange(await this.Validate()); + keyValuePairs3 = null; + if (keyValuePairs2.Count <= 0) + { + Vendedor selectedVendedor = this.SelectedVendedor; + ObservableCollection telefones = this.Telefones; + selectedVendedor.set_Telefones(( + from x in telefones + where !string.IsNullOrEmpty(x.get_Nome()) + select x).ToList()); + List repasses = this.Repasses.ToList(); + list = repasses.Where((Repasse x) => { + List> keyValuePairs = x.Validate(); + if (keyValuePairs == null) + { + return false; + } + return keyValuePairs.Count == 0; + }).ToList(); + if (list.Count < this.Repasses.Count) + { + if (!await base.ShowMessage(string.Concat("HÁ REPASSES INVÁLIDOS, DESEJA PROSSEGUIR?", Environment.NewLine, "CASO PROSSIGA OS REPASSES INVÁLIDOS NÃO SERÃO SALVOS."), "SIM", "NÃO", false)) + { + this.Repasses.ToList().ForEach((Repasse x) => keyValuePairs2.AddRange(x.Validate())); + keyValuePairs1 = keyValuePairs2; + variable = null; + list = null; + str1 = null; + return keyValuePairs1; + } + } + this.Repasses = new ObservableCollection(list); + str = (this.SelectedVendedor.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str1 = str; + Vendedor vendedor = await this._servico.Save(this.SelectedVendedor, this.Repasses.ToList()); + Vendedor vendedor1 = vendedor; + if (this._servico.Sucesso) + { + VendedorViewModel vendedorViewModel = this; + string str2 = string.Concat(str1, " VENDEDOR \"", vendedor1.get_Nome(), "\""); + long id = vendedor1.get_Id(); + TipoTela? nullable = new TipoTela?(15); + object[] agencia = new object[] { vendedor1.get_Id(), Recursos.Empresas.First((Empresa x) => x.get_Id() == (vendedor1.get_IdEmpresa() == 0 ? (long)1 : vendedor1.get_IdEmpresa())).get_Nome(), vendedor1.get_Documento(), null, null, null, null, null }; + Banco banco = vendedor1.get_Banco(); + if (banco != null) + { + nome = banco.get_Nome(); + } + else + { + nome = null; + } + agencia[3] = nome; + agencia[4] = vendedor1.get_Agencia(); + agencia[5] = vendedor1.get_Conta(); + agencia[6] = vendedor1.get_Desconto(); + obj = (vendedor1.get_Ativo() ? "SIM" : "NÃO"); + agencia[7] = obj; + vendedorViewModel.RegistrarAcao(str2, id, nullable, string.Format("ID: {0}\nFILIAL DO VENDEDOR: {1}\nDOCUMENTO: {2}\nBANCO: {3}\nAGÊNCIA: {4}\nCONTA: {5}\nDESCONTO: {6:N2}\nATIVO: {7}", agencia)); + this.Pesquisa = string.Empty; + this.SelectedVendedor = null; + await this.SelecionaVendedores(false); + this.SelectedVendedor = this.VendedoresFiltrados.FirstOrDefault((Vendedor x) => x.get_Id() == vendedor1.get_Id()); + Recursos.Vendedores = this.Vendedores; + base.Alterar(false); + base.ToggleSnackBar("VENDEDOR SALVO COM SUCESSO", true); + keyValuePairs1 = null; + } + else + { + keyValuePairs1 = null; + } + } + else + { + keyValuePairs1 = keyValuePairs2; + } + variable = null; + list = null; + str1 = null; + return keyValuePairs1; + } + + public async Task SalvarVinculo(VinculoRepasse vinculo) + { + await this._servico.Save(vinculo); + this.Repasses = new ObservableCollection((IEnumerable)await this._servico.BuscaRepassesPorIdVendedor(this.SelectedVendedor.get_Id())); + base.ToggleSnackBar("VINCULO SALVO COM SUCESSO", true); + } + + private async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(15); + await this.SelecionaVendedores(true); + await this.SelecionaRamos(); + base.Loading(false); + } + + private async Task SelecionaRamos() + { + Visibility visibility; + VendedorViewModel vendedorViewModel = this; + List configuracoes = Recursos.Configuracoes; + visibility = (configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 20) ? Visibility.Collapsed : Visibility.Visible); + vendedorViewModel.MostrarRamo = visibility; + ObservableCollection ramos = this.Ramos; + Ramo ramo = new Ramo(); + ramo.set_Nome("TODOS OS RAMOS"); + ramos.Add(ramo); + List ramos1 = await (new BaseServico()).BuscarRamosAsync(); + ObservableCollection observableCollection = this.Ramos; + List ramos2 = ramos1; + IEnumerable ativo = + from x in ramos2 + where x.get_Ativo() + select x; + ExtensionMethods.AddRange(observableCollection, + from x in ativo + orderby x.get_Nome() + select x); + } + + private async Task SelecionaVendedores(bool selecionar = true) + { + List vendedors = await (new BaseServico()).BuscarVendedoresAsync(); + VendedorViewModel list = this; + List vendedors1 = vendedors; + IEnumerable vendedors2 = vendedors1.Where((Vendedor x) => { + if (Recursos.Usuario.get_IdEmpresa() == (long)1) + { + return true; + } + return x.get_IdEmpresa() == Recursos.Usuario.get_IdEmpresa(); + }); + IOrderedEnumerable ativo = + from x in vendedors2 + orderby x.get_Ativo() descending + select x; + list.Vendedores = ativo.ThenBy((Vendedor x) => x.get_Nome()).ToList(); + this.VendedoresFiltrados = new ObservableCollection(this.Vendedores); + if (selecionar) + { + this.SelectedVendedor = this.VendedoresFiltrados.FirstOrDefault(); + } + Recursos.Vendedores = vendedors; + } + + private async Task>> Validate() + { + List vendedors; + IEnumerable repasses; + List> keyValuePairs = new List>(); + if (!ValidationHelper.ValidateDocument(this.SelectedVendedor.get_Documento())) + { + vendedors = new List(); + } + else + { + vendedors = await (new BaseServico()).BuscarVendedor(this.SelectedVendedor.get_Documento()); + } + Vendedor vendedor = vendedors.FirstOrDefault((Vendedor x) => { + if (x.get_Id() == this.SelectedVendedor.get_Id() || !(x.get_Documento() == this.SelectedVendedor.get_Documento())) + { + return false; + } + return x.get_Ativo(); + }); + if (vendedor != null) + { + List configuracoes = Recursos.Configuracoes; + if (configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 7)) + { + keyValuePairs.Add(new KeyValuePair("Documento", string.Concat("O DOCUMENTO JÁ ESTÁ CADASTRADO PARA O VENDEDOR ", vendedor.get_Nome(), "."))); + } + } + List configuracaoSistemas = Recursos.Configuracoes; + if (configuracaoSistemas.All((ConfiguracaoSistema x) => x.get_Configuracao() != 15)) + { + ObservableCollection observableCollection = this.Repasses; + if (observableCollection != null) + { + repasses = observableCollection.Where((Repasse x) => { + if (x.get_Tipo().GetValueOrDefault() != 2) + { + return false; + } + if (x.get_ValorNovo() > new decimal(100)) + { + return true; + } + return x.get_ValorRenovacao() > new decimal(100); + }); + } + else + { + repasses = null; + } + IEnumerable repasses1 = repasses; + if (repasses1 != null && repasses1.Any()) + { + keyValuePairs.Add(new KeyValuePair("VALOR REPASSE", "O VALOR DE REPASSE NÃO PODE SER SUPERIOR A 100%")); + } + } + ObservableCollection observableCollection1 = await this._servico.BuscaRepassesPorIdVendedor(this.SelectedVendedor.get_Id()); + if (observableCollection1 != null && observableCollection1.Count > 0) + { + foreach (Repasse repasse1 in observableCollection1) + { + if (!this.Repasses.Any((Repasse repasse) => { + long? nullable; + long? nullable1; + long? nullable2; + bool id; + if (repasse1.get_Id() != repasse.get_Id()) + { + return false; + } + TipoRepasse? tipo = repasse1.get_Tipo(); + TipoRepasse? tipo1 = repasse.get_Tipo(); + if (tipo.GetValueOrDefault() == tipo1.GetValueOrDefault() & tipo.HasValue == tipo1.HasValue && !(repasse1.get_ValorNovo() != repasse.get_ValorNovo()) && !(repasse1.get_ValorRenovacao() != repasse.get_ValorRenovacao())) + { + TipoIncidencia? incidencia = repasse1.get_Incidencia(); + TipoIncidencia? incidencia1 = repasse.get_Incidencia(); + if (incidencia.GetValueOrDefault() == incidencia1.GetValueOrDefault() & incidencia.HasValue == incidencia1.HasValue) + { + FormaRepasse? forma = repasse1.get_Forma(); + FormaRepasse? forma1 = repasse.get_Forma(); + if (forma.GetValueOrDefault() == forma1.GetValueOrDefault() & forma.HasValue == forma1.HasValue) + { + BaseRepasse? @base = repasse1.get_Base(); + BaseRepasse? base1 = repasse.get_Base(); + if (@base.GetValueOrDefault() == base1.GetValueOrDefault() & @base.HasValue == base1.HasValue) + { + long? seguradora = repasse1.get_Seguradora(); + long? seguradora1 = repasse.get_Seguradora(); + if (seguradora.GetValueOrDefault() == seguradora1.GetValueOrDefault() & seguradora.HasValue == seguradora1.HasValue) + { + if (repasse1.get_Ramo() == null) + { + Ramo ramo = repasse.get_Ramo(); + id = (ramo != null ? ramo.get_Id() != (long)0 : true); + if (!id) + { + return false; + } + } + Ramo ramo1 = repasse1.get_Ramo(); + if (ramo1 != null) + { + nullable1 = new long?(ramo1.get_Id()); + } + else + { + nullable = null; + nullable1 = nullable; + } + seguradora1 = nullable1; + Ramo ramo2 = repasse.get_Ramo(); + if (ramo2 != null) + { + nullable2 = new long?(ramo2.get_Id()); + } + else + { + nullable = null; + nullable2 = nullable; + } + seguradora = nullable2; + return !(seguradora1.GetValueOrDefault() == seguradora.GetValueOrDefault() & seguradora1.HasValue == seguradora.HasValue); + } + } + } + } + } + return true; + })) + { + continue; + } + if (await this._servico.BuscarVendedorParcela(repasse1.get_Id()).Count > 1) + { + keyValuePairs.Add(new KeyValuePair("REPASSE", string.Format("O REPASSE, DE ID {0}, NÃO PODE SER ALTERADO POIS JÁ ESTÁ CADASTRADO EM ALGUM DOCUMENTO!", repasse1.get_Id()))); + } + } + } + List> keyValuePairs1 = keyValuePairs; + keyValuePairs = null; + return keyValuePairs1; + } + + private async void WorkOnSelectedVendedor(Vendedor value, bool registrar = true) + { + Vendedor vendedor; + long? nullable; + bool corretora; + bool flag; + object nome; + object obj; + VendedorViewModel vendedorViewModel = this; + vendedor = (value == null || value.get_Id() == 0 ? this.CancelVendedor : (Vendedor)value.Clone()); + vendedorViewModel.CancelVendedor = vendedor; + if (value != null && value.get_Id() != 0) + { + base.Loading(true); + this.Repasses = new ObservableCollection((IEnumerable)await this._servico.BuscaRepassesPorIdVendedor(value.get_Id())); + this.Telefones = new ObservableCollection((IEnumerable)await this._servico.BuscarTelefonesAsync(value.get_Id())); + base.Loading(false); + if (this.LastAccessId != value.get_Id() || this.LastAccessTela != 15) + { + if (registrar) + { + VendedorViewModel vendedorViewModel1 = this; + string str = string.Concat("ACESSOU VENDEDOR \"", value.get_Nome(), "\""); + long id = value.get_Id(); + TipoTela? nullable1 = new TipoTela?(15); + object[] agencia = new object[] { value.get_Id(), Recursos.Empresas.First((Empresa x) => x.get_Id() == (value.get_IdEmpresa() == 0 ? (long)1 : value.get_IdEmpresa())).get_Nome(), value.get_Documento(), null, null, null, null, null }; + Banco banco = value.get_Banco(); + if (banco != null) + { + nome = banco.get_Nome(); + } + else + { + nome = null; + } + agencia[3] = nome; + agencia[4] = value.get_Agencia(); + agencia[5] = value.get_Conta(); + agencia[6] = value.get_Desconto(); + obj = (value.get_Ativo() ? "SIM" : "NÃO"); + agencia[7] = obj; + vendedorViewModel1.RegistrarAcao(str, id, nullable1, string.Format("ID: {0}\nFILIAL DO VENDEDOR: {1}\nDOCUMENTO: {2}\nBANCO: {3}\nAGÊNCIA: {4}\nCONTA: {5}\nDESCONTO: {6:N2}\nATIVO: {7}", agencia)); + } + this.LastAccessId = value.get_Id(); + this.LastAccessTela = 15; + Vendedor selectedVendedor = this.SelectedVendedor; + if (selectedVendedor != null) + { + nullable = new long?(selectedVendedor.get_Id()); + } + else + { + nullable = null; + } + long? nullable2 = nullable; + long num = value.get_Id(); + if (nullable2.GetValueOrDefault() != num | !nullable2.HasValue) + { + this.SelectedVendedor = this.VendedoresFiltrados.FirstOrDefault((Vendedor x) => x.get_Id() == value.get_Id()); + } + VendedorViewModel vendedorViewModel2 = this; + Vendedor selectedVendedor1 = this.SelectedVendedor; + if (selectedVendedor1 != null) + { + corretora = selectedVendedor1.get_Corretora(); + } + else + { + corretora = false; + } + vendedorViewModel2.VisualizacaoPropriaCorretora = (corretora ? Visibility.Visible : Visibility.Collapsed); + if (Recursos.Usuario.get_Id() == 0) + { + Vendedor vendedor1 = this.SelectedVendedor; + if (vendedor1 != null) + { + flag = vendedor1.get_Corretora(); + } + else + { + flag = false; + } + if (!flag) + { + this._alterarPermissEnabled = false; + base.EnableAlterar = false; + } + else + { + this._alterarPermissEnabled = true; + base.EnableAlterar = true; + } + } + } + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Financeiro/BancosContasViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Financeiro/BancosContasViewModel.cs new file mode 100644 index 0000000..e83a4eb --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Financeiro/BancosContasViewModel.cs @@ -0,0 +1,604 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Financeiro; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows.Media; + +namespace Gestor.Application.ViewModels.Financeiro +{ + public class BancosContasViewModel : BaseFinanceiroViewModel + { + private readonly BancosContasServico _bancosContasServico; + + public Gestor.Model.Domain.Financeiro.BancosContas CancelBancosContas; + + private long _ultimoId; + + private Gestor.Model.Domain.Financeiro.BancosContas _selectedBancosContas; + + private SolidColorBrush _corDoSaldo = new SolidColorBrush(Colors.Green); + + private ObservableCollection _bancosContasFiltrados = new ObservableCollection(); + + private bool _isExpanded; + + private ObservableCollection _saldos = new ObservableCollection(); + + private bool _habilitarFecharSaldo; + + private Saldo _selectedSaldo = new Saldo(); + + private string _saldoAtual; + + private decimal? _valorAbertura; + + private DateTime? _dataAbertura; + + private bool _incluindo; + + public List BancosContas + { + get; + set; + } + + public ObservableCollection BancosContasFiltrados + { + get + { + return this._bancosContasFiltrados; + } + set + { + this._bancosContasFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("BancosContasFiltrados"); + } + } + + public SolidColorBrush CorDoSaldo + { + get + { + return this._corDoSaldo; + } + set + { + this._corDoSaldo = value; + base.OnPropertyChanged("CorDoSaldo"); + } + } + + public DateTime? DataAbertura + { + get + { + return this._dataAbertura; + } + set + { + this._dataAbertura = value; + base.OnPropertyChanged("DataAbertura"); + } + } + + public bool HabilitarFecharSaldo + { + get + { + return this._habilitarFecharSaldo; + } + set + { + this._habilitarFecharSaldo = value; + base.OnPropertyChanged("HabilitarFecharSaldo"); + } + } + + public bool Incluindo + { + get + { + return this._incluindo; + } + set + { + this._incluindo = value; + base.OnPropertyChanged("Incluindo"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public string SaldoAtual + { + get + { + return this._saldoAtual; + } + set + { + this._saldoAtual = value; + base.OnPropertyChanged("SaldoAtual"); + } + } + + public ObservableCollection Saldos + { + get + { + return this._saldos; + } + set + { + this._saldos = value; + if (value != null && value.Count > 0) + { + this.SelectedSaldo = value.FirstOrDefault((Saldo x) => !x.get_DataFinal().HasValue); + if (this.SelectedSaldo == null) + { + this.UltimoSladoNaoAberto(); + } + } + base.OnPropertyChanged("Saldos"); + } + } + + public Gestor.Model.Domain.Financeiro.BancosContas SelectedBancosContas + { + get + { + return this._selectedBancosContas; + } + set + { + long? nullable; + this._selectedBancosContas = value; + this.CarregarSaldos(value); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + this.Incluindo = (value == null ? false : value.get_Id() == (long)0); + base.OnPropertyChanged("SelectedBancosContas"); + } + } + + public Saldo SelectedSaldo + { + get + { + return this._selectedSaldo; + } + set + { + bool id; + this._selectedSaldo = value; + if (value == null || value.get_DataFinal().HasValue) + { + id = false; + } + else + { + Usuario usuario = Recursos.Usuario; + if (usuario != null) + { + id = usuario.get_Id() > (long)0; + } + else + { + id = false; + } + } + this.HabilitarFecharSaldo = id; + base.OnPropertyChanged("SelectedSaldo"); + Saldo selectedSaldo = this.SelectedSaldo; + if (selectedSaldo == null) + { + return; + } + selectedSaldo.Initialize(); + } + } + + public decimal? ValorAbertura + { + get + { + return this._valorAbertura; + } + set + { + this._valorAbertura = value; + base.OnPropertyChanged("ValorAbertura"); + } + } + + public BancosContasViewModel() + { + this._bancosContasServico = new BancosContasServico(); + this.Seleciona(); + } + + public async Task CalcularValor() + { + decimal? valorFinal = await this._bancosContasServico.FecharSaldo(this.SelectedSaldo).get_ValorFinal(); + return valorFinal.GetValueOrDefault(); + } + + public async void CancelarAlteracao() + { + base.Loading(true); + if (this.SelectedBancosContas.get_Id() > (long)0) + { + await this.SelecionaBancosDeContas(); + } + BancosContasViewModel bancosContasViewModel = this; + Gestor.Model.Domain.Financeiro.BancosContas bancosConta = this.BancosContasFiltrados.FirstOrDefault((Gestor.Model.Domain.Financeiro.BancosContas x) => x.get_Id() == this._ultimoId); + if (bancosConta == null) + { + bancosConta = this.BancosContasFiltrados.FirstOrDefault(); + } + bancosContasViewModel.SelecionaBancosContas(bancosConta); + base.Alterar(false); + base.Loading(false); + } + + public async void CarregarSaldos(Gestor.Model.Domain.Financeiro.BancosContas banco) + { + if (banco != null && banco.get_Id() != 0) + { + List saldos = await this._bancosContasServico.BuscarSaldos(banco.get_Id()); + this.CorDoSaldo = new SolidColorBrush(Colors.Green); + this.SaldoAtual = string.Empty; + BancosContasViewModel observableCollection = this; + List saldos1 = saldos; + observableCollection.Saldos = new ObservableCollection( + from x in saldos1 + orderby x.get_DataInicio() descending + select x); + if (this.Saldos.FirstOrDefault() != null) + { + Saldo saldo = new Saldo(); + saldo.set_Conta(this.Saldos.First().get_Conta()); + saldo.set_ValorInicio(this.Saldos.First().get_ValorInicio()); + saldo.set_DataInicio(this.Saldos.First().get_DataInicio()); + saldo.set_DataFinal(new DateTime?(Funcoes.GetNetworkTime())); + Saldo saldo1 = saldo; + saldo1 = await this._bancosContasServico.FecharSaldo(saldo1); + decimal? valorFinal = saldo1.get_ValorFinal(); + decimal num = new decimal(); + if ((valorFinal.GetValueOrDefault() < num) & valorFinal.HasValue) + { + this.CorDoSaldo = new SolidColorBrush(Colors.Red); + } + valorFinal = saldo1.get_ValorFinal(); + this.SaldoAtual = string.Format("SALDO: {0:c}", Math.Round(valorFinal.GetValueOrDefault(), 2)); + } + } + } + + public async void Excluir() + { + if (this.SelectedBancosContas != null && this.SelectedBancosContas.get_Id() != 0) + { + if (await (new BaseServico()).BancosContasUtilizado(this.SelectedBancosContas.get_Id())) + { + await base.ShowMessage("NÃO PODE SER EXCLUÍDO POIS ESTÁ SENDO UTILIZADO EM UM LANÇAMENTO.", "OK", "", false); + } + else if (await base.ShowMessage(string.Concat("DESEJA REALMENTE EXCLUIR A CONTA ", this.SelectedBancosContas.get_Descricao(), " PERMANENTEMENTE?"), "SIM", "NÃO", false)) + { + base.Loading(true); + if (await this._bancosContasServico.Delete(this.SelectedBancosContas)) + { + await this.SelecionaBancosDeContas(); + base.Loading(false); + base.ToggleSnackBar("CONTA EXCLUÍDA COM SUCESSO", true); + } + else + { + base.Loading(false); + } + } + } + } + + public async void ExcluirSaldo() + { + if (this.SelectedSaldo != null && this.SelectedSaldo.get_Id() != 0) + { + if (this.Saldos.Count <= 1) + { + await base.ShowMessage("NÃO É POSSÍVEL EXCLUIR O SALDO INICIAL DA CONTA.", "OK", "", false); + } + else if (await base.ShowMessage("DESEJA REALMENTE EXCLUIR O SALDO PERMANENTEMENTE?", "SIM", "NÃO", false)) + { + base.Loading(true); + Saldo saldo = this.Saldos.FirstOrDefault((Saldo x) => { + DateTime? dataFinal = x.get_DataFinal(); + DateTime? dataInicio = this.SelectedSaldo.get_DataInicio(); + if (dataFinal.HasValue != dataInicio.HasValue) + { + return false; + } + if (!dataFinal.HasValue) + { + return true; + } + return dataFinal.GetValueOrDefault() == dataInicio.GetValueOrDefault(); + }); + if (saldo != null) + { + saldo.set_DataFinal(null); + saldo.set_ValorFinal(null); + await this._bancosContasServico.Save(saldo); + if (!this._bancosContasServico.Sucesso) + { + base.Loading(false); + } + else if (await this._bancosContasServico.DeleteSaldo(this.SelectedSaldo)) + { + this.CarregarSaldos(this.SelectedBancosContas); + base.Loading(false); + base.ToggleSnackBar("SALDO EXCLUÍDO COM SUCESSO", true); + base.Loading(false); + } + else + { + base.Loading(false); + } + } + else + { + base.Loading(false); + await base.ShowMessage("NÃO É POSSÍVEL EXCLUIR O SALDO DA CONTA.", "OK", "", false); + } + } + } + } + + public async Task FecharSaldo() + { + this.SelectedSaldo = await this._bancosContasServico.Save(this.SelectedSaldo); + if (this._bancosContasServico.Sucesso) + { + DateTime? dataFinal = this.SelectedSaldo.get_DataFinal(); + if (dataFinal.HasValue) + { + decimal? valorFinal = this.SelectedSaldo.get_ValorFinal(); + if (valorFinal.HasValue) + { + Saldo saldo = new Saldo(); + saldo.set_Conta(this.SelectedSaldo.get_Conta()); + dataFinal = null; + saldo.set_DataFinal(dataFinal); + dataFinal = this.SelectedSaldo.get_DataFinal(); + saldo.set_DataInicio(new DateTime?(dataFinal.Value)); + valorFinal = null; + saldo.set_ValorFinal(valorFinal); + valorFinal = this.SelectedSaldo.get_ValorFinal(); + saldo.set_ValorInicio(valorFinal.Value); + await this._bancosContasServico.Save(saldo); + if (!this._bancosContasServico.Sucesso) + { + return; + } + } + } + this.CarregarSaldos(this.SelectedBancosContas); + base.ToggleSnackBar("SALDO FECHADO COM SUCESSO", true); + } + } + + internal async Task> Filtrar(string value) + { + List bancosContas = await Task.Run>(() => this.FiltrarBancosContas(value)); + return bancosContas; + } + + public List FiltrarBancosContas(string filter) + { + this.BancosContasFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.BancosContas) : new ObservableCollection( + from x in this.BancosContas + where Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Descricao().Trim()).ToUpper().Contains(Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(filter)) + orderby x.get_Ativo() descending, x.get_Descricao() + select x)); + return this.BancosContasFiltrados.ToList(); + } + + public void Incluir() + { + this._ultimoId = this.SelectedBancosContas.get_Id(); + this.DataAbertura = null; + this.ValorAbertura = new decimal?(new decimal()); + this.SaldoAtual = ""; + Gestor.Model.Domain.Financeiro.BancosContas bancosConta = new Gestor.Model.Domain.Financeiro.BancosContas(); + bancosConta.set_Ativo(true); + this.SelectedBancosContas = bancosConta; + this.Saldos = new ObservableCollection(); + this.SelectedSaldo = null; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + Gestor.Model.Domain.Financeiro.BancosContas bancosConta; + List> keyValuePairs1 = this.SelectedBancosContas.Validate(); + keyValuePairs1.AddRange(this.Validate()); + if (keyValuePairs1.Count <= 0) + { + bancosConta = await this._bancosContasServico.Save(this.SelectedBancosContas); + if (this._bancosContasServico.Sucesso) + { + if (this.SelectedBancosContas.get_Id() == 0 && this.DataAbertura.HasValue && this.ValorAbertura.HasValue) + { + Saldo saldo = new Saldo(); + saldo.set_Conta(bancosConta); + saldo.set_DataInicio(new DateTime?(this.DataAbertura.Value)); + saldo.set_ValorInicio(this.ValorAbertura.Value); + await this._bancosContasServico.Save(saldo); + if (!this._bancosContasServico.Sucesso) + { + keyValuePairs = null; + bancosConta = null; + return keyValuePairs; + } + } + await this.SelecionaBancosDeContas(); + this.SelecionaBancosContas(bancosConta); + Recursos.BancosContas = this.BancosContas; + base.Alterar(false); + base.ToggleSnackBar("CONTA SALVA COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + bancosConta = null; + return keyValuePairs; + } + + private async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(26); + await this.SelecionaBancosDeContas(); + base.Loading(false); + } + + public void SelecionaBancosContas(Gestor.Model.Domain.Financeiro.BancosContas bancosContas) + { + base.Loading(true); + this.SelectedBancosContas = this.BancosContasFiltrados.FirstOrDefault((Gestor.Model.Domain.Financeiro.BancosContas x) => x.get_Id() == bancosContas.get_Id()); + base.Loading(false); + } + + private async Task SelecionaBancosDeContas() + { + base.Loading(true); + List bancosContas = await this._bancosContasServico.BuscarBancos(); + BancosContasViewModel list = this; + List bancosContas1 = bancosContas; + IOrderedEnumerable ativo = + from x in bancosContas1 + orderby x.get_Ativo() descending + select x; + list.BancosContas = ativo.ThenBy((Gestor.Model.Domain.Financeiro.BancosContas x) => x.get_Descricao()).ToList(); + this.BancosContasFiltrados = new ObservableCollection(this.BancosContas); + if (this.BancosContasFiltrados.Count <= 0) + { + this.SelectedBancosContas = new Gestor.Model.Domain.Financeiro.BancosContas(); + this.Saldos = new ObservableCollection(); + this.DataAbertura = null; + this.ValorAbertura = new decimal?(new decimal()); + this.SaldoAtual = ""; + base.Alterar(false); + base.EnableMenu = false; + } + else + { + this.SelecionaBancosContas(this.BancosContasFiltrados.First()); + } + Recursos.BancosContas = bancosContas; + base.Loading(false); + } + + private async void UltimoSladoNaoAberto() + { + Saldo saldo = this.Saldos.ToList().Find((Saldo x) => { + DateTime? dataInicio = x.get_DataInicio(); + DateTime? nullable = this.Saldos.Max((Saldo r) => r.get_DataInicio()); + if (dataInicio.HasValue != nullable.HasValue) + { + return false; + } + if (!dataInicio.HasValue) + { + return true; + } + return dataInicio.GetValueOrDefault() == nullable.GetValueOrDefault(); + }); + DateTime? dataFinal = saldo.get_DataFinal(); + bool hasValue = dataFinal.HasValue; + if (hasValue) + { + hasValue = await base.ShowMessage("O ÚLTIMO SALDO NÃO ESTÁ ABERTO. DESEJA ABRÍ-LO AGORA?", "SIM", "NÃO", false); + } + if (hasValue) + { + dataFinal = null; + saldo.set_DataFinal(dataFinal); + saldo.set_ValorFinal(null); + this.SelectedSaldo = await this._bancosContasServico.Save(saldo); + this.SelectedBancosContas = this.SelectedBancosContas; + } + saldo = null; + } + + public List> Validate() + { + List> keyValuePairs = new List>(); + if (this.BancosContas.Where((Gestor.Model.Domain.Financeiro.BancosContas x) => { + if (x.get_Descricao() != this.SelectedBancosContas.get_Descricao()) + { + return false; + } + return x.get_Id() != this.SelectedBancosContas.get_Id(); + }).Any()) + { + Gestor.Model.Helper.ValidationHelper.AddValue(keyValuePairs, "Descricao|DESCRIÇÃO", "NÃO É POSSÍVEL SALVAR MAIS DE UMA CONTA COM A MESMA DESCRIÇÃO.", true); + } + if (this.SelectedBancosContas.get_Id() == 0) + { + if (!this.DataAbertura.HasValue) + { + Gestor.Model.Helper.ValidationHelper.AddValue(keyValuePairs, "DataAbertura|ABERTURA", "É NECESSÁRIO PREENCHER A DATA DE ABERTURA DA CONTA.", true); + } + else if (DateTime.Compare(this.DataAbertura.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.DataAbertura.Value, new DateTime(9999, 12, 31)) > 0) + { + Gestor.Model.Helper.ValidationHelper.AddValue(keyValuePairs, "DataAbertura|ABERTURA", "DATA INVÁLIDA", true); + } + if (!this.ValorAbertura.HasValue) + { + Gestor.Model.Helper.ValidationHelper.AddValue(keyValuePairs, "ValorAbertura|VALOR", "É NECESSÁRIO PREENCHER O VALOR DE ABERTURA DA CONTA.", true); + } + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Financeiro/CentroDeCustoViewmodel.cs b/Codemerx/Gestor.Application/ViewModels/Financeiro/CentroDeCustoViewmodel.cs new file mode 100644 index 0000000..ef57541 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Financeiro/CentroDeCustoViewmodel.cs @@ -0,0 +1,255 @@ +using Gestor.Application.Servicos.Financeiro; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Financeiro +{ + public class CentroDeCustoViewmodel : BaseFinanceiroViewModel + { + private readonly CentroServico _centroServico; + + private ObservableCollection _centrosFiltrados = new ObservableCollection(); + + private bool _isExpanded; + + private Centro _selectedCentro; + + private bool _ativo; + + private long _ultimoId; + + public Centro CancelCentro; + + public bool Ativo + { + get + { + return this._ativo; + } + set + { + this._ativo = bool.Parse(value.ToString()); + base.OnPropertyChanged("Ativo"); + } + } + + public List Centros + { + get; + set; + } + + public ObservableCollection CentrosFiltrados + { + get + { + return this._centrosFiltrados; + } + set + { + this._centrosFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("CentrosFiltrados"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public Centro SelectedCentro + { + get + { + return this._selectedCentro; + } + set + { + this._selectedCentro = value; + if (value.get_Id() > (long)0) + { + this._ultimoId = value.get_Id(); + } + base.VerificarEnables(new long?(value.get_Id())); + base.OnPropertyChanged("SelectedCentro"); + } + } + + public CentroDeCustoViewmodel() + { + this._centroServico = new CentroServico(); + base.EnableMenu = true; + this.Seleciona(); + } + + public async void CancelarAlteracao() + { + base.Loading(true); + base.Alterar(false); + if (this.SelectedCentro.get_Id() > (long)0) + { + await this.SelecionaCentro(); + } + await this.SelecionaCentro(this.CentrosFiltrados.FirstOrDefault((Centro x) => x.get_Id() == this._ultimoId)); + base.Loading(false); + } + + public async Task> Filtrar(string value) + { + List centros = await Task.Run>(() => this.FiltrarCentro(value)); + return centros; + } + + public List FiltrarCentro(string filter) + { + this.CentrosFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Centros) : new ObservableCollection( + from x in this.Centros + where ValidationHelper.RemoveDiacritics(x.get_Descricao().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby this.Ativo descending, x.get_Descricao() + select x)); + return this.CentrosFiltrados.ToList(); + } + + public void Incluir() + { + long id; + Centro selectedCentro = this.SelectedCentro; + if (selectedCentro != null) + { + id = selectedCentro.get_Id(); + } + else + { + id = (long)0; + } + this._ultimoId = id; + Centro centro = new Centro(); + centro.set_Ativo(true); + this.SelectedCentro = centro; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + List> keyValuePairs1 = this.SelectedCentro.Validate(); + List> keyValuePairs2 = keyValuePairs1; + keyValuePairs2.AddRange(await this.Validate()); + keyValuePairs2 = null; + if (keyValuePairs1.Count <= 0) + { + this.SelectedCentro = await this._centroServico.Save(this.SelectedCentro); + if (this._centroServico.Sucesso) + { + await this.SelecionaCentro(); + await this.SelecionaCentro(this.CentrosFiltrados.First((Centro x) => x.get_Id() == this.SelectedCentro.get_Id())); + base.Alterar(false); + base.ToggleSnackBar("CENTRO DE CUSTO SALVO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + keyValuePairs1 = null; + return keyValuePairs; + } + + private async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(29); + await this.SelecionaCentro(); + await this.SelecionaCentro(this.CentrosFiltrados.FirstOrDefault()); + base.Loading(false); + } + + private async Task SelecionaCentro(Centro centros) + { + if (centros != null) + { + base.Loading(true); + List centros1 = await (new BaseServico()).BuscarCentroAsync(); + DomainBase.Copy(this.CentrosFiltrados.First((Centro x) => x.get_Id() == centros.get_Id()), centros1.First((Centro x) => x.get_Id() == centros.get_Id())); + this.SelectedCentro = this.CentrosFiltrados.First((Centro x) => x.get_Id() == centros.get_Id()); + base.Loading(false); + } + else + { + base.Alterar(false); + base.EnableMenu = false; + base.EnableAlterar = false; + } + } + + private async Task SelecionaCentro() + { + List centros = await (new BaseServico()).BuscarCentroAsync(); + CentroDeCustoViewmodel list = this; + List centros1 = centros; + IOrderedEnumerable ativo = + from x in centros1 + orderby x.get_Ativo() descending + select x; + IOrderedEnumerable centros2 = ativo.ThenBy((Centro x) => x.get_Descricao()); + list.Centros = centros2.ThenBy((Centro x) => x.get_Descricao()).ToList(); + this.CentrosFiltrados = new ObservableCollection(this.Centros); + } + + public void SelecionaCentroDeCusto(Centro centro) + { + this.SelectedCentro = this.CentrosFiltrados.First((Centro x) => x.get_Id() == centro.get_Id()); + } + + public async Task>> Validate() + { + List> keyValuePairs = new List>(); + bool flag = true; + List centros = await (new BaseServico()).BuscarCentroAsync(); + if (centros.Count > 0) + { + centros.ForEach((Centro x) => { + if (x.get_Id() == this.SelectedCentro.get_Id()) + { + return; + } + if (x.get_Descricao() == this.SelectedCentro.get_Descricao() && x.get_IdEmpresa() == this.SelectedCentro.get_IdEmpresa()) + { + flag = false; + } + }); + } + if (!flag) + { + keyValuePairs.Add(new KeyValuePair("Descricao", "UM CENTRO COM ESSE NOME JÁ EXISTE.")); + } + List> keyValuePairs1 = keyValuePairs; + keyValuePairs = null; + return keyValuePairs1; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Financeiro/ContasDialogModel.cs b/Codemerx/Gestor.Application/ViewModels/Financeiro/ContasDialogModel.cs new file mode 100644 index 0000000..8e112a4 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Financeiro/ContasDialogModel.cs @@ -0,0 +1,48 @@ +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.Financeiro; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; + +namespace Gestor.Application.ViewModels.Financeiro +{ + public class ContasDialogModel : BaseViewModel + { + private ObservableCollection _contasFiltradas; + + private BancosContas _conta; + + public BancosContas Conta + { + get + { + return this._conta; + } + set + { + this._conta = value; + base.OnPropertyChanged("Conta"); + } + } + + public ObservableCollection ContasFiltradas + { + get + { + return this._contasFiltradas; + } + set + { + this._contasFiltradas = value; + base.OnPropertyChanged("ContasFiltradas"); + } + } + + public ContasDialogModel(List contas) + { + this.ContasFiltradas = new ObservableCollection(contas); + this.Conta = this.ContasFiltradas.FirstOrDefault(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Financeiro/CopiarClienteViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Financeiro/CopiarClienteViewModel.cs new file mode 100644 index 0000000..3bde895 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Financeiro/CopiarClienteViewModel.cs @@ -0,0 +1,28 @@ +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.Seguros; +using System; + +namespace Gestor.Application.ViewModels.Financeiro +{ + public class CopiarClienteViewModel : BaseSegurosViewModel + { + private Cliente _selectedCliente; + + public Cliente SelectedCliente + { + get + { + return this._selectedCliente; + } + set + { + this._selectedCliente = value; + base.OnPropertyChanged("SelectedCliente"); + } + } + + public CopiarClienteViewModel() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Financeiro/ExtratoContaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Financeiro/ExtratoContaViewModel.cs new file mode 100644 index 0000000..114d175 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Financeiro/ExtratoContaViewModel.cs @@ -0,0 +1,552 @@ +using ClosedXML.Excel; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Financeiro; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Helpers; +using Gestor.Model.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Forms; +using System.Windows.Media; + +namespace Gestor.Application.ViewModels.Financeiro +{ + public class ExtratoContaViewModel : BaseFinanceiroViewModel + { + private Geometry _maximizeRestore = Geometry.Parse((string)System.Windows.Application.Current.Resources["Restore"]); + + private string _head; + + private readonly FinanceiroServico _servico; + + private ObservableCollection _contas; + + private ObservableCollection _contasFilter; + + private Gestor.Model.Domain.Financeiro.BancosContas _selectedConta; + + private DateTime? _inicio; + + private DateTime? _fim; + + private static ObservableCollection _bancosContas; + + private string _selectedBancosContas; + + private ObservableCollection _extrato; + + private bool _saldoFinal; + + private bool _naoHaDados; + + public ObservableCollection BancosContas + { + get + { + return ExtratoContaViewModel._bancosContas; + } + set + { + ExtratoContaViewModel._bancosContas = value; + base.OnPropertyChanged("BancosContas"); + } + } + + public ObservableCollection Contas + { + get + { + return this._contas; + } + set + { + this._contas = value; + base.OnPropertyChanged("Contas"); + } + } + + public ObservableCollection ContasFilter + { + get + { + return this._contasFilter; + } + set + { + this._contasFilter = value; + base.OnPropertyChanged("ContasFilter"); + } + } + + public ObservableCollection Extrato + { + get + { + return this._extrato; + } + set + { + this._extrato = value; + this.NaoHaDados = (value == null ? true : value.Count == 0); + base.OnPropertyChanged("Extrato"); + } + } + + public DateTime? Fim + { + get + { + return this._fim; + } + set + { + this._fim = value; + base.OnPropertyChanged("Fim"); + } + } + + public string Head + { + get + { + return this._head; + } + set + { + this._head = value; + base.OnPropertyChanged("Head"); + } + } + + public DateTime? Inicio + { + get + { + return this._inicio; + } + set + { + this._inicio = value; + base.OnPropertyChanged("Inicio"); + } + } + + public Geometry MaximizeRestore + { + get + { + return this._maximizeRestore; + } + set + { + this._maximizeRestore = value; + base.OnPropertyChanged("MaximizeRestore"); + } + } + + public bool NaoHaDados + { + get + { + return this._naoHaDados; + } + set + { + this._naoHaDados = value; + base.OnPropertyChanged("NaoHaDados"); + } + } + + public bool SaldoFinal + { + get + { + return this._saldoFinal; + } + set + { + this._saldoFinal = value; + base.OnPropertyChanged("SaldoFinal"); + } + } + + public string SelectedBancosContas + { + get + { + return this._selectedBancosContas; + } + set + { + this._selectedBancosContas = value; + if (value == null || this.Contas == null || this.Contas.Count <= 0) + { + return; + } + if (value == "TODOS") + { + this.ContasFilter = this.Contas; + } + else if (value == "ATIVOS") + { + this.ContasFilter = new ObservableCollection(( + from x in this.Contas + where x.get_Ativo() + select x).ToList()); + } + else if (value == "INATIVOS") + { + this.ContasFilter = new ObservableCollection(( + from x in this.Contas + where !x.get_Ativo() + select x).ToList()); + } + base.OnPropertyChanged("SelectedBancosContas"); + } + } + + public Gestor.Model.Domain.Financeiro.BancosContas SelectedConta + { + get + { + return this._selectedConta; + } + set + { + this._selectedConta = value; + base.OnPropertyChanged("SelectedConta"); + } + } + + static ExtratoContaViewModel() + { + ExtratoContaViewModel._bancosContas = new ObservableCollection() + { + "TODOS", + "ATIVOS", + "INATIVOS" + }; + } + + public ExtratoContaViewModel(long id) + { + this._maximizeRestore = Geometry.Parse((string)System.Windows.Application.Current.Resources["Restore"]); + DateTime date = Funcoes.GetNetworkTime().Date; + int year = date.Year; + date = Funcoes.GetNetworkTime().Date; + this._inicio = new DateTime?(new DateTime(year, date.Month, 1)); + this._fim = new DateTime?(Funcoes.GetNetworkTime()); + this._selectedBancosContas = "TODOS"; + base(); + this._servico = new FinanceiroServico(); + this.BuscaInicial(id); + } + + private async void BuscaInicial(long id) + { + Gestor.Model.Domain.Financeiro.BancosContas bancosConta; + base.Loading(true); + List bancosContas = await (new BancosContasServico()).BuscarBancos(); + ExtratoContaViewModel observableCollection = this; + List bancosContas1 = bancosContas; + observableCollection.Contas = new ObservableCollection( + from x in bancosContas1 + orderby x.get_Descricao() + select x); + ExtratoContaViewModel extratoContaViewModel = this; + List bancosContas2 = bancosContas; + extratoContaViewModel.ContasFilter = new ObservableCollection( + from x in bancosContas2 + orderby x.get_Descricao() + select x); + ExtratoContaViewModel extratoContaViewModel1 = this; + bancosConta = (id > (long)0 ? this.Contas.FirstOrDefault((Gestor.Model.Domain.Financeiro.BancosContas x) => x.get_Id() == id) : this.Contas.FirstOrDefault()); + extratoContaViewModel1.SelectedConta = bancosConta; + await this.GerarRelatorio(); + base.Loading(false); + } + + public async Task GerarExcel() + { + string str; + string str1; + if (this.Extrato == null || this.Extrato.Count == 0) + { + base.ShowMessage("NÃO HÁ DADOS PARA A IMPRESSÃO EM EXCEL", "OK", "", false); + } + else + { + List list = this.Extrato.ToList(); + string tempPath = ""; + str1 = ""; + List configuracoes = Recursos.Configuracoes; + if (!configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 41)) + { + tempPath = Path.GetTempPath(); + str1 = string.Format("{0}{1}.xlsx", tempPath, Guid.NewGuid()); + } + else + { + using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog()) + { + if (DialogResult.OK == folderBrowserDialog.ShowDialog()) + { + tempPath = string.Concat(folderBrowserDialog.SelectedPath, "\\"); + Directory.CreateDirectory(tempPath); + } + else + { + str1 = null; + return; + } + } + string[] descricao = new string[] { tempPath, "EXTRATO CONTA - ", this.SelectedConta.get_Descricao(), " ", null, null }; + DateTime date = Functions.GetNetworkTime().Date; + descricao[4] = date.ToShortDateString().Replace("/", ""); + descricao[5] = ".xlsx"; + str1 = string.Concat(descricao); + } + XLWorkbook xLWorkbook = new XLWorkbook(); + string str2 = string.Concat("EXTRATO CONTA - ", this.SelectedConta.get_Descricao()); + str = (str2.Length < 30 ? str2 : str2.Substring(0, 30)); + str2 = str; + await Funcoes.GerarXls(xLWorkbook, str2, list, new List()).SaveAs(str1); + Process.Start(str1); + } + str1 = null; + } + + public async Task GerarRelatorio() + { + DateTime? dataInicio; + bool flag; + Sinal sinal; + Sinal sinal1; + string str; + ExtratoContaViewModel.u003cu003ec__DisplayClass52_0 variable; + if (this.SelectedConta != null && this.SelectedConta.get_Id() != 0) + { + DateTime? inicio = this.Inicio; + if (inicio.HasValue) + { + inicio = this.Fim; + if (inicio.HasValue) + { + BancosContasServico bancosContasServico = new BancosContasServico(); + Saldo saldo = await bancosContasServico.BuscarSaldoInicial(this.SelectedConta.get_Id()); + if (saldo != null) + { + dataInicio = saldo.get_DataInicio(); + } + else + { + dataInicio = null; + } + inicio = dataInicio; + DateTime? fim = this.Inicio; + flag = (inicio.HasValue & fim.HasValue ? inicio.GetValueOrDefault() > fim.GetValueOrDefault() : false); + if (!flag) + { + FinanceiroServico financeiroServico = this._servico; + fim = this.Inicio; + DateTime value = fim.Value; + fim = this.Fim; + List extratoContas2 = await financeiroServico.BuscarLancamentosPorConta(value, fim.Value, this.SelectedConta.get_Id()); + List extratoContas3 = extratoContas2; + BancosContasServico bancosContasServico1 = bancosContasServico; + fim = this.Inicio; + Saldo saldo1 = await bancosContasServico1.BuscarSaldo(fim.Value, this.SelectedConta.get_Id()); + if (extratoContas3.Count != 0) + { + if (saldo1 == null) + { + Saldo saldo2 = new Saldo(); + saldo2.set_Conta(this.SelectedConta); + saldo2.set_DataInicio(this.Inicio); + saldo2.set_ValorInicio(decimal.Zero); + saldo1 = saldo2; + } + fim = this.Inicio; + saldo1.set_DataFinal(new DateTime?(fim.Value)); + decimal num1 = new decimal(); + saldo1.set_ValorFinal(new decimal?(num1)); + saldo1 = await bancosContasServico.FecharSaldo(saldo1); + List extratoContas4 = new List(); + ExtratoConta extratoContum2 = new ExtratoConta(); + fim = this.Inicio; + extratoContum2.set_Baixa(new DateTime?(fim.Value)); + extratoContum2.set_Fornecedor("SALDO INICIAL"); + decimal? valorFinal = saldo1.get_ValorFinal(); + extratoContum2.set_Valor(new decimal?(valorFinal.GetValueOrDefault())); + valorFinal = saldo1.get_ValorFinal(); + sinal = (valorFinal.GetValueOrDefault() < decimal.Zero ? 1 : 0); + extratoContum2.set_Sinal(sinal); + extratoContum2.set_Bold(true); + ExtratoConta extratoContum3 = extratoContum2; + extratoContas4.Add(extratoContum3); + decimal? valor = extratoContum3.get_Valor(); + List extratoContas5 = extratoContas3; + IOrderedEnumerable extratoContas6 = + from x in extratoContas5 + orderby x.get_Baixa() + select x; + ( + from x in extratoContas6 + group x by x.get_Baixa()).ToList>().ForEach((IGrouping g) => { + decimal? nullable; + decimal? nullable1; + List list = extratoContas3.Where((ExtratoConta x) => { + DateTime? baixa = x.get_Baixa(); + DateTime? key = g.Key; + if (baixa.HasValue != key.HasValue) + { + return false; + } + if (!baixa.HasValue) + { + return true; + } + return baixa.GetValueOrDefault() == key.GetValueOrDefault(); + }).ToList(); + ExtratoConta extratoContum = new ExtratoConta(); + extratoContum.set_Baixa(g.Key); + extratoContum.set_Fornecedor("SALDO FINAL DO DIA"); + decimal? nullable2 = valor; + List extratoContas = list; + Func u003cu003e9_524 = ExtratoContaViewModel.u003cu003ec.u003cu003e9__52_4; + if (u003cu003e9_524 == null) + { + u003cu003e9_524 = (ExtratoConta x) => x.get_Valor(); + ExtratoContaViewModel.u003cu003ec.u003cu003e9__52_4 = u003cu003e9_524; + } + decimal? nullable3 = extratoContas.Sum(u003cu003e9_524); + if (nullable2.HasValue & nullable3.HasValue) + { + nullable1 = new decimal?(nullable2.GetValueOrDefault() + nullable3.GetValueOrDefault()); + } + else + { + nullable = null; + nullable1 = nullable; + } + extratoContum.set_Valor(nullable1); + nullable2 = valor; + List extratoContas1 = list; + Func u003cu003e9_525 = ExtratoContaViewModel.u003cu003ec.u003cu003e9__52_5; + if (u003cu003e9_525 == null) + { + u003cu003e9_525 = (ExtratoConta x) => x.get_Valor(); + ExtratoContaViewModel.u003cu003ec.u003cu003e9__52_5 = u003cu003e9_525; + } + nullable = extratoContas1.Sum(u003cu003e9_525); + nullable3 = (nullable2.HasValue & nullable.HasValue ? new decimal?(nullable2.GetValueOrDefault() + nullable.GetValueOrDefault()) : null); + decimal num = new decimal(); + extratoContum.set_Sinal(((nullable3.GetValueOrDefault() < num) & nullable3.HasValue ? 1 : 0)); + extratoContum.set_Bold(true); + ExtratoConta extratoContum1 = extratoContum; + if (!this.SaldoFinal) + { + extratoContas4.AddRange(list); + } + extratoContas4.Add(extratoContum1); + valor = extratoContum1.get_Valor(); + }); + List extratoContas7 = extratoContas4; + ExtratoConta extratoContum4 = new ExtratoConta(); + fim = this.Fim; + extratoContum4.set_Baixa(new DateTime?(fim.Value)); + extratoContum4.set_Fornecedor("SALDO FINAL"); + extratoContum4.set_Valor(valor); + valorFinal = valor; + num1 = new decimal(); + sinal1 = ((valorFinal.GetValueOrDefault() < num1) & valorFinal.HasValue ? 1 : 0); + extratoContum4.set_Sinal(sinal1); + extratoContum4.set_Bold(true); + extratoContas7.Add(extratoContum4); + this.Extrato = new ObservableCollection(extratoContas4); + bancosContasServico = null; + } + else + { + this.NaoHaDados = true; + variable = null; + return; + } + } + else + { + ExtratoContaViewModel extratoContaViewModel = this; + string descricao = saldo.get_Conta().get_Descricao(); + fim = saldo.get_DataInicio(); + if (fim.HasValue) + { + str = fim.GetValueOrDefault().ToString("dd/MM/yyyy"); + } + else + { + str = null; + } + extratoContaViewModel.ShowMessage(string.Concat("DATA DE INÍCIO É MENOR QUE A CRIAÇÃO DA CONTA ", descricao, ",\nDATA DE ABERTURA ", str), "OK", "", false); + this.NaoHaDados = true; + variable = null; + return; + } + } + } + } + variable = null; + } + + public void LimparRelatorio() + { + this.Extrato = null; + } + + public async Task Print() + { + DateTime dateTime; + DateTime dateTime1; + string str; + if (this.Extrato == null || this.Extrato.Count == 0) + { + base.ShowMessage("NÃO HÁ DADOS PARA A IMPRESSÃO", "OK", "", false); + } + else + { + string str1 = await Funcoes.GenerateTable(this.Extrato.ToList(), new List(), false, false, "", null); + TipoRelatorio tipoRelatorio = new TipoRelatorio(); + tipoRelatorio.set_Nome(string.Concat("EXTRATO CONTA - ", this.SelectedConta.get_Descricao())); + DateTime? inicio = this.Inicio; + dateTime = (inicio.HasValue ? inicio.GetValueOrDefault() : DateTime.MinValue); + tipoRelatorio.set_Inicio(dateTime); + inicio = this.Fim; + dateTime1 = (inicio.HasValue ? inicio.GetValueOrDefault() : DateTime.MinValue); + tipoRelatorio.set_Fim(dateTime1); + TipoRelatorio tipoRelatorio1 = tipoRelatorio; + TipoRelatorio tipoRelatorio2 = tipoRelatorio1; + str = (tipoRelatorio1.get_Nome().Length < 30 ? tipoRelatorio1.get_Nome() : tipoRelatorio1.get_Nome().Substring(0, 30)); + tipoRelatorio2.set_Nome(str); + string str2 = Funcoes.ExportarHtml(tipoRelatorio1, str1, "60", "portrait", false, ""); + string tempPath = Path.GetTempPath(); + string str3 = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.html", tempPath, (new Regex(string.Concat("[", Regex.Escape(string.Concat(new string(Path.GetInvalidFileNameChars()), new string(Path.GetInvalidPathChars()))), "]"))).Replace(tipoRelatorio1.get_Nome(), ""), Funcoes.GetNetworkTime()); + StreamWriter streamWriter = new StreamWriter(str3, true, Encoding.UTF8); + streamWriter.Write(str2); + streamWriter.Close(); + Process.Start(str3); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Financeiro/FinanceiroViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Financeiro/FinanceiroViewModel.cs new file mode 100644 index 0000000..630e3db --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Financeiro/FinanceiroViewModel.cs @@ -0,0 +1,5973 @@ +using ClosedXML.Excel; +using CsQuery.ExtensionMethods; +using Gestor.Application.Actions; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Financeiro; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Relatorios; +using Gestor.Common.Helpers; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using OfxSharpLib; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Forms; + +namespace Gestor.Application.ViewModels.Financeiro +{ + public class FinanceiroViewModel : BaseFinanceiroViewModel + { + private readonly FinanceiroServico _servico; + + private bool _enableIncluirNovo; + + private bool _enableChanges; + + private SinteticoFinanceiroTipo _sinteticoTipo; + + private Visibility _isVisibleData; + + private Visibility _isVisibleFornecedor = Visibility.Collapsed; + + private Visibility _isVisiblePersonalizado = Visibility.Collapsed; + + private Visibility _isVisibleFiltros = Visibility.Collapsed; + + private Visibility _isVisibleLancamento; + + private Visibility _isvisibleStatus; + + private FiltroLancamento _selectedFiltro; + + private FiltroLancamentoData _selectedFiltroData; + + private StatusLancamento _selectedStatus; + + private StatusLancamento _selectedStatusImportacao = 2; + + private Visibility _botaoSalvarVisibility; + + private DateTime? _inicio = new DateTime?(Funcoes.GetNetworkTime()); + + private DateTime? _fim = new DateTime?(Funcoes.GetNetworkTime().AddDays(7)); + + private Fornecedor _selectedFornecedor; + + private ObservableCollection _saldos = new ObservableCollection(); + + private Saldo _selectedSaldo = new Saldo(); + + private ObservableCollection _lancamentos = new ObservableCollection(); + + private bool _dontSort; + + private ObservableCollection _lancamentosFiltrados = new ObservableCollection(); + + private ObservableCollection _lancamentosFiltradosCopia = new ObservableCollection(); + + private ObservableCollection _lancamentosVinculo = new ObservableCollection(); + + private Lancamento _lancamentoVinculo; + + private Lancamento _selectedLancamento; + + private Fornecedor _fornecedorInclusao; + + private long _idLancamento; + + private string _historico; + + private string _observacao; + + private string _documento; + + private string _complemento; + + private string _competencia; + + private int _parcela; + + private double _dropDownHeight; + + private int _parcelas; + + public bool VencimentoAlterado; + + private DateTime _vencimento; + + private DateTime? _baixa; + + private DateTime? _pagamento; + + private decimal _valor; + + private decimal? _valorPago; + + private Gestor.Model.Common.Sinal _sinal; + + private Gestor.Model.Domain.Financeiro.Planos _plano; + + private Gestor.Model.Domain.Financeiro.Centro _centro; + + private BancosContas _conta; + + private Gestor.Model.Common.TipoPagamento _tipoPagamento; + + private List _planosFiltro; + + private List _centroFiltro; + + private List _contaFiltro; + + private List _planos; + + private ObservableCollection _planosFiltrados; + + private List _contas; + + private ObservableCollection _contasFiltradas; + + private List _centros; + + private ObservableCollection _centrosFiltrados; + + private ObservableCollection _totalizacao; + + private Visibility _visibilityFornecedor; + + private Visibility _visibilityCentro; + + private Visibility _visibilityConta; + + private Visibility _alterando = Visibility.Collapsed; + + private bool _buscaHabilitada = true; + + private bool _alteracao = true; + + private List _filtroRelatorioPersonalizado; + + private List _filtros; + + private ObservableCollection _personalizadoSelecionado; + + private ObservableCollection _filtroRelatorioSelecionado = new ObservableCollection(); + + private Visibility _visibilitySemValor = Visibility.Collapsed; + + private Gestor.Model.Domain.Relatorios.FiltroPersonalizado _filtro; + + private Type _tipoString = typeof(string); + + private Type _tipoEnum = typeof(Enum); + + private Type _tipoDateTime = typeof(DateTime); + + private Type _tipoDecimal = typeof(decimal); + + private Type _tipoInt = typeof(int); + + private Type _tipoLong = typeof(long); + + private string _valorIncial = ""; + + private string _valorFinal = ""; + + private bool _semValor; + + private List _filtroPersonalizado; + + private ObservableCollection _filtroPersonalizadoSelecionado = new ObservableCollection(); + + private Visibility _visibleFiltros = Visibility.Collapsed; + + private Visibility _visibleOlho = Visibility.Collapsed; + + private bool importando; + + private bool _isExpanded; + + public bool Alteracao + { + get + { + return this._alteracao; + } + set + { + this._alteracao = value; + base.OnPropertyChanged("Alteracao"); + } + } + + public Visibility Alterando + { + get + { + return this._alterando; + } + set + { + this._alterando = value; + base.OnPropertyChanged("Alterando"); + } + } + + public DateTime? Baixa + { + get + { + return this._baixa; + } + set + { + this._baixa = value; + base.OnPropertyChanged("Baixa"); + } + } + + public Visibility BotaoSalvarVisibility + { + get + { + return this._isvisibleStatus; + } + set + { + this._isvisibleStatus = value; + base.OnPropertyChanged("BotaoSalvarVisibility"); + } + } + + public bool BuscaHabilitada + { + get + { + return this._buscaHabilitada; + } + set + { + this._buscaHabilitada = value; + base.OnPropertyChanged("BuscaHabilitada"); + } + } + + private bool Carregar { get; set; } = true; + + public Gestor.Model.Domain.Financeiro.Centro Centro + { + get + { + return this._centro; + } + set + { + this._centro = value; + base.OnPropertyChanged("Centro"); + } + } + + public List CentroFiltro + { + get + { + return this._centroFiltro; + } + set + { + this._centroFiltro = value; + base.OnPropertyChanged("CentroFiltro"); + } + } + + public List Centros + { + get + { + return this._centros; + } + set + { + this._centros = value; + base.OnPropertyChanged("Centros"); + } + } + + public ObservableCollection CentrosFiltrados + { + get + { + return this._centrosFiltrados; + } + set + { + this._centrosFiltrados = value; + base.OnPropertyChanged("CentrosFiltrados"); + } + } + + public string CodigoBanco + { + get; + set; + } + + public string Competencia + { + get + { + return this._competencia; + } + set + { + this._competencia = value; + base.OnPropertyChanged("Competencia"); + } + } + + public string Complemento + { + get + { + return this._complemento; + } + set + { + this._complemento = value; + base.OnPropertyChanged("Complemento"); + } + } + + public BancosContas Conta + { + get + { + return this._conta; + } + set + { + this._conta = value; + base.OnPropertyChanged("Conta"); + } + } + + public List ContaFiltro + { + get + { + return this._contaFiltro; + } + set + { + this._contaFiltro = value; + base.OnPropertyChanged("ContaFiltro"); + } + } + + public List Contas + { + get + { + return this._contas; + } + set + { + this._contas = value; + base.OnPropertyChanged("Contas"); + } + } + + public ObservableCollection ContasFiltradas + { + get + { + return this._contasFiltradas; + } + set + { + this._contasFiltradas = value; + base.OnPropertyChanged("ContasFiltradas"); + } + } + + public string Documento + { + get + { + return this._documento; + } + set + { + this._documento = value; + base.OnPropertyChanged("Documento"); + } + } + + public double DropDownHeight + { + get + { + return this._dropDownHeight; + } + set + { + this._dropDownHeight = value; + base.OnPropertyChanged("DropDownHeight"); + } + } + + public bool EnableChanges + { + get + { + return this._enableChanges; + } + set + { + this._enableChanges = value; + base.OnPropertyChanged("EnableChanges"); + } + } + + public bool EnableIncluirNovo + { + get + { + return this._enableIncluirNovo; + } + set + { + this._enableIncluirNovo = value; + base.OnPropertyChanged("EnableIncluirNovo"); + } + } + + public Gestor.Model.Domain.Relatorios.FiltroPersonalizado Filtro + { + get + { + return this._filtro; + } + set + { + char chr; + this._filtro = value; + this.VisibilitySemValor = (value != null ? Visibility.Visible : Visibility.Collapsed); + base.OnPropertyChanged("Filtro"); + if (value == null) + { + return; + } + string name = value.get_Tipo().Name; + if (name != null) + { + switch (name.Length) + { + case 3: + { + if (name == "int") + { + break; + } + return; + } + case 4: + { + chr = name[0]; + if (chr == 'E') + { + if (name == "Enum") + { + this.ValorInicial = null; + this.ValorFinal = null; + return; + } + return; + } + else + { + if (chr != 'l') + { + return; + } + if (name == "long") + { + break; + } + return; + } + } + case 5: + { + chr = name[3]; + if (chr == '3') + { + if (name == "int32") + { + break; + } + return; + } + else + { + if (chr != '6') + { + return; + } + if (name == "int64") + { + break; + } + return; + } + } + case 6: + { + if (name != "String") + { + return; + } + this.ValorInicial = ""; + this.ValorFinal = ""; + return; + } + case 7: + { + if (name != "Decimal") + { + return; + } + this.ValorInicial = "0,00"; + this.ValorFinal = "0,00"; + return; + } + case 8: + { + if (name == "DateTime") + { + this.ValorInicial = null; + this.ValorFinal = null; + return; + } + return; + } + default: + { + return; + } + } + this.ValorInicial = "0"; + this.ValorFinal = "0"; + } + } + } + + public List FiltroPersonalizado + { + get + { + return this._filtroPersonalizado; + } + set + { + this._filtroPersonalizado = value; + base.OnPropertyChanged("FiltroPersonalizado"); + } + } + + public AutoCompleteFilterPredicate FiltroPersonalizadoItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_3690 = FinanceiroViewModel.u003cu003ec.u003cu003e9__369_0; + if (u003cu003e9_3690 == null) + { + u003cu003e9_3690 = new AutoCompleteFilterPredicate(FinanceiroViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((Gestor.Model.Domain.Financeiro.FiltroPersonalizado)obj).get_Descricao().ToUpper().Contains(searchText.ToUpper())); + FinanceiroViewModel.u003cu003ec.u003cu003e9__369_0 = u003cu003e9_3690; + } + return u003cu003e9_3690; + } + } + + public ObservableCollection FiltroPersonalizadoSelecionado + { + get + { + return this._filtroPersonalizadoSelecionado; + } + set + { + this._filtroPersonalizadoSelecionado = value; + base.OnPropertyChanged("FiltroPersonalizadoSelecionado"); + } + } + + public ObservableCollection FiltroRelatorioSelecionado + { + get + { + return this._filtroRelatorioSelecionado; + } + set + { + this._filtroRelatorioSelecionado = value; + base.OnPropertyChanged("FiltroRelatorioSelecionado"); + } + } + + public List Filtros + { + get + { + return this._filtros; + } + set + { + this._filtros = value; + base.OnPropertyChanged("Filtros"); + } + } + + public DateTime? Fim + { + get + { + return this._fim; + } + set + { + if (value.HasValue && value.Value < new DateTime(1754, 1, 1)) + { + value = new DateTime?(new DateTime(1754, 1, 1)); + } + if (value.HasValue && value.Value > new DateTime(9999, 12, 31)) + { + value = new DateTime?(new DateTime(9999, 12, 31)); + } + this._fim = value; + base.OnPropertyChanged("Fim"); + } + } + + public Fornecedor FornecedorInclusao + { + get + { + return this._fornecedorInclusao; + } + set + { + // + // Current member / type: System.Void Gestor.Application.ViewModels.Financeiro.FinanceiroViewModel::set_FornecedorInclusao(Gestor.Model.Domain.Financeiro.Fornecedor) + // File path: C:\AggerSeguros\Gestor.Application.exe + // + // Product version: 0.0.0.0 + // Exception in: System.Void set_FornecedorInclusao(Gestor.Model.Domain.Financeiro.Fornecedor) + // + // Object reference not set to an instance of an object. + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.FindLowestCommonAncestor(ICollection`1 typeNodes) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 515 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.MergeWithLowestCommonAncestor() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 459 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.ProcessSingleConstraints() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 378 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.InferTypes() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 331 + // at Telerik.JustDecompiler.Decompiler.ExpressionDecompilerStep.Process(DecompilationContext theContext, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\ExpressionDecompilerStep.cs:line 104 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.PropertyDecompiler.DecompileMethod(MethodBody body, MethodSpecificContext& methodContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\PropertyDecompiler.cs:line 347 + // + // mailto: JustDecompilePublicFeedback@telerik.com + + } + } + + public string Historico + { + get + { + return this._historico; + } + set + { + this._historico = value; + base.OnPropertyChanged("Historico"); + } + } + + public long IdLancamento + { + get + { + return this._idLancamento; + } + set + { + this._idLancamento = value; + base.OnPropertyChanged("IdLancamento"); + } + } + + public bool Importando + { + get + { + return this.importando; + } + set + { + this.importando = value; + base.OnPropertyChanged("Importando"); + } + } + + public DateTime? Inicio + { + get + { + return this._inicio; + } + set + { + if (value.HasValue && value.Value < new DateTime(1754, 1, 1)) + { + value = new DateTime?(new DateTime(1754, 1, 1)); + } + if (value.HasValue && value.Value > new DateTime(9999, 12, 31)) + { + value = new DateTime?(new DateTime(9999, 12, 31)); + } + this._inicio = value; + base.OnPropertyChanged("Inicio"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public Visibility IsVisibleData + { + get + { + return this._isVisibleData; + } + set + { + this._isVisibleData = value; + base.OnPropertyChanged("IsVisibleData"); + } + } + + public Visibility IsVisibleFiltros + { + get + { + return this._isVisibleFiltros; + } + set + { + this._isVisibleFiltros = value; + base.OnPropertyChanged("IsVisibleFiltros"); + } + } + + public Visibility IsVisibleFornecedor + { + get + { + return this._isVisibleFornecedor; + } + set + { + this._isVisibleFornecedor = value; + base.OnPropertyChanged("IsVisibleFornecedor"); + } + } + + public Visibility IsVisibleLancamento + { + get + { + return this._isVisibleLancamento; + } + set + { + this._isVisibleLancamento = value; + base.OnPropertyChanged("IsVisibleLancamento"); + } + } + + public Visibility IsVisiblePersonalizado + { + get + { + return this._isVisiblePersonalizado; + } + set + { + this._isVisiblePersonalizado = value; + base.OnPropertyChanged("IsVisiblePersonalizado"); + } + } + + public Visibility IsvisibleStatus + { + get + { + return this._isvisibleStatus; + } + set + { + this._isvisibleStatus = value; + base.OnPropertyChanged("IsvisibleStatus"); + } + } + + public ObservableCollection Lancamentos + { + get + { + return this._lancamentos; + } + set + { + this._lancamentos = value; + base.OnPropertyChanged("Lancamentos"); + } + } + + private Lancamento LancamentoSelecionado + { + get; + set; + } + + public ObservableCollection LancamentosFiltrados + { + get + { + return this._lancamentosFiltrados; + } + set + { + if (!this._dontSort) + { + Action saveSortLancamentos = Gestor.Application.Actions.Actions.SaveSortLancamentos; + if (saveSortLancamentos != null) + { + saveSortLancamentos(); + } + else + { + } + } + this._lancamentosFiltrados = value; + this.Totalizar(); + base.OnPropertyChanged("LancamentosFiltrados"); + if (!this._dontSort) + { + Action sortLancamentos = Gestor.Application.Actions.Actions.SortLancamentos; + if (sortLancamentos == null) + { + return; + } + sortLancamentos(); + } + } + } + + public ObservableCollection LancamentosFiltradosCopia + { + get + { + return this._lancamentosFiltradosCopia; + } + set + { + this._lancamentosFiltradosCopia = value; + base.OnPropertyChanged("LancamentosFiltradosCopia"); + } + } + + public ObservableCollection LancamentosVinculo + { + get + { + return this._lancamentosVinculo; + } + set + { + this._lancamentosVinculo = value; + base.OnPropertyChanged("LancamentosVinculo"); + } + } + + public Lancamento LancamentoVinculo + { + get + { + return this._lancamentoVinculo; + } + set + { + this._lancamentoVinculo = value; + base.OnPropertyChanged("LancamentoVinculo"); + } + } + + public bool NotImportando + { + get + { + return !this.Importando; + } + } + + public string Observacao + { + get + { + return this._observacao; + } + set + { + this._observacao = value; + base.OnPropertyChanged("Observacao"); + } + } + + public DateTime? Pagamento + { + get + { + return this._pagamento; + } + set + { + this._pagamento = value; + base.OnPropertyChanged("Pagamento"); + } + } + + public int Parcela + { + get + { + return this._parcela; + } + set + { + this._parcela = value; + base.OnPropertyChanged("Parcela"); + } + } + + public int Parcelas + { + get + { + return this._parcelas; + } + set + { + this._parcelas = value; + base.OnPropertyChanged("Parcelas"); + } + } + + public ObservableCollection PersonalizadoSelecionado + { + get + { + return this._personalizadoSelecionado; + } + set + { + this._personalizadoSelecionado = value; + base.OnPropertyChanged("PersonalizadoSelecionado"); + } + } + + public Gestor.Model.Domain.Financeiro.Planos Plano + { + get + { + return this._plano; + } + set + { + this._plano = value; + base.OnPropertyChanged("Plano"); + if (value == null || value.get_Id() == 0) + { + return; + } + this.Sinal = (this.importando ? this.Sinal : value.get_Sinal()); + } + } + + public List Planos + { + get + { + return this._planos; + } + set + { + this._planos = value; + base.OnPropertyChanged("Planos"); + } + } + + public ObservableCollection PlanosFiltrados + { + get + { + return this._planosFiltrados; + } + set + { + this._planosFiltrados = value; + base.OnPropertyChanged("PlanosFiltrados"); + } + } + + public List PlanosFiltro + { + get + { + return this._planosFiltro; + } + set + { + this._planosFiltro = value; + base.OnPropertyChanged("PlanosFiltro"); + } + } + + public List RelatorioFiltroPersonalizado + { + get + { + return this._filtroRelatorioPersonalizado; + } + set + { + this._filtroRelatorioPersonalizado = value; + base.OnPropertyChanged("RelatorioFiltroPersonalizado"); + } + } + + public ObservableCollection Saldos + { + get + { + return this._saldos; + } + set + { + this._saldos = value; + base.OnPropertyChanged("Saldos"); + } + } + + private bool Salvando + { + get; + set; + } + + public FiltroLancamento SelectedFiltro + { + get + { + return this._selectedFiltro; + } + set + { + this._selectedFiltro = value; + this.LimparLancamentos(); + base.OnPropertyChanged("SelectedFiltro"); + } + } + + public FiltroLancamentoData SelectedFiltroData + { + get + { + return this._selectedFiltroData; + } + set + { + this._selectedFiltroData = value; + this.LimparLancamentos(); + base.OnPropertyChanged("SelectedFiltroData"); + } + } + + public Fornecedor SelectedFornecedor + { + get + { + return this._selectedFornecedor; + } + set + { + this._selectedFornecedor = value; + this.LimparLancamentos(); + base.OnPropertyChanged("SelectedFornecedor"); + } + } + + public Lancamento SelectedLancamento + { + get + { + return this._selectedLancamento; + } + set + { + bool id; + bool flag; + bool id1; + if (value != null && value.get_Id() != 0) + { + this.IdLancamento = value.get_Id(); + } + else if (this.importando) + { + this.IdLancamento = (long)0; + } + if (value == null || value.get_Id() <= (long)0) + { + id = false; + } + else + { + Usuario usuario = Recursos.Usuario; + if (usuario != null) + { + id = usuario.get_Id() > (long)0; + } + else + { + id = false; + } + } + this.EnableIncluirNovo = id; + this._selectedLancamento = value; + if (value == null || value.get_Id() <= (long)0) + { + flag = false; + } + else + { + Usuario usuario1 = Recursos.Usuario; + if (usuario1 != null) + { + flag = usuario1.get_Id() > (long)0; + } + else + { + flag = false; + } + } + base.EnableButtons = flag; + Usuario usuario2 = Recursos.Usuario; + if (usuario2 != null) + { + id1 = usuario2.get_Id() > (long)0; + } + else + { + id1 = false; + } + this.EnableChanges = id1; + this.Alteracao = (value == null ? false : value.get_Controle().get_Id() > (long)0); + base.OnPropertyChanged("SelectedLancamento"); + this.Feed(value); + if (value == null || value.get_Id() == 0) + { + return; + } + this.LancamentoSelecionado = value; + } + } + + public Saldo SelectedSaldo + { + get + { + return this._selectedSaldo; + } + set + { + this._selectedSaldo = value; + base.OnPropertyChanged("SelectedSaldo"); + } + } + + public StatusLancamento SelectedStatus + { + get + { + return this._selectedStatus; + } + set + { + this._selectedStatus = value; + this.LimparLancamentos(); + base.OnPropertyChanged("SelectedStatus"); + } + } + + public StatusLancamento SelectedStatusImportacao + { + get + { + return this._selectedStatusImportacao; + } + set + { + this._selectedStatusImportacao = value; + base.OnPropertyChanged("SelectedStatusImportacao"); + } + } + + public bool SemValor + { + get + { + return this._semValor; + } + set + { + this._semValor = value; + if (value) + { + this.ValorInicial = null; + this.ValorFinal = null; + } + base.OnPropertyChanged("SemValor"); + } + } + + public Gestor.Model.Common.Sinal Sinal + { + get + { + return this._sinal; + } + set + { + this._sinal = value; + base.OnPropertyChanged("Sinal"); + } + } + + public SinteticoFinanceiroTipo SinteticoTipo + { + get + { + return this._sinteticoTipo; + } + set + { + this._sinteticoTipo = value; + base.OnPropertyChanged("SinteticoTipo"); + } + } + + public Type TipoDateTime + { + get + { + return this._tipoDateTime; + } + set + { + this._tipoDateTime = value; + base.OnPropertyChanged("TipoDateTime"); + } + } + + public Type TipoDecimal + { + get + { + return this._tipoDecimal; + } + set + { + this._tipoDecimal = value; + base.OnPropertyChanged("TipoDecimal"); + } + } + + public Type TipoEnum + { + get + { + return this._tipoEnum; + } + set + { + this._tipoEnum = value; + base.OnPropertyChanged("TipoEnum"); + } + } + + public Type TipoInt + { + get + { + return this._tipoInt; + } + set + { + this._tipoInt = value; + base.OnPropertyChanged("TipoInt"); + } + } + + public Type TipoLong + { + get + { + return this._tipoLong; + } + set + { + this._tipoLong = value; + base.OnPropertyChanged("TipoLong"); + } + } + + public Gestor.Model.Common.TipoPagamento TipoPagamento + { + get + { + return this._tipoPagamento; + } + set + { + this._tipoPagamento = value; + base.OnPropertyChanged("TipoPagamento"); + } + } + + public Type TipoString + { + get + { + return this._tipoString; + } + set + { + this._tipoString = value; + base.OnPropertyChanged("TipoString"); + } + } + + public ObservableCollection Totalizacao + { + get + { + return this._totalizacao; + } + set + { + this._totalizacao = value; + base.OnPropertyChanged("Totalizacao"); + } + } + + public Func>> ValidationEvent + { + get + { + return new Func>>(this.ValidateIncluir); + } + } + + public decimal Valor + { + get + { + return this._valor; + } + set + { + this._valor = value; + if (this.Vencimento <= Funcoes.GetNetworkTime().Date) + { + this.ValorPago = new decimal?(value); + } + base.OnPropertyChanged("Valor"); + } + } + + public string ValorFinal + { + get + { + return this._valorFinal; + } + set + { + this._valorFinal = value; + base.OnPropertyChanged("ValorFinal"); + } + } + + public string ValorInicial + { + get + { + return this._valorIncial; + } + set + { + this._valorIncial = value; + base.OnPropertyChanged("ValorInicial"); + } + } + + public decimal? ValorPago + { + get + { + return this._valorPago; + } + set + { + this._valorPago = value; + base.OnPropertyChanged("ValorPago"); + } + } + + public DateTime Vencimento + { + get + { + return this._vencimento; + } + set + { + if (this.Alterando == Visibility.Visible && value != this.VencimentoAnt) + { + this.VencimentoAlterado = true; + } + this.VencimentoAnt = value; + this._vencimento = value; + base.OnPropertyChanged("Vencimento"); + } + } + + public DateTime VencimentoAnt + { + get; + set; + } + + public Visibility VisibilityCentro + { + get + { + return this._visibilityCentro; + } + set + { + this._visibilityCentro = value; + base.OnPropertyChanged("VisibilityCentro"); + } + } + + public Visibility VisibilityConta + { + get + { + return this._visibilityConta; + } + set + { + this._visibilityConta = value; + base.OnPropertyChanged("VisibilityConta"); + } + } + + public Visibility VisibilityFornecedor + { + get + { + return this._visibilityFornecedor; + } + set + { + this._visibilityFornecedor = value; + base.OnPropertyChanged("VisibilityFornecedor"); + } + } + + public Visibility VisibilitySemValor + { + get + { + return this._visibilitySemValor; + } + set + { + this._visibilitySemValor = value; + base.OnPropertyChanged("VisibilitySemValor"); + } + } + + public Visibility VisibleFiltros + { + get + { + return this._visibleFiltros; + } + set + { + this._visibleFiltros = value; + base.OnPropertyChanged("VisibleFiltros"); + } + } + + public Visibility VisibleOlho + { + get + { + return this._visibleOlho; + } + set + { + this._visibleOlho = value; + base.OnPropertyChanged("VisibleOlho"); + } + } + + public FinanceiroViewModel() + { + this._servico = new FinanceiroServico(); + this.RelatorioFiltroPersonalizado = Funcoes.PopularFiltroFinanceiro(); + this.BuscaInicial(); + } + + public async void AdcionarFiltroPersonalizado() + { + string str; + DateTime dateTime; + decimal num; + int num1; + long num2; + List filtroPersonalizados; + List filtroPersonalizados1; + if (this.Filtro != null) + { + if (this.SemValor) + { + filtroPersonalizados = (this.PersonalizadoSelecionado == null ? new List() : ( + from x in this.PersonalizadoSelecionado + where x.get_Propriedade() == this.Filtro.get_Propriedade() + select x).ToList()); + List filtroPersonalizados2 = filtroPersonalizados; + if (filtroPersonalizados2.Count > 0) + { + filtroPersonalizados2.ForEach((Gestor.Model.Domain.Relatorios.FiltroPersonalizado x) => this.PersonalizadoSelecionado.Remove(x)); + } + str = string.Concat(this.Filtro.get_Nome(), ": EM BRANCO"); + } + else + { + filtroPersonalizados1 = (this.PersonalizadoSelecionado == null ? new List() : this.PersonalizadoSelecionado.Where((Gestor.Model.Domain.Relatorios.FiltroPersonalizado x) => { + if (x.get_Propriedade() != this.Filtro.get_Propriedade()) + { + return false; + } + return x.get_SemValor(); + }).ToList()); + List filtroPersonalizados3 = filtroPersonalizados1; + if (filtroPersonalizados3.Count > 0) + { + filtroPersonalizados3.ForEach((Gestor.Model.Domain.Relatorios.FiltroPersonalizado x) => this.PersonalizadoSelecionado.Remove(x)); + } + string name = this.Filtro.get_Tipo().Name; + if (name == "DateTime") + { + if (!DateTime.TryParse(this.ValorInicial, out dateTime) || !DateTime.TryParse(this.ValorFinal, out dateTime) || DateTime.Parse(this.ValorInicial) > DateTime.Parse(this.ValorFinal)) + { + await base.ShowMessage("O VALOR DE INTERVALO DEVE SER PREENCHIDO CORRETAMENTE.", "OK", "", false); + return; + } + else + { + str = string.Format("{0}: {1:d} até {2:d}", this.Filtro.get_Nome(), DateTime.Parse(this.ValorInicial), DateTime.Parse(this.ValorFinal)); + } + } + else if (name == "Decimal") + { + if (!decimal.TryParse(this.ValorInicial, out num) || !decimal.TryParse(this.ValorFinal, out num) || Math.Abs(decimal.Parse(this.ValorInicial)) > Math.Abs(decimal.Parse(this.ValorFinal))) + { + await base.ShowMessage("O VALOR DE INTERVALO DEVE SER PREENCHIDO CORRETAMENTE.", "OK", "", false); + return; + } + else + { + str = string.Format("{0}: {1:n2} até {2:n2}", this.Filtro.get_Nome(), decimal.Parse(this.ValorInicial), decimal.Parse(this.ValorFinal)); + } + } + else if (name == "Int32") + { + if (!int.TryParse(this.ValorInicial, out num1) || !int.TryParse(this.ValorFinal, out num1) || int.Parse(this.ValorInicial) > int.Parse(this.ValorFinal)) + { + await base.ShowMessage("O VALOR DE INTERVALO DEVE SER PREENCHIDO CORRETAMENTE.", "OK", "", false); + return; + } + else + { + str = string.Format("{0}: {1:n0} até {2:n0}", this.Filtro.get_Nome(), int.Parse(this.ValorInicial), int.Parse(this.ValorFinal)); + } + } + else if (name != "Int64") + { + if (!string.IsNullOrEmpty(this.ValorInicial)) + { + str = string.Concat(this.Filtro.get_Nome(), " = ", this.ValorInicial); + } + else + { + await base.ShowMessage("O VALOR DEVE SER PREENCHIDO CORRETAMENTE.", "OK", "", false); + return; + } + } + else if (!long.TryParse(this.ValorInicial, out num2) || !long.TryParse(this.ValorFinal, out num2) || long.Parse(this.ValorInicial) > (long)int.Parse(this.ValorFinal)) + { + await base.ShowMessage("O VALOR DE INTERVALO DEVE SER PREENCHIDO CORRETAMENTE.", "OK", "", false); + return; + } + else + { + str = string.Format("{0}: {1:n0} até {2:n0}", this.Filtro.get_Nome(), long.Parse(this.ValorInicial), long.Parse(this.ValorFinal)); + } + } + if (this.PersonalizadoSelecionado == null) + { + this.PersonalizadoSelecionado = new ObservableCollection(); + } + ObservableCollection personalizadoSelecionado = this.PersonalizadoSelecionado; + Gestor.Model.Domain.Relatorios.FiltroPersonalizado filtroPersonalizado = new Gestor.Model.Domain.Relatorios.FiltroPersonalizado(); + filtroPersonalizado.set_Nome(this.Filtro.get_Nome()); + filtroPersonalizado.set_Propriedade(this.Filtro.get_Propriedade()); + filtroPersonalizado.set_Tipo(this.Filtro.get_Tipo()); + filtroPersonalizado.set_ValorIncial(this.ValorInicial); + filtroPersonalizado.set_ValorFinal(this.ValorFinal); + filtroPersonalizado.set_SemValor(this.SemValor); + filtroPersonalizado.set_Descricao(str); + personalizadoSelecionado.Add(filtroPersonalizado); + this.Filtro = null; + this.ValorInicial = string.Empty; + this.ValorFinal = string.Empty; + this.PesquisaPersonalizada(); + } + } + + public void AdicionarFiltro(Gestor.Model.Domain.Financeiro.FiltroPersonalizado filtro) + { + if (filtro == null) + { + return; + } + if (this.FiltroPersonalizadoSelecionado == null) + { + this.FiltroPersonalizadoSelecionado = new ObservableCollection(); + } + this.VisibleFiltros = Visibility.Visible; + if (this.FiltroPersonalizadoSelecionado.Any((Gestor.Model.Domain.Financeiro.FiltroPersonalizado x) => { + if (x.get_Id() != filtro.get_Id()) + { + return false; + } + return x.get_Tipo() == filtro.get_Tipo(); + })) + { + return; + } + this.FiltroPersonalizadoSelecionado.Add(filtro); + this.FiltrarPersonalizado(); + } + + public void AdicionarFiltros() + { + ExtensionMethods.ForEach( + from x in this.PlanosFiltro + where x.get_Selecionado() + select x, (Gestor.Model.Domain.Financeiro.Planos x) => { + Gestor.Model.Domain.Financeiro.FiltroPersonalizado filtroPersonalizado = new Gestor.Model.Domain.Financeiro.FiltroPersonalizado(); + filtroPersonalizado.set_Id(x.get_Id()); + filtroPersonalizado.set_Tipo(1); + filtroPersonalizado.set_Descricao(x.get_Descricao()); + this.AdicionarFiltro(filtroPersonalizado); + }); + this.PlanosFiltro = new List( + from x in this.Planos + orderby x.get_Descricao() + select x); + ExtensionMethods.ForEach( + from x in this.ContaFiltro + where x.get_Selecionado() + select x, (BancosContas x) => { + Gestor.Model.Domain.Financeiro.FiltroPersonalizado filtroPersonalizado = new Gestor.Model.Domain.Financeiro.FiltroPersonalizado(); + filtroPersonalizado.set_Id(x.get_Id()); + filtroPersonalizado.set_Tipo(3); + filtroPersonalizado.set_Descricao(x.get_Descricao()); + this.AdicionarFiltro(filtroPersonalizado); + }); + this.ContaFiltro = new List( + from x in this.Contas + orderby x.get_Descricao() + select x); + ExtensionMethods.ForEach( + from x in this.CentroFiltro + where x.get_Selecionado() + select x, (Gestor.Model.Domain.Financeiro.Centro x) => { + Gestor.Model.Domain.Financeiro.FiltroPersonalizado filtroPersonalizado = new Gestor.Model.Domain.Financeiro.FiltroPersonalizado(); + filtroPersonalizado.set_Id(x.get_Id()); + filtroPersonalizado.set_Tipo(2); + filtroPersonalizado.set_Descricao(x.get_Descricao()); + this.AdicionarFiltro(filtroPersonalizado); + x.set_Selecionado(false); + }); + this.CentroFiltro = new List( + from x in this.Centros + orderby x.get_Descricao() + select x); + } + + private async Task AdicionarParcelaRange() + { + base.Loading(true); + List lancamentos = new List(); + ObservableCollection lancamentosFiltrados = this.LancamentosFiltrados; + IEnumerable selecionado = + from x in lancamentosFiltrados + where x.get_Selecionado() + select x; + List list = selecionado.Select((Lancamento x) => { + Lancamento lancamento = new Lancamento(); + ControleFinanceiro controleFinanceiro = new ControleFinanceiro(); + controleFinanceiro.set_Centro(x.get_Controle().get_Centro()); + controleFinanceiro.set_Fornecedor(x.get_Controle().get_Fornecedor()); + controleFinanceiro.set_Historico(x.get_Controle().get_Historico()); + controleFinanceiro.set_Id(x.get_Controle().get_Id()); + controleFinanceiro.set_Parcelas(x.get_Controle().get_Parcelas() + 1); + controleFinanceiro.set_Plano(x.get_Controle().get_Plano()); + lancamento.set_Controle(controleFinanceiro); + lancamento.set_Historico(x.get_Historico()); + lancamento.set_Observacao(x.get_Observacao()); + lancamento.set_Vencimento(x.get_Vencimento().AddMonths(1)); + lancamento.set_Conta(x.get_Conta()); + lancamento.set_Parcela(x.get_Parcela() + 1); + lancamento.set_Documento(x.get_Documento()); + lancamento.set_Sinal(x.get_Sinal()); + lancamento.set_TipoPagamento(x.get_TipoPagamento()); + lancamento.set_Valor(x.get_Valor()); + return lancamento; + }).ToList(); + foreach (Lancamento lancamento1 in list) + { + if (await this._servico.BuscarLancamento(lancamento1.get_Controle().get_Id(), lancamento1.get_Parcela()) != null) + { + continue; + } + lancamentos.Add(lancamento1); + } + await this._servico.IncluirRange(lancamentos); + if (this._servico.Sucesso) + { + await this.Buscar(); + base.ToggleSnackBar("INCLUSÃO DE PARCELA REALIZADA COM SUCESSO", true); + base.Loading(false); + } + else + { + base.Loading(false); + } + lancamentos = null; + } + + public async Task AlterarLancamentos(Lancamento lancamentoAtual, bool alterarVencimento, bool alterarValores) + { + Func func = null; + List lancamentos = await this._servico.BuscarLancamentosPorControle(lancamentoAtual.get_Controle().get_Id()); + int num = 1; + List lancamentos1 = lancamentos; + Func func1 = func; + if (func1 == null) + { + Func parcela = (Lancamento l) => l.get_Parcela() > lancamentoAtual.get_Parcela(); + Func func2 = parcela; + func = parcela; + func1 = func2; + } + foreach (Lancamento lancamento in lancamentos1.Where(func1)) + { + if (!lancamento.get_Baixado()) + { + if (alterarVencimento) + { + lancamento.set_Vencimento(lancamentoAtual.get_Vencimento().AddMonths(num)); + } + if (alterarValores) + { + lancamento.set_Valor(lancamentoAtual.get_Valor()); + } + await this._servico.Save(lancamento); + } + num++; + } + this.SelectedLancamento = lancamentoAtual; + } + + public async Task Atualizar(List list) + { + DateTime? baixa; + DateTime? nullable; + string str; + bool flag; + base.Loading(true); + List lancamentos = new List(); + List lancamentos1 = new List(); + List lancamentos2 = new List(); + foreach (Lancamento lancamento in list) + { + if (lancamento.get_Baixado()) + { + continue; + } + if (!lancamento.get_Selecionado()) + { + baixa = null; + lancamento.set_Baixa(baixa); + } + baixa = lancamento.get_Baixa(); + if (baixa.HasValue) + { + Saldo saldo = await this.VerificaSaldo(lancamento.get_Conta().get_Id(), false); + if (saldo == null) + { + continue; + } + baixa = saldo.get_DataInicio(); + nullable = lancamento.get_Baixa(); + flag = (baixa.HasValue & nullable.HasValue ? baixa.GetValueOrDefault() > nullable.GetValueOrDefault() : false); + if (flag) + { + continue; + } + } + if (lancamento.get_Selecionado()) + { + str = (lancamento.get_Observacao() == null ? "" : string.Concat("\n ", lancamento.get_Observacao())); + string str1 = str; + Lancamento lancamento1 = lancamento; + object[] id = new object[] { Recursos.Usuario.get_Id(), Recursos.Usuario.get_Nome(), null, null }; + DateTime networkTime = Funcoes.GetNetworkTime(); + id[2] = networkTime.ToString("F").ToUpper(); + id[3] = str1; + lancamento1.set_Observacao(string.Format("BAIXA AGRUPADA REALIZADA PELO USUARIO {0} {1} EM {2}{3}", id)); + } + List> keyValuePairs = lancamento.Validate(); + if (keyValuePairs != null && keyValuePairs.Count > 0) + { + continue; + } + nullable = lancamento.get_Baixa(); + if (!nullable.HasValue) + { + lancamentos.Add(lancamento); + } + else + { + lancamentos1.Add(lancamento); + } + lancamentos2.Add(lancamento); + } + if (lancamentos2.Count != 0) + { + object[] count = new object[] { lancamentos.Count, Environment.NewLine, lancamentos1.Count, Environment.NewLine, Environment.NewLine }; + if (await base.ShowMessage(string.Format("{0} LANÇAMENTOS SERÃO ATUALIZADOS.{1}{2} LANÇAMENTOS SERÃO BAIXADOS.{3}{4}DESEJA REALMENTE PROSSEGUIR?", count), "SIM", "NÃO", false)) + { + await this._servico.Atualizar(lancamentos2); + if (this._servico.Sucesso) + { + if (await base.ShowMessage("DESEJA GERAR O RELATÓRIO NOVAMENTE?", "SIM,", "NÃO", false)) + { + await this.Buscar(); + } + base.ToggleSnackBar("ATUALIZAÇÃO REALIZADA COM SUCESSO", true); + await this.CarregarSaldos(); + base.Loading(false); + } + else + { + base.Loading(false); + } + } + else + { + base.Loading(false); + } + } + else + { + await base.ShowMessage("NÃO HÁ LANÇAMENTOS PARA SEREM ATUALIZADOS.", "OK", "", false); + base.Loading(false); + } + lancamentos = null; + lancamentos1 = null; + lancamentos2 = null; + } + + public void Bind() + { + // + // Current member / type: System.Void Gestor.Application.ViewModels.Financeiro.FinanceiroViewModel::Bind() + // File path: C:\AggerSeguros\Gestor.Application.exe + // + // Product version: 0.0.0.0 + // Exception in: System.Void Bind() + // + // Object reference not set to an instance of an object. + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.FindLowestCommonAncestor(ICollection`1 typeNodes) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 515 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.MergeWithLowestCommonAncestor() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 459 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.ProcessSingleConstraints() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 378 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.InferTypes() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 331 + // at Telerik.JustDecompiler.Decompiler.ExpressionDecompilerStep.Process(DecompilationContext theContext, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\ExpressionDecompilerStep.cs:line 104 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61 + // at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 133 + // + // mailto: JustDecompilePublicFeedback@telerik.com + + } + + public void BindImportando() + { + // + // Current member / type: System.Void Gestor.Application.ViewModels.Financeiro.FinanceiroViewModel::BindImportando() + // File path: C:\AggerSeguros\Gestor.Application.exe + // + // Product version: 0.0.0.0 + // Exception in: System.Void BindImportando() + // + // Object reference not set to an instance of an object. + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.FindLowestCommonAncestor(ICollection`1 typeNodes) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 515 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.MergeWithLowestCommonAncestor() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 459 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.ProcessSingleConstraints() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 378 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.InferTypes() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 331 + // at Telerik.JustDecompiler.Decompiler.ExpressionDecompilerStep.Process(DecompilationContext theContext, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\ExpressionDecompilerStep.cs:line 104 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61 + // at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 133 + // + // mailto: JustDecompilePublicFeedback@telerik.com + + } + + private async void BuscaInicial() + { + base.Loading(true); + this.Planos = await (new PlanoServico()).BuscarPlanos(); + FinanceiroViewModel observableCollection = this; + List planos = this.Planos; + IEnumerable ativo = + from x in planos + where x.get_Ativo() + select x; + observableCollection.PlanosFiltrados = new ObservableCollection( + from x in ativo + orderby x.get_Descricao() + select x); + this.Contas = await (new BancosContasServico()).BuscarBancos(); + FinanceiroViewModel financeiroViewModel = this; + List contas = this.Contas; + IEnumerable bancosContas = + from x in contas + where x.get_Ativo() + select x; + financeiroViewModel.ContasFiltradas = new ObservableCollection( + from x in bancosContas + orderby x.get_Descricao() + select x); + this.Centros = await (new CentroServico()).BuscarCentros(); + FinanceiroViewModel observableCollection1 = this; + List centros = this.Centros; + IEnumerable ativo1 = + from x in centros + where x.get_Ativo() + select x; + observableCollection1.CentrosFiltrados = new ObservableCollection( + from x in ativo1 + orderby x.get_Descricao() + select x); + FinanceiroViewModel planos1 = this; + List planos2 = this.Planos; + planos1.PlanosFiltro = new List( + from x in planos2 + orderby x.get_Descricao() + select x); + FinanceiroViewModel bancosContas1 = this; + List contas1 = this.Contas; + bancosContas1.ContaFiltro = new List( + from x in contas1 + orderby x.get_Descricao() + select x); + FinanceiroViewModel centros1 = this; + List centros2 = this.Centros; + centros1.CentroFiltro = new List( + from x in centros2 + orderby x.get_Descricao() + select x); + this.PopularFiltro(); + await this.Buscar(); + base.Loading(false); + } + + public async Task Buscar() + { + List list; + bool flag; + List nums; + List list1; + List nums1; + List list2; + List nums2; + this.Importando = false; + DateTime? inicio = this.Inicio; + if (inicio.HasValue) + { + inicio = this.Fim; + if (inicio.HasValue) + { + inicio = this.Inicio; + DateTime? fim = this.Fim; + flag = (inicio.HasValue & fim.HasValue ? inicio.GetValueOrDefault() > fim.GetValueOrDefault() : false); + if (!flag) + { + this.PersonalizadoSelecionado = null; + switch (this.SelectedFiltro) + { + case 1: + { + FinanceiroServico financeiroServico = this._servico; + fim = this.Inicio; + DateTime value = fim.Value; + fim = this.Fim; + list = await financeiroServico.BuscarLancamentosPorBaixa(value, fim.Value); + break; + } + case 2: + { + FinanceiroServico financeiroServico1 = this._servico; + fim = this.Inicio; + DateTime dateTime = fim.Value; + fim = this.Fim; + list = await financeiroServico1.BuscarLancamentosPorPagamento(dateTime, fim.Value); + break; + } + case 3: + { + if (this.SelectedFornecedor != null) + { + list = await this._servico.BuscarLancamentosPorFornecedor(this.SelectedFornecedor.get_Id(), this.SelectedStatus); + break; + } + else + { + return; + } + } + case 4: + { + FinanceiroServico financeiroServico2 = this._servico; + fim = this.Inicio; + DateTime value1 = fim.Value; + fim = this.Fim; + list = await financeiroServico2.BuscarLancamentosPorLancamento(value1, fim.Value, this.SelectedStatus); + break; + } + case 5: + { + FinanceiroServico financeiroServico3 = this._servico; + fim = this.Inicio; + DateTime dateTime1 = fim.Value; + fim = this.Fim; + List lancamentos = await financeiroServico3.BuscarLancamentosPersonalizados(dateTime1, fim.Value, this.SelectedStatus, this.SelectedFiltroData); + if (this.FiltroPersonalizadoSelecionado != null) + { + ObservableCollection filtroPersonalizadoSelecionado = this.FiltroPersonalizadoSelecionado; + IEnumerable tipo = + from x in filtroPersonalizadoSelecionado + where x.get_Tipo() == 0 + select x; + nums = ( + from x in tipo + select x.get_Id()).ToList(); + } + else + { + nums = new List(); + } + List nums3 = nums; + if (this.FiltroPersonalizadoSelecionado != null) + { + ObservableCollection observableCollection = this.FiltroPersonalizadoSelecionado; + IEnumerable filtroPersonalizados = + from x in observableCollection + where x.get_Tipo() == 2 + select x; + list1 = ( + from x in filtroPersonalizados + select x.get_Id()).ToList(); + } + else + { + list1 = new List(); + } + List nums4 = list1; + if (this.FiltroPersonalizadoSelecionado != null) + { + ObservableCollection filtroPersonalizadoSelecionado1 = this.FiltroPersonalizadoSelecionado; + IEnumerable tipo1 = + from x in filtroPersonalizadoSelecionado1 + where x.get_Tipo() == 1 + select x; + nums1 = ( + from x in tipo1 + select x.get_Id()).ToList(); + } + else + { + nums1 = new List(); + } + List nums5 = nums1; + if (this.FiltroPersonalizadoSelecionado != null) + { + ObservableCollection observableCollection1 = this.FiltroPersonalizadoSelecionado; + IEnumerable filtroPersonalizados1 = + from x in observableCollection1 + where x.get_Tipo() == 3 + select x; + list2 = ( + from x in filtroPersonalizados1 + select x.get_Id()).ToList(); + } + else + { + list2 = new List(); + } + List nums6 = list2; + if (this.FiltroPersonalizadoSelecionado != null) + { + ObservableCollection filtroPersonalizadoSelecionado2 = this.FiltroPersonalizadoSelecionado; + IEnumerable tipo2 = + from x in filtroPersonalizadoSelecionado2 + where x.get_Tipo() == 4 + select x; + nums2 = ( + from x in tipo2 + select x.get_Id()).ToList(); + } + else + { + nums2 = new List(); + } + List nums7 = nums2; + list = lancamentos.Where((Lancamento x) => { + if (nums3.Count != 0 && (x.get_Controle().get_Fornecedor() == null || !nums3.Contains(x.get_Controle().get_Fornecedor().get_Id())) || nums4.Count != 0 && (x.get_Controle().get_Centro() == null || !nums4.Contains(x.get_Controle().get_Centro().get_Id())) || nums5.Count != 0 && (x.get_Controle().get_Plano() == null || !nums5.Contains(x.get_Controle().get_Plano().get_Id())) || nums6.Count != 0 && (x.get_Conta() == null || !nums6.Contains(x.get_Conta().get_Id()))) + { + return false; + } + if (nums7.Count == 0) + { + return true; + } + return nums7.Contains((long)x.get_Sinal()); + }).ToList(); + break; + } + default: + { + FinanceiroServico financeiroServico4 = this._servico; + fim = this.Inicio; + DateTime value2 = fim.Value; + fim = this.Fim; + list = await financeiroServico4.BuscarLancamentos(value2, fim.Value, this.SelectedStatus); + break; + } + } + List lancamentos1 = list; + lancamentos1.ForEach((Lancamento x) => x.Initialize()); + this.Lancamentos = new ObservableCollection(list); + this.LancamentosFiltrados = this.Lancamentos; + this.LancamentosFiltradosCopia = this.LancamentosFiltrados; + this.SelectedLancamento = this.LancamentosFiltrados.FirstOrDefault(); + await this.CarregarSaldos(); + return; + } + else + { + await base.ShowMessage("A DATA DE INÍCIO NÃO PODE SER SUPERIOR A DATA FINAL.", "OK", "", false); + return; + } + } + } + await base.ShowMessage("NECESSÁRIO PREENCHER TANTO A DATA DE INÍCIO QUANTO A DATA FINAL PARA REALIZAR A PESQUISA.", "OK", "", false); + } + + internal async Task BuscarLancamentosVinculo() + { + DateTime vencimento; + DateTime? dataInicio; + DateTime valueOrDefault; + if (this.SelectedLancamento.get_Conta() != null) + { + Saldo saldo = this.Saldos.FirstOrDefault((Saldo x) => x.get_Id() == this.SelectedLancamento.get_Conta().get_Id()); + if (saldo != null) + { + dataInicio = saldo.get_DataInicio(); + } + else + { + dataInicio = null; + } + } + else + { + vencimento = this.SelectedLancamento.get_Vencimento(); + dataInicio = new DateTime?(vencimento.AddDays(-5)); + } + DateTime? nullable = dataInicio; + if (nullable.HasValue) + { + valueOrDefault = nullable.GetValueOrDefault(); + } + else + { + vencimento = this.SelectedLancamento.get_Vencimento(); + valueOrDefault = vencimento.AddDays(-5); + } + DateTime dateTime = valueOrDefault; + List list = await this._servico.BuscarLancamentosPorFornecedor(this.FornecedorInclusao.get_Id(), dateTime, this.Sinal); + ObservableCollection lancamentos = this.Lancamentos; + List nums = ( + from x in lancamentos + select x.get_Id()).ToList(); + list = ( + from x in list + where !nums.Contains(x.get_Id()) + select x).ToList(); + this.LancamentosVinculo = new ObservableCollection(list); + } + + public void CancelarAlteracao() + { + this.LancamentosFiltrados = this.LancamentosFiltradosCopia; + this.SelectedLancamento = this.LancamentosFiltrados.FirstOrDefault((Lancamento x) => { + long? nullable; + long id = x.get_Id(); + Lancamento lancamentoSelecionado = this.LancamentoSelecionado; + if (lancamentoSelecionado != null) + { + nullable = new long?(lancamentoSelecionado.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + return id == nullable1.GetValueOrDefault() & nullable1.HasValue; + }); + } + + public async Task CarregarSaldos() + { + this.Saldos = new ObservableCollection(); + BancosContasServico bancosContasServico = new BancosContasServico(); + foreach (BancosContas contasFiltrada in this.ContasFiltradas) + { + Saldo saldo = await bancosContasServico.BuscarSaldoAberto(contasFiltrada.get_Id()); + if (saldo == null) + { + continue; + } + DateTime date = Funcoes.GetNetworkTime().Date; + saldo.set_DataFinal(new DateTime?(date.AddDays(1))); + saldo = await bancosContasServico.FecharSaldo(saldo); + this.Saldos.Add(saldo); + } + this.SelectedSaldo = this.Saldos.FirstOrDefault(); + bancosContasServico = null; + } + + private Tuple CorrigeLancamentos(OfxDocument lancamentos, List codigoBanco) + { + DateTime? nullable; + DateTime? nullable1; + DateTime? nullable2; + if (!this.VerificaFiltroErrado(lancamentos)) + { + if (this.VerificaDataInvertida(lancamentos)) + { + return new Tuple(lancamentos.get_StatementEnd(), lancamentos.get_StatementStart()); + } + return new Tuple(lancamentos.get_StatementStart(), lancamentos.get_StatementEnd()); + } + Transaction transaction = ( + from lanc in lancamentos.get_Transactions() + orderby lanc.get_Date() + select lanc).First(); + if (transaction != null) + { + nullable1 = new DateTime?(transaction.get_Date()); + } + else + { + nullable = null; + nullable1 = nullable; + } + nullable = nullable1; + DateTime value = nullable.Value; + Transaction transaction1 = ( + from lanc in lancamentos.get_Transactions() + orderby lanc.get_Date() descending + select lanc).First(); + if (transaction1 != null) + { + nullable2 = new DateTime?(transaction1.get_Date()); + } + else + { + nullable = null; + nullable2 = nullable; + } + nullable = nullable2; + return new Tuple(value, nullable.Value); + } + + public void DeSelecionarLancamento(Lancamento lancamento) + { + Lancamento lancamento1 = (lancamento.get_Id() > (long)0 ? this.LancamentosFiltrados.First((Lancamento x) => x.get_Id() == lancamento.get_Id()) : this.LancamentosFiltrados.First((Lancamento x) => { + long? nullable; + long? nullable1; + long? nullable2; + long? nullable3; + long? nullable4; + if (x.get_Id() == lancamento.get_Id()) + { + ControleFinanceiro controle = x.get_Controle(); + if (controle != null) + { + Fornecedor fornecedor = controle.get_Fornecedor(); + if (fornecedor != null) + { + nullable1 = new long?(fornecedor.get_Id()); + } + else + { + nullable = null; + nullable1 = nullable; + } + } + else + { + nullable = null; + nullable1 = nullable; + } + long? nullable5 = nullable1; + ControleFinanceiro controleFinanceiro = lancamento.get_Controle(); + if (controleFinanceiro != null) + { + Fornecedor fornecedor1 = controleFinanceiro.get_Fornecedor(); + if (fornecedor1 != null) + { + nullable2 = new long?(fornecedor1.get_Id()); + } + else + { + nullable = null; + nullable2 = nullable; + } + } + else + { + nullable = null; + nullable2 = nullable; + } + long? nullable6 = nullable2; + if (nullable5.GetValueOrDefault() == nullable6.GetValueOrDefault() & nullable5.HasValue == nullable6.HasValue && x.get_Valor() == lancamento.get_Valor() && x.get_Vencimento() == lancamento.get_Vencimento()) + { + ControleFinanceiro controle1 = x.get_Controle(); + if (controle1 != null) + { + Gestor.Model.Domain.Financeiro.Planos plano = controle1.get_Plano(); + if (plano != null) + { + nullable3 = new long?(plano.get_Id()); + } + else + { + nullable = null; + nullable3 = nullable; + } + } + else + { + nullable = null; + nullable3 = nullable; + } + nullable6 = nullable3; + ControleFinanceiro controleFinanceiro1 = lancamento.get_Controle(); + if (controleFinanceiro1 != null) + { + Gestor.Model.Domain.Financeiro.Planos plano1 = controleFinanceiro1.get_Plano(); + if (plano1 != null) + { + nullable4 = new long?(plano1.get_Id()); + } + else + { + nullable = null; + nullable4 = nullable; + } + } + else + { + nullable = null; + nullable4 = nullable; + } + nullable5 = nullable4; + return nullable6.GetValueOrDefault() == nullable5.GetValueOrDefault() & nullable6.HasValue == nullable5.HasValue; + } + } + return false; + })); + lancamento1.set_Selecionado(false); + if (!lancamento1.get_Baixado()) + { + DateTime? nullable7 = null; + lancamento1.set_Baixa(nullable7); + nullable7 = null; + lancamento1.set_Pagamento(nullable7); + lancamento1.set_ValorPago(new decimal?(new decimal())); + } + this.LancamentosFiltradosCopia = this.LancamentosFiltrados; + this.Totalizar(); + } + + public async Task Excluir() + { + bool flag; + long? nullable; + object historico; + bool flag1; + long num; + Lancamento lancamento; + if (this.SelectedLancamento != null && this.SelectedLancamento.get_Id() != 0) + { + base.Loading(true); + lancamento = await this._servico.BuscarLancamento(this.SelectedLancamento.get_Id()); + Saldo saldo = await this.VerificaSaldo(this.SelectedLancamento.get_Conta().get_Id(), true); + if (saldo != null) + { + DateTime? dataInicio = saldo.get_DataInicio(); + DateTime? baixa = lancamento.get_Baixa(); + flag = (dataInicio.HasValue & baixa.HasValue ? dataInicio.GetValueOrDefault() > baixa.GetValueOrDefault() : false); + if (flag) + { + await base.ShowMessage("LANÇAMENTO NÃO PODE SER EXCLUÍDO POIS NÃO POSSUI SALDO ABERTO PARA O PERÍODO.", "OK", "", false); + base.Loading(false); + } + else if (!await base.ShowMessage("DESEJA REAMENTE EXCLUIR O LANÇAMENTO SELECIONADO?", "SIM", "NÃO", false)) + { + base.Loading(false); + } + else if (await this._servico.Excluir(this.SelectedLancamento)) + { + FinanceiroViewModel financeiroViewModel = this; + Lancamento selectedLancamento = this.SelectedLancamento; + if (selectedLancamento != null) + { + nullable = new long?(selectedLancamento.get_Id()); + } + else + { + nullable = null; + } + object obj = nullable; + Lancamento selectedLancamento1 = this.SelectedLancamento; + if (selectedLancamento1 != null) + { + historico = selectedLancamento1.get_Historico(); + } + else + { + historico = null; + } + string str = string.Format("EXCLUIU O LANÇAMENTO DO ID {0} HISTORICO: {1}", obj, historico); + Lancamento lancamento1 = this.SelectedLancamento; + if (lancamento1 != null) + { + lancamento1.get_Id(); + flag1 = false; + } + else + { + flag1 = true; + } + num = (flag1 ? (long)0 : this.SelectedLancamento.get_Id()); + financeiroViewModel.RegistrarAcao(str, num, new TipoTela?(25), null); + base.ToggleSnackBar("EXCLUSÃO REALIZADA COM SUCESSO", true); + await this.Buscar(); + base.Loading(false); + } + else + { + base.Loading(false); + } + } + } + lancamento = null; + } + + public async Task ExcluirBaixa() + { + bool flag; + if (this.SelectedLancamento != null && this.SelectedLancamento.get_Id() != 0) + { + base.Loading(true); + DateTime? baixa = await this._servico.BuscarLancamento(this.SelectedLancamento.get_Id()).get_Baixa(); + if (!baixa.HasValue) + { + await base.ShowMessage("LANÇAMENTO AINDA NÃO BAIXADO. PROCESSO INTERROMPIDO", "OK", "", false); + base.Loading(false); + } + else if (await base.ShowMessage("DESEJA REAMENTE EXCLUIR A BAIXA DO LANÇAMENTO SELECIONADO?", "SIM", "NÃO", false)) + { + Saldo saldo = await this.VerificaSaldo(this.SelectedLancamento.get_Conta().get_Id(), true); + if (saldo != null) + { + baixa = saldo.get_DataInicio(); + DateTime? nullable = this.SelectedLancamento.get_Baixa(); + flag = (baixa.HasValue & nullable.HasValue ? baixa.GetValueOrDefault() > nullable.GetValueOrDefault() : false); + if (!flag) + { + nullable = null; + this.SelectedLancamento.set_Baixa(nullable); + this.SelectedLancamento.set_ValorPago(new decimal?(new decimal())); + nullable = null; + this.SelectedLancamento.set_Pagamento(nullable); + this.SelectedLancamento.set_Baixado(false); + this.SelectedLancamento = await this._servico.Save(this.SelectedLancamento); + if (this.importando) + { + this.BindImportando(); + this.LancamentosFiltrados = this.Lancamentos; + base.Loading(false); + } + else if (this._servico.Sucesso) + { + base.ToggleSnackBar("EXCLUSÃO DE BAIXA REALIZADA COM SUCESSO", true); + await this.Buscar(); + base.Loading(false); + } + } + else + { + await base.ShowMessage("LANÇAMENTO NÃO PODE TER SUA BAIXA EXCLUÍDA POIS NÃO POSSUI SALDO ABERTO PARA O PERÍODO.", "OK", "", false); + base.Loading(false); + } + } + } + else + { + base.Loading(false); + } + } + } + + public async Task ExcluirBaixaRange() + { + bool flag; + List lancamentos; + ObservableCollection lancamentosFiltrados = this.LancamentosFiltrados; + List list = lancamentosFiltrados.Where((Lancamento x) => { + if (x.get_Selecionado() && x.get_Controle().get_Plano() != null) + { + return true; + } + if (!x.get_Historico().Equals("TRANSFERÊNCIA ENTRE CONTAS") || !x.get_Selecionado()) + { + return false; + } + return x.get_Controle().get_Plano() == null; + }).ToList(); + if (list.Count == 0) + { + await base.ShowMessage("NÃO HÁ LANÇAMENTOS SELECIONADOS, SELECIONE-OS ANTES DE EXCLUIR A BAIXA.", "OK", "", false); + } + else if (await base.ShowMessage("DESEJA REAMENTE EXCLUIR A BAIXA DOS LANÇAMENTOS SELECIONADOS?", "SIM", "NÃO", false)) + { + base.Loading(true); + lancamentos = new List(); + bool flag1 = false; + foreach (Lancamento lancamento in list) + { + Saldo saldo = await this.VerificaSaldo(lancamento.get_Conta().get_Id(), false); + if (saldo == null || !lancamento.get_Baixado()) + { + continue; + } + DateTime? dataInicio = saldo.get_DataInicio(); + DateTime? baixa = lancamento.get_Baixa(); + flag = (dataInicio.HasValue & baixa.HasValue ? dataInicio.GetValueOrDefault() > baixa.GetValueOrDefault() : false); + if (!flag) + { + baixa = null; + lancamento.set_Baixa(baixa); + lancamento.set_ValorPago(new decimal?(new decimal())); + baixa = null; + lancamento.set_Pagamento(baixa); + lancamentos.Add(lancamento); + lancamento = null; + } + else + { + flag1 = true; + } + } + if (lancamentos.Count != 0) + { + bool flag2 = flag1; + if (flag2) + { + flag2 = !await base.ShowMessage(string.Concat("HÁ LANÇAMENTOS SELECIONADOS QUE NÃO PODERÃO TER A BAIXA EXCLUÍDA. ", Environment.NewLine, "DESEJA PROSSEGUIR COM A EXCLUSÃO DA BAIXA DOS DEMAIS LANÇAMENTOS?"), "SIM", "NÃO", false); + } + if (!flag2) + { + await this._servico.Atualizar(lancamentos); + if (this._servico.Sucesso) + { + base.ToggleSnackBar(string.Format("EXCLUSÃO DE BAIXA DE {0} DO TOTAL DE {1} LANÇAMENTOS SELECIONADOS REALIZADA COM SUCESSO.", lancamentos.Count, list.Count), true); + await this.Buscar(); + base.Loading(false); + } + else + { + base.Loading(false); + } + } + else + { + base.Loading(false); + } + } + else + { + await base.ShowMessage("NÃO FOI POSSÍVEL FAZER A EXCLUSÃO, POIS NÃO HÁ LANÇAMENTOS BAIXADOS DENTRO DO ÚLTIMO SALDO ABERTO. PROCESSO INTERROMPIDO", "OK", "", false); + base.Loading(false); + } + } + list = null; + lancamentos = null; + } + + public void ExcluirFiltro(Gestor.Model.Domain.Financeiro.FiltroPersonalizado filtro) + { + Gestor.Model.Domain.Financeiro.FiltroPersonalizado filtroPersonalizado = this.FiltroPersonalizadoSelecionado.First((Gestor.Model.Domain.Financeiro.FiltroPersonalizado x) => { + if (x.get_Id() != filtro.get_Id()) + { + return false; + } + return x.get_Tipo() == filtro.get_Tipo(); + }); + this.FiltroPersonalizadoSelecionado.Remove(filtroPersonalizado); + this.FiltroPersonalizadoSelecionado = new ObservableCollection(this.FiltroPersonalizadoSelecionado); + this.FiltrarPersonalizado(); + } + + public async Task ExcluirRange() + { + int? nullable; + bool flag1; + List lancamentos; + ObservableCollection lancamentosFiltrados = this.LancamentosFiltrados; + List list = ( + from x in lancamentosFiltrados + where x.get_Selecionado() + select x).ToList(); + if (list.Count == 0) + { + await base.ShowMessage("NÃO HÁ LANÇAMENTOS SELECIONADOS, SELECIONE-OS ANTES DE EXCLUIR.", "OK", "", false); + } + else if (await base.ShowMessage("DESEJA REAMENTE EXCLUIR OS LANÇAMENTOS SELECIONADOS? ESSE PROCESSO É IRREVERSÍVEL.", "SIM", "NÃO", false)) + { + base.Loading(true); + List lancamentos1 = new List(); + ObservableCollection observableCollection = this.LancamentosFiltrados; + List list1 = observableCollection.Where((Lancamento x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Historico().Equals("TRANSFERÊNCIA ENTRE CONTAS"); + }).ToList(); + list1.ForEach((Lancamento x) => { + Lancamento lancamento = list1.FirstOrDefault((Lancamento z) => { + if (z.get_Controle().get_Id() != this.x.get_Controle().get_Id() || !(this.x.get_Valor() == z.get_Valor())) + { + return false; + } + return this.x.get_Sinal() != z.get_Sinal(); + }); + if (lancamento == null || lancamentos1.Where((Lancamento z) => { + if ((object)z == (object)x) + { + return true; + } + return (object)z == (object)lancamento; + }).ToList().Count > 0) + { + return; + } + lancamentos1.AddRange(new List() + { + x, + lancamento + }); + }); + List lancamentos2 = list1; + if (lancamentos2 != null) + { + nullable = new int?(lancamentos2.Count); + } + else + { + nullable = null; + } + int? nullable1 = nullable; + int count = lancamentos1.Count; + bool valueOrDefault = !(nullable1.GetValueOrDefault() == count & nullable1.HasValue); + if (valueOrDefault) + { + valueOrDefault = !await base.ShowMessage(string.Concat("HÁ TRANSFERÊNCIA ENTRE CONTAS SELECIONADOS QUE NÃO PODERÃO TER A BAIXA EXCLUÍDA, PARA EXCLUIR É NECESSÁRIO SELECIONAR O DÉBITO E O CRÉDITO DA TRANSFERENCIA", Environment.NewLine, "DESEJA PROSSEGUIR COM A EXCLUSÃO DOS DEMAIS LANÇAMENTOS?"), "SIM", "NÃO", false); + } + if (!valueOrDefault) + { + bool flag2 = false; + lancamentos = new List(); + List lancamentos3 = list; + IOrderedEnumerable id = + from x in lancamentos3 + orderby x.get_Controle().get_Id() + select x; + foreach (Lancamento lancamento1 in id.ThenByDescending((Lancamento x) => x.get_Parcela()).ToList()) + { + if (lancamento1.get_Baixado()) + { + Saldo saldo = await this.VerificaSaldo(lancamento1.get_Conta().get_Id(), false); + if (saldo == null) + { + continue; + } + DateTime? dataInicio = saldo.get_DataInicio(); + DateTime? baixa = lancamento1.get_Baixa(); + flag1 = (dataInicio.HasValue & baixa.HasValue ? dataInicio.GetValueOrDefault() > baixa.GetValueOrDefault() : false); + if (flag1) + { + flag2 = true; + continue; + } + } + Lancamento lancamento2 = await this._servico.BuscarLancamento(lancamento1.get_Controle().get_Id(), lancamento1.get_Parcela() + 1); + Lancamento lancamento3 = lancamento2; + if (lancamento3 != null) + { + List lancamentos4 = await this._servico.BuscarLancamentosPorControle(lancamento1.get_Controle().get_Id()); + lancamentos = lancamentos4.Where((Lancamento c) => { + if (c.get_Baixado()) + { + return false; + } + return c.get_Parcela() >= lancamento1.get_Parcela() + 1; + }).AsEnumerable().ToList(); + } + if (lancamento3 == null || !lancamentos1.All((Lancamento l) => l.get_Id() != lancamento3.get_Id())) + { + if (lancamento1.get_Controle().get_Plano() != null) + { + lancamentos1.Add(lancamento1); + } + } + else + { + flag2 = true; + } + } + if (lancamentos1.Count != 0 || lancamentos.Count != 0) + { + valueOrDefault = flag2; + if (valueOrDefault) + { + valueOrDefault = !await base.ShowMessage(string.Concat("HÁ LANÇAMENTOS SELECIONADOS QUE NÃO PODERÃO SER EXCLUÍDOS. ", Environment.NewLine, "DESEJA PROSSEGUIR COM A EXCLUSÃO DOS DEMAIS LANÇAMENTOS?"), "SIM", "NÃO", false); + } + if (!valueOrDefault) + { + valueOrDefault = lancamentos.Count > 0; + if (valueOrDefault) + { + valueOrDefault = await base.ShowMessage("DESEJA EXCLUIR LANÇAMENTOS/PARCELAS CADASTRADOS ACIMA DAS SELECIONADAS.", "SIM", "NÃO", false); + } + if (valueOrDefault) + { + lancamentos1.AddRange(lancamentos); + } + if (await this._servico.Excluir(lancamentos1)) + { + if (lancamentos1 != null && lancamentos1.Count > 0) + { + lancamentos1.ForEach((Lancamento x) => { + bool flag; + FinanceiroViewModel u003cu003e4_this = this; + string str = string.Format("EXCLUIU O LANÇAMENTO DO ID {0} HISTORICO: {1}", (x != null ? new long?(x.get_Id()) : null), (x != null ? x.get_Historico() : null)); + if (x != null) + { + x.get_Id(); + flag = false; + } + else + { + flag = true; + } + u003cu003e4_this.RegistrarAcao(str, (flag ? (long)0 : x.get_Id()), new TipoTela?(25), null); + }); + } + base.ToggleSnackBar(string.Format("EXCLUSÃO DE {0} DO TOTAL DE {1} LANÇAMENTOS SELECIONADOS REALIZADA COM SUCESSO.", lancamentos1.Count, list.Count), true); + await this.Buscar(); + base.Loading(false); + } + else + { + base.Loading(false); + } + } + else + { + base.Loading(false); + } + } + else + { + await base.ShowMessage("OS LANÇAMENTOS SELECIONADOS NÃO PODEM SER EXCLUÍDOS. NENHUMA ALTERAÇÃO FOI FEITA", "OK", "", false); + base.Loading(false); + } + } + else + { + base.Loading(false); + } + } + list = null; + lancamentos = null; + } + + public void Feed(Lancamento lancamento) + { + bool id; + Fornecedor fornecedor; + Gestor.Model.Domain.Financeiro.Planos plano; + BancosContas bancosConta; + if (lancamento == null || this.Salvando) + { + return; + } + if (!this.importando && lancamento.get_Controle().get_Plano() == null) + { + return; + } + Fornecedor fornecedor1 = lancamento.get_Controle().get_Fornecedor(); + if (fornecedor1 != null) + { + id = fornecedor1.get_Id() == (long)0; + } + else + { + id = false; + } + if (id) + { + fornecedor = null; + } + else + { + fornecedor = lancamento.get_Controle().get_Fornecedor(); + } + this.FornecedorInclusao = fornecedor; + if (lancamento.get_Controle().get_Plano() != null) + { + plano = this.PlanosFiltrados.FirstOrDefault((Gestor.Model.Domain.Financeiro.Planos x) => x.get_Id() == lancamento.get_Controle().get_Plano().get_Id()); + } + else + { + plano = null; + } + this.Plano = plano; + this.Centro = this.CentrosFiltrados.FirstOrDefault((Gestor.Model.Domain.Financeiro.Centro x) => x.get_Id() == lancamento.get_Controle().get_Centro().get_Id()); + if (lancamento.get_Conta() != null) + { + bancosConta = this.ContasFiltradas.FirstOrDefault((BancosContas x) => x.get_Id() == lancamento.get_Conta().get_Id()); + } + else + { + bancosConta = null; + } + this.Conta = bancosConta; + this.TipoPagamento = lancamento.get_TipoPagamento(); + this.Historico = lancamento.get_Historico(); + this.Observacao = lancamento.get_Observacao(); + this.Complemento = lancamento.get_Complemento(); + this.Competencia = lancamento.get_Competencia(); + this.Documento = lancamento.get_Documento(); + this.Parcela = lancamento.get_Parcela(); + this.Parcelas = lancamento.get_Controle().get_Parcelas(); + this.Valor = lancamento.get_Valor(); + this.ValorPago = lancamento.get_ValorPago(); + this.Vencimento = lancamento.get_Vencimento(); + this.Pagamento = lancamento.get_Pagamento(); + this.Baixa = lancamento.get_Baixa(); + this.Sinal = lancamento.get_Sinal(); + this.CodigoBanco = lancamento.get_CodigoBanco(); + } + + public void FeedImportando(Lancamento lancamento) + { + BancosContas bancosConta; + Gestor.Model.Domain.Financeiro.Planos plano; + if (lancamento == null || this.Salvando) + { + return; + } + if (!this.importando && lancamento.get_Controle().get_Plano() == null) + { + return; + } + if (this.Conta == null) + { + bancosConta = this.ContasFiltradas.FirstOrDefault((BancosContas x) => x.get_Id() == lancamento.get_Conta().get_Id()); + } + else + { + bancosConta = null; + } + this.Conta = bancosConta; + this.SelectedLancamento.set_Id(lancamento.get_Id()); + this.SelectedLancamento.get_Controle().set_Id(lancamento.get_Controle().get_Id()); + this.SelectedLancamento.get_Controle().set_Historico(lancamento.get_Controle().get_Historico()); + this.SelectedLancamento.set_Baixado(lancamento.get_Baixa().HasValue); + decimal? valorPago = this.SelectedLancamento.get_ValorPago(); + this.IdLancamento = lancamento.get_Id(); + if (lancamento.get_Controle().get_Plano() != null) + { + plano = this.PlanosFiltrados.FirstOrDefault((Gestor.Model.Domain.Financeiro.Planos x) => x.get_Id() == lancamento.get_Controle().get_Plano().get_Id()); + } + else + { + plano = null; + } + this.Plano = plano; + this.Centro = this.CentrosFiltrados.FirstOrDefault((Gestor.Model.Domain.Financeiro.Centro x) => x.get_Id() == lancamento.get_Controle().get_Centro().get_Id()); + this.TipoPagamento = lancamento.get_TipoPagamento(); + this.Historico = lancamento.get_Historico(); + this.Observacao = lancamento.get_Observacao(); + this.Complemento = lancamento.get_Complemento(); + this.Documento = lancamento.get_Documento(); + this.Parcela = lancamento.get_Parcela(); + this.Parcelas = lancamento.get_Controle().get_Parcelas(); + this.Valor = lancamento.get_Valor(); + this.ValorPago = valorPago; + this.Vencimento = lancamento.get_Vencimento(); + this.Pagamento = (lancamento.get_Pagamento().HasValue ? lancamento.get_Pagamento() : this.Pagamento); + } + + public List Filtrar(string filter) + { + this._dontSort = true; + this.LancamentosFiltrados = (string.IsNullOrWhiteSpace(filter) ? this.Lancamentos : new ObservableCollection(this.Lancamentos.Where((Lancamento x) => { + bool plano; + bool centro; + bool fornecedor; + if ((x.get_Historico() == null || !Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Historico().Trim()).Contains(filter)) && (x.get_Documento() == null || !Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Documento().Trim()).Contains(filter)) && (x.get_Competencia() == null || !Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Competencia().Trim()).Contains(filter)) && (x.get_Complemento() == null || !Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Complemento().Trim()).Contains(filter)) && (x.get_Observacao() == null || !Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Observacao().Trim()).Contains(filter)) && !Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Vencimento().ToString(CultureInfo.CurrentCulture).Trim()).ToUpper().Contains(filter) && (!x.get_Baixa().HasValue || !Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Baixa().ToString().Trim()).ToUpper().Contains(filter)) && (!x.get_Pagamento().HasValue || !Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Pagamento().ToString().Trim()).ToUpper().Contains(filter)) && (x.get_Conta() == null || !Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Conta().get_Descricao().Trim()).ToUpper().Contains(filter)) && (x.get_Controle().get_Historico() == null || !Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Controle().get_Historico().Trim()).ToUpper().Contains(filter)) && !Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(EnumHelper.GetDescription(x.get_Sinal()).Trim()).Contains(filter)) + { + ControleFinanceiro controle = x.get_Controle(); + if (controle != null) + { + plano = controle.get_Plano(); + } + else + { + plano = false; + } + if (!plano || !Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Controle().get_Plano().get_Descricao().Trim()).ToUpper().Contains(filter)) + { + x.get_TipoPagamento(); + if (!Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(EnumHelper.GetDescription(x.get_TipoPagamento()).Trim()).ToUpper().Contains(filter)) + { + ControleFinanceiro controleFinanceiro = x.get_Controle(); + if (controleFinanceiro != null) + { + centro = controleFinanceiro.get_Centro(); + } + else + { + centro = false; + } + if (!centro || !Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Controle().get_Centro().get_Descricao().Trim()).ToUpper().Contains(filter)) + { + ControleFinanceiro controle1 = x.get_Controle(); + if (controle1 != null) + { + fornecedor = controle1.get_Fornecedor(); + } + else + { + fornecedor = false; + } + if (!fornecedor) + { + return false; + } + return Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Controle().get_Fornecedor().get_Nome().Trim()).ToUpper().Contains(filter); + } + } + } + } + return true; + }))); + this._dontSort = false; + this.LancamentosFiltradosCopia = this.LancamentosFiltrados; + return this.LancamentosFiltrados.ToList(); + } + + public List FiltrarLancamento(long id) + { + this.LancamentosFiltrados = new ObservableCollection( + from x in this.Lancamentos + where x.get_Id() == id + select x); + return this.LancamentosFiltrados.ToList(); + } + + public List FiltrarLancamento(Lancamento lancamento) + { + this.LancamentosFiltrados = new ObservableCollection(this.Lancamentos.Where((Lancamento x) => { + if (!(x.get_Valor() == lancamento.get_Valor()) || !(x.get_Vencimento() == lancamento.get_Vencimento())) + { + return false; + } + return x.get_Historico() == lancamento.get_Historico(); + })); + return this.LancamentosFiltrados.ToList(); + } + + public async Task> FiltrarLancamento(string value) + { + List lancamentos = await Task.Run>(() => this.Filtrar(value)); + return lancamentos; + } + + public void FiltrarPersonalizado() + { + List nums = (this.FiltroPersonalizadoSelecionado != null ? ( + from x in this.FiltroPersonalizadoSelecionado + where x.get_Tipo() == 0 + select x.get_Id()).ToList() : new List()); + List nums1 = (this.FiltroPersonalizadoSelecionado != null ? ( + from x in this.FiltroPersonalizadoSelecionado + where x.get_Tipo() == 2 + select x.get_Id()).ToList() : new List()); + List nums2 = (this.FiltroPersonalizadoSelecionado != null ? ( + from x in this.FiltroPersonalizadoSelecionado + where x.get_Tipo() == 1 + select x.get_Id()).ToList() : new List()); + List nums3 = (this.FiltroPersonalizadoSelecionado != null ? ( + from x in this.FiltroPersonalizadoSelecionado + where x.get_Tipo() == 3 + select x.get_Id()).ToList() : new List()); + List nums4 = (this.FiltroPersonalizadoSelecionado != null ? ( + from x in this.FiltroPersonalizadoSelecionado + where x.get_Tipo() == 4 + select x.get_Id()).ToList() : new List()); + List list = this.Lancamentos.Where((Lancamento x) => { + if (nums.Count != 0 && (x.get_Controle().get_Fornecedor() == null || !nums.Contains(x.get_Controle().get_Fornecedor().get_Id())) || nums1.Count != 0 && (x.get_Controle().get_Centro() == null || !nums1.Contains(x.get_Controle().get_Centro().get_Id())) || nums2.Count != 0 && (x.get_Controle().get_Plano() == null || !nums2.Contains(x.get_Controle().get_Plano().get_Id())) || nums3.Count != 0 && (x.get_Conta() == null || !nums3.Contains(x.get_Conta().get_Id()))) + { + return false; + } + if (nums4.Count == 0) + { + return true; + } + return nums4.Contains((long)x.get_Sinal()); + }).ToList(); + this.LancamentosFiltrados = new ObservableCollection(list); + this.LancamentosFiltradosCopia = this.LancamentosFiltrados; + this.SelectedLancamento = this.LancamentosFiltrados.FirstOrDefault(); + } + + public List FiltrarPersonalizado(string filter) + { + if (this.FiltroPersonalizado == null) + { + this.PopularFiltro(); + } + return ( + from x in this.FiltroPersonalizado + where Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Descricao().Trim()).ToUpper().Contains(filter.ToUpper()) + select x).ToList(); + } + + public void FiltroImportacao() + { + if (!this.importando) + { + return; + } + switch (this.SelectedStatusImportacao) + { + case 0: + { + this.LancamentosFiltrados = new ObservableCollection( + from x in this.Lancamentos + where !x.get_Baixado() + select x); + return; + } + case 1: + { + this.LancamentosFiltrados = new ObservableCollection( + from x in this.Lancamentos + where x.get_Baixado() + select x); + return; + } + case 2: + { + this.LancamentosFiltrados = new ObservableCollection(this.Lancamentos); + return; + } + default: + { + return; + } + } + } + + internal async Task> FiltroPersonalizadoTask(string value) + { + List filtroPersonalizados = await Task.Run>(() => this.FiltrarPersonalizado(value)); + return filtroPersonalizados; + } + + public async Task GerarExcel(List relatorioGrid) + { + List list; + string str1; + FinanceiroViewModel.u003cu003ec__DisplayClass266_0 variable; + bool flag = await base.ShowMessage(string.Concat("DESEJA AGRUPAR POR ", EnumHelper.GetDescription(this.SinteticoTipo)), "SIM", "NÃO", false); + XLWorkbook xLWorkbook = new XLWorkbook(); + string str2 = "LANÇAMENTOS FINANCEIROS"; + List relatorioLancamentos = new List(); + List lancamentos = new List(); + List lancamentos1 = relatorioGrid; + bool flag1 = lancamentos1.Any((Lancamento x) => x.get_Selecionado()); + relatorioGrid.ToList().ForEach((Lancamento lancamentoGrid) => { + decimal? valorPago; + if (flag1 && !lancamentoGrid.get_Selecionado()) + { + return; + } + Lancamento lancamento2 = (Lancamento)lancamentoGrid.Clone(); + lancamento2.set_Valor((lancamento2.get_Sinal() == 1 ? -lancamento2.get_Valor() : lancamento2.get_Valor())); + Lancamento lancamento1 = lancamento2; + if (lancamento2.get_Sinal() == 1) + { + decimal? nullable = lancamento2.get_ValorPago(); + valorPago = (nullable.HasValue ? new decimal?(-nullable.GetValueOrDefault()) : null); + } + else + { + valorPago = lancamento2.get_ValorPago(); + } + lancamento1.set_ValorPago(valorPago); + lancamentos.Add(lancamento2); + }); + IEnumerable> groupings = lancamentos.GroupBy((Lancamento lancamento) => { + object descricao; + if (this.SinteticoTipo == 1) + { + Gestor.Model.Domain.Financeiro.Centro centro = lancamento.get_Controle().get_Centro(); + if (centro != null) + { + descricao = centro.get_Descricao(); + } + else + { + descricao = null; + } + if (descricao == null) + { + descricao = ""; + } + } + else if (this.SinteticoTipo == null) + { + Gestor.Model.Domain.Financeiro.Planos plano = lancamento.get_Controle().get_Plano(); + if (plano != null) + { + descricao = plano.get_Nome(); + } + else + { + descricao = null; + } + if (descricao == null) + { + return ""; + } + } + else + { + if (this.SinteticoTipo != 3) + { + Fornecedor fornecedor = lancamento.get_Controle().get_Fornecedor(); + if (fornecedor != null) + { + return fornecedor.get_Nome(); + } + return null; + } + BancosContas conta = lancamento.get_Conta(); + if (conta != null) + { + descricao = conta.get_Descricao(); + } + else + { + descricao = null; + } + if (descricao == null) + { + return ""; + } + } + return descricao; + }); + List sinteticoFinanceiros = groupings.Select, Gestor.Model.Domain.Relatorios.SinteticoFinanceiro>((IGrouping lancamento) => { + Gestor.Model.Domain.Relatorios.SinteticoFinanceiro sinteticoFinanceiro = new Gestor.Model.Domain.Relatorios.SinteticoFinanceiro(); + sinteticoFinanceiro.set_Agrupamento(lancamento.Key ?? "TRANSFERÊNCIAS"); + sinteticoFinanceiro.set_Valor(new decimal?(lancamento.Sum((Lancamento sintetic) => sintetic.get_Valor()))); + sinteticoFinanceiro.set_ValorPago(new decimal?(lancamento.Sum((Lancamento sintetic) => sintetic.get_ValorPago()).GetValueOrDefault())); + return sinteticoFinanceiro; + }).ToList(); + List sinteticoFinanceiros1 = sinteticoFinanceiros; + sinteticoFinanceiros = ( + from lancamento in sinteticoFinanceiros1 + orderby lancamento.get_Agrupamento() + select lancamento).ToList(); + List sinteticoFinanceiros2 = sinteticoFinanceiros; + Gestor.Model.Domain.Relatorios.SinteticoFinanceiro sinteticoFinanceiro1 = new Gestor.Model.Domain.Relatorios.SinteticoFinanceiro(); + sinteticoFinanceiro1.set_Agrupamento("TOTAL"); + List sinteticoFinanceiros3 = sinteticoFinanceiros; + sinteticoFinanceiro1.set_Valor(sinteticoFinanceiros3.Sum((Gestor.Model.Domain.Relatorios.SinteticoFinanceiro sintetic) => sintetic.get_Valor())); + List sinteticoFinanceiros4 = sinteticoFinanceiros; + sinteticoFinanceiro1.set_ValorPago(sinteticoFinanceiros4.Sum((Gestor.Model.Domain.Relatorios.SinteticoFinanceiro sintetic) => sintetic.get_ValorPago())); + sinteticoFinanceiros2.Add(sinteticoFinanceiro1); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "SINTÉTICO", sinteticoFinanceiros, null); + if (!flag) + { + relatorioLancamentos = FinanceiroViewModel.GerarRelatorio(lancamentos); + List relatorioLancamentos1 = relatorioLancamentos; + RelatorioLancamentos relatorioLancamento = new RelatorioLancamentos(); + relatorioLancamento.set_Fornecedor("TOTAL"); + List relatorioLancamentos2 = relatorioLancamentos; + relatorioLancamento.set_Valor(relatorioLancamentos2.Sum((RelatorioLancamentos lancamento) => lancamento.get_Valor())); + List relatorioLancamentos3 = relatorioLancamentos; + relatorioLancamento.set_ValorPago(relatorioLancamentos3.Sum((RelatorioLancamentos lancamento) => lancamento.get_ValorPago())); + relatorioLancamentos1.Add(relatorioLancamento); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str2, relatorioLancamentos, null); + } + else + { + switch (this.SinteticoTipo) + { + case 0: + { + List lancamentos2 = lancamentos; + list = lancamentos2.Select((Lancamento x) => { + object descricao; + ControleFinanceiro controle = x.get_Controle(); + if (controle != null) + { + Gestor.Model.Domain.Financeiro.Planos plano = controle.get_Plano(); + if (plano != null) + { + descricao = plano.get_Descricao(); + } + else + { + descricao = null; + } + } + else + { + descricao = null; + } + if (descricao == null) + { + descricao = ""; + } + return descricao; + }).Distinct().ToList(); + foreach (string str3 in list) + { + List list1 = lancamentos.Where((Lancamento lancamento) => { + string descricao; + string str; + if (string.IsNullOrWhiteSpace(str3)) + { + ControleFinanceiro controle = lancamento.get_Controle(); + if (controle != null) + { + Gestor.Model.Domain.Financeiro.Planos plano = controle.get_Plano(); + if (plano != null) + { + str = plano.get_Descricao(); + } + else + { + str = null; + } + } + else + { + str = null; + } + return string.IsNullOrEmpty(str); + } + ControleFinanceiro controleFinanceiro = lancamento.get_Controle(); + if (controleFinanceiro != null) + { + Gestor.Model.Domain.Financeiro.Planos plano1 = controleFinanceiro.get_Plano(); + if (plano1 != null) + { + descricao = plano1.get_Descricao(); + } + else + { + descricao = null; + } + } + else + { + descricao = null; + } + return descricao == str3; + }).ToList(); + if (list1.Count == 0) + { + continue; + } + relatorioLancamentos = FinanceiroViewModel.GerarRelatorio(list1); + List relatorioLancamentos4 = relatorioLancamentos; + RelatorioLancamentos relatorioLancamento1 = new RelatorioLancamentos(); + relatorioLancamento1.set_Fornecedor("TOTAL"); + List lancamentos3 = list1; + relatorioLancamento1.set_Valor(lancamentos3.Sum((Lancamento lancamento) => lancamento.get_Valor())); + List lancamentos4 = list1; + relatorioLancamento1.set_ValorPago(lancamentos4.Sum((Lancamento lancamento) => lancamento.get_ValorPago())); + relatorioLancamentos4.Add(relatorioLancamento1); + str1 = (!string.IsNullOrWhiteSpace(str3) ? str3.ValidaNomePlanilha("", 0) : "TRANSFERENCIAS"); + str2 = str1; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str2, relatorioLancamentos, null); + } + break; + } + case 1: + { + List lancamentos5 = lancamentos; + list = lancamentos5.Select((Lancamento lancamento) => { + object descricao; + ControleFinanceiro controle = lancamento.get_Controle(); + if (controle != null) + { + Gestor.Model.Domain.Financeiro.Centro centro = controle.get_Centro(); + if (centro != null) + { + descricao = centro.get_Descricao(); + } + else + { + descricao = null; + } + } + else + { + descricao = null; + } + if (descricao == null) + { + descricao = ""; + } + return descricao; + }).Distinct().ToList(); + foreach (string str4 in list) + { + List list2 = lancamentos.Where((Lancamento lanamento) => { + string descricao; + string str; + if (string.IsNullOrWhiteSpace(str4)) + { + ControleFinanceiro controle = lanamento.get_Controle(); + if (controle != null) + { + Gestor.Model.Domain.Financeiro.Centro centro = controle.get_Centro(); + if (centro != null) + { + str = centro.get_Descricao(); + } + else + { + str = null; + } + } + else + { + str = null; + } + return string.IsNullOrEmpty(str); + } + ControleFinanceiro controleFinanceiro = lanamento.get_Controle(); + if (controleFinanceiro != null) + { + Gestor.Model.Domain.Financeiro.Centro centro1 = controleFinanceiro.get_Centro(); + if (centro1 != null) + { + descricao = centro1.get_Descricao(); + } + else + { + descricao = null; + } + } + else + { + descricao = null; + } + return descricao == str4; + }).ToList(); + if (list2.Count == 0) + { + continue; + } + relatorioLancamentos = FinanceiroViewModel.GerarRelatorio(list2); + List relatorioLancamentos5 = relatorioLancamentos; + RelatorioLancamentos relatorioLancamento2 = new RelatorioLancamentos(); + relatorioLancamento2.set_Fornecedor("TOTAL"); + List lancamentos6 = list2; + relatorioLancamento2.set_Valor(lancamentos6.Sum((Lancamento lancamento) => lancamento.get_Valor())); + List lancamentos7 = list2; + relatorioLancamento2.set_ValorPago(lancamentos7.Sum((Lancamento lancamento) => lancamento.get_ValorPago())); + relatorioLancamentos5.Add(relatorioLancamento2); + str2 = str4.ValidaNomePlanilha("", 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str2, relatorioLancamentos, null); + } + break; + } + case 2: + { + List lancamentos8 = lancamentos; + list = lancamentos8.Select((Lancamento lancamento) => { + object nome; + ControleFinanceiro controle = lancamento.get_Controle(); + if (controle != null) + { + Fornecedor fornecedor = controle.get_Fornecedor(); + if (fornecedor != null) + { + nome = fornecedor.get_Nome(); + } + else + { + nome = null; + } + } + else + { + nome = null; + } + if (nome == null) + { + nome = ""; + } + return nome; + }).Distinct().ToList(); + foreach (string str5 in list) + { + List list3 = lancamentos.Where((Lancamento lancamento) => { + string nome; + string str; + if (string.IsNullOrWhiteSpace(str5)) + { + ControleFinanceiro controle = lancamento.get_Controle(); + if (controle != null) + { + Fornecedor fornecedor = controle.get_Fornecedor(); + if (fornecedor != null) + { + str = fornecedor.get_Nome(); + } + else + { + str = null; + } + } + else + { + str = null; + } + return string.IsNullOrEmpty(str); + } + ControleFinanceiro controleFinanceiro = lancamento.get_Controle(); + if (controleFinanceiro != null) + { + Fornecedor fornecedor1 = controleFinanceiro.get_Fornecedor(); + if (fornecedor1 != null) + { + nome = fornecedor1.get_Nome(); + } + else + { + nome = null; + } + } + else + { + nome = null; + } + return nome == str5; + }).ToList(); + if (list3.Count == 0) + { + continue; + } + relatorioLancamentos = FinanceiroViewModel.GerarRelatorio(list3); + List relatorioLancamentos6 = relatorioLancamentos; + RelatorioLancamentos relatorioLancamento3 = new RelatorioLancamentos(); + relatorioLancamento3.set_Fornecedor("TOTAL"); + List lancamentos9 = list3; + relatorioLancamento3.set_Valor(lancamentos9.Sum((Lancamento lancamento) => lancamento.get_Valor())); + List lancamentos10 = list3; + relatorioLancamento3.set_ValorPago(lancamentos10.Sum((Lancamento lancamento) => lancamento.get_ValorPago())); + relatorioLancamentos6.Add(relatorioLancamento3); + str2 = str5.ValidaNomePlanilha("", 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str2, relatorioLancamentos, null); + } + break; + } + case 3: + { + List lancamentos11 = lancamentos; + list = lancamentos11.Select((Lancamento x) => { + object descricao; + BancosContas conta = x.get_Conta(); + if (conta != null) + { + descricao = conta.get_Descricao(); + } + else + { + descricao = null; + } + if (descricao == null) + { + descricao = ""; + } + return descricao; + }).Distinct().ToList(); + foreach (string str6 in list) + { + if (string.IsNullOrWhiteSpace(str6)) + { + continue; + } + List list4 = lancamentos.Where((Lancamento lancamento) => { + string descricao; + string str; + if (string.IsNullOrWhiteSpace(str6)) + { + BancosContas conta = lancamento.get_Conta(); + if (conta != null) + { + str = conta.get_Descricao(); + } + else + { + str = null; + } + return string.IsNullOrEmpty(str); + } + BancosContas bancosConta = lancamento.get_Conta(); + if (bancosConta != null) + { + descricao = bancosConta.get_Descricao(); + } + else + { + descricao = null; + } + return descricao == str6; + }).ToList(); + if (list4.Count == 0) + { + continue; + } + relatorioLancamentos = FinanceiroViewModel.GerarRelatorio(list4); + List relatorioLancamentos7 = relatorioLancamentos; + RelatorioLancamentos relatorioLancamento4 = new RelatorioLancamentos(); + relatorioLancamento4.set_Fornecedor("TOTAL"); + List lancamentos12 = list4; + relatorioLancamento4.set_Valor(lancamentos12.Sum((Lancamento lancamento) => lancamento.get_Valor())); + List lancamentos13 = list4; + relatorioLancamento4.set_ValorPago(lancamentos13.Sum((Lancamento lancamento) => lancamento.get_ValorPago())); + relatorioLancamentos7.Add(relatorioLancamento4); + str2 = str6.ValidaNomePlanilha("", 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str2, relatorioLancamentos, null); + } + break; + } + } + } + string tempPath = ""; + string str7 = ""; + List configuracoes = Recursos.Configuracoes; + if (!configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 41)) + { + tempPath = Path.GetTempPath(); + str7 = string.Format("{0}{1}.xlsx", tempPath, Guid.NewGuid()); + } + else + { + using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog()) + { + if (DialogResult.OK == folderBrowserDialog.ShowDialog()) + { + tempPath = string.Concat(folderBrowserDialog.SelectedPath, "\\"); + Directory.CreateDirectory(tempPath); + } + else + { + variable = null; + str2 = null; + return; + } + } + string[] strArrays = new string[] { tempPath, str2, " ", null, null }; + DateTime date = Functions.GetNetworkTime().Date; + strArrays[3] = date.ToShortDateString().Replace("/", ""); + strArrays[4] = ".xlsx"; + str7 = string.Concat(strArrays); + } + xLWorkbook.SaveAs(str7); + Process.Start(str7); + variable = null; + str2 = null; + } + + private async Task GerarHtml(List relatorioGrid, bool posicao = false) + { + DateTime dateTime; + DateTime dateTime1; + int num; + string str1; + TipoRelatorio tipoRelatorio = new TipoRelatorio(); + tipoRelatorio.set_Nome("RELATÓRIO FINANCEIRO"); + DateTime? inicio = this.Inicio; + dateTime = (inicio.HasValue ? inicio.GetValueOrDefault() : DateTime.MinValue); + tipoRelatorio.set_Inicio(dateTime); + inicio = this.Fim; + dateTime1 = (inicio.HasValue ? inicio.GetValueOrDefault() : DateTime.MinValue); + tipoRelatorio.set_Fim(dateTime1); + TipoRelatorio tipoRelatorio1 = tipoRelatorio; + switch (this.SelectedFiltro) + { + case 0: + { + tipoRelatorio1.set_Nome("RELATORIO FINANCEIRO - VENCIMENTO"); + break; + } + case 1: + { + tipoRelatorio1.set_Nome("RELATORIO FINANCEIRO - BAIXA"); + break; + } + case 2: + { + tipoRelatorio1.set_Nome("RELATORIO FINANCEIRO - PAGAMENTO"); + break; + } + case 3: + { + tipoRelatorio1.set_Nome(this.SelectedFornecedor.get_Nome()); + tipoRelatorio1.set_Inicio(DateTime.MinValue); + tipoRelatorio1.set_Fim(DateTime.MinValue); + break; + } + } + List strs = Funcoes.OcultarColunasDescricao(typeof(Sintetico), "FINANCEIRO"); + List lancamentos = new List(); + List lancamentos1 = relatorioGrid; + bool flag = lancamentos1.Any((Lancamento x) => x.get_Selecionado()); + relatorioGrid.ToList().ForEach((Lancamento lancamentoGrid) => { + decimal? valorPago; + if (flag && !lancamentoGrid.get_Selecionado()) + { + return; + } + Lancamento lancamento2 = (Lancamento)lancamentoGrid.Clone(); + lancamento2.set_Valor((lancamento2.get_Sinal() == 1 ? -lancamento2.get_Valor() : lancamento2.get_Valor())); + Lancamento lancamento1 = lancamento2; + if (lancamento2.get_Sinal() == 1) + { + decimal? nullable = lancamento2.get_ValorPago(); + valorPago = (nullable.HasValue ? new decimal?(-nullable.GetValueOrDefault()) : null); + } + else + { + valorPago = lancamento2.get_ValorPago(); + } + lancamento1.set_ValorPago(valorPago); + lancamentos.Add(lancamento2); + }); + IEnumerable> groupings = lancamentos.GroupBy((Lancamento lancamento) => { + object descricao; + if (this.SinteticoTipo == 1) + { + Gestor.Model.Domain.Financeiro.Centro centro = lancamento.get_Controle().get_Centro(); + if (centro != null) + { + descricao = centro.get_Descricao(); + } + else + { + descricao = null; + } + if (descricao == null) + { + descricao = ""; + } + } + else if (this.SinteticoTipo == null) + { + Gestor.Model.Domain.Financeiro.Planos plano = lancamento.get_Controle().get_Plano(); + if (plano != null) + { + descricao = plano.get_Descricao(); + } + else + { + descricao = null; + } + if (descricao == null) + { + return ""; + } + } + else + { + if (this.SinteticoTipo != 3) + { + Fornecedor fornecedor = lancamento.get_Controle().get_Fornecedor(); + if (fornecedor != null) + { + return fornecedor.get_Nome(); + } + return null; + } + BancosContas conta = lancamento.get_Conta(); + if (conta != null) + { + descricao = conta.get_Descricao(); + } + else + { + descricao = null; + } + if (descricao == null) + { + return ""; + } + } + return descricao; + }); + List list = groupings.Select, Gestor.Model.Domain.Relatorios.SinteticoFinanceiro>((IGrouping lancamento) => { + Gestor.Model.Domain.Relatorios.SinteticoFinanceiro sinteticoFinanceiro = new Gestor.Model.Domain.Relatorios.SinteticoFinanceiro(); + sinteticoFinanceiro.set_Agrupamento(lancamento.Key ?? "TRANSFERÊNCIAS"); + sinteticoFinanceiro.set_Valor(new decimal?(lancamento.Sum((Lancamento sintetic) => sintetic.get_Valor()))); + sinteticoFinanceiro.set_ValorPago(new decimal?(lancamento.Sum((Lancamento sintetic) => sintetic.get_ValorPago()).GetValueOrDefault())); + return sinteticoFinanceiro; + }).ToList(); + List sinteticoFinanceiros = list; + list = ( + from lancamento in sinteticoFinanceiros + orderby lancamento.get_Agrupamento() + select lancamento).ToList(); + List sinteticoFinanceiros1 = list; + Gestor.Model.Domain.Relatorios.SinteticoFinanceiro sinteticoFinanceiro1 = new Gestor.Model.Domain.Relatorios.SinteticoFinanceiro(); + sinteticoFinanceiro1.set_Agrupamento("TOTAL"); + List sinteticoFinanceiros2 = list; + sinteticoFinanceiro1.set_Valor(sinteticoFinanceiros2.Sum((Gestor.Model.Domain.Relatorios.SinteticoFinanceiro sintetic) => sintetic.get_Valor())); + List sinteticoFinanceiros3 = list; + sinteticoFinanceiro1.set_ValorPago(sinteticoFinanceiros3.Sum((Gestor.Model.Domain.Relatorios.SinteticoFinanceiro sintetic) => sintetic.get_ValorPago())); + sinteticoFinanceiros1.Add(sinteticoFinanceiro1); + string str2 = await Funcoes.GenerateTable(list, strs, false, false, "", null); + string str3 = Funcoes.CreateCard(string.Concat("SINTÉTICO ", EnumHelper.GetDescription(this.SinteticoTipo)), str2, false); + IEnumerable> groupings1 = lancamentos.GroupBy((Lancamento lancamento) => { + object descricao; + if (this.SinteticoTipo == 1) + { + Gestor.Model.Domain.Financeiro.Centro centro = lancamento.get_Controle().get_Centro(); + if (centro != null) + { + descricao = centro.get_Descricao(); + } + else + { + descricao = null; + } + if (descricao == null) + { + descricao = ""; + } + } + else if (this.SinteticoTipo == null) + { + Gestor.Model.Domain.Financeiro.Planos plano = lancamento.get_Controle().get_Plano(); + if (plano != null) + { + descricao = plano.get_Nome(); + } + else + { + descricao = null; + } + if (descricao == null) + { + return ""; + } + } + else + { + if (this.SinteticoTipo != 3) + { + Fornecedor fornecedor = lancamento.get_Controle().get_Fornecedor(); + if (fornecedor != null) + { + return fornecedor.get_Nome(); + } + return null; + } + BancosContas conta = lancamento.get_Conta(); + if (conta != null) + { + descricao = conta.get_Descricao(); + } + else + { + descricao = null; + } + if (descricao == null) + { + return ""; + } + } + return descricao; + }); + List list1 = ( + from lancamento in groupings1 + select lancamento.Key).Distinct().ToList(); + foreach (string str4 in list1) + { + List list2 = lancamentos.Where((Lancamento lancamento) => { + string descricao; + string nome; + string str; + string nome1; + if (this.SinteticoTipo == 1) + { + Gestor.Model.Domain.Financeiro.Centro centro = lancamento.get_Controle().get_Centro(); + if (centro != null) + { + descricao = centro.get_Descricao(); + } + else + { + descricao = null; + } + return descricao == str4; + } + if (this.SinteticoTipo == null) + { + Gestor.Model.Domain.Financeiro.Planos plano = lancamento.get_Controle().get_Plano(); + if (plano != null) + { + nome = plano.get_Nome(); + } + else + { + nome = null; + } + return nome == str4; + } + if (this.SinteticoTipo == 3) + { + BancosContas conta = lancamento.get_Conta(); + if (conta != null) + { + str = conta.get_Descricao(); + } + else + { + str = null; + } + return str == str4; + } + Fornecedor fornecedor = lancamento.get_Controle().get_Fornecedor(); + if (fornecedor != null) + { + nome1 = fornecedor.get_Nome(); + } + else + { + nome1 = null; + } + return nome1 == str4; + }).ToList(); + if (list2.Count == 0) + { + continue; + } + List lancamentos2 = list2; + Lancamento lancamento3 = new Lancamento(); + ControleFinanceiro controleFinanceiro = new ControleFinanceiro(); + Fornecedor fornecedor1 = new Fornecedor(); + fornecedor1.set_Nome("TOTAL"); + controleFinanceiro.set_Fornecedor(fornecedor1); + lancamento3.set_Controle(controleFinanceiro); + List lancamentos3 = list2; + lancamento3.set_Valor(lancamentos3.Sum((Lancamento lancamento) => lancamento.get_Valor())); + List lancamentos4 = list2; + lancamento3.set_ValorPago(lancamentos4.Sum((Lancamento lancamento) => lancamento.get_ValorPago())); + lancamentos2.Add(lancamento3); + string str5 = await Funcoes.GenerateTable(FinanceiroViewModel.GerarRelatorio(list2), new List(), false, false, "", null); + str3 = string.Concat(str3, Funcoes.CreateCard(str4, str5, false)); + } + List configuracoes = Recursos.Configuracoes; + num = (configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 14) ? 70 : 50); + int num1 = num; + TipoRelatorio tipoRelatorio2 = tipoRelatorio1; + string str6 = str3; + if (str6 == null) + { + str6 = ""; + } + string str7 = num1.ToString(); + str1 = (posicao ? "landscape" : "portrait"); + string str8 = Funcoes.ExportarHtml(tipoRelatorio2, str6, str7, str1, false, ""); + tipoRelatorio1 = null; + str3 = null; + return str8; + } + + private static List GerarRelatorio(List lancamentos) + { + return lancamentos.Select((Lancamento x) => { + string nome; + string descricao; + string str; + string descricao1; + string str1; + string nome1; + RelatorioLancamentos relatorioLancamento = new RelatorioLancamentos(); + Fornecedor fornecedor = x.get_Controle().get_Fornecedor(); + if (fornecedor != null) + { + nome = fornecedor.get_Nome(); + } + else + { + nome = null; + } + relatorioLancamento.set_Fornecedor(nome); + relatorioLancamento.set_Historico(x.get_Historico()); + relatorioLancamento.set_Observacao(x.get_Observacao()); + relatorioLancamento.set_Documento(x.get_Documento()); + relatorioLancamento.set_Parcela(x.get_Parcela()); + relatorioLancamento.set_Vencimento(x.get_Vencimento()); + relatorioLancamento.set_Valor(x.get_Valor()); + relatorioLancamento.set_Baixa(x.get_Baixa()); + relatorioLancamento.set_ValorPago(x.get_ValorPago()); + relatorioLancamento.set_Pagamento(x.get_Pagamento()); + Gestor.Model.Domain.Financeiro.Planos plano = x.get_Controle().get_Plano(); + if (plano != null) + { + descricao = plano.get_Descricao(); + } + else + { + descricao = null; + } + relatorioLancamento.set_Plano(descricao); + Gestor.Model.Domain.Financeiro.Planos plano1 = x.get_Controle().get_Plano(); + if (plano1 != null) + { + str = plano1.get_Plano().get_Descricao(); + } + else + { + str = null; + } + relatorioLancamento.set_Planos(str); + Gestor.Model.Domain.Financeiro.Centro centro = x.get_Controle().get_Centro(); + if (centro != null) + { + descricao1 = centro.get_Descricao(); + } + else + { + descricao1 = null; + } + relatorioLancamento.set_Centro(descricao1); + BancosContas conta = x.get_Conta(); + if (conta != null) + { + str1 = conta.get_Descricao(); + } + else + { + str1 = null; + } + relatorioLancamento.set_Conta(str1); + Fornecedor fornecedor1 = x.get_Controle().get_Fornecedor(); + if (fornecedor1 != null) + { + nome1 = fornecedor1.get_Nome(); + } + else + { + nome1 = null; + } + relatorioLancamento.set_Sinal((nome1 == "TOTAL" ? "" : EnumHelper.GetDescription(x.get_Sinal()))); + relatorioLancamento.set_Competencia(x.get_Competencia()); + return relatorioLancamento; + }).ToList(); + } + + public void IncluirLancamento() + { + Gestor.Model.Common.TipoPagamento? nullable; + bool hasValue; + bool flag; + bool hasValue1; + Gestor.Model.Common.TipoPagamento? tipoPagamento; + Gestor.Model.Common.Sinal sinal; + this.Alterando = Visibility.Visible; + this.BuscaHabilitada = false; + Fornecedor selectedFornecedor = null; + if (this.SelectedFiltro == 3 && this.SelectedFornecedor != null && this.SelectedFornecedor.get_Id() > (long)0) + { + selectedFornecedor = this.SelectedFornecedor; + } + this.VisibilityFornecedor = (selectedFornecedor == null ? Visibility.Visible : Visibility.Collapsed); + Fornecedor fornecedor = selectedFornecedor; + if (fornecedor != null) + { + hasValue = fornecedor.get_IdPlano().HasValue; + } + else + { + hasValue = false; + } + Gestor.Model.Domain.Financeiro.Planos plano = (hasValue ? this.PlanosFiltrados.FirstOrDefault((Gestor.Model.Domain.Financeiro.Planos x) => { + long id = x.get_Id(); + long? idPlano = selectedFornecedor.get_IdPlano(); + return id == idPlano.GetValueOrDefault() & idPlano.HasValue; + }) ?? this.PlanosFiltrados.FirstOrDefault() : this.PlanosFiltrados.FirstOrDefault()); + Fornecedor fornecedor1 = selectedFornecedor; + if (fornecedor1 != null) + { + flag = fornecedor1.get_IdConta().HasValue; + } + else + { + flag = false; + } + BancosContas bancosConta = (flag ? this.ContasFiltradas.FirstOrDefault((BancosContas x) => { + long id = x.get_Id(); + long? idConta = selectedFornecedor.get_IdConta(); + return id == idConta.GetValueOrDefault() & idConta.HasValue; + }) ?? this.ContasFiltradas.FirstOrDefault() : this.ContasFiltradas.FirstOrDefault()); + Fornecedor fornecedor2 = selectedFornecedor; + if (fornecedor2 != null) + { + hasValue1 = fornecedor2.get_IdCentro().HasValue; + } + else + { + hasValue1 = false; + } + Gestor.Model.Domain.Financeiro.Centro centro = (hasValue1 ? this.CentrosFiltrados.FirstOrDefault((Gestor.Model.Domain.Financeiro.Centro x) => { + long id = x.get_Id(); + long? idCentro = selectedFornecedor.get_IdCentro(); + return id == idCentro.GetValueOrDefault() & idCentro.HasValue; + }) ?? this.CentrosFiltrados.FirstOrDefault() : this.CentrosFiltrados.FirstOrDefault()); + Fornecedor fornecedor3 = selectedFornecedor; + if (fornecedor3 != null) + { + tipoPagamento = fornecedor3.get_TipoPagamento(); + } + else + { + nullable = null; + tipoPagamento = nullable; + } + nullable = tipoPagamento; + Gestor.Model.Common.TipoPagamento valueOrDefault = nullable.GetValueOrDefault(); + DateTime date = Funcoes.GetNetworkTime().Date; + Lancamento lancamento = new Lancamento(); + ControleFinanceiro controleFinanceiro = new ControleFinanceiro(); + controleFinanceiro.set_Fornecedor(selectedFornecedor); + controleFinanceiro.set_Centro(centro); + controleFinanceiro.set_Plano(plano); + controleFinanceiro.set_Parcelas(1); + lancamento.set_Controle(controleFinanceiro); + lancamento.set_Conta(bancosConta); + lancamento.set_Vencimento(date); + lancamento.set_Parcela(1); + lancamento.set_TipoPagamento(valueOrDefault); + this.SelectedLancamento = lancamento; + this.FornecedorInclusao = selectedFornecedor ?? new Fornecedor(); + this.Historico = ""; + this.Documento = ""; + this.Competencia = ""; + this.Complemento = ""; + this.Plano = plano; + this.Centro = centro; + this.Conta = bancosConta; + Gestor.Model.Domain.Financeiro.Planos plano1 = this.Plano; + if (plano1 != null) + { + sinal = plano1.get_Sinal(); + } + else + { + sinal = 0; + } + this.Sinal = sinal; + this.Parcelas = 1; + this.Parcela = 0; + this.Vencimento = date; + this.Valor = decimal.Zero; + DateTime? nullable1 = null; + this.Baixa = nullable1; + this.ValorPago = new decimal?(new decimal()); + nullable1 = null; + this.Pagamento = nullable1; + this.TipoPagamento = valueOrDefault; + this.Observacao = ""; + this.Alteracao = false; + this.VisibilityCentro = (this.CentrosFiltrados.Count > 1 ? Visibility.Visible : Visibility.Collapsed); + this.VisibilityConta = (this.ContasFiltradas.Count > 1 ? Visibility.Visible : Visibility.Collapsed); + } + + public async void IncluirParcela() + { + bool controle; + Visibility visibility; + Visibility visibility1; + ObservableCollection lancamentosFiltrados = this.LancamentosFiltrados; + if (lancamentosFiltrados.Any((Lancamento x) => x.get_Selecionado())) + { + ObservableCollection observableCollection = this.LancamentosFiltrados; + if (observableCollection.Count((Lancamento x) => x.get_Selecionado()) == 1) + { + FinanceiroViewModel financeiroViewModel = this; + ObservableCollection lancamentosFiltrados1 = this.LancamentosFiltrados; + financeiroViewModel.SelectedLancamento = lancamentosFiltrados1.FirstOrDefault((Lancamento x) => x.get_Selecionado()); + } + ObservableCollection observableCollection1 = this.LancamentosFiltrados; + if (observableCollection1.Count((Lancamento x) => x.get_Selecionado()) <= 1) + { + Lancamento selectedLancamento = this.SelectedLancamento; + if (selectedLancamento != null) + { + controle = selectedLancamento.get_Controle(); + } + else + { + controle = false; + } + if (controle && this.SelectedLancamento.get_Controle().get_Id() != 0) + { + this.VisibilityFornecedor = Visibility.Collapsed; + this.Alterando = Visibility.Visible; + this.BuscaHabilitada = false; + Lancamento lancamento = new Lancamento(); + ControleFinanceiro controleFinanceiro = new ControleFinanceiro(); + controleFinanceiro.set_Centro(this.SelectedLancamento.get_Controle().get_Centro()); + controleFinanceiro.set_Fornecedor(this.SelectedLancamento.get_Controle().get_Fornecedor()); + controleFinanceiro.set_Historico(this.SelectedLancamento.get_Controle().get_Historico()); + controleFinanceiro.set_Id(this.SelectedLancamento.get_Controle().get_Id()); + controleFinanceiro.set_Parcelas(this.SelectedLancamento.get_Controle().get_Parcelas() + 1); + controleFinanceiro.set_Plano(this.SelectedLancamento.get_Controle().get_Plano()); + lancamento.set_Controle(controleFinanceiro); + lancamento.set_Historico(this.SelectedLancamento.get_Historico()); + lancamento.set_Observacao(this.SelectedLancamento.get_Observacao()); + DateTime vencimento = this.SelectedLancamento.get_Vencimento(); + lancamento.set_Vencimento(vencimento.AddMonths(1)); + lancamento.set_Conta(this.SelectedLancamento.get_Conta()); + lancamento.set_Parcela(this.SelectedLancamento.get_Parcela() + 1); + lancamento.set_Documento(this.SelectedLancamento.get_Documento()); + lancamento.set_Sinal(this.SelectedLancamento.get_Sinal()); + lancamento.set_TipoPagamento(this.SelectedLancamento.get_TipoPagamento()); + lancamento.set_Valor(this.SelectedLancamento.get_Valor()); + this.SelectedLancamento = lancamento; + FinanceiroViewModel financeiroViewModel1 = this; + visibility = (this.CentrosFiltrados.Count > 1 ? Visibility.Visible : Visibility.Collapsed); + financeiroViewModel1.VisibilityCentro = visibility; + FinanceiroViewModel financeiroViewModel2 = this; + visibility1 = (this.ContasFiltradas.Count > 1 ? Visibility.Visible : Visibility.Collapsed); + financeiroViewModel2.VisibilityConta = visibility1; + } + } + else if (await base.ShowMessage("HÁ MAIS DE UM LANÇAMENTO SELECIONADO, DESEJA FAZER A INCLUSÃO DE NOVAS PARCELAS PARA TODOS OS LANÇAMENTOS SELECIONADOS?", "SIM", "NÃO", false)) + { + await this.AdicionarParcelaRange(); + } + } + else + { + await base.ShowMessage("NECESSÁRIO SELECIONAR AO MENOS UM LANCAMENTOS PARA INCLUIR UMA NOVA PARCELA.", "OK", "", false); + } + } + + public void LimparFiltros() + { + this.FiltroPersonalizadoSelecionado = null; + this.VisibleFiltros = Visibility.Collapsed; + } + + public void LimparLancamentos() + { + this.Lancamentos = new ObservableCollection(); + this.LancamentosFiltrados = new ObservableCollection(); + this.LimparFiltros(); + } + + public async Task ParseOfx(BancosContas conta) + { + FinanceiroViewModel.u003cu003ec__DisplayClass256_1 variable = null; + Func func2 = null; + this.SelectedStatusImportacao = 2; + this.Importando = true; + this.VisibleFiltros = Visibility.Collapsed; + List ofxDocuments = await base.ImportarOfx(); + if (ofxDocuments == null || ofxDocuments.Count == 0) + { + this.Importando = false; + } + else + { + List strs = new List() + { + "0237", + "033" + }; + List lancamentos = new List(); + foreach (OfxDocument ofxDocument in ofxDocuments) + { + Tuple tuple = this.CorrigeLancamentos(ofxDocument, strs); + ofxDocument.set_StatementStart(tuple.Item1); + ofxDocument.set_StatementEnd(tuple.Item2); + FinanceiroServico financeiroServico = this._servico; + DateTime statementStart = ofxDocument.get_StatementStart(); + DateTime dateTime2 = statementStart.AddDays(-5); + statementStart = ofxDocument.get_StatementEnd(); + List lancamentos1 = await financeiroServico.BuscarLancamentos(dateTime2, statementStart.AddDays(5), conta.get_Id()); + List lancamentos2 = lancamentos1; + ofxDocument.get_Transactions().ForEach((Transaction t) => { + DateTime dateTime1; + bool length; + string str; + string str1; + string str2; + string str3; + string str4; + if (t.get_Date() < ofxDocument.get_StatementStart().AddDays(-5) && t.get_Date() < ofxDocument.get_StatementEnd().AddDays(5)) + { + List cSu0024u003cu003e8_locals1 = strs; + Func u003cu003e9_2 = func2; + if (u003cu003e9_2 == null) + { + FinanceiroViewModel.u003cu003ec__DisplayClass256_1 cSu0024u003cu003e8_locals2 = variable; + Func func = (string c) => c == this.x.get_Account().get_BankId().Trim(); + Func func1 = func; + cSu0024u003cu003e8_locals2.u003cu003e9__2 = func; + u003cu003e9_2 = func1; + } + if (!cSu0024u003cu003e8_locals1.Any(u003cu003e9_2)) + { + return; + } + } + Gestor.Model.Common.Sinal sinal = (t.get_Amount() < decimal.Zero ? 1 : 0); + Lancamento lancamento = lancamentos2.FirstOrDefault((Lancamento l) => { + if ((!l.get_ValorPago().HasValue || !(Math.Abs(l.get_ValorPago().Value) > decimal.Zero) || !(Math.Abs(l.get_ValorPago().Value) == Math.Abs(t.get_Amount()))) && !(Math.Abs(l.get_Valor()) == Math.Abs(t.get_Amount())) || l.get_Sinal() != sinal || l.get_Documento() == null || !t.get_TransactionId().Contains(l.get_Documento())) + { + return false; + } + DateTime? pagamento = l.get_Pagamento(); + DateTime date = t.get_Date(); + if ((pagamento.HasValue ? pagamento.GetValueOrDefault() == date : false) || l.get_Vencimento() == t.get_Date()) + { + return true; + } + DateTime vencimento = l.get_Vencimento(); + date = t.get_Date(); + if (vencimento < date.AddDays(-5)) + { + return false; + } + DateTime dateTime = l.get_Vencimento(); + date = t.get_Date(); + return dateTime <= date.AddDays(5); + }); + Gestor.Model.Common.TipoPagamento tipoPagamento = t.get_TransType().ParseTransactionType(); + string transactionId = t.get_TransactionId(); + length = (transactionId != null ? transactionId.Trim().Length > 50 : false); + if (length) + { + string transactionId1 = t.get_TransactionId(); + if (transactionId1 != null) + { + string str5 = transactionId1.Trim(); + if (str5 != null) + { + str = str5.Substring(0, 50); + } + else + { + str = null; + } + } + else + { + str = null; + } + } + else + { + string transactionId2 = t.get_TransactionId(); + if (transactionId2 != null) + { + str = transactionId2.Trim(); + } + else + { + str = null; + } + } + string str6 = str; + if (lancamento == null) + { + Lancamento lancamento1 = new Lancamento(); + ControleFinanceiro controleFinanceiro = new ControleFinanceiro(); + controleFinanceiro.set_Fornecedor(null); + controleFinanceiro.set_Centro(this.Centros.FirstOrDefault()); + controleFinanceiro.set_Plano(null); + controleFinanceiro.set_Parcelas(1); + string memo = t.get_Memo(); + if (memo != null) + { + str1 = memo.Trim(); + } + else + { + str1 = null; + } + controleFinanceiro.set_Historico(str1); + lancamento1.set_Controle(controleFinanceiro); + lancamento1.set_Valor(Math.Abs(t.get_Amount())); + lancamento1.set_ValorPago(new decimal?(Math.Abs(t.get_Amount()))); + string memo1 = t.get_Memo(); + if (memo1 != null) + { + str2 = memo1.Trim(); + } + else + { + str2 = null; + } + lancamento1.set_Historico(str2); + lancamento1.set_Sinal((t.get_Amount() < decimal.Zero ? 1 : 0)); + lancamento1.set_Conta(conta); + lancamento1.set_Vencimento(t.get_Date()); + lancamento1.set_Baixa(new DateTime?(t.get_Date())); + lancamento1.set_Pagamento(new DateTime?(t.get_Date())); + string transactionId3 = t.get_TransactionId(); + if (transactionId3 != null) + { + str3 = transactionId3.Trim(); + } + else + { + str3 = null; + } + lancamento1.set_Documento(str3); + lancamento1.set_TipoPagamento(tipoPagamento); + dateTime1 = t.get_Date(); + lancamento1.set_Competencia(dateTime1.ToString("MM/yyyy")); + lancamento1.set_Parcela(1); + string transactionId4 = t.get_TransactionId(); + if (transactionId4 != null) + { + str4 = transactionId4.Trim(); + } + else + { + str4 = null; + } + lancamento1.set_CodigoBanco(str4); + lancamento1.set_Baixado(false); + lancamento = lancamento1; + } + else + { + lancamento.set_Baixado(lancamento.get_Baixa().HasValue); + lancamento.set_Conta(conta); + lancamento.set_ValorPago(new decimal?(Math.Abs(t.get_Amount()))); + dateTime1 = t.get_Date(); + lancamento.set_Competencia(dateTime1.ToString("MM/yyyy")); + lancamento.set_Baixa((!lancamento.get_Baixa().HasValue ? new DateTime?(t.get_Date()) : lancamento.get_Baixa())); + lancamento.set_Pagamento((!lancamento.get_Pagamento().HasValue ? new DateTime?(t.get_Date()) : lancamento.get_Pagamento())); + lancamento.set_Documento(str6); + lancamento.set_CodigoBanco(t.get_TransactionId()); + lancamento.set_TipoPagamento((lancamento.get_TipoPagamento() == null ? tipoPagamento : lancamento.get_TipoPagamento())); + } + lancamentos.Add(lancamento); + }); + } + this.Lancamentos = new ObservableCollection(lancamentos); + this.LancamentosFiltrados = this.Lancamentos; + ExtensionMethods.ForEach(this.LancamentosFiltrados, (Lancamento x) => this.SelecionarLancamento(x)); + this.LancamentosFiltradosCopia = this.LancamentosFiltrados; + } + } + + public void PesquisaPersonalizada() + { + List list = ( + from x in this.PersonalizadoSelecionado + where !x.get_Propriedade().Contains(".") + select x).ToList(); + List list1 = this.Lancamentos.ToList().CustomWhere(list, false); + ( + from x in this.PersonalizadoSelecionado + where x.get_Propriedade().Contains(".") + select x).ToList().ForEach((Gestor.Model.Domain.Relatorios.FiltroPersonalizado x) => { + string str = x.get_Nome(); + if (str == "FORNECEDOR") + { + list1 = list1.Where((Lancamento l) => { + bool nomeSocial; + ControleFinanceiro controle = l.get_Controle(); + if (controle != null) + { + Fornecedor fornecedor = controle.get_Fornecedor(); + nomeSocial = (fornecedor != null ? fornecedor.get_NomeSocial() : false); + } + else + { + nomeSocial = false; + } + if (!nomeSocial) + { + return false; + } + return Gestor.Common.Validation.ValidationHelper.AlphanumericAndSpace(l.get_Controle().get_Fornecedor().get_NomeSocial().ToLower().Trim()).Contains(Gestor.Common.Validation.ValidationHelper.AlphanumericAndSpace(x.get_ValorIncial().ToLower().Trim())); + }).ToList(); + return; + } + if (str == "FORNECEDOR ATIVO") + { + if (x.get_ValorIncial().Trim().Equals("SIM")) + { + List lancamentos = list1; + Func u003cu003e9_3584 = FinanceiroViewModel.u003cu003ec.u003cu003e9__358_4; + if (u003cu003e9_3584 == null) + { + u003cu003e9_3584 = (Lancamento l) => { + bool flag; + ControleFinanceiro controle = l.get_Controle(); + if (controle != null) + { + Fornecedor fornecedor = controle.get_Fornecedor(); + if (fornecedor != null) + { + fornecedor.get_Ativo(); + flag = true; + } + else + { + flag = false; + } + } + else + { + flag = false; + } + if (!flag) + { + return false; + } + return l.get_Controle().get_Fornecedor().get_Ativo(); + }; + FinanceiroViewModel.u003cu003ec.u003cu003e9__358_4 = u003cu003e9_3584; + } + list1 = lancamentos.Where(u003cu003e9_3584).ToList(); + return; + } + if (x.get_ValorIncial().Equals("NÃO")) + { + List lancamentos1 = list1; + Func u003cu003e9_3585 = FinanceiroViewModel.u003cu003ec.u003cu003e9__358_5; + if (u003cu003e9_3585 == null) + { + u003cu003e9_3585 = (Lancamento l) => { + bool flag; + ControleFinanceiro controle = l.get_Controle(); + if (controle != null) + { + Fornecedor fornecedor = controle.get_Fornecedor(); + if (fornecedor != null) + { + fornecedor.get_Ativo(); + flag = true; + } + else + { + flag = false; + } + } + else + { + flag = false; + } + if (!flag) + { + return false; + } + return !l.get_Controle().get_Fornecedor().get_Ativo(); + }; + FinanceiroViewModel.u003cu003ec.u003cu003e9__358_5 = u003cu003e9_3585; + } + list1 = lancamentos1.Where(u003cu003e9_3585).ToList(); + return; + } + } + else + { + if (str == "CONTA") + { + list1 = list1.Where((Lancamento l) => { + bool descricao; + BancosContas conta = l.get_Conta(); + descricao = (conta != null ? conta.get_Descricao() : false); + if (!descricao) + { + return false; + } + return Gestor.Common.Validation.ValidationHelper.AlphanumericAndSpace(l.get_Conta().get_Descricao().ToLower().Trim()).Contains(Gestor.Common.Validation.ValidationHelper.AlphanumericAndSpace(x.get_ValorIncial().ToLower().Trim())); + }).ToList(); + return; + } + if (str == "PLANO DE CONTAS") + { + list1 = list1.Where((Lancamento l) => { + bool descricao; + ControleFinanceiro controle = l.get_Controle(); + if (controle != null) + { + Gestor.Model.Domain.Financeiro.Planos plano = controle.get_Plano(); + descricao = (plano != null ? plano.get_Descricao() : false); + } + else + { + descricao = false; + } + if (!descricao) + { + return false; + } + return Gestor.Common.Validation.ValidationHelper.AlphanumericAndSpace(l.get_Controle().get_Plano().get_Descricao().ToLower().Trim()).Contains(Gestor.Common.Validation.ValidationHelper.AlphanumericAndSpace(x.get_ValorIncial().ToLower().Trim())); + }).ToList(); + return; + } + if (str == "CENTRO DE CUSTO") + { + list1 = list1.Where((Lancamento l) => { + bool descricao; + ControleFinanceiro controle = l.get_Controle(); + if (controle != null) + { + Gestor.Model.Domain.Financeiro.Centro centro = controle.get_Centro(); + descricao = (centro != null ? centro.get_Descricao() : false); + } + else + { + descricao = false; + } + if (!descricao) + { + return false; + } + return Gestor.Common.Validation.ValidationHelper.AlphanumericAndSpace(l.get_Controle().get_Centro().get_Descricao().ToLower().Trim()).Contains(Gestor.Common.Validation.ValidationHelper.AlphanumericAndSpace(x.get_ValorIncial().ToLower().Trim())); + }).ToList(); + return; + } + if (str != "PLANO") + { + return; + } + list1 = list1.Where((Lancamento l) => { + bool nome; + ControleFinanceiro controle = l.get_Controle(); + if (controle != null) + { + Gestor.Model.Domain.Financeiro.Planos plano = controle.get_Plano(); + nome = (plano != null ? plano.get_Nome() : false); + } + else + { + nome = false; + } + if (!nome) + { + return false; + } + return Gestor.Common.Validation.ValidationHelper.AlphanumericAndSpace(l.get_Controle().get_Plano().get_Nome().ToLower().Trim()).Contains(Gestor.Common.Validation.ValidationHelper.AlphanumericAndSpace(x.get_ValorIncial().ToLower().Trim())); + }).ToList(); + } + }); + this.LancamentosFiltrados = new ObservableCollection(list1); + } + + public async void PopularFiltro() + { + if (this.FiltroPersonalizado == null || this.FiltroPersonalizado.Count <= 0) + { + this.FiltroPersonalizado = new List(); + List fornecedors = await (new BaseServico()).BuscarFornecedor(); + List list = fornecedors.Select((Fornecedor x) => { + Gestor.Model.Domain.Financeiro.FiltroPersonalizado filtroPersonalizado = new Gestor.Model.Domain.Financeiro.FiltroPersonalizado(); + filtroPersonalizado.set_Tipo(0); + filtroPersonalizado.set_Descricao(string.Concat(x.get_Nome(), " ", x.get_Documento())); + filtroPersonalizado.set_Id(x.get_Id()); + return filtroPersonalizado; + }).ToList(); + this.FiltroPersonalizado.AddRange(list); + List centros = this.Centros; + list = centros.Select((Gestor.Model.Domain.Financeiro.Centro x) => { + Gestor.Model.Domain.Financeiro.FiltroPersonalizado filtroPersonalizado = new Gestor.Model.Domain.Financeiro.FiltroPersonalizado(); + filtroPersonalizado.set_Tipo(2); + filtroPersonalizado.set_Descricao(x.get_Descricao()); + filtroPersonalizado.set_Id(x.get_Id()); + return filtroPersonalizado; + }).ToList(); + this.FiltroPersonalizado.AddRange(list); + List planos = this.Planos; + list = planos.Select((Gestor.Model.Domain.Financeiro.Planos x) => { + Gestor.Model.Domain.Financeiro.FiltroPersonalizado filtroPersonalizado = new Gestor.Model.Domain.Financeiro.FiltroPersonalizado(); + filtroPersonalizado.set_Tipo(1); + filtroPersonalizado.set_Descricao(x.get_Descricao()); + filtroPersonalizado.set_Id(x.get_Id()); + return filtroPersonalizado; + }).ToList(); + this.FiltroPersonalizado.AddRange(list); + List contas = this.Contas; + list = contas.Select((BancosContas x) => { + Gestor.Model.Domain.Financeiro.FiltroPersonalizado filtroPersonalizado = new Gestor.Model.Domain.Financeiro.FiltroPersonalizado(); + filtroPersonalizado.set_Tipo(3); + filtroPersonalizado.set_Descricao(x.get_Descricao()); + filtroPersonalizado.set_Id(x.get_Id()); + return filtroPersonalizado; + }).ToList(); + this.FiltroPersonalizado.AddRange(list); + List filtroPersonalizados = this.FiltroPersonalizado; + Gestor.Model.Domain.Financeiro.FiltroPersonalizado filtroPersonalizado1 = new Gestor.Model.Domain.Financeiro.FiltroPersonalizado(); + filtroPersonalizado1.set_Descricao(EnumHelper.GetDescription(0)); + filtroPersonalizado1.set_Id((long)0); + filtroPersonalizado1.set_Tipo(4); + filtroPersonalizados.Add(filtroPersonalizado1); + List filtroPersonalizados1 = this.FiltroPersonalizado; + Gestor.Model.Domain.Financeiro.FiltroPersonalizado filtroPersonalizado2 = new Gestor.Model.Domain.Financeiro.FiltroPersonalizado(); + filtroPersonalizado2.set_Descricao(EnumHelper.GetDescription(1)); + filtroPersonalizado2.set_Id((long)1); + filtroPersonalizado2.set_Tipo(4); + filtroPersonalizados1.Add(filtroPersonalizado2); + } + } + + public async Task Print(List relatorioGrid, bool posicao = false) + { + string tempPath = Path.GetTempPath(); + string str = await this.GerarHtml(relatorioGrid, posicao); + string str1 = string.Format("{0}RELATORIO FINANCEIRO_{1:ddMMyyyyhhmmss}.html", tempPath, Funcoes.GetNetworkTime()); + StreamWriter streamWriter = new StreamWriter(str1, true, Encoding.UTF8); + streamWriter.Write(str); + streamWriter.Close(); + Process.Start(str1); + tempPath = null; + } + + public async Task>> Salvar(Transferencia transferencia) + { + List> keyValuePairs; + List> keyValuePairs1 = transferencia.Validate(); + List> keyValuePairs2 = keyValuePairs1; + keyValuePairs2.AddRange(await this.Validar(transferencia)); + keyValuePairs2 = null; + if (keyValuePairs1.Count <= 0) + { + ControleFinanceiro controleFinanceiro = new ControleFinanceiro(); + controleFinanceiro.set_Historico("TRANSFERÊNCIA ENTRE CONTAS"); + controleFinanceiro.set_Parcelas(2); + ControleFinanceiro controleFinanceiro1 = controleFinanceiro; + Lancamento lancamento = new Lancamento(); + lancamento.set_Controle(controleFinanceiro1); + lancamento.set_Historico("TRANSFERÊNCIA ENTRE CONTAS"); + lancamento.set_Vencimento(transferencia.get_Data()); + lancamento.set_Conta(transferencia.get_Origem()); + lancamento.set_Valor(transferencia.get_Valor()); + lancamento.set_ValorPago(new decimal?(transferencia.get_Valor())); + lancamento.set_Pagamento(new DateTime?(transferencia.get_Data())); + lancamento.set_Baixa(new DateTime?(transferencia.get_Data())); + lancamento.set_Parcela(1); + lancamento.set_Sinal(1); + lancamento.set_TipoPagamento(11); + Lancamento lancamento1 = lancamento; + Lancamento lancamento2 = new Lancamento(); + lancamento2.set_Controle(controleFinanceiro1); + lancamento2.set_Historico("TRANSFERÊNCIA ENTRE CONTAS"); + lancamento2.set_Vencimento(transferencia.get_Data()); + lancamento2.set_Conta(transferencia.get_Destino()); + lancamento2.set_Valor(transferencia.get_Valor()); + lancamento2.set_ValorPago(new decimal?(transferencia.get_Valor())); + lancamento2.set_Pagamento(new DateTime?(transferencia.get_Data())); + lancamento2.set_Baixa(new DateTime?(transferencia.get_Data())); + lancamento2.set_Parcela(2); + lancamento2.set_Sinal(0); + lancamento2.set_TipoPagamento(11); + if (await this._servico.Transferir(lancamento1, lancamento2)) + { + await this.CarregarSaldos(); + base.ToggleSnackBar("TRANSFERÊNCIA REALIZADA COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + keyValuePairs1 = null; + return keyValuePairs; + } + + public async Task>> Salvar() + { + List> keyValuePairs; + DateTime? nullable; + DateTime vencimento; + decimal? nullable1; + DateTime? pagamento; + DateTime? baixa; + string str; + long? nullable2; + object historico; + bool flag; + long num; + List> keyValuePairs1 = this.SelectedLancamento.Validate(); + if (keyValuePairs1 == null) + { + keyValuePairs1 = new List>(); + } + List> keyValuePairs2 = keyValuePairs1; + List> keyValuePairs3 = keyValuePairs2; + keyValuePairs3.AddRange(await this.Validar()); + keyValuePairs3 = null; + if (keyValuePairs2.Count > 0) + { + keyValuePairs = keyValuePairs2; + } + else if (this.SelectedLancamento.get_Controle().get_Id() != (long)0 || this.SelectedLancamento.get_Controle().get_Parcelas() <= 0) + { + if (this.SelectedLancamento.get_Controle().get_Id() == 0) + { + this.VencimentoAlterado = false; + } + this.SelectedLancamento = await this._servico.Save(this.SelectedLancamento); + if (this.VencimentoAlterado && this.SelectedLancamento.get_Controle().get_Parcelas() > 1) + { + if (await base.ShowMessage("DESEJA ALTERAR O VENCIMENTO PARA OS PRÓXIMOS LANÇAMENTOS?", "SIM", "NÃO", false)) + { + await this.AlterarLancamentos(this.SelectedLancamento, true, false); + } + this.VencimentoAlterado = false; + } + if (this.SelectedLancamento.get_Controle().get_Parcelas() > 1) + { + if (await base.ShowMessage("DESEJA ALTERAR O VALOR PARA OS PRÓXIMOS LANÇAMENTOS?", "SIM", "NÃO", false)) + { + await this.AlterarLancamentos(this.SelectedLancamento, false, true); + } + } + if (this._servico.Sucesso) + { + await this.Buscar(); + base.ToggleSnackBar("LANÇAMENTO SALVO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + List lancamentos = new List(); + for (int i = 1; i <= this.SelectedLancamento.get_Controle().get_Parcelas(); i++) + { + Lancamento lancamento = new Lancamento(); + ControleFinanceiro controleFinanceiro = new ControleFinanceiro(); + controleFinanceiro.set_Centro(this.SelectedLancamento.get_Controle().get_Centro()); + controleFinanceiro.set_Fornecedor(this.SelectedLancamento.get_Controle().get_Fornecedor()); + controleFinanceiro.set_Historico(this.SelectedLancamento.get_Controle().get_Historico()); + controleFinanceiro.set_Id(this.SelectedLancamento.get_Controle().get_Id()); + controleFinanceiro.set_Parcelas(this.SelectedLancamento.get_Controle().get_Parcelas()); + controleFinanceiro.set_Plano(this.SelectedLancamento.get_Controle().get_Plano()); + lancamento.set_Controle(controleFinanceiro); + lancamento.set_Historico(this.SelectedLancamento.get_Historico()); + lancamento.set_Observacao(this.SelectedLancamento.get_Observacao()); + lancamento.set_Complemento(this.SelectedLancamento.get_Complemento()); + lancamento.set_Competencia(this.SelectedLancamento.get_Competencia()); + if (i == 1) + { + vencimento = this.SelectedLancamento.get_Vencimento(); + } + else + { + DateTime dateTime = this.SelectedLancamento.get_Vencimento(); + vencimento = dateTime.AddMonths(i - 1); + } + lancamento.set_Vencimento(vencimento); + lancamento.set_Conta(this.SelectedLancamento.get_Conta()); + nullable1 = (i == 1 ? this.SelectedLancamento.get_ValorPago() : new decimal?(new decimal())); + lancamento.set_ValorPago(nullable1); + if (i == 1) + { + pagamento = this.SelectedLancamento.get_Pagamento(); + } + else + { + nullable = null; + pagamento = nullable; + } + lancamento.set_Pagamento(pagamento); + if (i == 1) + { + baixa = this.SelectedLancamento.get_Baixa(); + } + else + { + nullable = null; + baixa = nullable; + } + lancamento.set_Baixa(baixa); + lancamento.set_Parcela(i); + str = (i == 1 ? this.SelectedLancamento.get_Documento() : ""); + lancamento.set_Documento(str); + lancamento.set_Sinal(this.SelectedLancamento.get_Sinal()); + lancamento.set_TipoPagamento(this.SelectedLancamento.get_TipoPagamento()); + lancamento.set_Valor(this.SelectedLancamento.get_Valor()); + lancamentos.Add(lancamento); + } + List lancamentos1 = await this._servico.AddRange(lancamentos); + this.SelectedLancamento = lancamentos1.FirstOrDefault(); + FinanceiroViewModel financeiroViewModel = this; + Lancamento selectedLancamento = this.SelectedLancamento; + if (selectedLancamento != null) + { + nullable2 = new long?(selectedLancamento.get_Id()); + } + else + { + nullable2 = null; + } + object obj = nullable2; + Lancamento selectedLancamento1 = this.SelectedLancamento; + if (selectedLancamento1 != null) + { + historico = selectedLancamento1.get_Historico(); + } + else + { + historico = null; + } + string str1 = string.Format("INSERIU O LANÇAMENTO DO ID {0} HISTORICO: {1}", obj, historico); + Lancamento lancamento1 = this.SelectedLancamento; + if (lancamento1 != null) + { + lancamento1.get_Id(); + flag = false; + } + else + { + flag = true; + } + num = (flag ? (long)0 : this.SelectedLancamento.get_Id()); + financeiroViewModel.RegistrarAcao(str1, num, new TipoTela?(25), null); + this.VencimentoAlterado = false; + keyValuePairs = null; + } + keyValuePairs2 = null; + return keyValuePairs; + } + + public async Task SalvarImportacao(List list) + { + bool flag; + DateTime? baixa; + DateTime? nullable; + string[] strArrays; + bool flag1; + bool flag2; + string historico; + object obj; + bool flag3; + long num; + Lancamento lancamento = null; + List lancamentos = new List(); + List lancamentos1 = new List(); + List lancamentos2 = new List(); + List lancamentos3 = new List(); + foreach (Lancamento lancamento in list) + { + if (lancamento.get_Baixado()) + { + continue; + } + if (!lancamento.get_Selecionado()) + { + baixa = null; + lancamento.set_Baixa(baixa); + } + baixa = lancamento.get_Baixa(); + if (baixa.HasValue) + { + Saldo saldo = await this.VerificaSaldo(lancamento.get_Conta().get_Id(), false); + if (saldo == null) + { + continue; + } + baixa = saldo.get_DataInicio(); + nullable = lancamento.get_Baixa(); + flag1 = (baixa.HasValue & nullable.HasValue ? baixa.GetValueOrDefault() > nullable.GetValueOrDefault() : false); + if (flag1) + { + continue; + } + } + string observacao = lancamento.get_Observacao(); + if (observacao != null) + { + strArrays = observacao.Split(new char[] { '\n' }); + } + else + { + strArrays = null; + } + string[] strArrays1 = strArrays; + StringBuilder stringBuilder = new StringBuilder(); + string str = "IMPORTAÇÃO OFX REALIZADA PELO USUÁRIO"; + if (strArrays1 != null) + { + string[] strArrays2 = strArrays1; + for (int i = 0; i < (int)strArrays2.Length; i++) + { + string str1 = strArrays2[i]; + if (str1.IndexOf(str, StringComparison.InvariantCulture) != 0) + { + stringBuilder.Append(string.Concat(str1, "\n")); + } + } + } + Lancamento lancamento1 = lancamento; + object[] id = new object[] { stringBuilder, Recursos.Usuario.get_Id(), Recursos.Usuario.get_Nome(), null }; + DateTime networkTime = Funcoes.GetNetworkTime(); + id[3] = networkTime.ToString("F").ToUpper(); + lancamento1.set_Observacao(string.Format("{0}IMPORTAÇÃO OFX REALIZADA PELO USUÁRIO {1} {2} EM {3}", id)); + if (lancamento.get_Id() <= (long)0) + { + lancamentos2.Add(lancamento); + } + else + { + nullable = lancamento.get_Baixa(); + if (!nullable.HasValue) + { + lancamentos.Add(lancamento); + } + else + { + lancamentos1.Add(lancamento); + } + } + lancamentos3.Add(lancamento); + } + if (lancamentos3.Count != 0) + { + object[] count = new object[] { lancamentos2.Count, Environment.NewLine, lancamentos.Count, Environment.NewLine, lancamentos1.Count, Environment.NewLine, Environment.NewLine }; + if (await base.ShowMessage(string.Format("{0} LANÇAMENTOS SERÃO CRIADOS.{1}{2} LANÇAMENTOS SERÃO ATUALIZADOS.{3}{4} LANÇAMENTOS SERÃO BAIXADOS.{5}{6}DESEJA REALMENTE PROSSEGUIR?", count), "SIM", "NÃO", false)) + { + bool flag4 = true; + foreach (Lancamento lancamento2 in lancamentos3) + { + await this._servico.Save(lancamento2); + flag4 = (flag4 ? this._servico.Sucesso : false); + flag2 = (lancamento2 == null ? false : lancamento2.get_Id() != (long)0); + if (flag2 & flag4) + { + FinanceiroViewModel financeiroViewModel = this; + object id1 = lancamento2.get_Id(); + Lancamento lancamento3 = lancamento2; + if (lancamento3 != null) + { + obj = lancamento3.get_Historico(); + } + else + { + obj = null; + } + string str2 = string.Format("BAIXOU/ATUALIZOU O LANÇAMENTO DO ID {0}POR IMPORTAÇÃO HISTORICO: {1}", id1, obj); + Lancamento lancamento4 = lancamento2; + if (lancamento4 != null) + { + lancamento4.get_Id(); + flag3 = false; + } + else + { + flag3 = true; + } + num = (flag3 ? (long)0 : lancamento2.get_Id()); + financeiroViewModel.RegistrarAcao(str2, num, new TipoTela?(25), null); + } + else if (lancamento2 != null & flag4) + { + FinanceiroViewModel financeiroViewModel1 = this; + Lancamento lancamento5 = lancamento2; + if (lancamento5 != null) + { + historico = lancamento5.get_Historico(); + } + else + { + historico = null; + } + financeiroViewModel1.RegistrarAcao(string.Concat("INSERIU O LANÇAMENTO POR IMPORTAÇÃO HISTORICO: ", historico), (long)0, new TipoTela?(25), null); + } + } + if (flag4) + { + await this.Buscar(); + base.ToggleSnackBar("ATUALIZAÇÃO REALIZADA COM SUCESSO", true); + await this.CarregarSaldos(); + flag = true; + } + else + { + await base.ShowMessage("HOUVERAM PROBLEMAS AO INCLUIR OU ATUALIZAR LANÇAMENTOS, FAVOR CONFERIR A IMPORTAÇÃO.", "OK", "", false); + flag = false; + } + } + else + { + base.Loading(false); + flag = false; + } + } + else + { + await base.ShowMessage("NÃO HÁ LANÇAMENTOS PARA SEREM ATUALIZADOS.", "OK", "", false); + base.Loading(false); + flag = false; + } + lancamentos = null; + lancamentos1 = null; + lancamentos2 = null; + lancamentos3 = null; + return flag; + } + + public void SelecionarLancamento(Lancamento lancamento) + { + Lancamento lancamento1 = (lancamento.get_Id() > (long)0 ? this.LancamentosFiltrados.First((Lancamento x) => x.get_Id() == lancamento.get_Id()) : this.LancamentosFiltrados.First((Lancamento x) => { + long? nullable; + long? nullable1; + long? nullable2; + long? nullable3; + long? nullable4; + if (x.get_Id() == lancamento.get_Id()) + { + ControleFinanceiro controle = x.get_Controle(); + if (controle != null) + { + Fornecedor fornecedor = controle.get_Fornecedor(); + if (fornecedor != null) + { + nullable1 = new long?(fornecedor.get_Id()); + } + else + { + nullable = null; + nullable1 = nullable; + } + } + else + { + nullable = null; + nullable1 = nullable; + } + long? nullable5 = nullable1; + ControleFinanceiro controleFinanceiro = lancamento.get_Controle(); + if (controleFinanceiro != null) + { + Fornecedor fornecedor1 = controleFinanceiro.get_Fornecedor(); + if (fornecedor1 != null) + { + nullable2 = new long?(fornecedor1.get_Id()); + } + else + { + nullable = null; + nullable2 = nullable; + } + } + else + { + nullable = null; + nullable2 = nullable; + } + long? nullable6 = nullable2; + if (nullable5.GetValueOrDefault() == nullable6.GetValueOrDefault() & nullable5.HasValue == nullable6.HasValue && x.get_Valor() == lancamento.get_Valor() && x.get_Vencimento() == lancamento.get_Vencimento()) + { + ControleFinanceiro controle1 = x.get_Controle(); + if (controle1 != null) + { + Gestor.Model.Domain.Financeiro.Planos plano = controle1.get_Plano(); + if (plano != null) + { + nullable3 = new long?(plano.get_Id()); + } + else + { + nullable = null; + nullable3 = nullable; + } + } + else + { + nullable = null; + nullable3 = nullable; + } + nullable6 = nullable3; + ControleFinanceiro controleFinanceiro1 = lancamento.get_Controle(); + if (controleFinanceiro1 != null) + { + Gestor.Model.Domain.Financeiro.Planos plano1 = controleFinanceiro1.get_Plano(); + if (plano1 != null) + { + nullable4 = new long?(plano1.get_Id()); + } + else + { + nullable = null; + nullable4 = nullable; + } + } + else + { + nullable = null; + nullable4 = nullable; + } + nullable5 = nullable4; + if (nullable6.GetValueOrDefault() == nullable5.GetValueOrDefault() & nullable6.HasValue == nullable5.HasValue) + { + return lancamento.get_Documento() == x.get_Documento(); + } + } + } + return false; + })); + DateTime date = Funcoes.GetNetworkTime().Date; + lancamento1.set_Selecionado(true); + Lancamento lancamento2 = lancamento1; + DateTime? baixa = lancamento1.get_Baixa(); + lancamento2.set_Baixa(new DateTime?((baixa.HasValue ? baixa.GetValueOrDefault() : lancamento1.get_Pagamento().GetValueOrDefault(date)))); + baixa = lancamento1.get_Pagamento(); + lancamento1.set_Pagamento(new DateTime?(baixa.GetValueOrDefault(date))); + Lancamento lancamento3 = lancamento1; + decimal? valorPago = lancamento1.get_ValorPago(); + decimal num = new decimal(); + lancamento3.set_ValorPago(((valorPago.GetValueOrDefault() == num) & valorPago.HasValue ? new decimal?(lancamento.get_Valor()) : lancamento1.get_ValorPago())); + this.LancamentosFiltradosCopia = this.LancamentosFiltrados; + this.Totalizar(); + } + + public void SelecionarTodos() + { + List list = this.LancamentosFiltrados.ToList(); + list.ForEach((Lancamento x) => { + DateTime? baixa; + decimal num; + x.set_Selecionado(!x.get_Selecionado()); + if (x.get_Baixado() || this.importando) + { + return; + } + if (!x.get_Selecionado()) + { + baixa = null; + x.set_Baixa(baixa); + baixa = null; + x.set_Pagamento(baixa); + num = new decimal(); + x.set_ValorPago(new decimal?(num)); + return; + } + DateTime date = Funcoes.GetNetworkTime().Date; + Lancamento lancamento = x; + baixa = x.get_Baixa(); + lancamento.set_Baixa((!baixa.HasValue ? new DateTime?(date) : x.get_Baixa())); + x.set_Baixa(new DateTime?(date)); + Lancamento lancamento1 = x; + baixa = x.get_Pagamento(); + lancamento1.set_Pagamento((!baixa.HasValue ? new DateTime?(date) : x.get_Pagamento())); + Lancamento lancamento2 = x; + decimal? valorPago = x.get_ValorPago(); + num = new decimal(); + lancamento2.set_ValorPago(((valorPago.GetValueOrDefault() == num) & valorPago.HasValue ? new decimal?(x.get_Valor()) : x.get_ValorPago())); + }); + this.LancamentosFiltrados = new ObservableCollection(list); + this.LancamentosFiltradosCopia = this.LancamentosFiltrados; + } + + public void Sintetizar() + { + List list; + switch (this.SinteticoTipo) + { + case 1: + { + list = ( + from x in this.LancamentosFiltrados + where x.get_Controle().get_Plano() != null + group x by new { Id = x.get_Controle().get_Centro().get_Id(), Descricao = x.get_Controle().get_Centro().get_Descricao() }).Select((x) => { + Sintetico sintetico = new Sintetico(); + sintetico.set_Agrupamento(x.Key.Descricao); + sintetico.set_Valor(new decimal?(x.Sum((Lancamento s) => { + if (s.get_Sinal() == null) + { + return s.get_Valor(); + } + return -s.get_Valor(); + }))); + sintetico.set_ValorPago(new decimal?(x.Sum((Lancamento s) => { + decimal? valorPago; + decimal? nullable; + if (s.get_Sinal() == null) + { + valorPago = s.get_ValorPago(); + return valorPago.GetValueOrDefault(); + } + decimal? valorPago1 = s.get_ValorPago(); + if (valorPago1.HasValue) + { + nullable = new decimal?(-valorPago1.GetValueOrDefault()); + } + else + { + valorPago = null; + nullable = valorPago; + } + valorPago = nullable; + return valorPago.GetValueOrDefault(); + }))); + return sintetico; + }).ToList(); + break; + } + case 2: + { + list = ( + from x in this.LancamentosFiltrados + where x.get_Controle().get_Plano() != null + group x by new { Id = x.get_Controle().get_Fornecedor().get_Id(), Nome = x.get_Controle().get_Fornecedor().get_Nome() }).Select((x) => { + Sintetico sintetico = new Sintetico(); + sintetico.set_Agrupamento(x.Key.Nome); + sintetico.set_Valor(new decimal?(x.Sum((Lancamento s) => { + if (s.get_Sinal() == null) + { + return s.get_Valor(); + } + return -s.get_Valor(); + }))); + sintetico.set_ValorPago(new decimal?(x.Sum((Lancamento s) => { + decimal? valorPago; + decimal? nullable; + if (s.get_Sinal() == null) + { + valorPago = s.get_ValorPago(); + return valorPago.GetValueOrDefault(); + } + decimal? valorPago1 = s.get_ValorPago(); + if (valorPago1.HasValue) + { + nullable = new decimal?(-valorPago1.GetValueOrDefault()); + } + else + { + valorPago = null; + nullable = valorPago; + } + valorPago = nullable; + return valorPago.GetValueOrDefault(); + }))); + return sintetico; + }).ToList(); + break; + } + case 3: + { + list = ( + from x in this.LancamentosFiltrados + where x.get_Controle().get_Plano() != null + group x by new { Id = x.get_Conta().get_Id(), Descricao = x.get_Conta().get_Descricao() }).Select((x) => { + Sintetico sintetico = new Sintetico(); + sintetico.set_Agrupamento(x.Key.Descricao); + sintetico.set_Valor(new decimal?(x.Sum((Lancamento s) => { + if (s.get_Sinal() == null) + { + return s.get_Valor(); + } + return -s.get_Valor(); + }))); + sintetico.set_ValorPago(new decimal?(x.Sum((Lancamento s) => { + decimal? valorPago; + decimal? nullable; + if (s.get_Sinal() == null) + { + valorPago = s.get_ValorPago(); + return valorPago.GetValueOrDefault(); + } + decimal? valorPago1 = s.get_ValorPago(); + if (valorPago1.HasValue) + { + nullable = new decimal?(-valorPago1.GetValueOrDefault()); + } + else + { + valorPago = null; + nullable = valorPago; + } + valorPago = nullable; + return valorPago.GetValueOrDefault(); + }))); + return sintetico; + }).ToList(); + break; + } + case 4: + { + list = this.LancamentosFiltrados.Where((Lancamento x) => { + if (x.get_Controle().get_Plano() == null) + { + return false; + } + return x.get_Controle().get_Plano().get_Plano() != null; + }).GroupBy((Lancamento x) => new { Id = x.get_Controle().get_Plano().get_Plano().get_Id(), Descricao = x.get_Controle().get_Plano().get_Plano().get_Descricao() }).Select((x) => { + Sintetico sintetico = new Sintetico(); + sintetico.set_Agrupamento(x.Key.Descricao); + sintetico.set_Valor(new decimal?(x.Sum((Lancamento s) => { + if (s.get_Sinal() == null) + { + return s.get_Valor(); + } + return -s.get_Valor(); + }))); + sintetico.set_ValorPago(new decimal?(x.Sum((Lancamento s) => { + decimal? valorPago; + decimal? nullable; + if (s.get_Sinal() == null) + { + valorPago = s.get_ValorPago(); + return valorPago.GetValueOrDefault(); + } + decimal? valorPago1 = s.get_ValorPago(); + if (valorPago1.HasValue) + { + nullable = new decimal?(-valorPago1.GetValueOrDefault()); + } + else + { + valorPago = null; + nullable = valorPago; + } + valorPago = nullable; + return valorPago.GetValueOrDefault(); + }))); + return sintetico; + }).ToList(); + break; + } + default: + { + list = ( + from x in this.LancamentosFiltrados + where x.get_Controle().get_Plano() != null + group x by new { Id = x.get_Controle().get_Plano().get_Id(), Descricao = x.get_Controle().get_Plano().get_Descricao() }).Select((x) => { + Sintetico sintetico = new Sintetico(); + sintetico.set_Agrupamento(x.Key.Descricao); + sintetico.set_Valor(new decimal?(x.Sum((Lancamento s) => { + if (s.get_Sinal() == null) + { + return s.get_Valor(); + } + return -s.get_Valor(); + }))); + sintetico.set_ValorPago(new decimal?(x.Sum((Lancamento s) => { + decimal? valorPago; + decimal? nullable; + if (s.get_Sinal() == null) + { + valorPago = s.get_ValorPago(); + return valorPago.GetValueOrDefault(); + } + decimal? valorPago1 = s.get_ValorPago(); + if (valorPago1.HasValue) + { + nullable = new decimal?(-valorPago1.GetValueOrDefault()); + } + else + { + valorPago = null; + nullable = valorPago; + } + valorPago = nullable; + return valorPago.GetValueOrDefault(); + }))); + return sintetico; + }).ToList(); + break; + } + } + if (list.Count == 0) + { + return; + } + (new SinteticoView(list, "RELATORIO FINANCEIRO", this.Inicio, this.Fim)).Show(); + } + + public void Totalizar() + { + if (this.LancamentosFiltrados == null) + { + this.Totalizacao = null; + return; + } + List list = ( + from x in this.LancamentosFiltrados + where x.get_Conta() != null + group x by new { Id = x.get_Conta().get_Id(), Descricao = x.get_Conta().get_Descricao() }).Select((x) => { + Gestor.Model.Domain.Financeiro.SinteticoFinanceiro sinteticoFinanceiro = new Gestor.Model.Domain.Financeiro.SinteticoFinanceiro(); + BancosContas bancosConta = new BancosContas(); + bancosConta.set_Id(x.Key.Id); + bancosConta.set_Descricao(x.Key.Descricao); + sinteticoFinanceiro.set_Conta(bancosConta); + sinteticoFinanceiro.set_Filtrados(x.Count()); + sinteticoFinanceiro.set_Credito(x.Sum((Lancamento s) => { + if (s.get_Sinal() != null) + { + return decimal.Zero; + } + return s.get_Valor(); + })); + sinteticoFinanceiro.set_Debito(x.Sum((Lancamento s) => { + if (s.get_Sinal() == null) + { + return decimal.Zero; + } + return -s.get_Valor(); + })); + sinteticoFinanceiro.set_Liquido(x.Sum((Lancamento s) => { + if (s.get_Sinal() == null) + { + return s.get_Valor(); + } + return -s.get_Valor(); + })); + sinteticoFinanceiro.set_LiquidoPago(x.Sum((Lancamento s) => { + if (s.get_Sinal() == null) + { + return s.get_ValorPago(); + } + decimal? valorPago = s.get_ValorPago(); + if (!valorPago.HasValue) + { + return null; + } + return new decimal?(-valorPago.GetValueOrDefault()); + }).GetValueOrDefault()); + sinteticoFinanceiro.set_Selecionados(x.Count((Lancamento s) => s.get_Selecionado())); + sinteticoFinanceiro.set_LiquidoSelecionados(( + from s in x + where s.get_Selecionado() + select s).Sum((Lancamento s) => { + decimal? valorPago; + decimal? nullable; + if (s.get_Sinal() == null) + { + valorPago = s.get_ValorPago(); + return valorPago.GetValueOrDefault(); + } + decimal? valorPago1 = s.get_ValorPago(); + if (valorPago1.HasValue) + { + nullable = new decimal?(-valorPago1.GetValueOrDefault()); + } + else + { + valorPago = null; + nullable = valorPago; + } + valorPago = nullable; + return valorPago.GetValueOrDefault(); + })); + return sinteticoFinanceiro; + }).ToList(); + if (list.Count > 1) + { + List sinteticoFinanceiros = list; + Gestor.Model.Domain.Financeiro.SinteticoFinanceiro sinteticoFinanceiro1 = new Gestor.Model.Domain.Financeiro.SinteticoFinanceiro(); + BancosContas bancosConta1 = new BancosContas(); + bancosConta1.set_Id((long)0); + bancosConta1.set_Descricao("TOTAL"); + sinteticoFinanceiro1.set_Conta(bancosConta1); + sinteticoFinanceiro1.set_Filtrados(list.Sum((Gestor.Model.Domain.Financeiro.SinteticoFinanceiro x) => x.get_Filtrados())); + sinteticoFinanceiro1.set_Credito(list.Sum((Gestor.Model.Domain.Financeiro.SinteticoFinanceiro x) => x.get_Credito())); + sinteticoFinanceiro1.set_Debito(list.Sum((Gestor.Model.Domain.Financeiro.SinteticoFinanceiro x) => x.get_Debito())); + sinteticoFinanceiro1.set_Liquido(list.Sum((Gestor.Model.Domain.Financeiro.SinteticoFinanceiro x) => x.get_Liquido())); + sinteticoFinanceiro1.set_LiquidoPago(list.Sum((Gestor.Model.Domain.Financeiro.SinteticoFinanceiro x) => x.get_LiquidoPago())); + sinteticoFinanceiro1.set_Selecionados(list.Sum((Gestor.Model.Domain.Financeiro.SinteticoFinanceiro x) => x.get_Selecionados())); + sinteticoFinanceiro1.set_LiquidoSelecionados(list.Sum((Gestor.Model.Domain.Financeiro.SinteticoFinanceiro x) => x.get_LiquidoSelecionados())); + sinteticoFinanceiros.Add(sinteticoFinanceiro1); + } + this.Totalizacao = new ObservableCollection(list); + } + + private async Task>> Validar(Transferencia transferencia) + { + List> keyValuePairs; + DateTime? dataFinal; + DateTime data; + bool origem; + bool destino; + bool flag; + bool flag1; + bool flag2; + bool hasValue; + List saldos1; + Saldo saldo; + List> keyValuePairs1 = Gestor.Model.Helper.ValidationHelper.AddValue(); + BancosContasServico bancosContasServico = new BancosContasServico(); + Transferencia transferencium = transferencia; + if (transferencium != null) + { + origem = transferencium.get_Origem(); + } + else + { + origem = false; + } + if (origem) + { + Transferencia transferencium1 = transferencia; + if (transferencium1 != null) + { + destino = transferencium1.get_Destino(); + } + else + { + destino = false; + } + if (destino) + { + List nums = new List() + { + transferencia.get_Origem().get_Id(), + transferencia.get_Destino().get_Id() + }; + saldos1 = await bancosContasServico.BuscarSaldoAberto(nums); + saldo = saldos1.FirstOrDefault((Saldo s) => s.get_Conta().get_Id() == transferencia.get_Origem().get_Id()); + if (saldo == null) + { + List saldos2 = await bancosContasServico.BuscarSaldos(transferencia.get_Origem().get_Id()); + List saldos3 = saldos2; + Saldo saldo1 = saldos3.Find((Saldo x) => { + DateTime? dataInicio = x.get_DataInicio(); + List saldos = saldos3; + Func u003cu003e9_3863 = FinanceiroViewModel.u003cu003ec.u003cu003e9__386_3; + if (u003cu003e9_3863 == null) + { + u003cu003e9_3863 = (Saldo r) => r.get_DataInicio(); + FinanceiroViewModel.u003cu003ec.u003cu003e9__386_3 = u003cu003e9_3863; + } + DateTime? nullable = saldos.Max(u003cu003e9_3863); + if (dataInicio.HasValue != nullable.HasValue) + { + return false; + } + if (!dataInicio.HasValue) + { + return true; + } + return dataInicio.GetValueOrDefault() == nullable.GetValueOrDefault(); + }); + dataFinal = saldo1.get_DataInicio(); + data = transferencia.get_Data(); + flag2 = (dataFinal.HasValue ? dataFinal.GetValueOrDefault() <= data : false); + if (!flag2) + { + hasValue = false; + } + else + { + dataFinal = saldo1.get_DataFinal(); + hasValue = dataFinal.HasValue; + } + bool flag3 = hasValue; + if (flag3) + { + flag3 = await base.ShowMessage("O ÚLTIMO SALDO NÃO ESTÁ ABERTO. DESEJA ABRÍ-LO AGORA E CONTINUAR?", "SIM", "NÃO", false); + } + if (flag3) + { + dataFinal = null; + saldo1.set_DataFinal(dataFinal); + saldo1.set_ValorFinal(null); + saldo = await bancosContasServico.Save(saldo1); + } + saldo1 = null; + } + if (saldo != null) + { + dataFinal = saldo.get_DataInicio(); + data = transferencia.get_Data(); + flag1 = (dataFinal.HasValue ? dataFinal.GetValueOrDefault() > data : false); + if (!flag1) + { + goto Label0; + } + } + Gestor.Model.Helper.ValidationHelper.AddValue(keyValuePairs1, "SALDO", string.Concat("NÃO É POSSÍVEL REALIZAR A BAIXA DO LANÇAMENTO POIS NÃO HÁ SALDO ABERTO NO PERÍODO PARA A CONTA ", transferencia.get_Origem().get_Descricao(), "."), true); + Label0: + saldo = saldos1.FirstOrDefault((Saldo s) => s.get_Conta().get_Id() == transferencia.get_Destino().get_Id()); + if (saldo != null) + { + dataFinal = saldo.get_DataInicio(); + data = transferencia.get_Data(); + flag = (dataFinal.HasValue ? dataFinal.GetValueOrDefault() > data : false); + if (!flag) + { + goto Label1; + } + } + Gestor.Model.Helper.ValidationHelper.AddValue(keyValuePairs1, "SALDO", string.Concat("NÃO É POSSÍVEL REALIZAR A BAIXA DO LANÇAMENTO POIS NÃO HÁ SALDO ABERTO NO PERÍODO PARA A CONTA ", transferencia.get_Destino().get_Descricao(), "."), true); + Label1: + keyValuePairs = keyValuePairs1; + } + else + { + Gestor.Model.Helper.ValidationHelper.AddValue(keyValuePairs1, "DESTINO", "NÃO É POSSÍVEL FAZER UMA TRANSFERÊNCIA SEM BANDO DESTINO", true); + keyValuePairs = keyValuePairs1; + } + } + else + { + Gestor.Model.Helper.ValidationHelper.AddValue(keyValuePairs1, "ORIGEM", "NÃO É POSSÍVEL FAZER UMA TRANSFERÊNCIA SEM BANDO ORIGEM", true); + keyValuePairs = keyValuePairs1; + } + keyValuePairs1 = null; + bancosContasServico = null; + saldos1 = null; + saldo = null; + return keyValuePairs; + } + + private async Task>> Validar() + { + List> keyValuePairs; + DateTime? baixa; + DateTime? dataFinal; + bool flag; + bool flag1; + bool flag2; + bool hasValue; + List> keyValuePairs1 = Gestor.Model.Helper.ValidationHelper.AddValue(); + BancosContasServico bancosContasServico = new BancosContasServico(); + BancosContasServico bancosContasServico1 = bancosContasServico; + List contas = this.Contas; + List saldos1 = await bancosContasServico1.BuscarSaldoAberto(( + from x in contas + select x.get_Id()).ToList()); + Saldo saldo = saldos1.FirstOrDefault((Saldo s) => { + long? nullable; + long? nullable1; + long id = s.get_Conta().get_Id(); + Lancamento selectedLancamento = this.SelectedLancamento; + if (selectedLancamento != null) + { + BancosContas conta = selectedLancamento.get_Conta(); + if (conta != null) + { + nullable1 = new long?(conta.get_Id()); + } + else + { + nullable = null; + nullable1 = nullable; + } + } + else + { + nullable = null; + nullable1 = nullable; + } + long? nullable2 = nullable1; + return id == nullable2.GetValueOrDefault() & nullable2.HasValue; + }); + if (saldo == null) + { + Lancamento lancamento = this.SelectedLancamento; + if (lancamento != null) + { + flag1 = lancamento.get_Conta(); + } + else + { + flag1 = false; + } + if (flag1) + { + List saldos2 = await bancosContasServico.BuscarSaldos(this.SelectedLancamento.get_Conta().get_Id()); + List saldos3 = saldos2; + Saldo saldo1 = saldos3.Find((Saldo x) => { + DateTime? dataInicio = x.get_DataInicio(); + List saldos = saldos3; + Func u003cu003e9_3893 = FinanceiroViewModel.u003cu003ec.u003cu003e9__389_3; + if (u003cu003e9_3893 == null) + { + u003cu003e9_3893 = (Saldo r) => r.get_DataInicio(); + FinanceiroViewModel.u003cu003ec.u003cu003e9__389_3 = u003cu003e9_3893; + } + DateTime? nullable = saldos.Max(u003cu003e9_3893); + if (dataInicio.HasValue != nullable.HasValue) + { + return false; + } + if (!dataInicio.HasValue) + { + return true; + } + return dataInicio.GetValueOrDefault() == nullable.GetValueOrDefault(); + }); + baixa = saldo1.get_DataInicio(); + dataFinal = this.SelectedLancamento.get_Baixa(); + flag2 = (baixa.HasValue & dataFinal.HasValue ? baixa.GetValueOrDefault() <= dataFinal.GetValueOrDefault() : false); + if (!flag2) + { + hasValue = false; + } + else + { + dataFinal = saldo1.get_DataFinal(); + hasValue = dataFinal.HasValue; + } + bool flag3 = hasValue; + if (flag3) + { + flag3 = await base.ShowMessage("O ÚLTIMO SALDO NÃO ESTÁ ABERTO. DESEJA ABRÍ-LO AGORA E CONTINUAR?", "SIM", "NÃO", false); + } + if (flag3) + { + dataFinal = null; + saldo1.set_DataFinal(dataFinal); + saldo1.set_ValorFinal(null); + saldo = await bancosContasServico.Save(saldo1); + } + saldo1 = null; + } + } + if (saldo != null) + { + dataFinal = saldo.get_DataInicio(); + baixa = this.SelectedLancamento.get_Baixa(); + flag = (dataFinal.HasValue & baixa.HasValue ? dataFinal.GetValueOrDefault() > baixa.GetValueOrDefault() : false); + if (!flag) + { + keyValuePairs = new List>(); + keyValuePairs1 = null; + bancosContasServico = null; + saldo = null; + return keyValuePairs; + } + } + Gestor.Model.Helper.ValidationHelper.AddValue(keyValuePairs1, "SALDO", "NÃO É POSSÍVEL REALIZAR A BAIXA DO LANÇAMENTO POIS NÃO HÁ SALDO ABERTO NO PERÍODO.", true); + keyValuePairs = keyValuePairs1; + keyValuePairs1 = null; + bancosContasServico = null; + saldo = null; + return keyValuePairs; + } + + public List> ValidateIncluir() + { + // + // Current member / type: System.Collections.Generic.List`1> Gestor.Application.ViewModels.Financeiro.FinanceiroViewModel::ValidateIncluir() + // File path: C:\AggerSeguros\Gestor.Application.exe + // + // Product version: 0.0.0.0 + // Exception in: System.Collections.Generic.List> ValidateIncluir() + // + // Object reference not set to an instance of an object. + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.FindLowestCommonAncestor(ICollection`1 typeNodes) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 515 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.MergeWithLowestCommonAncestor() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 459 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.ProcessSingleConstraints() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 378 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.InferTypes() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 331 + // at Telerik.JustDecompiler.Decompiler.ExpressionDecompilerStep.Process(DecompilationContext theContext, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\ExpressionDecompilerStep.cs:line 104 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61 + // at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 133 + // + // mailto: JustDecompilePublicFeedback@telerik.com + + } + + private bool VerificaDataInvertida(OfxDocument lancamentos) + { + List strs = new List() + { + "0104" + }; + if (lancamentos.get_StatementStart() <= lancamentos.get_StatementEnd()) + { + return false; + } + return strs.Any((string banco) => banco == lancamentos.get_Account().get_BankId()); + } + + private bool VerificaFiltroErrado(OfxDocument lancamentos) + { + List strs = new List() + { + "0237", + "756" + }; + if (lancamentos.get_StatementStart() != lancamentos.get_StatementEnd()) + { + return false; + } + return strs.Any((string idbanco) => idbanco == lancamentos.get_Account().get_BankId()); + } + + private async Task VerificaSaldo(long contaId, bool reabrirSaldo) + { + BancosContasServico bancosContasServico = new BancosContasServico(); + List contas = this.Contas; + List saldos = await bancosContasServico.BuscarSaldoAberto(( + from x in contas + select x.get_Id()).ToList()); + Saldo saldo = saldos.FirstOrDefault((Saldo s) => s.get_Conta().get_Id() == contaId); + if (saldo == null & reabrirSaldo) + { + await base.ShowMessage("NÃO FOI ENCONTRADO UM SALDO ABERTO PARA FAZER A EXCLUSÃO.", "OK", "", false); + } + Saldo saldo1 = saldo; + saldo = null; + return saldo1; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Financeiro/FornecedorViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Financeiro/FornecedorViewModel.cs new file mode 100644 index 0000000..6d1dc77 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Financeiro/FornecedorViewModel.cs @@ -0,0 +1,780 @@ +using Assinador.Infrastructure.Helpers; +using ClosedXML.Excel; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Financeiro; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace Gestor.Application.ViewModels.Financeiro +{ + public class FornecedorViewModel : BaseFinanceiroViewModel + { + private readonly FornecedorServico _servico; + + private List _planos; + + private ObservableCollection _planosFiltrados; + + private List _contas; + + private ObservableCollection _contasFiltradas; + + private List _centros; + + private ObservableCollection _centrosFiltrados; + + private ObservableCollection _fornecedorFiltrados = new ObservableCollection(); + + private bool _isExpanded; + + private Gestor.Model.Domain.Financeiro.Fornecedor _selectedFornecedor; + + private string _anotacoes; + + private long _ultimoId; + + public Gestor.Model.Domain.Financeiro.Fornecedor CancelProduto; + + public string Anotacoes + { + get + { + return this._anotacoes; + } + set + { + this._anotacoes = value; + base.OnPropertyChanged("Anotacoes"); + } + } + + public List Centros + { + get + { + return this._centros; + } + set + { + this._centros = value; + base.OnPropertyChanged("Centros"); + } + } + + public ObservableCollection CentrosFiltrados + { + get + { + return this._centrosFiltrados; + } + set + { + this._centrosFiltrados = value; + base.OnPropertyChanged("CentrosFiltrados"); + } + } + + public List Contas + { + get + { + return this._contas; + } + set + { + this._contas = value; + base.OnPropertyChanged("Contas"); + } + } + + public ObservableCollection ContasFiltradas + { + get + { + return this._contasFiltradas; + } + set + { + this._contasFiltradas = value; + base.OnPropertyChanged("ContasFiltradas"); + } + } + + public List Fornecedor + { + get; + set; + } + + public ObservableCollection FornecedorFiltrados + { + get + { + return this._fornecedorFiltrados; + } + set + { + this._fornecedorFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("FornecedorFiltrados"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public List Planos + { + get + { + return this._planos; + } + set + { + this._planos = value; + base.OnPropertyChanged("Planos"); + } + } + + public ObservableCollection PlanosFiltrados + { + get + { + return this._planosFiltrados; + } + set + { + this._planosFiltrados = value; + base.OnPropertyChanged("PlanosFiltrados"); + } + } + + public Gestor.Model.Domain.Financeiro.Fornecedor SelectedFornecedor + { + get + { + return this._selectedFornecedor; + } + set + { + long? nullable; + this._selectedFornecedor = value; + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + this.Anotacoes = string.Empty; + this._ultimoId = (value == null || value.get_Id() <= (long)0 ? this._ultimoId : value.get_Id()); + base.OnPropertyChanged("SelectedFornecedor"); + } + } + + public FornecedorViewModel() + { + this._servico = new FornecedorServico(); + base.EnableMenu = true; + this.BuscaIncial(); + } + + private async void BuscaIncial() + { + base.Loading(true); + await base.PermissaoTela(24); + this.Planos = await (new PlanoServico()).BuscarPlanos(); + FornecedorViewModel observableCollection = this; + List planos = this.Planos; + IEnumerable ativo = + from x in planos + where x.get_Ativo() + select x; + observableCollection.PlanosFiltrados = new ObservableCollection( + from x in ativo + orderby x.get_Descricao() + select x); + this.Contas = await (new BancosContasServico()).BuscarBancos(); + FornecedorViewModel fornecedorViewModel = this; + List contas = this.Contas; + IEnumerable bancosContas = + from x in contas + where x.get_Ativo() + select x; + fornecedorViewModel.ContasFiltradas = new ObservableCollection( + from x in bancosContas + orderby x.get_Descricao() + select x); + this.Centros = await (new CentroServico()).BuscarCentros(); + FornecedorViewModel observableCollection1 = this; + List centros = this.Centros; + IEnumerable ativo1 = + from x in centros + where x.get_Ativo() + select x; + observableCollection1.CentrosFiltrados = new ObservableCollection( + from x in ativo1 + orderby x.get_Descricao() + select x); + await this.SelecionaFornecedor(); + this.SelectedFornecedor = this.FornecedorFiltrados.FirstOrDefault(); + base.Loading(false); + } + + public async void CancelarAlteracao() + { + base.Loading(true); + base.Alterar(false); + if (this.SelectedFornecedor.get_Id() > (long)0) + { + await this.SelecionaFornecedor(); + } + this.SelectedFornecedor = this.FornecedorFiltrados.FirstOrDefault((Gestor.Model.Domain.Financeiro.Fornecedor x) => x.get_Id() == this._ultimoId); + base.Loading(false); + } + + public void Copiar(Cliente cliente) + { + TipoTelefone? nullable; + string str; + string str1; + string str2; + string str3; + string str4; + string str5; + string str6; + TipoTelefone? tipo; + string str7; + string str8; + TipoTelefone? tipo1; + string str9; + string str10; + string str11; + if (this.SelectedFornecedor == null) + { + this.Incluir(); + } + this.SelectedFornecedor.set_Nome(cliente.get_Nome()); + this.SelectedFornecedor.set_Documento(cliente.get_Documento()); + Gestor.Model.Domain.Financeiro.Fornecedor selectedFornecedor = this.SelectedFornecedor; + if (cliente.get_Enderecos() == null || !cliente.get_Enderecos().Any()) + { + str = null; + } + else + { + ClienteEndereco clienteEndereco = cliente.get_Enderecos().First(); + if (clienteEndereco != null) + { + string cep = clienteEndereco.get_Cep(); + if (cep != null) + { + str = cep.Trim(); + } + else + { + str = null; + } + } + else + { + str = null; + } + } + selectedFornecedor.set_Cep(str); + Gestor.Model.Domain.Financeiro.Fornecedor fornecedor = this.SelectedFornecedor; + if (cliente.get_Enderecos() == null || !cliente.get_Enderecos().Any()) + { + str1 = null; + } + else + { + ClienteEndereco clienteEndereco1 = cliente.get_Enderecos().First(); + if (clienteEndereco1 != null) + { + string endereco = clienteEndereco1.get_Endereco(); + if (endereco != null) + { + str1 = endereco.Trim(); + } + else + { + str1 = null; + } + } + else + { + str1 = null; + } + } + fornecedor.set_Endereco(str1); + Gestor.Model.Domain.Financeiro.Fornecedor selectedFornecedor1 = this.SelectedFornecedor; + if (cliente.get_Enderecos() == null || !cliente.get_Enderecos().Any()) + { + str2 = null; + } + else + { + ClienteEndereco clienteEndereco2 = cliente.get_Enderecos().First(); + if (clienteEndereco2 != null) + { + string numero = clienteEndereco2.get_Numero(); + if (numero != null) + { + str2 = numero.Trim(); + } + else + { + str2 = null; + } + } + else + { + str2 = null; + } + } + selectedFornecedor1.set_Numero(str2); + Gestor.Model.Domain.Financeiro.Fornecedor fornecedor1 = this.SelectedFornecedor; + if (cliente.get_Enderecos() == null || !cliente.get_Enderecos().Any()) + { + str3 = null; + } + else + { + ClienteEndereco clienteEndereco3 = cliente.get_Enderecos().First(); + if (clienteEndereco3 != null) + { + string complemento = clienteEndereco3.get_Complemento(); + if (complemento != null) + { + str3 = complemento.Trim(); + } + else + { + str3 = null; + } + } + else + { + str3 = null; + } + } + fornecedor1.set_Complemento(str3); + Gestor.Model.Domain.Financeiro.Fornecedor selectedFornecedor2 = this.SelectedFornecedor; + if (cliente.get_Enderecos() == null || !cliente.get_Enderecos().Any()) + { + str4 = null; + } + else + { + ClienteEndereco clienteEndereco4 = cliente.get_Enderecos().First(); + if (clienteEndereco4 != null) + { + string bairro = clienteEndereco4.get_Bairro(); + if (bairro != null) + { + str4 = bairro.Trim(); + } + else + { + str4 = null; + } + } + else + { + str4 = null; + } + } + selectedFornecedor2.set_Bairro(str4); + Gestor.Model.Domain.Financeiro.Fornecedor fornecedor2 = this.SelectedFornecedor; + if (cliente.get_Enderecos() == null || !cliente.get_Enderecos().Any()) + { + str5 = null; + } + else + { + ClienteEndereco clienteEndereco5 = cliente.get_Enderecos().First(); + if (clienteEndereco5 != null) + { + string cidade = clienteEndereco5.get_Cidade(); + if (cidade != null) + { + str5 = cidade.Trim(); + } + else + { + str5 = null; + } + } + else + { + str5 = null; + } + } + fornecedor2.set_Cidade(str5); + Gestor.Model.Domain.Financeiro.Fornecedor selectedFornecedor3 = this.SelectedFornecedor; + if (cliente.get_Enderecos() == null || !cliente.get_Enderecos().Any()) + { + str6 = null; + } + else + { + ClienteEndereco clienteEndereco6 = cliente.get_Enderecos().First(); + if (clienteEndereco6 != null) + { + string estado = clienteEndereco6.get_Estado(); + if (estado != null) + { + str6 = estado.Trim(); + } + else + { + str6 = null; + } + } + else + { + str6 = null; + } + } + selectedFornecedor3.set_Estado(str6); + Gestor.Model.Domain.Financeiro.Fornecedor fornecedor3 = this.SelectedFornecedor; + if (cliente.get_Telefones() == null || !cliente.get_Telefones().Any()) + { + nullable = null; + tipo = nullable; + } + else + { + tipo = cliente.get_Telefones().First().get_Tipo(); + } + fornecedor3.set_TipoTelefone1(tipo); + Gestor.Model.Domain.Financeiro.Fornecedor selectedFornecedor4 = this.SelectedFornecedor; + if (cliente.get_Telefones() == null || !cliente.get_Telefones().Any()) + { + str7 = null; + } + else + { + string prefixo = cliente.get_Telefones().First().get_Prefixo(); + if (prefixo != null) + { + str7 = prefixo.Trim(); + } + else + { + str7 = null; + } + } + selectedFornecedor4.set_Prefixo1(str7); + Gestor.Model.Domain.Financeiro.Fornecedor fornecedor4 = this.SelectedFornecedor; + if (cliente.get_Telefones() == null || !cliente.get_Telefones().Any()) + { + str8 = null; + } + else + { + string numero1 = cliente.get_Telefones().First().get_Numero(); + if (numero1 != null) + { + str8 = numero1.Trim(); + } + else + { + str8 = null; + } + } + fornecedor4.set_Telefone1(str8); + Gestor.Model.Domain.Financeiro.Fornecedor selectedFornecedor5 = this.SelectedFornecedor; + if (cliente.get_Telefones() == null || !cliente.get_Telefones().Any() || cliente.get_Telefones().Count <= 2) + { + nullable = null; + tipo1 = nullable; + } + else + { + tipo1 = cliente.get_Telefones()[1].get_Tipo(); + } + selectedFornecedor5.set_TipoTelefone2(tipo1); + Gestor.Model.Domain.Financeiro.Fornecedor fornecedor5 = this.SelectedFornecedor; + if (cliente.get_Telefones() == null || cliente.get_Telefones().Count <= 2) + { + str9 = null; + } + else + { + string prefixo1 = cliente.get_Telefones()[1].get_Prefixo(); + if (prefixo1 != null) + { + str9 = prefixo1.Trim(); + } + else + { + str9 = null; + } + } + fornecedor5.set_Prefixo2(str9); + Gestor.Model.Domain.Financeiro.Fornecedor selectedFornecedor6 = this.SelectedFornecedor; + if (cliente.get_Telefones() == null || cliente.get_Telefones().Count <= 2) + { + str10 = null; + } + else + { + string numero2 = cliente.get_Telefones()[1].get_Numero(); + if (numero2 != null) + { + str10 = numero2.Trim(); + } + else + { + str10 = null; + } + } + selectedFornecedor6.set_Telefone2(str10); + Gestor.Model.Domain.Financeiro.Fornecedor fornecedor6 = this.SelectedFornecedor; + if (cliente.get_Emails() == null || !cliente.get_Emails().Any() || cliente.get_Emails().Count <= 0) + { + str11 = null; + } + else + { + string email = cliente.get_Emails().First().get_Email(); + if (email != null) + { + str11 = email.Trim(); + } + else + { + str11 = null; + } + } + fornecedor6.set_Email(str11); + base.OnPropertyChanged("SelectedFornecedor"); + } + + public async Task Delete() + { + if (this.SelectedFornecedor != null && this.SelectedFornecedor.get_Id() != 0) + { + if (await base.ShowMessage(string.Concat("DESEJA REALMENTE EXCLUIR O FORNECEDOR ", this.SelectedFornecedor.get_Nome(), "?"), "SIM", "NÃO", false)) + { + base.Loading(true); + if (await (new FinanceiroServico()).TemLancamentosPorFornecedor(this.SelectedFornecedor.get_Id())) + { + await base.ShowMessage("IMPOSSÍVEL REAIZAR A EXCLUSÃO POIS EXISTEM LANCAMENTOS PARA ESSE FORNECEDOR. PROCESSO INTERROMPIDO", "OK", "", false); + base.Loading(false); + } + else if (await this._servico.Delete(this.SelectedFornecedor)) + { + await this.SelecionaFornecedor(); + this.SelectedFornecedor = this.FornecedorFiltrados.FirstOrDefault(); + base.ToggleSnackBar("FORNECEDOR EXCLUÍDO COM SUCESSO", true); + base.Loading(false); + } + else + { + base.Loading(false); + } + } + } + } + + public async void Excel() + { + XLWorkbook xLWorkbook = new XLWorkbook(); + string str = "RELAÓRIO DE FORNECEDOR"; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, this.FornecedorFiltrados.ToList(), null); + string tempPath = ""; + string str1 = ""; + List configuracoes = Recursos.Configuracoes; + if (!configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 41)) + { + tempPath = Path.GetTempPath(); + str1 = string.Format("{0}{1}.xlsx", tempPath, Guid.NewGuid()); + } + else + { + using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog()) + { + if (DialogResult.OK == folderBrowserDialog.ShowDialog()) + { + tempPath = string.Concat(folderBrowserDialog.SelectedPath, "\\"); + Directory.CreateDirectory(tempPath); + } + else + { + str = null; + return; + } + } + string[] strArrays = new string[] { tempPath, str, " ", null, null }; + DateTime date = Functions.GetNetworkTime().Date; + strArrays[3] = date.ToShortDateString().Replace("/", ""); + strArrays[4] = ".xlsx"; + str1 = string.Concat(strArrays); + } + xLWorkbook.SaveAs(str1); + Process.Start(str1); + str = null; + } + + internal async Task> Filtrar(string value) + { + List fornecedors = await Task.Run>(() => this.FiltrarFornecedor(value)); + return fornecedors; + } + + public List FiltrarFornecedor(string filter) + { + this.FornecedorFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Fornecedor) : new ObservableCollection(this.Fornecedor.Where((Gestor.Model.Domain.Financeiro.Fornecedor x) => { + if (Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Nome().Trim()).ToUpper().Contains(Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(filter)) || x.get_Documento() != null && Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Documento().Trim()).Contains(filter) || x.get_Telefone1() != null && Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Telefone1().Trim()).Contains(filter) || x.get_Telefone2() != null && Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Telefone2().Trim()).Contains(filter)) + { + return true; + } + if (x.get_Email() == null) + { + return false; + } + return Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Email().Trim()).Contains(filter); + }).OrderByDescending((Gestor.Model.Domain.Financeiro.Fornecedor x) => x.get_Nome()))); + if (this.FornecedorFiltrados.Count == 1) + { + this.SelectedFornecedor = this.FornecedorFiltrados.First(); + } + return this.FornecedorFiltrados.ToList(); + } + + public async void Imprimir() + { + await base.ImprimirFornecedor(this.FornecedorFiltrados.ToList()); + } + + public void Incluir() + { + long id; + Gestor.Model.Domain.Financeiro.Fornecedor selectedFornecedor = this.SelectedFornecedor; + if (selectedFornecedor != null) + { + id = selectedFornecedor.get_Id(); + } + else + { + id = (long)0; + } + this._ultimoId = id; + Gestor.Model.Domain.Financeiro.Fornecedor fornecedor = new Gestor.Model.Domain.Financeiro.Fornecedor(); + fornecedor.set_IdEmpresa((long)1); + fornecedor.set_Ativo(true); + this.SelectedFornecedor = fornecedor; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + List> keyValuePairs1 = this.SelectedFornecedor.Validate(); + List> keyValuePairs2 = keyValuePairs1; + keyValuePairs2.AddRange(await this.Validate()); + keyValuePairs2 = null; + if (keyValuePairs1.Count <= 0) + { + if (!this.SelectedFornecedor.get_TipoPagamento().HasValue) + { + this.SelectedFornecedor.set_TipoPagamento(new TipoPagamento?(12)); + } + if (!string.IsNullOrWhiteSpace(this.Anotacoes)) + { + Gestor.Model.Domain.Financeiro.Fornecedor selectedFornecedor = this.SelectedFornecedor; + object[] nome = new object[] { Recursos.Usuario.get_Nome(), Recursos.Usuario.get_Id(), Funcoes.GetNetworkTime(), Environment.NewLine, this.Anotacoes, Environment.NewLine, Environment.NewLine, this.SelectedFornecedor.get_Observacao() }; + selectedFornecedor.set_Observacao(string.Format("{0}, ID: {1}, {2:g}{3}{4}{5}{6}{7}", nome)); + } + Gestor.Model.Domain.Financeiro.Fornecedor fornecedor = await this._servico.Save(this.SelectedFornecedor); + if (this._servico.Sucesso) + { + await this.SelecionaFornecedor(); + this.SelectedFornecedor = this.FornecedorFiltrados.First((Gestor.Model.Domain.Financeiro.Fornecedor x) => x.get_Id() == fornecedor.get_Id()); + base.ToggleSnackBar("FORNECEDOR SALVO COM SUCESSO", true); + base.Alterar(false); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + keyValuePairs1 = null; + return keyValuePairs; + } + + private async Task SelecionaFornecedor() + { + this.Fornecedor = await this._servico.BuscarFornecedores(); + FornecedorViewModel observableCollection = this; + List fornecedor = this.Fornecedor; + observableCollection.FornecedorFiltrados = new ObservableCollection( + from x in fornecedor + orderby x.get_Nome() + select x); + } + + public async Task>> Validate() + { + List> keyValuePairs = Gestor.Model.Helper.ValidationHelper.AddValue(); + if (!string.IsNullOrWhiteSpace(this.SelectedFornecedor.get_Documento())) + { + List list = await this._servico.BuscarFornecedores(); + list = list.Where((Gestor.Model.Domain.Financeiro.Fornecedor x) => { + if (x.get_Id() == this.SelectedFornecedor.get_Id()) + { + return false; + } + return Gestor.Model.Helper.ValidationHelper.DocumentoFornecedor(x.get_Documento()) == Gestor.Model.Helper.ValidationHelper.DocumentoFornecedor(this.SelectedFornecedor.get_Documento()); + }).ToList(); + if (list.Count > 0) + { + List> keyValuePairs1 = keyValuePairs; + List fornecedors = list; + Gestor.Model.Helper.ValidationHelper.AddValue(keyValuePairs1, "DOCUMENTO", string.Concat("DOCUMENTO JÁ CADASTRADO PARA OUTROS FORNECEDORES ", string.Join(" | ", + from x in fornecedors + select x.get_Nome())), true); + } + } + List> keyValuePairs2 = keyValuePairs; + keyValuePairs = null; + return keyValuePairs2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Financeiro/InfoExtratoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Financeiro/InfoExtratoViewModel.cs new file mode 100644 index 0000000..d1a0c38 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Financeiro/InfoExtratoViewModel.cs @@ -0,0 +1,81 @@ +using Gestor.Application.Servicos.Financeiro; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Financeiro +{ + public class InfoExtratoViewModel : BaseFinanceiroViewModel + { + private readonly BancosContasServico _saldoServico; + + private Saldo _selectedSaldo; + + public bool _telaBancos + { + get; + set; + } + + public Saldo SelectedSaldo + { + get + { + return this._selectedSaldo; + } + set + { + if (value != null && !this._telaBancos) + { + value.set_DataFinal(null); + value.set_ValorFinal(null); + } + this._selectedSaldo = value; + base.OnPropertyChanged("SelectedSaldo"); + this.SelectedSaldo.Initialize(); + } + } + + public InfoExtratoViewModel(bool telaBancos) + { + this._telaBancos = telaBancos; + this._saldoServico = new BancosContasServico(); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + List> keyValuePairs1 = this.SelectedSaldo.Validate(); + if (keyValuePairs1.Count <= 0) + { + if (!this._telaBancos) + { + this.SelectedSaldo.set_DataFinal(null); + this.SelectedSaldo.set_ValorFinal(null); + } + this.SelectedSaldo = await this._saldoServico.Save(this.SelectedSaldo); + if (this._saldoServico.Sucesso) + { + base.Alterar(false); + base.ToggleSnackBar("SALDO SALVO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Financeiro/MenuFinanceiroViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Financeiro/MenuFinanceiroViewModel.cs new file mode 100644 index 0000000..9c1bdee --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Financeiro/MenuFinanceiroViewModel.cs @@ -0,0 +1,30 @@ +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Financeiro; +using System; + +namespace Gestor.Application.ViewModels.Financeiro +{ + public class MenuFinanceiroViewModel : BaseViewModel + { + private object _content; + + public Gestor.Application.Views.Financeiro.FinanceiroView FinanceiroView; + + public object Content + { + get + { + return this._content; + } + set + { + this._content = value; + base.OnPropertyChanged("Content"); + } + } + + public MenuFinanceiroViewModel() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Financeiro/PlanoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Financeiro/PlanoViewModel.cs new file mode 100644 index 0000000..e62f957 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Financeiro/PlanoViewModel.cs @@ -0,0 +1,147 @@ +using Gestor.Application.Servicos.Financeiro; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Financeiro +{ + public class PlanoViewModel : BaseFinanceiroViewModel + { + private readonly PlanoServico _planoServico; + + private Plano _selectedPlano; + + public Plano Cancel; + + public Plano SelectedPlano + { + get + { + return this._selectedPlano; + } + set + { + long? nullable; + this._selectedPlano = value; + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedPlano"); + } + } + + public PlanoViewModel(Plano plano) + { + this._planoServico = new PlanoServico(); + this.Seleciona(plano); + } + + public void Cancelar() + { + base.Loading(true); + if (this.SelectedPlano.get_Id() != 0) + { + base.Alterar(false); + base.Loading(false); + return; + } + this.SelectedPlano = new Plano(); + base.Alterar(false); + base.Loading(false); + } + + public void Incluir() + { + Plano plano = new Plano(); + plano.set_Ativo(true); + this.SelectedPlano = plano; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + List> keyValuePairs1 = this.SelectedPlano.Validate(); + List> keyValuePairs2 = keyValuePairs1; + keyValuePairs2.AddRange(await this.Validate()); + keyValuePairs2 = null; + if (keyValuePairs1.Count <= 0) + { + this.SelectedPlano = await this._planoServico.Save(this.SelectedPlano); + if (this._planoServico.Sucesso) + { + base.Alterar(false); + base.ToggleSnackBar("PLANO SALVO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + keyValuePairs1 = null; + return keyValuePairs; + } + + private async void Seleciona(Plano plano) + { + base.Loading(true); + await base.PermissaoTela(27); + if (plano != null) + { + this.SelectedPlano = plano; + } + else + { + Plano plano1 = new Plano(); + plano1.set_Descricao(""); + plano1.set_Ativo(true); + this.SelectedPlano = plano1; + } + base.Loading(false); + } + + public async Task>> Validate() + { + List> keyValuePairs = new List>(); + bool flag = true; + List planos = await (new BaseServico()).BuscarPlanoAsync(); + if (planos.Count > 0) + { + planos.ForEach((Plano x) => { + if (x.get_Id() == this.SelectedPlano.get_Id()) + { + return; + } + if (x.get_Descricao() == this.SelectedPlano.get_Descricao()) + { + flag = false; + } + }); + } + if (!flag) + { + keyValuePairs.Add(new KeyValuePair("Descricao", "UM PLANO COM ESSE NOME JÁ EXISTE.")); + } + List> keyValuePairs1 = keyValuePairs; + keyValuePairs = null; + return keyValuePairs1; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Financeiro/PlanosViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Financeiro/PlanosViewModel.cs new file mode 100644 index 0000000..e2251f3 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Financeiro/PlanosViewModel.cs @@ -0,0 +1,330 @@ +using Gestor.Application.Servicos.Financeiro; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Financeiro +{ + public class PlanosViewModel : BaseFinanceiroViewModel + { + private readonly PlanosServico _planosServico; + + private ObservableCollection _plano = new ObservableCollection(); + + private ObservableCollection _planosFiltrados = new ObservableCollection(); + + private bool _isExpanded; + + private Gestor.Model.Domain.Financeiro.Planos _selectedPlanos; + + private Gestor.Model.Domain.Financeiro.Plano _selectedPlano; + + private bool _ativo; + + private long _ultimoId; + + public bool Ativo + { + get + { + return this._ativo; + } + set + { + this._ativo = value; + base.OnPropertyChanged("Ativo"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public ObservableCollection Plano + { + get + { + return this._plano; + } + set + { + this._plano = value; + base.OnPropertyChanged("Plano"); + } + } + + public List Planos + { + get; + set; + } + + public ObservableCollection PlanosFiltrados + { + get + { + return this._planosFiltrados; + } + set + { + this._planosFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("PlanosFiltrados"); + } + } + + public Gestor.Model.Domain.Financeiro.Plano SelectedPlano + { + get + { + return this._selectedPlano; + } + set + { + this._selectedPlano = value; + base.OnPropertyChanged("SelectedPlano"); + } + } + + public Gestor.Model.Domain.Financeiro.Planos SelectedPlanos + { + get + { + return this._selectedPlanos; + } + set + { + bool plano; + Gestor.Model.Domain.Financeiro.Plano plano1; + bool id; + long? nullable; + this._selectedPlanos = value; + Gestor.Model.Domain.Financeiro.Planos plano2 = value; + if (plano2 != null) + { + plano = plano2.get_Plano(); + } + else + { + plano = false; + } + if (plano) + { + plano1 = this.Plano.FirstOrDefault((Gestor.Model.Domain.Financeiro.Plano x) => x.get_Id() == value.get_Plano().get_Id()); + } + else + { + plano1 = null; + } + this.SelectedPlano = plano1; + Gestor.Model.Domain.Financeiro.Planos plano3 = value; + if (plano3 != null) + { + id = plano3.get_Id() > (long)0; + } + else + { + id = false; + } + if (id) + { + this._ultimoId = value.get_Id(); + } + Gestor.Model.Domain.Financeiro.Planos plano4 = value; + if (plano4 != null) + { + nullable = new long?(plano4.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedPlanos"); + } + } + + public PlanosViewModel() + { + this._planosServico = new PlanosServico(); + base.EnableMenu = true; + this.Seleciona(); + } + + public async void CancelarAlteracao() + { + base.Loading(true); + base.Alterar(false); + if (this.SelectedPlanos.get_Id() > (long)0) + { + await this.SelecionaPlanos(); + } + await this.SelecionaPlanos(this.PlanosFiltrados.FirstOrDefault((Gestor.Model.Domain.Financeiro.Planos x) => x.get_Id() == this._ultimoId)); + base.Loading(false); + } + + public async Task> Filtrar(string value) + { + ObservableCollection observableCollection = await Task.Run>(() => this.FiltrarPlanos(value)); + return observableCollection; + } + + public ObservableCollection FiltrarPlanos(string filter) + { + this.PlanosFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Planos) : new ObservableCollection( + from x in this.Planos + where ValidationHelper.RemoveDiacritics(x.get_Descricao().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby this.Ativo descending, x.get_Descricao() + select x)); + return this.PlanosFiltrados; + } + + public void Incluir() + { + Gestor.Model.Domain.Financeiro.Planos plano = new Gestor.Model.Domain.Financeiro.Planos(); + plano.set_Plano(this.SelectedPlano); + this.SelectedPlanos = plano; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + this.SelectedPlanos.set_Plano(this.SelectedPlano); + List> keyValuePairs1 = this.SelectedPlanos.Validate(); + List> keyValuePairs2 = keyValuePairs1; + keyValuePairs2.AddRange(await this.Validate()); + keyValuePairs2 = null; + if (keyValuePairs1.Count <= 0) + { + this.SelectedPlanos.set_Plano(this.SelectedPlano); + this.SelectedPlanos = await this._planosServico.Save(this.SelectedPlanos); + if (this._planosServico.Sucesso) + { + await this.SelecionaPlanos(); + await this.SelecionaPlanos(this.PlanosFiltrados.First((Gestor.Model.Domain.Financeiro.Planos x) => x.get_Id() == this.SelectedPlanos.get_Id())); + base.Alterar(false); + base.ToggleSnackBar("SUBNÍVEL SALVO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + keyValuePairs1 = null; + return keyValuePairs; + } + + private async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(28); + await this.SelecionaPlanos(); + await this.SelecionaPlanos(this.PlanosFiltrados.FirstOrDefault()); + base.Loading(false); + } + + private async Task SelecionaPlanos() + { + List planos = await (new BaseServico()).BuscarPlanosAsync(); + PlanosViewModel list = this; + List planos1 = planos; + IOrderedEnumerable ativo = + from x in planos1 + orderby x.get_Ativo() descending + select x; + IOrderedEnumerable planos2 = ativo.ThenBy((Gestor.Model.Domain.Financeiro.Planos x) => { + Gestor.Model.Domain.Financeiro.Plano plano = x.get_Plano(); + if (plano != null) + { + return plano.get_Descricao(); + } + return null; + }); + list.Planos = planos2.ThenBy((Gestor.Model.Domain.Financeiro.Planos x) => x.get_Descricao()).ToList(); + this.PlanosFiltrados = new ObservableCollection(this.Planos); + } + + public async Task SelecionaPlanos(Gestor.Model.Domain.Financeiro.Planos planos) + { + if (planos != null) + { + base.Loading(true); + ObservableCollection observableCollection = await this._planosServico.BuscarPlanos(); + DomainBase.Copy(this.PlanosFiltrados.First((Gestor.Model.Domain.Financeiro.Planos x) => x.get_Id() == planos.get_Id()), observableCollection.First((Gestor.Model.Domain.Financeiro.Planos x) => x.get_Id() == planos.get_Id())); + if (this.Plano == null) + { + List planos1 = await (new BaseServico()).BuscarPlanoAsync(); + PlanosViewModel planosViewModel = this; + List planos2 = planos1; + IOrderedEnumerable ativo = + from x in planos2 + orderby x.get_Ativo() descending + select x; + planosViewModel.Plano = new ObservableCollection(ativo.ThenBy((Gestor.Model.Domain.Financeiro.Plano x) => x.get_Descricao()).ToList()); + } + this.SelectedPlanos = this.PlanosFiltrados.First((Gestor.Model.Domain.Financeiro.Planos x) => x.get_Id() == planos.get_Id()); + base.Loading(false); + } + else + { + base.Alterar(false); + base.EnableMenu = false; + base.EnableAlterar = false; + } + } + + public async Task>> Validate() + { + List> keyValuePairs = new List>(); + bool flag = true; + List planos = await (new BaseServico()).BuscarPlanosAsync(); + if (planos != null) + { + planos.ForEach((Gestor.Model.Domain.Financeiro.Planos x) => { + if (x.get_Id() == this.SelectedPlanos.get_Id()) + { + return; + } + if (x.get_Descricao() == this.SelectedPlanos.get_Descricao()) + { + flag = false; + } + }); + } + else + { + } + if (!flag) + { + keyValuePairs.Add(new KeyValuePair("Descricao", "UM SUBNÍVEL COM ESSE NOME JÁ EXISTE.")); + } + List> keyValuePairs1 = keyValuePairs; + keyValuePairs = null; + return keyValuePairs1; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Financeiro/Relatorios/FechamentoFinanceiroViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Financeiro/Relatorios/FechamentoFinanceiroViewModel.cs new file mode 100644 index 0000000..084c527 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Financeiro/Relatorios/FechamentoFinanceiroViewModel.cs @@ -0,0 +1,2746 @@ +using ClosedXML.Excel; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Financeiro; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Helpers; +using Gestor.Model.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Financeiro.Relatorios; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace Gestor.Application.ViewModels.Financeiro.Relatorios +{ + public class FechamentoFinanceiroViewModel : BaseViewModel + { + private readonly FinanceiroServico _servico; + + private bool _isExpanded; + + private bool _analitico; + + private List _plano; + + private List _planos; + + private List _centro; + + private List _conta; + + private DateTime? _inicio; + + private DateTime? _fim; + + private List _fechamento; + + private List _fechamentoAnalitico; + + private string _htmlContent; + + private bool _print; + + public bool Analitico + { + get + { + return this._analitico; + } + set + { + this._analitico = value; + base.OnPropertyChanged("Analitico"); + } + } + + public List Centro + { + get + { + return this._centro; + } + set + { + this._centro = value; + base.OnPropertyChanged("Centro"); + } + } + + public List Conta + { + get + { + return this._conta; + } + set + { + this._conta = value; + base.OnPropertyChanged("Conta"); + } + } + + public List Fechamento + { + get + { + return this._fechamento; + } + set + { + this._fechamento = value; + base.OnPropertyChanged("Fechamento"); + } + } + + public List FechamentoAnalitico + { + get + { + return this._fechamentoAnalitico; + } + set + { + this._fechamentoAnalitico = value; + base.OnPropertyChanged("FechamentoAnalitico"); + } + } + + public DateTime? Fim + { + get + { + return this._fim; + } + set + { + this._fim = value; + base.OnPropertyChanged("Fim"); + } + } + + public string HtmlContent + { + get + { + return this._htmlContent; + } + set + { + this._htmlContent = value; + this.IsPrintable = !string.IsNullOrWhiteSpace(this._htmlContent); + base.OnPropertyChanged("HtmlContent"); + } + } + + public DateTime? Inicio + { + get + { + return this._inicio; + } + set + { + this._inicio = value; + base.OnPropertyChanged("Inicio"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public bool IsPrintable + { + get + { + return this._print; + } + set + { + this._print = value; + base.OnPropertyChanged("IsPrintable"); + } + } + + public List Plano + { + get + { + return this._plano; + } + set + { + this._plano = value; + base.OnPropertyChanged("Plano"); + } + } + + public List Planos + { + get + { + return this._planos; + } + set + { + this._planos = value; + base.OnPropertyChanged("Planos"); + } + } + + public FechamentoFinanceiroViewModel() + { + DateTime date = Funcoes.GetNetworkTime().Date; + int year = date.Year; + date = Funcoes.GetNetworkTime().Date; + this._inicio = new DateTime?(new DateTime(year, date.Month, 1)); + this._fim = new DateTime?(Funcoes.GetNetworkTime()); + base(); + this._servico = new FinanceiroServico(); + this.LoadInicial(); + } + + public async Task GerarExcel() + { + string tempPath = ""; + string str = ""; + List configuracoes = Recursos.Configuracoes; + if (!configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 41)) + { + tempPath = Path.GetTempPath(); + str = string.Format("{0}{1}.xlsx", tempPath, Guid.NewGuid()); + } + else + { + using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog()) + { + if (DialogResult.OK == folderBrowserDialog.ShowDialog()) + { + tempPath = string.Concat(folderBrowserDialog.SelectedPath, "\\"); + Directory.CreateDirectory(tempPath); + } + else + { + str = null; + return; + } + } + DateTime date = Functions.GetNetworkTime().Date; + str = string.Concat(tempPath, "FECHAMENTO ", date.ToShortDateString().Replace("/", ""), ".xlsx"); + } + XLWorkbook xLWorkbook = new XLWorkbook(); + int num = 1; + if (this.Analitico) + { + if (this.FechamentoAnalitico == null || this.FechamentoAnalitico.Count == 0) + { + str = null; + return; + } + else + { + foreach (FechamentoFinanceiroAnalitico fechamentoAnalitico in this.FechamentoAnalitico) + { + string str1 = string.Format("{0}_{1}", num, fechamentoAnalitico.get_NomeConta()); + while (str1.Replace("/", "_").Trim().Length > 30) + { + str1 = Regex.Replace(str1.Trim(), "[^\\s]*$", ""); + } + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str1.Replace("/", "_"), fechamentoAnalitico.get_Dados().ToList(), null); + } + } + } + else if (this.Fechamento == null || this.Fechamento.Count == 0) + { + str = null; + return; + } + else + { + List fechamentoFinanceiros = new List(); + fechamentoFinanceiros.AddRange(this.Fechamento); + List fechamentoFinanceiros1 = fechamentoFinanceiros; + FechamentoFinanceiro fechamentoFinanceiro = new FechamentoFinanceiro(); + fechamentoFinanceiro.set_Plano("TOTAL NO PERÍODO"); + List dadosFechamentos = new List(); + DadosFechamento dadosFechamento = new DadosFechamento(); + dadosFechamento.set_Planos("TOTAL"); + List fechamento = this.Fechamento; + IEnumerable plano = + from x in fechamento + where x.get_Plano() == "TIPO PAGAMENTO" + select x; + dadosFechamento.set_Soma(plano.Sum((FechamentoFinanceiro x) => x.get_Dados().Sum((DadosFechamento y) => y.get_Soma()))); + dadosFechamentos.Add(dadosFechamento); + fechamentoFinanceiro.set_Dados(dadosFechamentos); + fechamentoFinanceiros1.Add(fechamentoFinanceiro); + num = 1; + foreach (FechamentoFinanceiro fechamentoFinanceiro1 in fechamentoFinanceiros) + { + string str2 = string.Format("{0}_{1}", num, fechamentoFinanceiro1.get_Plano()); + num++; + while (str2.Replace("/", "_").Trim().Length > 30) + { + str2 = Regex.Replace(str2.Trim(), "[^\\s]*$", ""); + } + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str2.Replace("/", "_"), fechamentoFinanceiro1.get_Dados().ToList(), null); + } + } + base.RegistrarAcao(string.Format("EMITIU EXCEL DO RELATÓRIO PERÍODO ENTRE {0:d} E {1:d}", this.Inicio, this.Fim), new Relatorio?(11), null); + xLWorkbook.SaveAs(str); + Process.Start(str); + str = null; + } + + private async Task GerarHtml(bool screen) + { + string str; + string str1 = ""; + if (!this.Analitico) + { + foreach (FechamentoFinanceiro fechamento in this.Fechamento) + { + List dados = fechamento.get_Dados(); + List strs = new List() + { + "TOTAL CRÉDITO - TOTAL DÉBITO", + "% TOTAL DE CRÉDITO - % TOTAL DE DÉBITO" + }; + string str2 = await Funcoes.GenerateTable(dados, strs, false, screen, "", null); + str1 = string.Concat(str1, Funcoes.CreateCard(fechamento.get_Plano(), str2, false)); + } + FechamentoFinanceiro fechamentoFinanceiro = new FechamentoFinanceiro(); + fechamentoFinanceiro.set_Plano("TOTAL NO PERÍODO"); + List dadosFechamentos = new List(); + DadosFechamento dadosFechamento = new DadosFechamento(); + dadosFechamento.set_Planos("TOTAL"); + List fechamentoFinanceiros = this.Fechamento; + IEnumerable plano = + from x in fechamentoFinanceiros + where x.get_Plano() == "TIPO PAGAMENTO" + select x; + dadosFechamento.set_Soma(plano.Sum((FechamentoFinanceiro x) => x.get_Dados().Sum((DadosFechamento y) => y.get_Soma()))); + List fechamento1 = this.Fechamento; + IEnumerable plano1 = + from x in fechamento1 + where x.get_Plano() == "TIPO PAGAMENTO" + select x; + dadosFechamento.set_SomaPercentual(plano1.Sum((FechamentoFinanceiro x) => x.get_Dados().Sum((DadosFechamento y) => y.get_SomaPercentual()))); + dadosFechamentos.Add(dadosFechamento); + fechamentoFinanceiro.set_Dados(dadosFechamentos); + FechamentoFinanceiro fechamentoFinanceiro1 = fechamentoFinanceiro; + List dados1 = fechamentoFinanceiro1.get_Dados(); + List strs1 = new List() + { + "TOTAL CRÉDITO", + "TOTAL DÉBITO", + "% CRÉDITO", + "% DÉBITO" + }; + string str3 = await Funcoes.GenerateTable(dados1, strs1, false, screen, "", null); + str1 = string.Concat(str1, Funcoes.CreateCard(fechamentoFinanceiro1.get_Plano(), str3, false)); + fechamentoFinanceiro1 = null; + } + else + { + foreach (FechamentoFinanceiroAnalitico fechamentoAnalitico in this.FechamentoAnalitico) + { + string str4 = await Funcoes.GenerateTable(fechamentoAnalitico.get_Dados(), new List(), false, screen, "", null); + str1 = string.Concat(str1, Funcoes.CreateCard(fechamentoAnalitico.get_NomeConta(), str4, false)); + } + } + if (!this.Inicio.HasValue || !this.Fim.HasValue) + { + str = null; + } + else + { + TipoRelatorio tipoRelatorio = new TipoRelatorio(); + tipoRelatorio.set_Nome((this.Analitico ? "RELATÓRIO FECHAMENTO FINANCEIRO ANALÍTICO" : "RELATÓRIO FECHAMENTO FINANCEIRO")); + tipoRelatorio.set_Inicio(this.Inicio.Value); + tipoRelatorio.set_Fim(this.Fim.Value); + str = Funcoes.ExportarHtml(tipoRelatorio, str1, "50", "portrait", false, ""); + } + str1 = null; + return str; + } + + public async Task GerarRelatorio() + { + decimal num7; + decimal num8; + decimal num9; + decimal num10; + decimal num11; + decimal num12; + decimal num13; + decimal num14; + decimal num15; + decimal num16; + decimal num17; + Func func8 = null; + Func func9 = null; + Func func10 = null; + Func func11 = null; + Func func12 = null; + Func func13 = null; + Func func14 = null; + Func func15 = null; + Func func16 = null; + Func func17 = null; + Func func18 = null; + Func func19 = null; + if (this.Inicio.HasValue && this.Fim.HasValue) + { + List planos = this.Plano; + IEnumerable selecionado = + from x in planos + where x.get_Selecionado() + select x; + List nums20 = ( + from x in selecionado + select x.get_Id()).ToList(); + List planos1 = this.Planos; + IEnumerable selecionado1 = + from x in planos1 + where x.get_Selecionado() + select x; + List nums21 = ( + from x in selecionado1 + select x.get_Id()).ToList(); + List centro = this.Centro; + IEnumerable centros = + from x in centro + where x.get_Selecionado() + select x; + List nums22 = ( + from x in centros + select x.get_Id()).ToList(); + List conta = this.Conta; + IEnumerable bancosContas = + from x in conta + where x.get_Selecionado() + select x; + List nums23 = ( + from x in bancosContas + select x.get_Id()).ToList(); + FiltroFinanceiro filtroFinanceiro = new FiltroFinanceiro(); + filtroFinanceiro.set_Inicio(this.Inicio.Value); + filtroFinanceiro.set_Fim(this.Fim.Value); + filtroFinanceiro.set_Plano(nums20); + filtroFinanceiro.set_Planos(nums21); + filtroFinanceiro.set_Centro(nums22); + filtroFinanceiro.set_Conta(nums23); + filtroFinanceiro.set_Referencia("l.dtbaixa"); + FiltroFinanceiro filtroFinanceiro1 = filtroFinanceiro; + List lancamentos13 = await this._servico.BuscarFechamento(filtroFinanceiro1); + if (!this.Analitico) + { + this.Fechamento = new List(); + List lancamentos14 = lancamentos13; + IEnumerable lancamentos15 = lancamentos14.Where((Lancamento x) => { + object plano; + ControleFinanceiro controle = x.get_Controle(); + if (controle != null) + { + plano = controle.get_Plano(); + } + else + { + plano = null; + } + return plano != null; + }); + IOrderedEnumerable nome = + from x in lancamentos15 + orderby x.get_Controle().get_Plano().get_Nome() + select x; + ( + from x in nome + group x by x.get_Controle().get_Plano().get_Plano().get_Id()).ToList>().ForEach((IGrouping x) => { + decimal num3; + decimal num4; + FechamentoFinanceiro fechamentoFinanceiro = new FechamentoFinanceiro(); + fechamentoFinanceiro.set_Plano(x.First().get_Controle().get_Plano().get_Nome().ToUpper()); + IGrouping nums8 = x; + Func u003cu003e9_5197 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_97; + if (u003cu003e9_5197 == null) + { + u003cu003e9_5197 = (Lancamento f) => f.get_Controle().get_Plano().get_Nome(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_97 = u003cu003e9_5197; + } + IOrderedEnumerable lancamentos8 = nums8.OrderBy(u003cu003e9_5197); + Func u003cu003e9_5198 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_98; + if (u003cu003e9_5198 == null) + { + u003cu003e9_5198 = (Lancamento f) => f.get_Controle().get_Plano().get_Id(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_98 = u003cu003e9_5198; + } + fechamentoFinanceiro.set_Dados(lancamentos8.GroupBy(u003cu003e9_5198).Select, DadosFechamento>((IGrouping f) => { + decimal zero; + decimal num; + DadosFechamento dadosFechamento = new DadosFechamento(); + dadosFechamento.set_Planos(f.First().get_Controle().get_Plano().get_Descricao()); + IGrouping nums = f; + Func u003cu003e9_51100 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_100; + if (u003cu003e9_51100 == null) + { + u003cu003e9_51100 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_100 = u003cu003e9_51100; + } + IEnumerable lancamentos = nums.Where(u003cu003e9_51100); + Func u003cu003e9_51101 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_101; + if (u003cu003e9_51101 == null) + { + u003cu003e9_51101 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_101 = u003cu003e9_51101; + } + dadosFechamento.set_Credito(lancamentos.Sum(u003cu003e9_51101)); + IGrouping nums1 = f; + Func u003cu003e9_51102 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_102; + if (u003cu003e9_51102 == null) + { + u003cu003e9_51102 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_102 = u003cu003e9_51102; + } + IEnumerable lancamentos1 = nums1.Where(u003cu003e9_51102); + Func u003cu003e9_51103 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_103; + if (u003cu003e9_51103 == null) + { + u003cu003e9_51103 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_103 = u003cu003e9_51103; + } + if (lancamentos1.Sum(u003cu003e9_51103) == decimal.Zero) + { + zero = decimal.Zero; + } + else + { + IGrouping nums2 = f; + Func u003cu003e9_51104 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_104; + if (u003cu003e9_51104 == null) + { + u003cu003e9_51104 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_104 = u003cu003e9_51104; + } + IEnumerable lancamentos2 = nums2.Where(u003cu003e9_51104); + Func u003cu003e9_51105 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_105; + if (u003cu003e9_51105 == null) + { + u003cu003e9_51105 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_105 = u003cu003e9_51105; + } + decimal num1 = lancamentos2.Sum(u003cu003e9_51105); + IGrouping nums3 = x; + Func u003cu003e9_51106 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_106; + if (u003cu003e9_51106 == null) + { + u003cu003e9_51106 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_106 = u003cu003e9_51106; + } + IEnumerable lancamentos3 = nums3.Where(u003cu003e9_51106); + Func u003cu003e9_51107 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_107; + if (u003cu003e9_51107 == null) + { + u003cu003e9_51107 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_107 = u003cu003e9_51107; + } + zero = (num1 / lancamentos3.Sum(u003cu003e9_51107)) * new decimal(100); + } + dadosFechamento.set_PercentualCredito(zero); + IGrouping nums4 = f; + Func u003cu003e9_51108 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_108; + if (u003cu003e9_51108 == null) + { + u003cu003e9_51108 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_108 = u003cu003e9_51108; + } + IEnumerable lancamentos4 = nums4.Where(u003cu003e9_51108); + Func u003cu003e9_51109 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_109; + if (u003cu003e9_51109 == null) + { + u003cu003e9_51109 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_109 = u003cu003e9_51109; + } + dadosFechamento.set_Debito(lancamentos4.Sum(u003cu003e9_51109)); + IGrouping nums5 = f; + Func u003cu003e9_51110 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_110; + if (u003cu003e9_51110 == null) + { + u003cu003e9_51110 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_110 = u003cu003e9_51110; + } + IEnumerable lancamentos5 = nums5.Where(u003cu003e9_51110); + Func u003cu003e9_51111 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_111; + if (u003cu003e9_51111 == null) + { + u003cu003e9_51111 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_111 = u003cu003e9_51111; + } + if (lancamentos5.Sum(u003cu003e9_51111) == decimal.Zero) + { + num = decimal.Zero; + } + else + { + IGrouping nums6 = f; + Func u003cu003e9_51112 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_112; + if (u003cu003e9_51112 == null) + { + u003cu003e9_51112 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_112 = u003cu003e9_51112; + } + IEnumerable lancamentos6 = nums6.Where(u003cu003e9_51112); + Func u003cu003e9_51113 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_113; + if (u003cu003e9_51113 == null) + { + u003cu003e9_51113 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_113 = u003cu003e9_51113; + } + decimal num2 = lancamentos6.Sum(u003cu003e9_51113); + IGrouping nums7 = x; + Func u003cu003e9_51114 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_114; + if (u003cu003e9_51114 == null) + { + u003cu003e9_51114 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_114 = u003cu003e9_51114; + } + IEnumerable lancamentos7 = nums7.Where(u003cu003e9_51114); + Func u003cu003e9_51115 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_115; + if (u003cu003e9_51115 == null) + { + u003cu003e9_51115 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_115 = u003cu003e9_51115; + } + num = (num2 / lancamentos7.Sum(u003cu003e9_51115)) * new decimal(100); + } + dadosFechamento.set_PercentualDebito(num); + return dadosFechamento; + }).ToList()); + FechamentoFinanceiro fechamentoFinanceiro1 = fechamentoFinanceiro; + List dados = fechamentoFinanceiro1.get_Dados(); + DadosFechamento dadosFechamento1 = new DadosFechamento(); + dadosFechamento1.set_Planos("TOTAL"); + List dadosFechamentos = fechamentoFinanceiro1.get_Dados(); + Func u003cu003e9_51116 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_116; + if (u003cu003e9_51116 == null) + { + u003cu003e9_51116 = (DadosFechamento t) => t.get_Credito(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_116 = u003cu003e9_51116; + } + dadosFechamento1.set_Credito(dadosFechamentos.Sum(u003cu003e9_51116)); + List dados1 = fechamentoFinanceiro1.get_Dados(); + Func u003cu003e9_51117 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_117; + if (u003cu003e9_51117 == null) + { + u003cu003e9_51117 = (DadosFechamento t) => t.get_Debito(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_117 = u003cu003e9_51117; + } + dadosFechamento1.set_Debito(dados1.Sum(u003cu003e9_51117)); + List dadosFechamentos1 = fechamentoFinanceiro1.get_Dados(); + Func u003cu003e9_51118 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_118; + if (u003cu003e9_51118 == null) + { + u003cu003e9_51118 = (DadosFechamento t) => t.get_Credito(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_118 = u003cu003e9_51118; + } + if (dadosFechamentos1.Sum(u003cu003e9_51118) == decimal.Zero) + { + num3 = decimal.Zero; + } + else + { + List dados2 = fechamentoFinanceiro1.get_Dados(); + Func u003cu003e9_51119 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_119; + if (u003cu003e9_51119 == null) + { + u003cu003e9_51119 = (DadosFechamento t) => t.get_Credito(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_119 = u003cu003e9_51119; + } + decimal num5 = dados2.Sum(u003cu003e9_51119); + List lancamentos9 = lancamentos13; + Func u003cu003e9_51120 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_120; + if (u003cu003e9_51120 == null) + { + u003cu003e9_51120 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_120 = u003cu003e9_51120; + } + IEnumerable lancamentos10 = lancamentos9.Where(u003cu003e9_51120); + Func u003cu003e9_51121 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_121; + if (u003cu003e9_51121 == null) + { + u003cu003e9_51121 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_121 = u003cu003e9_51121; + } + num3 = (num5 / lancamentos10.Sum(u003cu003e9_51121)) * new decimal(100); + } + dadosFechamento1.set_PercentualCredito(num3); + List dadosFechamentos2 = fechamentoFinanceiro1.get_Dados(); + Func u003cu003e9_51122 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_122; + if (u003cu003e9_51122 == null) + { + u003cu003e9_51122 = (DadosFechamento t) => t.get_Debito(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_122 = u003cu003e9_51122; + } + if (dadosFechamentos2.Sum(u003cu003e9_51122) == decimal.Zero) + { + num4 = decimal.Zero; + } + else + { + List dados3 = fechamentoFinanceiro1.get_Dados(); + Func u003cu003e9_51123 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_123; + if (u003cu003e9_51123 == null) + { + u003cu003e9_51123 = (DadosFechamento t) => t.get_Debito(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_123 = u003cu003e9_51123; + } + decimal num6 = dados3.Sum(u003cu003e9_51123); + List lancamentos11 = lancamentos13; + Func u003cu003e9_51124 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_124; + if (u003cu003e9_51124 == null) + { + u003cu003e9_51124 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_124 = u003cu003e9_51124; + } + IEnumerable lancamentos12 = lancamentos11.Where(u003cu003e9_51124); + Func u003cu003e9_51125 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_125; + if (u003cu003e9_51125 == null) + { + u003cu003e9_51125 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_125 = u003cu003e9_51125; + } + num4 = (num6 / lancamentos12.Sum(u003cu003e9_51125)) * new decimal(100); + } + dadosFechamento1.set_PercentualDebito(num4); + dados.Add(dadosFechamento1); + this.Fechamento.Add(fechamentoFinanceiro1); + }); + FechamentoFinanceiro fechamentoFinanceiro2 = new FechamentoFinanceiro(); + fechamentoFinanceiro2.set_Plano("CONTA CORRENTE"); + List lancamentos16 = lancamentos13; + IEnumerable lancamentos17 = lancamentos16.Where((Lancamento x) => { + object plano; + ControleFinanceiro controle = x.get_Controle(); + if (controle != null) + { + plano = controle.get_Plano(); + } + else + { + plano = null; + } + return plano != null; + }); + IOrderedEnumerable descricao = + from x in lancamentos17 + orderby x.get_Conta().get_Descricao() + select x; + fechamentoFinanceiro2.set_Dados(( + from x in descricao + group x by x.get_Conta().get_Id()).Select, DadosFechamento>((IGrouping f) => { + decimal zero; + decimal num; + DadosFechamento dadosFechamento = new DadosFechamento(); + dadosFechamento.set_Planos(f.First().get_Conta().get_Descricao()); + IGrouping nums = f; + Func u003cu003e9_51130 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_130; + if (u003cu003e9_51130 == null) + { + u003cu003e9_51130 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_130 = u003cu003e9_51130; + } + IEnumerable lancamentos = nums.Where(u003cu003e9_51130); + Func u003cu003e9_51131 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_131; + if (u003cu003e9_51131 == null) + { + u003cu003e9_51131 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_131 = u003cu003e9_51131; + } + dadosFechamento.set_Credito(lancamentos.Sum(u003cu003e9_51131)); + IGrouping nums1 = f; + Func u003cu003e9_51132 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_132; + if (u003cu003e9_51132 == null) + { + u003cu003e9_51132 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_132 = u003cu003e9_51132; + } + IEnumerable lancamentos1 = nums1.Where(u003cu003e9_51132); + Func u003cu003e9_51133 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_133; + if (u003cu003e9_51133 == null) + { + u003cu003e9_51133 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_133 = u003cu003e9_51133; + } + if (lancamentos1.Sum(u003cu003e9_51133) == decimal.Zero) + { + zero = decimal.Zero; + } + else + { + IGrouping nums2 = f; + Func u003cu003e9_51134 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_134; + if (u003cu003e9_51134 == null) + { + u003cu003e9_51134 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_134 = u003cu003e9_51134; + } + IEnumerable lancamentos2 = nums2.Where(u003cu003e9_51134); + Func u003cu003e9_51135 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_135; + if (u003cu003e9_51135 == null) + { + u003cu003e9_51135 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_135 = u003cu003e9_51135; + } + decimal num1 = lancamentos2.Sum(u003cu003e9_51135); + List lancamentos3 = lancamentos13; + Func u003cu003e9_51136 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_136; + if (u003cu003e9_51136 == null) + { + u003cu003e9_51136 = (Lancamento s) => { + if (s.get_Controle() == null) + { + return false; + } + return s.get_Sinal() == 0; + }; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_136 = u003cu003e9_51136; + } + IEnumerable lancamentos4 = lancamentos3.Where(u003cu003e9_51136); + Func u003cu003e9_51137 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_137; + if (u003cu003e9_51137 == null) + { + u003cu003e9_51137 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_137 = u003cu003e9_51137; + } + zero = (num1 / lancamentos4.Sum(u003cu003e9_51137)) * new decimal(100); + } + dadosFechamento.set_PercentualCredito(zero); + IGrouping nums3 = f; + Func u003cu003e9_51138 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_138; + if (u003cu003e9_51138 == null) + { + u003cu003e9_51138 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_138 = u003cu003e9_51138; + } + IEnumerable lancamentos5 = nums3.Where(u003cu003e9_51138); + Func u003cu003e9_51139 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_139; + if (u003cu003e9_51139 == null) + { + u003cu003e9_51139 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_139 = u003cu003e9_51139; + } + dadosFechamento.set_Debito(lancamentos5.Sum(u003cu003e9_51139)); + IGrouping nums4 = f; + Func u003cu003e9_51140 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_140; + if (u003cu003e9_51140 == null) + { + u003cu003e9_51140 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_140 = u003cu003e9_51140; + } + IEnumerable lancamentos6 = nums4.Where(u003cu003e9_51140); + Func u003cu003e9_51141 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_141; + if (u003cu003e9_51141 == null) + { + u003cu003e9_51141 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_141 = u003cu003e9_51141; + } + if (lancamentos6.Sum(u003cu003e9_51141) == decimal.Zero) + { + num = decimal.Zero; + } + else + { + IGrouping nums5 = f; + Func u003cu003e9_51142 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_142; + if (u003cu003e9_51142 == null) + { + u003cu003e9_51142 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_142 = u003cu003e9_51142; + } + IEnumerable lancamentos7 = nums5.Where(u003cu003e9_51142); + Func u003cu003e9_51143 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_143; + if (u003cu003e9_51143 == null) + { + u003cu003e9_51143 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_143 = u003cu003e9_51143; + } + decimal num2 = lancamentos7.Sum(u003cu003e9_51143); + List lancamentos8 = lancamentos13; + Func u003cu003e9_51144 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_144; + if (u003cu003e9_51144 == null) + { + u003cu003e9_51144 = (Lancamento s) => { + if (s.get_Controle() == null) + { + return false; + } + return s.get_Sinal() == 1; + }; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_144 = u003cu003e9_51144; + } + IEnumerable lancamentos9 = lancamentos8.Where(u003cu003e9_51144); + Func u003cu003e9_51145 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_145; + if (u003cu003e9_51145 == null) + { + u003cu003e9_51145 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_145 = u003cu003e9_51145; + } + num = (num2 / lancamentos9.Sum(u003cu003e9_51145)) * new decimal(100); + } + dadosFechamento.set_PercentualDebito(num); + return dadosFechamento; + }).ToList()); + FechamentoFinanceiro fechamentoFinanceiro3 = fechamentoFinanceiro2; + List dadosFechamentos3 = fechamentoFinanceiro3.get_Dados(); + DadosFechamento dadosFechamento2 = new DadosFechamento(); + dadosFechamento2.set_Planos("TOTAL"); + List dadosFechamentos4 = fechamentoFinanceiro3.get_Dados(); + dadosFechamento2.set_Credito(dadosFechamentos4.Sum((DadosFechamento t) => t.get_Credito())); + List dadosFechamentos5 = fechamentoFinanceiro3.get_Dados(); + dadosFechamento2.set_Debito(dadosFechamentos5.Sum((DadosFechamento t) => t.get_Debito())); + List dadosFechamentos6 = fechamentoFinanceiro3.get_Dados(); + if (dadosFechamentos6.Sum((DadosFechamento t) => t.get_Credito()) == decimal.Zero) + { + num7 = decimal.Zero; + } + else + { + List dadosFechamentos7 = fechamentoFinanceiro3.get_Dados(); + decimal num18 = dadosFechamentos7.Sum((DadosFechamento t) => t.get_Credito()); + List lancamentos18 = lancamentos13; + IEnumerable lancamentos19 = lancamentos18.Where((Lancamento s) => { + if (s.get_Controle() == null) + { + return false; + } + return s.get_Sinal() == 0; + }); + num7 = (num18 / lancamentos19.Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault())) * new decimal(100); + } + dadosFechamento2.set_PercentualCredito(num7); + List dadosFechamentos8 = fechamentoFinanceiro3.get_Dados(); + if (dadosFechamentos8.Sum((DadosFechamento t) => t.get_Debito()) == decimal.Zero) + { + num8 = decimal.Zero; + } + else + { + List dadosFechamentos9 = fechamentoFinanceiro3.get_Dados(); + decimal num19 = dadosFechamentos9.Sum((DadosFechamento t) => t.get_Debito()); + List lancamentos20 = lancamentos13; + IEnumerable lancamentos21 = lancamentos20.Where((Lancamento s) => { + if (s.get_Controle() == null) + { + return false; + } + return s.get_Sinal() == 1; + }); + num8 = (num19 / lancamentos21.Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault())) * new decimal(100); + } + dadosFechamento2.set_PercentualDebito(num8); + dadosFechamentos3.Add(dadosFechamento2); + this.Fechamento.Add(fechamentoFinanceiro3); + FechamentoFinanceiro fechamentoFinanceiro4 = new FechamentoFinanceiro(); + fechamentoFinanceiro4.set_Plano("TRANSFERÊNCIA"); + List lancamentos22 = lancamentos13; + IEnumerable lancamentos23 = lancamentos22.Where((Lancamento x) => { + object plano; + ControleFinanceiro controle = x.get_Controle(); + if (controle != null) + { + plano = controle.get_Plano(); + } + else + { + plano = null; + } + return plano == null; + }); + IOrderedEnumerable descricao1 = + from x in lancamentos23 + orderby x.get_Conta().get_Descricao() + select x; + IEnumerable> id = + from x in descricao1 + group x by x.get_Conta().get_Id(); + fechamentoFinanceiro4.set_Dados(id.Select, DadosFechamento>((IGrouping f) => { + DadosFechamento dadosFechamento = new DadosFechamento(); + dadosFechamento.set_Planos(f.First().get_Conta().get_Descricao()); + dadosFechamento.set_Credito(( + from s in f + where s.get_Sinal() == 0 + select s).Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault())); + dadosFechamento.set_PercentualCredito((( + from s in f + where s.get_Sinal() == 0 + select s).Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault()) == decimal.Zero ? decimal.Zero : (( + from s in f + where s.get_Sinal() == 0 + select s).Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault()) / ( + from s in f + where s.get_Sinal() == 0 + select s).Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault())) * new decimal(100))); + dadosFechamento.set_Debito(( + from s in f + where s.get_Sinal() == 1 + select s).Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault())); + dadosFechamento.set_PercentualDebito((( + from s in f + where s.get_Sinal() == 1 + select s).Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault()) == decimal.Zero ? decimal.Zero : (( + from s in f + where s.get_Sinal() == 1 + select s).Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault()) / ( + from s in f + where s.get_Sinal() == 1 + select s).Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault())) * new decimal(100))); + return dadosFechamento; + }).ToList()); + FechamentoFinanceiro fechamentoFinanceiro5 = fechamentoFinanceiro4; + List dadosFechamentos10 = fechamentoFinanceiro5.get_Dados(); + DadosFechamento dadosFechamento3 = new DadosFechamento(); + dadosFechamento3.set_Planos("TOTAL"); + List dadosFechamentos11 = fechamentoFinanceiro5.get_Dados(); + dadosFechamento3.set_Credito(dadosFechamentos11.Sum((DadosFechamento t) => t.get_Credito())); + List dadosFechamentos12 = fechamentoFinanceiro5.get_Dados(); + dadosFechamento3.set_Debito(dadosFechamentos12.Sum((DadosFechamento t) => t.get_Debito())); + List dadosFechamentos13 = fechamentoFinanceiro5.get_Dados(); + if (dadosFechamentos13.Sum((DadosFechamento t) => t.get_Credito()) == decimal.Zero) + { + num9 = decimal.Zero; + } + else + { + List dadosFechamentos14 = fechamentoFinanceiro5.get_Dados(); + decimal num20 = dadosFechamentos14.Sum((DadosFechamento t) => t.get_Credito()); + List lancamentos24 = lancamentos13; + IEnumerable lancamentos25 = lancamentos24.Where((Lancamento s) => { + bool plano; + ControleFinanceiro controle = s.get_Controle(); + if (controle != null) + { + plano = controle.get_Plano(); + } + else + { + plano = false; + } + if (plano) + { + return false; + } + return s.get_Sinal() == 0; + }); + num9 = (num20 / lancamentos25.Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault())) * new decimal(100); + } + dadosFechamento3.set_PercentualCredito(num9); + List dadosFechamentos15 = fechamentoFinanceiro5.get_Dados(); + if (dadosFechamentos15.Sum((DadosFechamento t) => t.get_Debito()) == decimal.Zero) + { + num10 = decimal.Zero; + } + else + { + List dadosFechamentos16 = fechamentoFinanceiro5.get_Dados(); + decimal num21 = dadosFechamentos16.Sum((DadosFechamento t) => t.get_Debito()); + List lancamentos26 = lancamentos13; + IEnumerable lancamentos27 = lancamentos26.Where((Lancamento s) => { + bool plano; + ControleFinanceiro controle = s.get_Controle(); + if (controle != null) + { + plano = controle.get_Plano(); + } + else + { + plano = false; + } + if (plano) + { + return false; + } + return s.get_Sinal() == 1; + }); + num10 = (num21 / lancamentos27.Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault())) * new decimal(100); + } + dadosFechamento3.set_PercentualDebito(num10); + dadosFechamentos10.Add(dadosFechamento3); + this.Fechamento.Add(fechamentoFinanceiro5); + FechamentoFinanceiro fechamentoFinanceiro6 = new FechamentoFinanceiro(); + fechamentoFinanceiro6.set_Plano("CONTA CORRENTE + TRANSFERÊNCIA"); + List lancamentos28 = lancamentos13; + IOrderedEnumerable descricao2 = + from x in lancamentos28 + orderby x.get_Conta().get_Descricao() + select x; + fechamentoFinanceiro6.set_Dados(( + from x in descricao2 + group x by x.get_Conta().get_Id()).Select, DadosFechamento>((IGrouping f) => { + decimal zero; + decimal num; + DadosFechamento dadosFechamento = new DadosFechamento(); + dadosFechamento.set_Planos(f.First().get_Conta().get_Descricao()); + IGrouping nums = f; + Func u003cu003e9_51189 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_189; + if (u003cu003e9_51189 == null) + { + u003cu003e9_51189 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_189 = u003cu003e9_51189; + } + IEnumerable lancamentos = nums.Where(u003cu003e9_51189); + Func u003cu003e9_51190 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_190; + if (u003cu003e9_51190 == null) + { + u003cu003e9_51190 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_190 = u003cu003e9_51190; + } + dadosFechamento.set_Credito(lancamentos.Sum(u003cu003e9_51190)); + IGrouping nums1 = f; + Func u003cu003e9_51191 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_191; + if (u003cu003e9_51191 == null) + { + u003cu003e9_51191 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_191 = u003cu003e9_51191; + } + IEnumerable lancamentos1 = nums1.Where(u003cu003e9_51191); + Func u003cu003e9_51192 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_192; + if (u003cu003e9_51192 == null) + { + u003cu003e9_51192 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_192 = u003cu003e9_51192; + } + if (lancamentos1.Sum(u003cu003e9_51192) == decimal.Zero) + { + zero = decimal.Zero; + } + else + { + IGrouping nums2 = f; + Func u003cu003e9_51193 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_193; + if (u003cu003e9_51193 == null) + { + u003cu003e9_51193 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_193 = u003cu003e9_51193; + } + IEnumerable lancamentos2 = nums2.Where(u003cu003e9_51193); + Func u003cu003e9_51194 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_194; + if (u003cu003e9_51194 == null) + { + u003cu003e9_51194 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_194 = u003cu003e9_51194; + } + decimal num1 = lancamentos2.Sum(u003cu003e9_51194); + List lancamentos3 = lancamentos13; + Func u003cu003e9_51195 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_195; + if (u003cu003e9_51195 == null) + { + u003cu003e9_51195 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_195 = u003cu003e9_51195; + } + IEnumerable lancamentos4 = lancamentos3.Where(u003cu003e9_51195); + Func u003cu003e9_51196 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_196; + if (u003cu003e9_51196 == null) + { + u003cu003e9_51196 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_196 = u003cu003e9_51196; + } + zero = (num1 / lancamentos4.Sum(u003cu003e9_51196)) * new decimal(100); + } + dadosFechamento.set_PercentualCredito(zero); + IGrouping nums3 = f; + Func u003cu003e9_51197 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_197; + if (u003cu003e9_51197 == null) + { + u003cu003e9_51197 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_197 = u003cu003e9_51197; + } + IEnumerable lancamentos5 = nums3.Where(u003cu003e9_51197); + Func u003cu003e9_51198 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_198; + if (u003cu003e9_51198 == null) + { + u003cu003e9_51198 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_198 = u003cu003e9_51198; + } + dadosFechamento.set_Debito(lancamentos5.Sum(u003cu003e9_51198)); + IGrouping nums4 = f; + Func u003cu003e9_51199 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_199; + if (u003cu003e9_51199 == null) + { + u003cu003e9_51199 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_199 = u003cu003e9_51199; + } + IEnumerable lancamentos6 = nums4.Where(u003cu003e9_51199); + Func u003cu003e9_51200 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_200; + if (u003cu003e9_51200 == null) + { + u003cu003e9_51200 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_200 = u003cu003e9_51200; + } + if (lancamentos6.Sum(u003cu003e9_51200) == decimal.Zero) + { + num = decimal.Zero; + } + else + { + IGrouping nums5 = f; + Func u003cu003e9_51201 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_201; + if (u003cu003e9_51201 == null) + { + u003cu003e9_51201 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_201 = u003cu003e9_51201; + } + IEnumerable lancamentos7 = nums5.Where(u003cu003e9_51201); + Func u003cu003e9_51202 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_202; + if (u003cu003e9_51202 == null) + { + u003cu003e9_51202 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_202 = u003cu003e9_51202; + } + decimal num2 = lancamentos7.Sum(u003cu003e9_51202); + List lancamentos8 = lancamentos13; + Func u003cu003e9_51203 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_203; + if (u003cu003e9_51203 == null) + { + u003cu003e9_51203 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_203 = u003cu003e9_51203; + } + IEnumerable lancamentos9 = lancamentos8.Where(u003cu003e9_51203); + Func u003cu003e9_51204 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_204; + if (u003cu003e9_51204 == null) + { + u003cu003e9_51204 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_204 = u003cu003e9_51204; + } + num = (num2 / lancamentos9.Sum(u003cu003e9_51204)) * new decimal(100); + } + dadosFechamento.set_PercentualDebito(num); + return dadosFechamento; + }).ToList()); + FechamentoFinanceiro fechamentoFinanceiro7 = fechamentoFinanceiro6; + List dadosFechamentos17 = fechamentoFinanceiro7.get_Dados(); + DadosFechamento dadosFechamento4 = new DadosFechamento(); + dadosFechamento4.set_Planos("TOTAL"); + List dadosFechamentos18 = fechamentoFinanceiro7.get_Dados(); + dadosFechamento4.set_Credito(dadosFechamentos18.Sum((DadosFechamento t) => t.get_Credito())); + List dadosFechamentos19 = fechamentoFinanceiro7.get_Dados(); + dadosFechamento4.set_Debito(dadosFechamentos19.Sum((DadosFechamento t) => t.get_Debito())); + List dadosFechamentos20 = fechamentoFinanceiro7.get_Dados(); + if (dadosFechamentos20.Sum((DadosFechamento t) => t.get_Credito()) == decimal.Zero) + { + num11 = decimal.Zero; + } + else + { + List dadosFechamentos21 = fechamentoFinanceiro7.get_Dados(); + decimal num22 = dadosFechamentos21.Sum((DadosFechamento t) => t.get_Credito()); + List lancamentos29 = lancamentos13; + IEnumerable sinal = + from s in lancamentos29 + where s.get_Sinal() == 0 + select s; + num11 = (num22 / sinal.Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault())) * new decimal(100); + } + dadosFechamento4.set_PercentualCredito(num11); + List dadosFechamentos22 = fechamentoFinanceiro7.get_Dados(); + if (dadosFechamentos22.Sum((DadosFechamento t) => t.get_Debito()) == decimal.Zero) + { + num12 = decimal.Zero; + } + else + { + List dadosFechamentos23 = fechamentoFinanceiro7.get_Dados(); + decimal num23 = dadosFechamentos23.Sum((DadosFechamento t) => t.get_Debito()); + List lancamentos30 = lancamentos13; + IEnumerable sinal1 = + from s in lancamentos30 + where s.get_Sinal() == 1 + select s; + num12 = (num23 / sinal1.Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault())) * new decimal(100); + } + dadosFechamento4.set_PercentualDebito(num12); + dadosFechamentos17.Add(dadosFechamento4); + this.Fechamento.Add(fechamentoFinanceiro7); + FechamentoFinanceiro fechamentoFinanceiro8 = new FechamentoFinanceiro(); + fechamentoFinanceiro8.set_Plano("CENTRO DE CUSTO"); + List lancamentos31 = lancamentos13; + IEnumerable lancamentos32 = lancamentos31.Where((Lancamento x) => { + object plano; + ControleFinanceiro controle = x.get_Controle(); + if (controle != null) + { + plano = controle.get_Plano(); + } + else + { + plano = null; + } + return plano != null; + }); + IOrderedEnumerable descricao3 = + from x in lancamentos32 + orderby x.get_Controle().get_Centro().get_Descricao() + select x; + fechamentoFinanceiro8.set_Dados(( + from x in descricao3 + group x by x.get_Controle().get_Centro().get_Id()).Select, DadosFechamento>((IGrouping f) => { + decimal zero; + decimal num; + DadosFechamento dadosFechamento = new DadosFechamento(); + dadosFechamento.set_Planos(f.First().get_Controle().get_Centro().get_Descricao()); + IGrouping nums = f; + Func u003cu003e9_51219 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_219; + if (u003cu003e9_51219 == null) + { + u003cu003e9_51219 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_219 = u003cu003e9_51219; + } + IEnumerable lancamentos = nums.Where(u003cu003e9_51219); + Func u003cu003e9_51220 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_220; + if (u003cu003e9_51220 == null) + { + u003cu003e9_51220 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_220 = u003cu003e9_51220; + } + dadosFechamento.set_Credito(lancamentos.Sum(u003cu003e9_51220)); + IGrouping nums1 = f; + Func u003cu003e9_51221 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_221; + if (u003cu003e9_51221 == null) + { + u003cu003e9_51221 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_221 = u003cu003e9_51221; + } + IEnumerable lancamentos1 = nums1.Where(u003cu003e9_51221); + Func u003cu003e9_51222 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_222; + if (u003cu003e9_51222 == null) + { + u003cu003e9_51222 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_222 = u003cu003e9_51222; + } + if (lancamentos1.Sum(u003cu003e9_51222) == decimal.Zero) + { + zero = decimal.Zero; + } + else + { + IGrouping nums2 = f; + Func u003cu003e9_51223 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_223; + if (u003cu003e9_51223 == null) + { + u003cu003e9_51223 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_223 = u003cu003e9_51223; + } + IEnumerable lancamentos2 = nums2.Where(u003cu003e9_51223); + Func u003cu003e9_51224 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_224; + if (u003cu003e9_51224 == null) + { + u003cu003e9_51224 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_224 = u003cu003e9_51224; + } + decimal num1 = lancamentos2.Sum(u003cu003e9_51224); + List lancamentos3 = lancamentos13; + Func u003cu003e9_51225 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_225; + if (u003cu003e9_51225 == null) + { + u003cu003e9_51225 = (Lancamento s) => { + if (s.get_Controle() == null) + { + return false; + } + return s.get_Sinal() == 0; + }; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_225 = u003cu003e9_51225; + } + IEnumerable lancamentos4 = lancamentos3.Where(u003cu003e9_51225); + Func u003cu003e9_51226 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_226; + if (u003cu003e9_51226 == null) + { + u003cu003e9_51226 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_226 = u003cu003e9_51226; + } + zero = (num1 / lancamentos4.Sum(u003cu003e9_51226)) * new decimal(100); + } + dadosFechamento.set_PercentualCredito(zero); + IGrouping nums3 = f; + Func u003cu003e9_51227 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_227; + if (u003cu003e9_51227 == null) + { + u003cu003e9_51227 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_227 = u003cu003e9_51227; + } + IEnumerable lancamentos5 = nums3.Where(u003cu003e9_51227); + Func u003cu003e9_51228 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_228; + if (u003cu003e9_51228 == null) + { + u003cu003e9_51228 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_228 = u003cu003e9_51228; + } + dadosFechamento.set_Debito(lancamentos5.Sum(u003cu003e9_51228)); + IGrouping nums4 = f; + Func u003cu003e9_51229 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_229; + if (u003cu003e9_51229 == null) + { + u003cu003e9_51229 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_229 = u003cu003e9_51229; + } + IEnumerable lancamentos6 = nums4.Where(u003cu003e9_51229); + Func u003cu003e9_51230 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_230; + if (u003cu003e9_51230 == null) + { + u003cu003e9_51230 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_230 = u003cu003e9_51230; + } + if (lancamentos6.Sum(u003cu003e9_51230) == decimal.Zero) + { + num = decimal.Zero; + } + else + { + IGrouping nums5 = f; + Func u003cu003e9_51231 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_231; + if (u003cu003e9_51231 == null) + { + u003cu003e9_51231 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_231 = u003cu003e9_51231; + } + IEnumerable lancamentos7 = nums5.Where(u003cu003e9_51231); + Func u003cu003e9_51232 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_232; + if (u003cu003e9_51232 == null) + { + u003cu003e9_51232 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_232 = u003cu003e9_51232; + } + decimal num2 = lancamentos7.Sum(u003cu003e9_51232); + List lancamentos8 = lancamentos13; + Func u003cu003e9_51233 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_233; + if (u003cu003e9_51233 == null) + { + u003cu003e9_51233 = (Lancamento s) => { + if (s.get_Controle() == null) + { + return false; + } + return s.get_Sinal() == 1; + }; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_233 = u003cu003e9_51233; + } + IEnumerable lancamentos9 = lancamentos8.Where(u003cu003e9_51233); + Func u003cu003e9_51234 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_234; + if (u003cu003e9_51234 == null) + { + u003cu003e9_51234 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_234 = u003cu003e9_51234; + } + num = (num2 / lancamentos9.Sum(u003cu003e9_51234)) * new decimal(100); + } + dadosFechamento.set_PercentualDebito(num); + return dadosFechamento; + }).ToList()); + FechamentoFinanceiro fechamentoFinanceiro9 = fechamentoFinanceiro8; + List dadosFechamentos24 = fechamentoFinanceiro9.get_Dados(); + DadosFechamento dadosFechamento5 = new DadosFechamento(); + dadosFechamento5.set_Planos("TOTAL"); + List dadosFechamentos25 = fechamentoFinanceiro9.get_Dados(); + dadosFechamento5.set_Credito(dadosFechamentos25.Sum((DadosFechamento t) => t.get_Credito())); + List dadosFechamentos26 = fechamentoFinanceiro9.get_Dados(); + dadosFechamento5.set_Debito(dadosFechamentos26.Sum((DadosFechamento t) => t.get_Debito())); + List dadosFechamentos27 = fechamentoFinanceiro9.get_Dados(); + if (dadosFechamentos27.Sum((DadosFechamento t) => t.get_Credito()) == decimal.Zero) + { + num13 = decimal.Zero; + } + else + { + List dadosFechamentos28 = fechamentoFinanceiro9.get_Dados(); + decimal num24 = dadosFechamentos28.Sum((DadosFechamento t) => t.get_Credito()); + List lancamentos33 = lancamentos13; + IEnumerable lancamentos34 = lancamentos33.Where((Lancamento s) => { + if (s.get_Controle() == null) + { + return false; + } + return s.get_Sinal() == 0; + }); + num13 = (num24 / lancamentos34.Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault())) * new decimal(100); + } + dadosFechamento5.set_PercentualCredito(num13); + List dadosFechamentos29 = fechamentoFinanceiro9.get_Dados(); + if (dadosFechamentos29.Sum((DadosFechamento t) => t.get_Debito()) == decimal.Zero) + { + num14 = decimal.Zero; + } + else + { + List dadosFechamentos30 = fechamentoFinanceiro9.get_Dados(); + decimal num25 = dadosFechamentos30.Sum((DadosFechamento t) => t.get_Debito()); + List lancamentos35 = lancamentos13; + IEnumerable lancamentos36 = lancamentos35.Where((Lancamento s) => { + if (s.get_Controle() == null) + { + return false; + } + return s.get_Sinal() == 1; + }); + num14 = (num25 / lancamentos36.Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault())) * new decimal(100); + } + dadosFechamento5.set_PercentualDebito(num14); + dadosFechamentos24.Add(dadosFechamento5); + this.Fechamento.Add(fechamentoFinanceiro9); + FechamentoFinanceiro fechamentoFinanceiro10 = new FechamentoFinanceiro(); + fechamentoFinanceiro10.set_Plano("TIPO PAGAMENTO"); + List lancamentos37 = lancamentos13; + IOrderedEnumerable description = + from x in lancamentos37 + orderby EnumHelper.GetDescription(x.get_TipoPagamento()) + select x; + fechamentoFinanceiro10.set_Dados(( + from x in description + group x by x.get_TipoPagamento()).Select, DadosFechamento>((IGrouping f) => { + decimal zero; + decimal num; + DadosFechamento dadosFechamento = new DadosFechamento(); + dadosFechamento.set_Planos(EnumHelper.GetDescription(f.First().get_TipoPagamento())); + IGrouping tipoPagamentos = f; + Func u003cu003e9_51248 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_248; + if (u003cu003e9_51248 == null) + { + u003cu003e9_51248 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_248 = u003cu003e9_51248; + } + IEnumerable lancamentos = tipoPagamentos.Where(u003cu003e9_51248); + Func u003cu003e9_51249 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_249; + if (u003cu003e9_51249 == null) + { + u003cu003e9_51249 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_249 = u003cu003e9_51249; + } + dadosFechamento.set_Credito(lancamentos.Sum(u003cu003e9_51249)); + IGrouping tipoPagamentos1 = f; + Func u003cu003e9_51250 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_250; + if (u003cu003e9_51250 == null) + { + u003cu003e9_51250 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_250 = u003cu003e9_51250; + } + IEnumerable lancamentos1 = tipoPagamentos1.Where(u003cu003e9_51250); + Func u003cu003e9_51251 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_251; + if (u003cu003e9_51251 == null) + { + u003cu003e9_51251 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_251 = u003cu003e9_51251; + } + if (lancamentos1.Sum(u003cu003e9_51251) == decimal.Zero) + { + zero = decimal.Zero; + } + else + { + IGrouping tipoPagamentos2 = f; + Func u003cu003e9_51252 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_252; + if (u003cu003e9_51252 == null) + { + u003cu003e9_51252 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_252 = u003cu003e9_51252; + } + IEnumerable lancamentos2 = tipoPagamentos2.Where(u003cu003e9_51252); + Func u003cu003e9_51253 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_253; + if (u003cu003e9_51253 == null) + { + u003cu003e9_51253 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_253 = u003cu003e9_51253; + } + decimal num1 = lancamentos2.Sum(u003cu003e9_51253); + List lancamentos3 = lancamentos13; + Func u003cu003e9_51254 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_254; + if (u003cu003e9_51254 == null) + { + u003cu003e9_51254 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_254 = u003cu003e9_51254; + } + IEnumerable lancamentos4 = lancamentos3.Where(u003cu003e9_51254); + Func u003cu003e9_51255 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_255; + if (u003cu003e9_51255 == null) + { + u003cu003e9_51255 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_255 = u003cu003e9_51255; + } + zero = (num1 / lancamentos4.Sum(u003cu003e9_51255)) * new decimal(100); + } + dadosFechamento.set_PercentualCredito(zero); + IGrouping tipoPagamentos3 = f; + Func u003cu003e9_51256 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_256; + if (u003cu003e9_51256 == null) + { + u003cu003e9_51256 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_256 = u003cu003e9_51256; + } + IEnumerable lancamentos5 = tipoPagamentos3.Where(u003cu003e9_51256); + Func u003cu003e9_51257 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_257; + if (u003cu003e9_51257 == null) + { + u003cu003e9_51257 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_257 = u003cu003e9_51257; + } + dadosFechamento.set_Debito(lancamentos5.Sum(u003cu003e9_51257)); + IGrouping tipoPagamentos4 = f; + Func u003cu003e9_51258 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_258; + if (u003cu003e9_51258 == null) + { + u003cu003e9_51258 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_258 = u003cu003e9_51258; + } + IEnumerable lancamentos6 = tipoPagamentos4.Where(u003cu003e9_51258); + Func u003cu003e9_51259 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_259; + if (u003cu003e9_51259 == null) + { + u003cu003e9_51259 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_259 = u003cu003e9_51259; + } + if (lancamentos6.Sum(u003cu003e9_51259) == decimal.Zero) + { + num = decimal.Zero; + } + else + { + IGrouping tipoPagamentos5 = f; + Func u003cu003e9_51260 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_260; + if (u003cu003e9_51260 == null) + { + u003cu003e9_51260 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_260 = u003cu003e9_51260; + } + IEnumerable lancamentos7 = tipoPagamentos5.Where(u003cu003e9_51260); + Func u003cu003e9_51261 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_261; + if (u003cu003e9_51261 == null) + { + u003cu003e9_51261 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_261 = u003cu003e9_51261; + } + decimal num2 = lancamentos7.Sum(u003cu003e9_51261); + List lancamentos8 = lancamentos13; + Func u003cu003e9_51262 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_262; + if (u003cu003e9_51262 == null) + { + u003cu003e9_51262 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_262 = u003cu003e9_51262; + } + IEnumerable lancamentos9 = lancamentos8.Where(u003cu003e9_51262); + Func u003cu003e9_51263 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_263; + if (u003cu003e9_51263 == null) + { + u003cu003e9_51263 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_263 = u003cu003e9_51263; + } + num = (num2 / lancamentos9.Sum(u003cu003e9_51263)) * new decimal(100); + } + dadosFechamento.set_PercentualDebito(num); + return dadosFechamento; + }).ToList()); + FechamentoFinanceiro fechamentoFinanceiro11 = fechamentoFinanceiro10; + List dadosFechamentos31 = fechamentoFinanceiro11.get_Dados(); + DadosFechamento dadosFechamento6 = new DadosFechamento(); + dadosFechamento6.set_Planos("TOTAL"); + List dadosFechamentos32 = fechamentoFinanceiro11.get_Dados(); + dadosFechamento6.set_Credito(dadosFechamentos32.Sum((DadosFechamento t) => t.get_Credito())); + List dadosFechamentos33 = fechamentoFinanceiro11.get_Dados(); + dadosFechamento6.set_Debito(dadosFechamentos33.Sum((DadosFechamento t) => t.get_Debito())); + List dadosFechamentos34 = fechamentoFinanceiro11.get_Dados(); + if (dadosFechamentos34.Sum((DadosFechamento t) => t.get_Credito()) == decimal.Zero) + { + num15 = decimal.Zero; + } + else + { + List dadosFechamentos35 = fechamentoFinanceiro11.get_Dados(); + decimal num26 = dadosFechamentos35.Sum((DadosFechamento t) => t.get_Credito()); + List lancamentos38 = lancamentos13; + IEnumerable sinal2 = + from s in lancamentos38 + where s.get_Sinal() == 0 + select s; + num15 = (num26 / sinal2.Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault())) * new decimal(100); + } + dadosFechamento6.set_PercentualCredito(num15); + List dadosFechamentos36 = fechamentoFinanceiro11.get_Dados(); + if (dadosFechamentos36.Sum((DadosFechamento t) => t.get_Debito()) == decimal.Zero) + { + num16 = decimal.Zero; + } + else + { + List dadosFechamentos37 = fechamentoFinanceiro11.get_Dados(); + decimal num27 = dadosFechamentos37.Sum((DadosFechamento t) => t.get_Debito()); + List lancamentos39 = lancamentos13; + IEnumerable sinal3 = + from s in lancamentos39 + where s.get_Sinal() == 1 + select s; + num16 = (num27 / sinal3.Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault())) * new decimal(100); + } + dadosFechamento6.set_PercentualDebito(num16); + List dadosFechamentos38 = fechamentoFinanceiro11.get_Dados(); + decimal num28 = dadosFechamentos38.Sum((DadosFechamento t) => t.get_Credito()); + List dadosFechamentos39 = fechamentoFinanceiro11.get_Dados(); + dadosFechamento6.set_Soma(num28 - dadosFechamentos39.Sum((DadosFechamento t) => t.get_Debito())); + List dadosFechamentos40 = fechamentoFinanceiro11.get_Dados(); + decimal num29 = dadosFechamentos40.Sum((DadosFechamento t) => t.get_Credito()); + List dadosFechamentos41 = fechamentoFinanceiro11.get_Dados(); + if ((num29 + dadosFechamentos41.Sum((DadosFechamento t) => t.get_Debito())) == decimal.Zero) + { + num17 = decimal.Zero; + } + else + { + List dadosFechamentos42 = fechamentoFinanceiro11.get_Dados(); + decimal num30 = dadosFechamentos42.Sum((DadosFechamento t) => t.get_Credito()); + List dadosFechamentos43 = fechamentoFinanceiro11.get_Dados(); + decimal num31 = (num30 - dadosFechamentos43.Sum((DadosFechamento t) => t.get_Debito())) * new decimal(100); + List dadosFechamentos44 = fechamentoFinanceiro11.get_Dados(); + decimal num32 = dadosFechamentos44.Sum((DadosFechamento t) => t.get_Credito()); + List dadosFechamentos45 = fechamentoFinanceiro11.get_Dados(); + num17 = num31 / (num32 + dadosFechamentos45.Sum((DadosFechamento t) => t.get_Debito())); + } + dadosFechamento6.set_SomaPercentual(num17); + dadosFechamentos31.Add(dadosFechamento6); + this.Fechamento.Add(fechamentoFinanceiro11); + } + else + { + this.FechamentoAnalitico = new List(); + List lancamentos40 = lancamentos13; + IEnumerable lancamentos41 = lancamentos40.Where((Lancamento x) => { + object plano; + ControleFinanceiro controle = x.get_Controle(); + if (controle != null) + { + plano = controle.get_Plano(); + } + else + { + plano = null; + } + return plano != null; + }); + IOrderedEnumerable nome1 = + from x in lancamentos41 + orderby x.get_Controle().get_Plano().get_Nome() + select x; + ( + from x in nome1 + group x by x.get_Controle().get_Plano().get_Plano().get_Id()).ToList>().ForEach((IGrouping x) => { + FechamentoFinanceiroAnalitico fechamentoFinanceiroAnalitico = new FechamentoFinanceiroAnalitico(); + fechamentoFinanceiroAnalitico.set_NomeConta(x.First().get_Controle().get_Plano().get_Plano().get_Descricao().ToUpper()); + IGrouping nums19 = x; + Func u003cu003e9_5112 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_12; + if (u003cu003e9_5112 == null) + { + u003cu003e9_5112 = (Lancamento f) => f.get_Controle().get_Plano().get_Id(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_12 = u003cu003e9_5112; + } + IOrderedEnumerable lancamentos12 = nums19.OrderBy(u003cu003e9_5112); + Func u003cu003e9_5113 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_13; + if (u003cu003e9_5113 == null) + { + u003cu003e9_5113 = (Lancamento f) => f.get_Controle().get_Plano().get_Id(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_13 = u003cu003e9_5113; + } + fechamentoFinanceiroAnalitico.set_Dados(lancamentos12.GroupBy(u003cu003e9_5113).Select, DadosFechamentoAnalitico>((IGrouping f) => { + Func func; + decimal zero; + decimal zero1; + DadosFechamentoAnalitico dadosFechamentoAnalitico = new DadosFechamentoAnalitico(); + dadosFechamentoAnalitico.set_Nome(f.First().get_Controle().get_Plano().get_Descricao()); + IGrouping nums = f; + Func u003cu003e9_15 = func8; + if (u003cu003e9_15 == null) + { + Func cSu0024u003cu003e8_locals11 = (Lancamento s) => { + DateTime? baixa = s.get_Baixa(); + DateTime inicio = filtroFinanceiro1.get_Inicio(); + DateTime dateTime = new DateTime(inicio.Year, 1, 1); + if ((baixa.HasValue ? baixa.GetValueOrDefault() < dateTime : true)) + { + return false; + } + baixa = s.get_Baixa(); + inicio = filtroFinanceiro1.get_Inicio(); + dateTime = new DateTime(inicio.Year, 1, 31); + if (!baixa.HasValue) + { + return false; + } + return baixa.GetValueOrDefault() <= dateTime; + }; + func = cSu0024u003cu003e8_locals11; + func8 = cSu0024u003cu003e8_locals11; + u003cu003e9_15 = func; + } + List list = nums.Where(u003cu003e9_15).ToList(); + Func u003cu003e9_5116 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_16; + if (u003cu003e9_5116 == null) + { + u003cu003e9_5116 = (Lancamento s) => { + if (s.get_Sinal() != 1) + { + return s.get_ValorPago(); + } + decimal? valorPago = s.get_ValorPago(); + decimal num = 2; + decimal? nullable = s.get_ValorPago(); + decimal? nullable1 = (nullable.HasValue ? new decimal?(num * nullable.GetValueOrDefault()) : null); + if (!valorPago.HasValue | !nullable1.HasValue) + { + nullable = null; + return nullable; + } + return new decimal?(valorPago.GetValueOrDefault() - nullable1.GetValueOrDefault()); + }; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_16 = u003cu003e9_5116; + } + dadosFechamentoAnalitico.set_Jan(list.Sum(u003cu003e9_5116)); + IGrouping nums1 = f; + Func u003cu003e9_17 = func9; + if (u003cu003e9_17 == null) + { + Func func1 = (Lancamento s) => { + DateTime? baixa = s.get_Baixa(); + DateTime inicio = filtroFinanceiro1.get_Inicio(); + DateTime dateTime = new DateTime(inicio.Year, 2, 1); + if ((baixa.HasValue ? baixa.GetValueOrDefault() < dateTime : true)) + { + return false; + } + baixa = s.get_Baixa(); + int year = filtroFinanceiro1.get_Inicio().Year; + inicio = filtroFinanceiro1.get_Inicio(); + dateTime = new DateTime(year, 2, DateTime.DaysInMonth(inicio.Year, 2)); + if (!baixa.HasValue) + { + return false; + } + return baixa.GetValueOrDefault() <= dateTime; + }; + func = func1; + func9 = func1; + u003cu003e9_17 = func; + } + List lancamentos = nums1.Where(u003cu003e9_17).ToList(); + Func u003cu003e9_5118 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_18; + if (u003cu003e9_5118 == null) + { + u003cu003e9_5118 = (Lancamento s) => { + if (s.get_Sinal() != 1) + { + return s.get_ValorPago(); + } + decimal? valorPago = s.get_ValorPago(); + decimal num = 2; + decimal? nullable = s.get_ValorPago(); + decimal? nullable1 = (nullable.HasValue ? new decimal?(num * nullable.GetValueOrDefault()) : null); + if (!valorPago.HasValue | !nullable1.HasValue) + { + nullable = null; + return nullable; + } + return new decimal?(valorPago.GetValueOrDefault() - nullable1.GetValueOrDefault()); + }; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_18 = u003cu003e9_5118; + } + dadosFechamentoAnalitico.set_Fev(lancamentos.Sum(u003cu003e9_5118)); + IGrouping nums2 = f; + Func u003cu003e9_19 = func10; + if (u003cu003e9_19 == null) + { + Func cSu0024u003cu003e8_locals12 = (Lancamento s) => { + DateTime? baixa = s.get_Baixa(); + DateTime inicio = filtroFinanceiro1.get_Inicio(); + DateTime dateTime = new DateTime(inicio.Year, 3, 1); + if ((baixa.HasValue ? baixa.GetValueOrDefault() < dateTime : true)) + { + return false; + } + baixa = s.get_Baixa(); + inicio = filtroFinanceiro1.get_Inicio(); + dateTime = new DateTime(inicio.Year, 3, 31); + if (!baixa.HasValue) + { + return false; + } + return baixa.GetValueOrDefault() <= dateTime; + }; + func = cSu0024u003cu003e8_locals12; + func10 = cSu0024u003cu003e8_locals12; + u003cu003e9_19 = func; + } + List list1 = nums2.Where(u003cu003e9_19).ToList(); + Func u003cu003e9_5120 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_20; + if (u003cu003e9_5120 == null) + { + u003cu003e9_5120 = (Lancamento s) => { + if (s.get_Sinal() != 1) + { + return s.get_ValorPago(); + } + decimal? valorPago = s.get_ValorPago(); + decimal num = 2; + decimal? nullable = s.get_ValorPago(); + decimal? nullable1 = (nullable.HasValue ? new decimal?(num * nullable.GetValueOrDefault()) : null); + if (!valorPago.HasValue | !nullable1.HasValue) + { + nullable = null; + return nullable; + } + return new decimal?(valorPago.GetValueOrDefault() - nullable1.GetValueOrDefault()); + }; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_20 = u003cu003e9_5120; + } + dadosFechamentoAnalitico.set_Mar(list1.Sum(u003cu003e9_5120)); + IGrouping nums3 = f; + Func u003cu003e9_21 = func11; + if (u003cu003e9_21 == null) + { + Func func2 = (Lancamento s) => { + DateTime? baixa = s.get_Baixa(); + DateTime inicio = filtroFinanceiro1.get_Inicio(); + DateTime dateTime = new DateTime(inicio.Year, 4, 1); + if ((baixa.HasValue ? baixa.GetValueOrDefault() < dateTime : true)) + { + return false; + } + baixa = s.get_Baixa(); + inicio = filtroFinanceiro1.get_Inicio(); + dateTime = new DateTime(inicio.Year, 4, 30); + if (!baixa.HasValue) + { + return false; + } + return baixa.GetValueOrDefault() <= dateTime; + }; + func = func2; + func11 = func2; + u003cu003e9_21 = func; + } + List lancamentos1 = nums3.Where(u003cu003e9_21).ToList(); + Func u003cu003e9_5122 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_22; + if (u003cu003e9_5122 == null) + { + u003cu003e9_5122 = (Lancamento s) => { + if (s.get_Sinal() != 1) + { + return s.get_ValorPago(); + } + decimal? valorPago = s.get_ValorPago(); + decimal num = 2; + decimal? nullable = s.get_ValorPago(); + decimal? nullable1 = (nullable.HasValue ? new decimal?(num * nullable.GetValueOrDefault()) : null); + if (!valorPago.HasValue | !nullable1.HasValue) + { + nullable = null; + return nullable; + } + return new decimal?(valorPago.GetValueOrDefault() - nullable1.GetValueOrDefault()); + }; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_22 = u003cu003e9_5122; + } + dadosFechamentoAnalitico.set_Abr(lancamentos1.Sum(u003cu003e9_5122)); + IGrouping nums4 = f; + Func u003cu003e9_23 = func12; + if (u003cu003e9_23 == null) + { + Func func3 = (Lancamento s) => { + DateTime? baixa = s.get_Baixa(); + DateTime inicio = filtroFinanceiro1.get_Inicio(); + DateTime dateTime = new DateTime(inicio.Year, 5, 1); + if ((baixa.HasValue ? baixa.GetValueOrDefault() < dateTime : true)) + { + return false; + } + baixa = s.get_Baixa(); + inicio = filtroFinanceiro1.get_Inicio(); + dateTime = new DateTime(inicio.Year, 5, 31); + if (!baixa.HasValue) + { + return false; + } + return baixa.GetValueOrDefault() <= dateTime; + }; + func = func3; + func12 = func3; + u003cu003e9_23 = func; + } + List list2 = nums4.Where(u003cu003e9_23).ToList(); + Func u003cu003e9_5124 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_24; + if (u003cu003e9_5124 == null) + { + u003cu003e9_5124 = (Lancamento s) => { + if (s.get_Sinal() != 1) + { + return s.get_ValorPago(); + } + decimal? valorPago = s.get_ValorPago(); + decimal num = 2; + decimal? nullable = s.get_ValorPago(); + decimal? nullable1 = (nullable.HasValue ? new decimal?(num * nullable.GetValueOrDefault()) : null); + if (!valorPago.HasValue | !nullable1.HasValue) + { + nullable = null; + return nullable; + } + return new decimal?(valorPago.GetValueOrDefault() - nullable1.GetValueOrDefault()); + }; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_24 = u003cu003e9_5124; + } + dadosFechamentoAnalitico.set_Mai(list2.Sum(u003cu003e9_5124)); + IGrouping nums5 = f; + Func u003cu003e9_25 = func13; + if (u003cu003e9_25 == null) + { + Func cSu0024u003cu003e8_locals14 = (Lancamento s) => { + DateTime? baixa = s.get_Baixa(); + DateTime inicio = filtroFinanceiro1.get_Inicio(); + DateTime dateTime = new DateTime(inicio.Year, 6, 1); + if ((baixa.HasValue ? baixa.GetValueOrDefault() < dateTime : true)) + { + return false; + } + baixa = s.get_Baixa(); + inicio = filtroFinanceiro1.get_Inicio(); + dateTime = new DateTime(inicio.Year, 6, 30); + if (!baixa.HasValue) + { + return false; + } + return baixa.GetValueOrDefault() <= dateTime; + }; + func = cSu0024u003cu003e8_locals14; + func13 = cSu0024u003cu003e8_locals14; + u003cu003e9_25 = func; + } + List lancamentos2 = nums5.Where(u003cu003e9_25).ToList(); + Func u003cu003e9_5126 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_26; + if (u003cu003e9_5126 == null) + { + u003cu003e9_5126 = (Lancamento s) => { + if (s.get_Sinal() != 1) + { + return s.get_ValorPago(); + } + decimal? valorPago = s.get_ValorPago(); + decimal num = 2; + decimal? nullable = s.get_ValorPago(); + decimal? nullable1 = (nullable.HasValue ? new decimal?(num * nullable.GetValueOrDefault()) : null); + if (!valorPago.HasValue | !nullable1.HasValue) + { + nullable = null; + return nullable; + } + return new decimal?(valorPago.GetValueOrDefault() - nullable1.GetValueOrDefault()); + }; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_26 = u003cu003e9_5126; + } + dadosFechamentoAnalitico.set_Jun(lancamentos2.Sum(u003cu003e9_5126)); + IGrouping nums6 = f; + Func u003cu003e9_27 = func14; + if (u003cu003e9_27 == null) + { + Func func4 = (Lancamento s) => { + DateTime? baixa = s.get_Baixa(); + DateTime inicio = filtroFinanceiro1.get_Inicio(); + DateTime dateTime = new DateTime(inicio.Year, 7, 1); + if ((baixa.HasValue ? baixa.GetValueOrDefault() < dateTime : true)) + { + return false; + } + baixa = s.get_Baixa(); + inicio = filtroFinanceiro1.get_Inicio(); + dateTime = new DateTime(inicio.Year, 7, 31); + if (!baixa.HasValue) + { + return false; + } + return baixa.GetValueOrDefault() <= dateTime; + }; + func = func4; + func14 = func4; + u003cu003e9_27 = func; + } + List list3 = nums6.Where(u003cu003e9_27).ToList(); + Func u003cu003e9_5128 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_28; + if (u003cu003e9_5128 == null) + { + u003cu003e9_5128 = (Lancamento s) => { + if (s.get_Sinal() != 1) + { + return s.get_ValorPago(); + } + decimal? valorPago = s.get_ValorPago(); + decimal num = 2; + decimal? nullable = s.get_ValorPago(); + decimal? nullable1 = (nullable.HasValue ? new decimal?(num * nullable.GetValueOrDefault()) : null); + if (!valorPago.HasValue | !nullable1.HasValue) + { + nullable = null; + return nullable; + } + return new decimal?(valorPago.GetValueOrDefault() - nullable1.GetValueOrDefault()); + }; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_28 = u003cu003e9_5128; + } + dadosFechamentoAnalitico.set_Jul(list3.Sum(u003cu003e9_5128)); + IGrouping nums7 = f; + Func u003cu003e9_29 = func15; + if (u003cu003e9_29 == null) + { + Func func5 = (Lancamento s) => { + DateTime? baixa = s.get_Baixa(); + DateTime inicio = filtroFinanceiro1.get_Inicio(); + DateTime dateTime = new DateTime(inicio.Year, 8, 1); + if ((baixa.HasValue ? baixa.GetValueOrDefault() < dateTime : true)) + { + return false; + } + baixa = s.get_Baixa(); + inicio = filtroFinanceiro1.get_Inicio(); + dateTime = new DateTime(inicio.Year, 8, 31); + if (!baixa.HasValue) + { + return false; + } + return baixa.GetValueOrDefault() <= dateTime; + }; + func = func5; + func15 = func5; + u003cu003e9_29 = func; + } + List lancamentos3 = nums7.Where(u003cu003e9_29).ToList(); + Func u003cu003e9_5130 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_30; + if (u003cu003e9_5130 == null) + { + u003cu003e9_5130 = (Lancamento s) => { + if (s.get_Sinal() != 1) + { + return s.get_ValorPago(); + } + decimal? valorPago = s.get_ValorPago(); + decimal num = 2; + decimal? nullable = s.get_ValorPago(); + decimal? nullable1 = (nullable.HasValue ? new decimal?(num * nullable.GetValueOrDefault()) : null); + if (!valorPago.HasValue | !nullable1.HasValue) + { + nullable = null; + return nullable; + } + return new decimal?(valorPago.GetValueOrDefault() - nullable1.GetValueOrDefault()); + }; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_30 = u003cu003e9_5130; + } + dadosFechamentoAnalitico.set_Ago(lancamentos3.Sum(u003cu003e9_5130)); + IGrouping nums8 = f; + Func u003cu003e9_31 = func16; + if (u003cu003e9_31 == null) + { + Func cSu0024u003cu003e8_locals16 = (Lancamento s) => { + DateTime? baixa = s.get_Baixa(); + DateTime inicio = filtroFinanceiro1.get_Inicio(); + DateTime dateTime = new DateTime(inicio.Year, 9, 1); + if ((baixa.HasValue ? baixa.GetValueOrDefault() < dateTime : true)) + { + return false; + } + baixa = s.get_Baixa(); + inicio = filtroFinanceiro1.get_Inicio(); + dateTime = new DateTime(inicio.Year, 9, 30); + if (!baixa.HasValue) + { + return false; + } + return baixa.GetValueOrDefault() <= dateTime; + }; + func = cSu0024u003cu003e8_locals16; + func16 = cSu0024u003cu003e8_locals16; + u003cu003e9_31 = func; + } + List list4 = nums8.Where(u003cu003e9_31).ToList(); + Func u003cu003e9_5132 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_32; + if (u003cu003e9_5132 == null) + { + u003cu003e9_5132 = (Lancamento s) => { + if (s.get_Sinal() != 1) + { + return s.get_ValorPago(); + } + decimal? valorPago = s.get_ValorPago(); + decimal num = 2; + decimal? nullable = s.get_ValorPago(); + decimal? nullable1 = (nullable.HasValue ? new decimal?(num * nullable.GetValueOrDefault()) : null); + if (!valorPago.HasValue | !nullable1.HasValue) + { + nullable = null; + return nullable; + } + return new decimal?(valorPago.GetValueOrDefault() - nullable1.GetValueOrDefault()); + }; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_32 = u003cu003e9_5132; + } + dadosFechamentoAnalitico.set_Set(list4.Sum(u003cu003e9_5132)); + IGrouping nums9 = f; + Func u003cu003e9_33 = func17; + if (u003cu003e9_33 == null) + { + Func func6 = (Lancamento s) => { + DateTime? baixa = s.get_Baixa(); + DateTime inicio = filtroFinanceiro1.get_Inicio(); + DateTime dateTime = new DateTime(inicio.Year, 10, 1); + if ((baixa.HasValue ? baixa.GetValueOrDefault() < dateTime : true)) + { + return false; + } + baixa = s.get_Baixa(); + inicio = filtroFinanceiro1.get_Inicio(); + dateTime = new DateTime(inicio.Year, 10, 31); + if (!baixa.HasValue) + { + return false; + } + return baixa.GetValueOrDefault() <= dateTime; + }; + func = func6; + func17 = func6; + u003cu003e9_33 = func; + } + List lancamentos4 = nums9.Where(u003cu003e9_33).ToList(); + Func u003cu003e9_5134 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_34; + if (u003cu003e9_5134 == null) + { + u003cu003e9_5134 = (Lancamento s) => { + if (s.get_Sinal() != 1) + { + return s.get_ValorPago(); + } + decimal? valorPago = s.get_ValorPago(); + decimal num = 2; + decimal? nullable = s.get_ValorPago(); + decimal? nullable1 = (nullable.HasValue ? new decimal?(num * nullable.GetValueOrDefault()) : null); + if (!valorPago.HasValue | !nullable1.HasValue) + { + nullable = null; + return nullable; + } + return new decimal?(valorPago.GetValueOrDefault() - nullable1.GetValueOrDefault()); + }; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_34 = u003cu003e9_5134; + } + dadosFechamentoAnalitico.set_Out(lancamentos4.Sum(u003cu003e9_5134)); + IGrouping nums10 = f; + Func u003cu003e9_35 = func18; + if (u003cu003e9_35 == null) + { + Func func7 = (Lancamento s) => { + DateTime? baixa = s.get_Baixa(); + DateTime inicio = filtroFinanceiro1.get_Inicio(); + DateTime dateTime = new DateTime(inicio.Year, 11, 1); + if ((baixa.HasValue ? baixa.GetValueOrDefault() < dateTime : true)) + { + return false; + } + baixa = s.get_Baixa(); + inicio = filtroFinanceiro1.get_Inicio(); + dateTime = new DateTime(inicio.Year, 11, 30); + if (!baixa.HasValue) + { + return false; + } + return baixa.GetValueOrDefault() <= dateTime; + }; + func = func7; + func18 = func7; + u003cu003e9_35 = func; + } + List list5 = nums10.Where(u003cu003e9_35).ToList(); + Func u003cu003e9_5136 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_36; + if (u003cu003e9_5136 == null) + { + u003cu003e9_5136 = (Lancamento s) => { + if (s.get_Sinal() != 1) + { + return s.get_ValorPago(); + } + decimal? valorPago = s.get_ValorPago(); + decimal num = 2; + decimal? nullable = s.get_ValorPago(); + decimal? nullable1 = (nullable.HasValue ? new decimal?(num * nullable.GetValueOrDefault()) : null); + if (!valorPago.HasValue | !nullable1.HasValue) + { + nullable = null; + return nullable; + } + return new decimal?(valorPago.GetValueOrDefault() - nullable1.GetValueOrDefault()); + }; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_36 = u003cu003e9_5136; + } + dadosFechamentoAnalitico.set_Nov(list5.Sum(u003cu003e9_5136)); + IGrouping nums11 = f; + Func u003cu003e9_37 = func19; + if (u003cu003e9_37 == null) + { + Func cSu0024u003cu003e8_locals18 = (Lancamento s) => { + DateTime? baixa = s.get_Baixa(); + DateTime inicio = filtroFinanceiro1.get_Inicio(); + DateTime dateTime = new DateTime(inicio.Year, 12, 1); + if ((baixa.HasValue ? baixa.GetValueOrDefault() < dateTime : true)) + { + return false; + } + baixa = s.get_Baixa(); + inicio = filtroFinanceiro1.get_Inicio(); + dateTime = new DateTime(inicio.Year, 12, 31); + if (!baixa.HasValue) + { + return false; + } + return baixa.GetValueOrDefault() <= dateTime; + }; + func = cSu0024u003cu003e8_locals18; + func19 = cSu0024u003cu003e8_locals18; + u003cu003e9_37 = func; + } + List lancamentos5 = nums11.Where(u003cu003e9_37).ToList(); + Func u003cu003e9_5138 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_38; + if (u003cu003e9_5138 == null) + { + u003cu003e9_5138 = (Lancamento s) => { + if (s.get_Sinal() != 1) + { + return s.get_ValorPago(); + } + decimal? valorPago = s.get_ValorPago(); + decimal num = 2; + decimal? nullable = s.get_ValorPago(); + decimal? nullable1 = (nullable.HasValue ? new decimal?(num * nullable.GetValueOrDefault()) : null); + if (!valorPago.HasValue | !nullable1.HasValue) + { + nullable = null; + return nullable; + } + return new decimal?(valorPago.GetValueOrDefault() - nullable1.GetValueOrDefault()); + }; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_38 = u003cu003e9_5138; + } + dadosFechamentoAnalitico.set_Dez(lancamentos5.Sum(u003cu003e9_5138)); + IGrouping nums12 = f; + Func u003cu003e9_5139 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_39; + if (u003cu003e9_5139 == null) + { + u003cu003e9_5139 = (Lancamento s) => { + if (s.get_Sinal() != 1) + { + return s.get_ValorPago(); + } + decimal? valorPago = s.get_ValorPago(); + decimal num = 2; + decimal? nullable = s.get_ValorPago(); + decimal? nullable1 = (nullable.HasValue ? new decimal?(num * nullable.GetValueOrDefault()) : null); + if (!valorPago.HasValue | !nullable1.HasValue) + { + nullable = null; + return nullable; + } + return new decimal?(valorPago.GetValueOrDefault() - nullable1.GetValueOrDefault()); + }; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_39 = u003cu003e9_5139; + } + dadosFechamentoAnalitico.set_Total(nums12.Sum(u003cu003e9_5139)); + IGrouping nums13 = f; + Func u003cu003e9_5140 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_40; + if (u003cu003e9_5140 == null) + { + u003cu003e9_5140 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_40 = u003cu003e9_5140; + } + IEnumerable lancamentos6 = nums13.Where(u003cu003e9_5140); + Func u003cu003e9_5141 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_41; + if (u003cu003e9_5141 == null) + { + u003cu003e9_5141 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_41 = u003cu003e9_5141; + } + if (lancamentos6.Sum(u003cu003e9_5141) == decimal.Zero) + { + zero = decimal.Zero; + } + else + { + IGrouping nums14 = f; + Func u003cu003e9_5142 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_42; + if (u003cu003e9_5142 == null) + { + u003cu003e9_5142 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_42 = u003cu003e9_5142; + } + IEnumerable lancamentos7 = nums14.Where(u003cu003e9_5142); + Func u003cu003e9_5143 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_43; + if (u003cu003e9_5143 == null) + { + u003cu003e9_5143 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_43 = u003cu003e9_5143; + } + decimal num1 = lancamentos7.Sum(u003cu003e9_5143); + IGrouping nums15 = x; + Func u003cu003e9_5144 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_44; + if (u003cu003e9_5144 == null) + { + u003cu003e9_5144 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_44 = u003cu003e9_5144; + } + IEnumerable lancamentos8 = nums15.Where(u003cu003e9_5144); + Func u003cu003e9_5145 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_45; + if (u003cu003e9_5145 == null) + { + u003cu003e9_5145 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_45 = u003cu003e9_5145; + } + zero = (num1 / lancamentos8.Sum(u003cu003e9_5145)) * new decimal(100); + } + dadosFechamentoAnalitico.set_PercentualCredito(zero); + IGrouping nums16 = f; + Func u003cu003e9_5146 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_46; + if (u003cu003e9_5146 == null) + { + u003cu003e9_5146 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_46 = u003cu003e9_5146; + } + IEnumerable lancamentos9 = nums16.Where(u003cu003e9_5146); + Func u003cu003e9_5147 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_47; + if (u003cu003e9_5147 == null) + { + u003cu003e9_5147 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_47 = u003cu003e9_5147; + } + if (lancamentos9.Sum(u003cu003e9_5147) == decimal.Zero) + { + zero1 = decimal.Zero; + } + else + { + IGrouping nums17 = f; + Func u003cu003e9_5148 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_48; + if (u003cu003e9_5148 == null) + { + u003cu003e9_5148 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_48 = u003cu003e9_5148; + } + IEnumerable lancamentos10 = nums17.Where(u003cu003e9_5148); + Func u003cu003e9_5149 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_49; + if (u003cu003e9_5149 == null) + { + u003cu003e9_5149 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_49 = u003cu003e9_5149; + } + decimal num2 = lancamentos10.Sum(u003cu003e9_5149); + IGrouping nums18 = x; + Func u003cu003e9_5150 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_50; + if (u003cu003e9_5150 == null) + { + u003cu003e9_5150 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_50 = u003cu003e9_5150; + } + IEnumerable lancamentos11 = nums18.Where(u003cu003e9_5150); + Func u003cu003e9_5151 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_51; + if (u003cu003e9_5151 == null) + { + u003cu003e9_5151 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_51 = u003cu003e9_5151; + } + zero1 = (num2 / lancamentos11.Sum(u003cu003e9_5151)) * new decimal(100); + } + dadosFechamentoAnalitico.set_PercentualDebito(zero1); + return dadosFechamentoAnalitico; + }).ToList()); + FechamentoFinanceiroAnalitico fechamentoFinanceiroAnalitico1 = fechamentoFinanceiroAnalitico; + List dados = fechamentoFinanceiroAnalitico1.get_Dados(); + DadosFechamentoAnalitico dadosFechamentoAnalitico1 = new DadosFechamentoAnalitico(); + dadosFechamentoAnalitico1.set_Nome("TOTAL"); + List dadosFechamentoAnaliticos = fechamentoFinanceiroAnalitico1.get_Dados(); + Func u003cu003e9_5152 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_52; + if (u003cu003e9_5152 == null) + { + u003cu003e9_5152 = (DadosFechamentoAnalitico t) => t.get_Jan(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_52 = u003cu003e9_5152; + } + dadosFechamentoAnalitico1.set_Jan(dadosFechamentoAnaliticos.Sum(u003cu003e9_5152)); + List dados1 = fechamentoFinanceiroAnalitico1.get_Dados(); + Func u003cu003e9_5153 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_53; + if (u003cu003e9_5153 == null) + { + u003cu003e9_5153 = (DadosFechamentoAnalitico t) => t.get_Fev(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_53 = u003cu003e9_5153; + } + dadosFechamentoAnalitico1.set_Fev(dados1.Sum(u003cu003e9_5153)); + List dadosFechamentoAnaliticos1 = fechamentoFinanceiroAnalitico1.get_Dados(); + Func u003cu003e9_5154 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_54; + if (u003cu003e9_5154 == null) + { + u003cu003e9_5154 = (DadosFechamentoAnalitico t) => t.get_Mar(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_54 = u003cu003e9_5154; + } + dadosFechamentoAnalitico1.set_Mar(dadosFechamentoAnaliticos1.Sum(u003cu003e9_5154)); + List dados2 = fechamentoFinanceiroAnalitico1.get_Dados(); + Func u003cu003e9_5155 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_55; + if (u003cu003e9_5155 == null) + { + u003cu003e9_5155 = (DadosFechamentoAnalitico t) => t.get_Abr(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_55 = u003cu003e9_5155; + } + dadosFechamentoAnalitico1.set_Abr(dados2.Sum(u003cu003e9_5155)); + List dadosFechamentoAnaliticos2 = fechamentoFinanceiroAnalitico1.get_Dados(); + Func u003cu003e9_5156 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_56; + if (u003cu003e9_5156 == null) + { + u003cu003e9_5156 = (DadosFechamentoAnalitico t) => t.get_Mai(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_56 = u003cu003e9_5156; + } + dadosFechamentoAnalitico1.set_Mai(dadosFechamentoAnaliticos2.Sum(u003cu003e9_5156)); + List dados3 = fechamentoFinanceiroAnalitico1.get_Dados(); + Func u003cu003e9_5157 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_57; + if (u003cu003e9_5157 == null) + { + u003cu003e9_5157 = (DadosFechamentoAnalitico t) => t.get_Jun(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_57 = u003cu003e9_5157; + } + dadosFechamentoAnalitico1.set_Jun(dados3.Sum(u003cu003e9_5157)); + List dadosFechamentoAnaliticos3 = fechamentoFinanceiroAnalitico1.get_Dados(); + Func u003cu003e9_5158 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_58; + if (u003cu003e9_5158 == null) + { + u003cu003e9_5158 = (DadosFechamentoAnalitico t) => t.get_Jul(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_58 = u003cu003e9_5158; + } + dadosFechamentoAnalitico1.set_Jul(dadosFechamentoAnaliticos3.Sum(u003cu003e9_5158)); + List dados4 = fechamentoFinanceiroAnalitico1.get_Dados(); + Func u003cu003e9_5159 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_59; + if (u003cu003e9_5159 == null) + { + u003cu003e9_5159 = (DadosFechamentoAnalitico t) => t.get_Ago(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_59 = u003cu003e9_5159; + } + dadosFechamentoAnalitico1.set_Ago(dados4.Sum(u003cu003e9_5159)); + List dadosFechamentoAnaliticos4 = fechamentoFinanceiroAnalitico1.get_Dados(); + Func u003cu003e9_5160 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_60; + if (u003cu003e9_5160 == null) + { + u003cu003e9_5160 = (DadosFechamentoAnalitico t) => t.get_Set(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_60 = u003cu003e9_5160; + } + dadosFechamentoAnalitico1.set_Set(dadosFechamentoAnaliticos4.Sum(u003cu003e9_5160)); + List dados5 = fechamentoFinanceiroAnalitico1.get_Dados(); + Func u003cu003e9_5161 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_61; + if (u003cu003e9_5161 == null) + { + u003cu003e9_5161 = (DadosFechamentoAnalitico t) => t.get_Out(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_61 = u003cu003e9_5161; + } + dadosFechamentoAnalitico1.set_Out(dados5.Sum(u003cu003e9_5161)); + List dadosFechamentoAnaliticos5 = fechamentoFinanceiroAnalitico1.get_Dados(); + Func u003cu003e9_5162 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_62; + if (u003cu003e9_5162 == null) + { + u003cu003e9_5162 = (DadosFechamentoAnalitico t) => t.get_Nov(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_62 = u003cu003e9_5162; + } + dadosFechamentoAnalitico1.set_Nov(dadosFechamentoAnaliticos5.Sum(u003cu003e9_5162)); + List dados6 = fechamentoFinanceiroAnalitico1.get_Dados(); + Func u003cu003e9_5163 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_63; + if (u003cu003e9_5163 == null) + { + u003cu003e9_5163 = (DadosFechamentoAnalitico t) => t.get_Dez(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_63 = u003cu003e9_5163; + } + dadosFechamentoAnalitico1.set_Dez(dados6.Sum(u003cu003e9_5163)); + List dadosFechamentoAnaliticos6 = fechamentoFinanceiroAnalitico1.get_Dados(); + Func u003cu003e9_5164 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_64; + if (u003cu003e9_5164 == null) + { + u003cu003e9_5164 = (DadosFechamentoAnalitico t) => t.get_Total(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_64 = u003cu003e9_5164; + } + dadosFechamentoAnalitico1.set_Total(dadosFechamentoAnaliticos6.Sum(u003cu003e9_5164)); + List dados7 = fechamentoFinanceiroAnalitico1.get_Dados(); + Func u003cu003e9_5165 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_65; + if (u003cu003e9_5165 == null) + { + u003cu003e9_5165 = (DadosFechamentoAnalitico t) => t.get_PercentualCredito(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_65 = u003cu003e9_5165; + } + dadosFechamentoAnalitico1.set_PercentualCredito(dados7.Sum(u003cu003e9_5165)); + List dadosFechamentoAnaliticos7 = fechamentoFinanceiroAnalitico1.get_Dados(); + Func u003cu003e9_5166 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_66; + if (u003cu003e9_5166 == null) + { + u003cu003e9_5166 = (DadosFechamentoAnalitico t) => t.get_PercentualDebito(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_66 = u003cu003e9_5166; + } + dadosFechamentoAnalitico1.set_PercentualDebito(dadosFechamentoAnaliticos7.Sum(u003cu003e9_5166)); + dados.Add(dadosFechamentoAnalitico1); + this.FechamentoAnalitico.Add(fechamentoFinanceiroAnalitico1); + }); + FechamentoFinanceiroAnalitico fechamentoFinanceiroAnalitico2 = new FechamentoFinanceiroAnalitico(); + fechamentoFinanceiroAnalitico2.set_NomeConta("TOTAL NO PERÍODO"); + fechamentoFinanceiroAnalitico2.set_Dados(new List()); + FechamentoFinanceiroAnalitico fechamentoFinanceiroAnalitico3 = fechamentoFinanceiroAnalitico2; + List dadosFechamentoAnaliticos8 = fechamentoFinanceiroAnalitico3.get_Dados(); + DadosFechamentoAnalitico dadosFechamentoAnalitico2 = new DadosFechamentoAnalitico(); + dadosFechamentoAnalitico2.set_Nome("TOTAL"); + List fechamentoAnalitico = this.FechamentoAnalitico; + dadosFechamentoAnalitico2.set_Jan(fechamentoAnalitico.Sum((FechamentoFinanceiroAnalitico x) => x.get_Dados().Sum((DadosFechamentoAnalitico y) => { + if (y.get_Nome() != "TOTAL") + { + return y.get_Jan(); + } + return new decimal?(new decimal()); + }))); + List fechamentoFinanceiroAnaliticos = this.FechamentoAnalitico; + dadosFechamentoAnalitico2.set_Fev(fechamentoFinanceiroAnaliticos.Sum((FechamentoFinanceiroAnalitico x) => x.get_Dados().Sum((DadosFechamentoAnalitico y) => { + if (y.get_Nome() != "TOTAL") + { + return y.get_Fev(); + } + return new decimal?(new decimal()); + }))); + List fechamentoAnalitico1 = this.FechamentoAnalitico; + dadosFechamentoAnalitico2.set_Mar(fechamentoAnalitico1.Sum((FechamentoFinanceiroAnalitico x) => x.get_Dados().Sum((DadosFechamentoAnalitico y) => { + if (y.get_Nome() != "TOTAL") + { + return y.get_Mar(); + } + return new decimal?(new decimal()); + }))); + List fechamentoFinanceiroAnaliticos1 = this.FechamentoAnalitico; + dadosFechamentoAnalitico2.set_Abr(fechamentoFinanceiroAnaliticos1.Sum((FechamentoFinanceiroAnalitico x) => x.get_Dados().Sum((DadosFechamentoAnalitico y) => { + if (y.get_Nome() != "TOTAL") + { + return y.get_Abr(); + } + return new decimal?(new decimal()); + }))); + List fechamentoAnalitico2 = this.FechamentoAnalitico; + dadosFechamentoAnalitico2.set_Mai(fechamentoAnalitico2.Sum((FechamentoFinanceiroAnalitico x) => x.get_Dados().Sum((DadosFechamentoAnalitico y) => { + if (y.get_Nome() != "TOTAL") + { + return y.get_Mai(); + } + return new decimal?(new decimal()); + }))); + List fechamentoFinanceiroAnaliticos2 = this.FechamentoAnalitico; + dadosFechamentoAnalitico2.set_Jun(fechamentoFinanceiroAnaliticos2.Sum((FechamentoFinanceiroAnalitico x) => x.get_Dados().Sum((DadosFechamentoAnalitico y) => { + if (y.get_Nome() != "TOTAL") + { + return y.get_Jun(); + } + return new decimal?(new decimal()); + }))); + List fechamentoAnalitico3 = this.FechamentoAnalitico; + dadosFechamentoAnalitico2.set_Jul(fechamentoAnalitico3.Sum((FechamentoFinanceiroAnalitico x) => x.get_Dados().Sum((DadosFechamentoAnalitico y) => { + if (y.get_Nome() != "TOTAL") + { + return y.get_Jul(); + } + return new decimal?(new decimal()); + }))); + List fechamentoFinanceiroAnaliticos3 = this.FechamentoAnalitico; + dadosFechamentoAnalitico2.set_Ago(fechamentoFinanceiroAnaliticos3.Sum((FechamentoFinanceiroAnalitico x) => x.get_Dados().Sum((DadosFechamentoAnalitico y) => { + if (y.get_Nome() != "TOTAL") + { + return y.get_Ago(); + } + return new decimal?(new decimal()); + }))); + List fechamentoAnalitico4 = this.FechamentoAnalitico; + dadosFechamentoAnalitico2.set_Set(fechamentoAnalitico4.Sum((FechamentoFinanceiroAnalitico x) => x.get_Dados().Sum((DadosFechamentoAnalitico y) => { + if (y.get_Nome() != "TOTAL") + { + return y.get_Set(); + } + return new decimal?(new decimal()); + }))); + List fechamentoFinanceiroAnaliticos4 = this.FechamentoAnalitico; + dadosFechamentoAnalitico2.set_Out(fechamentoFinanceiroAnaliticos4.Sum((FechamentoFinanceiroAnalitico x) => x.get_Dados().Sum((DadosFechamentoAnalitico y) => { + if (y.get_Nome() != "TOTAL") + { + return y.get_Out(); + } + return new decimal?(new decimal()); + }))); + List fechamentoAnalitico5 = this.FechamentoAnalitico; + dadosFechamentoAnalitico2.set_Nov(fechamentoAnalitico5.Sum((FechamentoFinanceiroAnalitico x) => x.get_Dados().Sum((DadosFechamentoAnalitico y) => { + if (y.get_Nome() != "TOTAL") + { + return y.get_Nov(); + } + return new decimal?(new decimal()); + }))); + List fechamentoFinanceiroAnaliticos5 = this.FechamentoAnalitico; + dadosFechamentoAnalitico2.set_Dez(fechamentoFinanceiroAnaliticos5.Sum((FechamentoFinanceiroAnalitico x) => x.get_Dados().Sum((DadosFechamentoAnalitico y) => { + if (y.get_Nome() != "TOTAL") + { + return y.get_Dez(); + } + return new decimal?(new decimal()); + }))); + List fechamentoAnalitico6 = this.FechamentoAnalitico; + dadosFechamentoAnalitico2.set_Total(fechamentoAnalitico6.Sum((FechamentoFinanceiroAnalitico x) => x.get_Dados().Sum((DadosFechamentoAnalitico y) => { + if (y.get_Nome() != "TOTAL") + { + return y.get_Total(); + } + return new decimal?(new decimal()); + }))); + dadosFechamentoAnalitico2.set_PercentualCredito(new decimal(100)); + dadosFechamentoAnalitico2.set_PercentualDebito(new decimal(100)); + dadosFechamentoAnaliticos8.Add(dadosFechamentoAnalitico2); + this.FechamentoAnalitico.Add(fechamentoFinanceiroAnalitico3); + } + this.HtmlContent = await this.GerarHtml(true); + } + } + + private async void LoadInicial() + { + this.Plano = await this._servico.BuscarPlanoAsync(); + this.Planos = await this._servico.BuscarPlanosAsync(); + this.Centro = await this._servico.BuscarCentroAsync(); + this.Conta = await (new BancosContasServico()).BuscarBancos(); + } + + public async Task Print() + { + string tempPath = Path.GetTempPath(); + string str = await this.GerarHtml(false); + string str1 = string.Format("{0}FECHAMENTO_FINANCEIRO_{1:ddMMyyyyhhmmss}.html", tempPath, Funcoes.GetNetworkTime()); + StreamWriter streamWriter = new StreamWriter(str1, true, Encoding.UTF8); + streamWriter.Write(str); + streamWriter.Close(); + Process.Start(str1); + tempPath = null; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Financeiro/TranferenciaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Financeiro/TranferenciaViewModel.cs new file mode 100644 index 0000000..d4e189a --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Financeiro/TranferenciaViewModel.cs @@ -0,0 +1,99 @@ +using Gestor.Application.Servicos.Financeiro; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Financeiro +{ + public class TranferenciaViewModel : BaseViewModel + { + private Gestor.Model.Domain.Financeiro.Transferencia _transferencia; + + private ObservableCollection _contas; + + private BancosContasServico _servico + { + get; + set; + } + + public ObservableCollection Contas + { + get + { + return this._contas; + } + set + { + this._contas = value; + base.OnPropertyChanged("Contas"); + } + } + + public Gestor.Model.Domain.Financeiro.Transferencia Transferencia + { + get + { + return this._transferencia; + } + set + { + this._transferencia = value; + base.OnPropertyChanged("Transferencia"); + } + } + + public TranferenciaViewModel(Gestor.Model.Domain.Financeiro.Transferencia transferencia) + { + this._servico = new BancosContasServico(); + this.Carregar(transferencia); + } + + private async void Carregar(Gestor.Model.Domain.Financeiro.Transferencia transferencia) + { + BancosContas bancosConta; + BancosContas bancosConta1; + List bancosContas = await this._servico.BuscarBancos(); + TranferenciaViewModel observableCollection = this; + List bancosContas1 = bancosContas; + IEnumerable ativo = + from x in bancosContas1 + where x.get_Ativo() + select x; + observableCollection.Contas = new ObservableCollection( + from x in ativo + orderby x.get_Descricao() + select x); + TranferenciaViewModel tranferenciaViewModel = this; + Gestor.Model.Domain.Financeiro.Transferencia transferencium = new Gestor.Model.Domain.Financeiro.Transferencia(); + if (transferencia.get_Origem() != null) + { + bancosConta = bancosContas.First((BancosContas x) => x.get_Id() == transferencia.get_Origem().get_Id()); + } + else + { + bancosConta = null; + } + transferencium.set_Origem(bancosConta); + transferencium.set_Data(transferencia.get_Data()); + transferencium.set_Valor(transferencia.get_Valor()); + if (transferencia.get_Destino() != null) + { + bancosConta1 = bancosContas.First((BancosContas x) => x.get_Id() == transferencia.get_Destino().get_Id()); + } + else + { + bancosConta1 = null; + } + transferencium.set_Destino(bancosConta1); + tranferenciaViewModel.Transferencia = transferencium; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/BaseApoliceViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/BaseApoliceViewModel.cs new file mode 100644 index 0000000..5bb2e93 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/BaseApoliceViewModel.cs @@ -0,0 +1,6893 @@ +using Gestor.Application.Actions; +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Generic +{ + public class BaseApoliceViewModel : BaseSegurosViewModel + { + internal ApoliceServico Servico; + + internal Gestor.Application.Servicos.Seguros.PerfilServico PerfilServico; + + internal Gestor.Application.Servicos.Ferramentas.RamoServico RamoServico; + + internal Gestor.Application.Servicos.Ferramentas.SeguradoraServico SeguradoraServico; + + internal Gestor.Application.Servicos.Ferramentas.VendedorServico VendedorServico; + + internal Gestor.Application.Servicos.ParcelaServico ParcelaServico; + + internal Gestor.Application.Servicos.Ferramentas.ProdutoServico ProdutoServico; + + internal Gestor.Application.Servicos.Ferramentas.EstipulanteServico EstipulanteServico; + + internal Gestor.Application.Servicos.TarefaServico TarefaServico; + + private bool _invoke = true; + + public bool UpdatePremio; + + private bool _enableControle = true; + + private bool _apelido; + + private bool _controleAdm; + + private Documento _selectedDocumento; + + private Visibility _visibilityExcluirParcela = Visibility.Collapsed; + + private Visibility _visibilityReplicarFatura = Visibility.Collapsed; + + private Visibility _visibilityAlterarVencimento; + + private string _importado = "CLIQUE PARA VER INFORMAÇÕES SOBRE A INCLUSÃO"; + + private string _codigoDocumento; + + private DateTime? _emissaoDocumento; + + private DateTime? _transmissaoDocumento; + + private bool _editandoParcela; + + private bool _botoesParcelaEnabled = true; + + private List _vendedores; + + private List _todosVendedores; + + private ObservableCollection _pagamentos; + + private ObservableCollection _situacao = new ObservableCollection(new List() + { + 1, + 2, + 5 + }); + + private ObservableCollection _tipoEndosso = new ObservableCollection(new List() + { + 0, + 1, + 2, + 4, + 3 + }); + + private Parcela _selectedParcela; + + private bool _coCorretagem; + + private Visibility _baixarParcelaVisibility = Visibility.Collapsed; + + private ObservableCollection _parcelas; + + private decimal _gerada; + + private decimal _comissOriginal; + + private Visibility _comissOriginalVisibility = Visibility.Collapsed; + + private decimal _recebida; + + private decimal _pendente; + + private decimal _repasse; + + private Visibility _recusaVisibility; + + private string _excluirParcelaLabel = "EXCLUIR BAIXA"; + + private bool _isEnableSituacao; + + private List _produtos = Recursos.Produtos; + + private List _status = Recursos.Status; + + private List _ramos; + + private List _seguradorasAnteriores; + + private List _seguradoras; + + private Visibility _isRenovacaoVisibility = Visibility.Collapsed; + + private bool _isEndosso; + + private bool _enableAlterarSituacao; + + private string _assinada = "PROPOSTA ASSINADA"; + + private string _conferida = "APÓLICE CONFERIDA"; + + private string _transmissao = "TRANSMISSÃO DE PROPOSTA"; + + private string _emissao = "EMISSÃO DA APÓLICE"; + + private List _tiposVendedor; + + private List _estipulantes; + + public Documento CancelDocumento; + + private List _repasses; + + private List _repassesVendedores; + + private List _repassesVendedor; + + private VendedorParcela _selectedPagamento; + + private bool _baixarParcelas; + + private bool _isFatura; + + private bool _ultimaFatura; + + private bool _allowEditVendedor; + + private bool _alteracaoEnabled; + + private bool _allowEditEmissao; + + private bool _allowEditApolice; + + private bool _allowVigenciaFinal; + + private bool _novaApolice; + + private bool _renovar; + + public decimal Tolerancia; + + private bool _enableRepasse; + + private bool _bloquearObservacao; + + private string _editarParcelasLabel; + + private string _anotacoes; + + private int _quantidadeFaturas; + + private double _tamanhoGrid; + + private bool _inclusao; + + private bool _criandoParcelaEspecial; + + private bool _visibilityLogAntigo; + + public AcessoApolice Acesso + { + get; + set; + } + + public bool AllowEditApolice + { + get + { + return this._allowEditApolice; + } + set + { + this._allowEditApolice = value; + this.AllowVigenciaFinal = (value ? true : this.IsFatura); + base.OnPropertyChanged("AllowEditApolice"); + } + } + + public bool AllowEditEmissao + { + get + { + return this._allowEditEmissao; + } + set + { + this._allowEditEmissao = value; + base.OnPropertyChanged("AllowEditEmissao"); + } + } + + public bool AllowEditVendedor + { + get + { + return this._allowEditVendedor; + } + set + { + this._allowEditVendedor = this._incluirPermissEnabled & value; + base.OnPropertyChanged("AllowEditVendedor"); + } + } + + public bool AllowVigenciaFinal + { + get + { + return this._allowVigenciaFinal; + } + set + { + this._allowVigenciaFinal = value; + base.OnPropertyChanged("AllowVigenciaFinal"); + } + } + + public bool AlteracaoEnabled + { + get + { + return this._alteracaoEnabled; + } + set + { + this._alteracaoEnabled = value; + base.OnPropertyChanged("AlteracaoEnabled"); + } + } + + public new string Anotacoes + { + get + { + return this._anotacoes; + } + set + { + this._anotacoes = value; + base.OnPropertyChanged("Anotacoes"); + } + } + + public bool Apelido + { + get + { + return this._apelido; + } + set + { + this._apelido = value; + base.OnPropertyChanged("Apelido"); + } + } + + public string Assinada + { + get + { + return this._assinada; + } + set + { + this._assinada = value; + base.OnPropertyChanged("Assinada"); + } + } + + public bool BaixarParcelas + { + get + { + return this._baixarParcelas; + } + set + { + this._baixarParcelas = value; + base.OnPropertyChanged("BaixarParcelas"); + } + } + + public Visibility BaixarParcelaVisibility + { + get + { + return this._baixarParcelaVisibility; + } + set + { + if (base.Restricao(15)) + { + return; + } + this._baixarParcelaVisibility = value; + base.OnPropertyChanged("BaixarParcelaVisibility"); + } + } + + public bool BloquearObservacao + { + get + { + return this._bloquearObservacao; + } + set + { + this._bloquearObservacao = value; + base.OnPropertyChanged("BloquearObservacao"); + } + } + + public bool BotoesParcelaEnabled + { + get + { + return this._botoesParcelaEnabled; + } + set + { + this._botoesParcelaEnabled = value; + base.OnPropertyChanged("BotoesParcelaEnabled"); + } + } + + public bool CoCorretagem + { + get + { + return this._coCorretagem; + } + set + { + if (this.SelectedPagamento != null) + { + this.SelectedPagamento.set_CoCorretagem(value); + } + this._coCorretagem = value; + base.OnPropertyChanged("CoCorretagem"); + } + } + + public string CodigoDocumento + { + get + { + return this._codigoDocumento; + } + set + { + this._codigoDocumento = value; + base.OnPropertyChanged("CodigoDocumento"); + } + } + + public decimal ComissOriginal + { + get + { + return this._comissOriginal; + } + set + { + this.ComissOriginalVisibility = (this.VerificaCoCorretagem() ? Visibility.Visible : Visibility.Collapsed); + this._comissOriginal = value; + base.OnPropertyChanged("ComissOriginal"); + } + } + + public Visibility ComissOriginalVisibility + { + get + { + return this._comissOriginalVisibility; + } + set + { + this._comissOriginalVisibility = value; + base.OnPropertyChanged("ComissOriginalVisibility"); + } + } + + public string Conferida + { + get + { + return this._conferida; + } + set + { + this._conferida = value; + base.OnPropertyChanged("Conferida"); + } + } + + public bool ControleAdm + { + get + { + return this._controleAdm; + } + set + { + this._controleAdm = value; + base.OnPropertyChanged("ControleAdm"); + } + } + + public bool CriandoParcelaEspecial + { + get + { + return this._criandoParcelaEspecial; + } + set + { + this._criandoParcelaEspecial = value; + } + } + + private Documento DocumentoRenovado + { + get; + set; + } + + internal Documento DocumentoSelecionado + { + get; + set; + } + + public bool EditandoParcela + { + get + { + return this._editandoParcela; + } + set + { + this._editandoParcela = value; + base.OnPropertyChanged("EditandoParcela"); + } + } + + public string EditarParcelasLabel + { + get + { + return this._editarParcelasLabel; + } + set + { + this._editarParcelasLabel = value; + base.OnPropertyChanged("EditarParcelasLabel"); + } + } + + public string Emissao + { + get + { + return this._emissao; + } + set + { + this._emissao = value; + base.OnPropertyChanged("Emissao"); + } + } + + public DateTime? EmissaoDocumento + { + get + { + return this._emissaoDocumento; + } + set + { + this._emissaoDocumento = value; + base.OnPropertyChanged("EmissaoDocumento"); + } + } + + public bool EnableAlterarSituacao + { + get + { + return this._enableAlterarSituacao; + } + set + { + this._enableAlterarSituacao = value; + base.OnPropertyChanged("EnableAlterarSituacao"); + } + } + + public bool EnableControle + { + get + { + return this._enableControle; + } + set + { + this._enableControle = value; + base.OnPropertyChanged("EnableControle"); + } + } + + public bool EnableRepasse + { + get + { + return this._enableRepasse; + } + set + { + this._enableRepasse = value; + base.OnPropertyChanged("EnableRepasse"); + } + } + + public List Estipulantes + { + get + { + return this._estipulantes; + } + set + { + this._estipulantes = value; + base.OnPropertyChanged("Estipulantes"); + } + } + + public string ExcluirParcelaLabel + { + get + { + return this._excluirParcelaLabel; + } + set + { + this._excluirParcelaLabel = value; + base.OnPropertyChanged("ExcluirParcelaLabel"); + } + } + + public decimal Gerada + { + get + { + return this._gerada; + } + set + { + this._gerada = value; + base.OnPropertyChanged("Gerada"); + } + } + + public string Importado + { + get + { + return this._importado; + } + set + { + this._importado = value; + base.OnPropertyChanged("Importado"); + } + } + + public Gestor.Model.Domain.Ferramentas.Imposto Imposto + { + get; + set; + } + + public bool Inclusao + { + get + { + return this._inclusao; + } + set + { + this._inclusao = value; + base.OnPropertyChanged("Inclusao"); + } + } + + public bool Invoke + { + get + { + return this._invoke; + } + set + { + this._invoke = value; + base.OnPropertyChanged("Invoke"); + } + } + + public bool IsEnableSituacao + { + get + { + return this._isEnableSituacao; + } + set + { + this._isEnableSituacao = value; + base.OnPropertyChanged("IsEnableSituacao"); + } + } + + public bool IsEndosso + { + get + { + return this._isEndosso; + } + set + { + this._isEndosso = value; + this.WorkOnSelectedTipo(value); + base.OnPropertyChanged("IsEndosso"); + } + } + + public bool IsFatura + { + get + { + return this._isFatura; + } + set + { + this._isFatura = value; + base.OnPropertyChanged("IsFatura"); + } + } + + public Visibility IsRenovacaoVisibility + { + get + { + return this._isRenovacaoVisibility; + } + set + { + this._isRenovacaoVisibility = value; + base.OnPropertyChanged("IsRenovacaoVisibility"); + } + } + + public bool Loaded + { + get; + set; + } + + public bool NovaApolice + { + get + { + return this._novaApolice; + } + set + { + this._novaApolice = value; + base.OnPropertyChanged("NovaApolice"); + } + } + + public ObservableCollection Pagamentos + { + get + { + return this._pagamentos; + } + set + { + this._pagamentos = value; + base.OnPropertyChanged("Pagamentos"); + } + } + + public ObservableCollection Parcelas + { + get + { + return this._parcelas; + } + set + { + this._parcelas = value; + if (value != null && value.Count == 0) + { + this.VisibilityExcluirParcela = Visibility.Collapsed; + this.VisibilityReplicarFatura = Visibility.Collapsed; + this.BaixarParcelaVisibility = Visibility.Collapsed; + this.VisibilityAlterarVencimento = Visibility.Collapsed; + } + base.OnPropertyChanged("Parcelas"); + } + } + + internal long ParcelaSelecionada + { + get; + set; + } + + public decimal Pendente + { + get + { + return this._pendente; + } + set + { + this._pendente = value; + base.OnPropertyChanged("Pendente"); + } + } + + public List Produtos + { + get + { + return this._produtos; + } + set + { + this._produtos = value; + base.OnPropertyChanged("Produtos"); + } + } + + public int QuantidadeFaturas + { + get + { + return this._quantidadeFaturas; + } + set + { + if (value < 0) + { + value = 0; + } + if (value > 12) + { + value = 12; + } + this._quantidadeFaturas = value; + base.OnPropertyChanged("QuantidadeFaturas"); + } + } + + public List Ramos + { + get + { + return this._ramos; + } + set + { + this._ramos = value; + base.OnPropertyChanged("Ramos"); + } + } + + public decimal Recebida + { + get + { + return this._recebida; + } + set + { + this._recebida = value; + base.OnPropertyChanged("Recebida"); + } + } + + public Visibility RecusaVisibility + { + get + { + return this._recusaVisibility; + } + set + { + this._recusaVisibility = (!base.Restricao(18) ? value : Visibility.Collapsed); + base.OnPropertyChanged("RecusaVisibility"); + } + } + + public bool Renovar + { + get + { + return this._renovar; + } + set + { + this._renovar = value; + base.OnPropertyChanged("Renovar"); + } + } + + public decimal Repasse + { + get + { + return this._repasse; + } + set + { + this._repasse = value; + base.OnPropertyChanged("Repasse"); + } + } + + public List Repasses + { + get + { + return this._repasses; + } + set + { + this._repasses = value; + base.OnPropertyChanged("Repasses"); + } + } + + public List RepassesVendedor + { + get + { + return this._repassesVendedor; + } + set + { + this._repassesVendedor = value; + this.EnableRepasse = (value == null ? false : value.Count > 0); + base.OnPropertyChanged("RepassesVendedor"); + } + } + + public List RepassesVendedores + { + get + { + return this._repassesVendedores; + } + set + { + this._repassesVendedores = value; + base.OnPropertyChanged("RepassesVendedores"); + } + } + + public List Seguradoras + { + get + { + return this._seguradoras; + } + set + { + this._seguradoras = value; + base.OnPropertyChanged("Seguradoras"); + } + } + + public List SeguradorasAnteriores + { + get + { + return this._seguradorasAnteriores; + } + set + { + this._seguradorasAnteriores = value; + base.OnPropertyChanged("SeguradorasAnteriores"); + } + } + + public Documento SelectedDocumento + { + get + { + return this._selectedDocumento; + } + set + { + DateTime networkTime; + long? nullable; + bool flag; + DateTime? emissao; + DateTime? remessa; + Visibility visibility; + long? nullable1; + string apolice; + if (value != null && value.get_Id() == 0) + { + this.VisibilityLogAntigo = false; + } + this._selectedDocumento = value; + this.Anotacoes = string.Empty; + base.EnableButtons = (value == null ? false : value.get_Id() > (long)0); + base.EnableIncluir = (value == null ? true : value.get_Id() > (long)0); + bool flag1 = Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 13); + if (value == null || value.get_Id() <= (long)0) + { + flag = false; + } + else if (flag1) + { + flag = true; + } + else + { + flag = (string.IsNullOrWhiteSpace(value.get_Apolice()) || string.IsNullOrWhiteSpace(value.get_Proposta()) ? false : value.get_Emissao().HasValue); + } + base.EnableEndossar = flag; + base.EnableRenovar = (value == null || value.get_Id() <= (long)0 || !value.get_Vigencia2().HasValue ? false : !string.IsNullOrWhiteSpace(value.get_Apolice())); + if (value == null || value.get_Id() == 0) + { + this.ZeraComissao(); + } + this.CodigoDocumento = (this.SelectedDocumento == null || this.SelectedDocumento.get_Id() == 0 ? "" : string.Format("{0}", this.SelectedDocumento.get_Id())); + if (value != null && value.get_Status() == null && this.Status.First().get_Nome() == "SEM STATUS") + { + value.set_Status(this.Status.First()); + } + if (value == null || !value.get_Emissao().HasValue) + { + networkTime = Funcoes.GetNetworkTime(); + emissao = new DateTime?(networkTime.Date); + } + else + { + emissao = value.get_Emissao(); + } + this.EmissaoDocumento = emissao; + if (value == null || !value.get_Remessa().HasValue) + { + networkTime = Funcoes.GetNetworkTime(); + remessa = new DateTime?(networkTime.Date); + } + else + { + remessa = value.get_Remessa(); + } + this.TransmissaoDocumento = remessa; + if (Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 19)) + { + if (value != null) + { + apolice = value.get_Apolice(); + } + else + { + apolice = null; + } + if (string.IsNullOrWhiteSpace(apolice) || !value.get_Emissao().HasValue) + { + visibility = Visibility.Visible; + this.RecusaVisibility = visibility; + if (value != null) + { + nullable1 = new long?(value.get_Id()); + } + else + { + nullable = null; + nullable1 = nullable; + } + base.VerificarEnables(nullable1); + base.OnPropertyChanged("SelectedDocumento"); + return; + } + visibility = Visibility.Collapsed; + this.RecusaVisibility = visibility; + if (value != null) + { + nullable1 = new long?(value.get_Id()); + } + else + { + nullable = null; + nullable1 = nullable; + } + base.VerificarEnables(nullable1); + base.OnPropertyChanged("SelectedDocumento"); + return; + } + visibility = Visibility.Visible; + this.RecusaVisibility = visibility; + if (value != null) + { + nullable1 = new long?(value.get_Id()); + } + else + { + nullable = null; + nullable1 = nullable; + } + base.VerificarEnables(nullable1); + base.OnPropertyChanged("SelectedDocumento"); + } + } + + public VendedorParcela SelectedPagamento + { + get + { + return this._selectedPagamento; + } + set + { + this._selectedPagamento = value; + base.OnPropertyChanged("SelectedPagamento"); + } + } + + public Parcela SelectedParcela + { + get + { + return this._selectedParcela; + } + set + { + this._selectedParcela = value; + this.WorkOnSelectedParcela(value); + base.OnPropertyChanged("SelectedParcela"); + } + } + + public ObservableCollection Situacao + { + get + { + return this._situacao; + } + set + { + this._situacao = value; + base.OnPropertyChanged("Situacao"); + } + } + + public List Status + { + get + { + return this._status; + } + set + { + if (value.All((Gestor.Model.Domain.Seguros.Status x) => x.get_Nome() != "SEM STATUS")) + { + Gestor.Model.Domain.Seguros.Status statu = new Gestor.Model.Domain.Seguros.Status(); + statu.set_Nome("SEM STATUS"); + statu.set_Id((long)0); + statu.set_Ativo(true); + value.Insert(0, statu); + } + this._status = value; + base.OnPropertyChanged("Status"); + } + } + + public double TamanhoGrid + { + get + { + return this._tamanhoGrid; + } + set + { + this._tamanhoGrid = value; + base.OnPropertyChanged("TamanhoGrid"); + } + } + + public ObservableCollection TipoEndossoList + { + get + { + return this._tipoEndosso; + } + set + { + this._tipoEndosso = value; + base.OnPropertyChanged("TipoEndossoList"); + } + } + + public List TiposVendedor + { + get + { + return this._tiposVendedor; + } + set + { + this._tiposVendedor = value; + base.OnPropertyChanged("TiposVendedor"); + } + } + + public List TodosVendedores + { + get + { + return this._todosVendedores; + } + set + { + this._todosVendedores = value; + base.OnPropertyChanged("TodosVendedores"); + } + } + + public string Transmissao + { + get + { + return this._transmissao; + } + set + { + this._transmissao = value; + base.OnPropertyChanged("Transmissao"); + } + } + + public DateTime? TransmissaoDocumento + { + get + { + return this._transmissaoDocumento; + } + set + { + this._transmissaoDocumento = value; + base.OnPropertyChanged("TransmissaoDocumento"); + } + } + + public bool UltimaFatura + { + get + { + return this._ultimaFatura; + } + set + { + this._ultimaFatura = value; + base.OnPropertyChanged("UltimaFatura"); + } + } + + public List Vendedores + { + get + { + return this._vendedores; + } + set + { + this._vendedores = value; + base.OnPropertyChanged("Vendedores"); + } + } + + public Visibility VisibilityAlterarVencimento + { + get + { + return this._visibilityAlterarVencimento; + } + set + { + this._visibilityAlterarVencimento = value; + base.OnPropertyChanged("VisibilityAlterarVencimento"); + } + } + + public Visibility VisibilityExcluirParcela + { + get + { + return this._visibilityExcluirParcela; + } + set + { + this._visibilityExcluirParcela = value; + base.OnPropertyChanged("VisibilityExcluirParcela"); + } + } + + public bool VisibilityLogAntigo + { + get + { + return this._visibilityLogAntigo; + } + set + { + this._visibilityLogAntigo = value; + base.OnPropertyChanged("VisibilityLogAntigo"); + } + } + + public Visibility VisibilityReplicarFatura + { + get + { + return this._visibilityReplicarFatura; + } + set + { + this._visibilityReplicarFatura = value; + base.OnPropertyChanged("VisibilityReplicarFatura"); + } + } + + public BaseApoliceViewModel() + { + this._invoke = true; + this._enableControle = true; + this._visibilityExcluirParcela = Visibility.Collapsed; + this._visibilityReplicarFatura = Visibility.Collapsed; + this._importado = "CLIQUE PARA VER INFORMAÇÕES SOBRE A INCLUSÃO"; + this._botoesParcelaEnabled = true; + this._situacao = new ObservableCollection(new List() + { + 1, + 2, + 5 + }); + this._tipoEndosso = new ObservableCollection(new List() + { + 0, + 1, + 2, + 4, + 3 + }); + this._baixarParcelaVisibility = Visibility.Collapsed; + this._comissOriginalVisibility = Visibility.Collapsed; + this._excluirParcelaLabel = "EXCLUIR BAIXA"; + this._produtos = Recursos.Produtos; + this._status = Recursos.Status; + this._isRenovacaoVisibility = Visibility.Collapsed; + this._assinada = "PROPOSTA ASSINADA"; + this._conferida = "APÓLICE CONFERIDA"; + this._transmissao = "TRANSMISSÃO DE PROPOSTA"; + this._emissao = "EMISSÃO DA APÓLICE"; + List tipoVendedor = Recursos.TipoVendedor; + if (tipoVendedor != null) + { + list = tipoVendedor.Where((TipoVendedor x) => { + if (!x.get_Ativo().HasValue) + { + return true; + } + return x.get_Ativo().Value; + }).ToList(); + } + else + { + list = null; + } + this._tiposVendedor = list; + this._allowEditVendedor = true; + this._alteracaoEnabled = true; + this._allowEditEmissao = true; + this._allowEditApolice = true; + this._allowVigenciaFinal = true; + this._bloquearObservacao = Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 39); + this._editarParcelasLabel = "EDITAR PARCELAS"; + this._visibilityLogAntigo = Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 22); + base(); + List list; + this.Servico = new ApoliceServico(); + this.VendedorServico = new Gestor.Application.Servicos.Ferramentas.VendedorServico(); + this.ParcelaServico = new Gestor.Application.Servicos.ParcelaServico(); + this.RamoServico = new Gestor.Application.Servicos.Ferramentas.RamoServico(); + this.SeguradoraServico = new Gestor.Application.Servicos.Ferramentas.SeguradoraServico(); + this.ProdutoServico = new Gestor.Application.Servicos.Ferramentas.ProdutoServico(); + this.EstipulanteServico = new Gestor.Application.Servicos.Ferramentas.EstipulanteServico(); + this.TarefaServico = new Gestor.Application.Servicos.TarefaServico(); + this.PerfilServico = new Gestor.Application.Servicos.Seguros.PerfilServico(); + this.Apelido = Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 6); + this.ControleAdm = (Recursos.Configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 33) ? true : Recursos.Usuario.get_Administrador()); + } + + public Documento AbrirDetalhes() + { + Documento selectedDocumento = this.SelectedDocumento; + selectedDocumento.set_Parcelas(this.Parcelas); + selectedDocumento.set_Pagamentos(this.Repasses); + return selectedDocumento; + } + + public Parcela AbrirDetalhesParcela() + { + Parcela selectedParcela = this.SelectedParcela; + selectedParcela.set_Vendedores(this.Pagamentos); + return selectedParcela; + } + + public async void AbrirLogAntigo() + { + base.Loading(true); + string str = await this.Servico.BuscarLogAntigo(this.SelectedDocumento.get_Id()); + base.Loading(false); + if (!string.IsNullOrEmpty(str)) + { + base.ShowDrawer(new LogSistemaAntigo(this.SelectedDocumento.get_Id(), str), 0, false); + } + else + { + await base.ShowMessage("NÃO HÁ LOG PARA ESSE DOCUMENTO", "OK", "", false); + } + } + + public async void AbrirLogAntigoParcela() + { + base.Loading(true); + string str = ""; + foreach (Parcela parcela in await this.ParcelaServico.BuscarParcelas(this.SelectedDocumento.get_Id())) + { + string str1 = str; + string str2 = await this.ParcelaServico.BuscarLogAntigo(parcela.get_Id()); + str = string.Concat(str1, str2); + str1 = null; + } + base.Loading(false); + if (!string.IsNullOrEmpty(str)) + { + base.ShowDrawer(new LogSistemaAntigo(this.SelectedDocumento.get_Id(), str), 0, false); + } + else + { + await base.ShowMessage("NÃO HÁ LOG PARA PARCELAS", "OK", "", false); + } + str = null; + } + + public async Task AdicionarParcelaEspecial() + { + long num; + DateTime? nullable; + DateTime valueOrDefault; + string str; + long num1; + DateTime? nullable1; + DateTime? nullable2; + DateTime? nullable3; + DateTime? nullable4; + DateTime? nullable5; + DateTime? nullable6; + string str1; + string str2; + string str3; + if (this.SelectedParcela != null && !this.CriandoParcelaEspecial) + { + this.CriandoParcelaEspecial = true; + if (this.SelectedPagamento == null || this.SelectedPagamento.get_Vendedor().get_Corretora()) + { + this.SelectedPagamento = this.PropriaCorretora(); + } + else + { + List> keyValuePairs = await this.AdicionarVendedorParcelaEspecial(); + if (keyValuePairs.Count > 0) + { + this._criandoParcelaEspecial = false; + await base.ShowMessage(keyValuePairs, " PROCESSO INTERROMPIDO, PARCELA/FATURA SEM VENDENDEDOR", "OK", ""); + return; + } + } + this.SelectedParcela.set_Documento(this.SelectedDocumento); + DateTime vencimento = this.SelectedParcela.get_Vencimento(); + DateTime? dataRecebimento = this.SelectedParcela.get_DataRecebimento(); + DateTime? dataCredito = this.SelectedParcela.get_DataCredito(); + DateTime? dataControle = this.SelectedParcela.get_DataControle(); + int numeroParcela = this.SelectedParcela.get_NumeroParcela(); + DateTime? vigenciaIncial = this.SelectedParcela.get_VigenciaIncial(); + DateTime? vigenciaFinal = this.SelectedParcela.get_VigenciaFinal(); + DateTime? emissao = this.SelectedParcela.get_Emissao(); + str = (string.IsNullOrWhiteSpace(Gestor.Common.Validation.ValidationHelper.OnlyNumber(this.SelectedParcela.get_Fatura())) ? "1" : Gestor.Common.Validation.ValidationHelper.OnlyNumber(this.SelectedParcela.get_Fatura())); + num1 = (long.TryParse(str, out num) ? num : (long)1); + long num2 = num1; + if (this.QuantidadeFaturas == 0 || !this.IsFatura) + { + this.QuantidadeFaturas = 1; + } + if (this.QuantidadeFaturas <= 12) + { + for (int i = 0; i < this.QuantidadeFaturas; i++) + { + this.SelectedParcela.set_Vencimento(vencimento.AddMonths(i)); + Parcela selectedParcela = this.SelectedParcela; + ref Nullable nullablePointer = ref vigenciaIncial; + if (nullablePointer.HasValue) + { + valueOrDefault = nullablePointer.GetValueOrDefault(); + nullable1 = new DateTime?(valueOrDefault.AddMonths(i)); + } + else + { + nullable = null; + nullable1 = nullable; + } + selectedParcela.set_VigenciaIncial(nullable1); + Parcela parcela = this.SelectedParcela; + ref Nullable nullablePointer1 = ref vigenciaFinal; + if (nullablePointer1.HasValue) + { + valueOrDefault = nullablePointer1.GetValueOrDefault(); + nullable2 = new DateTime?(valueOrDefault.AddMonths(i)); + } + else + { + nullable = null; + nullable2 = nullable; + } + parcela.set_VigenciaFinal(nullable2); + Parcela selectedParcela1 = this.SelectedParcela; + ref Nullable nullablePointer2 = ref emissao; + if (nullablePointer2.HasValue) + { + valueOrDefault = nullablePointer2.GetValueOrDefault(); + nullable3 = new DateTime?(valueOrDefault.AddMonths(i)); + } + else + { + nullable = null; + nullable3 = nullable; + } + selectedParcela1.set_Emissao(nullable3); + Parcela parcela1 = this.SelectedParcela; + ref Nullable nullablePointer3 = ref dataRecebimento; + if (nullablePointer3.HasValue) + { + valueOrDefault = nullablePointer3.GetValueOrDefault(); + nullable4 = new DateTime?(valueOrDefault.AddMonths(i)); + } + else + { + nullable = null; + nullable4 = nullable; + } + parcela1.set_DataRecebimento(nullable4); + Parcela selectedParcela2 = this.SelectedParcela; + ref Nullable nullablePointer4 = ref dataCredito; + if (nullablePointer4.HasValue) + { + valueOrDefault = nullablePointer4.GetValueOrDefault(); + nullable5 = new DateTime?(valueOrDefault.AddMonths(i)); + } + else + { + nullable = null; + nullable5 = nullable; + } + selectedParcela2.set_DataCredito(nullable5); + Parcela parcela2 = this.SelectedParcela; + ref Nullable nullablePointer5 = ref dataControle; + if (nullablePointer5.HasValue) + { + valueOrDefault = nullablePointer5.GetValueOrDefault(); + nullable6 = new DateTime?(valueOrDefault.AddMonths(i)); + } + else + { + nullable = null; + nullable6 = nullable; + } + parcela2.set_DataControle(nullable6); + this.SelectedParcela.set_NumeroParcela(numeroParcela + i); + if (i > 0) + { + num2 += (long)1; + this.SelectedParcela.set_Fatura(string.Format("{0}", num2)); + nullable = null; + this.SelectedParcela.set_DataQuitacao(nullable); + } + List repasses = this.Repasses; + if (repasses != null) + { + repasses.ForEach((VendedorParcela x) => { + if (x.get_Repasse() == null) + { + return; + } + if (x.get_Repasse().get_Forma().GetValueOrDefault() == 1) + { + x.set_DataPrePagamento(this.SelectedParcela.get_DataRecebimento()); + } + x.set_Parcela(this.SelectedParcela); + BaseRepasse? @base = x.get_Repasse().get_Base(); + if (@base.HasValue) + { + switch (@base.GetValueOrDefault()) + { + case 1: + { + x.set_DataPrePagamento((this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 2 ? x.get_Parcela().get_VigenciaIncial() : new DateTime?(this.SelectedDocumento.get_Vigencia1()))); + return; + } + case 2: + { + x.set_DataPrePagamento(x.get_Parcela().get_DataCriacao()); + return; + } + case 3: + { + x.set_DataPrePagamento(new DateTime?((x.get_Parcela().get_Vencimento() == DateTime.MinValue ? this.SelectedDocumento.get_Vigencia1() : x.get_Parcela().get_Vencimento()))); + return; + } + case 4: + { + x.set_DataPrePagamento((this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 2 ? x.get_Parcela().get_Emissao() : this.SelectedDocumento.get_Emissao())); + return; + } + case 5: + { + x.set_DataPrePagamento((this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 2 ? x.get_Parcela().get_Emissao() : this.SelectedDocumento.get_Remessa())); + break; + } + default: + { + return; + } + } + } + }); + } + else + { + } + if (this.Repasses == null) + { + this.Repasses = new List() + { + this.PropriaCorretora() + }; + } + List vendedorParcelas = this.Repasses; + if (vendedorParcelas.All((VendedorParcela x) => x.get_TipoVendedor().get_Id() != (long)1)) + { + this.Repasses.Add(this.PropriaCorretora()); + } + Parcela parcela3 = await this.ParcelaServico.Save(this.SelectedParcela, this.Parcelas.ToList(), this.Repasses, true); + if (i == this.QuantidadeFaturas - 1) + { + this.SelectedParcela = parcela3; + } + } + this.QuantidadeFaturas = 0; + if (this.SelectedDocumento.get_Tipo() == 0 && string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + str1 = string.Concat("NA PROPOSTA \"", this.SelectedDocumento.get_Proposta(), "\""); + } + else if (this.SelectedDocumento.get_Tipo() != 0 || string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + str1 = (string.IsNullOrEmpty(this.SelectedDocumento.get_Endosso()) ? string.Concat("NA PROPOSTA DE ENDOSSO \"", this.SelectedDocumento.get_PropostaEndosso(), "\"") : string.Concat("NO ENDOSSO \"", this.SelectedDocumento.get_Endosso(), "\"")); + } + else + { + str1 = string.Concat("NA APÓLICE \"", this.SelectedDocumento.get_Apolice(), "\""); + } + string str4 = str1; + str2 = (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 1 ? string.Concat("PARCELA ESPECIAL ADICIONADA, ", str4) : string.Concat("FATURA ", this.SelectedParcela.get_Fatura(), " ADICIONADA, ", str4)); + string str5 = str2; + base.RegistrarAcao(str5, this.SelectedParcela.get_Id(), new TipoTela?(5), this.GerarObs(this.SelectedDocumento)); + if (this.ParcelaServico.Sucesso) + { + BaseApoliceViewModel baseApoliceViewModel = this; + str3 = (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 1 ? "PARCELA ESPECIAL ADICIONADA COM SUCESSO" : "FATURA ADICIONADA COM SUCESSO"); + baseApoliceViewModel.ToggleSnackBar(str3, true); + } + await this.CarregarParcelas(this.SelectedDocumento); + await this.CarregaRepasse(this.SelectedDocumento.get_Id()); + BaseApoliceViewModel baseApoliceViewModel1 = this; + Parcela selectedParcela3 = this.SelectedParcela; + if (selectedParcela3 == null) + { + selectedParcela3 = this.Parcelas.FirstOrDefault(); + } + await baseApoliceViewModel1.SelecionaParcela(selectedParcela3); + this.CalculaComissao(this.SelectedDocumento, this.Parcelas); + this.BaixarParcelas = false; + this.CriandoParcelaEspecial = false; + } + else + { + this.CriandoParcelaEspecial = false; + await base.ShowMessage("NÃO É POSSIVEL REPLICAR MAIS QUE 12 VEZES A MESMA FATURA. PROCESSO CANCELADO", "OK", "", false); + } + } + } + + public async Task>> AdicionarVendedor() + { + // + // Current member / type: System.Threading.Tasks.Task`1>> Gestor.Application.ViewModels.Generic.BaseApoliceViewModel::AdicionarVendedor() + // File path: C:\AggerSeguros\Gestor.Application.exe + // + // Product version: 0.0.0.0 + // Exception in: System.Threading.Tasks.Task>> AdicionarVendedor() + // + // Object reference not set to an instance of an object. + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.FindLowestCommonAncestor(ICollection`1 typeNodes) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 515 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.MergeWithLowestCommonAncestor() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 459 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.ProcessSingleConstraints() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 378 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.InferTypes() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 331 + // at Telerik.JustDecompiler.Decompiler.ExpressionDecompilerStep.Process(DecompilationContext theContext, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\ExpressionDecompilerStep.cs:line 104 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.Extensions.DecompileStateMachine(MethodBody body, DecompilationContext enclosingContext, BaseStateMachineRemoverStep removeStateMachineStep, Func`2 stateMachineDataSelector, DecompilationContext& decompilationContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 104 + // at Telerik.JustDecompiler.Decompiler.Extensions.DecompileAsyncStateMachine(MethodBody body, DecompilationContext enclosingContext, AsyncData& asyncData) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 150 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.GetMoveNextStatements() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 155 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.Match() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 60 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.Process(DecompilationContext context, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 31 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.Extensions.RunPipeline(DecompilationPipeline pipeline, ILanguage language, MethodBody body, DecompilationContext& context) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 95 + // at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61 + // at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 118 + // + // mailto: JustDecompilePublicFeedback@telerik.com + + } + + public async Task>> AdicionarVendedorParcelaEspecial() + { + List> keyValuePairs; + List list; + bool valueOrDefault; + bool flag; + bool flag1; + string str1; + DateTime? nullable; + DateTime dateTime; + DateTime? nullable1; + DateTime? nullable2; + bool flag2; + decimal num; + List vinculoRepasses; + List vendedorParcelas; + List> keyValuePairs1 = new List>(); + if (this.SelectedPagamento == null) + { + keyValuePairs1.Add(new KeyValuePair("SelectedPagamento|PAGAMENTO", "ERRO AO INCLUIR VENDEDOR.")); + keyValuePairs = keyValuePairs1; + } + else if (this.SelectedPagamento.get_Repasse() != null) + { + this.SelectedPagamento.set_Parcela(this.SelectedParcela); + if (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() != 2 || this.SelectedPagamento.get_Repasse().get_Forma().GetValueOrDefault() != 3) + { + Gestor.Model.Domain.Seguros.Repasse repasse = this.SelectedPagamento.get_Repasse(); + if (repasse != null) + { + List vinculo = repasse.get_Vinculo(); + if (vinculo != null) + { + list = ( + from x in vinculo + where x.get_TipoVendedor().get_Id() == this.SelectedPagamento.get_TipoVendedor().get_Id() + select x).ToList(); + } + else + { + list = null; + } + } + else + { + list = null; + } + vinculoRepasses = list; + vendedorParcelas = new List() + { + this.SelectedPagamento + }; + if (this.SelectedDocumento.get_NegocioCorretora().HasValue) + { + NegocioCorretora? negocioCorretora = this.SelectedDocumento.get_NegocioCorretora(); + valueOrDefault = negocioCorretora.GetValueOrDefault() == 1; + } + else if (this.SelectedDocumento.get_Situacao() != 2 || !this.SelectedDocumento.get_Negocio().HasValue) + { + valueOrDefault = false; + } + else + { + Negocio? negocio = this.SelectedDocumento.get_Negocio(); + valueOrDefault = negocio.GetValueOrDefault() == 1; + } + bool flag3 = valueOrDefault; + flag = (vinculoRepasses == null ? false : vinculoRepasses.Count > 0); + bool flag4 = flag; + if (flag4) + { + flag4 = await base.ShowMessage("DESEJA ADICIONAR OS REPASSES VINCULADOS?", "SIM", "NÃO", false); + } + if (flag4) + { + foreach (VinculoRepasse vinculoRepasse in vinculoRepasses) + { + Gestor.Model.Domain.Seguros.Repasse repasseVinculo = vinculoRepasse.get_RepasseVinculo(); + Parcela parcela = this.SelectedPagamento.get_Parcela(); + flag2 = (this.SelectedPagamento.get_Parcela() == null ? true : this.SelectedPagamento.get_Parcela().get_SubTipo() == 1); + decimal num1 = Funcoes.CalculaRepasse(repasseVinculo, parcela, flag2); + VendedorParcela vendedorParcela = new VendedorParcela(); + vendedorParcela.set_TipoVendedor(vinculoRepasse.get_TipoVendedorVinculo()); + vendedorParcela.set_Vendedor(vinculoRepasse.get_RepasseVinculo().get_Vendedor()); + vendedorParcela.set_Repasse(vinculoRepasse.get_RepasseVinculo()); + vendedorParcela.set_Documento(this.SelectedPagamento.get_Documento()); + vendedorParcela.set_Parcela(this.SelectedPagamento.get_Parcela()); + num = (flag3 ? vinculoRepasse.get_RepasseVinculo().get_ValorRenovacao() : vinculoRepasse.get_RepasseVinculo().get_ValorNovo()); + vendedorParcela.set_PorcentagemRepasse(new decimal?(num)); + vendedorParcela.set_ValorRepasse(new decimal?(num1)); + vendedorParcela.set_ValorTotal(new decimal?(num1)); + vendedorParcelas.Add(vendedorParcela); + } + } + foreach (VendedorParcela vendedorParcela1 in vendedorParcelas) + { + VendedorParcela vendedorParcela2 = vendedorParcela1; + keyValuePairs1 = vendedorParcela2.Validate(); + keyValuePairs1.AddRange(this.ValidateEspecial(vendedorParcela2)); + if (keyValuePairs1.Count <= 0) + { + if (vendedorParcela2.get_Repasse() != null) + { + BaseRepasse? @base = vendedorParcela2.get_Repasse().get_Base(); + if (@base.HasValue) + { + switch (@base.GetValueOrDefault()) + { + case 1: + { + VendedorParcela vendedorParcela3 = vendedorParcela2; + nullable = (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 2 ? vendedorParcela2.get_Parcela().get_VigenciaIncial() : new DateTime?(this.SelectedDocumento.get_Vigencia1())); + vendedorParcela3.set_DataPrePagamento(nullable); + break; + } + case 2: + { + vendedorParcela2.set_DataPrePagamento(vendedorParcela2.get_Parcela().get_DataCriacao()); + break; + } + case 3: + { + VendedorParcela vendedorParcela4 = vendedorParcela2; + dateTime = (vendedorParcela2.get_Parcela().get_Vencimento() == DateTime.MinValue ? this.SelectedDocumento.get_Vigencia1() : vendedorParcela2.get_Parcela().get_Vencimento()); + vendedorParcela4.set_DataPrePagamento(new DateTime?(dateTime)); + break; + } + case 4: + { + VendedorParcela vendedorParcela5 = vendedorParcela2; + nullable1 = (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 2 ? vendedorParcela2.get_Parcela().get_Emissao() : this.SelectedDocumento.get_Emissao()); + vendedorParcela5.set_DataPrePagamento(nullable1); + break; + } + case 5: + { + VendedorParcela vendedorParcela6 = vendedorParcela2; + nullable2 = (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 2 ? vendedorParcela2.get_Parcela().get_Emissao() : this.SelectedDocumento.get_Remessa()); + vendedorParcela6.set_DataPrePagamento(nullable2); + break; + } + } + } + } + if (this.Pagamentos == null) + { + this.Pagamentos = new ObservableCollection(); + } + VendedorParcela vendedorParcela7 = this.Repasses.FirstOrDefault((VendedorParcela x) => { + if (x.get_Parcela().get_Id() != this.SelectedParcela.get_Id() || x.get_TipoVendedor().get_Id() != (long)1) + { + return false; + } + return x.get_Vendedor().get_Corretora(); + }); + flag1 = (vendedorParcela2.get_TipoVendedor().get_Id() != (long)1 ? false : vendedorParcela7 != null); + bool flag5 = flag1; + if (this.SelectedParcela.get_Id() != 0) + { + if (vendedorParcela2.get_Repasse().get_Forma().GetValueOrDefault() == 1) + { + vendedorParcela2.set_DataPrePagamento(this.SelectedParcela.get_DataRecebimento()); + } + List vendedorParcelas1 = new List() + { + vendedorParcela2 + }; + vendedorParcelas1 = await this.Servico.IncluirVendedores(vendedorParcelas1); + if (this.SelectedDocumento.get_Tipo() == 0 && string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + str1 = string.Concat("NA PROPOSTA \"", this.SelectedDocumento.get_Proposta(), "\""); + } + else if (this.SelectedDocumento.get_Tipo() != 0 || string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + str1 = (string.IsNullOrEmpty(this.SelectedDocumento.get_Endosso()) ? string.Concat("NA PROPOSTA DE ENDOSSO \"", this.SelectedDocumento.get_PropostaEndosso(), "\"") : string.Concat("NO ENDOSSO \"", this.SelectedDocumento.get_Endosso(), "\"")); + } + else + { + str1 = string.Concat("NA APÓLICE \"", this.SelectedDocumento.get_Apolice(), "\""); + } + string str2 = str1; + if (vendedorParcelas1 != null) + { + vendedorParcelas1.ForEach((VendedorParcela x) => { + string str = string.Concat("VENDEDOR ", x.get_Vendedor().get_Nome(), " ADICIONADO A PARCELA ESPECIAL, ", str2); + base.RegistrarAcao(str, x.get_Id(), new TipoTela?(37), string.Format("{0}{1}VENDEDOR: {2}{3}COMISSÃO TOTAL: {4:C2}", new object[] { this.GerarObs(this.SelectedDocumento), Environment.NewLine, x.get_Vendedor().get_Nome(), Environment.NewLine, x.get_ValorTotal() })); + }); + } + this.Repasses.AddRange(vendedorParcelas1); + if (flag5) + { + await this.ExcluirVendedor(vendedorParcela7, false); + } + this.Repasses = await this.VendedorServico.BuscaRepasse(this.SelectedDocumento.get_Id()); + BaseApoliceViewModel baseApoliceViewModel = this; + Parcela selectedParcela = this.SelectedParcela; + if (selectedParcela == null) + { + selectedParcela = this.Parcelas.FirstOrDefault(); + } + await baseApoliceViewModel.SelecionaParcela(selectedParcela); + this.SelectedPagamento = null; + vendedorParcela7 = null; + } + else + { + this.Repasses.Add(vendedorParcela2); + this.Pagamentos.Add(vendedorParcela2); + this.SelectedPagamento = null; + if (!this.IsFatura && this.SelectedParcela.get_SubTipo() == 1 || !flag5) + { + continue; + } + await this.ExcluirVendedor(vendedorParcela7, false); + } + } + else + { + if (this.SelectedPagamento == null) + { + this.SelectedPagamento = vendedorParcela2; + } + keyValuePairs = keyValuePairs1; + vinculoRepasses = null; + vendedorParcelas = null; + return keyValuePairs; + } + } + base.ToggleSnackBar("VENDEDOR ADICIONADO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + base.ShowMessage("NÃO É POSSÍVEL ADICIONAR UM VENDEDOR COM A FORMA DE PAGAMENTO À PRAZO EM DOCUMENTOS DO TIPO FATURA", "OK", "", false); + keyValuePairs = null; + } + } + else + { + keyValuePairs1.Add(new KeyValuePair("Repasse|REPASSE", "ERRO AO INCLUIR VENDEDOR.")); + keyValuePairs = keyValuePairs1; + } + vinculoRepasses = null; + vendedorParcelas = null; + return keyValuePairs; + } + + public async void AjustaParcelasCoCorretagem() + { + int num = 0; + try + { + ObservableCollection parcelas = this.Parcelas; + foreach (Parcela parcela in parcelas) + { + if (parcela.get_NumeroParcela() != 999) + { + parcela.set_Comissao(this.SelectedDocumento.get_Comissao()); + } + else + { + return; + } + } + this.Parcelas = new ObservableCollection(await this.ParcelaServico.SaveRange(parcelas.ToList())); + await this.CarregarParcelas(this.SelectedDocumento); + } + catch + { + num = 1; + } + if (num == 1) + { + await base.ShowMessage("NÃO FOI POSSÍVEL SALVAR AS PARCELAS", "OK", "", false); + } + } + + public async Task AjusteComissãoCoCorretagem(bool removido = false) + { + decimal? nullable; + decimal valorNovo; + decimal? comissaoTotal; + int num = 0; + try + { + if (!removido) + { + VendedorParcela selectedPagamento = this.SelectedPagamento; + if (selectedPagamento != null) + { + valorNovo = selectedPagamento.get_Repasse().get_ValorNovo(); + } + else + { + valorNovo = decimal.Zero; + } + decimal num1 = valorNovo; + decimal comissao = this.SelectedDocumento.get_Comissao(); + this.SelectedDocumento.set_ComissaoTotal(new decimal?(comissao)); + this.SelectedDocumento.set_Comissao(Math.Round(comissao - (comissao * num1 * new decimal(1, 0, 0, false, 2)), 2)); + this.SelectedDocumento = await this.Servico.Save(this.SelectedDocumento, false, false); + this.AjustaParcelasCoCorretagem(); + this.CalculaComissao(this.SelectedDocumento, this.Parcelas); + } + else + { + Documento selectedDocumento = this.SelectedDocumento; + Documento documento = this.SelectedDocumento; + if (documento != null) + { + comissaoTotal = documento.get_ComissaoTotal(); + } + else + { + nullable = null; + comissaoTotal = nullable; + } + nullable = comissaoTotal; + selectedDocumento.set_Comissao(nullable.GetValueOrDefault()); + this.SelectedDocumento = await this.Servico.Save(this.SelectedDocumento, false, false); + this.AjustaParcelasCoCorretagem(); + this.CalculaComissao(this.SelectedDocumento, this.Parcelas); + return; + } + } + catch + { + num = 1; + } + if (num == 1) + { + await base.ShowMessage("NÃO FOI POSSÍVEL ALTERAR A COMISSÃO DA CO-CORRETAGEM", "OK", "", false); + } + } + + public async Task AlterarVencimento() + { + // + // Current member / type: System.Threading.Tasks.Task Gestor.Application.ViewModels.Generic.BaseApoliceViewModel::AlterarVencimento() + // File path: C:\AggerSeguros\Gestor.Application.exe + // + // Product version: 0.0.0.0 + // Exception in: System.Threading.Tasks.Task AlterarVencimento() + // + // An item with the same key has already been added. Key: Label0 + // at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior) + // at System.Collections.Generic.Dictionary`2.System.Collections.Generic.ICollection>.Add(KeyValuePair`2 keyValuePair) + // at Telerik.JustDecompiler.Common.Extensions.AddRange[TKey,TValue](IDictionary`2 self, IDictionary`2 source) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Common\Extensions.cs:line 99 + // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.AnonymousDelegateRebuilder.VisitObjectCreationExpression(ObjectCreationExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 332 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit[TCollection,TElement](TCollection original) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 312 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitMethodInvocationExpression(MethodInvocationExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 500 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitExpressionStatement(ExpressionStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 384 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 + // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.AnonymousDelegateRebuilder.Match(BlockStatement theBlock, Int32 index) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 74 + // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.VisitBlockStatement(BlockStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 30 + // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 351 + // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.VisitIfStatement(IfStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 409 + // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 351 + // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.Visit(IEnumerable collection) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 384 + // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.VisitBlockStatement(BlockStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 33 + // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 351 + // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.VisitIfStatement(IfStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 408 + // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 351 + // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.Visit(IEnumerable collection) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 384 + // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.VisitBlockStatement(BlockStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 33 + // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.Process(DecompilationContext context, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 21 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.Extensions.RunPipeline(DecompilationPipeline pipeline, ILanguage language, MethodBody body, DecompilationContext& context) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 95 + // at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61 + // at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 118 + // + // mailto: JustDecompilePublicFeedback@telerik.com + + } + + private void AtualizaValores(bool renovacao) + { + this.Repasses.ForEach((VendedorParcela x) => { + decimal? nullable; + decimal? comissaoTotal; + if (x.get_Repasse() == null) + { + return; + } + if (x.get_Repasse().get_Tipo().GetValueOrDefault() == 1) + { + return; + } + Parcela parcela = x.get_Parcela(); + if (parcela.get_SubTipo() != 1) + { + return; + } + parcela.set_Documento(this.SelectedDocumento); + decimal numeroParcelas = Funcoes.CalculaRepasse(x.get_Repasse(), parcela, true); + decimal valorNovo = (renovacao ? x.get_Repasse().get_ValorRenovacao() : x.get_Repasse().get_ValorNovo()); + if (x.get_CoCorretagem()) + { + valorNovo = x.get_Repasse().get_ValorNovo(); + } + if (x.get_Repasse().get_Forma().GetValueOrDefault() == 3) + { + numeroParcelas /= this.SelectedDocumento.get_NumeroParcelas(); + } + if (x.get_CoCorretagem()) + { + decimal comissao = this.SelectedDocumento.get_Comissao(); + Documento selectedDocumento = this.SelectedDocumento; + if (selectedDocumento != null) + { + comissaoTotal = selectedDocumento.get_ComissaoTotal(); + } + else + { + nullable = null; + comissaoTotal = nullable; + } + nullable = comissaoTotal; + decimal valueOrDefault = nullable.GetValueOrDefault(); + numeroParcelas = this.SelectedDocumento.get_PremioLiquido() * ((valueOrDefault - comissao) / new decimal(100)); + } + x.set_PorcentagemRepasse(new decimal?(valorNovo)); + x.set_ValorRepasse(new decimal?(numeroParcelas)); + x.set_ValorTotal(new decimal?(numeroParcelas)); + }); + decimal num = (this.Parcelas.Count((Parcela x) => x.get_SubTipo() == 1) > 0 ? this.SelectedDocumento.get_PremioTotal() / this.Parcelas.Count((Parcela x) => x.get_SubTipo() == 1) : decimal.Zero); + ( + from x in this.Parcelas + where x.get_SubTipo() == 1 + select x).ToList().ForEach((Parcela x) => { + x.set_Valor(num); + x.set_Comissao(this.SelectedDocumento.get_Comissao()); + x.set_Vendedores(new ObservableCollection( + from r in this.Repasses + where r.get_Parcela().get_Id() == x.get_Id() + select r)); + }); + } + + internal async Task BaixarComissao() + { + decimal? nullable; + bool valueOrDefault; + decimal? tolerancia; + decimal num; + bool tipo; + bool flag; + string endosso; + string propostaEndosso; + string str; + bool valueOrDefault1; + string str1; + bool flag1; + long? nullable1; + if (this.SelectedParcela != null) + { + base.Loading(true); + if (!this.IsFatura) + { + valueOrDefault = false; + } + else + { + ObservableCollection parcelas = this.Parcelas; + IOrderedEnumerable numeroParcela = + from x in parcelas + orderby x.get_NumeroParcela() + select x; + Parcela parcela = numeroParcela.LastOrDefault((Parcela x) => x.get_SubTipo() == 1); + if (parcela != null) + { + nullable1 = new long?(parcela.get_Id()); + } + else + { + nullable1 = null; + } + long? nullable2 = nullable1; + long id = this.SelectedParcela.get_Id(); + valueOrDefault = nullable2.GetValueOrDefault() == id & nullable2.HasValue; + } + bool flag2 = valueOrDefault; + this.SelectedParcela.set_Documento(this.SelectedDocumento); + Parcela selectedParcela = this.SelectedParcela; + List list = this.Parcelas.ToList(); + List repasses = this.Repasses; + Documento selectedDocumento = this.SelectedDocumento; + if (selectedDocumento != null) + { + Controle controle = selectedDocumento.get_Controle(); + if (controle != null) + { + Seguradora seguradora = controle.get_Seguradora(); + if (seguradora != null) + { + tolerancia = seguradora.get_Tolerancia(); + } + else + { + nullable = null; + tolerancia = nullable; + } + } + else + { + nullable = null; + tolerancia = nullable; + } + } + else + { + nullable = null; + tolerancia = nullable; + } + decimal? nullable3 = tolerancia; + num = (nullable3.HasValue ? nullable3.GetValueOrDefault() : this.Tolerancia); + this.SelectedParcela = await Funcoes.BaixarComissao(selectedParcela, list, repasses, num, false); + Documento documento = this.SelectedDocumento; + if (documento != null) + { + tipo = documento.get_Tipo() == 0; + } + else + { + tipo = false; + } + if (!tipo || !string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + Documento selectedDocumento1 = this.SelectedDocumento; + if (selectedDocumento1 != null) + { + flag = selectedDocumento1.get_Tipo() == 0; + } + else + { + flag = false; + } + if (!flag || string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + Documento documento1 = this.SelectedDocumento; + if (documento1 != null) + { + endosso = documento1.get_Endosso(); + } + else + { + endosso = null; + } + if (string.IsNullOrEmpty(endosso)) + { + Documento selectedDocumento2 = this.SelectedDocumento; + if (selectedDocumento2 != null) + { + propostaEndosso = selectedDocumento2.get_PropostaEndosso(); + } + else + { + propostaEndosso = null; + } + str = string.Concat("PROPOSTA DE ENDOSSO ", propostaEndosso); + } + else + { + str = string.Concat("ENDOSSO ", this.SelectedDocumento.get_Endosso()); + } + } + else + { + str = string.Concat("APÓLICE ", this.SelectedDocumento.get_Apolice()); + } + } + else + { + str = string.Concat("PROPOSTA ", this.SelectedDocumento.get_Proposta()); + } + string str2 = str; + Documento documento2 = this.SelectedDocumento; + if (documento2 != null) + { + valueOrDefault1 = documento2.get_TipoRecebimento().GetValueOrDefault() == 1; + } + else + { + valueOrDefault1 = false; + } + str1 = (valueOrDefault1 ? string.Format("PARCELA {0} BAIXADA, {1}", this.SelectedParcela.get_NumeroParcela(), str2) : string.Concat("FATURA ", this.SelectedParcela.get_Fatura(), " BAIXADA, ", str2)); + string str3 = str1; + base.RegistrarAcao(str3, this.SelectedParcela.get_Id(), new TipoTela?(5), this.GerarObs(this.SelectedDocumento)); + if (this.SelectedDocumento != null) + { + await this.CarregarParcelas(this.SelectedDocumento); + await this.CarregaRepasse(this.SelectedDocumento.get_Id()); + this.CalculaComissao(this.SelectedDocumento, this.Parcelas); + } + BaseApoliceViewModel baseApoliceViewModel = this; + Parcela selectedParcela1 = this.SelectedParcela; + if (selectedParcela1 == null) + { + selectedParcela1 = this.Parcelas.FirstOrDefault(); + } + await baseApoliceViewModel.SelecionaParcela(selectedParcela1); + this.BaixarParcelas = false; + BaseApoliceViewModel baseApoliceViewModel1 = this; + ObservableCollection observableCollection = this.Parcelas; + IEnumerable subTipo = + from x in observableCollection + where x.get_SubTipo() == 1 + select x; + if (!subTipo.All((Parcela x) => !x.get_DataRecebimento().HasValue)) + { + flag1 = false; + } + else + { + List vendedorParcelas = this.Repasses; + IEnumerable subTipo1 = + from x in vendedorParcelas + where x.get_Parcela().get_SubTipo() == 1 + select x; + flag1 = subTipo1.All((VendedorParcela x) => !x.get_DataPagamento().HasValue); + } + baseApoliceViewModel1.AllowEditApolice = flag1; + base.Loading(false); + bool flag3 = flag2; + if (flag3) + { + flag3 = await base.ShowMessage("DESEJA INCLUIR A PRÓXIMA FATURA?", "SIM", "NÃO", false); + } + if (flag3) + { + this.UltimaFatura = true; + } + base.ToggleSnackBar("PARCELA BAIXADA COM SUCESSO", true); + } + } + + public async Task BuscarVendedores(bool verificarRamo = true) + { + List vendedors1; + List vendedores; + bool ramo; + bool id; + Func func = null; + if (this.RepassesVendedores == null) + { + this.RepassesVendedores = await this.VendedorServico.BuscaRepasses(); + BaseApoliceViewModel list = this; + List repassesVendedores = this.RepassesVendedores; + IEnumerable> groupings = + from x in repassesVendedores + group x by x.get_Vendedor().get_Id(); + IEnumerable vendedor = + from x in groupings + select x.First().get_Vendedor(); + list.TodosVendedores = ( + from x in vendedor + orderby x.get_Nome() + select x).ToList(); + } + Documento selectedDocumento = this.SelectedDocumento; + if (selectedDocumento != null) + { + vendedores = selectedDocumento.get_Vendedores(); + } + else + { + vendedores = null; + } + List vendedors2 = vendedores; + if (vendedors2 == null) + { + Documento documento = this.SelectedDocumento; + if (documento != null) + { + id = documento.get_Id() > (long)0; + } + else + { + id = false; + } + if (!id) + { + vendedors1 = new List(); + } + else + { + vendedors1 = await this.ParcelaServico.BuscarVendedores(this.SelectedDocumento.get_Id()); + } + vendedors2 = vendedors1; + } + List vendedors3 = vendedors2; + this.Vendedores = this.TodosVendedores.Where((Vendedor x) => { + if (x.get_IdEmpresa() != Recursos.Usuario.get_IdEmpresa()) + { + List vendedors = vendedors3; + Func u003cu003e9_1475 = BaseApoliceViewModel.u003cu003ec.u003cu003e9__147_5; + if (u003cu003e9_1475 == null) + { + u003cu003e9_1475 = (Vendedor y) => y.get_Id(); + BaseApoliceViewModel.u003cu003ec.u003cu003e9__147_5 = u003cu003e9_1475; + } + if (!vendedors.Select(u003cu003e9_1475).Contains(x.get_Id())) + { + return false; + } + } + if (x.get_Ativo()) + { + return !x.get_Corretora(); + } + return false; + }).ToList(); + List vendedorUsuarios = await base.VerificaVinculoVendedor(Recursos.Usuario); + if (vendedorUsuarios.Count > 0) + { + vendedorUsuarios.ForEach((VendedorUsuario x) => vendedors3.Add(x.get_Vendedor())); + this.Vendedores = vendedors3; + } + if (verificarRamo) + { + Documento selectedDocumento1 = this.SelectedDocumento; + if (selectedDocumento1 != null) + { + Controle controle = selectedDocumento1.get_Controle(); + if (controle != null) + { + ramo = controle.get_Ramo(); + } + else + { + ramo = false; + } + } + else + { + ramo = false; + } + if (ramo) + { + for (int i = this.Vendedores.Count - 1; i >= 0; i--) + { + List repasses = this.GetRepasses(this.Vendedores[i]); + List repasses1 = repasses; + if (!repasses1.Any((Gestor.Model.Domain.Seguros.Repasse x) => x.get_Ramo() == null)) + { + List repasses2 = repasses; + Func func1 = func; + if (func1 == null) + { + Func id1 = (Gestor.Model.Domain.Seguros.Repasse x) => x.get_Ramo().get_Id() != this.SelectedDocumento.get_Controle().get_Ramo().get_Id(); + Func func2 = id1; + func = id1; + func1 = func2; + } + if (repasses2.All(func1)) + { + this.Vendedores.Remove(this.Vendedores[i]); + } + } + } + } + } + } + + private void CalculaComissao(Documento documento, ObservableCollection parcelas) + { + decimal? nullable; + decimal? comissaoTotal; + decimal num = (documento.get_AdicionalComiss() ? documento.get_PremioLiquido() + documento.get_PremioAdicional() : documento.get_PremioLiquido()); + decimal comissao = documento.get_Comissao() * new decimal(1, 0, 0, false, 2); + this.Gerada = num * comissao; + this.Recebida = (Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 32) ? parcelas.Where((Parcela x) => { + if (x.get_SubTipo() == 1) + { + return true; + } + return x.get_SubTipo() == 6; + }).Sum((Parcela x) => x.get_ValorComissao()) : ( + from x in parcelas + where x.get_SubTipo() == 1 + select x).Sum((Parcela x) => x.get_ValorComissao())); + this.Pendente = this.Gerada - this.Recebida; + this.Pendente = (this.Pendente < new decimal(1, 0, 0, false, 2) ? new decimal(0, 0, 0, false, 2) : this.Pendente); + this.Repasse = this.Repasses.Where((VendedorParcela x) => { + if (!x.get_DataPrePagamento().HasValue) + { + return false; + } + return !x.get_CoCorretagem(); + }).Sum((VendedorParcela x) => x.get_ValorRepasse().GetValueOrDefault()); + if (this.Pendente < this.Tolerancia) + { + this.Pendente = decimal.Zero; + } + if (this.VerificaCoCorretagem()) + { + Documento selectedDocumento = this.SelectedDocumento; + if (selectedDocumento != null) + { + comissaoTotal = selectedDocumento.get_ComissaoTotal(); + } + else + { + nullable = null; + comissaoTotal = nullable; + } + nullable = comissaoTotal; + this.ComissOriginal = nullable.GetValueOrDefault(); + } + } + + public VendedorParcela CalculaRepasse(Gestor.Model.Domain.Seguros.Repasse repasse, TipoVendedor tipoVendedor) + { + NegocioCorretora? negocioCorretora = this.SelectedDocumento.get_NegocioCorretora(); + bool valueOrDefault = negocioCorretora.GetValueOrDefault() == 1; + if (this.SelectedParcela == null) + { + Parcela parcela = new Parcela(); + parcela.set_SubTipo(1); + parcela.set_IdEmpresa(this.SelectedDocumento.get_Controle().get_IdEmpresa()); + this.SelectedParcela = parcela; + } + this.SelectedParcela.set_Documento(this.SelectedDocumento); + decimal num = Funcoes.CalculaRepasse(repasse, this.SelectedParcela, true); + VendedorParcela vendedorParcela = new VendedorParcela(); + vendedorParcela.set_Repasse(repasse); + vendedorParcela.set_ValorRepasse(new decimal?(num)); + vendedorParcela.set_ValorTotal(new decimal?(num)); + vendedorParcela.set_Vendedor(repasse.get_Vendedor()); + vendedorParcela.set_PorcentagemRepasse(new decimal?((valueOrDefault ? repasse.get_ValorRenovacao() : repasse.get_ValorNovo()))); + vendedorParcela.set_TipoVendedor(tipoVendedor); + vendedorParcela.set_CoCorretagem((repasse != null ? repasse.get_Tipo().GetValueOrDefault() == 3 : false)); + return vendedorParcela; + } + + public async Task CancelarAlteracao() + { + this.Acesso = 0; + if (this.CancelDocumento == null || this.CancelDocumento.get_Id() == 0) + { + this.SelectedDocumento = null; + } + else + { + await this.SelecionaDocumento(this.CancelDocumento); + } + this.Anotacoes = string.Empty; + base.EnableFields = false; + Action enableMainMenu = Gestor.Application.Actions.Actions.EnableMainMenu; + if (enableMainMenu != null) + { + enableMainMenu(true); + } + else + { + } + Action enableMenu = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu != null) + { + enableMenu(true); + } + else + { + } + Action enablePesquisarClientes = Gestor.Application.Actions.Actions.EnablePesquisarClientes; + if (enablePesquisarClientes != null) + { + enablePesquisarClientes(true); + } + else + { + } + } + + public async void CancelPagamento() + { + ObservableCollection observableCollection; + this.BaixarParcelas = false; + this.SelectedParcela.set_Baixando(false); + ObservableCollection observableCollection1 = await this.ParcelaServico.BuscarParcelasAsync(this.SelectedDocumento.get_Id()); + BaseApoliceViewModel baseApoliceViewModel = this; + if (this.IsFatura) + { + ObservableCollection observableCollection2 = observableCollection1; + observableCollection = new ObservableCollection( + from x in observableCollection2 + orderby x.get_NumeroParcela() descending + select x); + } + else + { + observableCollection = observableCollection1; + } + baseApoliceViewModel.Parcelas = observableCollection; + await this.CarregaRepasse(this.SelectedDocumento.get_Id()); + await this.SelecionaParcela(this.Parcelas.FirstOrDefault()); + } + + public async Task CarregaRepasse(long id) + { + this.Repasses = await this.VendedorServico.BuscaRepasse(id); + BaseApoliceViewModel baseApoliceViewModel = this; + Parcela selectedParcela = this.SelectedParcela; + if (selectedParcela == null) + { + selectedParcela = this.Parcelas.FirstOrDefault(); + } + await baseApoliceViewModel.SelecionaParcela(selectedParcela); + } + + public async Task CarregarImposto() + { + List impostos = await (new ImpostoServico()).Buscar(new bool?(true)); + Gestor.Model.Domain.Ferramentas.Imposto imposto = impostos.FirstOrDefault((Gestor.Model.Domain.Ferramentas.Imposto x) => { + if (x.get_Seguradora() == null || x.get_Seguradora().get_Id() != this.SelectedDocumento.get_Controle().get_Seguradora().get_Id() || x.get_Ramo() == null) + { + return false; + } + return x.get_Ramo().get_Id() == this.SelectedDocumento.get_Controle().get_Ramo().get_Id(); + }); + if (imposto == null) + { + imposto = impostos.FirstOrDefault((Gestor.Model.Domain.Ferramentas.Imposto x) => { + if (x.get_Seguradora() == null || x.get_Seguradora().get_Id() != this.SelectedDocumento.get_Controle().get_Seguradora().get_Id()) + { + return false; + } + return x.get_Ramo() == null; + }); + } + if (imposto == null) + { + imposto = impostos.FirstOrDefault((Gestor.Model.Domain.Ferramentas.Imposto x) => { + if (x.get_Seguradora() != null || x.get_Ramo() == null) + { + return false; + } + return x.get_Ramo().get_Id() == this.SelectedDocumento.get_Controle().get_Ramo().get_Id(); + }); + } + if (imposto == null) + { + List impostos1 = impostos; + imposto = impostos1.FirstOrDefault((Gestor.Model.Domain.Ferramentas.Imposto x) => { + if (x.get_Seguradora() != null) + { + return false; + } + return x.get_Ramo() == null; + }); + } + Gestor.Model.Domain.Ferramentas.Imposto imposto1 = imposto; + BaseApoliceViewModel baseApoliceViewModel = this; + Gestor.Model.Domain.Ferramentas.Imposto imposto2 = imposto1; + if (imposto2 == null) + { + imposto2 = new Gestor.Model.Domain.Ferramentas.Imposto(); + } + baseApoliceViewModel.Imposto = imposto2; + } + + public async Task CarregarParcelas(Documento documento) + { + ObservableCollection observableCollection; + if (documento != null) + { + ObservableCollection observableCollection1 = await this.ParcelaServico.BuscarParcelasPorDocumento(documento); + BaseApoliceViewModel baseApoliceViewModel = this; + if (this.IsFatura) + { + ObservableCollection observableCollection2 = observableCollection1; + observableCollection = new ObservableCollection( + from x in observableCollection2 + orderby x.get_NumeroParcela() descending + select x); + } + else + { + observableCollection = observableCollection1; + } + baseApoliceViewModel.Parcelas = observableCollection; + if (this.Invoke) + { + Action recarregarParcelas = Gestor.Application.Actions.Actions.RecarregarParcelas; + if (recarregarParcelas != null) + { + recarregarParcelas(this.SelectedDocumento); + } + else + { + } + } + } + } + + public bool CompararValores() + { + if (this.SelectedDocumento.get_Id() == 0 || this.SelectedDocumento.HasChange("PremioLiquido") || this.SelectedDocumento.HasChange("PremioAdicional") || this.SelectedDocumento.HasChange("Comissao") || this.SelectedDocumento.HasChange("Iof")) + { + return true; + } + return this.SelectedDocumento.HasChange("AdicionalComiss"); + } + + private void CriarParcelas(bool insert) + { + if (this.Repasses == null) + { + this.Repasses = new List(); + } + var list = this.Repasses.Where((VendedorParcela x) => { + if (insert) + { + return true; + } + return x.get_Parcela().get_SubTipo() == 1; + }).GroupBy((VendedorParcela x) => new { Repasse = x.get_Repasse(), TipoVendedor = x.get_TipoVendedor() }).Distinct().ToList(); + List vendedorParcelas = new List(); + list.ForEach((x) => { + decimal num; + if (x.Key.Repasse == null) + { + return; + } + VendedorParcela vendedorParcela = this.CalculaRepasse(x.Key.Repasse, x.Key.TipoVendedor); + if (vendedorParcela.get_Repasse().get_Forma().GetValueOrDefault() == 3) + { + VendedorParcela vendedorParcela1 = vendedorParcela; + decimal? valorRepasse = vendedorParcela1.get_ValorRepasse(); + num = (this.SelectedDocumento.get_NumeroParcelas() > decimal.Zero ? this.SelectedDocumento.get_NumeroParcelas() : decimal.One); + vendedorParcela1.set_ValorRepasse((valorRepasse.HasValue ? new decimal?(valorRepasse.GetValueOrDefault() / num) : null)); + } + vendedorParcelas.Add(vendedorParcela); + }); + if (vendedorParcelas.All((VendedorParcela x) => x.get_TipoVendedor().get_Id() != (long)1)) + { + vendedorParcelas.Add(this.PropriaCorretora()); + } + this.Parcelas = new ObservableCollection(this.CriarParcelas(vendedorParcelas)); + } + + private List CriarParcelas(List vendedores) + { + TipoPagamento tipoPagamento; + List parcelas = new List(); + if (this.SelectedDocumento.get_NumeroParcelas() == decimal.Zero) + { + return parcelas; + } + decimal premioTotal = this.SelectedDocumento.get_PremioTotal() / this.SelectedDocumento.get_NumeroParcelas(); + FormaPagamento? formaPagamento = this.SelectedDocumento.get_FormaPagamento(); + if (!formaPagamento.HasValue) + { + this.SelectedDocumento.set_FormaPagamento(new FormaPagamento?(0)); + } + for (int i = 1; i <= this.SelectedDocumento.get_NumeroParcelas(); i++) + { + Parcela parcela = new Parcela(); + parcela.set_IdEmpresa(this.SelectedDocumento.get_Controle().get_IdEmpresa()); + parcela.set_NumeroParcela(i); + parcela.set_Valor(premioTotal); + parcela.set_Comissao(this.SelectedDocumento.get_Comissao()); + DateTime vigencia1 = this.SelectedDocumento.get_Vigencia1(); + parcela.set_Vencimento(vigencia1.AddMonths(i - 1)); + parcela.set_SubTipo(1); + parcela.set_Vendedores(new ObservableCollection((i == 1 ? vendedores : vendedores.Where((VendedorParcela x) => { + Gestor.Model.Domain.Seguros.Repasse repasse = x.get_Repasse(); + if (repasse == null) + { + return false; + } + return repasse.get_Forma().GetValueOrDefault() == 3; + }).ToList()))); + formaPagamento = this.SelectedDocumento.get_FormaPagamento(); + if (formaPagamento.GetValueOrDefault() == 0 & formaPagamento.HasValue) + { + tipoPagamento = 7; + } + else + { + formaPagamento = this.SelectedDocumento.get_FormaPagamento(); + if (formaPagamento.GetValueOrDefault() == 1) + { + tipoPagamento = 3; + } + else + { + formaPagamento = this.SelectedDocumento.get_FormaPagamento(); + if (formaPagamento.GetValueOrDefault() == 2) + { + tipoPagamento = 15; + } + else + { + formaPagamento = this.SelectedDocumento.get_FormaPagamento(); + tipoPagamento = (formaPagamento.GetValueOrDefault() != 3 || i != 1 ? 7 : 15); + } + } + } + parcela.set_TipoPagamento(tipoPagamento); + parcela.set_DataCriacao(new DateTime?(Funcoes.GetNetworkTime())); + parcela.set_UsuarioCriacao(Recursos.Usuario.get_Id()); + parcelas.Add(parcela); + } + return parcelas; + } + + private List CriarRepasses(VendedorParcela repasse) + { + decimal? nullable; + if (this.Parcelas == null || this.Parcelas.Count == 0 || this.SelectedDocumento == null) + { + return null; + } + List vendedorParcelas = new List(); + VendedorParcela vendedorParcela1 = repasse; + if (repasse.get_Repasse().get_Forma().GetValueOrDefault() == 3) + { + decimal? valorRepasse = repasse.get_ValorRepasse(); + decimal numeroParcelas = this.SelectedDocumento.get_NumeroParcelas(); + if (valorRepasse.HasValue) + { + nullable = new decimal?(valorRepasse.GetValueOrDefault() / numeroParcelas); + } + else + { + nullable = null; + } + } + else + { + nullable = repasse.get_ValorRepasse(); + } + vendedorParcela1.set_ValorRepasse(nullable); + this.Parcelas.ToList().ForEach((Parcela x) => { + if (repasse.get_Repasse().get_Forma().GetValueOrDefault() != 3 && x.get_NumeroParcela() > 1) + { + return; + } + VendedorParcela vendedorParcela = (VendedorParcela)repasse.Clone(); + if (repasse.get_Repasse().get_Forma().GetValueOrDefault() == 3) + { + vendedorParcela.set_DataPrePagamento(new DateTime?(x.get_Vencimento())); + } + vendedorParcela.set_Parcela(x); + vendedorParcelas.Add(vendedorParcela); + }); + return vendedorParcelas; + } + + private async Task DesfazerAlteracoes() + { + IEnumerable list; + ItemServico itemServico = new ItemServico(); + IList documentos = this.SelectedDocumento.get_Controle().get_Documentos(); + ObservableCollection observableCollection = await itemServico.BuscarItems(documentos.FirstOrDefault((Documento x) => { + if (x.get_Excluido() || x.get_Situacao() == 7) + { + return false; + } + return x.get_Ordem() == 0; + }).get_Id(), 2, false); + ObservableCollection observableCollection1 = await (new ItemServico()).BuscarItems(this.SelectedDocumento.get_Id(), 2, false); + ObservableCollection observableCollection2 = observableCollection1; + List items = observableCollection.Where((Item x) => { + long? idDocumentoCancelado = x.get_IdDocumentoCancelado(); + long id = this.SelectedDocumento.get_Id(); + return idDocumentoCancelado.GetValueOrDefault() == id & idDocumentoCancelado.HasValue; + }).ToList(); + List items1 = items; + IEnumerable items2 = observableCollection.Where((Item x) => { + long? nullable; + long? nullable1 = x.get_Substituido(); + if (!nullable1.HasValue) + { + return false; + } + nullable1 = x.get_Substituido(); + Item item = observableCollection2.FirstOrDefault((Item d) => { + long id = d.get_Id(); + long? substituido = x.get_Substituido(); + return id == substituido.GetValueOrDefault() & substituido.HasValue; + }); + if (item != null) + { + nullable = new long?(item.get_Id()); + } + else + { + nullable = null; + } + long? nullable2 = nullable; + return nullable1.GetValueOrDefault() == nullable2.GetValueOrDefault() & nullable1.HasValue == nullable2.HasValue; + }); + if (items2 != null) + { + list = items2.ToList(); + } + else + { + list = null; + } + items1.AddRange(list); + if (items.Count == 0) + { + items = observableCollection.Where((Item x) => { + if (x.get_Status() == null || Gestor.Common.Validation.ValidationHelper.IsNullOrEmpty(x.get_Status()) || !x.get_Status().Contains("ORDEM")) + { + return false; + } + return x.get_Status().Replace("ORDEM", "-").Split(new char[] { '-' })[1].Trim().Equals(string.Format("{0}", this.SelectedDocumento.get_Ordem())); + }).ToList(); + } + foreach (Item item1 in items) + { + await (new ItemServico()).Reativar(item1, ""); + } + observableCollection = null; + } + + public void EditarParcelaEspecial() + { + this.AllowEditVendedor = true; + } + + public async Task EditarParcelas() + { + if (this.DocumentoSelecionado == null) + { + this.DocumentoSelecionado = this.SelectedDocumento; + } + await base.ShowEditarParcelasDialog(this.DocumentoSelecionado); + await this.CarregarParcelas(this.DocumentoSelecionado); + } + + public async Task ExcluirApolice() + { + string str; + int ordem; + string str1; + string str2; + TipoSeguro value; + int? nullable; + Documento selectedDocumento; + string str3; + string str4; + if (this.SelectedDocumento != null) + { + if (this.AllowEditApolice) + { + ObservableCollection parcelas = this.Parcelas; + if (!parcelas.Any((Parcela x) => x.get_DataRecebimento().HasValue)) + { + List repasses = this.Repasses; + if (!repasses.Any((VendedorParcela x) => x.get_DataPagamento().HasValue)) + { + if (this.SelectedDocumento.get_Tipo() <= 0 || !this.SelectedDocumento.get_Sinistro()) + { + selectedDocumento = this.SelectedDocumento; + if (selectedDocumento.get_Tipo() != 0 || !string.IsNullOrEmpty(selectedDocumento.get_Apolice())) + { + str = (selectedDocumento.get_Tipo() != 0 || string.IsNullOrEmpty(selectedDocumento.get_Apolice()) ? "O ENDOSSO SELECIONADO" : "A APÓLICE SELECIONADA"); + } + else + { + str = "A PROPOSTA SELECIONADA"; + } + str3 = str; + int num = this.SelectedDocumento.get_Ordem(); + IList documentos = this.SelectedDocumento.get_Controle().get_Documentos(); + Documento documento = ( + from x in documentos + orderby x.get_Ordem() descending + select x).FirstOrDefault((Documento x) => { + if (!x.get_Excluido() && x.get_Situacao() != 7) + { + return true; + } + return x.get_Id() == this.SelectedDocumento.get_Id(); + }); + if (documento != null) + { + ordem = documento.get_Ordem(); + } + else + { + ordem = this.SelectedDocumento.get_Ordem(); + } + if (num == ordem) + { + string[] newLine = new string[] { "DESEJA REALMENTE EXCLUIR ", str3, "?", Environment.NewLine, "ESSE PROCEDIMENTO É IRREVERSÍVEL." }; + if (await base.ShowMessage(string.Concat(newLine), "SIM", "NÃO", false)) + { + bool hasValue = selectedDocumento.get_TipoEndosso().HasValue; + if (hasValue) + { + hasValue = await base.ShowMessage("DESEJA DESFAZER AS ALTERAÇOES NOS ITENS VINCULADOS A ESSE ENDOSSO ?", "SIM", "NÃO", false); + } + if (hasValue) + { + IList documentos1 = this.SelectedDocumento.get_Controle().get_Documentos(); + Documento documento1 = ( + from x in documentos1 + orderby x.get_Ordem() descending + select x).FirstOrDefault((Documento x) => { + if (x.get_Excluido() || x.get_Situacao() == 7) + { + return false; + } + return x.get_Ordem() > this.SelectedDocumento.get_Ordem(); + }); + if (documento1 != null) + { + nullable = new int?(documento1.get_Ordem()); + } + else + { + nullable = null; + } + int? nullable1 = nullable; + int ordem1 = this.SelectedDocumento.get_Ordem(); + if (!(nullable1.GetValueOrDefault() > ordem1 & nullable1.HasValue)) + { + await this.DesfazerAlteracoes(); + } + else + { + await base.ShowMessage(string.Concat("NÃO É POSSIVEL DESFAZER AS ALTERAÇÕES, POIS ", str3, " POSSUE ENDOSSOS ATIVOS ACIMA."), "OK", "", false); + selectedDocumento = null; + str3 = null; + str4 = null; + return; + } + } + if (selectedDocumento.get_Tipo() == 0 && string.IsNullOrEmpty(selectedDocumento.get_Apolice())) + { + str1 = string.Concat("EXCLUIU PROPOSTA ", selectedDocumento.get_Proposta()); + } + else if (selectedDocumento.get_Tipo() != 0 || string.IsNullOrEmpty(selectedDocumento.get_Apolice())) + { + str1 = (string.IsNullOrEmpty(selectedDocumento.get_Endosso()) ? string.Concat("EXCLUIU PROPOSTA DE ENDOSSO ", selectedDocumento.get_PropostaEndosso()) : string.Concat("EXCLUIU ENDOSSO ", selectedDocumento.get_Endosso())); + } + else + { + str1 = string.Concat("EXCLUIU APÓLICE ", selectedDocumento.get_Apolice()); + } + string str5 = str1; + base.RegistrarAcao(str5, this.SelectedDocumento.get_Id(), new TipoTela?(2), this.GerarObs(selectedDocumento)); + base.Loading(true); + if (selectedDocumento.get_Tipo() != 0 || !string.IsNullOrEmpty(selectedDocumento.get_Apolice())) + { + str2 = (selectedDocumento.get_Tipo() != 0 || string.IsNullOrEmpty(selectedDocumento.get_Apolice()) ? "ENDOSSO EXCLUÍDO" : "APÓLICE EXCLUÍDA"); + } + else + { + str2 = "PROPOSTA EXCLUÍDA"; + } + str4 = str2; + selectedDocumento.set_Excluido(true); + this.Servico.Sucesso = true; + await this.Servico.ExcluirCritica(selectedDocumento.get_Id()); + if (this.Servico.Sucesso) + { + Gestor.Application.Servicos.TarefaServico tarefaServico = this.TarefaServico; + hasValue = await this.TarefaServico.ExcluirTarefasDocumento(selectedDocumento.get_Id()); + tarefaServico.Sucesso = hasValue; + tarefaServico = null; + if (this.TarefaServico.Sucesso) + { + this.Servico.Sucesso = true; + if (selectedDocumento.get_TipoEndosso().HasValue && selectedDocumento.get_TipoEndosso().GetValueOrDefault() == 2) + { + IList documentos2 = this.CancelDocumento.get_Controle().get_Documentos(); + Documento documento2 = documentos2.FirstOrDefault((Documento x) => { + if (x.get_Tipo() != 0) + { + return false; + } + return !x.get_Excluido(); + }); + IList documentos3 = this.CancelDocumento.get_Controle().get_Documentos(); + List list = documentos3.Where((Documento x) => { + if (x.get_Tipo() != 1) + { + return false; + } + return !x.get_Excluido(); + }).ToList(); + if (documento2 != null) + { + Documento documento3 = documento2; + if (!documento2.get_SituacaoAnterior().HasValue || documento2.get_SituacaoAnterior().GetValueOrDefault() == 3) + { + value = (documento2.get_NegocioCorretora().GetValueOrDefault() == 1 ? 2 : 1); + } + else + { + value = documento2.get_SituacaoAnterior().Value; + } + documento3.set_Situacao(value); + await this.Servico.Save(documento2, false, false); + foreach (Documento documento4 in list) + { + documento4.set_Situacao(documento2.get_Situacao()); + await this.Servico.Save(documento4, false, false); + } + } + documento2 = null; + list = null; + } + await this.Servico.Excluir(selectedDocumento); + if (this.Servico.Sucesso) + { + if (selectedDocumento.get_Tipo() > 0) + { + await Funcoes.OrganizarDocumentos(selectedDocumento.get_Controle().get_Id()); + await Funcoes.InativarItens(selectedDocumento.get_Id(), selectedDocumento.get_Controle().get_Ramo().get_Id(), true); + } + if (this.Invoke) + { + ConsultaViewModel.DocumentoSelecionado = null; + Action recarregarDocumentos = Gestor.Application.Actions.Actions.RecarregarDocumentos; + if (recarregarDocumentos != null) + { + recarregarDocumentos(null); + } + else + { + } + } + base.Loading(false); + base.ToggleSnackBar(string.Concat(str4, " COM SUCESSO"), true); + if (this.Invoke) + { + Action acessaTela = Gestor.Application.Actions.Actions.AcessaTela; + if (acessaTela != null) + { + acessaTela(21, ""); + } + else + { + } + } + selectedDocumento = null; + str3 = null; + str4 = null; + return; + } + else + { + base.Loading(false); + selectedDocumento = null; + str3 = null; + str4 = null; + return; + } + } + else + { + base.Loading(false); + selectedDocumento = null; + str3 = null; + str4 = null; + return; + } + } + else + { + base.Loading(false); + selectedDocumento = null; + str3 = null; + str4 = null; + return; + } + } + else + { + selectedDocumento = null; + str3 = null; + str4 = null; + return; + } + } + else + { + await base.ShowMessage(string.Concat(str3, " NÃO PODE SER EXCLUÍDO(A) POIS POSSUEM DOCUMENTOS ATIVOS ACIMA."), "OK", "", false); + selectedDocumento = null; + str3 = null; + str4 = null; + return; + } + } + else + { + await base.ShowMessage("DOCUMENTO NÃO PODE SER EXCLUÍDO POIS POSSUI SINISTROS PARA UM OU MAIS DE SEUS ITENS.", "OK", "", false); + selectedDocumento = null; + str3 = null; + str4 = null; + return; + } + } + } + } + await base.ShowMessage("DOCUMENTO NÃO PODE SER EXCLUÍDO POIS POSSUI BAIXAS DE COMISSÃO OU PAGAMENTO DE VENDEDORES.", "OK", "", false); + } + selectedDocumento = null; + str3 = null; + str4 = null; + } + + internal async Task ExcluirBaixa() + { + string str; + string str1; + bool flag; + if (this.SelectedParcela != null) + { + if (await base.ShowMessage(string.Concat("DESEJA REALMENTE EXCLUIR A BAIXA DA PARCELA SELECIONADA?", Environment.NewLine, "ESSE PROCEDIMENTO É IRREVERSÍVEL."), "SIM", "NÃO", false)) + { + base.Loading(true); + this.SelectedParcela.set_Documento(this.SelectedDocumento); + this.SelectedParcela = await Funcoes.ExcluirBaixa(this.SelectedParcela, this.Repasses, this.Parcelas.ToList()); + if (this.SelectedDocumento.get_Tipo() == 0 && string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + str = string.Concat("PROPOSTA ", this.SelectedDocumento.get_Proposta()); + } + else if (this.SelectedDocumento.get_Tipo() != 0 || string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + str = (string.IsNullOrEmpty(this.SelectedDocumento.get_Endosso()) ? string.Concat("PROPOSTA DE ENDOSSO ", this.SelectedDocumento.get_PropostaEndosso()) : string.Concat("ENDOSSO ", this.SelectedDocumento.get_Endosso())); + } + else + { + str = string.Concat("APÓLICE ", this.SelectedDocumento.get_Apolice()); + } + string str2 = str; + str1 = (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 1 ? string.Format("BAIXA DA PARCELA {0} EXCLUÍDA, {1}", this.SelectedParcela.get_NumeroParcela(), str2) : string.Concat("BAIXA DA FATURA ", this.SelectedParcela.get_Fatura(), " EXCLUÍDA, ", str2)); + string str3 = str1; + base.RegistrarAcao(str3, this.SelectedParcela.get_Id(), new TipoTela?(5), this.GerarObs(this.SelectedDocumento)); + await this.CarregarParcelas(this.SelectedDocumento); + await this.CarregaRepasse(this.SelectedDocumento.get_Id()); + this.CalculaComissao(this.SelectedDocumento, this.Parcelas); + BaseApoliceViewModel baseApoliceViewModel = this; + Parcela selectedParcela = this.SelectedParcela; + if (selectedParcela == null) + { + selectedParcela = this.Parcelas.FirstOrDefault(); + } + await baseApoliceViewModel.SelecionaParcela(selectedParcela); + this.BaixarParcelas = false; + BaseApoliceViewModel baseApoliceViewModel1 = this; + ObservableCollection parcelas = this.Parcelas; + IEnumerable subTipo = + from x in parcelas + where x.get_SubTipo() == 1 + select x; + if (!subTipo.All((Parcela x) => !x.get_DataRecebimento().HasValue)) + { + flag = false; + } + else + { + List repasses = this.Repasses; + IEnumerable vendedorParcelas = + from x in repasses + where x.get_Parcela().get_SubTipo() == 1 + select x; + flag = vendedorParcelas.All((VendedorParcela x) => !x.get_DataPagamento().HasValue); + } + baseApoliceViewModel1.AllowEditApolice = flag; + base.Loading(false); + base.ToggleSnackBar("BAIXA EXCLUÍDA COM SUCESSO", true); + } + } + } + + public async Task ExcluirPagamento(VendedorParcela pagamento) + { + bool flag; + string str; + base.Loading(true); + if (await Funcoes.ExcluirPagamento(pagamento)) + { + base.ToggleSnackBar("PAGAMENTO EXCLUÍDO COM SUCESSO", true); + if (this.SelectedDocumento.get_Tipo() == 0 && string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + str = string.Concat("NA PROPOSTA \"", this.SelectedDocumento.get_Proposta(), "\""); + } + else if (this.SelectedDocumento.get_Tipo() != 0 || string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + str = (string.IsNullOrEmpty(this.SelectedDocumento.get_Endosso()) ? string.Concat("NA PROPOSTA DE ENDOSSO \"", this.SelectedDocumento.get_PropostaEndosso(), "\"") : string.Concat("NO ENDOSSO \"", this.SelectedDocumento.get_Endosso(), "\"")); + } + else + { + str = string.Concat("NA APÓLICE \"", this.SelectedDocumento.get_Apolice(), "\""); + } + string str1 = str; + string str2 = string.Concat("PAGAMENTO DO VENDEDOR ", pagamento.get_Vendedor().get_Nome(), " EXCLUÍDO, ", str1); + long id = pagamento.get_Id(); + TipoTela? nullable = new TipoTela?(37); + object[] objArray = new object[] { this.GerarObs(this.SelectedDocumento), Environment.NewLine, pagamento.get_Vendedor().get_Nome(), Environment.NewLine, pagamento.get_ValorTotal() }; + base.RegistrarAcao(str2, id, nullable, string.Format("{0}{1}VENDEDOR: {2}{3}COMISSÃO TOTAL: {4:C2}", objArray)); + } + await this.CarregarParcelas(this.SelectedDocumento); + await this.CarregaRepasse(this.SelectedDocumento.get_Id()); + await this.SelecionaParcela(this.Parcelas.FirstOrDefault()); + BaseApoliceViewModel baseApoliceViewModel = this; + ObservableCollection parcelas = this.Parcelas; + IEnumerable subTipo = + from x in parcelas + where x.get_SubTipo() == 1 + select x; + if (!subTipo.All((Parcela x) => !x.get_DataRecebimento().HasValue)) + { + flag = false; + } + else + { + List repasses = this.Repasses; + IEnumerable vendedorParcelas = + from x in repasses + where x.get_Parcela().get_SubTipo() == 1 + select x; + flag = vendedorParcelas.All((VendedorParcela x) => !x.get_DataPagamento().HasValue); + } + baseApoliceViewModel.AllowEditApolice = flag; + this.BaixarParcelas = false; + base.Loading(false); + } + + public async Task ExcluirParcela() + { + string str; + string str1; + string str2; + if (this.SelectedParcela != null) + { + if (this.SelectedParcela.get_SubTipo() != 1 || this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() != 1) + { + if (this.SelectedParcela.get_SubTipo() == 1) + { + ObservableCollection parcelas = this.Parcelas; + IOrderedEnumerable numeroParcela = + from x in parcelas + orderby x.get_NumeroParcela() + select x; + Parcela parcela = numeroParcela.Last((Parcela x) => x.get_SubTipo() == 1); + if (this.SelectedParcela.get_Id() != parcela.get_Id()) + { + await base.ShowMessage("A FATURA NÃO PODE SER EXCLUÍDA POIS HÁ FATURAS CADASTRADAS ACIMA DA SELECIONADA.", "OK", "", false); + return; + } + } + if (await base.ShowMessage(string.Concat("DESEJA REALMENTE EXCLUIR A PARCELA SELECIONADA?", Environment.NewLine, "ESSE PROCEDIMENTO É IRREVERSÍVEL."), "SIM", "NÃO", false)) + { + base.Loading(true); + if (await this.ParcelaServico.Delete(this.SelectedParcela, this.Parcelas.ToList())) + { + BaseApoliceViewModel baseApoliceViewModel = this; + str = (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 1 ? "PARCELA EXCLUÍDA COM SUCESSO" : "FATURA EXCLUÍDA COM SUCESSO"); + baseApoliceViewModel.ToggleSnackBar(str, true); + if (this.SelectedDocumento.get_Tipo() == 0 && string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + str1 = string.Concat("PROPOSTA ", this.SelectedDocumento.get_Proposta()); + } + else if (this.SelectedDocumento.get_Tipo() != 0 || string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + str1 = (string.IsNullOrEmpty(this.SelectedDocumento.get_Endosso()) ? string.Concat("PROPOSTA DE ENDOSSO ", this.SelectedDocumento.get_PropostaEndosso()) : string.Concat("ENDOSSO ", this.SelectedDocumento.get_Endosso())); + } + else + { + str1 = string.Concat("APÓLICE ", this.SelectedDocumento.get_Apolice()); + } + string str3 = str1; + str2 = (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 1 ? string.Format("PARCELA {0} EXCLUÍDA, {1}", this.SelectedParcela.get_NumeroParcela(), str3) : string.Concat("FATURA ", this.SelectedParcela.get_Fatura(), " EXCLUÍDA, ", str3)); + string str4 = str2; + base.RegistrarAcao(str4, this.SelectedParcela.get_Id(), new TipoTela?(5), this.GerarObs(this.SelectedDocumento)); + } + await this.CarregarParcelas(this.SelectedDocumento); + await this.CarregaRepasse(this.SelectedDocumento.get_Id()); + await this.SelecionaParcela(this.Parcelas.FirstOrDefault()); + this.BaixarParcelas = false; + if (this.Parcelas == null || this.Parcelas.Count == 0) + { + this.VisibilityExcluirParcela = Visibility.Collapsed; + this.VisibilityReplicarFatura = Visibility.Collapsed; + this.BaixarParcelaVisibility = Visibility.Collapsed; + } + base.Loading(false); + this.AllowEditVendedor = this.Parcelas.Any(); + } + } + } + } + + public async Task ExcluirVendedor(VendedorParcela pagamento, bool incluirCorretora = true) + { + List vendedorParcelas; + bool flag; + Vendedor vendedor; + string str1; + List list; + if (this.IsEndosso && this.SelectedDocumento.get_Id() == 0) + { + this.RemoverVendedor(pagamento.get_Vendedor().get_Id()); + base.ToggleSnackBar("VENDEDOR EXCLUÍDO COM SUCESSO", true); + } + else if (!this.AllowEditApolice && !this.IsFatura && this.SelectedParcela.get_SubTipo() == 1) + { + string[] upper = new string[] { "O VENDEDOR ", pagamento.get_Vendedor().get_Nome().ToUpper(), " NÃO PODE SER EXCLUÍDO.", Environment.NewLine, "JÁ EXISTEM RECEBIMENTOS OU PAGAMENTOS DE COMISSÃO PARA ESSE DOCUMENTO." }; + await base.ShowMessage(string.Concat(upper), "OK", "", false); + } + else if (this.SelectedDocumento.get_Id() > (long)0 && (this.IsFatura || this.SelectedParcela.get_SubTipo() != 1) && (this.SelectedParcela.get_Id() > (long)0 && this.SelectedParcela.get_DataRecebimento().HasValue || this.Repasses.Any((VendedorParcela x) => { + if (x.get_Parcela().get_Id() != this.SelectedParcela.get_Id()) + { + return false; + } + return x.get_DataPagamento().HasValue; + }))) + { + string[] strArrays = new string[] { "O VENDEDOR ", pagamento.get_Vendedor().get_Nome().ToUpper(), " NÃO PODE SER EXCLUÍDO.", Environment.NewLine, "JÁ EXISTEM RECEBIMENTOS OU PAGAMENTOS DE COMISSÃO PARA ESSA FATURA." }; + await base.ShowMessage(string.Concat(strArrays), "OK", "", false); + } + else if (this.SelectedDocumento.get_Id() != 0) + { + vendedorParcelas = (this.SelectedParcela.get_SubTipo() != 1 || this.IsFatura ? this.Repasses.Where((VendedorParcela x) => { + if (x.get_Vendedor().get_Id() != pagamento.get_Vendedor().get_Id()) + { + return false; + } + return x.get_Parcela().get_Id() == this.SelectedParcela.get_Id(); + }).ToList() : this.Repasses.Where((VendedorParcela x) => { + if (x.get_Vendedor().get_Id() != pagamento.get_Vendedor().get_Id()) + { + return false; + } + return x.get_Parcela().get_NumeroParcela() != 999; + }).ToList()); + list = vendedorParcelas.Distinct().ToList(); + if (await this.Servico.ExcluirPagamento(list)) + { + if (this.SelectedParcela.get_Id() > (long)0) + { + if (this.SelectedDocumento.get_Tipo() == 0 && string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + str1 = string.Concat("NA PROPOSTA \"", this.SelectedDocumento.get_Proposta(), "\""); + } + else if (this.SelectedDocumento.get_Tipo() != 0 || string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + str1 = (string.IsNullOrEmpty(this.SelectedDocumento.get_Endosso()) ? string.Concat("NA PROPOSTA DE ENDOSSO \"", this.SelectedDocumento.get_PropostaEndosso(), "\"") : string.Concat("NO ENDOSSO \"", this.SelectedDocumento.get_Endosso(), "\"")); + } + else + { + str1 = string.Concat("NA APÓLICE \"", this.SelectedDocumento.get_Apolice(), "\""); + } + string str2 = str1; + list.ForEach((VendedorParcela x) => { + string str = string.Concat("VENDEDOR ", x.get_Vendedor().get_Nome(), " EXCLUÍDO, ", str2); + base.RegistrarAcao(str, x.get_Id(), new TipoTela?(37), string.Format("{0}{1}VENDEDOR: {2}{3}COMISSÃO TOTAL: {4:C2}", new object[] { this.GerarObs(this.SelectedDocumento), Environment.NewLine, x.get_Vendedor().get_Nome(), Environment.NewLine, x.get_ValorTotal() })); + }); + } + this.RemoverVendedor(pagamento.get_Vendedor().get_Id()); + if (this.IsFatura || this.SelectedParcela.get_SubTipo() != 1) + { + flag = this.Repasses.Any((VendedorParcela x) => { + if (x.get_Parcela().get_Id() != this.SelectedParcela.get_Id()) + { + return false; + } + return x.get_TipoVendedor().get_Id() == (long)1; + }); + } + else + { + List repasses = this.Repasses; + flag = repasses.Any((VendedorParcela x) => { + if (x.get_Parcela().get_SubTipo() != 1 || x.get_TipoVendedor().get_Id() != (long)1) + { + return false; + } + return !x.get_CoCorretagem(); + }); + } + bool flag1 = flag; + if (pagamento.get_TipoVendedor().get_Id() == (long)1 & incluirCorretora && !flag1) + { + VendedorParcela vendedorParcela = await this.IncluirPropriaCorretora(); + if (vendedorParcela != null) + { + this.Repasses.Add(vendedorParcela); + Documento selectedDocumento = this.SelectedDocumento; + List repasses1 = this.Repasses; + VendedorParcela vendedorParcela1 = repasses1.FirstOrDefault((VendedorParcela x) => x.get_TipoVendedor().get_Id() == (long)1); + if (vendedorParcela1 != null) + { + vendedor = vendedorParcela1.get_Vendedor(); + } + else + { + vendedor = null; + } + selectedDocumento.set_VendedorPrincipal(vendedor); + } + } + if (this.Repasses != null) + { + this.Pagamentos = new ObservableCollection(( + from x in this.Repasses + where x.get_Parcela().get_Id() == this.SelectedParcela.get_Id() + select x).ToList()); + } + base.ToggleSnackBar("VENDEDOR EXCLUÍDO COM SUCESSO", true); + this.CalculaComissao(this.SelectedDocumento, this.Parcelas); + } + else + { + BaseApoliceViewModel baseApoliceViewModel = this; + Parcela selectedParcela = this.SelectedParcela; + if (selectedParcela == null) + { + selectedParcela = this.Parcelas.FirstOrDefault(); + } + await baseApoliceViewModel.SelecionaParcela(selectedParcela); + } + } + else + { + this.RemoverVendedor(pagamento.get_Vendedor().get_Id()); + base.ToggleSnackBar("VENDEDOR EXCLUÍDO COM SUCESSO", true); + } + list = null; + } + + public void FiltrarRepasse(Vendedor vendedor) + { + if (this.SelectedPagamento == null) + { + this.SelectedPagamento = new VendedorParcela(); + } + this.SelectedPagamento.set_Vendedor(vendedor); + this.RepassesVendedor = this.GetRepasses(vendedor); + } + + public string GerarObs(Documento doc) + { + if (doc.get_Tipo() == 0) + { + return string.Format("CLIENTE: {0}{1}CÓDIGO: {2}{3}PROPOSTA: {4}{5}APÓLICE: {6}", new object[] { doc.get_Controle().get_Cliente().get_Nome(), Environment.NewLine, doc.get_Id(), Environment.NewLine, doc.get_Proposta(), Environment.NewLine, doc.get_Apolice() }); + } + return string.Format("CLIENTE: {0}{1}CÓDIGO: {2}{3}PROPOSTA: {4}{5}APÓLICE: {6}{7}PROPOSTA DE ENDOSSO: {8}{9}ENDOSSO: {10}", new object[] { doc.get_Controle().get_Cliente().get_Nome(), Environment.NewLine, doc.get_Id(), Environment.NewLine, doc.get_Proposta(), Environment.NewLine, doc.get_Apolice(), Environment.NewLine, doc.get_PropostaEndosso(), Environment.NewLine, doc.get_Endosso() }); + } + + public List GetRepasses(Vendedor vendedor) + { + List repasses; + if (this.CoCorretagem) + { + IEnumerable repassesVendedores = + from x in this.RepassesVendedores + where x.get_Vendedor().get_Id() == vendedor.get_Id() + select x; + if (repassesVendedores == null) + { + return null; + } + IEnumerable valueOrDefault = + from x in repassesVendedores + where x.get_Tipo().GetValueOrDefault() == 3 + select x; + if (valueOrDefault == null) + { + return null; + } + return ( + from x in valueOrDefault + orderby x.get_ValorNovo() + select x).ToList(); + } + if (Recursos.Configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 20)) + { + IEnumerable repassesVendedores1 = + from x in this.RepassesVendedores + where x.get_Vendedor().get_Id() == vendedor.get_Id() + select x; + if (repassesVendedores1 == null) + { + return null; + } + return ( + from x in repassesVendedores1 + where x.get_Tipo().GetValueOrDefault() != 3 + orderby x.get_ValorNovo() + select x).ToList(); + } + repasses = (!this.RepassesVendedores.Any((Gestor.Model.Domain.Seguros.Repasse x) => { + if (x.get_Vendedor().get_Id() != vendedor.get_Id() || x.get_Ramo() == null) + { + return false; + } + return x.get_Ramo().get_Id() == this.SelectedDocumento.get_Controle().get_Ramo().get_Id(); + }) ? this.RepassesVendedores.Where((Gestor.Model.Domain.Seguros.Repasse x) => { + if (x.get_Vendedor().get_Id() != vendedor.get_Id()) + { + return false; + } + return x.get_Ramo() == null; + }).OrderBy((Gestor.Model.Domain.Seguros.Repasse x) => x.get_ValorNovo()).ToList() : this.RepassesVendedores.Where((Gestor.Model.Domain.Seguros.Repasse x) => { + if (x.get_Vendedor().get_Id() != vendedor.get_Id() || x.get_Ramo() == null) + { + return false; + } + return x.get_Ramo().get_Id() == this.SelectedDocumento.get_Controle().get_Ramo().get_Id(); + }).OrderBy((Gestor.Model.Domain.Seguros.Repasse x) => x.get_ValorNovo()).ToList()); + return repasses; + } + + public List> HabilitarVendedor(int editarParcelaTipo = 0) + { + IEnumerable u00210s; + List> keyValuePairs = new List>(); + if (editarParcelaTipo != 4) + { + keyValuePairs.AddRange(this.SelectedDocumento.Validate(this.IsEndosso, Recursos.Configuracoes.Any((ConfiguracaoSistema c) => c.get_Configuracao() == 11))); + } + else if (this.SelectedParcela != null) + { + List> keyValuePairs1 = keyValuePairs; + Parcela selectedParcela = this.SelectedParcela; + if (selectedParcela != null) + { + u00210s = selectedParcela.Validate(Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 9), Recursos.Configuracoes.Any((ConfiguracaoSistema y) => y.get_Configuracao() == 11), this.EditandoParcela, Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 16)); + } + else + { + u00210s = null; + } + keyValuePairs1.AddRange(u00210s); + } + return keyValuePairs; + } + + public async Task Importacao() + { + DateTime? dataCriacao; + DateTime? dataImportacao; + RegistroLog registroLog; + DateTime? nullable; + object nome; + string str; + object obj; + string str1; + bool flag; + string str2; + DateTime? nullable1; + object nome1; + bool flag1; + string str3; + DateTime? nullable2; + object obj1; + string str4; + string str5; + List criticaApolices = await (new CriticaApoliceServico()).BuscarImportacao(this.SelectedDocumento.get_Id()); + List list = await (new LogServico()).FindByEntityId(2, this.SelectedDocumento.get_Id()).ToList(); + if (list.Count > 0) + { + registroLog = list.Last(); + } + else + { + registroLog = null; + } + RegistroLog registroLog1 = registroLog; + switch (criticaApolices.Count) + { + case 0: + { + BaseApoliceViewModel baseApoliceViewModel = this; + dataCriacao = this.SelectedDocumento.get_DataCriacao(); + if (!dataCriacao.HasValue) + { + if (registroLog1 != null) + { + nome = registroLog1.get_Usuario().get_Nome(); + } + else + { + nome = null; + } + if (registroLog1 != null) + { + nullable = new DateTime?(registroLog1.get_DataHora()); + } + else + { + dataCriacao = null; + nullable = dataCriacao; + } + str = string.Format("CADASTRO MANUAL: {0} - {1:dd/MM/yyyy 'ÀS' HH:mm:ss}", nome, nullable); + } + else + { + Usuario usuarioCriacao = this.SelectedDocumento.get_UsuarioCriacao(); + if (usuarioCriacao != null) + { + obj = usuarioCriacao.get_Nome(); + } + else + { + obj = null; + } + str = string.Format("CADASTRO MANUAL: {0} - {1:dd/MM/yyyy 'ÀS' HH:mm:ss}", obj, this.SelectedDocumento.get_DataCriacao()); + } + baseApoliceViewModel.Importado = str; + break; + } + case 1: + { + if (string.IsNullOrWhiteSpace(criticaApolices[0].get_Tipo()) || criticaApolices[0].get_Tipo() == "0") + { + BaseApoliceViewModel baseApoliceViewModel1 = this; + str1 = (!criticaApolices[0].get_Aggilizador().HasValue || !criticaApolices[0].get_Aggilizador().Value ? string.Format("IMPORTAÇÃO DA PROPOSTA: {0} - {1:dd/MM/yyyy 'ÀS' HH:mm:ss}", criticaApolices[0].get_UsuarioImportacao().get_Nome(), criticaApolices[0].get_DataImportacao()) : string.Format("IMPORTAÇÃO DA PROPOSTA VIA AGGILIZADOR: {0} - {1:dd/MM/yyyy 'ÀS' HH:mm:ss}", criticaApolices[0].get_UsuarioImportacao().get_Nome(), criticaApolices[0].get_DataImportacao())); + baseApoliceViewModel1.Importado = str1; + } + if (criticaApolices[0].get_Tipo() == "1") + { + dataCriacao = this.SelectedDocumento.get_DataCriacao(); + if (dataCriacao.HasValue) + { + dataCriacao = criticaApolices[0].get_DataImportacao(); + if (dataCriacao.HasValue) + { + dataCriacao = this.SelectedDocumento.get_DataCriacao(); + DateTime value = dataCriacao.Value; + dataCriacao = criticaApolices[0].get_DataImportacao(); + if (DateTime.Compare(value, dataCriacao.Value) < 0) + { + this.Importado = string.Format("CADASTRO MANUAL DA PROPOSTA: {0} - {1:dd/MM/yyyy 'ÀS' HH:mm:ss}\n", this.SelectedDocumento.get_UsuarioCriacao(), this.SelectedDocumento.get_DataCriacao()); + } + } + } + else + { + BaseApoliceViewModel baseApoliceViewModel2 = this; + if (registroLog1 != null) + { + obj1 = registroLog1.get_Usuario().get_Nome(); + } + else + { + obj1 = null; + } + if (registroLog1 != null) + { + nullable2 = new DateTime?(registroLog1.get_DataHora()); + } + else + { + dataCriacao = null; + nullable2 = dataCriacao; + } + baseApoliceViewModel2.Importado = string.Format("CADASTRO MANUAL DA PROPOSTA: {0} - {1:dd/MM/yyyy 'ÀS' HH:mm:ss}\n", obj1, nullable2); + } + dataCriacao = this.SelectedDocumento.get_DataCriacao(); + dataImportacao = criticaApolices[0].get_DataImportacao(); + flag1 = (dataCriacao.HasValue & dataImportacao.HasValue ? dataCriacao.GetValueOrDefault() <= dataImportacao.GetValueOrDefault() : false); + if (flag1) + { + BaseApoliceViewModel baseApoliceViewModel3 = this; + str3 = (!criticaApolices[0].get_Aggilizador().HasValue || !criticaApolices[0].get_Aggilizador().Value ? string.Format("IMPORTAÇÃO DA APÓLICE: {0} - {1:dd/MM/yyyy 'ÀS' HH:mm:ss}", criticaApolices[0].get_UsuarioImportacao().get_Nome(), criticaApolices[0].get_DataImportacao()) : string.Format("IMPORTAÇÃO DA APÓLICE VIA AGGILIZADOR: {0} - {1:dd/MM/yyyy 'ÀS' HH:mm:ss}", criticaApolices[0].get_UsuarioImportacao().get_Nome(), criticaApolices[0].get_DataImportacao())); + baseApoliceViewModel3.Importado = str3; + } + } + if (criticaApolices[0].get_Tipo() != "2") + { + break; + } + dataImportacao = this.SelectedDocumento.get_DataCriacao(); + if (dataImportacao.HasValue) + { + dataImportacao = criticaApolices[0].get_DataImportacao(); + if (dataImportacao.HasValue) + { + dataImportacao = this.SelectedDocumento.get_DataCriacao(); + DateTime dateTime = dataImportacao.Value; + dataImportacao = criticaApolices[0].get_DataImportacao(); + if (DateTime.Compare(dateTime, dataImportacao.Value) < 0) + { + this.Importado = string.Format("CADASTRO MANUAL DA PROPOSTA: {0} - {1:dd/MM/yyyy 'ÀS' HH:mm:ss}\n", this.SelectedDocumento.get_UsuarioCriacao(), this.SelectedDocumento.get_DataCriacao()); + } + } + } + else + { + BaseApoliceViewModel baseApoliceViewModel4 = this; + if (registroLog1 != null) + { + nome1 = registroLog1.get_Usuario().get_Nome(); + } + else + { + nome1 = null; + } + if (registroLog1 != null) + { + nullable1 = new DateTime?(registroLog1.get_DataHora()); + } + else + { + dataImportacao = null; + nullable1 = dataImportacao; + } + baseApoliceViewModel4.Importado = string.Format("CADASTRO MANUAL DA PROPOSTA: {0} - {1:dd/MM/yyyy 'ÀS' HH:mm:ss}\n", nome1, nullable1); + } + dataImportacao = this.SelectedDocumento.get_DataCriacao(); + dataCriacao = criticaApolices[0].get_DataImportacao(); + flag = (dataImportacao.HasValue & dataCriacao.HasValue ? dataImportacao.GetValueOrDefault() <= dataCriacao.GetValueOrDefault() : false); + if (!flag) + { + break; + } + BaseApoliceViewModel baseApoliceViewModel5 = this; + str2 = (!criticaApolices[0].get_Aggilizador().HasValue || !criticaApolices[0].get_Aggilizador().Value ? string.Format("IMPORTAÇÃO DO ENDOSSO: {0} - {1:dd/MM/yyyy 'ÀS' HH:mm:ss}", criticaApolices[0].get_UsuarioImportacao().get_Nome(), criticaApolices[0].get_DataImportacao()) : string.Format("IMPORTAÇÃO DO ENDOSSO VIA AGGILIZADOR: {0} - {1:dd/MM/yyyy 'ÀS' HH:mm:ss}", criticaApolices[0].get_UsuarioImportacao().get_Nome(), criticaApolices[0].get_DataImportacao())); + baseApoliceViewModel5.Importado = str2; + break; + } + case 2: + case 3: + { + List criticaApolices1 = criticaApolices; + CriticaApolice criticaApolouse = criticaApolices1.Find((CriticaApolice x) => { + if (string.IsNullOrWhiteSpace(x.get_Tipo())) + { + return true; + } + return x.get_Tipo() == "0"; + }); + List criticaApolices2 = criticaApolices; + CriticaApolice criticaApolouse1 = criticaApolices2.Find((CriticaApolice x) => x.get_Tipo() == "1"); + BaseApoliceViewModel baseApoliceViewModel6 = this; + str4 = (!criticaApolouse.get_Aggilizador().HasValue || !criticaApolouse.get_Aggilizador().Value ? string.Format("IMPORTAÇÃO DA PROPOSTA: {0} - {1:dd/MM/yyyy 'ÀS' HH:mm:ss}\n", criticaApolouse.get_UsuarioImportacao().get_Nome(), criticaApolouse.get_DataImportacao()) : string.Format("IMPORTAÇÃO DA PROPOSTA VIA AGGILIZADOR: {0} - {1:dd/MM/yyyy 'ÀS' HH:mm:ss}\n", criticaApolouse.get_UsuarioImportacao().get_Nome(), criticaApolouse.get_DataImportacao())); + baseApoliceViewModel6.Importado = str4; + if (criticaApolouse1 == null) + { + break; + } + BaseApoliceViewModel baseApoliceViewModel7 = this; + string importado = this.Importado; + str5 = (!criticaApolouse1.get_Aggilizador().HasValue || !criticaApolouse1.get_Aggilizador().Value ? string.Format("IMPORTAÇÃO DA APÓLICE: {0} - {1:dd/MM/yyyy 'ÀS' HH:mm:ss}", criticaApolouse1.get_UsuarioImportacao().get_Nome(), criticaApolouse1.get_DataImportacao()) : string.Format("IMPORTAÇÃO DA APÓLICE VIA AGGILIZADOR: {0} - {1:dd/MM/yyyy 'ÀS' HH:mm:ss}", criticaApolouse1.get_UsuarioImportacao().get_Nome(), criticaApolouse1.get_DataImportacao())); + baseApoliceViewModel7.Importado = string.Concat(importado, str5); + break; + } + } + criticaApolices = null; + } + + public async Task IncluirApolice(bool renovar = false) + { + bool flag; + DateTime? emissao; + FormaPagamento? nullable1; + List list; + List vendedors; + DateTime dateTime; + ObservableCollection observableCollection; + Documento documento; + if (renovar) + { + if (!string.IsNullOrWhiteSpace(this.SelectedDocumento.get_Apolice())) + { + emissao = this.SelectedDocumento.get_Emissao(); + if (emissao.HasValue) + { + goto Label1; + } + } + await base.ShowMessage("PROPOSTA NÃO PODE SER RENOVADA. NECESSÁRIO PREENCHER O NÚMERO DA APÓLICE E DATA DE EMISSÃO ANTES DE PROSSEGUIR.", "OK", "", false); + flag = false; + documento = null; + return flag; + } + Label1: + List seguradoras = Recursos.Seguradoras; + IEnumerable ativo = + from x in seguradoras + where x.get_Ativo() + select x; + List list1 = ( + from x in ativo + orderby x.get_Nome() + select x).ToList(); + this.Seguradoras = list1; + this.SeguradorasAnteriores = Recursos.Seguradoras; + List ramos = Recursos.Ramos; + IEnumerable ativo1 = + from x in ramos + where x.get_Ativo() + select x; + List ramos1 = ( + from x in ativo1 + orderby x.get_Nome() + select x).ToList(); + this.Ramos = ramos1; + List produtos = Recursos.Produtos; + List produtos1 = ( + from x in produtos + where x.get_Ativo() + select x).ToList(); + this.Produtos = produtos1; + List status = Recursos.Status; + List statuses = ( + from x in status + where x.get_Ativo() + select x).ToList(); + this.Status = statuses; + DateTime date = Funcoes.GetNetworkTime().Date; + if (!renovar) + { + this.Inclusao = true; + BaseApoliceViewModel baseApoliceViewModel = this; + List configuracoes = Recursos.Configuracoes; + if (configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 20)) + { + List todosVendedores = this.TodosVendedores; + list = todosVendedores.Where((Vendedor x) => { + if (x.get_IdEmpresa() != MainViewModel.ClienteSelecionado.get_IdEmpresa() || !x.get_Ativo()) + { + return false; + } + return !x.get_Corretora(); + }).ToList(); + } + else + { + list = new List(); + } + baseApoliceViewModel.Vendedores = list; + BaseApoliceViewModel baseApoliceViewModel1 = this; + List estipulantes = Recursos.Estipulantes; + baseApoliceViewModel1.Estipulantes = estipulantes.Where((Estipulante x) => { + if (x.get_IdEmpresa() != MainViewModel.ClienteSelecionado.get_IdEmpresa()) + { + return false; + } + return x.get_Ativo(); + }).ToList(); + Documento documento1 = new Documento(); + Controle controle = new Controle(); + controle.set_Cliente(MainViewModel.ClienteSelecionado); + controle.set_IdEmpresa(MainViewModel.ClienteSelecionado.get_IdEmpresa()); + documento1.set_Controle(controle); + documento1.set_Ordem(0); + documento1.set_Tipo(0); + documento1.set_NegocioCorretora(new NegocioCorretora?(0)); + documento1.set_Situacao(1); + documento1.set_TipoRecebimento(new TipoRecebimento?(1)); + documento1.set_Vigencia1(date); + documento1.set_Vigencia2(new DateTime?(date.AddYears(1))); + documento1.set_ApoliceConferida(false); + documento1.set_PropostaAssinada(false); + documento1.set_AdicionalComiss(false); + documento1.set_Excluido(false); + nullable1 = null; + documento1.set_FormaPagamento(nullable1); + documento = documento1; + this.Pagamentos = null; + this.Repasses = null; + } + else + { + this.SelectedDocumento = await this.Servico.BuscarApoliceAsync(this.SelectedDocumento.get_Id(), false, false); + this.DocumentoRenovado = this.SelectedDocumento; + if (this.Seguradoras.All((Seguradora x) => x.get_Id() != this.SelectedDocumento.get_Controle().get_Seguradora().get_Id())) + { + this.Seguradoras.Add(this.SelectedDocumento.get_Controle().get_Seguradora()); + } + if (this.SelectedDocumento.get_Controle().get_Produto() != null && this.Produtos.All((Produto x) => x.get_Id() != this.SelectedDocumento.get_Controle().get_Produto().get_Id())) + { + this.Seguradoras.Add(this.SelectedDocumento.get_Controle().get_Seguradora()); + } + if (this.SelectedDocumento.get_Controle().get_Ramo() != null && this.Ramos.All((Ramo x) => x.get_Id() != this.SelectedDocumento.get_Controle().get_Ramo().get_Id())) + { + this.Seguradoras.Add(this.SelectedDocumento.get_Controle().get_Seguradora()); + } + BaseApoliceViewModel baseApoliceViewModel2 = this; + List configuracaoSistemas = Recursos.Configuracoes; + vendedors = (configuracaoSistemas.All((ConfiguracaoSistema x) => x.get_Configuracao() != 20) ? this.TodosVendedores.Where((Vendedor x) => { + if (x.get_IdEmpresa() != this.SelectedDocumento.get_Controle().get_IdEmpresa() || !x.get_Ativo()) + { + return false; + } + return !x.get_Corretora(); + }).ToList() : new List()); + baseApoliceViewModel2.Vendedores = vendedors; + this.Estipulantes = Recursos.Estipulantes.Where((Estipulante x) => { + if (x.get_IdEmpresa() != this.SelectedDocumento.get_Controle().get_IdEmpresa()) + { + return false; + } + return x.get_Ativo(); + }).ToList(); + Documento documento2 = new Documento(); + Controle controle1 = new Controle(); + controle1.set_Cliente(MainViewModel.ClienteSelecionado); + controle1.set_IdEmpresa(this.SelectedDocumento.get_Controle().get_IdEmpresa()); + controle1.set_Ramo(this.SelectedDocumento.get_Controle().get_Ramo()); + controle1.set_Seguradora(this.SelectedDocumento.get_Controle().get_Seguradora()); + controle1.set_SeguradoraAnterior(this.SelectedDocumento.get_Controle().get_Seguradora()); + documento2.set_Controle(controle1); + documento2.set_Ordem(0); + documento2.set_Tipo(0); + documento2.set_NegocioCorretora(new NegocioCorretora?(1)); + documento2.set_Situacao(2); + documento2.set_Negocio(new Negocio?(1)); + documento2.set_TipoRecebimento(new TipoRecebimento?(1)); + emissao = this.SelectedDocumento.get_Vigencia2(); + documento2.set_Vigencia1(emissao.GetValueOrDefault(date)); + emissao = this.SelectedDocumento.get_Vigencia2(); + dateTime = (emissao.HasValue ? emissao.GetValueOrDefault().AddYears(1) : date.AddYears(1)); + documento2.set_Vigencia2(new DateTime?(dateTime)); + documento2.set_ApoliceConferida(false); + documento2.set_PropostaAssinada(false); + documento2.set_AdicionalComiss(false); + documento2.set_Excluido(false); + documento2.set_ApoliceAnterior(this.SelectedDocumento.get_Apolice()); + nullable1 = null; + documento2.set_FormaPagamento(nullable1); + documento = documento2; + this.EmissaoDocumento = new DateTime?(date); + this.TransmissaoDocumento = new DateTime?(date); + if (!await base.ShowMessage("DESEJA MANTER OS VENDEDORES DA APÓLICE ANTERIOR?", "SIM", "NÃO", false)) + { + this.Pagamentos = new ObservableCollection() + { + this.PropriaCorretora() + }; + this.Repasses = null; + } + else + { + ObservableCollection pagamentos = this.Pagamentos; + if (pagamentos != null) + { + List vendedorParcelas = pagamentos.ToList(); + vendedorParcelas.ForEach((VendedorParcela x) => { + x.set_Documento(null); + x.set_ValorRepasse(new decimal?(new decimal())); + x.set_ValorTotal(null); + DateTime? nullable = null; + x.set_DataPagamento(nullable); + nullable = null; + x.set_DataPagamento(nullable); + }); + } + else + { + } + } + BaseApoliceViewModel baseApoliceViewModel3 = this; + observableCollection = (this.Pagamentos != null ? new ObservableCollection(this.Pagamentos) : new ObservableCollection()); + baseApoliceViewModel3.Pagamentos = observableCollection; + } + this.IsFatura = false; + this.SelectedParcela = null; + this.SelectedDocumento = null; + this.SelectedPagamento = null; + this.Parcelas = null; + this.SelectedDocumento = documento; + this.IsEndosso = false; + this.NovaApolice = true; + this.Renovar = renovar; + this.EnableAlterarSituacao = true; + this.AllowEditVendedor = !renovar; + this.AllowEditApolice = true; + base.IsEnabledEdit = true; + base.IsEnabledEditEndosso = true; + base.AllowEditParcela = false; + base.EnableFields = true; + base.EnableIncluir = false; + Action enableMainMenu = Gestor.Application.Actions.Actions.EnableMainMenu; + if (enableMainMenu != null) + { + enableMainMenu(false); + } + else + { + } + flag = true; + documento = null; + return flag; + } + + public async Task IncluirEndosso() + { + bool flag; + ObservableCollection observableCollection; + NegocioCorretora valueOrDefault; + TipoEndosso tipoEndosso; + List configuracoes = Recursos.Configuracoes; + if (configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 13) || !string.IsNullOrWhiteSpace(this.SelectedDocumento.get_Apolice())) + { + if (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 2) + { + observableCollection = new ObservableCollection(new List() + { + 2, + 1, + 4 + }); + } + else + { + List tipoEndossos = new List() + { + 0, + 1, + 2, + 4 + }; + observableCollection = new ObservableCollection(tipoEndossos); + } + ObservableCollection observableCollection1 = observableCollection; + if (this.SelectedDocumento.get_Situacao() == 3) + { + observableCollection1 = new ObservableCollection(new List() + { + 3 + }); + } + this.TipoEndossoList = observableCollection1; + Documento documento = new Documento(); + documento.set_Controle(this.SelectedDocumento.get_Controle()); + documento.set_Tipo(1); + IList documentos = this.SelectedDocumento.get_Controle().get_Documentos(); + IEnumerable excluido = + from x in documentos + where !x.get_Excluido() + select x; + documento.set_Ordem(excluido.Max((Documento x) => x.get_Ordem()) + 1); + NegocioCorretora? negocioCorretora = this.SelectedDocumento.get_NegocioCorretora(); + if (negocioCorretora.HasValue) + { + valueOrDefault = negocioCorretora.GetValueOrDefault(); + } + else + { + valueOrDefault = (this.SelectedDocumento.get_Situacao() != 2 || !this.SelectedDocumento.get_Negocio().HasValue || this.SelectedDocumento.get_Negocio().GetValueOrDefault() != 1 ? 0 : 1); + } + documento.set_NegocioCorretora(new NegocioCorretora?(valueOrDefault)); + documento.set_Situacao(this.SelectedDocumento.get_Situacao()); + documento.set_Negocio(this.SelectedDocumento.get_Negocio()); + documento.set_TipoRecebimento(this.SelectedDocumento.get_TipoRecebimento()); + documento.set_Vigencia1(Funcoes.GetNetworkTime().Date); + documento.set_Vigencia2(this.SelectedDocumento.get_Vigencia2()); + documento.set_ApoliceConferida(false); + documento.set_PropostaAssinada(false); + documento.set_AdicionalComiss(false); + documento.set_Excluido(false); + documento.set_Apolice(this.SelectedDocumento.get_Apolice()); + documento.set_Proposta(this.SelectedDocumento.get_Proposta()); + tipoEndosso = (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 2 ? 2 : 0); + documento.set_TipoEndosso(new TipoEndosso?(tipoEndosso)); + documento.set_Comissao(this.SelectedDocumento.get_Comissao()); + documento.set_Estipulante1(this.SelectedDocumento.get_Estipulante1()); + documento.set_Estipulante2(this.SelectedDocumento.get_Estipulante2()); + documento.set_Estipulante3(this.SelectedDocumento.get_Estipulante3()); + documento.set_Estipulante4(this.SelectedDocumento.get_Estipulante4()); + documento.set_Estipulante5(this.SelectedDocumento.get_Estipulante5()); + Documento documento1 = documento; + this.SelectedParcela = null; + this.SelectedDocumento = null; + this.SelectedPagamento = null; + if (documento1.get_TipoRecebimento().GetValueOrDefault() != 1) + { + this.Pagamentos = null; + this.Repasses = null; + } + else + { + List repasses = this.Repasses; + List list = ( + from x in repasses + where x.get_Parcela().get_SubTipo() == 1 + select x).ToList(); + List vendedorParcelas = ( + from x in list + group x by x.get_Vendedor().get_Id()).Select, VendedorParcela>((IGrouping x) => { + VendedorParcela vendedorParcela = new VendedorParcela(); + vendedorParcela.set_Repasse(x.First().get_Repasse()); + vendedorParcela.set_Parcela(this.SelectedParcela); + vendedorParcela.set_Documento(this.SelectedDocumento); + vendedorParcela.set_ValorRepasse(new decimal?(new decimal())); + vendedorParcela.set_Vendedor(x.First().get_Vendedor()); + vendedorParcela.set_PorcentagemRepasse(x.First().get_PorcentagemRepasse()); + vendedorParcela.set_TipoVendedor(x.First().get_TipoVendedor()); + return vendedorParcela; + }).ToList(); + this.Pagamentos = new ObservableCollection(vendedorParcelas); + this.Repasses = vendedorParcelas; + } + this.Parcelas = null; + this.SelectedDocumento = documento1; + this.NovaApolice = true; + this.AllowEditVendedor = false; + this.AllowEditApolice = true; + this.IsEndosso = true; + base.IsEnabledEditEndosso = true; + base.EnableFields = true; + base.EnableIncluir = false; + this.AllowEditEmissao = true; + Action enableMainMenu = Gestor.Application.Actions.Actions.EnableMainMenu; + if (enableMainMenu != null) + { + enableMainMenu(false); + } + else + { + } + flag = true; + } + else + { + await base.ShowMessage("PROPOSTA NÃO PODE SER ENDOSSADA. NECESSÁRIO PREENCHER O NÚMERO DA APÓLICE E DATA DE EMISSÃO ANTES DE PROSSEGUIR.", "OK", "", false); + flag = false; + } + return flag; + } + + public void IncluirFatura() + { + long? nullable1; + int numeroParcela; + decimal comissao; + long id; + long? nullable2; + Parcela parcela = ( + from x in this.Parcelas + orderby x.get_NumeroParcela() + select x).LastOrDefault((Parcela x) => x.get_SubTipo() == 1); + if (parcela != null) + { + numeroParcela = parcela.get_NumeroParcela(); + } + else + { + numeroParcela = 0; + } + int num = numeroParcela + 1; + if (parcela != null) + { + comissao = parcela.get_Comissao(); + } + else + { + comissao = decimal.Zero; + } + decimal num1 = comissao; + Parcela selectedParcela = this.SelectedParcela; + if (selectedParcela != null) + { + id = selectedParcela.get_Id(); + } + else + { + ObservableCollection parcelas = this.Parcelas; + if (parcelas != null) + { + Parcela parcela1 = ( + from x in parcelas + orderby x.get_NumeroParcela() + select x).LastOrDefault((Parcela x) => x.get_SubTipo() == 1); + if (parcela1 != null) + { + nullable2 = new long?(parcela1.get_Id()); + } + else + { + nullable1 = null; + nullable2 = nullable1; + } + } + else + { + nullable1 = null; + nullable2 = nullable1; + } + nullable1 = nullable2; + id = nullable1.GetValueOrDefault(); + } + long num2 = id; + DateTime networkTime = Funcoes.GetNetworkTime(); + Parcela parcela2 = new Parcela(); + parcela2.set_IdEmpresa(this.SelectedDocumento.get_Controle().get_IdEmpresa()); + parcela2.set_Documento(this.SelectedDocumento); + parcela2.set_Vencimento(Funcoes.GetNetworkTime().Date); + parcela2.set_Comissao(num1); + parcela2.set_SubTipo(1); + parcela2.set_NumeroParcela(num); + parcela2.set_DataCriacao(new DateTime?(networkTime)); + parcela2.set_UsuarioCriacao(Recursos.Usuario.get_Id()); + this.SelectedParcela = parcela2; + if (num2 == 0) + { + return; + } + List list = ( + from x in this.Repasses + where x.get_Parcela().get_Id() == num2 + select x).ToList(); + list.ForEach((VendedorParcela x) => { + decimal zero; + x.set_Id((long)0); + x.set_Parcela(this.SelectedParcela); + DateTime? nullable = null; + x.set_DataPrePagamento(nullable); + nullable = null; + x.set_DataPagamento(nullable); + VendedorParcela vendedorParcela = x; + if (x.get_Repasse() != null) + { + NegocioCorretora? negocioCorretora = this.SelectedDocumento.get_NegocioCorretora(); + zero = (negocioCorretora.GetValueOrDefault() == 0 & negocioCorretora.HasValue ? x.get_Repasse().get_ValorNovo() : x.get_Repasse().get_ValorRenovacao()); + } + else + { + zero = decimal.Zero; + } + vendedorParcela.set_PorcentagemRepasse(new decimal?(zero)); + }); + this.Repasses = list; + this.RecalculaRepasse(); + } + + public void IncluirParcelaEspecial() + { + Parcela parcela; + Parcela parcela1 = new Parcela(); + parcela1.set_IdEmpresa(this.SelectedDocumento.get_Controle().get_IdEmpresa()); + parcela1.set_Documento(this.SelectedDocumento); + parcela1.set_Vencimento(Funcoes.GetNetworkTime().Date); + parcela1.set_Comissao(new decimal(100)); + parcela1.set_SubTipo(3); + parcela1.set_NumeroParcela(999); + parcela1.set_DataCriacao(new DateTime?(Funcoes.GetNetworkTime())); + parcela1.set_UsuarioCriacao(Recursos.Usuario.get_Id()); + this.SelectedParcela = parcela1; + ObservableCollection parcelas = this.Parcelas; + if (parcelas != null) + { + parcela = parcelas.FirstOrDefault((Parcela x) => x.get_SubTipo() == 1); + } + else + { + parcela = null; + } + Parcela parcela2 = parcela; + if (parcela2 == null) + { + this.Repasses = new List(); + return; + } + List list = ( + from x in this.Repasses + where x.get_Parcela().get_Id() == parcela2.get_Id() + select x).ToList(); + list.ForEach((VendedorParcela x) => { + x.set_Id((long)0); + x.set_Parcela(this.SelectedParcela); + DateTime? nullable = null; + x.set_DataPrePagamento(nullable); + nullable = null; + x.set_DataPagamento(nullable); + x.set_ValorRepasse(new decimal?(new decimal())); + nullable = null; + x.set_DataPagamento(nullable); + }); + this.Repasses = list; + this.RecalculaRepasse(); + } + + private async Task IncluirPropriaCorretora() + { + VendedorParcela vendedorParcela; + Parcela selectedParcela; + if (this.Parcelas.Count != 0) + { + VendedorParcela vendedorParcela1 = this.PropriaCorretora(); + if (this.SelectedParcela.get_SubTipo() != 1 || this.IsFatura) + { + selectedParcela = this.SelectedParcela; + } + else + { + ObservableCollection parcelas = this.Parcelas; + selectedParcela = parcelas.FirstOrDefault((Parcela x) => x.get_NumeroParcela() == 1); + } + Parcela parcela = selectedParcela; + vendedorParcela1.set_Parcela(parcela); + vendedorParcela1.set_Documento(this.SelectedDocumento); + if (parcela == null || parcela.get_Id() != 0) + { + vendedorParcela = await this.Servico.IncluirVendedor(vendedorParcela1); + } + else + { + vendedorParcela = vendedorParcela1; + } + } + else + { + vendedorParcela = null; + } + return vendedorParcela; + } + + public void IncluirVendedor() + { + VendedorParcela vendedorParcela = new VendedorParcela(); + vendedorParcela.set_Documento(this.SelectedDocumento); + this.SelectedPagamento = vendedorParcela; + } + + public async Task LimparRepasses() + { + bool count; + bool flag; + if (this.Pagamentos != null) + { + ObservableCollection pagamentos = this.Pagamentos; + if (pagamentos != null) + { + count = pagamentos.Count == 0; + } + else + { + count = false; + } + if (!count && this.Repasses != null) + { + List repasses = this.Repasses; + if (repasses != null) + { + flag = repasses.Count == 0; + } + else + { + flag = false; + } + if (!flag && this.SelectedDocumento.get_Id() == 0) + { + if (!base.EnableFields || !this.AllowEditApolice || !this.AlteracaoEnabled) + { + return; + } + else + { + await base.ShowMessage("REPASSES ADICIONADOS NÃO PERTENCEM AO RAMO SELECIONADO E SERÃO EXCLUÍDOS.", "OK", "", false); + this.Pagamentos.Clear(); + this.Repasses.Clear(); + return; + } + } + } + } + } + + public void ManutecaoItens() + { + if (!this.Invoke) + { + return; + } + Action acessaTela = Gestor.Application.Actions.Actions.AcessaTela; + if (acessaTela == null) + { + return; + } + acessaTela(3, "Manutencao"); + } + + public async Task PagamentoVendedor(Parcela parcela) + { + return await this.ParcelaServico.TemPagamento(parcela.get_Id()); + } + + private void PreLoad() + { + this.Ramos = Recursos.Ramos; + this.Seguradoras = Recursos.Seguradoras; + this.Produtos = Recursos.Produtos; + this.Status = Recursos.Status; + this.SeguradorasAnteriores = Recursos.Seguradoras; + this.TipoEndossoList = new ObservableCollection(new List() + { + 0, + 1, + 2, + 4, + 3 + }); + } + + private VendedorParcela PropriaCorretora() + { + VendedorParcela vendedorParcela = new VendedorParcela(); + vendedorParcela.set_Repasse(null); + decimal num = new decimal(); + vendedorParcela.set_ValorRepasse(new decimal?(num)); + vendedorParcela.set_Documento(this.SelectedDocumento); + vendedorParcela.set_Vendedor(Recursos.Vendedores.FirstOrDefault((Vendedor x) => { + long? nullable; + long? nullable1; + long idEmpresa = x.get_IdEmpresa(); + Documento selectedDocumento = this.SelectedDocumento; + if (selectedDocumento != null) + { + Controle controle = selectedDocumento.get_Controle(); + if (controle != null) + { + nullable1 = new long?(controle.get_IdEmpresa()); + } + else + { + nullable = null; + nullable1 = nullable; + } + } + else + { + nullable = null; + nullable1 = nullable; + } + long? nullable2 = nullable1; + if (idEmpresa != (nullable2.HasValue ? nullable2.GetValueOrDefault() : Recursos.Empresa.get_Id())) + { + return false; + } + return x.get_Corretora(); + })); + num = new decimal(); + vendedorParcela.set_PorcentagemRepasse(new decimal?(num)); + vendedorParcela.set_TipoVendedor(Recursos.TipoVendedor.First((TipoVendedor x) => x.get_Id() == (long)1)); + return vendedorParcela; + } + + public void RecalculaRepasse() + { + List list; + if (!this.IsFatura && this.BaixarParcelas && this.SelectedParcela.get_SubTipo() == 1) + { + return; + } + if (this.Repasses == null || this.Repasses.Count == 0) + { + return; + } + if (this.SelectedParcela.get_Id() == 0) + { + this.Repasses.ForEach((VendedorParcela x) => { + decimal? porcentagemRepasse; + bool valueOrDefault; + decimal? nullable; + bool flag; + if (x.get_DataPagamento().HasValue) + { + return; + } + Gestor.Model.Domain.Seguros.Repasse repasse = x.get_Repasse(); + valueOrDefault = (repasse != null ? repasse.get_Tipo().GetValueOrDefault() == 3 : false); + if (valueOrDefault) + { + return; + } + Parcela parcela = x.get_Parcela() ?? this.SelectedParcela; + parcela.set_Documento(this.SelectedDocumento); + if (x.get_Repasse() != null) + { + Gestor.Model.Domain.Seguros.Repasse repasse1 = x.get_Repasse(); + porcentagemRepasse = x.get_PorcentagemRepasse(); + repasse1.set_ValorNovo((porcentagemRepasse.HasValue ? porcentagemRepasse.GetValueOrDefault() : x.get_Repasse().get_ValorNovo())); + Gestor.Model.Domain.Seguros.Repasse repasse2 = x.get_Repasse(); + porcentagemRepasse = x.get_PorcentagemRepasse(); + repasse2.set_ValorRenovacao((porcentagemRepasse.HasValue ? porcentagemRepasse.GetValueOrDefault() : x.get_Repasse().get_ValorRenovacao())); + } + decimal num = Funcoes.CalculaRepasse(x.get_Repasse(), parcela, true); + VendedorParcela vendedorParcela = x; + if (this.SelectedDocumento.get_NumeroParcelas() > decimal.Zero && !this.SelectedParcela.get_NumeroParcela().Equals(999)) + { + Gestor.Model.Domain.Seguros.Repasse repasse3 = x.get_Repasse(); + flag = (repasse3 != null ? repasse3.get_Forma().GetValueOrDefault() == 3 : false); + if (!flag) + { + nullable = new decimal?(num); + vendedorParcela.set_ValorRepasse(nullable); + x.set_ValorTotal(new decimal?(num)); + return; + } + porcentagemRepasse = x.get_ValorTotal(); + decimal numeroParcelas = this.SelectedDocumento.get_NumeroParcelas(); + if (porcentagemRepasse.HasValue) + { + nullable = new decimal?(porcentagemRepasse.GetValueOrDefault() / numeroParcelas); + vendedorParcela.set_ValorRepasse(nullable); + x.set_ValorTotal(new decimal?(num)); + return; + } + else + { + nullable = null; + vendedorParcela.set_ValorRepasse(nullable); + x.set_ValorTotal(new decimal?(num)); + return; + } + } + nullable = new decimal?(num); + vendedorParcela.set_ValorRepasse(nullable); + x.set_ValorTotal(new decimal?(num)); + }); + this.Pagamentos = new ObservableCollection(this.Repasses); + return; + } + List repasses = this.Repasses; + if (repasses != null) + { + repasses.Where((VendedorParcela x) => { + if (this.SelectedParcela.get_Id() <= (long)0) + { + return false; + } + return x.get_Parcela().get_Id() == this.SelectedParcela.get_Id(); + }).ToList().ForEach((VendedorParcela x) => { + decimal? porcentagemRepasse; + bool valueOrDefault; + decimal? nullable; + VendedorParcela vendedorParcela; + decimal? nullable1; + bool flag; + if (x.get_DataPagamento().HasValue) + { + return; + } + Gestor.Model.Domain.Seguros.Repasse repasse = x.get_Repasse(); + valueOrDefault = (repasse != null ? repasse.get_Tipo().GetValueOrDefault() == 3 : false); + if (valueOrDefault) + { + return; + } + Parcela selectedParcela = this.SelectedParcela; + selectedParcela.set_Documento(this.SelectedDocumento); + if (x.get_Repasse() != null) + { + Gestor.Model.Domain.Seguros.Repasse repasse1 = x.get_Repasse(); + porcentagemRepasse = x.get_PorcentagemRepasse(); + repasse1.set_ValorNovo((porcentagemRepasse.HasValue ? porcentagemRepasse.GetValueOrDefault() : x.get_Repasse().get_ValorNovo())); + Gestor.Model.Domain.Seguros.Repasse repasse2 = x.get_Repasse(); + porcentagemRepasse = x.get_PorcentagemRepasse(); + repasse2.set_ValorRenovacao((porcentagemRepasse.HasValue ? porcentagemRepasse.GetValueOrDefault() : x.get_Repasse().get_ValorRenovacao())); + } + decimal num = Funcoes.CalculaRepasse(x.get_Repasse(), selectedParcela, true); + VendedorParcela vendedorParcela1 = x; + if (this.SelectedDocumento.get_NumeroParcelas() > decimal.Zero && !this.SelectedParcela.get_NumeroParcela().Equals(999)) + { + Gestor.Model.Domain.Seguros.Repasse repasse3 = x.get_Repasse(); + flag = (repasse3 != null ? repasse3.get_Forma().GetValueOrDefault() == 3 : false); + if (!flag) + { + nullable = new decimal?(num); + vendedorParcela1.set_ValorRepasse(nullable); + vendedorParcela = x; + nullable1 = (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() != 1 || this.SelectedParcela.get_SubTipo() != 1 ? x.get_ValorTotal() : new decimal?(num)); + vendedorParcela.set_ValorTotal(nullable1); + return; + } + porcentagemRepasse = x.get_ValorTotal(); + decimal numeroParcelas = this.SelectedDocumento.get_NumeroParcelas(); + if (porcentagemRepasse.HasValue) + { + nullable = new decimal?(porcentagemRepasse.GetValueOrDefault() / numeroParcelas); + vendedorParcela1.set_ValorRepasse(nullable); + vendedorParcela = x; + nullable1 = (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() != 1 || this.SelectedParcela.get_SubTipo() != 1 ? x.get_ValorTotal() : new decimal?(num)); + vendedorParcela.set_ValorTotal(nullable1); + return; + } + else + { + nullable = null; + vendedorParcela1.set_ValorRepasse(nullable); + vendedorParcela = x; + nullable1 = (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() != 1 || this.SelectedParcela.get_SubTipo() != 1 ? x.get_ValorTotal() : new decimal?(num)); + vendedorParcela.set_ValorTotal(nullable1); + return; + } + } + nullable = new decimal?(num); + vendedorParcela1.set_ValorRepasse(nullable); + vendedorParcela = x; + nullable1 = (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() != 1 || this.SelectedParcela.get_SubTipo() != 1 ? x.get_ValorTotal() : new decimal?(num)); + vendedorParcela.set_ValorTotal(nullable1); + }); + } + else + { + } + List vendedorParcelas = this.Repasses; + if (vendedorParcelas != null) + { + list = vendedorParcelas.Where((VendedorParcela x) => { + if (this.SelectedParcela.get_Id() <= (long)0) + { + return false; + } + return x.get_Parcela().get_Id() == this.SelectedParcela.get_Id(); + }).ToList(); + } + else + { + list = null; + } + this.Pagamentos = new ObservableCollection(list); + } + + public async void RecalculaRepasses() + { + bool flag; + if (this.Repasses != null) + { + if (this.SelectedDocumento.get_NegocioCorretora().HasValue) + { + NegocioCorretora? negocioCorretora = this.SelectedDocumento.get_NegocioCorretora(); + flag = negocioCorretora.GetValueOrDefault() == 1; + } + else if (this.SelectedDocumento.get_Situacao() != 2 || !this.SelectedDocumento.get_Negocio().HasValue) + { + flag = false; + } + else + { + Negocio? negocio = this.SelectedDocumento.get_Negocio(); + flag = negocio.GetValueOrDefault() == 1; + } + bool flag1 = flag; + List repasses = this.Repasses; + if (repasses != null) + { + repasses.Where((VendedorParcela x) => { + if (this.NovaApolice) + { + return true; + } + return x.get_Parcela().get_SubTipo() == 1; + }).ToList().ForEach((VendedorParcela x) => { + decimal? valorTotal; + decimal numeroParcelas; + decimal? nullable; + decimal valorRenovacao; + decimal? nullable1; + decimal? nullable2; + decimal? nullable3; + bool valueOrDefault; + if (x.get_Parcela() == null) + { + return; + } + if (x.get_Repasse() == null) + { + return; + } + if (x.get_DataPagamento().HasValue) + { + return; + } + Parcela parcela = x.get_Parcela(); + parcela.set_Documento(this.SelectedDocumento); + decimal num = Funcoes.CalculaRepasse(x.get_Repasse(), parcela, true); + VendedorParcela vendedorParcela = x; + if (flag1) + { + Gestor.Model.Domain.Seguros.Repasse repasse = x.get_Repasse(); + valueOrDefault = (repasse != null ? repasse.get_Tipo().GetValueOrDefault() != 3 : true); + if (!valueOrDefault) + { + goto Label1; + } + valorRenovacao = x.get_Repasse().get_ValorRenovacao(); + goto Label0; + } + Label1: + valorRenovacao = x.get_Repasse().get_ValorNovo(); + Label0: + vendedorParcela.set_PorcentagemRepasse(new decimal?(valorRenovacao)); + if (x.get_Repasse().get_Forma().GetValueOrDefault() == 3) + { + valorTotal = x.get_ValorTotal(); + numeroParcelas = this.SelectedDocumento.get_NumeroParcelas(); + if (valorTotal.HasValue) + { + nullable1 = new decimal?(valorTotal.GetValueOrDefault() / numeroParcelas); + } + else + { + nullable = null; + nullable1 = nullable; + } + } + else + { + nullable1 = new decimal?(num); + } + decimal? nullable4 = nullable1; + if (x.get_CoCorretagem()) + { + numeroParcelas = this.SelectedDocumento.get_PremioLiquido(); + decimal? comissaoTotal = this.SelectedDocumento.get_ComissaoTotal(); + decimal comissao = this.SelectedDocumento.get_Comissao(); + nullable = (comissaoTotal.HasValue ? new decimal?(comissaoTotal.GetValueOrDefault() - comissao) : null); + decimal num1 = 100; + if (nullable.HasValue) + { + nullable2 = new decimal?(nullable.GetValueOrDefault() / num1); + } + else + { + comissaoTotal = null; + nullable2 = comissaoTotal; + } + valorTotal = nullable2; + if (valorTotal.HasValue) + { + nullable3 = new decimal?(numeroParcelas * valorTotal.GetValueOrDefault()); + } + else + { + nullable = null; + nullable3 = nullable; + } + nullable4 = nullable3; + } + x.set_ValorRepasse(nullable4); + x.set_ValorTotal(new decimal?(num)); + }); + } + else + { + } + if (!this.NovaApolice) + { + BaseApoliceViewModel baseApoliceViewModel = this; + Parcela selectedParcela = this.SelectedParcela; + if (selectedParcela == null) + { + selectedParcela = this.Parcelas.FirstOrDefault(); + } + await baseApoliceViewModel.SelecionaParcela(selectedParcela); + this.CalculaComissao(this.SelectedDocumento, this.Parcelas); + } + else + { + BaseApoliceViewModel observableCollection = this; + List vendedorParcelas = this.Repasses; + observableCollection.Pagamentos = new ObservableCollection( + from x in vendedorParcelas + orderby x.get_TipoVendedor().get_Id() + select x); + } + } + } + + public async Task RecusarApolice() + { + bool flag; + IList list; + string str; + string str1; + string str2; + if (this.SelectedDocumento != null) + { + bool[] flagArray = await Funcoes.VerificarPagamento(this.SelectedDocumento.get_Id()); + List configuracoes = Recursos.Configuracoes; + if (configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 23)) + { + bool[] flagArray1 = flagArray; + if (((IEnumerable)flagArray1).Any((bool x) => x)) + { + await base.ShowMessage("NÃO É POSSÍVEL RECURSAR UM APÓLICE ENQUANTO HOUVER RECEBIMENTO DE COMISSÃO OU PAGAMENTO DE VENDEDORES PARA A APÓLICE", "OK", "", false); + str2 = null; + return; + } + } + List configuracaoSistemas = Recursos.Configuracoes; + flag = (!configuracaoSistemas.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 23) ? false : flagArray[1]); + bool flag1 = flag; + if (flag1) + { + flag1 = await base.ShowMessage("EXISTEM PAGAMENTOS PARA OS VENDEDORES DO CONTRATO, DESEJA CRIAR ESTORNOS PARA ESSES PAGAMENTOS?", "SIM", "NÃO", false); + } + bool flag2 = flag1; + Documento documento = await this.Servico.BuscarApoliceAsync(this.DocumentoSelecionado.get_Id(), false, false); + if (documento.get_Controle().get_Documentos().Count > 1) + { + IList documentos = documento.get_Controle().get_Documentos(); + IEnumerable excluido = + from x in documentos + where !x.get_Excluido() + select x; + list = ( + from x in excluido + orderby x.get_Ordem() + select x).ToList(); + } + else + { + list = documento.get_Controle().get_Documentos(); + } + IList documentos1 = list; + if (documentos1.Count > 1) + { + IList documentos2 = documentos1; + if (documentos2.Last((Documento x) => x.get_Situacao() != 7).get_Id() != this.DocumentoSelecionado.get_Id()) + { + await base.ShowMessage("NÃO É POSSÍVEL RECUSAR UM DOCUMENTO ENQUANTO HOUVER ENDOSSOS EM CIMA DO MESMO.", "OK", "", false); + str2 = null; + return; + } + } + if (documento.get_Situacao() != 7) + { + if (this.SelectedDocumento.get_Tipo() != 0 || !string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + str = (this.SelectedDocumento.get_Tipo() != 0 || string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice()) ? "O ENDOSSO SELECIONADO" : "A APÓLICE SELECIONADA"); + } + else + { + str = "A PROPOSTA SELECIONADA"; + } + string str3 = str; + string[] newLine = new string[] { "DESEJA REALMENTE RECUSAR ", str3, "? ", Environment.NewLine, "ESSE PROCEDIMENTO É IRREVERSÍVEL." }; + if (await base.ShowMessage(string.Concat(newLine), "SIM", "NÃO", false)) + { + str2 = null; + str2 = await base.ShowObservacaoDialog(); + if (str2 != null) + { + base.Loading(true); + await Funcoes.RecusarApolice(this.SelectedDocumento, str2, flag2); + if (this.SelectedDocumento.get_Tipo() == 0 && string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + str1 = string.Concat("A PROPOSTA \"", this.SelectedDocumento.get_Proposta(), "\""); + } + else if (this.SelectedDocumento.get_Tipo() != 0 || string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + str1 = (string.IsNullOrEmpty(this.SelectedDocumento.get_Endosso()) ? string.Concat("A PROPOSTA DE ENDOSSO \"", this.SelectedDocumento.get_PropostaEndosso(), "\"") : string.Concat("O ENDOSSO \"", this.SelectedDocumento.get_Endosso(), "\"")); + } + else + { + str1 = string.Concat("A APÓLICE \"", this.SelectedDocumento.get_Apolice(), "\""); + } + string str4 = str1; + base.RegistrarAcao(string.Concat("RECUSOU ", str4), this.SelectedDocumento.get_Id(), new TipoTela?(2), string.Concat(this.GerarObs(this.SelectedDocumento), Environment.NewLine, "MOTIVO: ", str2)); + base.Loading(false); + } + } + } + else + { + await base.ShowMessage("NÃO É POSSÍVEL RECUSAR UM DOCUMENTO JÁ RECUSADO.", "OK", "", false); + } + } + str2 = null; + } + + private void RemoverVendedor(long id) + { + ((this.SelectedDocumento.get_Id() == 0 || this.SelectedParcela.get_SubTipo() == 1 && !this.IsFatura ? ( + from x in this.Repasses + where x.get_Vendedor().get_Id() == id + select x).ToList() : this.Repasses.Where((VendedorParcela x) => { + if (x.get_Vendedor().get_Id() != id) + { + return false; + } + return x.get_Parcela().get_Id() == this.SelectedParcela.get_Id(); + }).ToList())).ForEach((VendedorParcela x) => this.Repasses.Remove(x)); + ((this.SelectedDocumento.get_Id() == 0 || this.SelectedParcela.get_SubTipo() == 1 && !this.IsFatura ? ( + from x in this.Pagamentos + where x.get_Vendedor().get_Id() == id + select x).ToList() : this.Pagamentos.Where((VendedorParcela x) => { + long num; + if (x.get_Vendedor().get_Id() != id) + { + return false; + } + Parcela parcela = x.get_Parcela(); + num = (parcela != null ? parcela.get_Id() : (long)0); + return num == this.SelectedParcela.get_Id(); + }).ToList())).ForEach((VendedorParcela x) => this.Pagamentos.Remove(x)); + } + + public async Task ReplicarFatura() + { + DateTime? emissao; + int num; + decimal comissao; + DateTime? vigenciaFinal; + DateTime dateTime; + DateTime? nullable1; + DateTime dateTime1; + DateTime date; + decimal valor; + decimal valorLiquidoFatura; + if (this.Parcelas != null) + { + ObservableCollection parcelas = this.Parcelas; + IOrderedEnumerable numeroParcela = + from x in parcelas + orderby x.get_NumeroParcela() + select x; + Parcela parcela = numeroParcela.LastOrDefault((Parcela x) => x.get_SubTipo() == 1); + if (parcela == null || parcela.get_NumeroParcela() != 999) + { + num = (parcela != null ? parcela.get_NumeroParcela() : 0); + int num1 = num + 1; + Parcela selectedParcela = this.SelectedParcela; + if (selectedParcela != null) + { + comissao = selectedParcela.get_Comissao(); + } + else + { + comissao = decimal.Zero; + } + decimal num2 = comissao; + ObservableCollection observableCollection = this.Parcelas; + Parcela parcela1 = observableCollection.First((Parcela x) => x.get_SubTipo() == 1); + DateTime networkTime = Funcoes.GetNetworkTime(); + Parcela parcela2 = parcela1; + if (parcela2 != null) + { + vigenciaFinal = parcela2.get_VigenciaFinal(); + } + else + { + emissao = null; + vigenciaFinal = emissao; + } + DateTime? nullable2 = vigenciaFinal; + dateTime = (nullable2.HasValue ? nullable2.GetValueOrDefault() : networkTime.Date); + DateTime dateTime2 = dateTime; + Parcela parcela3 = parcela1; + if (parcela3 != null) + { + emissao = parcela3.get_Emissao(); + if (emissao.HasValue) + { + DateTime valueOrDefault = emissao.GetValueOrDefault(); + nullable1 = new DateTime?(valueOrDefault.AddMonths(1)); + } + else + { + nullable1 = null; + } + } + else + { + emissao = null; + nullable1 = emissao; + } + nullable2 = nullable1; + dateTime1 = (nullable2.HasValue ? nullable2.GetValueOrDefault() : networkTime.Date); + DateTime dateTime3 = dateTime1; + Parcela parcela4 = parcela1; + if (parcela4 != null) + { + date = parcela4.get_Vencimento().AddMonths(1); + } + else + { + date = networkTime.Date; + } + DateTime dateTime4 = date; + DateTime dateTime5 = dateTime2.AddMonths(1); + Parcela parcela5 = parcela1; + if (parcela5 != null) + { + valor = parcela5.get_Valor(); + } + else + { + valor = decimal.Zero; + } + decimal num3 = valor; + Parcela parcela6 = parcela1; + if (parcela6 != null) + { + valorLiquidoFatura = parcela6.get_ValorLiquidoFatura(); + } + else + { + valorLiquidoFatura = decimal.Zero; + } + decimal num4 = valorLiquidoFatura; + IEnumerable vendedorParcelas = this.Repasses.Where((VendedorParcela x) => { + if (parcela1 == null) + { + return false; + } + return x.get_Parcela().get_Id() == parcela1.get_Id(); + }); + List list = Funcoes.DistinctBy(vendedorParcelas, (VendedorParcela x) => new { Id = x.get_Parcela().get_Id(), vendedor = x.get_Vendedor().get_Id(), tipovendedor = x.get_TipoVendedor().get_Id() }).ToList(); + Parcela parcela7 = new Parcela(); + parcela7.set_IdEmpresa(this.SelectedDocumento.get_Controle().get_IdEmpresa()); + parcela7.set_Documento(this.SelectedDocumento); + parcela7.set_Vencimento(dateTime4); + parcela7.set_Comissao(num2); + parcela7.set_SubTipo(1); + parcela7.set_NumeroParcela(num1); + parcela7.set_VigenciaIncial(new DateTime?(dateTime2)); + parcela7.set_VigenciaFinal(new DateTime?(dateTime5)); + parcela7.set_Valor(num3); + parcela7.set_Emissao(new DateTime?(dateTime3)); + parcela7.set_DataCriacao(new DateTime?(networkTime)); + parcela7.set_ValorLiquidoFatura(num4); + this.SelectedParcela = parcela7; + list.ForEach((VendedorParcela x) => { + decimal zero; + x.set_Id((long)0); + x.set_Parcela(this.SelectedParcela); + DateTime? nullable = null; + x.set_DataPrePagamento(nullable); + nullable = null; + x.set_DataPagamento(nullable); + VendedorParcela vendedorParcela = x; + if (x.get_Repasse() != null) + { + NegocioCorretora? negocioCorretora = this.SelectedDocumento.get_NegocioCorretora(); + zero = (negocioCorretora.GetValueOrDefault() == 0 & negocioCorretora.HasValue ? x.get_Repasse().get_ValorNovo() : x.get_Repasse().get_ValorRenovacao()); + } + else + { + zero = decimal.Zero; + } + vendedorParcela.set_PorcentagemRepasse(new decimal?(zero)); + }); + this.Repasses = list; + } + else + { + await base.ShowMessage("PARCELA ESPECIAL NÃO PODE SER REPLICADA.", "OK", "", false); + return; + } + } + this.RecalculaRepasse(); + } + + public async Task>> Salvar(bool critica = false) + { + List> list; + NegocioCorretora? negocioCorretora; + NegocioCorretora? nullable; + bool id; + bool vendedor; + bool updatePremio; + bool flag2; + bool flag3; + List vendedorParcelas; + bool flag4; + Vendedor vendedor1; + Documento documento; + string str; + string str1; + bool valueOrDefault; + long? nullable1; + bool flag5; + NegocioCorretora negocioCorretora1; + string str2; + NegocioCorretora negocioCorretora2; + FormaPagamento formaPagamento; + bool vendedor2; + Negocio negocio; + object obj = null; + if (this.SelectedDocumento.get_Situacao() == 2) + { + Documento selectedDocumento = this.SelectedDocumento; + negocioCorretora = this.SelectedDocumento.get_NegocioCorretora(); + negocio = (negocioCorretora.GetValueOrDefault() == 0 & negocioCorretora.HasValue ? 2 : 1); + selectedDocumento.set_Negocio(new Negocio?(negocio)); + } + Gestor.Model.Domain.Seguros.Status status = this.SelectedDocumento.get_Status(); + if (status != null) + { + id = status.get_Id() == (long)0; + } + else + { + id = false; + } + if (id) + { + this.SelectedDocumento.set_Status(null); + } + this.ZerarValores(); + Documento selectedDocumento1 = this.SelectedDocumento; + bool isEndosso = this.IsEndosso; + List configuracaoSistemas1 = Recursos.Configuracoes; + List> keyValuePairs1 = selectedDocumento1.Validate(isEndosso, configuracaoSistemas1.Any((ConfiguracaoSistema c) => c.get_Configuracao() == 11)); + if (this.SelectedDocumento.get_Comissao() > new decimal(100)) + { + this.SelectedDocumento.set_Comissao(new decimal(100)); + } + bool id1 = this.SelectedDocumento.get_Id() == (long)0; + VendedorParcela selectedPagamento = this.SelectedPagamento; + if (selectedPagamento != null) + { + vendedor = selectedPagamento.get_Vendedor(); + } + else + { + vendedor = false; + } + if (vendedor && this.SelectedDocumento.get_Vendedores() == null) + { + Documento documento1 = this.SelectedDocumento; + List vendedors = new List() + { + this.TodosVendedores.First((Vendedor x) => { + if (!x.get_Corretora()) + { + return false; + } + return x.get_IdEmpresa() == this.SelectedDocumento.get_Controle().get_IdEmpresa(); + }) + }; + documento1.set_Vendedores(vendedors); + } + if (id1) + { + VendedorParcela vendedorParcela = this.SelectedPagamento; + if (vendedorParcela != null) + { + vendedor2 = vendedorParcela.get_Vendedor(); + } + else + { + vendedor2 = false; + } + if (vendedor2 && this.SelectedDocumento.get_Vendedores() != null) + { + List> keyValuePairs2 = keyValuePairs1; + List> keyValuePairs3 = await this.AdicionarVendedor(); + List> keyValuePairs4 = keyValuePairs2; + List> keyValuePairs5 = keyValuePairs3; + if (keyValuePairs5 == null) + { + keyValuePairs5 = new List>(); + } + keyValuePairs4.AddRange(keyValuePairs5); + keyValuePairs2 = null; + } + } + if (keyValuePairs1.Count <= 0) + { + bool tipo = this.SelectedDocumento.get_Tipo() == 0; + if (tipo) + { + tipo = !await this.VerificarVigencia(this.SelectedDocumento); + } + if (tipo) + { + if (critica) + { + keyValuePairs1.Add(new KeyValuePair("Vigencia2", "VIGENCIANAOACEITA")); + } + list = keyValuePairs1; + } + else if (this.SelectedDocumento.get_TipoEndosso().GetValueOrDefault() == 3 || this.SelectedDocumento.get_Situacao() != 3 || this.SelectedDocumento.get_Id() != 0) + { + if (this.SelectedDocumento.get_TipoEndosso().HasValue && this.SelectedDocumento.get_TipoEndosso().GetValueOrDefault() == 3) + { + this.SelectedDocumento.set_Situacao(4); + } + Documento selectedDocumento2 = this.SelectedDocumento; + base.Alterar(false); + if (!selectedDocumento2.get_FormaPagamento().HasValue) + { + Documento documento2 = selectedDocumento2; + List configuracaoSistemas2 = Recursos.Configuracoes; + formaPagamento = (configuracaoSistemas2.Any((ConfiguracaoSistema y) => y.get_Configuracao() == 21) ? 4 : 0); + documento2.set_FormaPagamento(new FormaPagamento?(formaPagamento)); + } + this.Acesso = 0; + if (selectedDocumento2.get_Id() <= (long)0 || !this.AllowEditApolice) + { + updatePremio = false; + } + else + { + if (!(this.CancelDocumento.get_PremioLiquido() != selectedDocumento2.get_PremioLiquido()) && this.CancelDocumento.get_AdicionalComiss() == selectedDocumento2.get_AdicionalComiss() && (!selectedDocumento2.get_AdicionalComiss() || !(this.CancelDocumento.get_PremioAdicional() != selectedDocumento2.get_PremioAdicional())) && !(this.CancelDocumento.get_Comissao() != selectedDocumento2.get_Comissao())) + { + negocioCorretora = this.CancelDocumento.get_NegocioCorretora(); + nullable = selectedDocumento2.get_NegocioCorretora(); + if (negocioCorretora.GetValueOrDefault() != nullable.GetValueOrDefault() | negocioCorretora.HasValue != nullable.HasValue || this.CancelDocumento.get_Diferenca() != selectedDocumento2.get_Diferenca() || this.CancelDocumento.get_Iof() != selectedDocumento2.get_Iof()) + { + goto Label1; + } + updatePremio = this.UpdatePremio; + goto Label0; + } + Label1: + updatePremio = true; + } + Label0: + bool flag6 = updatePremio; + if (selectedDocumento2.get_TipoRecebimento().GetValueOrDefault() == 2) + { + flag2 = false; + } + else + { + flag2 = (selectedDocumento2.get_Id() == 0 || this.CancelDocumento.get_NumeroParcelas() != selectedDocumento2.get_NumeroParcelas() ? true : selectedDocumento2.get_NumeroParcelas() != this.Parcelas.Count((Parcela x) => x.get_SubTipo() == 1)); + } + bool flag7 = flag2; + nullable = selectedDocumento2.get_NegocioCorretora(); + bool valueOrDefault1 = nullable.GetValueOrDefault() == 1; + if (flag7 && selectedDocumento2.get_TipoRecebimento().GetValueOrDefault() == 1) + { + this.CriarParcelas(id1); + this.Parcelas.ToList().ForEach((Parcela x) => { + x.set_Documento(selectedDocumento2); + List> keyValuePairs = keyValuePairs1; + Parcela parcela = x; + List configuracoes = Recursos.Configuracoes; + Func u003cu003e9_29911 = BaseApoliceViewModel.u003cu003ec.u003cu003e9__299_11; + if (u003cu003e9_29911 == null) + { + u003cu003e9_29911 = (ConfiguracaoSistema y) => y.get_Configuracao() == 9; + BaseApoliceViewModel.u003cu003ec.u003cu003e9__299_11 = u003cu003e9_29911; + } + bool flag = configuracoes.Any(u003cu003e9_29911); + List configuracaoSistemas = Recursos.Configuracoes; + Func u003cu003e9_29912 = BaseApoliceViewModel.u003cu003ec.u003cu003e9__299_12; + if (u003cu003e9_29912 == null) + { + u003cu003e9_29912 = (ConfiguracaoSistema y) => y.get_Configuracao() == 11; + BaseApoliceViewModel.u003cu003ec.u003cu003e9__299_12 = u003cu003e9_29912; + } + bool flag1 = configuracaoSistemas.Any(u003cu003e9_29912); + bool editandoParcela = this.EditandoParcela; + List configuracoes1 = Recursos.Configuracoes; + Func u003cu003e9_29913 = BaseApoliceViewModel.u003cu003ec.u003cu003e9__299_13; + if (u003cu003e9_29913 == null) + { + u003cu003e9_29913 = (ConfiguracaoSistema r) => r.get_Configuracao() == 16; + BaseApoliceViewModel.u003cu003ec.u003cu003e9__299_13 = u003cu003e9_29913; + } + keyValuePairs.AddRange(parcela.Validate(flag, flag1, editandoParcela, configuracoes1.Any(u003cu003e9_29913))); + }); + if (keyValuePairs1.Count > 0) + { + base.Alterar(true); + list = keyValuePairs1.Distinct>().ToList>(); + return list; + } + } + if (this.Parcelas == null || this.Parcelas.Count == 0) + { + this.Pagamentos = new ObservableCollection(); + } + if (flag6 && !flag7) + { + this.AtualizaValores(valueOrDefault1); + } + if (this.SelectedDocumento.get_Situacao() == 5 && this.SelectedDocumento.get_Controle().get_Documentos() != null && this.SelectedDocumento.get_Controle().get_Documentos().Count > 0) + { + IList documentos = this.SelectedDocumento.get_Controle().get_Documentos(); + foreach (Documento documento3 in documentos.Where((Documento x) => { + if (x.get_Tipo() == 0) + { + return false; + } + return !x.get_Excluido(); + })) + { + if (documento3.get_Situacao() == 3) + { + continue; + } + documento3.set_SituacaoAnterior(new TipoSeguro?(documento3.get_Situacao())); + documento3.set_Situacao(5); + await this.Servico.Save(documento3, false, false); + } + } + if (this.SelectedDocumento.get_Id() != 0 && this.SelectedDocumento.get_Tipo() == 0 && this.SelectedDocumento.get_Controle().get_Documentos() != null && this.SelectedDocumento.get_Controle().get_Documentos().Count > 0) + { + IList documentos1 = this.SelectedDocumento.get_Controle().get_Documentos(); + if (documentos1.Where((Documento x) => { + if (x.get_Tipo() == 0) + { + return false; + } + return !x.get_Excluido(); + }).Any((Documento x) => { + if (x.get_Apolice() != this.SelectedDocumento.get_Apolice()) + { + return true; + } + return x.get_Proposta() != this.SelectedDocumento.get_Proposta(); + })) + { + IList documentos2 = this.SelectedDocumento.get_Controle().get_Documentos(); + foreach (Documento documento4 in documentos2.Where((Documento x) => { + if (x.get_Tipo() == 0) + { + return false; + } + return !x.get_Excluido(); + })) + { + documento4.set_Apolice(this.SelectedDocumento.get_Apolice()); + documento4.set_Proposta(this.SelectedDocumento.get_Proposta()); + await this.Servico.Save(documento4, false, false); + base.ToggleSnackBar("NUMERO DA PROPOSTA/APOLICE ATUALIZADOS NO ENDOSSO", true); + } + } + } + if (this.Renovar) + { + nullable = this.CancelDocumento.get_NegocioCorretora(); + if (!nullable.HasValue) + { + Documento cancelDocumento = this.CancelDocumento; + negocioCorretora2 = (!this.CancelDocumento.get_Negocio().HasValue || this.CancelDocumento.get_Negocio().GetValueOrDefault() != 1 ? 0 : 1); + cancelDocumento.set_NegocioCorretora(new NegocioCorretora?(negocioCorretora2)); + } + this.CancelDocumento.set_Situacao(5); + IList documentos3 = this.CancelDocumento.get_Controle().get_Documentos(); + IEnumerable documentos4 = documentos3.Where((Documento d) => { + if (d.get_Tipo() != 1) + { + return false; + } + if (d.get_Situacao() == 1 || d.get_Situacao() == 2) + { + return true; + } + return d.get_Situacao() == 4; + }); + foreach (Documento documento5 in documentos4) + { + documento5.set_Situacao(5); + await this.Servico.Save(documento5, false, false); + } + this.Servico.Sucesso = true; + await this.Servico.Save(this.CancelDocumento, false, false); + if (!this.Servico.Sucesso) + { + await base.ShowMessage("NÃO FOI POSSÍVEL ALTERAR O STATUS DO DOCUMENTO RENOVADO, POR FAVOR VERIFIQUE APÓS O PROCEDIMENTO SER CONCLUÍDO.", "OK", "", false); + } + str2 = (string.IsNullOrEmpty(this.CancelDocumento.get_Apolice()) ? string.Concat("A PROPOSTA \"", this.CancelDocumento.get_Proposta(), "\"") : string.Concat("A APÓLICE \"", this.CancelDocumento.get_Apolice(), "\"")); + string str3 = str2; + base.RegistrarAcao(string.Concat("RENOVOU ", str3), this.CancelDocumento.get_Id(), new TipoTela?(2), this.GerarObs(this.CancelDocumento)); + } + if (selectedDocumento2.get_TipoEndosso().HasValue && selectedDocumento2.get_TipoEndosso().GetValueOrDefault() == 4 && this.SelectedDocumento.get_Vigencia2().HasValue) + { + ApoliceServico servico = this.Servico; + long num = this.SelectedDocumento.get_Controle().get_Id(); + DateTime? vigencia2 = this.SelectedDocumento.get_Vigencia2(); + if (!await servico.Prorrogar(num, vigencia2.Value)) + { + await base.ShowMessage("NÃO FOI POSSÍVEL ALTERAR A VIGÊNCIA FINAL DA APÓLICE, POR FAVOR VERIFIQUE APÓS O PROCEDIMENTO SER CONCLUÍDO.", "OK", "", false); + } + } + if (selectedDocumento2.get_TipoEndosso().HasValue && selectedDocumento2.get_TipoEndosso().GetValueOrDefault() == 3) + { + if (!await this.Servico.Reabilitar(this.SelectedDocumento.get_Controle().get_Id())) + { + await base.ShowMessage("NÃO FOI POSSÍVEL ALTERAR O STATUS DA APÓLICE, POR FAVOR VERIFIQUE APÓS O PROCEDIMENTO SER CONCLUÍDO.", "OK", "", false); + } + } + if (selectedDocumento2.get_TipoEndosso().HasValue && selectedDocumento2.get_TipoEndosso().GetValueOrDefault() == 2) + { + IList documentos5 = this.CancelDocumento.get_Controle().get_Documentos(); + Documento documento6 = documentos5.FirstOrDefault((Documento x) => x.get_Tipo() == 0); + documento6.set_Situacao(3); + IList documentos6 = this.CancelDocumento.get_Controle().get_Documentos(); + IEnumerable tipo1 = + from x in documentos6 + where x.get_Tipo() == 1 + select x; + foreach (Documento documento7 in tipo1) + { + documento7.set_Situacao(3); + await this.Servico.Save(documento7, false, false); + } + nullable = documento6.get_NegocioCorretora(); + if (!nullable.HasValue) + { + Documento documento8 = documento6; + negocioCorretora1 = (!documento6.get_Negocio().HasValue || documento6.get_Negocio().GetValueOrDefault() != 1 ? 0 : 1); + documento8.set_NegocioCorretora(new NegocioCorretora?(negocioCorretora1)); + } + selectedDocumento2.set_Situacao(3); + this.Servico.Sucesso = true; + await this.Servico.Save(documento6, false, false); + if (!this.Servico.Sucesso) + { + await base.ShowMessage("NÃO FOI POSSÍVEL ALTERAR O STATUS DO DOCUMENTO CANCELADO, POR FAVOR VERIFIQUE APÓS O PROCEDIMENTO SER CONCLUÍDO.", "OK", "", false); + } + tipo = id1; + if (tipo) + { + tipo = await base.ShowMessage("DESEJA BAIXAR AS PARCELAS PENDENTES ABAIXO DESSE DOCUMENTO?", "SIM", "NÃO", false); + } + if (tipo) + { + bool flag8 = true; + foreach (Documento documento9 in documento6.get_Controle().get_Documentos()) + { + tipo = await this.Servico.BaixarParcelasCancelamento(documento9, false); + flag8 = tipo & flag8; + } + if (!flag8) + { + await base.ShowMessage("NÃO FOI POSSÍVEL AS PARCELAS DO DOCUMENTO CANCELADO, POR FAVOR VERIFIQUE APÓS O PROCEDIMENTO SER CONCLUÍDO.", "OK", "", false); + } + } + string str4 = string.Concat("A APÓLICE \"", documento6.get_Apolice(), "\""); + base.RegistrarAcao(string.Concat("CANCELOU ", str4), documento6.get_Id(), new TipoTela?(2), this.GerarObs(documento6)); + documento6 = null; + } + if (this.Parcelas != null) + { + Documento documento10 = selectedDocumento2; + ObservableCollection parcelas = this.Parcelas; + documento10.set_Parcelas(new ObservableCollection( + from x in parcelas + where x.get_SubTipo() == 1 + select x)); + } + if (!string.IsNullOrWhiteSpace(this.Anotacoes)) + { + Documento documento11 = selectedDocumento2; + object[] nome = new object[] { Recursos.Usuario.get_Nome(), Recursos.Usuario.get_Id(), Funcoes.GetNetworkTime(), Environment.NewLine, this.Anotacoes, Environment.NewLine, Environment.NewLine, selectedDocumento2.get_Observacao() }; + documento11.set_Observacao(string.Format("{0}, ID: {1}, {2:g}{3}{4}{5}{6}{7}", nome)); + } + Documento documentoSelecionado = this.DocumentoSelecionado; + if (documentoSelecionado != null) + { + documentoSelecionado.get_Situacao(); + flag3 = true; + } + else + { + flag3 = false; + } + if (flag3 && this.DocumentoSelecionado.get_Situacao() == 7 && this.DocumentoSelecionado.get_Situacao() != selectedDocumento2.get_Situacao()) + { + ObservableCollection observableCollection = selectedDocumento2.get_Parcelas(); + if (observableCollection != null) + { + flag5 = ( + from x in observableCollection + where x.get_DataRecebimento().HasValue + select x).Count() >= 1; + } + else + { + flag5 = false; + } + if (flag5) + { + await base.ShowMessage("O DOCUMENTO TEM PARCELAS BAIXADAS DEVIDO A RECUSA. CASO NECESSÁRIO, REALIZE A EXCLUSÃO DAS BAIXAS MANUALMENTE.", "OK", "", false); + base.Alterar(true); + list = null; + return list; + } + } + this.Servico.Sucesso = true; + if (selectedDocumento2.get_Id() == 0) + { + selectedDocumento2.set_DataCriacao(new DateTime?(Funcoes.GetNetworkTime())); + selectedDocumento2.set_UsuarioCriacao(Recursos.Usuario); + } + selectedDocumento2.set_SituacaoAnterior(new TipoSeguro?(selectedDocumento2.get_Situacao())); + Documento documento12 = await this.Servico.Save(selectedDocumento2, flag6, flag7); + Documento documento13 = documento12; + ObservableCollection pagamentos = this.Pagamentos; + if (pagamentos != null) + { + vendedorParcelas = pagamentos.Where((VendedorParcela p) => { + if (documento13.get_TipoRecebimento().GetValueOrDefault() != 1 || p.get_Repasse() == null || p.get_Repasse().get_Base().GetValueOrDefault() != 1 && p.get_Repasse().get_Base().GetValueOrDefault() != 4 && p.get_Repasse().get_Base().GetValueOrDefault() != 5) + { + return false; + } + return !p.get_DataPagamento().HasValue; + }).ToList(); + } + else + { + vendedorParcelas = null; + } + List vendedorParcelas1 = vendedorParcelas; + if (vendedorParcelas1 != null && vendedorParcelas1.Count > 0) + { + List vendedorParcelas2 = new List(); + if (vendedorParcelas1 != null) + { + vendedorParcelas1.ForEach((VendedorParcela p) => { + DateTime? dataPrePagamento; + DateTime? emissao; + BaseRepasse? @base = p.get_Repasse().get_Base(); + if (@base.HasValue) + { + switch (@base.GetValueOrDefault()) + { + case 1: + { + dataPrePagamento = p.get_DataPrePagamento(); + DateTime vigencia1 = documento13.get_Vigencia1(); + if ((dataPrePagamento.HasValue ? dataPrePagamento.GetValueOrDefault() == vigencia1 : false)) + { + return; + } + p.set_DataPrePagamento(new DateTime?(documento13.get_Vigencia1())); + vendedorParcelas2.Add(p); + return; + } + case 2: + case 3: + { + break; + } + case 4: + { + dataPrePagamento = p.get_DataPrePagamento(); + emissao = documento13.get_Emissao(); + if ((dataPrePagamento.HasValue == emissao.HasValue ? (dataPrePagamento.HasValue ? dataPrePagamento.GetValueOrDefault() == emissao.GetValueOrDefault() : true) : false)) + { + return; + } + p.set_DataPrePagamento(documento13.get_Emissao()); + vendedorParcelas2.Add(p); + return; + } + case 5: + { + emissao = p.get_DataPrePagamento(); + dataPrePagamento = documento13.get_Remessa(); + if ((emissao.HasValue == dataPrePagamento.HasValue ? (emissao.HasValue ? emissao.GetValueOrDefault() == dataPrePagamento.GetValueOrDefault() : true) : false)) + { + return; + } + p.set_DataPrePagamento(documento13.get_Remessa()); + vendedorParcelas2.Add(p); + break; + } + default: + { + return; + } + } + } + }); + } + if (vendedorParcelas2.Count > 0) + { + await (new Gestor.Application.Servicos.ParcelaServico()).SaveRange(vendedorParcelas2.ToList()); + } + } + if (this.Servico.Sucesso) + { + Documento documentoSelecionado1 = this.DocumentoSelecionado; + if (documentoSelecionado1 != null) + { + documentoSelecionado1.get_Situacao(); + flag4 = true; + } + else + { + flag4 = false; + } + if (flag4 && this.DocumentoSelecionado.get_Situacao() == 7 && selectedDocumento2.get_Situacao() != this.DocumentoSelecionado.get_Situacao()) + { + Action acessaTela = Gestor.Application.Actions.Actions.AcessaTela; + if (acessaTela != null) + { + acessaTela(21, ""); + } + else + { + } + } + this.SelectedDocumento = await this.Servico.BuscarApoliceAsync(documento13.get_Id(), false, false); + this.SelectedDocumento.Initialize(); + await this.CarregarParcelas(this.SelectedDocumento); + await this.CarregaRepasse(this.SelectedDocumento.get_Id()); + this.SelectedParcela = this.Parcelas.FirstOrDefault(); + Documento selectedDocumento3 = this.SelectedDocumento; + List repasses = this.Repasses; + VendedorParcela vendedorParcela1 = repasses.FirstOrDefault((VendedorParcela x) => x.get_TipoVendedor().get_Id() == (long)1); + if (vendedorParcela1 != null) + { + vendedor1 = vendedorParcela1.get_Vendedor(); + } + else + { + vendedor1 = null; + } + selectedDocumento3.set_VendedorPrincipal(vendedor1); + bool renovar = this.Renovar; + documento = (renovar ? this.DocumentoRenovado : ConsultaViewModel.DocumentoSelecionado); + ConsultaViewModel.DocumentoRenovado = documento; + this.NovaApolice = false; + this.Renovar = false; + if (id1) + { + this.AllowEditApolice = true; + base.IsEnabledEdit = true; + base.IsEnabledEditEndosso = true; + if (this.Invoke) + { + ConsultaViewModel.DocumentoSelecionado = this.SelectedDocumento; + } + if (this.Invoke) + { + Action recarregarDocumentos = Gestor.Application.Actions.Actions.RecarregarDocumentos; + if (recarregarDocumentos != null) + { + recarregarDocumentos(this.SelectedDocumento); + } + else + { + } + } + if (this.Invoke) + { + Action updateDocumento = Gestor.Application.Actions.Actions.UpdateDocumento; + if (updateDocumento != null) + { + updateDocumento(this.SelectedDocumento); + } + else + { + } + } + } + else if (this.Invoke) + { + long num1 = this.SelectedDocumento.get_Id(); + Documento documentoSelecionado2 = ConsultaViewModel.DocumentoSelecionado; + if (documentoSelecionado2 != null) + { + nullable1 = new long?(documentoSelecionado2.get_Id()); + } + else + { + nullable1 = null; + } + long? nullable2 = nullable1; + if (num1 != nullable2.GetValueOrDefault() | !nullable2.HasValue) + { + ConsultaViewModel.DocumentoSelecionado = this.SelectedDocumento; + } + } + if (this.Parcelas.Count == 0) + { + this.AllowEditVendedor = false; + } + base.AllowEditParcela = true; + base.ToggleSnackBar("DOCUMENTO SALVO COM SUCESSO", true); + Action enableMainMenu = Gestor.Application.Actions.Actions.EnableMainMenu; + if (enableMainMenu != null) + { + enableMainMenu(true); + } + else + { + } + Action enableMenu = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu != null) + { + enableMenu(true); + } + else + { + } + if (renovar) + { + if (await base.ShowMessage("DESEJA MANTER OS DADOS DO PERFIL DA APÓLICE ANTERIOR?", "SIM", "NÃO", false)) + { + List perfils = await this.PerfilServico.BuscarPerfis(this.CancelDocumento.get_Controle().get_Id()); + int num2 = 0; + try + { + foreach (Perfil perfil in perfils.ToList()) + { + Perfil perfil1 = new Perfil(); + perfil1.set_Id((long)0); + perfil1.set_AntiFurto(perfil.get_AntiFurto()); + perfil1.set_CepCirculacao(Gestor.Model.Helper.ValidationHelper.FormataCep(perfil.get_CepCirculacao())); + perfil1.set_CepPernoite(Gestor.Model.Helper.ValidationHelper.FormataCep(perfil.get_CepPernoite())); + perfil1.set_Cliente(perfil.get_Cliente()); + Controle controle = new Controle(); + controle.set_AssistenciaId(perfil.get_Controle().get_AssistenciaId()); + controle.set_Cliente(perfil.get_Controle().get_Cliente()); + controle.set_Documentos(perfil.get_Controle().get_Documentos()); + controle.set_Id(this.SelectedDocumento.get_Controle().get_Id()); + controle.set_IdEmpresa(perfil.get_Controle().get_IdEmpresa()); + controle.set_Item(perfil.get_Controle().get_Item()); + controle.set_Produto(perfil.get_Controle().get_Produto()); + controle.set_Ramo(perfil.get_Controle().get_Ramo()); + controle.set_Seguradora(perfil.get_Controle().get_Seguradora()); + controle.set_SeguradoraAnterior(perfil.get_Controle().get_SeguradoraAnterior()); + perfil1.set_Controle(controle); + perfil1.set_Cpf(perfil.get_Cpf()); + perfil1.set_DistanciaResidenciaTrabalho(perfil.get_DistanciaResidenciaTrabalho()); + perfil1.set_EstadoCivil(perfil.get_EstadoCivil()); + perfil1.set_EstenderCobertura(perfil.get_EstenderCobertura()); + perfil1.set_GaragemEstudo(perfil.get_GaragemEstudo()); + perfil1.set_GaragemResidencia(perfil.get_GaragemResidencia()); + perfil1.set_GaragemTrabalho(perfil.get_GaragemTrabalho()); + perfil1.set_Habilitacao(perfil.get_Habilitacao()); + perfil1.set_Isencao(perfil.get_Isencao()); + perfil1.set_KmMensal(perfil.get_KmMensal()); + perfil1.set_Nascimento(perfil.get_Nascimento()); + perfil1.set_Nome(perfil.get_Nome()); + perfil1.set_Ocupacao(perfil.get_Ocupacao()); + perfil1.set_Relacao(perfil.get_Relacao()); + perfil1.set_SeguroVida(perfil.get_SeguroVida()); + perfil1.set_Sexo(perfil.get_Sexo()); + perfil1.set_TempoHabilitacao(perfil.get_TempoHabilitacao()); + perfil1.set_TipoResidencia(perfil.get_TipoResidencia()); + perfil1.set_UsoDependentes(perfil.get_UsoDependentes()); + perfil1.set_UsoProfissional(perfil.get_UsoProfissional()); + perfil1.set_VeiculoResidencia(perfil.get_VeiculoResidencia()); + await this.PerfilServico.Save(perfil1); + } + } + catch (Exception exception) + { + obj = exception; + num2 = 1; + } + if (num2 == 1) + { + Exception exception1 = (Exception)obj; + await base.ShowMessage("NÃO FOI POSSÍVEL MANTER OS DADOS DO PERFIL DA APÓLICE ANTERIOR, POR FAVOR VERIFIQUE APÓS O PROCEDIMENTO SER CONCLUÍDO.", "OK", "", false); + } + obj = null; + } + } + this.CancelDocumento = (Documento)this.SelectedDocumento.Clone(); + BaseApoliceViewModel baseApoliceViewModel = this; + str = (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 2 ? "EDITAR FATURAS" : "EDITAR PARCELAS"); + baseApoliceViewModel.EditarParcelasLabel = str; + base.EnableFields = false; + this.CalculaComissao(this.SelectedDocumento, this.Parcelas); + string str5 = (id1 ? "INCLUIU" : "ALTEROU"); + if (this.SelectedDocumento.get_Tipo() == 0 && string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + str1 = string.Concat("A PROPOSTA \"", this.SelectedDocumento.get_Proposta(), "\""); + } + else if (this.SelectedDocumento.get_Tipo() != 0 || string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + str1 = (string.IsNullOrEmpty(this.SelectedDocumento.get_Endosso()) ? string.Concat("A PROPOSTA DE ENDOSSO \"", this.SelectedDocumento.get_PropostaEndosso(), "\"") : string.Concat("O ENDOSSO \"", this.SelectedDocumento.get_Endosso(), "\"")); + } + else + { + str1 = string.Concat("A APÓLICE \"", this.SelectedDocumento.get_Apolice(), "\""); + } + string str6 = str1; + base.RegistrarAcao(string.Concat(str5, " ", str6), this.SelectedDocumento.get_Id(), new TipoTela?(2), this.GerarObs(this.SelectedDocumento)); + if (renovar) + { + valueOrDefault = true; + } + else if (!this.IsEndosso) + { + valueOrDefault = false; + } + else + { + TipoEndosso? tipoEndosso = this.SelectedDocumento.get_TipoEndosso(); + valueOrDefault = tipoEndosso.GetValueOrDefault() != 2; + } + if (valueOrDefault & id1) + { + Action action = Gestor.Application.Actions.Actions.AcessaTela; + if (action != null) + { + action(3, (renovar ? "Renovação" : "Endosso")); + } + else + { + } + list = null; + } + else if (this.SelectedDocumento.get_TipoEndosso().GetValueOrDefault() != 2) + { + tipo = (!this.Invoke ? true : !id1); + if (!tipo) + { + tipo = !await base.ShowMessage("DESEJA INCLUIR O ITEM AGORA?", "SIM", "NÃO", false); + } + if (!tipo) + { + Action acessaTela1 = Gestor.Application.Actions.Actions.AcessaTela; + if (acessaTela1 != null) + { + acessaTela1(3, ""); + } + else + { + } + list = null; + } + else + { + list = null; + } + } + else + { + list = null; + } + } + else + { + base.Alterar(true); + list = null; + } + } + else + { + await base.ShowMessage("EM DOCUMENTOS CANCELADOS SÓ É POSSIVEL INCLUIR ENDOSSO DE REABILITAÇÃO.", "OK", "", false); + base.Alterar(true); + list = null; + } + } + else + { + list = keyValuePairs1; + } + return list; + } + + public async Task>> SalvarParcelas(int tipo) + { + List> keyValuePairs; + decimal num; + int num1; + bool flag; + if (this.SelectedParcela.get_Documento() == null) + { + this.SelectedParcela.set_Documento(this.SelectedDocumento); + } + this.SelectedParcela.get_Documento().set_Parcelas(this.Parcelas); + if (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 1 && this.SelectedParcela.get_SubTipo() == 1 && this.SelectedParcela.get_Comissao() == decimal.Zero) + { + this.SelectedParcela.set_Comissao(this.SelectedDocumento.get_Comissao()); + } + Parcela selectedParcela = this.SelectedParcela; + List configuracoes = Recursos.Configuracoes; + bool flag1 = configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 9); + List configuracaoSistemas = Recursos.Configuracoes; + bool flag2 = configuracaoSistemas.Any((ConfiguracaoSistema y) => y.get_Configuracao() == 11); + bool editandoParcela = this.EditandoParcela; + List configuracoes1 = Recursos.Configuracoes; + List> keyValuePairs1 = selectedParcela.Validate(flag1, flag2, editandoParcela, configuracoes1.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 16)); + keyValuePairs1.AddRange(this.ValidaParcelaEspecial(tipo)); + num = (this.SelectedParcela.get_ValorExtrato() == decimal.Zero ? this.SelectedParcela.get_ValorLiquidoFatura() : this.SelectedParcela.get_ValorExtrato()); + decimal num2 = num; + num1 = (num2 > decimal.Zero ? num2.CompareTo(this.SelectedParcela.get_ValorComissao()) : this.SelectedParcela.get_ValorComissao().CompareTo(num2)); + int num3 = num1; + flag = (keyValuePairs1.Count != 1 || 2 != this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() ? false : num3 < 0); + bool flag3 = flag; + if (flag3) + { + flag3 = await base.ShowMessage("VALOR RECEBIMENTO MAIOR QUE VALOR PARCELA, CONTINUAR?", "SIM", "NÃO", false); + } + if (flag3) + { + keyValuePairs1.Clear(); + } + if (keyValuePairs1.Count <= 0) + { + this.SelectedParcela.set_Baixando(false); + List configuracaoSistemas1 = Recursos.Configuracoes; + if (!configuracaoSistemas1.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 5) && (this.SelectedParcela.get_Iss() > decimal.Zero || this.SelectedParcela.get_Irr() > decimal.Zero || this.SelectedParcela.get_Outros() > decimal.Zero || this.SelectedParcela.get_Desconto() > decimal.Zero)) + { + this.SelectedParcela.set_Iss(decimal.Zero); + this.SelectedParcela.set_Irr(decimal.Zero); + this.SelectedParcela.set_Outros(decimal.Zero); + this.SelectedParcela.set_Desconto(decimal.Zero); + this.SelectedParcela.set_ValorComDesconto(this.SelectedParcela.get_ValorComissao()); + } + switch (tipo) + { + case 1: + { + await this.AlterarVencimento(); + break; + } + case 2: + { + await this.BaixarComissao(); + break; + } + case 3: + case 4: + { + await this.AdicionarParcelaEspecial(); + break; + } + } + keyValuePairs = null; + } + else + { + keyValuePairs = keyValuePairs1; + } + keyValuePairs1 = null; + return keyValuePairs; + } + + public async void Seleciona(Documento documento) + { + base.Loading(true); + await base.PermissaoTela(2); + await base.PermissaoTela(5); + if (documento == null || (object)documento != (object)this.SelectedDocumento) + { + await this.SelecionaDocumento(documento); + } + Action redimencionar = Gestor.Application.Actions.Actions.Redimencionar; + if (redimencionar != null) + { + redimencionar(this.Invoke); + } + else + { + } + base.Loading(false); + } + + public async Task SelecionaDocumento(Documento documento) + { + long? nullable; + base.Loading(true); + base.IsEnabled = false; + await this.BuscarVendedores(false); + List estipulantes = await (new BaseServico()).BuscarEstipulantes(); + BaseApoliceViewModel list = this; + IEnumerable estipulantes1 = estipulantes.Where((Estipulante x) => { + if (documento == null) + { + return x.get_IdEmpresa() == Recursos.Usuario.get_IdEmpresa(); + } + if (x.get_IdEmpresa() != documento.get_Controle().get_IdEmpresa()) + { + return false; + } + return x.get_Ativo(); + }); + list.Estipulantes = ( + from x in estipulantes1 + orderby x.get_Nome() + select x).ToList(); + this.SelectedDocumento = null; + this.PreLoad(); + if (documento != null) + { + await this.WorkOnSelectedDocumento(documento); + if (this.Invoke) + { + long id = this.SelectedDocumento.get_Id(); + Documento documentoSelecionado = ConsultaViewModel.DocumentoSelecionado; + if (documentoSelecionado != null) + { + nullable = new long?(documentoSelecionado.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + if (id != nullable1.GetValueOrDefault() | !nullable1.HasValue) + { + ConsultaViewModel.DocumentoSelecionado = this.SelectedDocumento; + } + } + if (this.Acesso == 1 && this.ParcelaSelecionada != 0) + { + await this.SelecionaParcela(this.Parcelas.FirstOrDefault((Parcela x) => x.get_Id() == this.ParcelaSelecionada)); + } + if (this.Invoke) + { + this.Loaded = true; + } + base.IsEnabled = true; + base.Loading(false); + } + else + { + base.EnableFields = false; + base.Loading(false); + } + } + + public async Task SelecionaParcela(Parcela parcela) + { + bool flag; + bool flag1; + this.SelectedParcela = parcela; + if (parcela != null && parcela.get_Id() != 0 && this.SelectedDocumento != null) + { + if (this.Repasses == null) + { + await this.CarregaRepasse(this.SelectedDocumento.get_Id()); + } + List list = ( + from x in this.Repasses + where x.get_Parcela().get_Id() == parcela.get_Id() + select x).ToList(); + if (this.IsFatura || parcela.get_SubTipo() != 1) + { + BaseApoliceViewModel baseApoliceViewModel = this; + flag = (parcela.get_DataRecebimento().HasValue ? false : list.All((VendedorParcela x) => { + if (x.get_Parcela().get_Id() != parcela.get_Id()) + { + return false; + } + return !x.get_DataPagamento().HasValue; + })); + baseApoliceViewModel.AllowEditVendedor = flag; + } + if (!this.IsFatura && parcela.get_SubTipo() == 1) + { + BaseApoliceViewModel baseApoliceViewModel1 = this; + if (parcela.get_NumeroParcela() != 1 || parcela.get_DataRecebimento().HasValue) + { + flag1 = false; + } + else + { + List vendedorParcelas = list; + flag1 = vendedorParcelas.All((VendedorParcela x) => { + if (x.get_Parcela().get_SubTipo() != 1) + { + return false; + } + return !x.get_DataPagamento().HasValue; + }); + } + baseApoliceViewModel1.AllowEditVendedor = flag1; + } + BaseApoliceViewModel observableCollection = this; + List vendedorParcelas1 = list; + observableCollection.Pagamentos = new ObservableCollection( + from x in vendedorParcelas1 + orderby x.get_TipoVendedor().get_Id() + select x); + } + } + + public void SelecionaPrimeiraParcela() + { + this.SelectedParcela = this.SelectedParcela ?? this.Parcelas.FirstOrDefault(); + } + + public async Task SelecionarParcelaBaixa() + { + bool flag; + decimal num; + decimal num1; + Parcela parcela; + if (this.SelectedParcela == null || this.SelectedDocumento == null) + { + flag = false; + } + else if (this.SelectedParcela.get_SubTipo() != 1 && !this.SelectedParcela.get_DataRecebimento().HasValue) + { + Parcela selectedParcela = this.SelectedParcela; + decimal premioLiquido = this.SelectedDocumento.get_PremioLiquido(); + num1 = (this.SelectedDocumento.get_NumeroParcelas() > decimal.Zero ? this.SelectedDocumento.get_NumeroParcelas() : decimal.One); + selectedParcela.set_ValorLiquidoFatura(premioLiquido / num1); + this.SelectedParcela.set_Baixando(true); + flag = true; + } + else if (this.IsFatura && !this.SelectedParcela.get_DataRecebimento().HasValue) + { + this.SelectedParcela.set_Baixando(true); + flag = true; + } + else if (this.Parcelas == null || !this.Parcelas.Any()) + { + flag = false; + } + else + { + ObservableCollection parcelas = this.Parcelas; + IOrderedEnumerable numeroParcela = + from x in parcelas + orderby x.get_NumeroParcela() + select x; + parcela = numeroParcela.FirstOrDefault((Parcela x) => { + if (x.get_DataRecebimento().HasValue) + { + return false; + } + return x.get_SubTipo() == 1; + }); + if (parcela != null && !this.IsFatura && this.SelectedDocumento.get_NumeroParcelas() > decimal.Zero) + { + Parcela parcela1 = parcela; + num = (this.SelectedDocumento.get_AdicionalComiss() ? (this.SelectedDocumento.get_PremioLiquido() + this.SelectedDocumento.get_PremioAdicional()) / this.SelectedDocumento.get_NumeroParcelas() : this.SelectedDocumento.get_PremioLiquido() / this.SelectedDocumento.get_NumeroParcelas()); + parcela1.set_ValorLiquidoFatura(num); + } + BaseApoliceViewModel baseApoliceViewModel = this; + Parcela selectedParcela1 = parcela; + if (selectedParcela1 == null) + { + selectedParcela1 = this.SelectedParcela; + } + baseApoliceViewModel.SelectedParcela = selectedParcela1; + if (parcela == null) + { + await base.ShowMessage("NÃO HÁ MAIS NENHUMA PARCELA A SER BAIXADA", "OK", "", false); + } + if (parcela != null) + { + this.SelectedParcela.set_Baixando(true); + } + flag = parcela != null; + } + parcela = null; + return flag; + } + + public void SelecionarVendedor() + { + VendedorParcela vendedorParcela; + ObservableCollection pagamentos = this.Pagamentos; + if (pagamentos != null) + { + vendedorParcela = pagamentos.FirstOrDefault(); + } + else + { + vendedorParcela = null; + } + this.SelectedPagamento = vendedorParcela; + } + + public void ToggleSeguradoraAnterior(TipoSeguro situacao) + { + if (situacao != 2) + { + this.IsRenovacaoVisibility = Visibility.Collapsed; + return; + } + this.IsRenovacaoVisibility = Visibility.Visible; + } + + private List> ValidaParcelaEspecial(int tipo) + { + List> keyValuePairs = new List>(); + if (tipo == 4 && this.SelectedParcela.get_SubTipo() == 1) + { + keyValuePairs.Add(new KeyValuePair("SubTipo|TIPO", "A PARCELA ESPECIAL NÃO PODE SER DO TIPO PARCELA NORMAL")); + } + return keyValuePairs; + } + + public List> Validate(VendedorParcela pagamento) + { + long? nullable; + bool count; + List> keyValuePairs = new List>(); + if (pagamento == null || this.SelectedDocumento == null) + { + keyValuePairs.Add(new KeyValuePair("pagamento|PAGAMENTO", "ERRO AO INSERIR VENDEDOR.")); + return keyValuePairs; + } + if (pagamento.get_TipoVendedor() == null || pagamento.get_Vendedor() == null) + { + return keyValuePairs; + } + if (this.Repasses == null) + { + this.Repasses = new List(); + } + if (this.Repasses.Count > 0) + { + if (this.Repasses.All((VendedorParcela x) => x.get_Parcela() == null)) + { + if (this.SelectedDocumento.get_Id() > (long)0) + { + ObservableCollection parcelas = this.Parcelas; + if (parcelas != null) + { + count = parcelas.Count > 0; + } + else + { + count = false; + } + if (count) + { + keyValuePairs.Add(new KeyValuePair("|PARCELA", "PARCELA DEVE SER SELECIONADA PARA A INCLUSÃO DO VENDEDOR.")); + return keyValuePairs; + } + } + if (this.SelectedDocumento.get_Tipo() != 1) + { + goto Label1; + } + keyValuePairs.Add(new KeyValuePair("|PARCELA", "PARCELA DEVE SER SELECIONADA PARA A INCLUSÃO DO VENDEDOR.")); + return keyValuePairs; + } + Label1: + IEnumerable vendedorParcelas = this.Repasses.Where((VendedorParcela x) => { + if (x.get_Parcela().get_SubTipo() != 1) + { + return false; + } + decimal? porcentagemRepasse = x.get_PorcentagemRepasse(); + if ((porcentagemRepasse.GetValueOrDefault() == 100) & porcentagemRepasse.HasValue) + { + return false; + } + return pagamento.get_Repasse().get_Forma().GetValueOrDefault() == 1; + }); + decimal num = vendedorParcelas.Sum((VendedorParcela x) => x.get_ValorRepasse().GetValueOrDefault()) + pagamento.get_ValorRepasse().GetValueOrDefault(); + decimal num1 = ((this.SelectedDocumento.get_AdicionalComiss() ? this.SelectedDocumento.get_PremioLiquido() + this.SelectedDocumento.get_PremioAdicional() : this.SelectedDocumento.get_PremioLiquido()) * this.SelectedDocumento.get_Comissao()) * new decimal(1, 0, 0, false, 2); + if (Recursos.Configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 15) && Math.Abs(num) > (Math.Abs(num1) + this.Tolerancia)) + { + keyValuePairs.Add(new KeyValuePair("ValorRepasse|VALOR DO REPASSE", "O TOTAL DE COMISSÃO PAGA NÃO PODE SER SUPERIOR A COMISSÃO PREVISTA PARA RECEBIMENTO.")); + } + if (this.Repasses.Where((VendedorParcela vendedorParcela) => { + if (vendedorParcela.get_Repasse() == null) + { + return false; + } + return vendedorParcela.get_Repasse().get_Tipo().GetValueOrDefault() != 3; + }).Any((VendedorParcela x) => { + if (x.get_TipoVendedor().get_Id() != pagamento.get_TipoVendedor().get_Id() || x.get_Vendedor().get_Corretora()) + { + return false; + } + return x.get_Parcela().get_SubTipo() == 1; + })) + { + keyValuePairs.Add(new KeyValuePair("TipoVendedor|TIPO VENDEDOR", string.Concat("JÁ EXISTE UM VENDEDOR DO TIPO ", pagamento.get_TipoVendedor().get_Descricao(), " ADICIONADO AO DOCUMENTO."))); + } + if (this.Repasses.Any((VendedorParcela x) => { + if (x.get_Vendedor().get_Id() != pagamento.get_Vendedor().get_Id()) + { + return false; + } + return x.get_Parcela().get_SubTipo() == 1; + })) + { + keyValuePairs.Add(new KeyValuePair("Nome|VENDEDOR", string.Concat("VENDEDOR ", pagamento.get_Vendedor().get_Nome(), " JÁ ADICIONADO AO DOCUMENTO."))); + } + } + long id = pagamento.get_Vendedor().get_Id(); + Gestor.Model.Domain.Seguros.Repasse repasse = pagamento.get_Repasse(); + if (repasse != null) + { + nullable = new long?(repasse.get_Vendedor().get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + if (id != nullable1.GetValueOrDefault() | !nullable1.HasValue) + { + keyValuePairs.Add(new KeyValuePair("ValorRepasse|VALOR DO REPASSE", "PERCENTUAL DE REPASSE DEVE SER SELECIONADO")); + } + return keyValuePairs; + } + + public List> ValidateEspecial(VendedorParcela pagamento) + { + decimal? nullable2; + List> keyValuePairs = new List>(); + if (this.SelectedParcela == null) + { + keyValuePairs.Add(new KeyValuePair("SelectedParcela|PARCELA", "PARCELA DEVE SER SELECIONADA PARA A INCLUSÃO DO VENDEDOR.")); + return keyValuePairs; + } + if (this.Repasses == null) + { + this.Repasses = new List(); + } + decimal? nullable3 = ( + from x in this.Repasses + where x.get_Parcela().get_Id() == pagamento.get_Parcela().get_Id() + select x).Sum((VendedorParcela x) => x.get_ValorRepasse()); + decimal? valorRepasse = pagamento.get_ValorRepasse(); + if (nullable3.HasValue & valorRepasse.HasValue) + { + nullable2 = new decimal?(nullable3.GetValueOrDefault() + valorRepasse.GetValueOrDefault()); + } + else + { + nullable2 = null; + } + decimal? nullable4 = nullable2; + decimal valor = this.SelectedParcela.get_Valor(); + decimal num = (this.SelectedParcela.get_DataRecebimento().HasValue ? this.SelectedParcela.get_ValorComDesconto() : (valor * this.SelectedParcela.get_Comissao()) * new decimal(1, 0, 0, false, 2)); + if (Recursos.Configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 15) && nullable4.HasValue && Math.Abs(nullable4.Value) > (Math.Abs(num) + this.Tolerancia)) + { + keyValuePairs.Add(new KeyValuePair("SelectedParcela|VALOR DO REPASSE", "O TOTAL DE COMISSÃO PAGA NÃO PODE SER SUPERIOR A COMISSÃO PREVISTA PARA RECEBIMENTO.")); + } + if (pagamento.get_Parcela() == null) + { + if (this.Repasses.Any((VendedorParcela x) => { + if (x.get_TipoVendedor().get_Id() != pagamento.get_TipoVendedor().get_Id()) + { + return false; + } + return !x.get_Vendedor().get_Corretora(); + })) + { + keyValuePairs.Add(new KeyValuePair("TipoVendedor|TIPO VENDEDOR", string.Concat("JÁ EXISTE UM VENDEDOR DO TIPO ", pagamento.get_TipoVendedor().get_Descricao(), " ADICIONADO AO DOCUMENTO."))); + } + if (this.Repasses.Any((VendedorParcela x) => x.get_Vendedor().get_Id() == pagamento.get_Vendedor().get_Id())) + { + keyValuePairs.Add(new KeyValuePair("Nome|VENDEDOR", string.Concat("VENDEDOR ", pagamento.get_Vendedor().get_Nome(), " JÁ ADICIONADO AO DOCUMENTO"))); + } + return keyValuePairs; + } + if (pagamento.get_Parcela().get_SubTipo() == 1) + { + if (this.Repasses.Any((VendedorParcela x) => { + long? nullable; + long id = x.get_TipoVendedor().get_Id(); + TipoVendedor tipoVendedor = pagamento.get_TipoVendedor(); + if (tipoVendedor != null) + { + nullable = new long?(tipoVendedor.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + if (!(id == nullable1.GetValueOrDefault() & nullable1.HasValue) || x.get_Vendedor().get_Corretora()) + { + return false; + } + return x.get_Parcela().get_Id() == pagamento.get_Parcela().get_Id(); + })) + { + keyValuePairs.Add(new KeyValuePair("TipoVendedor|TIPO VENDEDOR", string.Concat("JÁ EXISTE UM VENDEDOR DO TIPO ", pagamento.get_TipoVendedor().get_Descricao(), " ADICIONADO AO DOCUMENTO."))); + } + if (this.Repasses.Any((VendedorParcela x) => { + if (x.get_Vendedor().get_Id() != pagamento.get_Vendedor().get_Id()) + { + return false; + } + return x.get_Parcela().get_Id() == pagamento.get_Parcela().get_Id(); + })) + { + keyValuePairs.Add(new KeyValuePair("Nome|VENDEDOR", string.Concat("VENDEDOR ", pagamento.get_Vendedor().get_Nome(), " JÁ ADICIONADO AO DOCUMENTO"))); + } + return keyValuePairs; + } + if (this.Repasses.Any((VendedorParcela x) => { + if (x.get_Parcela().get_Id() != pagamento.get_Parcela().get_Id() || x.get_TipoVendedor().get_Id() != pagamento.get_TipoVendedor().get_Id()) + { + return false; + } + return !x.get_Vendedor().get_Corretora(); + })) + { + keyValuePairs.Add(new KeyValuePair("TipoVendedor|TIPO VENDEDOR", string.Concat("JÁ EXISTE UM VENDEDOR DO TIPO ", pagamento.get_TipoVendedor().get_Descricao(), " ADICIONADO A PARCELA."))); + } + if (this.Repasses.Any((VendedorParcela x) => { + if (x.get_Parcela().get_Id() != pagamento.get_Parcela().get_Id()) + { + return false; + } + return x.get_Vendedor().get_Id() == pagamento.get_Vendedor().get_Id(); + })) + { + keyValuePairs.Add(new KeyValuePair("Nome|VENDEDOR", string.Concat("VENDEDOR ", pagamento.get_Vendedor().get_Nome(), " JÁ ADICIONADO A PARCELA"))); + } + return keyValuePairs; + } + + public List VendedorCoCorretagem(bool coCorretagem = false) + { + List vendedors; + if (coCorretagem) + { + List list = this.Vendedores.Where((Vendedor vendedor) => { + List repassesVendedores = this.RepassesVendedores; + if (repassesVendedores == null) + { + return false; + } + return repassesVendedores.FindAll((Gestor.Model.Domain.Seguros.Repasse repasse) => repasse.get_Vendedor().get_Id() == vendedor.get_Id()).Any((Gestor.Model.Domain.Seguros.Repasse x) => x.get_Tipo().GetValueOrDefault() == 3); + }).ToList(); + vendedors = list; + this.Vendedores = list; + return vendedors; + } + List list1 = Recursos.Vendedores.Where((Vendedor vendedor) => { + if (!vendedor.get_Ativo() || vendedor.get_Corretora()) + { + return false; + } + return vendedor.get_IdEmpresa() == Recursos.Usuario.get_IdEmpresa(); + }).OrderBy((Vendedor v) => v.get_Nome()).ToList(); + vendedors = list1; + this.Vendedores = list1; + return vendedors; + } + + public bool VerificaCoCorretagem() + { + List repasses = this.Repasses; + if (repasses == null) + { + return false; + } + return repasses.Any((VendedorParcela x) => x.get_CoCorretagem()); + } + + public async Task VerificarVigencia(Documento documento) + { + bool flag; + string str; + if (documento.get_Vigencia2().HasValue) + { + DateTime? vigencia2 = documento.get_Vigencia2(); + TimeSpan timeSpan = DateTime.Parse(vigencia2.ToString()) - documento.get_Vigencia1(); + if (timeSpan.Days > 366) + { + str = "VIGÊNCIA FINAL MAIOR QUE 365 DIAS.\nDESEJA CONTINUAR?"; + } + else + { + str = (timeSpan.Days < 365 ? "VIGÊNCIA FINAL MENOR QUE 365 DIAS.\nDESEJA CONTINUAR?" : ""); + } + string str1 = str; + if (str1 != "") + { + flag = await base.ShowMessage(str1, "SIM", "NÃO", false); + } + else + { + flag = true; + } + } + else + { + flag = true; + } + return flag; + } + + private async Task WorkOnSelectedDocumento(Documento value) + { + decimal? nullable; + bool flag; + bool flag1; + bool seguradora; + List list; + decimal? tolerancia; + bool flag2; + bool flag3; + bool valueOrDefault; + string str; + NegocioCorretora negocioCorretora; + Documento documento; + BaseApoliceViewModel baseApoliceViewModel = this; + flag = (value == null ? true : value.get_Id() == (long)0); + baseApoliceViewModel.IsEnabledEdit = flag; + BaseApoliceViewModel baseApoliceViewModel1 = this; + flag1 = (value == null ? true : value.get_Id() == (long)0); + baseApoliceViewModel1.IsEnabledEditEndosso = flag1; + if (value != null && value.get_Id() != 0) + { + if (!this.Situacao.All((TipoSeguro x) => x != value.get_Situacao())) + { + this.IsEnableSituacao = true; + } + else + { + List tipoSeguros = new List() + { + 1, + 2, + 5, + value.get_Situacao() + }; + this.Situacao = new ObservableCollection(tipoSeguros); + } + Controle controle = value.get_Controle(); + if (controle != null) + { + seguradora = controle.get_Seguradora(); + } + else + { + seguradora = false; + } + if (seguradora) + { + list = Recursos.Seguradoras.Where((Seguradora x) => { + if (x.get_Ativo()) + { + return true; + } + return x.get_Id() == value.get_Controle().get_Seguradora().get_Id(); + }).ToList(); + } + else + { + List seguradoras = Recursos.Seguradoras; + list = ( + from x in seguradoras + where x.get_Ativo() + select x).ToList(); + } + this.Seguradoras = list; + this.SeguradorasAnteriores = Recursos.Seguradoras; + this.SelectedDocumento = await this.Servico.BuscarApoliceAsync(value.get_Id(), false, false); + if (!this.SelectedDocumento.get_NegocioCorretora().HasValue) + { + Documento selectedDocumento = this.SelectedDocumento; + negocioCorretora = (this.SelectedDocumento.get_Situacao() != 2 || !this.SelectedDocumento.get_Negocio().HasValue || this.SelectedDocumento.get_Negocio().GetValueOrDefault() != 1 ? 0 : 1); + selectedDocumento.set_NegocioCorretora(new NegocioCorretora?(negocioCorretora)); + base.OnPropertyChanged("SelectedDocumento"); + } + BaseApoliceViewModel valueOrDefault1 = this; + Controle controle1 = this.SelectedDocumento.get_Controle(); + if (controle1 != null) + { + Seguradora seguradora1 = controle1.get_Seguradora(); + if (seguradora1 != null) + { + tolerancia = seguradora1.get_Tolerancia(); + } + else + { + nullable = null; + tolerancia = nullable; + } + } + else + { + nullable = null; + tolerancia = nullable; + } + nullable = tolerancia; + valueOrDefault1.Tolerancia = nullable.GetValueOrDefault(new decimal(2)); + List produtos = Recursos.Produtos.Where((Produto x) => { + if (x.get_Ativo()) + { + return true; + } + if (this.SelectedDocumento.get_Controle().get_Produto() == null) + { + return false; + } + return x.get_Id() == this.SelectedDocumento.get_Controle().get_Produto().get_Id(); + }).ToList(); + this.Produtos = produtos; + if (this.Invoke) + { + ConsultaViewModel.DocumentoSelecionado = this.SelectedDocumento; + } + documento = (Documento)this.SelectedDocumento.Clone(); + await this.CarregarParcelas(documento); + await this.CarregaRepasse(documento.get_Id()); + this.SelectedDocumento.Initialize(); + this.Initialized = true; + if (this.Parcelas.Count == 0) + { + this.AllowEditVendedor = false; + } + BaseApoliceViewModel baseApoliceViewModel2 = this; + ObservableCollection parcelas = this.Parcelas; + IEnumerable subTipo = + from x in parcelas + where x.get_SubTipo() == 1 + select x; + if (!subTipo.All((Parcela x) => !x.get_DataRecebimento().HasValue)) + { + flag2 = false; + } + else + { + List repasses = this.Repasses; + IEnumerable vendedorParcelas = + from x in repasses + where x.get_Parcela().get_SubTipo() == 1 + select x; + flag2 = vendedorParcelas.All((VendedorParcela x) => !x.get_DataPagamento().HasValue); + } + baseApoliceViewModel2.AllowEditApolice = flag2; + BaseApoliceViewModel baseApoliceViewModel3 = this; + if (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 2) + { + flag3 = true; + } + else + { + List repasses1 = this.Repasses; + IEnumerable vendedorParcelas1 = repasses1.Where((VendedorParcela x) => { + if (x.get_Repasse() == null) + { + return false; + } + return x.get_Repasse().get_Base().GetValueOrDefault() == 4; + }); + flag3 = vendedorParcelas1.All((VendedorParcela x) => !x.get_DataPagamento().HasValue); + } + baseApoliceViewModel3.AllowEditEmissao = flag3; + this.CalculaComissao(this.SelectedDocumento, this.Parcelas); + this.IsEndosso = this.SelectedDocumento.get_Tipo() != 0; + BaseApoliceViewModel baseApoliceViewModel4 = this; + if (!this.SelectedDocumento.get_TipoEndosso().HasValue) + { + valueOrDefault = true; + } + else if (this.SelectedDocumento.get_TipoEndosso().GetValueOrDefault() == 2) + { + valueOrDefault = false; + } + else + { + TipoEndosso? tipoEndosso = this.SelectedDocumento.get_TipoEndosso(); + valueOrDefault = tipoEndosso.GetValueOrDefault() != 3; + } + baseApoliceViewModel4.EnableAlterarSituacao = valueOrDefault; + BaseApoliceViewModel baseApoliceViewModel5 = this; + str = (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 2 ? "EDITAR FATURAS" : "EDITAR PARCELAS"); + baseApoliceViewModel5.EditarParcelasLabel = str; + base.AllowEditParcela = true; + this.CancelDocumento = (Documento)this.SelectedDocumento.Clone(); + } + documento = null; + } + + private void WorkOnSelectedParcela(Parcela value) + { + bool? nullable; + string str; + Visibility visibility; + int? nullable1; + bool? nullable2; + if (value == null || value.get_Id() == 0 || this.SelectedDocumento == null) + { + return; + } + bool flag = this.Repasses.Any((VendedorParcela x) => { + if (x.get_Parcela().get_Id() != this.SelectedParcela.get_Id()) + { + return false; + } + return x.get_DataPagamento().HasValue; + }); + if (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 2) + { + List repasses = this.Repasses; + if (repasses != null) + { + nullable2 = new bool?(repasses.Where((VendedorParcela x) => { + if (x.get_Parcela().get_Id() != this.SelectedParcela.get_Id() || x.get_Repasse() == null) + { + return false; + } + return x.get_Repasse().get_Base().GetValueOrDefault() == 4; + }).All((VendedorParcela x) => !x.get_DataPagamento().HasValue)); + } + else + { + nullable = null; + nullable2 = nullable; + } + nullable = nullable2; + this.AllowEditEmissao = nullable.Value; + } + if (value.get_SubTipo() != 1 || this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() != 1) + { + this.BaixarParcelaVisibility = (!value.get_DataRecebimento().HasValue ? Visibility.Visible : Visibility.Collapsed); + this.VisibilityExcluirParcela = (flag ? Visibility.Collapsed : Visibility.Visible); + if (value.get_DataRecebimento().HasValue) + { + str = "EXCLUIR BAIXA"; + } + else + { + str = (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 1 ? "EXCLUIR PARCELA" : "EXCLUIR FATURA"); + } + this.ExcluirParcelaLabel = str; + } + else + { + this.BaixarParcelaVisibility = (this.Parcelas.Any((Parcela x) => { + if (x.get_DataRecebimento().HasValue) + { + return false; + } + return x.get_SubTipo() == 1; + }) ? Visibility.Visible : Visibility.Collapsed); + Parcela parcela = ( + from x in this.Parcelas + orderby x.get_NumeroParcela() + select x).LastOrDefault((Parcela x) => { + if (!x.get_DataRecebimento().HasValue || x.get_SubTipo() != 1) + { + return false; + } + if (x.get_ValorComissao() != decimal.Zero) + { + return true; + } + return x.get_ValorRealizado() != decimal.Zero; + }); + if (flag) + { + visibility = Visibility.Collapsed; + } + else + { + if (!value.get_DataRecebimento().HasValue || parcela != null) + { + if (parcela != null) + { + nullable1 = new int?(parcela.get_NumeroParcela()); + } + else + { + nullable1 = null; + } + int? nullable3 = nullable1; + int numeroParcela = value.get_NumeroParcela(); + if (nullable3.GetValueOrDefault() <= numeroParcela & nullable3.HasValue) + { + goto Label1; + } + visibility = Visibility.Collapsed; + goto Label0; + } + Label1: + visibility = Visibility.Visible; + } + Label0: + this.VisibilityExcluirParcela = visibility; + this.ExcluirParcelaLabel = "EXCLUIR BAIXA"; + } + this.VisibilityReplicarFatura = (this.IsFatura ? Visibility.Visible : Visibility.Collapsed); + } + + private void WorkOnSelectedTipo(bool value) + { + this.Assinada = (value ? "PROPOSTA DE ENDOSSO ASSINADA" : "PROPOSTA ASSINADA"); + this.Conferida = (value ? "ENDOSSO CONFERIDO" : "APÓLICE CONFERIDA"); + this.Transmissao = (value ? "TRANSMISSÃO DA PROPOSTA DE ENDOSSO" : "TRANSMISSÃO DA PROPOSTA"); + this.Emissao = (value ? "EMISSÃO DO ENDOSSO" : "EMISSÃO DA APÓLICE"); + } + + private void ZeraComissao() + { + this.Gerada = decimal.Zero; + this.Recebida = decimal.Zero; + this.Pendente = decimal.Zero; + this.Repasse = decimal.Zero; + this.ComissOriginal = decimal.Zero; + } + + private void ZerarValores() + { + if (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() != 2) + { + return; + } + this.SelectedDocumento.set_PremioLiquido(decimal.Zero); + this.SelectedDocumento.set_PremioAdicional(decimal.Zero); + this.SelectedDocumento.set_PremioAdicional(decimal.Zero); + this.SelectedDocumento.set_Iof(decimal.Zero); + this.SelectedDocumento.set_Diferenca(decimal.Zero); + this.SelectedDocumento.set_NumeroParcelas(decimal.Zero); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/BaseDialogViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/BaseDialogViewModel.cs new file mode 100644 index 0000000..1b8cfbe --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/BaseDialogViewModel.cs @@ -0,0 +1,11 @@ +using System; + +namespace Gestor.Application.ViewModels.Generic +{ + public class BaseDialogViewModel : BaseViewModel + { + public BaseDialogViewModel() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/BaseFinanceiroViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/BaseFinanceiroViewModel.cs new file mode 100644 index 0000000..3e5561d --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/BaseFinanceiroViewModel.cs @@ -0,0 +1,512 @@ +using Gestor.Application.Componentes; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Financeiro; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Financeiro; +using MaterialDesignThemes.Wpf; +using OfxSharpLib; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Forms; +using Xceed.Wpf.AvalonDock.Controls; + +namespace Gestor.Application.ViewModels.Generic +{ + public abstract class BaseFinanceiroViewModel : BaseViewModel + { + public AutoCompleteFilterPredicate BancoItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_140 = BaseFinanceiroViewModel.u003cu003ec.u003cu003e9__14_0; + if (u003cu003e9_140 == null) + { + u003cu003e9_140 = new AutoCompleteFilterPredicate(BaseFinanceiroViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((Banco)obj).get_Nome().ToUpper().Contains(searchText.ToUpper())); + BaseFinanceiroViewModel.u003cu003ec.u003cu003e9__14_0 = u003cu003e9_140; + } + return u003cu003e9_140; + } + } + + public AutoCompleteFilterPredicate BancosContasItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_20 = BaseFinanceiroViewModel.u003cu003ec.u003cu003e9__2_0; + if (u003cu003e9_20 == null) + { + u003cu003e9_20 = new AutoCompleteFilterPredicate(BaseFinanceiroViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((BancosContas)obj).get_Descricao().ToUpper().Contains(searchText.ToUpper())); + BaseFinanceiroViewModel.u003cu003ec.u003cu003e9__2_0 = u003cu003e9_20; + } + return u003cu003e9_20; + } + } + + public AutoCompleteFilterPredicate FornecedorItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_60 = BaseFinanceiroViewModel.u003cu003ec.u003cu003e9__6_0; + if (u003cu003e9_60 == null) + { + u003cu003e9_60 = new AutoCompleteFilterPredicate(BaseFinanceiroViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (((Fornecedor)obj).get_Nome() != null && ((Fornecedor)obj).get_Nome().ToUpper().Contains(searchText.ToUpper()) || ((Fornecedor)obj).get_Documento() != null && ((Fornecedor)obj).get_Documento().ToString().Contains(searchText.ToUpper()) || ((Fornecedor)obj).get_Telefone1() != null && ((Fornecedor)obj).get_Telefone1().ToString().Contains(searchText.ToUpper()) || ((Fornecedor)obj).get_Telefone2() != null && ((Fornecedor)obj).get_Telefone2().ToString().Contains(searchText.ToUpper())) + { + return true; + } + if (((Fornecedor)obj).get_Email() == null) + { + return false; + } + return ((Fornecedor)obj).get_Email().ToString().Contains(searchText.ToUpper()); + }); + BaseFinanceiroViewModel.u003cu003ec.u003cu003e9__6_0 = u003cu003e9_60; + } + return u003cu003e9_60; + } + } + + public AutoCompleteFilterPredicate LancamentoItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_80 = BaseFinanceiroViewModel.u003cu003ec.u003cu003e9__8_0; + if (u003cu003e9_80 == null) + { + u003cu003e9_80 = new AutoCompleteFilterPredicate(BaseFinanceiroViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + bool historico; + bool plano; + bool centro; + bool fornecedor; + if ((((Lancamento)obj).get_Historico() == null || !((Lancamento)obj).get_Historico().ToUpper().Contains(searchText.ToUpper())) && !((Lancamento)obj).get_Vencimento().ToString().ToUpper().Contains(searchText.ToUpper()) && (!((Lancamento)obj).get_Baixa().HasValue || !((Lancamento)obj).get_Baixa().ToString().ToUpper().Contains(searchText.ToUpper())) && (!((Lancamento)obj).get_Pagamento().HasValue || !((Lancamento)obj).get_Pagamento().ToString().ToUpper().Contains(searchText.ToUpper())) && (((Lancamento)obj).get_Conta() == null || !((Lancamento)obj).get_Conta().get_Descricao().ToString().ToUpper().Contains(searchText.ToUpper()))) + { + ControleFinanceiro controle = ((Lancamento)obj).get_Controle(); + if (controle != null) + { + historico = controle.get_Historico(); + } + else + { + historico = false; + } + if (!historico || !((Lancamento)obj).get_Controle().get_Historico().ToString().ToUpper().Contains(searchText.ToUpper())) + { + ControleFinanceiro controleFinanceiro = ((Lancamento)obj).get_Controle(); + if (controleFinanceiro != null) + { + plano = controleFinanceiro.get_Plano(); + } + else + { + plano = false; + } + if (!plano || !((Lancamento)obj).get_Controle().get_Plano().get_Descricao().ToString().ToUpper().Contains(searchText.ToUpper())) + { + ControleFinanceiro controle1 = ((Lancamento)obj).get_Controle(); + if (controle1 != null) + { + centro = controle1.get_Centro(); + } + else + { + centro = false; + } + if (!centro || !((Lancamento)obj).get_Controle().get_Centro().get_Descricao().ToString().ToUpper().Contains(searchText.ToUpper())) + { + ControleFinanceiro controleFinanceiro1 = ((Lancamento)obj).get_Controle(); + if (controleFinanceiro1 != null) + { + fornecedor = controleFinanceiro1.get_Fornecedor(); + } + else + { + fornecedor = false; + } + if (!fornecedor) + { + return false; + } + return ((Lancamento)obj).get_Controle().get_Fornecedor().get_Nome().ToString().ToUpper().Contains(searchText.ToUpper()); + } + } + } + } + return true; + }); + BaseFinanceiroViewModel.u003cu003ec.u003cu003e9__8_0 = u003cu003e9_80; + } + return u003cu003e9_80; + } + } + + public AutoCompleteFilterPredicate PlanoItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_100 = BaseFinanceiroViewModel.u003cu003ec.u003cu003e9__10_0; + if (u003cu003e9_100 == null) + { + u003cu003e9_100 = new AutoCompleteFilterPredicate(BaseFinanceiroViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (((Plano)obj).get_Descricao().ToUpper().Contains(searchText.ToUpper())) + { + return true; + } + return ((Plano)obj).get_Descricao().ToString().Contains(searchText.ToUpper()); + }); + BaseFinanceiroViewModel.u003cu003ec.u003cu003e9__10_0 = u003cu003e9_100; + } + return u003cu003e9_100; + } + } + + public AutoCompleteFilterPredicate PlanosItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_120 = BaseFinanceiroViewModel.u003cu003ec.u003cu003e9__12_0; + if (u003cu003e9_120 == null) + { + u003cu003e9_120 = new AutoCompleteFilterPredicate(BaseFinanceiroViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (((Planos)obj).get_Descricao().ToUpper().Contains(searchText.ToUpper())) + { + return true; + } + return ((Planos)obj).get_Descricao().ToString().Contains(searchText.ToUpper()); + }); + BaseFinanceiroViewModel.u003cu003ec.u003cu003e9__12_0 = u003cu003e9_120; + } + return u003cu003e9_120; + } + } + + protected BaseFinanceiroViewModel() + { + } + + internal async Task> BuscarBancosContas(string value) + { + List bancosContas = await Task.Run>(() => (new BaseServico()).BuscarBancosContas(value)); + return bancosContas; + } + + internal async Task> BuscarFornecedor(string value) + { + List fornecedors = await Task.Run>(() => (new BaseServico()).BuscarFornecedor(value, false)); + return fornecedors; + } + + internal async Task> BuscarFornecedorAtivo(string value) + { + List fornecedors = await Task.Run>(() => (new BaseServico()).BuscarFornecedor(value, true)); + return fornecedors; + } + + private string DetectEncodingAndRead(string arquivo) + { + return File.ReadAllText(arquivo, BaseFinanceiroViewModel.DetectTextFileEncoding(arquivo)); + } + + public static Encoding DetectTextFileEncoding(string filePath) + { + byte[] numArray; + using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) + { + int num = (int)Math.Min(fileStream.Length, (long)4096); + numArray = new byte[num]; + fileStream.Read(numArray, 0, num); + } + if ((int)numArray.Length >= 2) + { + if ((int)numArray.Length >= 3 && numArray[0] == 239 && numArray[1] == 187 && numArray[2] == 191) + { + return Encoding.UTF8; + } + if (numArray[0] == 255 && numArray[1] == 254) + { + return Encoding.Unicode; + } + if (numArray[0] == 254 && numArray[1] == 255) + { + return Encoding.BigEndianUnicode; + } + if ((int)numArray.Length >= 4 && numArray[0] == 255 && numArray[1] == 254 && numArray[2] == 0 && numArray[3] == 0) + { + return Encoding.UTF32; + } + if ((int)numArray.Length >= 4 && numArray[0] == 0 && numArray[1] == 0 && numArray[2] == 254 && numArray[3] == 255) + { + return new UTF32Encoding(true, true); + } + } + bool flag = true; + int num1 = 0; + int num2 = 0; + for (int i = 0; i < (int)numArray.Length; i++) + { + if (numArray[i] <= 127) + { + num2++; + } + else if (numArray[i] >= 194 && numArray[i] <= 223 && i + 1 < (int)numArray.Length && numArray[i + 1] >= 128 && numArray[i + 1] <= 191) + { + num1++; + i++; + } + else if (numArray[i] >= 224 && numArray[i] <= 239 && i + 2 < (int)numArray.Length && numArray[i + 1] >= 128 && numArray[i + 1] <= 191 && numArray[i + 2] >= 128 && numArray[i + 2] <= 191) + { + num1++; + i += 2; + } + else if (numArray[i] < 240 || numArray[i] > 244 || i + 3 >= (int)numArray.Length || numArray[i + 1] < 128 || numArray[i + 1] > 191 || numArray[i + 2] < 128 || numArray[i + 2] > 191 || numArray[i + 3] < 128 || numArray[i + 3] > 191) + { + flag = false; + break; + } + else + { + num1++; + i += 3; + } + } + int num3 = 0; + for (int j = 0; j < (int)numArray.Length - 1; j += 2) + { + if (numArray[j] == 0 || numArray[j + 1] == 0) + { + num3++; + } + } + if (flag && num1 > 0) + { + return Encoding.UTF8; + } + if ((double)num2 > (double)((int)numArray.Length) * 0.95) + { + return Encoding.ASCII; + } + if ((double)num3 <= (double)((int)numArray.Length) * 0.4) + { + return Encoding.GetEncoding(1252); + } + int num4 = 0; + int num5 = 0; + for (int k = 0; k < (int)numArray.Length - 1; k += 2) + { + if (numArray[k] == 0 && numArray[k + 1] != 0) + { + num5++; + } + if (numArray[k] != 0 && numArray[k + 1] == 0) + { + num4++; + } + } + if (num4 > num5) + { + return Encoding.Unicode; + } + return Encoding.BigEndianUnicode; + } + + public async Task ExecuteRunExtendedDialogContas(System.Windows.Controls.UserControl dialogControl, string hostName) + { + BancosContas bancosConta; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + if (!(obj is bool)) + { + bancosConta = (BancosContas)obj; + } + else + { + bancosConta = null; + } + return bancosConta; + } + + public async Task ExecuteRunExtendedDialogTransferencia(System.Windows.Controls.UserControl dialogControl, string hostName) + { + Transferencia transferencium; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + if (!(obj is bool)) + { + transferencium = (Transferencia)obj; + } + else + { + transferencium = null; + } + return transferencium; + } + + public async Task ExecuteRunExtendedDialogVinculo(System.Windows.Controls.UserControl dialogControl, string hostName) + { + Lancamento lancamento; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + if (!(obj is bool)) + { + lancamento = (Lancamento)obj; + } + else + { + lancamento = null; + } + return lancamento; + } + + public Encoding GetEncoding(string filename) + { + byte[] numArray = new byte[4]; + using (FileStream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read)) + { + fileStream.Read(numArray, 0, 4); + } + if (numArray[0] == 43 && numArray[1] == 47 && numArray[2] == 118) + { + return Encoding.UTF7; + } + if (numArray[0] == 239 && numArray[1] == 187 && numArray[2] == 191) + { + return Encoding.UTF8; + } + if (numArray[0] == 255 && numArray[1] == 254 && numArray[2] == 0 && numArray[3] == 0) + { + return Encoding.UTF32; + } + if (numArray[0] == 255 && numArray[1] == 254) + { + return Encoding.Unicode; + } + if (numArray[0] == 254 && numArray[1] == 255) + { + return Encoding.BigEndianUnicode; + } + if (numArray[0] != 0 || numArray[1] != 0 || numArray[2] != 254 || numArray[3] != 255) + { + return Encoding.ASCII; + } + return new UTF32Encoding(true, true); + } + + public async Task> ImportarOfx() + { + List ofxDocuments; + BaseFinanceiroViewModel.u003cu003ec__DisplayClass22_0 variable; + List ofxDocuments1 = new List(); + bool flag = false; + List strs = new List(); + using (OpenFileDialog openFileDialog = new OpenFileDialog()) + { + openFileDialog.Multiselect = true; + openFileDialog.Filter = "Arquivos OFX|*.ofx"; + openFileDialog.InitialDirectory = Environment.SpecialFolder.Desktop.ToString(); + if (DialogResult.OK == openFileDialog.ShowDialog()) + { + strs.AddRange(openFileDialog.FileNames); + } + else + { + ofxDocuments = null; + variable = null; + return ofxDocuments; + } + } + await Task.Run(() => { + OfxDocumentParser ofxDocumentParser = new OfxDocumentParser(); + strs.ForEach((string x) => { + try + { + string str = DateTime.Now.Date.ToString("yyyyMMddHHmmss"); + string str1 = this.DetectEncodingAndRead(x).Replace("00000000", string.Concat("", str)).Replace("00000000000000", string.Concat("", str)).Replace(",", ".").Replace(" ", "."); + if (str1.Contains("336") && !str1.Contains("")) + { + str1 = str1.Replace("UTF - 8", "USASCII").Replace("", "\r\n\r\n0\r\n00000000\r\n").Replace("00000000", string.Concat("", str)).Replace(": ", ":").Replace(" ", "").Replace("", "0"); + } + if (str1.Contains("0403") && !str1.Contains("CHARSET:1252") && str1.Contains("ENCODING:UTF-8")) + { + str1 = str1.Replace("UTF-8", "USASCII\nCHARSET:1252").Replace("00000000", string.Concat("", str)).Replace("[0:GMT]", "").Replace(": ", ":").Replace(" ", ""); + } + if (str1.Contains("260")) + { + str1 = str1.Replace("UTF-8", "USASCII").Replace("CHARSET:NONE", "CHARSET:1252"); + } + if (str1.Contains("")) + { + str1 = str1.Replace("", "SEM INFORMAÇÃO"); + } + if (Regex.IsMatch(str1, "\\s*")) + { + str1 = str1.Replace("\n", "SEM NOME").Replace("", "SEM NOME"); + } + OfxDocument ofxDocument = ofxDocumentParser.Import(str1); + ofxDocuments1.Add(ofxDocument); + } + catch (Exception exception) + { + flag = true; + } + }); + }); + if (flag) + { + await base.ShowMessage("HOUVE PROBLEMAS AO IMPORTAR O OFX, BAIXE-O NOVAMENTE COM UM PERÍODO MENOR.", "OK", "", false); + } + ofxDocuments = ofxDocuments1; + variable = null; + return ofxDocuments; + } + + internal async Task ShowContas(List contas) + { + string str; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + DialogHost dialogHost = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).FirstOrDefault(); + ContasDialog contasDialog = new ContasDialog(contas); + BaseFinanceiroViewModel baseFinanceiroViewModel = this; + ContasDialog contasDialog1 = contasDialog; + str = (dialogHost != null ? dialogHost.get_Identifier().ToString() : "RootDialog"); + return await baseFinanceiroViewModel.ExecuteRunExtendedDialogContas(contasDialog1, str); + } + + internal async Task ShowTransferencia(Transferencia transferencia) + { + string str; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + DialogHost dialogHost = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).FirstOrDefault(); + DialogTransferencia dialogTransferencium = new DialogTransferencia(transferencia); + BaseFinanceiroViewModel baseFinanceiroViewModel = this; + DialogTransferencia dialogTransferencium1 = dialogTransferencium; + str = (dialogHost != null ? dialogHost.get_Identifier().ToString() : "RootDialog"); + return await baseFinanceiroViewModel.ExecuteRunExtendedDialogTransferencia(dialogTransferencium1, str); + } + + internal async Task ShowVinculo(FinanceiroViewModel viewModel) + { + string str; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + DialogHost dialogHost = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).FirstOrDefault(); + VincularLancamentoDialog vincularLancamentoDialog = new VincularLancamentoDialog(viewModel); + BaseFinanceiroViewModel baseFinanceiroViewModel = this; + VincularLancamentoDialog vincularLancamentoDialog1 = vincularLancamentoDialog; + str = (dialogHost != null ? dialogHost.get_Identifier().ToString() : "RootDialog"); + return await baseFinanceiroViewModel.ExecuteRunExtendedDialogVinculo(vincularLancamentoDialog1, str); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/BaseSegurosViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/BaseSegurosViewModel.cs new file mode 100644 index 0000000..8f75310 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/BaseSegurosViewModel.cs @@ -0,0 +1,1238 @@ +using Agger.Registro; +using Gestor.Application.Componentes; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels.Seguros.Itens; +using Gestor.Application.Views.Seguros.Itens; +using Gestor.Model.Common; +using Gestor.Model.Domain.Card; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.MalaDireta; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using MaterialDesignThemes.Wpf; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Globalization; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using Xceed.Wpf.AvalonDock.Controls; + +namespace Gestor.Application.ViewModels.Generic +{ + public class BaseSegurosViewModel : BaseViewModel + { + private string _anotacoes; + + private bool _enableEndossar; + + private bool _enableRenovar; + + public AutoCompleteFilterPredicate AgendaItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_80 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__8_0; + if (u003cu003e9_80 == null) + { + u003cu003e9_80 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((Agenda)obj).get_Nome().ToUpper().Contains(searchText.ToUpper())); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__8_0 = u003cu003e9_80; + } + return u003cu003e9_80; + } + } + + public string Anotacoes + { + get + { + return this._anotacoes; + } + set + { + this._anotacoes = value; + base.OnPropertyChanged("Anotacoes"); + } + } + + public AutoCompleteFilterPredicate AtividadeItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_400 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__40_0; + if (u003cu003e9_400 == null) + { + u003cu003e9_400 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (((Atividade)obj).get_Nome().ToUpper().Contains(searchText.ToUpper())) + { + return true; + } + return ((Atividade)obj).get_Cnac().ToUpper().Contains(searchText.ToUpper()); + }); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__40_0 = u003cu003e9_400; + } + return u003cu003e9_400; + } + } + + public AutoCompleteFilterPredicate BancoItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_380 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__38_0; + if (u003cu003e9_380 == null) + { + u003cu003e9_380 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (((Banco)obj).get_Nome().ToUpper().Contains(searchText.ToUpper())) + { + return true; + } + return ((Banco)obj).get_Codigo().ToString().Contains(searchText.ToUpper()); + }); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__38_0 = u003cu003e9_380; + } + return u003cu003e9_380; + } + } + + public AutoCompleteFilterPredicate ClienteItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_10 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__1_0; + if (u003cu003e9_10 == null) + { + u003cu003e9_10 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (CultureInfo.InvariantCulture.CompareInfo.IndexOf(((Cliente)obj).get_Nome().ToUpper(), searchText.Trim(), CompareOptions.IgnoreNonSpace) > -1 || ((Cliente)obj).get_Documento() != null && ((Cliente)obj).get_Documento().Contains(searchText.Trim()) || ((Cliente)obj).get_Rne() != null && ((Cliente)obj).get_Rne().Contains(searchText.Trim()) || ((Cliente)obj).get_Cei() != null && ((Cliente)obj).get_Cei().Contains(searchText.Trim()) || ((Cliente)obj).get_NomeSocialRg() != null && ((Cliente)obj).get_NomeSocialRg().ToUpper().Contains(searchText.Trim().ToUpper())) + { + return true; + } + if (((Cliente)obj).get_Telefones() == null || ((Cliente)obj).get_Telefones().Count <= 0) + { + return false; + } + return ((Cliente)obj).get_Telefones().Any((ClienteTelefone x) => x.get_Numero().Contains(searchText.Trim())); + }); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__1_0 = u003cu003e9_10; + } + return u003cu003e9_10; + } + } + + public AutoCompleteFilterPredicate CoberturaPadraoItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_580 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__58_0; + if (u003cu003e9_580 == null) + { + u003cu003e9_580 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((CoberturaPadrao)obj).get_Descricao().ToUpper().Contains(searchText.ToUpper())); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__58_0 = u003cu003e9_580; + } + return u003cu003e9_580; + } + } + + public AutoCompleteFilterPredicate ConfigItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_460 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__46_0; + if (u003cu003e9_460 == null) + { + u003cu003e9_460 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((ConfigExtratoImport)obj).get_Descricao().ToUpper().Contains(searchText.ToUpper())); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__46_0 = u003cu003e9_460; + } + return u003cu003e9_460; + } + } + + public AutoCompleteFilterPredicate EmpresaItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_300 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__30_0; + if (u003cu003e9_300 == null) + { + u003cu003e9_300 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (((Empresa)obj).get_Nome().ToUpper().Contains(searchText.ToUpper()) || ((Empresa)obj).get_Documento().ToString().Contains(searchText.ToUpper())) + { + return true; + } + return ((Empresa)obj).get_Serial().ToString().Contains(searchText.ToUpper()); + }); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__30_0 = u003cu003e9_300; + } + return u003cu003e9_300; + } + } + + public bool EnableEndossar + { + get + { + return this._enableEndossar; + } + set + { + this._enableEndossar = value; + base.OnPropertyChanged("EnableEndossar"); + } + } + + public bool EnableRenovar + { + get + { + return this._enableRenovar; + } + set + { + this._enableRenovar = value; + base.OnPropertyChanged("EnableRenovar"); + } + } + + public AutoCompleteFilterPredicate EstipulanteItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_140 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__14_0; + if (u003cu003e9_140 == null) + { + u003cu003e9_140 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (((Estipulante)obj).get_Nome().ToUpper().Contains(searchText.ToUpper())) + { + return true; + } + return ((Estipulante)obj).get_Documento().ToString().Contains(searchText.ToUpper()); + }); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__14_0 = u003cu003e9_140; + } + return u003cu003e9_140; + } + } + + public AutoCompleteFilterPredicate EtiquetaItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_280 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__28_0; + if (u003cu003e9_280 == null) + { + u003cu003e9_280 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((Documento)obj).get_Controle().get_Cliente().get_Nome().ToUpper().Contains(searchText.ToUpper())); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__28_0 = u003cu003e9_280; + } + return u003cu003e9_280; + } + } + + public AutoCompleteFilterPredicate FabricanteItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_420 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__42_0; + if (u003cu003e9_420 == null) + { + u003cu003e9_420 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((Fabricante)obj).get_Descricao().ToUpper().Contains(searchText.ToUpper())); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__42_0 = u003cu003e9_420; + } + return u003cu003e9_420; + } + } + + public AutoCompleteFilterPredicate ItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_540 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__54_0; + if (u003cu003e9_540 == null) + { + u003cu003e9_540 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((Item)obj).get_Descricao().ToUpper().Contains(searchText.ToUpper())); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__54_0 = u003cu003e9_540; + } + return u003cu003e9_540; + } + } + + public AutoCompleteFilterPredicate NomeItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_360 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__36_0; + if (u003cu003e9_360 == null) + { + u003cu003e9_360 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((Credencial)obj).get_Descricao().ToUpper().Contains(searchText.ToUpper())); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__36_0 = u003cu003e9_360; + } + return u003cu003e9_360; + } + } + + public AutoCompleteFilterPredicate NotaFiscalItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_220 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__22_0; + if (u003cu003e9_220 == null) + { + u003cu003e9_220 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((NotaFiscal)obj).get_Seguradora().get_Nome().ToUpper().Contains(searchText.ToUpper())); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__22_0 = u003cu003e9_220; + } + return u003cu003e9_220; + } + } + + public AutoCompleteFilterPredicate ParceiroItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_480 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__48_0; + if (u003cu003e9_480 == null) + { + u003cu003e9_480 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((Parceiro)obj).get_Nome().ToUpper().Contains(searchText.ToUpper())); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__48_0 = u003cu003e9_480; + } + return u003cu003e9_480; + } + } + + public AutoCompleteFilterPredicate ProdutoItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_160 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__16_0; + if (u003cu003e9_160 == null) + { + u003cu003e9_160 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((Produto)obj).get_Nome().ToUpper().Contains(searchText.ToUpper())); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__16_0 = u003cu003e9_160; + } + return u003cu003e9_160; + } + } + + public AutoCompleteFilterPredicate ProfissaoItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_120 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__12_0; + if (u003cu003e9_120 == null) + { + u003cu003e9_120 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (((Profissao)obj).get_Nome().ToUpper().Contains(searchText.ToUpper())) + { + return true; + } + return ((Profissao)obj).get_Codigo().ToUpper().Contains(searchText.ToUpper()); + }); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__12_0 = u003cu003e9_120; + } + return u003cu003e9_120; + } + } + + public AutoCompleteFilterPredicate RamoItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_520 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__52_0; + if (u003cu003e9_520 == null) + { + u003cu003e9_520 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((Ramo)obj).get_Nome().ToUpper().Contains(searchText.ToUpper())); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__52_0 = u003cu003e9_520; + } + return u003cu003e9_520; + } + } + + public AutoCompleteFilterPredicate ReciboItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_260 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__26_0; + if (u003cu003e9_260 == null) + { + u003cu003e9_260 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (((Recibo)obj).get_Pagante().ToUpper().Contains(searchText.ToUpper())) + { + return true; + } + return ((Recibo)obj).get_Recebedor().ToUpper().Contains(searchText.ToUpper()); + }); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__26_0 = u003cu003e9_260; + } + return u003cu003e9_260; + } + } + + public AutoCompleteFilterPredicate SeguradoraItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_440 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__44_0; + if (u003cu003e9_440 == null) + { + u003cu003e9_440 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (((Seguradora)obj).get_Nome().ToUpper().Contains(searchText.ToUpper()) || ((Seguradora)obj).get_Documento() != null && ((Seguradora)obj).get_Documento().ToUpper().Contains(searchText.ToUpper())) + { + return true; + } + if (((Seguradora)obj).get_Susep() == null) + { + return false; + } + return ((Seguradora)obj).get_Susep().ToUpper().Contains(searchText.ToUpper()); + }); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__44_0 = u003cu003e9_440; + } + return u003cu003e9_440; + } + } + + public AutoCompleteFilterPredicate SinitroItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_560 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__56_0; + if (u003cu003e9_560 == null) + { + u003cu003e9_560 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (((ControleSinistro)obj).get_DataSinistro().ToString().Contains(searchText)) + { + return true; + } + if (((ControleSinistro)obj).get_Sinistros() == null || ((ControleSinistro)obj).get_Sinistros().Count <= 0) + { + return false; + } + return ((ControleSinistro)obj).get_Sinistros()[0].get_Numero().ToUpper().Contains(searchText.ToUpper()); + }); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__56_0 = u003cu003e9_560; + } + return u003cu003e9_560; + } + } + + public AutoCompleteFilterPredicate SocioItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_320 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__32_0; + if (u003cu003e9_320 == null) + { + u003cu003e9_320 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (((Socio)obj).get_Nome().ToUpper().Contains(searchText.ToUpper()) || ((Socio)obj).get_Email().ToString().Contains(searchText.ToUpper())) + { + return true; + } + return ((Socio)obj).get_Telefone().ToString().Contains(searchText.ToUpper()); + }); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__32_0 = u003cu003e9_320; + } + return u003cu003e9_320; + } + } + + public AutoCompleteFilterPredicate StatusItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_240 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__24_0; + if (u003cu003e9_240 == null) + { + u003cu003e9_240 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((Status)obj).get_Nome().ToUpper().Contains(searchText.ToUpper())); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__24_0 = u003cu003e9_240; + } + return u003cu003e9_240; + } + } + + public AutoCompleteFilterPredicate StatusProspeccaoItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_200 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__20_0; + if (u003cu003e9_200 == null) + { + u003cu003e9_200 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((StatusDeProspeccao)obj).get_Nome().ToUpper().Contains(searchText.ToUpper())); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__20_0 = u003cu003e9_200; + } + return u003cu003e9_200; + } + } + + public AutoCompleteFilterPredicate TipoTarefaItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_180 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__18_0; + if (u003cu003e9_180 == null) + { + u003cu003e9_180 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((TipoDeTarefa)obj).get_Nome().ToUpper().Contains(searchText.ToUpper())); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__18_0 = u003cu003e9_180; + } + return u003cu003e9_180; + } + } + + public AutoCompleteFilterPredicate TipoVendedorItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_500 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__50_0; + if (u003cu003e9_500 == null) + { + u003cu003e9_500 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((TipoVendedor)obj).get_Descricao().ToUpper().Contains(searchText.ToUpper())); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__50_0 = u003cu003e9_500; + } + return u003cu003e9_500; + } + } + + public AutoCompleteFilterPredicate UsuarioItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_340 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__34_0; + if (u003cu003e9_340 == null) + { + u003cu003e9_340 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (((Usuario)obj).get_Nome().ToUpper().Contains(searchText.ToUpper())) + { + return true; + } + return ((Usuario)obj).get_Documento().ToString().Contains(searchText.ToUpper()); + }); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__34_0 = u003cu003e9_340; + } + return u003cu003e9_340; + } + } + + public AutoCompleteFilterPredicate VendedorItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_100 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__10_0; + if (u003cu003e9_100 == null) + { + u003cu003e9_100 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (((Vendedor)obj).get_Nome().ToUpper().Contains(searchText.ToUpper())) + { + return true; + } + if (((Vendedor)obj).get_Documento() == null) + { + return false; + } + return ((Vendedor)obj).get_Documento().ToUpper().Contains(searchText.ToUpper()); + }); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__10_0 = u003cu003e9_100; + } + return u003cu003e9_100; + } + } + + public BaseSegurosViewModel() + { + } + + internal async Task> BuscaFabricante(string value) + { + List fabricantes = await Task.Run>(() => (new BaseServico()).BuscarFabricante(value)); + return fabricantes; + } + + internal async Task> BuscarAtividade(string value) + { + List atividades = await Task.Run>(() => (new BaseServico()).BuscarAtividade(value)); + return atividades; + } + + internal async Task> BuscarCliente(string value, List vinculos = null, TipoFiltroCliente tipoFiltroCliente = 2) + { + return await (new ClienteServico()).BuscarCliente(value, vinculos, tipoFiltroCliente); + } + + internal async Task> BuscarClienteEmpresa(string value) + { + List clientes = await Task.Run>(() => (new BaseServico()).BuscarClienteEmpresa(value)); + return clientes; + } + + internal async Task> BuscarClienteVinculo(string value, long id) + { + List clientes = await Task.Run>(() => (new ClienteServico()).BuscarClienteVinculo(value, id)); + return clientes; + } + + internal async Task> BuscarProfissao(string value) + { + List profissaos = await Task.Run>(() => (new BaseServico()).BuscarProfissao(value)); + return profissaos; + } + + internal async Task> BuscarUsuario(string value) + { + List usuarios = await Task.Run>(() => (new BaseServico()).BuscarUsuario(value)); + return usuarios; + } + + public async Task CarregaApolice(long id) + { + return await (new ApoliceServico()).BuscarApoliceAsync(id, false, false); + } + + public async Task CarregaApoliceParcela(long id) + { + return await (new ParcelaServico()).BuscarApolice(id); + } + + public async Task CarregaCliente(long id) + { + return await (new ClienteServico()).BuscarClienteAsync(id); + } + + public async Task CarregaParcela(long id) + { + return await (new ParcelaServico()).BuscarParcela(id); + } + + public async Task> CarregarItem(long id, StatusItem status = 2) + { + List list = await (new ItemServico()).BuscarItens(id, status).ToList(); + return list; + } + + public async Task CarregarProspeccao(long id) + { + return await (new ProspeccaoServico()).BuscarProspeccao(id); + } + + public async Task CarregaSinistroApolice(long id) + { + return await (new SinistroServico()).BuscarSinistro(id); + } + + public async Task CreateCardLogo(Empresa empresa, string id = null) + { + string str; + string str1; + string str2; + if (empresa != null) + { + Logo logo = new Logo(); + logo.set_CustomId(ApplicationHelper.NumeroSerial); + logo.set_Data(empresa.get_Logo()); + str2 = (!string.IsNullOrEmpty(empresa.get_NomeSocial()) ? empresa.get_NomeSocial() : empresa.get_Nome()); + logo.set_Corretora(str2); + logo.set_Whatsapp(empresa.get_Whatsapp()); + logo.set_WhatsappSinistro(empresa.get_WhatsappSinistro()); + Logo logo1 = logo; + str1 = (!string.IsNullOrWhiteSpace(id) ? await Funcoes.Atualizarlogo(logo1, id) : await Funcoes.Criarlogo(logo1)); + id = str1; + str = id; + } + else + { + str = ""; + } + return str; + } + + public async Task CreateLinkAssistencia(Documento documento, string item, bool retorno = true) + { + string str; + str = (documento != null ? string.Format("{0}{1}", Address.get_Assistance(), documento.get_Id().GeraAssistencia()) : ""); + return str; + } + + public async Task CreateSeguradora(Seguradora seguradora, string id = null) + { + string str; + string str1; + if (seguradora != null) + { + int num = 1; + AssistenciaCia assistenciaCium = new AssistenciaCia(); + assistenciaCium.set_Seguradora(seguradora.get_Nome()); + assistenciaCium.set_IdSeguradora(seguradora.get_Id()); + assistenciaCium.set_LinkAppAndroid(seguradora.get_LinkAppAndroid()); + assistenciaCium.set_LinkAppIos(seguradora.get_LinkAppIos()); + assistenciaCium.set_CustomId(ApplicationHelper.NumeroSerial); + AssistenciaCia assistenciaCium1 = assistenciaCium; + List contatos = seguradora.get_Contatos(); + ( + from x in contatos + orderby x.get_Tipo().GetValueOrDefault(7).GetType() + select x).ToList().ForEach((SeguradoraContato x) => { + switch (num) + { + case 2: + { + assistenciaCium1.set_Assistencia2Tipo((!x.get_Tipo().HasValue ? 10 : x.get_Tipo().Value)); + assistenciaCium1.set_Assistencia2((!x.get_Tipo().HasValue || x.get_Tipo().GetValueOrDefault() != 10 ? (x.get_Tipo().GetValueOrDefault() == 11 ? string.Concat("0300-", x.get_Numero()) : (x.get_Tipo().GetValueOrDefault() != 7 || !string.IsNullOrEmpty(x.get_Prefixo()) ? string.Concat("(", x.get_Prefixo(), ") ", x.get_Numero()) : x.get_Numero())) : string.Concat("0800-", x.get_Numero()))); + assistenciaCium1.set_Assistencia2Obs(x.get_NomeContato()); + break; + } + case 3: + { + assistenciaCium1.set_Assistencia3Tipo((!x.get_Tipo().HasValue ? 10 : x.get_Tipo().Value)); + assistenciaCium1.set_Assistencia3((!x.get_Tipo().HasValue || x.get_Tipo().GetValueOrDefault() != 10 ? (x.get_Tipo().GetValueOrDefault() == 11 ? string.Concat("0300-", x.get_Numero()) : (x.get_Tipo().GetValueOrDefault() != 7 || !string.IsNullOrEmpty(x.get_Prefixo()) ? string.Concat("(", x.get_Prefixo(), ") ", x.get_Numero()) : x.get_Numero())) : string.Concat("0800-", x.get_Numero()))); + assistenciaCium1.set_Assistencia3Obs(x.get_NomeContato()); + break; + } + case 4: + { + assistenciaCium1.set_Assistencia4Tipo((!x.get_Tipo().HasValue ? 10 : x.get_Tipo().Value)); + assistenciaCium1.set_Assistencia4((!x.get_Tipo().HasValue || x.get_Tipo().GetValueOrDefault() != 10 ? (x.get_Tipo().GetValueOrDefault() == 11 ? string.Concat("0300-", x.get_Numero()) : (x.get_Tipo().GetValueOrDefault() != 7 || !string.IsNullOrEmpty(x.get_Prefixo()) ? string.Concat("(", x.get_Prefixo(), ") ", x.get_Numero()) : x.get_Numero())) : string.Concat("0800-", x.get_Numero()))); + assistenciaCium1.set_Assistencia4Obs(x.get_NomeContato()); + break; + } + default: + { + assistenciaCium1.set_Assistencia1Tipo((!x.get_Tipo().HasValue ? 10 : x.get_Tipo().Value)); + assistenciaCium1.set_Assistencia1((!x.get_Tipo().HasValue || x.get_Tipo().GetValueOrDefault() != 10 ? (x.get_Tipo().GetValueOrDefault() == 11 ? string.Concat("0300-", x.get_Numero()) : (x.get_Tipo().GetValueOrDefault() != 7 || !string.IsNullOrEmpty(x.get_Prefixo()) ? string.Concat("(", x.get_Prefixo(), ") ", x.get_Numero()) : x.get_Numero())) : string.Concat("0800-", x.get_Numero()))); + assistenciaCium1.set_Assistencia1Obs(x.get_NomeContato()); + break; + } + } + num++; + }); + str1 = (!string.IsNullOrWhiteSpace(id) ? await Funcoes.AtualizarSeguradora(assistenciaCium1, id) : await Funcoes.CriarSeguradora(assistenciaCium1)); + id = str1; + str = id; + } + else + { + str = ""; + } + return str; + } + + public async Task ExecuteRunExtendedDialogBuscaModelo(UserControl dialogControl, string hostName) + { + Fipe fipe; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + if (!(obj is bool)) + { + fipe = (Fipe)obj; + } + else + { + fipe = null; + } + return fipe; + } + + public async Task, Usuario, List, List, List>> ExecuteRunExtendedDialogCopiarPermiss(UserControl dialogControl, string hostName) + { + Tuple, Usuario, List, List, List> tuple; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + if (!(obj is bool)) + { + tuple = (Tuple, Usuario, List, List, List>)obj; + } + else + { + tuple = null; + } + return tuple; + } + + public async Task ExecuteRunExtendedDialogDetalheExtrato(UserControl dialogControl, string hostName) + { + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + } + + public async Task ExecuteRunExtendedDialogEditarParcelas(UserControl dialogControl, string hostName) + { + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + } + + public async Task ExecuteRunExtendedDialogEnviarEmails(UserControl dialogControl, string hostName) + { + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + } + + public async Task> ExecuteRunExtendedDialogExportarPermiss(UserControl dialogControl, string hostName) + { + List usuarios; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + if (!(obj is bool)) + { + usuarios = (List)obj; + } + else + { + usuarios = null; + } + return usuarios; + } + + public async Task ExecuteRunExtendedDialogLogAcesso(UserControl dialogControl, string hostName) + { + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + } + + public async Task ExecuteRunExtendedDialogObservacao(UserControl dialogControl, string hostName) + { + string str; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + if (!(obj is bool)) + { + str = (string)obj; + } + else + { + str = null; + } + return str; + } + + public async Task ExecuteRunExtendedDialogPesquisaAvancada(UserControl dialogControl, string hostName) + { + PesquisaAvancada pesquisaAvancada; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + if (!(obj is bool)) + { + pesquisaAvancada = (PesquisaAvancada)obj; + } + else + { + pesquisaAvancada = null; + } + return pesquisaAvancada; + } + + public async Task> ExecuteRunExtendedDialogProtocolo(UserControl dialogControl, string hostName) + { + List list; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List webEditors = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + webEditors.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + if (obj == null || obj is bool) + { + list = null; + } + else + { + list = ((ObservableCollection)obj).ToList(); + } + return list; + } + + public async Task> ExecuteRunExtendedDialogReordenarItens(UserControl dialogControl, string hostName) + { + ObservableCollection observableCollection; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + if (obj == null || obj is bool) + { + observableCollection = null; + } + else + { + observableCollection = (ObservableCollection)obj; + } + return observableCollection; + } + + public async Task> ExecuteRunExtendedDialogSelecionarItens(UserControl dialogControl, string hostName) + { + ObservableCollection observableCollection; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + if (!(obj is bool)) + { + observableCollection = (ObservableCollection)obj; + } + else + { + observableCollection = null; + } + return observableCollection; + } + + public async Task ExecuteRunExtendedDialogTarefa(UserControl dialogControl, string hostName) + { + Tarefa tarefa; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + if (!(obj is bool)) + { + tarefa = (Tarefa)obj; + } + else + { + tarefa = null; + } + return tarefa; + } + + public async Task ExecuteRunExtendedDialogVinculo(UserControl dialogControl, string hostName) + { + VinculoRepasse vinculoRepasse; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + if (!(obj is bool)) + { + vinculoRepasse = (VinculoRepasse)obj; + } + else + { + vinculoRepasse = null; + } + return vinculoRepasse; + } + + public List FilterCliente(List clientes, string searchText) + { + return clientes.Where((Cliente x) => { + if (x.get_Nome().ToUpper().Contains(searchText.ToUpper()) || x.get_Documento() != null && x.get_Documento().Contains(searchText) || x.get_Rne() != null && x.get_Rne().Contains(searchText)) + { + return true; + } + if (x.get_Cei() == null) + { + return false; + } + return x.get_Cei().Contains(searchText); + }).ToList(); + } + + internal async Task ShowBuscaModeloDialog(string modelo, string ano) + { + Fipe fipe; + string str; + DialogHost host = base.GetHost(); + if (host == null || !host.get_IsOpen()) + { + BuscarModeloView buscarModeloView = new BuscarModeloView(new BuscarModeloViewModel(modelo, ano)); + BaseSegurosViewModel baseSegurosViewModel = this; + BuscarModeloView buscarModeloView1 = buscarModeloView; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + fipe = await baseSegurosViewModel.ExecuteRunExtendedDialogBuscaModelo(buscarModeloView1, str); + } + else + { + fipe = null; + } + return fipe; + } + + internal async Task, Usuario, List, List, List>> ShowCopiarPermissaoDialog() + { + Tuple, Usuario, List, List, List> tuple; + string str; + DialogHost host = base.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogCopiarPermissao dialogCopiarPermissao = new DialogCopiarPermissao(new DialogCopiarPermissaoViewModel()); + BaseSegurosViewModel baseSegurosViewModel = this; + DialogCopiarPermissao dialogCopiarPermissao1 = dialogCopiarPermissao; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + tuple = await baseSegurosViewModel.ExecuteRunExtendedDialogCopiarPermiss(dialogCopiarPermissao1, str); + } + else + { + tuple = null; + } + return tuple; + } + + internal async Task ShowDetalheExtrato(List detalhes) + { + string str; + DialogHost host = base.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogDetalheExtrato dialogDetalheExtrato = new DialogDetalheExtrato(detalhes); + BaseSegurosViewModel baseSegurosViewModel = this; + DialogDetalheExtrato dialogDetalheExtrato1 = dialogDetalheExtrato; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + await baseSegurosViewModel.ExecuteRunExtendedDialogDetalheExtrato(dialogDetalheExtrato1, str); + } + } + + internal async Task ShowEditarParcelasDialog(Documento documento) + { + string str; + DialogHost host = base.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogEditarParcelas dialogEditarParcela = new DialogEditarParcelas(documento); + BaseSegurosViewModel baseSegurosViewModel = this; + DialogEditarParcelas dialogEditarParcela1 = dialogEditarParcela; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + await baseSegurosViewModel.ExecuteRunExtendedDialogEditarParcelas(dialogEditarParcela1, str); + } + } + + internal async Task ShowEnviarEmailsDialog(List lista, bool assinatura, bool original, List arquivosAnexados, string assunto, string corpo, Credencial credencial, FiltroArquivoDigital filtro, bool salvarAd, bool confirmarLeitura) + { + string str; + DialogHost host = base.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogEnviarEmails dialogEnviarEmail = new DialogEnviarEmails(new DialogEnviarEmailsViewModel(lista, assinatura, original, arquivosAnexados, assunto, corpo, credencial, filtro, salvarAd, confirmarLeitura)); + BaseSegurosViewModel baseSegurosViewModel = this; + DialogEnviarEmails dialogEnviarEmail1 = dialogEnviarEmail; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + await baseSegurosViewModel.ExecuteRunExtendedDialogEnviarEmails(dialogEnviarEmail1, str); + } + } + + internal async Task> ShowExportarPermissaoDialog(long idUsuario) + { + List usuarios; + string str; + DialogHost host = base.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogExportarPermissao dialogExportarPermissao = new DialogExportarPermissao(new DialogExportarPermissaoViewModel(idUsuario)); + BaseSegurosViewModel baseSegurosViewModel = this; + DialogExportarPermissao dialogExportarPermissao1 = dialogExportarPermissao; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + usuarios = await baseSegurosViewModel.ExecuteRunExtendedDialogExportarPermiss(dialogExportarPermissao1, str); + } + else + { + usuarios = null; + } + return usuarios; + } + + internal async Task ShowLogAcessoDialog(TipoTela tela, Usuario usuario) + { + string str; + DialogHost host = base.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogLogAcesso dialogLogAcesso = new DialogLogAcesso(tela, usuario); + BaseSegurosViewModel baseSegurosViewModel = this; + DialogLogAcesso dialogLogAcesso1 = dialogLogAcesso; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + await baseSegurosViewModel.ExecuteRunExtendedDialogEnviarEmails(dialogLogAcesso1, str); + } + } + + internal async Task ShowObservacaoDialog() + { + string str; + string str1; + DialogHost host = base.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogObservacao dialogObservacao = new DialogObservacao(); + BaseSegurosViewModel baseSegurosViewModel = this; + DialogObservacao dialogObservacao1 = dialogObservacao; + str1 = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + str = await baseSegurosViewModel.ExecuteRunExtendedDialogObservacao(dialogObservacao1, str1); + } + else + { + str = null; + } + return str; + } + + internal async Task ShowPesquisaAvancadaDialog() + { + PesquisaAvancada pesquisaAvancada; + string str; + DialogHost host = base.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogPesquisaAvancadaViewModel dialogPesquisaAvancadaViewModel = new DialogPesquisaAvancadaViewModel(); + DialogPesquisaAvancada dialogPesquisaAvancada = new DialogPesquisaAvancada(dialogPesquisaAvancadaViewModel) + { + DataContext = dialogPesquisaAvancadaViewModel + }; + BaseSegurosViewModel baseSegurosViewModel = this; + DialogPesquisaAvancada dialogPesquisaAvancada1 = dialogPesquisaAvancada; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + pesquisaAvancada = await baseSegurosViewModel.ExecuteRunExtendedDialogPesquisaAvancada(dialogPesquisaAvancada1, str); + } + else + { + pesquisaAvancada = null; + } + return pesquisaAvancada; + } + + internal async Task> ShowProtocoloDialog(List itens) + { + List documentos; + string str; + DialogHost host = base.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogProtocolo dialogProtocolo = new DialogProtocolo(itens); + BaseSegurosViewModel baseSegurosViewModel = this; + DialogProtocolo dialogProtocolo1 = dialogProtocolo; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + documentos = await baseSegurosViewModel.ExecuteRunExtendedDialogProtocolo(dialogProtocolo1, str); + } + else + { + documentos = null; + } + return documentos; + } + + internal async Task> ShowReordenarItensDialog(List ids) + { + ObservableCollection observableCollection; + string str; + DialogHost host = base.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogReordenarItens dialogReordenarIten = new DialogReordenarItens(ids); + BaseSegurosViewModel baseSegurosViewModel = this; + DialogReordenarItens dialogReordenarIten1 = dialogReordenarIten; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + observableCollection = await baseSegurosViewModel.ExecuteRunExtendedDialogReordenarItens(dialogReordenarIten1, str); + } + else + { + observableCollection = null; + } + return observableCollection; + } + + internal async Task> ShowSelecionarItensDialog(long id) + { + ObservableCollection observableCollection; + string str; + DialogHost host = base.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogSelecionarItens dialogSelecionarIten = new DialogSelecionarItens(id); + BaseSegurosViewModel baseSegurosViewModel = this; + DialogSelecionarItens dialogSelecionarIten1 = dialogSelecionarIten; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + observableCollection = await baseSegurosViewModel.ExecuteRunExtendedDialogSelecionarItens(dialogSelecionarIten1, str); + } + else + { + observableCollection = null; + } + return observableCollection; + } + + internal async Task ShowTarefaDialog(Tarefa tarefa, bool nota = false, bool agendamento = false) + { + Tarefa tarefa1; + bool idCliente; + string str; + DialogHost host = base.GetHost(); + if (host == null || !host.get_IsOpen()) + { + List telefoneBases = new List(); + Tarefa tarefa2 = tarefa; + if (tarefa2 != null) + { + idCliente = tarefa2.get_IdCliente() > (long)0; + } + else + { + idCliente = false; + } + if (idCliente) + { + ObservableCollection observableCollection = await (new ClienteServico()).BuscarTelefonesAsync(tarefa.get_IdCliente()); + IEnumerable clienteTelefones = + from x in observableCollection + where ValidationHelper.ValidacaoTelefone(x.get_Numero()) + select x; + telefoneBases = clienteTelefones.Select((ClienteTelefone x) => { + TelefoneBase telefoneBase = new TelefoneBase(); + telefoneBase.set_Tipo(x.get_Tipo()); + telefoneBase.set_Id(x.get_Id()); + telefoneBase.set_Numero(x.get_Numero()); + telefoneBase.set_Prefixo(x.get_Prefixo()); + return telefoneBase; + }).ToList(); + } + DialogTarefa dialogTarefa = new DialogTarefa(tarefa, telefoneBases, nota, agendamento); + BaseSegurosViewModel baseSegurosViewModel = this; + DialogTarefa dialogTarefa1 = dialogTarefa; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + tarefa1 = await baseSegurosViewModel.ExecuteRunExtendedDialogTarefa(dialogTarefa1, str); + } + else + { + tarefa1 = null; + } + host = null; + return tarefa1; + } + + internal async Task ShowVinculoDialog(VinculoRepasse vinculo, List repasses, Repasse repasse) + { + VinculoRepasse vinculoRepasse; + string str; + DialogHost host = base.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogVinculo dialogVinculo = new DialogVinculo(vinculo, repasses, repasse); + BaseSegurosViewModel baseSegurosViewModel = this; + DialogVinculo dialogVinculo1 = dialogVinculo; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + vinculoRepasse = await baseSegurosViewModel.ExecuteRunExtendedDialogVinculo(dialogVinculo1, str); + } + else + { + vinculoRepasse = null; + } + return vinculoRepasse; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/BaseTarefaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/BaseTarefaViewModel.cs new file mode 100644 index 0000000..ad8c5a5 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/BaseTarefaViewModel.cs @@ -0,0 +1,233 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Generic +{ + public abstract class BaseTarefaViewModel : BaseSegurosViewModel + { + private ObservableCollection _responsaveis = new ObservableCollection(); + + private bool _hasResponsaveis; + + public abstract bool EnableAlterarTarefa + { + get; + set; + } + + public bool HasResponsaveis + { + get + { + return this._hasResponsaveis; + } + set + { + this._hasResponsaveis = value; + base.OnPropertyChanged("HasResponsaveis"); + } + } + + public ObservableCollection Responsaveis + { + get + { + return this._responsaveis; + } + set + { + this._responsaveis = value; + this.HasResponsaveis = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("Responsaveis"); + } + } + + public abstract Tarefa SelectedTarefa + { + get; + set; + } + + public TarefaServico Servico + { + get; + set; + } + + protected BaseTarefaViewModel() + { + } + + internal async Task BuscaPermisaoUsuario() + { + return await (new PermissaoUsuarioServico()).VerificarPermissao(Recursos.Usuario, 38); + } + + public void ListaUsuariosResponsaveis() + { + bool usuario; + Tarefa selectedTarefa = this.SelectedTarefa; + if (selectedTarefa != null) + { + usuario = selectedTarefa.get_Usuario(); + } + else + { + usuario = false; + } + if (!usuario) + { + return; + } + if (!this.Responsaveis.Any((ResponsavelTarefa r) => r.get_Usuario().get_Id() == this.SelectedTarefa.get_Usuario().get_Id())) + { + ObservableCollection responsaveis = this.Responsaveis; + ResponsavelTarefa responsavelTarefa = new ResponsavelTarefa(); + responsavelTarefa.set_IdTarefa(this.SelectedTarefa.get_Id()); + responsavelTarefa.set_Usuario(this.SelectedTarefa.get_Usuario()); + responsaveis.Insert(0, responsavelTarefa); + } + } + + public async Task ValidaPermissaoParaEditarTarefa() + { + bool flag; + bool flag1; + bool flag2; + bool id; + bool flag3; + bool flag4 = false; + if (this.SelectedTarefa != null) + { + PermissaoUsuario permissaoUsuario = await this.BuscaPermisaoUsuario(); + if (Recursos.Usuario.get_Administrador()) + { + flag4 = true; + } + else if (permissaoUsuario == null && !this.SelectedTarefa.get_Restrito().GetValueOrDefault()) + { + flag4 = true; + } + else if (permissaoUsuario != null && !permissaoUsuario.get_Alterar()) + { + flag4 = false; + } + else if (!this.SelectedTarefa.get_Restrito().GetValueOrDefault()) + { + flag4 = true; + } + else + { + if (this.SelectedTarefa.get_UsuarioCadastro().get_Id() != Recursos.Usuario.get_Id()) + { + List responsaveis = this.SelectedTarefa.get_Responsaveis(); + if (responsaveis != null) + { + flag3 = responsaveis.Any((ResponsavelTarefa x) => x.get_Usuario().get_Id() == Recursos.Usuario.get_Id()); + } + else + { + flag3 = false; + } + if (flag3) + { + goto Label1; + } + id = this.SelectedTarefa.get_Usuario().get_Id() == Recursos.Usuario.get_Id(); + goto Label0; + } + Label1: + id = true; + Label0: + flag4 = id; + } + bool flag5 = flag4; + bool flag6 = flag5; + this.EnableAlterarTarefa = flag5; + bool flag7 = flag6; + flag2 = flag7; + base.EnableExcluir = flag7; + bool flag8 = flag2; + flag1 = flag8; + base.EnableAlterar = flag8; + flag = flag1; + } + else + { + bool flag9 = flag4; + flag2 = flag9; + this.EnableAlterarTarefa = flag9; + bool flag10 = flag2; + flag1 = flag10; + base.EnableExcluir = flag10; + base.EnableAlterar = flag1; + flag = flag4; + } + return flag; + } + + public async Task ValidaPermissaoParaExcluirTarefa(Tarefa tarefa = null) + { + bool id; + bool flag; + if (tarefa != null) + { + this.SelectedTarefa = tarefa; + } + PermissaoUsuario permissaoUsuario = await this.BuscaPermisaoUsuario(); + bool flag1 = false; + if (Recursos.Usuario.get_Administrador()) + { + flag1 = true; + } + else if (permissaoUsuario == null && !this.SelectedTarefa.get_Restrito().GetValueOrDefault()) + { + flag1 = true; + } + else if (permissaoUsuario != null && !permissaoUsuario.get_Excluir()) + { + flag1 = false; + } + else if (!this.SelectedTarefa.get_Restrito().GetValueOrDefault()) + { + flag1 = true; + } + else + { + if (this.SelectedTarefa.get_UsuarioCadastro().get_Id() != Recursos.Usuario.get_Id()) + { + List responsaveis = this.SelectedTarefa.get_Responsaveis(); + if (responsaveis != null) + { + flag = responsaveis.Any((ResponsavelTarefa x) => x.get_Usuario().get_Id() == Recursos.Usuario.get_Id()); + } + else + { + flag = false; + } + if (flag) + { + goto Label1; + } + id = this.SelectedTarefa.get_Usuario().get_Id() == Recursos.Usuario.get_Id(); + goto Label0; + } + Label1: + id = true; + Label0: + flag1 = id; + } + return flag1; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/BaseViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/BaseViewModel.cs new file mode 100644 index 0000000..e680922 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/BaseViewModel.cs @@ -0,0 +1,3140 @@ +using Agger.Registro; +using Gestor.Application; +using Gestor.Application.Actions; +using Gestor.Application.Componentes; +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Model; +using Gestor.Application.Properties; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Common.Helpers; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Aggilizador; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.MalaDireta; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.License; +using MaterialDesignThemes.Wpf; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Forms; +using System.Windows.Input; +using System.Windows.Threading; +using Xceed.Wpf.AvalonDock.Controls; + +namespace Gestor.Application.ViewModels.Generic +{ + public abstract class BaseViewModel : INotifyPropertyChanged + { + public Gestor.Application.Servicos.ArquivoDigitalServico ArquivoDigitalServico; + + public PermissaoArquivoDigitalServico ServicoPermissArquivoDigital; + + public PermissaoUsuarioServico ServicoPermissUsuario; + + public RestricaoUsuarioServico ServicoRestriUsuario; + + public VendedorUsuarioServico ServicoVendedorUsuario; + + public bool _incluirPermissEnabled; + + public bool _alterarPermissEnabled; + + public bool _excluirPermissEnabled; + + public long LastAccessId; + + public TipoTela LastAccessTela; + + private bool _enableButtons = true; + + private bool _enableIncluir = true; + + private bool _isVisibleEmpresa; + + private bool _enableAlterar; + + private bool _enableExcluir; + + private long? _lastId; + + private bool _incluirParcelaEnabled; + + private bool _alterarParcelaEnabled; + + private bool _excluirParcelaEnabled; + + private bool _permissaoWhatsapp; + + public bool Initialized; + + private bool _enableFields; + + private bool _allowEditParcela; + + private bool _isEnableEdit; + + private bool _isEnabledEditEndosso; + + private bool _enableMenu; + + private bool _enableMainMenu; + + private bool _isEnabled; + + private Visibility _isVisible; + + private object _popupContent; + + public bool AllowEditParcela + { + get + { + return this._allowEditParcela; + } + set + { + this._allowEditParcela = value; + this.OnPropertyChanged("AllowEditParcela"); + } + } + + public bool AlterarParcelaEnabled + { + get + { + return this._alterarParcelaEnabled; + } + set + { + this._alterarParcelaEnabled = value; + this.OnPropertyChanged("AlterarParcelaEnabled"); + } + } + + public AutoCompleteFilterPredicate CoberturaItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_1610 = BaseViewModel.u003cu003ec.u003cu003e9__161_0; + if (u003cu003e9_1610 == null) + { + u003cu003e9_1610 = new AutoCompleteFilterPredicate(BaseViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((CoberturaPadrao)obj).get_Descricao().ToUpper().Contains(searchText.ToUpper())); + BaseViewModel.u003cu003ec.u003cu003e9__161_0 = u003cu003e9_1610; + } + return u003cu003e9_1610; + } + } + + public bool EnableAlterar + { + get + { + return this._enableAlterar; + } + set + { + this._enableAlterar = this._alterarPermissEnabled & value; + this.OnPropertyChanged("EnableAlterar"); + } + } + + public bool EnableButtons + { + get + { + return this._enableButtons; + } + set + { + this._enableButtons = value; + this.OnPropertyChanged("EnableButtons"); + } + } + + public bool EnableExcluir + { + get + { + return this._enableExcluir; + } + set + { + this._enableExcluir = this._excluirPermissEnabled & value; + this.OnPropertyChanged("EnableExcluir"); + } + } + + public bool EnableFields + { + get + { + return this._enableFields; + } + set + { + this._enableFields = value; + this.OnPropertyChanged("EnableFields"); + } + } + + public bool EnableIncluir + { + get + { + return this._enableIncluir; + } + set + { + this._enableIncluir = this._incluirPermissEnabled & value; + this.OnPropertyChanged("EnableIncluir"); + } + } + + public bool EnableMainMenu + { + get + { + return this._enableMainMenu; + } + set + { + this._enableMainMenu = value; + this.OnPropertyChanged("EnableMainMenu"); + } + } + + public bool EnableMenu + { + get + { + return this._enableMenu; + } + set + { + this._enableMenu = value; + this.OnPropertyChanged("EnableMenu"); + } + } + + public string ErroCamposInvalidos + { + get; + } + + public bool ExcluirParcelaEnabled + { + get + { + return this._excluirParcelaEnabled; + } + set + { + this._excluirParcelaEnabled = value; + this.OnPropertyChanged("ExcluirParcelaEnabled"); + } + } + + public bool IncluirParcelaEnabled + { + get + { + return this._incluirParcelaEnabled; + } + set + { + this._incluirParcelaEnabled = value; + this.OnPropertyChanged("IncluirParcelaEnabled"); + } + } + + public bool IsEnabled + { + get + { + return this._isEnabled; + } + set + { + this._isEnabled = value; + this.OnPropertyChanged("IsEnabled"); + } + } + + public bool IsEnabledEdit + { + get + { + return this._isEnableEdit; + } + set + { + this._isEnableEdit = value; + this.OnPropertyChanged("IsEnabledEdit"); + } + } + + public bool IsEnabledEditEndosso + { + get + { + return this._isEnabledEditEndosso; + } + set + { + this._isEnabledEditEndosso = value; + this.OnPropertyChanged("IsEnabledEditEndosso"); + } + } + + public Visibility IsVisible + { + get + { + return this._isVisible; + } + set + { + this._isVisible = value; + this.OnPropertyChanged("IsVisible"); + } + } + + public bool IsVisibleEmpresa + { + get + { + return this._isVisibleEmpresa; + } + set + { + this._isVisibleEmpresa = value; + this.OnPropertyChanged("IsVisibleEmpresa"); + } + } + + public bool PermissaoWhatsapp + { + get + { + return this._permissaoWhatsapp; + } + set + { + this._permissaoWhatsapp = value; + this.OnPropertyChanged("PermissaoWhatsapp"); + } + } + + public object PopupContent + { + get + { + return this._popupContent; + } + set + { + this._popupContent = value; + this.OnPropertyChanged("PopupContent"); + } + } + + protected BaseViewModel() + { + this._enableButtons = true; + this._enableIncluir = true; + if (LicenseHelper.Produtos != null) + { + if (!LicenseHelper.Produtos.Any((Licenca x) => { + if (x.get_Produto() != 2) + { + return false; + } + return x.get_Status() == 1; + })) + { + goto Label1; + } + Empresa empresa = Recursos.Empresa; + if (empresa != null) + { + id = empresa.get_Id() == (long)1; + goto Label0; + } + else + { + id = false; + goto Label0; + } + } + Label1: + id = false; + Label0: + this._isVisibleEmpresa = id; + this._enableAlterar = true; + this._enableExcluir = true; + this._permissaoWhatsapp = true; + this._allowEditParcela = true; + this._isEnableEdit = true; + this._isEnabledEditEndosso = true; + Usuario usuario = Recursos.Usuario; + if (usuario != null) + { + flag = usuario.get_Id() > (long)0; + } + else + { + flag = false; + } + this._enableMenu = flag; + this._enableMainMenu = true; + this._isEnabled = true; + this._isVisible = Visibility.Collapsed; + this.ErroCamposInvalidos = string.Concat("HÁ CAMPOS DESTACADOS QUE DEVEM SER PREENCHIDOS CORRETAMENTE.", Environment.NewLine, "REALIZE A CORREÇÃO E TENTE NOVAMENTE."); + base(); + bool id; + bool flag; + this.ArquivoDigitalServico = new Gestor.Application.Servicos.ArquivoDigitalServico(); + Gestor.Application.Actions.Actions.EnableMainMenu = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.EnableMainMenu, new Action(this.HabilitarMenu)); + Gestor.Application.Actions.Actions.EnableMenu = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.EnableMenu, new Action(this.HabilitarMenuSecundario)); + this.ServicoPermissArquivoDigital = new PermissaoArquivoDigitalServico(); + this.ServicoPermissUsuario = new PermissaoUsuarioServico(); + this.ServicoRestriUsuario = new RestricaoUsuarioServico(); + this.ServicoVendedorUsuario = new VendedorUsuarioServico(); + } + + public bool Abrir(IndiceArquivoDigital indice, Gestor.Model.Domain.Common.ArquivoDigital arquivo) + { + bool flag; + string tempPath = Path.GetTempPath(); + Guid? azureGuid = arquivo.get_AzureGuid(); + string str = string.Format("{0}{1}{2}", tempPath, (azureGuid.HasValue ? azureGuid.GetValueOrDefault() : Guid.NewGuid()), Gestor.Common.Validation.ValidationHelper.GetDefaultExtension(arquivo.get_Extensao())); + try + { + using (BinaryWriter binaryWriter = new BinaryWriter(File.Open(str, FileMode.Create))) + { + binaryWriter.Write(arquivo.get_Arquivo()); + } + Process.Start(str); + return true; + } + catch (Exception exception) + { + flag = false; + } + return flag; + } + + public async void AbrirLog(TipoTela tipoTela, long id) + { + if (Recursos.Usuario.get_Id() != 0) + { + RestricaoUsuario restricaoUsuario = this.ServicoRestriUsuario.BuscarRestricao(Recursos.Usuario, 109); + if (restricaoUsuario == null || !restricaoUsuario.get_Restricao()) + { + this.ShowDrawer(new LogDrawer(tipoTela, id, null, 0), 0, false); + } + else + { + await this.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR OS LOGS", "OK", "", false); + } + } + else + { + this.ShowDrawer(new LogDrawer(tipoTela, id, null, 0), 0, false); + } + } + + public async void AbrirLogEmail(TipoTela tela, long id) + { + if (Recursos.Usuario.get_Id() != 0) + { + RestricaoUsuario restricaoUsuario = this.ServicoRestriUsuario.BuscarRestricao(Recursos.Usuario, 109); + if (restricaoUsuario == null || !restricaoUsuario.get_Restricao()) + { + this.ShowDrawer(new LogEmailDrawer(tela, id, false), 0, false); + } + else + { + await this.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR OS LOGS", "OK", "", false); + } + } + else + { + this.ShowDrawer(new LogEmailDrawer(tela, id, false), 0, false); + } + } + + public async void AbrirLogParcela(List parcelas, long documento, int numparcela = 0) + { + if (Recursos.Usuario.get_Id() != 0) + { + RestricaoUsuario restricaoUsuario = this.ServicoRestriUsuario.BuscarRestricao(Recursos.Usuario, 109); + if (restricaoUsuario == null || !restricaoUsuario.get_Restricao()) + { + this.ShowDrawer(new LogDrawer(5, documento, parcelas, numparcela), 0, false); + } + else + { + await this.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR OS LOGS", "OK", "", false); + } + } + else + { + this.ShowDrawer(new LogDrawer(5, documento, parcelas, numparcela), 0, false); + } + } + + public async Task> AddAttachments(List attachments, List attacheds) + { + List arquivoDigitals; + List arquivoDigitals1; + List strs = new List(); + using (OpenFileDialog openFileDialog = new OpenFileDialog()) + { + openFileDialog.Multiselect = true; + openFileDialog.Filter = "Todos os Arquivos|*.pdf;*.jpg;*.jpeg;*.png;*.bmp;*.doc;*.docx;*.xls;*.xlsx;*.json;*.rar;*.zip;*.msg;*.eml;*.txt|Arquivos PDF|*.pdf|Imagens|*.jpg;*.jpeg;*.png;*.bmp|Documentos|*.doc;*.docx;*.msg|Planilhas|*.xls;*.xlsx|Arquivos do Aggilizador|*.json|Arquivos de Áudio|*.amr;*.ogg"; + openFileDialog.InitialDirectory = Environment.SpecialFolder.Desktop.ToString(); + if (DialogResult.OK == openFileDialog.ShowDialog()) + { + strs.AddRange(openFileDialog.FileNames); + } + else + { + arquivoDigitals = null; + return arquivoDigitals; + } + } + strs = await this.ValidateAttachment(attachments, strs); + strs = await this.ValidateAttachment(attacheds, strs); + attachments = new List(); + foreach (string str in strs) + { + int num = 0; + try + { + string extension = Path.GetExtension(str); + using (MemoryStream memoryStream = new MemoryStream(File.ReadAllBytes(str))) + { + byte[] numArray = new byte[checked((IntPtr)memoryStream.Length)]; + memoryStream.Position = (long)0; + memoryStream.Read(numArray, 0, (int)numArray.Length); + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital = new Gestor.Model.Domain.Common.ArquivoDigital(); + arquivoDigital.set_Arquivo(numArray); + arquivoDigital.set_Descricao(Path.GetFileNameWithoutExtension(str)); + arquivoDigital.set_Extensao(extension); + attachments.Add(arquivoDigital); + } + } + catch (Exception exception) + { + num = 1; + } + if (num != 1) + { + continue; + } + string[] newLine = new string[] { "NÃO FOI POSSÍVEL CARREGAR O ARQUIVO ", str, ".", Environment.NewLine, "O ARQUIVO ESTÁ INACESSÍVEL OU SENDO UTILIZADO POR OUTRO PROCESSO." }; + await this.ShowMessage(string.Concat(newLine), "OK", "", false); + } + if (attachments.Count == 0) + { + arquivoDigitals1 = null; + } + else + { + arquivoDigitals1 = attachments; + } + arquivoDigitals = arquivoDigitals1; + return arquivoDigitals; + } + + public async void Alterar(bool alterar) + { + Action enablePesquisarClientes = Gestor.Application.Actions.Actions.EnablePesquisarClientes; + if (enablePesquisarClientes != null) + { + enablePesquisarClientes(!alterar); + } + else + { + } + Action enableMenu = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu != null) + { + enableMenu(!alterar); + } + else + { + } + Action enableMainMenu = Gestor.Application.Actions.Actions.EnableMainMenu; + if (enableMainMenu != null) + { + enableMainMenu(!alterar); + } + else + { + } + this.EnableFields = alterar; + this.EnableMenu = !alterar; + if (alterar) + { + this.EnableIncluir = false; + this.EnableAlterar = false; + this.EnableExcluir = false; + this.EnableButtons = false; + } + else + { + this.VerificarEnables(this._lastId); + } + this.AllowEditParcela = !alterar; + this.IsEnabledEdit = !alterar; + this.IsEnabledEditEndosso = !alterar; + if ((Funcoes.GetNetworkTime() - ApplicationHelper.ChecagemVersao).TotalMinutes > 10) + { + await this.VerificarVersao(); + } + } + + public async Task BuscaCep(string cep) + { + return await (new CepService()).SearchDirect(cep); + } + + internal async Task> BuscarBanco(string value) + { + List bancos = await Task.Run>(() => (new BaseServico()).BuscarBanco(value)); + return bancos; + } + + internal void CloseDrawer() + { + Window window = System.Windows.Application.Current.Windows.OfType().SingleOrDefault((Window x) => x.IsActive); + DrawerHost drawerHost = Extentions.FindVisualChildren(window).FirstOrDefault(); + Extentions.FindVisualChildren(window).ToList().ForEach((WebEditor x) => x.Visibility = Visibility.Visible); + if (drawerHost == null) + { + return; + } + drawerHost.set_IsBottomDrawerOpen(false); + drawerHost.set_IsTopDrawerOpen(false); + if (drawerHost.get_IsLeftDrawerOpen()) + { + drawerHost.set_IsLeftDrawerOpen(false); + return; + } + drawerHost.set_IsRightDrawerOpen(false); + } + + private void CloseSlackBar() + { + Thread.Sleep(5000); + Dispatcher dispatcher = App.ProgressRing.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => this.ToggleSnackBar("", false))); + } + + private async Task CreateDialogAdvertising() + { + DialogAdvertising dialogAdvertising; + DateTime? nullable; + DialogAdvertising dialogAdvertising1; + DateTime? nullable1; + DateTime? nullable2; + string str; + bool flag; + bool flag1; + object empty; + JObject jObject = await this.LoadJsonAdvertising(Address.get_SurveyJson()); + if (jObject != null) + { + JToken item = jObject.get_Item("Inicio"); + if (item != null) + { + nullable1 = new DateTime?(Extensions.Value(item)); + } + else + { + nullable = null; + nullable1 = nullable; + } + DateTime? nullable3 = nullable1; + JToken jToken = jObject.get_Item("Fim"); + if (jToken != null) + { + nullable2 = new DateTime?(Extensions.Value(jToken)); + } + else + { + nullable = null; + nullable2 = nullable; + } + DateTime? nullable4 = nullable2; + DateTime networkTime = Funcoes.GetNetworkTime(); + Gestor.Application.Model.Configuracoes configuraco = this.LoadConfiguracoes(); + JToken item1 = jObject.get_Item("UrlPost"); + if (item1 != null) + { + str = Extensions.Value(item1); + } + else + { + str = null; + } + string str1 = str; + if (Gestor.Common.Validation.ValidationHelper.IsNullOrEmpty(str1)) + { + JToken jToken1 = jObject.get_Item("UrlFixa"); + if (jToken1 != null) + { + empty = Extensions.Value(jToken1); + } + else + { + empty = null; + } + if (empty == null) + { + empty = string.Empty; + } + str1 = (string)empty; + } + if (configuraco.LinkPromo == str1 || configuraco.NaoverPromo) + { + dialogAdvertising = null; + } + else + { + nullable = nullable4; + DateTime dateTime = networkTime; + flag = (nullable.HasValue ? nullable.GetValueOrDefault() >= dateTime : false); + if (flag) + { + nullable = nullable3; + dateTime = networkTime; + flag1 = (nullable.HasValue ? nullable.GetValueOrDefault() <= dateTime : false); + if (!flag1) + { + goto Label1; + } + dialogAdvertising1 = new DialogAdvertising(jObject, false); + goto Label0; + } + Label1: + dialogAdvertising1 = await this.LoadDialogAdertisingPromo(); + Label0: + dialogAdvertising = dialogAdvertising1; + } + } + else + { + dialogAdvertising = await this.LoadDialogAdertisingPromo(); + } + return dialogAdvertising; + } + + private void CriarConfiguracaoPadrao(string configFile) + { + if (File.Exists(configFile)) + { + return; + } + File.WriteAllText(configFile, JsonConvert.SerializeObject(new Gestor.Application.Model.Configuracoes() + { + LinkPromo = "", + NaoverPromo = false + }, 1)); + } + + public async void Download(IndiceArquivoDigital indice, bool open = true) + { + DateTime valueOrDefault; + bool arquivo; + int? nullable; + bool flag; + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital; + if (indice.get_Id() != 0) + { + arquivoDigital = null; + if (indice.get_Assinado()) + { + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital1 = await this.ArquivoDigitalServico.BuscarPorId(indice.get_Id()); + if (arquivoDigital1 != null) + { + flag = arquivoDigital1.get_Arquivo(); + } + else + { + flag = false; + } + if (flag) + { + if (!arquivoDigital1.get_Extensao().Contains(".")) + { + arquivoDigital1.set_Extensao(string.Concat(".", arquivoDigital1.get_Extensao())); + } + arquivoDigital = arquivoDigital1; + } + } + if (arquivoDigital == null) + { + arquivoDigital = await this.ArquivoDigitalServico.BuscarPorId(indice.get_IdArquivoDigital(), indice.get_Bd()); + } + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital2 = arquivoDigital; + if (arquivoDigital2 != null) + { + arquivo = arquivoDigital2.get_Arquivo(); + } + else + { + arquivo = false; + } + if (!arquivo || arquivoDigital.get_Extensao() == null) + { + string str = "DOCUMENTO NÃO POSSUI PDF"; + DateTime? dataCriacao = indice.get_DataCriacao(); + if (dataCriacao.HasValue) + { + valueOrDefault = dataCriacao.GetValueOrDefault(); + nullable = new int?(valueOrDefault.Year); + } + else + { + nullable = null; + } + int? nullable1 = nullable; + valueOrDefault = DateTime.Now; + if (nullable1.GetValueOrDefault() <= valueOrDefault.Year - 5 & nullable1.HasValue) + { + str = string.Concat(str, " OU POR SER UM ARQUIVO ANTIGO, TENTE NOVAMENTE EM ALGUNS MINUTOS"); + } + await this.ShowMessage(string.Concat(str, "."), "OK", "", false); + } + else + { + if (open) + { + if (!this.Abrir(indice, arquivoDigital)) + { + await this.ShowMessage("NÃO FOI POSSÍVEL ABRIR O ARQUIVO. ESCOLHA UM LOCAL PARA SALVAR O ARQUIVO.", "OK", "", false); + } + else + { + arquivoDigital = null; + return; + } + } + using (SaveFileDialog saveFileDialog = new SaveFileDialog()) + { + saveFileDialog.Filter = "All Files|*.*"; + saveFileDialog.FileName = indice.get_Descricao(); + if (DialogResult.OK != saveFileDialog.ShowDialog()) + { + arquivoDigital = null; + return; + } + else if (!File.Exists(string.Concat(saveFileDialog.FileName, Gestor.Common.Validation.ValidationHelper.GetDefaultExtension(arquivoDigital.get_Extensao())))) + { + using (BinaryWriter binaryWriter = new BinaryWriter(File.Open(string.Concat(saveFileDialog.FileName, Gestor.Common.Validation.ValidationHelper.GetDefaultExtension(arquivoDigital.get_Extensao())), FileMode.Create))) + { + binaryWriter.Write(arquivoDigital.get_Arquivo()); + } + } + else + { + string[] descricao = new string[] { "JÁ EXISTE UM ARQUIVO COM O NOME DE ", arquivoDigital.get_Descricao(), Gestor.Common.Validation.ValidationHelper.GetDefaultExtension(arquivoDigital.get_Extensao()), " NA PASTA SELECIONADA. ", Environment.NewLine, "TENTE NOVAMENTE EM OUTRA PASTA." }; + await this.ShowMessage(string.Concat(descricao), "OK", "", false); + arquivoDigital = null; + return; + } + } + saveFileDialog = null; + } + } + arquivoDigital = null; + } + + public async Task DownloadAll(List indices, long id) + { + bool flag; + bool arquivo; + bool arquivo1; + string str; + using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog()) + { + if (DialogResult.OK == folderBrowserDialog.ShowDialog()) + { + str = string.Format("{0}\\{1}", folderBrowserDialog.SelectedPath, id); + Directory.CreateDirectory(str); + } + else + { + flag = false; + str = null; + return flag; + } + } + int num = 1; + foreach (IndiceArquivoDigital index in indices) + { + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital = null; + if (index.get_Assinado()) + { + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital1 = await this.ArquivoDigitalServico.BuscarPorId(index.get_Id()); + if (arquivoDigital1 != null) + { + arquivo1 = arquivoDigital1.get_Arquivo(); + } + else + { + arquivo1 = false; + } + if (arquivo1) + { + arquivoDigital = arquivoDigital1; + } + } + if (arquivoDigital == null) + { + arquivoDigital = await this.ArquivoDigitalServico.BuscarPorId(index.get_IdArquivoDigital(), index.get_Bd()); + } + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital2 = arquivoDigital; + if (arquivoDigital2 != null) + { + arquivo = arquivoDigital2.get_Arquivo(); + } + else + { + arquivo = false; + } + if (!arquivo || arquivoDigital.get_Extensao() == null) + { + flag = false; + str = null; + return flag; + } + else + { + if (File.Exists(Gestor.Common.Validation.ValidationHelper.NormalizePath(string.Concat(str, "\\", index.get_Descricao(), Gestor.Common.Validation.ValidationHelper.GetDefaultExtension(arquivoDigital.get_Extensao()))))) + { + index.set_Descricao(string.Format("{0}_{1}", index.get_Descricao(), num)); + num++; + } + using (BinaryWriter binaryWriter = new BinaryWriter(File.Open(Gestor.Common.Validation.ValidationHelper.NormalizePath(string.Concat(str, "\\", index.get_Descricao(), Gestor.Common.Validation.ValidationHelper.GetDefaultExtension(arquivoDigital.get_Extensao()))), FileMode.Create))) + { + binaryWriter.Write(arquivoDigital.get_Arquivo()); + } + arquivoDigital = null; + index = null; + } + } + Process.Start(str); + flag = true; + str = null; + return flag; + } + + public async Task DownloadAll(List ids, TipoArquivoVinculo type) + { + bool arquivo; + string str; + Gestor.Application.Servicos.ArquivoDigitalServico arquivoDigitalServico; + if (ids != null && ids.Count != 0) + { + str = string.Format("{0}{1}", Path.GetTempPath(), Guid.NewGuid()); + BaseServico baseServico = new BaseServico(); + arquivoDigitalServico = new Gestor.Application.Servicos.ArquivoDigitalServico(); + List arquivoVinculos = await baseServico.ArquivoVinculo(ids, type); + int num = 1; + if (!Directory.Exists(str)) + { + Directory.CreateDirectory(str); + } + foreach (ArquivoVinculo arquivoVinculo in await arquivoDigitalServico.BaixarArquivosPendentes(arquivoVinculos)) + { + if (arquivoVinculo != null) + { + arquivo = arquivoVinculo.get_Arquivo(); + } + else + { + arquivo = false; + } + if (!arquivo) + { + continue; + } + string str1 = Guid.NewGuid().ToString(); + if (File.Exists(string.Concat(str, "\\", str1, ".pdf"))) + { + str1 = string.Format("{0}_{1}", str1, num); + num++; + } + using (BinaryWriter binaryWriter = new BinaryWriter(File.Open(string.Concat(str, "\\", str1, ".pdf"), FileMode.Create))) + { + binaryWriter.Write(arquivoVinculo.get_Arquivo()); + } + } + Process.Start(str); + } + str = null; + arquivoDigitalServico = null; + } + + public async Task EmitirCheckList(List documentos) + { + DateTime vencimento; + string str; + string str1; + string str2; + string str3; + string str4; + string str5; + string str6; + string str7; + string nome; + ParcelaServico parcelaServico = new ParcelaServico(); + string str8 = "CHECK LIST DE PROTOCOLOS"; + str8 = string.Concat(str8, "
CHECK LIST DE PROTOCOLOS

"); + str8 = string.Concat(str8, "
"); + str8 = string.Concat(str8, ""); + int num = 1; + str8 = string.Concat(str8, ""); + str8 = string.Concat(str8, ""); + str8 = string.Concat(str8, ""); + str8 = string.Concat(str8, ""); + str8 = string.Concat(str8, ""); + str8 = string.Concat(str8, ""); + str8 = string.Concat(str8, ""); + str8 = string.Concat(str8, ""); + List documentos1 = documentos; + documentos = ( + from x in documentos1 + orderby x.get_Controle().get_Cliente().get_Nome() + select x).ToList(); + foreach (Documento documento in documentos) + { + Documento documento1 = documento; + ObservableCollection observableCollection = await parcelaServico.BuscarParcelasAsync(documento.get_Id()); + documento1.set_Parcelas(observableCollection); + documento1 = null; + string[] strArrays = new string[] { str8, ""; + str8 = string.Concat(strArrays); + string[] apolice = new string[] { str8, ""; + str8 = string.Concat(apolice); + if (documento.get_Parcelas() != null) + { + ObservableCollection parcelas = documento.get_Parcelas(); + if (( + from x in parcelas + where x.get_SubTipo() == 1 + select x).ToList().Count <= 0) + { + goto Label1; + } + ObservableCollection parcelas1 = documento.get_Parcelas(); + vencimento = ( + from x in parcelas1 + where x.get_NumeroParcela() == 1 + select x).First().get_Vencimento(); + vencimento = vencimento.Date; + str2 = vencimento.ToString("dd/MM/yyyy"); + goto Label0; + } + Label1: + str2 = ""; + Label0: + string str9 = str2; + string[] strArrays1 = new string[] { str8, ""; + str8 = string.Concat(strArrays1); + if (documento.get_Parcelas() != null) + { + ObservableCollection observableCollection1 = documento.get_Parcelas(); + if (( + from x in observableCollection1 + where x.get_SubTipo() == 1 + select x).ToList().Count <= 1) + { + goto Label3; + } + ObservableCollection parcelas2 = documento.get_Parcelas(); + vencimento = ( + from x in parcelas2 + where x.get_NumeroParcela() == 2 + select x).First().get_Vencimento(); + vencimento = vencimento.Date; + str4 = vencimento.ToString("dd/MM/yyyy"); + goto Label2; + } + Label3: + str4 = ""; + Label2: + str9 = str4; + string[] strArrays2 = new string[] { str8, ""; + str8 = string.Concat(strArrays2); + string str10 = str8; + str6 = (num % 2 == 0 ? "WhiteSmoke" : "White"); + str8 = string.Concat(str10, ""); + string[] strArrays3 = new string[] { str8, ""; + str8 = string.Concat(strArrays3); + if (num != 1) + { + num++; + } + else + { + num = 0; + } + } + DateTime networkTime = Funcoes.GetNetworkTime(); + string nome1 = Recursos.Usuario.get_Nome(); + str8 = string.Concat(str8, "
CLIENTEAPÓLICE1ª PARCELA2ª PARCELARECEBIDA PORVENDEDOR
"; + strArrays[4] = documento.get_Controle().get_Cliente().get_Nome(); + strArrays[5] = ""; + apolice[4] = documento.get_Apolice(); + apolice[5] = ""; + strArrays1[4] = str9; + strArrays1[5] = ""; + strArrays2[4] = str9; + strArrays2[5] = "____________/____/___"; + Vendedor vendedorPrincipal = documento.get_VendedorPrincipal(); + if (vendedorPrincipal != null) + { + nome = vendedorPrincipal.get_Nome(); + } + else + { + nome = null; + } + strArrays3[4] = nome; + strArrays3[5] = "
"); + string str11 = str8; + int count = documentos.Count; + str8 = string.Concat(str11, "
TOTAL DE PROTOCOLOS: ", count.ToString(), "
"); + str8 = string.Concat(str8, string.Format("Emitido pelo usuário: {0}, data e hora: {1}.", nome1, networkTime)); + str8 = string.Concat(str8, ""); + string tempPath = Path.GetTempPath(); + string str12 = string.Format("{0}{1}CheckList_{2:ddMMyyyyhhmmss}.html", tempPath, (TipoExtrato)0, networkTime); + StreamWriter streamWriter = new StreamWriter(str12, true, Encoding.UTF8); + streamWriter.Write(str8); + streamWriter.Close(); + Process.Start(str12); + parcelaServico = null; + str8 = null; + } + + public async Task EmitirProtocolos(List> lista, bool doisPorPagina, List protocolo) + { + DateTime vigencia1; + string str; + ClienteEndereco clienteEndereco; + string str1; + string str2; + string str3; + string str4; + string str5; + string str6; + string str7; + string str8; + bool flag; + string email; + string str9; + string str10; + string shortDateString; + string shortDateString1; + string shortDateString2; + string str11; + string obsProtocolo; + string str12; + string pasta; + string nome; + string str13; + string str14; + string str15; + object obj; + string shortDateString3; + string shortDateString4; + string str16; + object obj1; + int num = 0; + DateTime networkTime = Funcoes.GetNetworkTime(); + int num1 = 0; + StringBuilder stringBuilder = new StringBuilder(); + StringBuilder stringBuilder1 = new StringBuilder(); + foreach (Tuple listum in lista) + { + num1++; + ApoliceServico apoliceServico = new ApoliceServico(); + ItemServico itemServico = new ItemServico(); + ClienteServico clienteServico = new ClienteServico(); + ParcelaServico parcelaServico = new ParcelaServico(); + Documento documento = await apoliceServico.BuscarApoliceAsync(listum.Item1, false, false); + Documento documento1 = documento; + documento1.get_Controle().get_Cliente().set_Telefones(clienteServico.BuscarTelefones(documento1.get_Controle().get_Cliente().get_Id())); + Cliente cliente = documento1.get_Controle().get_Cliente(); + ObservableCollection observableCollection = await clienteServico.BuscarEmailsAsync(documento1.get_Controle().get_Cliente().get_Id()); + cliente.set_Emails(observableCollection); + cliente = null; + cliente = documento1.get_Controle().get_Cliente(); + ObservableCollection observableCollection1 = await clienteServico.BuscarEnderecosAsync(documento1.get_Controle().get_Cliente().get_Id()); + cliente.set_Enderecos(observableCollection1); + cliente = null; + if (documento1.get_VendedorPrincipal() == null) + { + Documento documento2 = documento1; + Vendedor vendedor = await apoliceServico.BuscarVendedorPrincipal(documento1.get_Controle().get_Id()); + documento2.set_VendedorPrincipal(vendedor); + documento2 = null; + } + ObservableCollection observableCollection2 = await itemServico.BuscarItems(documento1.get_Id(), 2, false); + if (observableCollection2 == null || observableCollection2.Count == 0) + { + observableCollection2 = await itemServico.BuscarItens(documento1.get_Controle().get_Id(), 3); + } + ObservableCollection observableCollection3 = await parcelaServico.BuscarParcelasAsync(documento1.get_Id()); + documento1.set_ProtocoloEmail(protocolo.Find((Documento x) => x.get_Id() == documento1.get_Id()).get_ProtocoloEmail()); + documento1.set_ProtocoloTelefone(protocolo.Find((Documento x) => x.get_Id() == documento1.get_Id()).get_ProtocoloTelefone()); + documento1.set_ProtocoloParcela(protocolo.Find((Documento x) => x.get_Id() == documento1.get_Id()).get_ProtocoloParcela()); + documento1.set_ProtocoloEndereco(protocolo.Find((Documento x) => x.get_Id() == documento1.get_Id()).get_ProtocoloEndereco()); + documento1.set_ProtocoloVendedor(protocolo.Find((Documento x) => x.get_Id() == documento1.get_Id()).get_ProtocoloVendedor()); + ObservableCollection telefones = documento1.get_Controle().get_Cliente().get_Telefones(); + if (documento1.get_ProtocoloTelefone() && telefones != null) + { + ObservableCollection observableCollection4 = telefones; + if (!( + from t in observableCollection4 + where !string.IsNullOrEmpty(t.get_Numero()) + select t).Any()) + { + goto Label1; + } + ObservableCollection observableCollection5 = telefones; + IEnumerable clienteTelefones = + from t in observableCollection5 + where !string.IsNullOrEmpty(t.get_Numero()) + select t; + str = string.Join(" | ", ( + from t in clienteTelefones + select string.Concat(t.get_Prefixo(), " ", t.get_Numero())).ToList()); + goto Label0; + } + Label1: + str = null; + Label0: + string str17 = string.Concat("Telefone: ", str, ""); + ObservableCollection enderecos = documento1.get_Controle().get_Cliente().get_Enderecos(); + if (enderecos != null) + { + clienteEndereco = enderecos.FirstOrDefault(); + } + else + { + clienteEndereco = null; + } + ClienteEndereco clienteEndereco1 = clienteEndereco; + if (protocolo.Find((Documento x) => x.get_Id() == documento1.get_Id()).get_ProtocoloEndereco()) + { + string[] strArrays = new string[12]; + str1 = (string.IsNullOrWhiteSpace(clienteEndereco1.get_Endereco()) ? "" : clienteEndereco1.get_Endereco()); + strArrays[0] = str1; + strArrays[1] = ", "; + str2 = (string.IsNullOrWhiteSpace(clienteEndereco1.get_Numero()) ? "" : clienteEndereco1.get_Numero()); + strArrays[2] = str2; + str3 = (string.IsNullOrWhiteSpace(clienteEndereco1.get_Complemento()) ? "" : string.Concat(" - ", clienteEndereco1.get_Complemento())); + strArrays[3] = str3; + strArrays[4] = " - "; + str4 = (string.IsNullOrWhiteSpace(clienteEndereco1.get_Bairro()) ? "" : clienteEndereco1.get_Bairro()); + strArrays[5] = str4; + strArrays[6] = " - "; + str5 = (string.IsNullOrWhiteSpace(clienteEndereco1.get_Cidade()) ? "" : clienteEndereco1.get_Cidade()); + strArrays[7] = str5; + strArrays[8] = " - "; + str6 = (string.IsNullOrWhiteSpace(clienteEndereco1.get_Estado()) ? "" : clienteEndereco1.get_Estado()); + strArrays[9] = str6; + strArrays[10] = ", "; + str7 = (string.IsNullOrWhiteSpace(clienteEndereco1.get_Cep()) ? "" : clienteEndereco1.get_Cep()); + strArrays[11] = str7; + str8 = string.Concat(strArrays); + } + else + { + str8 = null; + } + string str18 = str8; + ObservableCollection emails = documento1.get_Controle().get_Cliente().get_Emails(); + flag = (!documento1.get_ProtocoloEmail() || emails == null || emails.Count <= 0 ? false : !string.IsNullOrEmpty(emails.First().get_Email())); + if (flag) + { + email = emails.First().get_Email(); + } + else + { + email = null; + } + string str19 = string.Concat(" Email: ", email, ""); + str9 = (telefones != null || clienteEndereco1 != null || emails != null ? "" : "style='display:none;'"); + string str20 = str9; + str10 = (string.IsNullOrWhiteSpace(documento1.get_Endosso()) ? ", " : string.Concat(" e
endosso de n° ", documento1.get_Endosso(), ", ")); + string str21 = str10; + string[] strArrays1 = new string[] { "iniciado em ", null, null, null, null }; + if (string.IsNullOrWhiteSpace(documento1.get_Vigencia1().ToShortDateString())) + { + shortDateString = ""; + } + else + { + vigencia1 = documento1.get_Vigencia1(); + shortDateString = vigencia1.ToShortDateString(); + } + strArrays1[1] = shortDateString; + strArrays1[2] = " até "; + DateTime? vigencia2 = documento1.get_Vigencia2(); + if (vigencia2.HasValue) + { + shortDateString1 = vigencia2.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString1 = null; + } + if (string.IsNullOrWhiteSpace(shortDateString1)) + { + shortDateString2 = ""; + } + else + { + vigencia2 = documento1.get_Vigencia2(); + if (vigencia2.HasValue) + { + shortDateString2 = vigencia2.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString2 = null; + } + } + strArrays1[3] = shortDateString2; + strArrays1[4] = ""; + string str22 = string.Concat(strArrays1); + if (observableCollection2 == null || observableCollection2.Count <= 0) + { + str11 = ""; + } + else + { + str16 = (string.IsNullOrWhiteSpace(observableCollection2[0].get_Descricao()) ? "" : observableCollection2[0].get_Descricao()); + str11 = string.Concat("", str16, ""); + } + string str23 = str11; + string str24 = ""; + Documento documento3 = protocolo.FirstOrDefault((Documento x) => x.get_Id() == documento1.get_Id()); + if (documento3 != null) + { + obsProtocolo = documento3.get_ObsProtocolo(); + } + else + { + obsProtocolo = null; + } + string str25 = obsProtocolo; + str12 = (string.IsNullOrEmpty(str25) ? "" : string.Concat("OBSERVAÇÃO: ", str25)); + string str26 = str12; + if (documento1.get_ProtocoloParcela() && observableCollection3 != null && observableCollection3.Count > 0) + { + if (observableCollection3.Count != 1) + { + object count = observableCollection3.Count; + if (string.IsNullOrWhiteSpace(observableCollection3[0].get_Vencimento().ToShortDateString())) + { + obj = ""; + } + else + { + vigencia1 = observableCollection3[0].get_Vencimento(); + obj = vigencia1.ToShortDateString(); + } + string str27 = string.Format("{0} parcelas: vencimento 1ª parcela: {1}, ", count, obj); + if (string.IsNullOrWhiteSpace(observableCollection3[1].get_Vencimento().ToShortDateString())) + { + shortDateString3 = ""; + } + else + { + vigencia1 = observableCollection3[1].get_Vencimento(); + shortDateString3 = vigencia1.ToShortDateString(); + } + str24 = string.Concat(str27, "vencimento 2ª parcela: ", shortDateString3, ", demais parcelas, vide apólice."); + } + else + { + string str28 = str24; + if (string.IsNullOrWhiteSpace(observableCollection3[0].get_Vencimento().ToShortDateString())) + { + shortDateString4 = ""; + } + else + { + vigencia1 = observableCollection3[0].get_Vencimento(); + shortDateString4 = vigencia1.ToShortDateString(); + } + str24 = string.Concat(str28, "1 parcela: vencimento ", shortDateString4, " "); + } + } + if (documento1.get_ProtocoloVendedor()) + { + pasta = documento1.get_Pasta(); + } + else + { + pasta = null; + } + string str29 = pasta; + if (documento1.get_ProtocoloVendedor()) + { + Vendedor vendedorPrincipal = documento1.get_VendedorPrincipal(); + if (vendedorPrincipal != null) + { + nome = vendedorPrincipal.get_Nome(); + } + else + { + nome = null; + } + } + else + { + nome = null; + } + string str30 = nome; + str13 = (str29 != null || str30 != null ? "" : "style = 'display:none;'"); + string str31 = str13; + StringBuilder stringBuilder2 = stringBuilder1; + string protocoloTemplate = Resources.ProtocoloTemplate; + str14 = (doisPorPagina ? "12.2cm" : "24.4cm"); + string str32 = protocoloTemplate.Replace("{Tamanho}", str14).Replace("{Observacao}", str26).Replace("{Nome}", documento1.get_Controle().get_Cliente().get_Nome()).Replace("{Email}", str19).Replace("{DisplayTelefones}", str20); + str15 = (telefones != null ? str17 : ""); + stringBuilder2.Append(str32.Replace("{Telefones}", str15).Replace("{Endereço}", str18).Replace("{Ramo}", documento1.get_Controle().get_Ramo().get_Nome()).Replace("{Apolice}", documento1.get_Apolice()).Replace("{Endosso}", str21).Replace("{Seguradora}", documento1.get_Controle().get_Seguradora().get_Nome()).Replace("{Vigencias}", str22).Replace("{Item}", str23).Replace("{Parcelas}", str24).Replace("{Pasta}", str29).Replace("{Vendedor}", str30).Replace("{DisplayVendedor}", str31).Replace("{NomeCorretora}", Recursos.Empresa.get_Nome()).Replace("{Usuario}", Recursos.Usuario.get_Nome()).Replace("{Emissao}", string.Format("{0}", networkTime))); + num++; + if (!doisPorPagina || num1 == 2) + { + stringBuilder1.Append("
"); + num1 = 0; + } + apoliceServico = null; + itemServico = null; + clienteServico = null; + parcelaServico = null; + observableCollection2 = null; + } + stringBuilder.Append(Resources.ProtocoloPageTemplate.Replace("{Protocolos}", stringBuilder1.ToString())); + string tempPath = Path.GetTempPath(); + string str33 = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.html", tempPath, (TipoExtrato)0, networkTime); + StreamWriter streamWriter = new StreamWriter(str33, true, Encoding.UTF8); + streamWriter.Write(stringBuilder); + streamWriter.Close(); + Process.Start(str33); + BaseViewModel baseViewModel = this; + object count1 = lista.Count; + obj1 = (lista.Count == 1 ? "" : "S"); + string str34 = string.Format("EMITIU PROTOCOLO DE {0} DOCUMENTO{1}", count1, obj1); + long num2 = (long)0; + TipoTela? nullable = new TipoTela?(59); + List> tuples = lista; + baseViewModel.RegistrarAcao(str34, num2, nullable, string.Concat("IDS DOS DOCUMENTOS E SUAS RESPECTIVAS OBSERVAÇÕES:\n", string.Join("\n", + from x in tuples + select string.Concat(x.Item1.ToString(), ": \"", x.Item2, "\"")))); + stringBuilder = null; + stringBuilder1 = null; + } + + public async Task ExecuteRunExtendedDialog(System.Windows.Controls.UserControl dialogControl, string hostName) + { + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + DialogHost.CloseDialogCommand.Execute(null, null); + return (obj == null ? false : (bool)obj); + } + + public async Task ExecuteRunExtendedDialogAdvertising(System.Windows.Controls.UserControl dialogControl, string hostName) + { + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandlerArquivo)); + } + + public async Task> ExecuteRunExtendedDialogAnexar(System.Windows.Controls.UserControl dialogControl, string hostName) + { + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + List arquivoDigitals = (List)await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandlerArquivo)); + return arquivoDigitals; + } + + public async Task ExecuteRunExtendedDialogCopia(System.Windows.Controls.UserControl dialogControl, string hostName) + { + Copia copium; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + if (!(obj is bool)) + { + copium = (Copia)obj; + } + else + { + copium = null; + } + return copium; + } + + public async Task ExecuteRunExtendedDialogCopiarCliente(System.Windows.Controls.UserControl dialogControl, string hostName) + { + Cliente cliente; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + if (!(obj is bool)) + { + cliente = (Cliente)obj; + } + else + { + cliente = null; + } + return cliente; + } + + public async Task> ExecuteRunExtendedDialogExtratoComissao(System.Windows.Controls.UserControl dialogControl, string hostName) + { + List notaFiscals; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + if (!(obj is bool)) + { + notaFiscals = (List)obj; + } + else + { + notaFiscals = null; + } + return notaFiscals; + } + + public async Task ExecuteRunExtendedDialogInstalacoes(System.Windows.Controls.UserControl dialogControl, string hostName) + { + Instalacao instalacao; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + object obj1 = obj; + if (obj1 == null || obj1 is bool && !(bool)obj1) + { + instalacao = null; + } + else + { + instalacao = (Instalacao)obj; + } + return instalacao; + } + + public async Task ExecuteRunExtendedDialogPrint(System.Windows.Controls.UserControl dialogControl, string hostName) + { + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + ConfiguracaoImpressao configuracaoImpressao = (ConfiguracaoImpressao)await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + return configuracaoImpressao; + } + + public async Task ExecuteRunExtendedDialogProspeccao(System.Windows.Controls.UserControl dialogControl, string hostName) + { + Prospeccao prospeccao; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + if (!(obj is bool)) + { + prospeccao = (Prospeccao)obj; + } + else + { + prospeccao = null; + } + return prospeccao; + } + + public async Task ExecuteRunExtendedDialogSenha(System.Windows.Controls.UserControl dialogControl, string hostName) + { + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + bool? nullable = (bool?)await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + return nullable; + } + + public void ExtendedClosingEventHandler(object sender, DialogClosingEventArgs eventArgs) + { + this.IsEnabled = true; + Window window = System.Windows.Application.Current.Windows.OfType().SingleOrDefault((Window x) => x.IsActive); + Extentions.FindVisualChildren(window).ToList().ForEach((WebEditor x) => { + if (!x.IsReadOnly) + { + x.Visibility = Visibility.Visible; + } + }); + Extentions.FindVisualChildren(window).Any((DrawerHost x) => { + if (x.get_IsLeftDrawerOpen() || x.get_IsBottomDrawerOpen() || x.get_IsRightDrawerOpen()) + { + return true; + } + return x.get_IsTopDrawerOpen(); + }); + } + + public void ExtendedClosingEventHandlerArquivo(object sender, DialogClosingEventArgs eventArgs) + { + this.IsEnabled = true; + Extentions.FindVisualChildren(System.Windows.Application.Current.Windows.OfType().SingleOrDefault((Window x) => x.IsActive)).Any((DrawerHost x) => { + if (x.get_IsLeftDrawerOpen() || x.get_IsBottomDrawerOpen() || x.get_IsRightDrawerOpen()) + { + return true; + } + return x.get_IsTopDrawerOpen(); + }); + } + + public void ExtendedOpenedEventHandler(object sender, DialogOpenedEventArgs eventargs) + { + this.IsEnabled = false; + } + + internal DialogHost GetHost() + { + DialogHost dialogHost = Extentions.FindVisualChildren(System.Windows.Application.Current.Windows.OfType().SingleOrDefault((Window x) => x.IsActive)).FirstOrDefault(); + if (dialogHost == null) + { + foreach (Window window in System.Windows.Application.Current.Windows.OfType()) + { + dialogHost = Extentions.FindVisualChildren(window).FirstOrDefault(); + if (dialogHost == null || dialogHost.get_IsOpen()) + { + continue; + } + if (dialogHost != null && dialogHost.get_IsOpen()) + { + return null; + } + return dialogHost; + } + } + if (dialogHost != null && dialogHost.get_IsOpen()) + { + return null; + } + return dialogHost; + } + + public double GetWindowHeight() + { + return System.Windows.Application.Current.Windows.OfType().SingleOrDefault((Window x) => x.IsActive).ActualHeight; + } + + private void HabilitarMenu(bool enable) + { + this.EnableMainMenu = enable; + } + + private void HabilitarMenuSecundario(bool enable) + { + this.EnableMenu = enable; + } + + public async Task ImprimirFornecedor(List fornecedores) + { + string str; + string str1; + string str2; + string str3; + string str4; + string str5; + ParcelaServico parcelaServico = new ParcelaServico(); + string str6 = "RELATÓRIO DE FORNECEDORES"; + str6 = string.Concat(str6, "
RELATÓRIO DE FORNECEDORES

"); + str6 = string.Concat(str6, "
"); + str6 = string.Concat(str6, ""); + int num = 1; + str6 = string.Concat(str6, ""); + str6 = string.Concat(str6, ""); + str6 = string.Concat(str6, ""); + str6 = string.Concat(str6, ""); + str6 = string.Concat(str6, ""); + str6 = string.Concat(str6, ""); + str6 = string.Concat(str6, ""); + foreach (Fornecedor fornecedore in fornecedores) + { + string[] nome = new string[] { str6, ""; + str6 = string.Concat(nome); + string[] documento = new string[] { str6, ""; + str6 = string.Concat(documento); + string[] endereco = new string[] { str6, ""; + str6 = string.Concat(endereco); + string[] email = new string[] { str6, ""; + str6 = string.Concat(email); + if (fornecedore.get_Documento() == null) + { + str4 = ""; + } + else + { + str4 = (Gestor.Common.Validation.ValidationHelper.OnlyNumber(fornecedore.get_Documento()).Length > 11 ? "JURÍDICA" : "FÍSICA"); + } + string str7 = str4; + string[] strArrays = new string[] { str6, ""; + str6 = string.Concat(strArrays); + if (num != 1) + { + num++; + } + else + { + num = 0; + } + } + DateTime networkTime = Funcoes.GetNetworkTime(); + string nome1 = Recursos.Usuario.get_Nome(); + str6 = string.Concat(str6, "
NOMECPF/CNPJENDEREÇOE-MAILTIPO PESSOA
"; + nome[4] = fornecedore.get_Nome(); + nome[5] = ""; + documento[4] = fornecedore.get_Documento(); + documento[5] = ""; + endereco[4] = fornecedore.get_Endereco(); + endereco[5] = ""; + email[4] = fornecedore.get_Email(); + email[5] = ""; + strArrays[4] = str7; + strArrays[5] = "
"); + str6 = string.Concat(str6, string.Format("Emitido pelo usuário: {0}, data e hora: {1}.", nome1, networkTime)); + str6 = string.Concat(str6, ""); + string tempPath = Path.GetTempPath(); + string str8 = string.Format("{0}FORNECEDORES_{1:ddMMyyyyhhmmss}.html", tempPath, networkTime); + StreamWriter streamWriter = new StreamWriter(str8, true, Encoding.UTF8); + streamWriter.Write(str6); + streamWriter.Close(); + Process.Start(str8); + } + + private Gestor.Application.Model.Configuracoes LoadConfiguracoes() + { + this.CriarConfiguracaoPadrao("config.json"); + return JsonConvert.DeserializeObject(File.ReadAllText("config.json")); + } + + private async Task LoadDialogAdertisingPromo() + { + DialogAdvertising dialogAdvertising; + object empty; + Gestor.Application.Model.Configuracoes configuraco = this.LoadConfiguracoes(); + JObject jObject = await this.LoadJsonAdvertising(Address.JsonPromo()); + if (jObject != null) + { + JToken item = jObject.get_Item("Imagem"); + if (item != null) + { + empty = Extensions.Value(item); + } + else + { + empty = null; + } + if (empty == null) + { + empty = string.Empty; + } + string str = (string)empty; + if (configuraco.LinkPromo == str || configuraco.NaoverPromo) + { + dialogAdvertising = null; + } + else + { + dialogAdvertising = new DialogAdvertising(jObject, true); + } + } + else + { + dialogAdvertising = null; + } + configuraco = null; + return dialogAdvertising; + } + + public void Loading(bool isLoading) + { + Grid progressRing = App.ProgressRing; + if (progressRing == null) + { + return; + } + Dispatcher dispatcher = progressRing.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => this.LoadingThread(isLoading))); + } + + public void LoadingThread(bool isLoading) + { + this.IsVisible = (isLoading ? Visibility.Collapsed : Visibility.Visible); + App.ProgressRing.Visibility = (isLoading ? Visibility.Visible : Visibility.Collapsed); + this.IsEnabled = !isLoading; + } + + private async Task LoadJsonAdvertising(Uri location) + { + JObject jObject; + JObject jObject1; + using (HttpClient httpClient = new HttpClient()) + { + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + httpClient.set_Timeout(TimeSpan.FromSeconds(20)); + HttpResponseMessage async = await httpClient.GetAsync(location); + if (!async.get_IsSuccessStatusCode()) + { + jObject1 = null; + } + else + { + jObject1 = JObject.Parse(await async.get_Content().ReadAsStringAsync()); + } + jObject = jObject1; + } + return jObject; + } + + public void OnPropertyChanged([CallerMemberName] string name = "") + { + PropertyChangedEventHandler propertyChangedEventHandler = this.PropertyChanged; + if (propertyChangedEventHandler == null) + { + return; + } + propertyChangedEventHandler(this, new PropertyChangedEventArgs(name)); + } + + public bool Permissao(TipoTela tipoTela) + { + if (Recursos.Usuario.get_Id() == 0) + { + return false; + } + PermissaoUsuario permissaoUsuario = this.ServicoPermissUsuario.BuscarPermissao(Recursos.Usuario, tipoTela); + if (permissaoUsuario == null) + { + return true; + } + return permissaoUsuario.get_Consultar(); + } + + public async Task PermissaoArquivoDigital(TipoArquivoDigital tela) + { + bool flag; + bool flag1; + this.EnableIncluir = false; + this.EnableExcluir = false; + if (Recursos.Usuario.get_Id() != 0) + { + PermissaoArquivoDigital permissaoArquivoDigital = await this.ServicoPermissArquivoDigital.VerificarPermissao(Recursos.Usuario, tela); + BaseViewModel baseViewModel = this; + flag = (permissaoArquivoDigital != null ? permissaoArquivoDigital.get_Incluir() : true); + baseViewModel._incluirPermissEnabled = flag; + BaseViewModel baseViewModel1 = this; + flag1 = (permissaoArquivoDigital != null ? permissaoArquivoDigital.get_Excluir() : true); + baseViewModel1._excluirPermissEnabled = flag1; + } + } + + public async Task PermissaoConsultar(TipoTela tela) + { + bool flag; + bool consultar; + if (Recursos.Usuario.get_Id() != 0) + { + PermissaoUsuario permissaoUsuario = await this.ServicoPermissUsuario.VerificarPermissao(Recursos.Usuario, tela); + if (permissaoUsuario != null) + { + consultar = permissaoUsuario.get_Consultar(); + } + else + { + consultar = true; + } + flag = consultar; + } + else + { + flag = true; + } + return flag; + } + + public async Task PermissaoTela(TipoTela tela) + { + bool flag; + bool flag1; + bool flag2; + bool flag3; + bool flag4; + bool flag5; + this.EnableIncluir = false; + this.EnableAlterar = false; + this.EnableExcluir = false; + if (Recursos.Usuario.get_Id() != 0) + { + PermissaoUsuario permissaoUsuario = await this.ServicoPermissUsuario.VerificarPermissao(Recursos.Usuario, tela); + if (tela == 5) + { + BaseViewModel baseViewModel = this; + flag3 = (permissaoUsuario != null ? permissaoUsuario.get_Incluir() : true); + baseViewModel.IncluirParcelaEnabled = flag3; + BaseViewModel baseViewModel1 = this; + flag4 = (permissaoUsuario != null ? permissaoUsuario.get_Alterar() : true); + baseViewModel1.AlterarParcelaEnabled = flag4; + BaseViewModel baseViewModel2 = this; + flag5 = (permissaoUsuario != null ? permissaoUsuario.get_Excluir() : true); + baseViewModel2.ExcluirParcelaEnabled = flag5; + } + else if (tela == 24 || tela == 26 || tela == 29 || tela == 28 || tela == 27) + { + this._incluirPermissEnabled = true; + this._alterarPermissEnabled = true; + this._excluirPermissEnabled = true; + } + else + { + BaseViewModel baseViewModel3 = this; + flag = (permissaoUsuario != null ? permissaoUsuario.get_Incluir() : true); + baseViewModel3._incluirPermissEnabled = flag; + BaseViewModel baseViewModel4 = this; + flag1 = (permissaoUsuario != null ? permissaoUsuario.get_Alterar() : true); + baseViewModel4._alterarPermissEnabled = flag1; + BaseViewModel baseViewModel5 = this; + flag2 = (permissaoUsuario != null ? permissaoUsuario.get_Excluir() : true); + baseViewModel5._excluirPermissEnabled = flag2; + } + } + } + + public void RegistrarAcao(string descricao, long entidadeId, TipoTela? tela = null, object obs = null) + { + RegistroAcao registroAcao = new RegistroAcao(); + registroAcao.set_Descricao(descricao); + registroAcao.set_EntidadeId(entidadeId); + registroAcao.set_Tela(tela); + (new ApoliceServico()).SalvarAcao(registroAcao, obs); + } + + public void RegistrarAcao(string descricao, Relatorio? relatorio, object obs = null) + { + RegistroAcao registroAcao = new RegistroAcao(); + registroAcao.set_Relatorio(relatorio); + registroAcao.set_Descricao(descricao); + (new ApoliceServico()).SalvarAcao(registroAcao, obs); + } + + public bool Restricao(TipoRestricao tipoRestricao) + { + if (Recursos.Usuario.get_Id() == 0) + { + return false; + } + RestricaoUsuario restricaoUsuario = this.ServicoRestriUsuario.BuscarRestricao(Recursos.Usuario, tipoRestricao); + if (restricaoUsuario == null) + { + return false; + } + return restricaoUsuario.get_Restricao(); + } + + public async Task Salvar(IndiceArquivoDigital indice) + { + string str; + bool arquivo; + Guid guid; + if (indice.get_Id() != 0) + { + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital = await this.ArquivoDigitalServico.BuscarPorId(indice.get_IdArquivoDigital(), indice.get_Bd()); + if (arquivoDigital != null) + { + arquivo = arquivoDigital.get_Arquivo(); + } + else + { + arquivo = false; + } + if (!arquivo || arquivoDigital.get_Extensao() == null) + { + str = null; + } + else + { + string tempPath = Path.GetTempPath(); + Guid? azureGuid = arquivoDigital.get_AzureGuid(); + guid = (azureGuid.HasValue ? azureGuid.GetValueOrDefault() : Guid.NewGuid()); + string str1 = string.Format("{0}{1}{2}", tempPath, guid, Gestor.Common.Validation.ValidationHelper.GetDefaultExtension(arquivoDigital.get_Extensao())); + using (BinaryWriter binaryWriter = new BinaryWriter(File.Open(str1, FileMode.Create))) + { + binaryWriter.Write(arquivoDigital.get_Arquivo()); + } + str = str1; + } + } + else + { + str = null; + } + return str; + } + + public async Task SalvarAttachments(List arquivos, TipoArquivoDigital tipoAd, long id) + { + bool flag; + if (arquivos == null || arquivos.Count == 0) + { + flag = false; + } + else + { + arquivos.ForEach((Gestor.Model.Domain.Common.ArquivoDigital x) => { + x.set_IdCliente((tipoAd == 1 ? id : (long)0)); + x.set_IdDocumento((tipoAd == 2 ? id : (long)0)); + x.set_IdParcela((tipoAd == 3 ? id : (long)0)); + x.set_IdItem((tipoAd == 4 ? id : (long)0)); + x.set_IdSinistro((tipoAd == 5 ? id : (long)0)); + x.set_IdVendedor((tipoAd == 6 ? id : (long)0)); + x.set_IdUsuario((tipoAd == 12 ? id : (long)0)); + x.set_IdSeguradora((tipoAd == 8 ? id : (long)0)); + x.set_IdExtrato((tipoAd == 7 ? id : (long)0)); + x.set_IdLancamento((tipoAd == 9 ? id : (long)0)); + x.set_IdFornecedor((tipoAd == 10 ? id : (long)0)); + x.set_IdProspeccao((tipoAd == 11 ? id : (long)0)); + x.set_IdSocio((tipoAd == 14 ? id : (long)0)); + x.set_IdTarefa((tipoAd == 15 ? id : (long)0)); + x.set_IdNotaFiscal((tipoAd == 16 ? id : (long)0)); + x.set_IdEstipulante((tipoAd == 17 ? id : (long)0)); + x.set_IdEmpresa(Recursos.Usuario.get_IdEmpresa()); + }); + switch (tipoAd) + { + default: + { + break; + } + } + await this.ArquivoDigitalServico.Insert(arquivos); + flag = (this.ArquivoDigitalServico.Sucesso ? true : false); + } + return flag; + } + + public async Task>> SalvarProspeccao(Prospeccao prospecao) + { + List> keyValuePairs; + bool count; + string str; + List anexos; + Prospeccao prospeccao; + List> keyValuePairs1 = prospecao.Validate(); + if (keyValuePairs1.Count <= 0) + { + anexos = prospecao.get_Anexos(); + if (prospecao.get_Tarefa().get_Id() == 0) + { + prospecao.get_Tarefa().set_Cliente(prospecao.get_Nome()); + Tarefa tarefa = prospecao.get_Tarefa(); + DateTime? vigenciaFinal = prospecao.get_VigenciaFinal(); + if (vigenciaFinal.HasValue) + { + str = vigenciaFinal.GetValueOrDefault().ToString("d"); + } + else + { + str = null; + } + tarefa.set_Titulo(string.Concat("PROSPECÇÃO ", str)); + prospecao.get_Tarefa().set_Referencia(prospecao.get_Item()); + Tarefa tarefa1 = prospecao.get_Tarefa(); + object[] nome = new object[] { Recursos.Usuario.get_Nome(), Funcoes.GetNetworkTime(), Environment.NewLine, prospecao.get_Observacao() }; + tarefa1.set_Descricao(string.Format("{0} {1:g} {2}{3}", nome)); + } + prospeccao = await (new ProspeccaoServico()).Salvar(prospecao); + List arquivoDigitals = anexos; + if (arquivoDigitals != null) + { + count = arquivoDigitals.Count > 0; + } + else + { + count = false; + } + if (count) + { + await this.SalvarAttachments(anexos, 11, prospeccao.get_Id()); + } + if (prospeccao.get_Tarefa() != null && prospecao.get_AbrirTarefa() && prospeccao != null && prospeccao.get_Id() > (long)0) + { + Tarefa tarefa2 = prospeccao.get_Tarefa(); + this.ShowDrawer(new TarefaDrawer(tarefa2, true), 0, false); + } + keyValuePairs = null; + } + else + { + keyValuePairs = keyValuePairs1; + } + anexos = null; + prospeccao = null; + return keyValuePairs; + } + + internal async Task ShowCopiaDialog(Copia copia) + { + Copia copium; + string str; + DialogHost host = this.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogCopia dialogCopium = new DialogCopia(copia); + BaseViewModel baseViewModel = this; + DialogCopia dialogCopium1 = dialogCopium; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + copium = await baseViewModel.ExecuteRunExtendedDialogCopia(dialogCopium1, str); + } + else + { + copium = null; + } + return copium; + } + + internal async Task ShowCopiarCliente() + { + Cliente cliente; + string str; + DialogHost host = this.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogCopiarCliente dialogCopiarCliente = new DialogCopiarCliente(); + BaseViewModel baseViewModel = this; + DialogCopiarCliente dialogCopiarCliente1 = dialogCopiarCliente; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + cliente = await baseViewModel.ExecuteRunExtendedDialogCopiarCliente(dialogCopiarCliente1, str); + } + else + { + cliente = null; + } + return cliente; + } + + internal async Task ShowDialogAdvertising(bool root = false) + { + string str; + try + { + DialogHost host = null; + if (!root) + { + host = this.GetHost(); + if (host != null && host.get_IsOpen()) + { + return; + } + } + DialogAdvertising dialogAdvertising = await this.CreateDialogAdvertising(); + if (dialogAdvertising != null) + { + BaseViewModel baseViewModel = this; + DialogAdvertising dialogAdvertising1 = dialogAdvertising; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + await baseViewModel.ExecuteRunExtendedDialogAdvertising(dialogAdvertising1, str); + host = null; + } + else + { + return; + } + } + catch + { + } + } + + internal async Task> ShowDialogAnexar(List arquivos, bool root = false) + { + List arquivoDigitals; + string str; + DialogHost host = null; + if (!root) + { + host = this.GetHost(); + if (host != null && host.get_IsOpen()) + { + arquivoDigitals = arquivos; + return arquivoDigitals; + } + } + DialogAnexar dialogAnexar = new DialogAnexar(arquivos); + BaseViewModel baseViewModel = this; + DialogAnexar dialogAnexar1 = dialogAnexar; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + arquivoDigitals = await baseViewModel.ExecuteRunExtendedDialogAnexar(dialogAnexar1, str); + return arquivoDigitals; + } + + internal async Task ShowDialogPrint(Relatorio relatorio, Type tipo) + { + ConfiguracaoImpressao configuracaoImpressao; + string str; + DialogHost host = this.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogPrint dialogPrint = new DialogPrint(relatorio, tipo); + BaseViewModel baseViewModel = this; + DialogPrint dialogPrint1 = dialogPrint; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + configuracaoImpressao = await baseViewModel.ExecuteRunExtendedDialogPrint(dialogPrint1, str); + } + else + { + configuracaoImpressao = null; + } + return configuracaoImpressao; + } + + internal void ShowDrawer(object content, int position, bool close = true) + { + Window window = System.Windows.Application.Current.Windows.OfType().SingleOrDefault((Window x) => x.IsActive); + DrawerHost drawerHost = Extentions.FindVisualChildren(window).FirstOrDefault(); + Extentions.FindVisualChildren(window).ToList().ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + if (drawerHost == null) + { + return; + } + switch (position) + { + case 1: + { + drawerHost.set_TopDrawerContent(content); + drawerHost.set_IsTopDrawerOpen(true); + drawerHost.set_TopDrawerCloseOnClickAway(close); + return; + } + case 2: + { + drawerHost.set_LeftDrawerContent(content); + drawerHost.set_IsLeftDrawerOpen(true); + drawerHost.set_LeftDrawerCloseOnClickAway(close); + return; + } + case 3: + { + drawerHost.set_BottomDrawerContent(content); + drawerHost.set_IsBottomDrawerOpen(true); + drawerHost.set_BottomDrawerCloseOnClickAway(close); + return; + } + default: + { + if (!drawerHost.get_IsRightDrawerOpen() || drawerHost.get_RightDrawerContent() != null && !(drawerHost.get_RightDrawerContent().GetType() != content.GetType())) + { + break; + } + else + { + drawerHost.set_LeftDrawerContent(content); + drawerHost.set_IsLeftDrawerOpen(true); + drawerHost.set_LeftDrawerCloseOnClickAway(close); + return; + } + } + } + drawerHost.set_IsRightDrawerOpen(true); + drawerHost.set_RightDrawerContent(content); + drawerHost.set_RightDrawerCloseOnClickAway(close); + } + + internal async Task> ShowExtratoComissaoDialog(List seguradoras) + { + List notaFiscals; + string str; + DialogHost host = this.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogExtratoComissao dialogExtratoComissao = new DialogExtratoComissao(seguradoras); + BaseViewModel baseViewModel = this; + DialogExtratoComissao dialogExtratoComissao1 = dialogExtratoComissao; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + notaFiscals = await baseViewModel.ExecuteRunExtendedDialogExtratoComissao(dialogExtratoComissao1, str); + } + else + { + notaFiscals = null; + } + return notaFiscals; + } + + internal async Task ShowInstalacoes(List instalacoes) + { + Instalacao instalacao; + string str; + DialogHost host = this.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogInstalacoes dialogInstalaco = new DialogInstalacoes(instalacoes); + BaseViewModel baseViewModel = this; + DialogInstalacoes dialogInstalaco1 = dialogInstalaco; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + instalacao = await baseViewModel.ExecuteRunExtendedDialogInstalacoes(dialogInstalaco1, str); + } + else + { + instalacao = null; + } + return instalacao; + } + + internal async Task ShowMedalha(int liquido, int comissao, int resultado, int media) + { + string str; + DialogHost host = this.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogMedalha dialogMedalha = new DialogMedalha(liquido, comissao, resultado, media); + BaseViewModel baseViewModel = this; + DialogMedalha dialogMedalha1 = dialogMedalha; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + await baseViewModel.ExecuteRunExtendedDialog(dialogMedalha1, str); + } + } + + internal async Task ShowMessage(string message, string accept = "OK", string cancel = "", bool root = false) + { + bool flag; + string str; + DialogHost host = null; + if (!root) + { + host = this.GetHost(); + if (host == null) + { + flag = false; + return flag; + } + } + DefaultDialog defaultDialog = new DefaultDialog(); + DialogViewModel dialogViewModel = new DialogViewModel() + { + AcceptContent = accept, + CancelContent = cancel, + Message = message + }; + defaultDialog.DataContext = dialogViewModel; + DefaultDialog defaultDialog1 = defaultDialog; + BaseViewModel baseViewModel = this; + DefaultDialog defaultDialog2 = defaultDialog1; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + flag = await baseViewModel.ExecuteRunExtendedDialog(defaultDialog2, str); + return flag; + } + + internal async Task ShowMessage(List> pairs, string message, string accept, string cancel = "") + { + bool flag; + string str; + DialogHost host = this.GetHost(); + if (host == null || !host.get_IsOpen()) + { + ErrorDialog errorDialog = new ErrorDialog(); + ErrorDialogViewModel errorDialogViewModel = new ErrorDialogViewModel(); + List> keyValuePairs = pairs; + errorDialogViewModel.Erros = ( + from pair in keyValuePairs + select new KeyValuePair((pair.Key.Contains("|") ? pair.Key.Substring(pair.Key.IndexOf("|", StringComparison.Ordinal) + 1) : pair.Key), pair.Value)).ToList>(); + errorDialogViewModel.AcceptContent = accept; + errorDialogViewModel.CancelContent = cancel; + errorDialogViewModel.Message = message; + errorDialog.DataContext = errorDialogViewModel; + ErrorDialog errorDialog1 = errorDialog; + BaseViewModel baseViewModel = this; + ErrorDialog errorDialog2 = errorDialog1; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + flag = await baseViewModel.ExecuteRunExtendedDialog(errorDialog2, str); + } + else + { + flag = false; + } + return flag; + } + + internal async Task ShowProspeccaoDialog(Prospeccao prospecao) + { + Prospeccao prospeccao; + string str; + DialogHost host = this.GetHost(); + if (host == null || !host.get_IsOpen()) + { + ProspeccaoDialog prospeccaoDialog = new ProspeccaoDialog(prospecao); + BaseViewModel baseViewModel = this; + ProspeccaoDialog prospeccaoDialog1 = prospeccaoDialog; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + prospeccao = await baseViewModel.ExecuteRunExtendedDialogProspeccao(prospeccaoDialog1, str); + } + else + { + prospeccao = null; + } + return prospeccao; + } + + internal async Task ShowSenha(string mensagem) + { + bool? nullable; + string str; + DialogHost host = this.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogSenhaAdm dialogSenhaAdm = new DialogSenhaAdm(mensagem); + BaseViewModel baseViewModel = this; + DialogSenhaAdm dialogSenhaAdm1 = dialogSenhaAdm; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + nullable = await baseViewModel.ExecuteRunExtendedDialogSenha(dialogSenhaAdm1, str); + } + else + { + nullable = new bool?(false); + } + return nullable; + } + + public void ToggleSnackBar(string message, bool active = true) + { + Snackbar snackbar = Extentions.FindVisualChildren(System.Windows.Application.Current.Windows.OfType().SingleOrDefault((Window x) => x.IsActive)).FirstOrDefault(); + if (snackbar == null) + { + return; + } + snackbar.get_Message().Content = message; + snackbar.set_IsActive(active); + if (!active) + { + return; + } + Task.Factory.StartNew(new Action(this.CloseSlackBar)); + } + + public async Task> ValidateAttachment(List attachments, List files) + { + char chr; + bool flag; + string lower; + object obj; + string upper = string.Concat("Os Arquivos Abaixo não podem ser anexados pois não possuem Formatos válidos, são maiores que o permitido ou já foram anexados!", Environment.NewLine, Environment.NewLine).ToUpper(); + List strs = new List(); + bool flag1 = false; + foreach (string file in files) + { + int num = 0; + try + { + flag = (attachments == null ? false : attachments.Exists((Gestor.Model.Domain.Common.ArquivoDigital a) => { + string str; + string str1 = Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(a.get_Descricao().ToUpper()); + string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file); + if (fileNameWithoutExtension != null) + { + str = Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(fileNameWithoutExtension.ToUpper()); + } + else + { + str = null; + } + return str1 == str; + })); + if (!flag) + { + FileInfo fileInfo = new FileInfo(file); + if (fileInfo.Length > (long)1024) + { + long length = fileInfo.Length / (long)1024; + obj = (Recursos.Empresa.get_MaxFileSize() > 0 ? Recursos.Empresa.get_MaxFileSize() : 14336); + if (length > (long)obj) + { + upper = string.Concat(upper, Path.GetFileName(file)); + flag1 = true; + continue; + } + } + string extension = Path.GetExtension(file); + if (extension != null) + { + lower = extension.ToLower(); + } + else + { + lower = null; + } + string str2 = lower; + if (str2 != null) + { + int length1 = str2.Length; + if (length1 == 4) + { + chr = str2[1]; + if (chr <= 't') + { + switch (chr) + { + case 'a': + { + if (str2 == ".amr") + { + break; + } + goto Label1; + } + case 'b': + { + if (str2 == ".bmp") + { + break; + } + goto Label1; + } + case 'c': + { + goto Label1; + } + case 'd': + { + if (str2 == ".doc") + { + break; + } + goto Label1; + } + case 'e': + { + if (str2 == ".eml") + { + break; + } + goto Label1; + } + default: + { + switch (chr) + { + case 'j': + { + if (str2 == ".jpg") + { + goto Label2; + } + goto Label1; + } + case 'm': + { + if (str2 == ".msg") + { + goto Label2; + } + goto Label1; + } + case 'o': + { + if (str2 == ".ogg") + { + goto Label2; + } + goto Label1; + } + case 'p': + { + if (str2 == ".png" || str2 == ".pdf") + { + goto Label2; + } + goto Label1; + } + case 'r': + { + if (str2 == ".rar") + { + goto Label2; + } + goto Label1; + } + case 't': + { + if (str2 == ".txt") + { + goto Label2; + } + goto Label1; + } + default: + { + goto Label1; + } + } + break; + } + } + } + else if (chr == 'x') + { + if (str2 == ".xls") + { + goto Label2; + } + goto Label1; + } + else if (chr == 'z') + { + if (str2 == ".zip") + { + goto Label2; + } + goto Label1; + } + else + { + goto Label1; + } + } + else if (length1 == 5) + { + chr = str2[2]; + switch (chr) + { + case 'l': + { + if (str2 == ".xlsx") + { + break; + } + goto Label1; + } + case 'm': + case 'n': + { + goto Label1; + } + case 'o': + { + if (str2 == ".docx") + { + break; + } + goto Label1; + } + case 'p': + { + if (str2 == ".jpeg") + { + break; + } + goto Label1; + } + default: + { + if (chr != 's') + { + goto Label1; + } + else if (str2 == ".json") + { + break; + } + else + { + goto Label1; + } + } + } + } + else + { + goto Label1; + } + Label2: + strs.Add(file); + goto Label0; + } + Label1: + upper = string.Concat(upper, Path.GetFileName(file)); + Label0: + } + else + { + upper = string.Concat(upper, Path.GetFileName(file)); + flag1 = true; + continue; + } + } + catch (Exception exception) + { + num = 1; + } + if (num != 1) + { + continue; + } + string[] newLine = new string[] { "NÃO FOI POSSÍVEL CARREGAR O ARQUIVO ", file, ".", Environment.NewLine, "O ARQUIVO ESTÁ INACESSÍVEL OU SENDO UTILIZADO POR OUTRO PROCESSO." }; + await this.ShowMessage(string.Concat(newLine), "OK", "", false); + } + if (flag1) + { + await this.ShowMessage(string.Concat(upper, Environment.NewLine, Environment.NewLine, "Favor Corrija antes de tentar novamente.").ToUpper(), "OK", "", false); + } + return strs; + } + + public async Task VerificarAcesso(long id) + { + string str; + string str1; + string str2 = null; + Usuario usuario = await (new UsuarioServico()).BuscarUsuarioPorId(id); + if (usuario != null) + { + List strs = new List(); + List strs1 = new List() + { + "SEGUNDAS-FEIRAS", + "TERÇAS-FEIRAS", + "QUARTAS-FEIRAS", + "QUINTAS-FEIRAS", + "SEXTAS-FEIRAS", + "SÁBADOS", + "DOMINGOS" + }; + List strs2 = strs1; + bool? segunda = usuario.get_Segunda(); + if (!segunda.GetValueOrDefault() & segunda.HasValue) + { + strs.Add("SEGUNDAS-FEIRAS"); + strs2.Remove("SEGUNDAS-FEIRAS"); + } + segunda = usuario.get_Terca(); + if (!segunda.GetValueOrDefault() & segunda.HasValue) + { + strs.Add("TERÇAS-FEIRAS"); + strs2.Remove("TERÇAS-FEIRAS"); + } + segunda = usuario.get_Quarta(); + if (!segunda.GetValueOrDefault() & segunda.HasValue) + { + strs.Add("QUARTAS-FEIRAS"); + strs2.Remove("QUARTAS-FEIRAS"); + } + segunda = usuario.get_Quinta(); + if (!segunda.GetValueOrDefault() & segunda.HasValue) + { + strs.Add("QUINTAS-FEIRAS"); + strs2.Remove("QUINTAS-FEIRAS"); + } + segunda = usuario.get_Sexta(); + if (!segunda.GetValueOrDefault() & segunda.HasValue) + { + strs.Add("SEXTAS-FEIRAS"); + strs2.Remove("SEXTAS-FEIRAS"); + } + segunda = usuario.get_Sabado(); + if (!segunda.GetValueOrDefault() & segunda.HasValue) + { + strs.Add("SÁBADOS"); + strs2.Remove("SÁBADOS"); + } + segunda = usuario.get_Domingo(); + if (!segunda.GetValueOrDefault() & segunda.HasValue) + { + strs.Add("DOMINGOS"); + strs2.Remove("DOMINGOS"); + } + if (strs.Count == 7) + { + str1 = "RESTRITO TODOS OS DIAS"; + } + else if (strs.Count > 3) + { + str1 = "APENAS PERMITIDO "; + for (int i = 0; i < strs2.Count; i++) + { + if (i >= strs2.Count - 2) + { + str1 = (i != strs2.Count - 2 ? string.Concat(str1, strs2[i]) : string.Concat(str1, strs2[i], " E ")); + } + else + { + str1 = string.Concat(str1, strs2[i], ", "); + } + } + } + else + { + str1 = "RESTRITO "; + for (int j = 0; j < strs.Count; j++) + { + if (j >= strs.Count - 2) + { + str1 = (j != strs.Count - 2 ? string.Concat(str1, strs[j]) : string.Concat(str1, strs[j], " E ")); + } + else + { + str1 = string.Concat(str1, strs[j], ", "); + } + } + } + DateTime networkTime = Funcoes.GetNetworkTime(); + switch (networkTime.DayOfWeek) + { + case DayOfWeek.Sunday: + { + segunda = usuario.get_Domingo(); + if (!(!segunda.GetValueOrDefault() & segunda.HasValue)) + { + break; + } + str = string.Concat("ACESSO ", str1, ". CONTATE O ADMINISTRADOR DO SISTEMA"); + str2 = null; + return str; + } + case DayOfWeek.Monday: + { + segunda = usuario.get_Segunda(); + if (!(!segunda.GetValueOrDefault() & segunda.HasValue)) + { + break; + } + str = string.Concat("ACESSO ", str1, ". CONTATE O ADMINISTRADOR DO SISTEMA"); + str2 = null; + return str; + } + case DayOfWeek.Tuesday: + { + segunda = usuario.get_Terca(); + if (!(!segunda.GetValueOrDefault() & segunda.HasValue)) + { + break; + } + str = string.Concat("ACESSO ", str1, ". CONTATE O ADMINISTRADOR DO SISTEMA"); + str2 = null; + return str; + } + case DayOfWeek.Wednesday: + { + segunda = usuario.get_Quarta(); + if (!(!segunda.GetValueOrDefault() & segunda.HasValue)) + { + break; + } + str = string.Concat("ACESSO ", str1, ". CONTATE O ADMINISTRADOR DO SISTEMA"); + str2 = null; + return str; + } + case DayOfWeek.Thursday: + { + segunda = usuario.get_Quinta(); + if (!(!segunda.GetValueOrDefault() & segunda.HasValue)) + { + break; + } + str = string.Concat("ACESSO ", str1, ". CONTATE O ADMINISTRADOR DO SISTEMA"); + str2 = null; + return str; + } + case DayOfWeek.Friday: + { + segunda = usuario.get_Sexta(); + if (!(!segunda.GetValueOrDefault() & segunda.HasValue)) + { + break; + } + str = string.Concat("ACESSO ", str1, ". CONTATE O ADMINISTRADOR DO SISTEMA"); + str2 = null; + return str; + } + case DayOfWeek.Saturday: + { + segunda = usuario.get_Sabado(); + if (!(!segunda.GetValueOrDefault() & segunda.HasValue)) + { + break; + } + str = string.Concat("ACESSO ", str1, ". CONTATE O ADMINISTRADOR DO SISTEMA"); + str2 = null; + return str; + } + } + if (usuario.get_InicioAcesso().HasValue && usuario.get_FimAcesso().HasValue && (networkTime.TimeOfDay <= usuario.get_InicioAcesso().Value.TimeOfDay || networkTime.TimeOfDay >= usuario.get_FimAcesso().Value.TimeOfDay)) + { + DateTime value = usuario.get_InicioAcesso().Value; + string shortTimeString = value.ToShortTimeString(); + value = usuario.get_FimAcesso().Value; + str2 = string.Concat("USUÁRIO COM PERMISSÃO DE ACESSO ENTRE ", shortTimeString, " E ", value.ToShortTimeString()); + } + str = str2; + } + else + { + str = "DADOS DE ACESSO INVÁLIDOS"; + } + str2 = null; + return str; + } + + public async Task VerificarContrato(Gestor.Model.License.Produto produto, bool message = true, bool root = false) + { + bool flag; + Licenca licenca; + string str; + if (produto == 79) + { + List produtos = LicenseHelper.Produtos; + if (!produtos.Exists((Licenca x) => { + if (x.get_Produto() != 91) + { + return false; + } + return x.get_AcessoLiberado(); + })) + { + List licencas = LicenseHelper.Produtos; + if (!licencas.Exists((Licenca x) => { + if (x.get_Produto() != 81) + { + return false; + } + return x.get_AcessoLiberado(); + })) + { + List produtos1 = LicenseHelper.Produtos; + if (produtos1.Exists((Licenca x) => { + if (x.get_Produto() != 77) + { + return false; + } + return x.get_AcessoLiberado(); + })) + { + flag = true; + return flag; + } + } + else + { + flag = true; + return flag; + } + } + else + { + flag = true; + return flag; + } + } + if (LicenseHelper.Produtos == null || !LicenseHelper.Produtos.Exists((Licenca x) => { + if (x.get_Produto() != produto) + { + return false; + } + return x.get_AcessoLiberado(); + })) + { + if (message) + { + List licencas1 = LicenseHelper.Produtos; + if (licencas1 != null) + { + licenca = licencas1.FirstOrDefault((Licenca x) => x.get_Produto() == produto); + } + else + { + licenca = null; + } + Licenca licenca1 = licenca; + BaseViewModel baseViewModel = this; + str = (licenca1 == null ? string.Concat("VOCÊ NÃO POSSUI O MÓDULO ", EnumHelper.GetDescription(produto), " CONTRATADO") : string.Concat("ACESSO AO MÓDULO ", EnumHelper.GetDescription(produto), " INTERROMPIDO")); + await baseViewModel.ShowMessage(str, "OK", "", root); + } + flag = false; + } + else + { + flag = true; + } + return flag; + } + + public void VerificarEnables(long? id) + { + this._lastId = id; + this.EnableIncluir = (!id.HasValue ? true : id.Value >= (long)0); + this.EnableAlterar = (!id.HasValue ? false : id.Value > (long)0); + this.EnableExcluir = (!id.HasValue ? false : id.Value > (long)0); + this.EnableButtons = (!id.HasValue ? false : id.Value > (long)0); + } + + public async Task VerificarPermissao(TipoTela tela, bool root = false) + { + bool flag; + if (!await this.PermissaoConsultar(tela)) + { + await this.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR ESSA TELA. CONTATE O ADIMINSTRADOR DO SISTEMA.", "OK", "", root); + flag = false; + } + else + { + flag = true; + } + return flag; + } + + public async Task VerificarRestricao(TipoRestricao tipoRestricao, bool root = false, bool showmessage = true) + { + bool flag; + if (Recursos.Usuario.get_Id() != 0) + { + RestricaoUsuario restricaoUsuario = this.ServicoRestriUsuario.BuscarRestricao(Recursos.Usuario, tipoRestricao); + if (restricaoUsuario == null || !restricaoUsuario.get_Restricao()) + { + flag = true; + } + else + { + if (showmessage) + { + await this.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR ESSA TELA. CONTATE O ADMINISTRADOR DO SISTEMA.", "OK", "", root); + } + flag = false; + } + } + else + { + flag = true; + } + return flag; + } + + public async Task VerificarVersao() + { + bool flag; + bool flag1; + try + { + string str = await Gestor.Application.Helpers.Connection.Get(string.Format("Update/Stable?versao={0}", ApplicationHelper.Versao), true, false); + flag1 = (str == null ? false : bool.Parse(str)); + flag = flag1; + } + catch (Exception exception1) + { + Exception exception = exception1; + (new BaseServico()).Registrar(exception, 287, 3, ApplicationHelper.Versao.ToString(), false); + flag = false; + } + if (flag) + { + await this.ShowMessage("HÁ UMA ATUALIZAÇÃO OBRIGATÓRIA A SER FEITA. O PROCESSO SERÁ CANCELADO PARA A ATUALIZAÇÃO", "OK", "", false); + System.Windows.Application.Current.Shutdown(); + } + else + { + ApplicationHelper.ChecagemVersao = Funcoes.GetNetworkTime(); + } + } + + public async Task> VerificaVinculoVendedor(Usuario usuario) + { + List vendedorUsuarios; + if (usuario == null || usuario.get_Id() == 0) + { + vendedorUsuarios = new List(); + } + else + { + vendedorUsuarios = await this.ServicoVendedorUsuario.FindByVinculo(usuario); + } + return vendedorUsuarios; + } + + public event PropertyChangedEventHandler PropertyChanged; + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/DialogAdvertisingViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/DialogAdvertisingViewModel.cs new file mode 100644 index 0000000..abd3dde --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/DialogAdvertisingViewModel.cs @@ -0,0 +1,292 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Model; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using System; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Generic +{ + public class DialogAdvertisingViewModel : BaseViewModel + { + private readonly bool _isPromo; + + private string _urlPesquisa; + + private Visibility _visualizarNaoExibirNovamente = Visibility.Hidden; + + private string _titulo = ""; + + private string _imagem = ""; + + public string Url = ""; + + private bool _naoQuero; + + public string Imagem + { + get + { + return this._imagem; + } + set + { + this._imagem = value; + base.OnPropertyChanged("Imagem"); + } + } + + public bool NaoVer + { + get + { + return this._naoQuero; + } + set + { + this._naoQuero = value; + base.OnPropertyChanged("NaoVer"); + } + } + + public string Titulo + { + get + { + return this._titulo; + } + set + { + this._titulo = value; + base.OnPropertyChanged("Titulo"); + } + } + + public Visibility VisualizarNaoExibirNovamente + { + get + { + return this._visualizarNaoExibirNovamente; + } + set + { + this._visualizarNaoExibirNovamente = value; + base.OnPropertyChanged("VisualizarNaoExibirNovamente"); + } + } + + public DialogAdvertisingViewModel(JObject jsonAd, bool isPromo) + { + bool flag; + bool flag1 = false; + this._isPromo = isPromo; + if (this._isPromo) + { + this.CarregaImagem(jsonAd); + JToken item = jsonAd.get_Item("NaoExibirNovamente"); + if (item != null) + { + flag = Extensions.Value(item); + } + else + { + flag = true; + } + flag1 = flag; + } + else + { + this.CarregaPesquisa(jsonAd); + } + this.VisualizarNaoExibirNovamente = (flag1 ? Visibility.Visible : Visibility.Hidden); + } + + private void CarregaImagem(JObject json) + { + string str; + string str1; + string str2; + if (json == null) + { + return; + } + JToken item = json.get_Item("Titulo"); + if (item != null) + { + str = Extensions.Value(item); + } + else + { + str = null; + } + this.Titulo = str; + JToken jToken = json.get_Item("Url"); + if (jToken != null) + { + str1 = Extensions.Value(jToken); + } + else + { + str1 = null; + } + this.Url = str1; + JToken item1 = json.get_Item("Imagem"); + if (item1 != null) + { + str2 = Extensions.Value(item1); + } + else + { + str2 = null; + } + this.Imagem = str2; + } + + private void CarregaPesquisa(JObject json) + { + string str; + string str1; + string str2; + string str3; + if (json == null) + { + return; + } + JToken item = json.get_Item("Titulo"); + if (item != null) + { + str = Extensions.Value(item); + } + else + { + str = null; + } + this.Titulo = str; + JToken jToken = json.get_Item("Imagem"); + if (jToken != null) + { + str1 = Extensions.Value(jToken); + } + else + { + str1 = null; + } + this.Imagem = str1; + JToken item1 = json.get_Item("UrlPost"); + if (item1 != null) + { + str2 = Extensions.Value(item1); + } + else + { + str2 = null; + } + this._urlPesquisa = str2; + if (Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(this._urlPesquisa)) + { + return; + } + JToken jToken1 = json.get_Item("UrlFixa"); + if (jToken1 != null) + { + str3 = Extensions.Value(jToken1); + } + else + { + str3 = null; + } + this._urlPesquisa = str3; + this.Url = this._urlPesquisa; + } + + public void CriarConfiguracaoPadrao(string configFile) + { + File.WriteAllText(configFile, JsonConvert.SerializeObject(new Gestor.Application.Model.Configuracoes() + { + LinkPromo = "", + NaoverPromo = this.NaoVer + }, 1)); + } + + public void EnviarPesquisa() + { + string str; + try + { + using (HttpClient httpClient = new HttpClient()) + { + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + httpClient.set_Timeout(TimeSpan.FromSeconds(15)); + httpClient.get_DefaultRequestHeaders().TryAddWithoutValidation("company-key", "$2b$10$arV/viDP6N.5KX9sRt/.MOo8Gv5FFvHIx0P6HZyuky51P3ItWBV0u"); + var variable = new { customers = new u003cu003ef__AnonymousType49[] { new { nome = Recursos.Usuario.get_Nome(), email = (Gestor.Common.Validation.ValidationHelper.IsNullOrEmpty(Recursos.Usuario.get_Email()) ? string.Format("{0}-{1}@sememail.com", Recursos.Usuario.get_Id(), ApplicationHelper.IdFornecedor) : Recursos.Usuario.get_Email()), corretora = Recursos.Empresa.get_NomeSocial(), produto = "Gestor", idfornecedor = ApplicationHelper.IdFornecedor } } }; + HttpResponseMessage result = httpClient.PostAsync(this._urlPesquisa, variable.ToHttpContent(null, "application/json")).Result; + if (result.get_IsSuccessStatusCode()) + { + JToken item = JObject.Parse(result.get_Content().ReadAsStringAsync().Result).get_Item("customers"); + if (item != null) + { + JToken jToken = item.get_Item(0); + if (jToken != null) + { + JToken item1 = jToken.get_Item("shortUrl"); + if (item1 != null) + { + str = Extensions.Value(item1); + } + else + { + str = null; + } + } + else + { + str = null; + } + } + else + { + str = null; + } + string str1 = str; + if (!Gestor.Common.Validation.ValidationHelper.IsNullOrEmpty(str1)) + { + this.Url = str1; + } + else + { + return; + } + } + else + { + return; + } + } + } + catch (Exception exception) + { + } + } + + public void SalvaEditarArquivoConfig(bool visto = false) + { + if (!File.Exists("config.json")) + { + this.CriarConfiguracaoPadrao("config.json"); + } + Gestor.Application.Model.Configuracoes naoVer = JsonConvert.DeserializeObject(File.ReadAllText("config.json")); + naoVer.LinkPromo = (this._isPromo ? this.Imagem : this._urlPesquisa); + naoVer.NaoverPromo = this.NaoVer; + File.WriteAllText("config.json", JsonConvert.SerializeObject(naoVer, 1)); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/DialogAnexarViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/DialogAnexarViewModel.cs new file mode 100644 index 0000000..0e87f86 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/DialogAnexarViewModel.cs @@ -0,0 +1,44 @@ +using Gestor.Model.Domain.Common; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Gestor.Application.ViewModels.Generic +{ + public class DialogAnexarViewModel : BaseViewModel + { + private ObservableCollection _arquivos = new ObservableCollection(); + + public ObservableCollection Arquivos + { + get + { + return this._arquivos; + } + set + { + this._arquivos = value; + base.OnPropertyChanged("Arquivos"); + } + } + + public DialogAnexarViewModel(List arquivos) + { + this.Arquivos = new ObservableCollection(arquivos); + } + + public void Remover(ArquivoDigital removido) + { + IEnumerable arquivoDigitals = this.Arquivos.Where((ArquivoDigital x) => { + if (x.get_Descricao() != removido.get_Descricao()) + { + return false; + } + return (int)x.get_Arquivo().Length == (int)removido.get_Arquivo().Length; + }); + this.Arquivos = new ObservableCollection(arquivoDigitals); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/DialogCopiaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/DialogCopiaViewModel.cs new file mode 100644 index 0000000..3386705 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/DialogCopiaViewModel.cs @@ -0,0 +1,168 @@ +using Gestor.Model.Domain.MalaDireta; +using Gestor.Model.Helper; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; + +namespace Gestor.Application.ViewModels.Generic +{ + public class DialogCopiaViewModel : BaseViewModel + { + private List _tipoCopia = new List() + { + "CÓPIA COMUM", + "CÓPIA OCULTA" + }; + + private string _tipo; + + private string _copiarPara; + + private Gestor.Model.Domain.MalaDireta.Copia _copia; + + private string _erro; + + private ObservableCollection _copiasComuns; + + private ObservableCollection _copiasOcultas; + + public Gestor.Model.Domain.MalaDireta.Copia Copia + { + get + { + return this._copia; + } + set + { + this._copia = value; + base.OnPropertyChanged("Copia"); + } + } + + public string CopiarPara + { + get + { + return this._copiarPara; + } + set + { + this._copiarPara = value; + base.OnPropertyChanged("CopiarPara"); + } + } + + public ObservableCollection CopiasComuns + { + get + { + return this._copiasComuns; + } + set + { + this._copiasComuns = value; + base.OnPropertyChanged("CopiasComuns"); + } + } + + public ObservableCollection CopiasOcultas + { + get + { + return this._copiasOcultas; + } + set + { + this._copiasOcultas = value; + base.OnPropertyChanged("CopiasOcultas"); + } + } + + public string Erro + { + get + { + return this._erro; + } + set + { + this._erro = value; + base.OnPropertyChanged("Erro"); + } + } + + public string Tipo + { + get + { + return this._tipo; + } + set + { + this._tipo = value; + base.OnPropertyChanged("Tipo"); + } + } + + public List TipoCopia + { + get + { + return this._tipoCopia; + } + set + { + this._tipoCopia = value; + base.OnPropertyChanged("TipoCopia"); + } + } + + public DialogCopiaViewModel(Gestor.Model.Domain.MalaDireta.Copia copia) + { + this.Tipo = this.TipoCopia.First(); + Gestor.Model.Domain.MalaDireta.Copia copium = copia; + if (copium == null) + { + copium = new Gestor.Model.Domain.MalaDireta.Copia(); + copium.set_CopiaOculta(new List()); + copium.set_CopiaComum(new List()); + } + this.Copia = copium; + this.CopiasComuns = new ObservableCollection(this.Copia.get_CopiaComum()); + this.CopiasOcultas = new ObservableCollection(this.Copia.get_CopiaOculta()); + } + + public void AdicionarCopia() + { + if (!ValidationHelper.ValidacaoEmail(this.CopiarPara)) + { + this.Erro = "E-MAIL INVÁLIDO"; + return; + } + if (this.Copia.get_CopiaOculta().Contains(this.CopiarPara)) + { + this.Erro = "E-MAIL JÁ ADICIONADO"; + return; + } + this.Copia.get_CopiaOculta().Add(this.CopiarPara); + this.CopiasOcultas = new ObservableCollection(this.Copia.get_CopiaOculta()); + this.CopiarPara = string.Empty; + this.Erro = "E-MAIL ADICIONADO COM SUCESSO"; + } + + public void ExcluirCopia(string tipo, string copia) + { + if (tipo == "CÓPIA OCULTA") + { + this.Copia.get_CopiaOculta().Remove(copia); + } + else + { + this.Copia.get_CopiaComum().Remove(copia); + } + this.CopiasComuns = new ObservableCollection(this.Copia.get_CopiaComum()); + this.CopiasOcultas = new ObservableCollection(this.Copia.get_CopiaOculta()); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/DialogCopiarPermissaoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/DialogCopiarPermissaoViewModel.cs new file mode 100644 index 0000000..0ca71be --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/DialogCopiarPermissaoViewModel.cs @@ -0,0 +1,350 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Generic +{ + public class DialogCopiarPermissaoViewModel : BaseSegurosViewModel + { + private Usuario _selectedUsuario; + + private Tuple, Usuario, List, List, List> _usuarioParameter; + + public Usuario SelectedUsuario + { + get + { + return this._selectedUsuario; + } + set + { + this._selectedUsuario = value; + this.WorkOnSelectedUsuario(value); + base.OnPropertyChanged("SelectedUsuario"); + } + } + + public Tuple, Usuario, List, List, List> UsuarioParameter + { + get + { + return this._usuarioParameter; + } + set + { + this._usuarioParameter = value; + base.OnPropertyChanged("UsuarioParameter"); + } + } + + public DialogCopiarPermissaoViewModel() + { + this.UsuarioParameter = new Tuple, Usuario, List, List, List>(null, null, null, null, null); + } + + private async Task> GetPermissoes(Usuario usuario) + { + List permissaoUsuarios = new List(); + IEnumerable tipoTelas = Enum.GetValues(typeof(TipoTela)).Cast(); + IEnumerable str = + from v in tipoTelas + select v.ToString(); + List list = ( + from x in str + orderby x + select x).ToList(); + List permissaoUsuarios1 = await this.ServicoPermissUsuario.PermissUsuario(usuario); + list.ForEach((string x) => { + TipoTela tipoTela = (TipoTela)Enum.Parse(typeof(TipoTela), x); + if (!string.Equals(ValidationHelper.GetCategory(tipoTela), "seguros", StringComparison.CurrentCultureIgnoreCase) && !string.Equals(ValidationHelper.GetCategory(tipoTela), "ferramentas", StringComparison.CurrentCultureIgnoreCase)) + { + return; + } + long id = (long)0; + bool consultar = true; + bool incluir = true; + bool alterar = true; + bool excluir = true; + if (permissaoUsuarios1.Count > 0 && permissaoUsuarios1.Any((PermissaoUsuario y) => y.get_Tela() == tipoTela)) + { + id = permissaoUsuarios1.First((PermissaoUsuario y) => y.get_Tela() == tipoTela).get_Id(); + consultar = permissaoUsuarios1.First((PermissaoUsuario y) => y.get_Tela() == tipoTela).get_Consultar(); + incluir = permissaoUsuarios1.First((PermissaoUsuario y) => y.get_Tela() == tipoTela).get_Incluir(); + alterar = permissaoUsuarios1.First((PermissaoUsuario y) => y.get_Tela() == tipoTela).get_Alterar(); + excluir = permissaoUsuarios1.First((PermissaoUsuario y) => y.get_Tela() == tipoTela).get_Excluir(); + } + PermissaoUsuario permissaoUsuario = new PermissaoUsuario(); + permissaoUsuario.set_Id(id); + permissaoUsuario.set_Tela(tipoTela); + permissaoUsuario.set_Consultar(consultar); + permissaoUsuario.set_Incluir(incluir); + permissaoUsuario.set_Alterar(alterar); + permissaoUsuario.set_Excluir(excluir); + permissaoUsuarios.Add(permissaoUsuario); + }); + List permissaoUsuarios2 = permissaoUsuarios; + list = null; + return permissaoUsuarios2; + } + + private async Task> GetPermissoesArquivoDigital(Usuario usuario) + { + List permissaoArquivoDigitals = new List(); + IEnumerable tipoArquivoDigitals = Enum.GetValues(typeof(TipoArquivoDigital)).Cast(); + IEnumerable str = + from v in tipoArquivoDigitals + select v.ToString(); + List list = ( + from x in str + orderby x + select x).ToList(); + List permissaoArquivoDigitals1 = await this.ServicoPermissArquivoDigital.PermissArquivoDigital(usuario); + list.ForEach((string x) => { + TipoArquivoDigital tipoArquivoDigital = (TipoArquivoDigital)Enum.Parse(typeof(TipoArquivoDigital), x); + long id = (long)0; + bool consultar = true; + bool incluir = true; + bool excluir = true; + if (permissaoArquivoDigitals1.Count > 0 && permissaoArquivoDigitals1.Any((PermissaoArquivoDigital y) => y.get_Tela() == tipoArquivoDigital)) + { + id = permissaoArquivoDigitals1.First((PermissaoArquivoDigital y) => y.get_Tela() == tipoArquivoDigital).get_Id(); + consultar = permissaoArquivoDigitals1.First((PermissaoArquivoDigital y) => y.get_Tela() == tipoArquivoDigital).get_Consultar(); + incluir = permissaoArquivoDigitals1.First((PermissaoArquivoDigital y) => y.get_Tela() == tipoArquivoDigital).get_Incluir(); + excluir = permissaoArquivoDigitals1.First((PermissaoArquivoDigital y) => y.get_Tela() == tipoArquivoDigital).get_Excluir(); + } + PermissaoArquivoDigital permissaoArquivoDigital = new PermissaoArquivoDigital(); + permissaoArquivoDigital.set_Id(id); + permissaoArquivoDigital.set_Tela(tipoArquivoDigital); + permissaoArquivoDigital.set_Consultar(consultar); + permissaoArquivoDigital.set_Incluir(incluir); + permissaoArquivoDigital.set_Excluir(excluir); + permissaoArquivoDigitals.Add(permissaoArquivoDigital); + }); + List permissaoArquivoDigitals2 = permissaoArquivoDigitals; + list = null; + return permissaoArquivoDigitals2; + } + + private async Task> GetRestricoes(Usuario usuario) + { + List restricaoUsuarios = new List(); + IEnumerable tipoRestricaos = Enum.GetValues(typeof(TipoRestricao)).Cast(); + IEnumerable str = + from v in tipoRestricaos + select v.ToString(); + List list = ( + from x in str + orderby x + select x).ToList(); + List restricaoUsuarios1 = await this.ServicoRestriUsuario.BuscarRestricoes(usuario.get_Id()); + List restricaoUsuarios2 = restricaoUsuarios1; + list.ForEach((string x) => { + TipoRestricao tipoRestricao = (TipoRestricao)Enum.Parse(typeof(TipoRestricao), x); + long id = (long)0; + bool restricao = false; + if (restricaoUsuarios2.Count > 0 && restricaoUsuarios2.Any((RestricaoUsuario y) => y.get_Tipo() == tipoRestricao)) + { + id = restricaoUsuarios2.First((RestricaoUsuario y) => y.get_Tipo() == tipoRestricao).get_Id(); + restricao = restricaoUsuarios2.First((RestricaoUsuario y) => y.get_Tipo() == tipoRestricao).get_Restricao(); + } + RestricaoUsuario restricaoUsuario = new RestricaoUsuario(); + restricaoUsuario.set_Id(id); + restricaoUsuario.set_Tipo(tipoRestricao); + restricaoUsuario.set_Restricao(restricao); + restricaoUsuarios.Add(restricaoUsuario); + }); + List restricaoUsuarios3 = restricaoUsuarios; + list = null; + return restricaoUsuarios3; + } + + private async Task> GetRestricoesCamposRelatorios(Usuario usuario) + { + List restricaoUsuarioCamposRelatorios = new List(); + List parametrosRelatorios = new List(); + foreach (Relatorio relatorio in Enum.GetValues(typeof(Relatorio)).Cast()) + { + switch (relatorio) + { + case 0: + case 1: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 2: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 3: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 4: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 5: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 6: + case 16: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 7: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 8: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 9: + case 10: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 11: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 12: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 13: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 14: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 15: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 17: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 18: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 19: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 20: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 23: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 27: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 29: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + default: + { + continue; + } + } + } + List restricaoUsuarioCamposRelatorios1 = await this.ServicoRestriUsuario.BuscarRestricoesCamposRelatorios(usuario.get_Id()); + List restricaoUsuarioCamposRelatorios2 = restricaoUsuarioCamposRelatorios1; + parametrosRelatorios.ForEach((ParametrosRelatorio x) => { + long id = (long)0; + bool restricao = false; + if (restricaoUsuarioCamposRelatorios2.Count > 0 && restricaoUsuarioCamposRelatorios2.Any((RestricaoUsuarioCamposRelatorios y) => { + if (y.get_Campo() != x.get_Header()) + { + return false; + } + return y.get_Relatorio() == x.get_Relatorio(); + })) + { + id = restricaoUsuarioCamposRelatorios2.First((RestricaoUsuarioCamposRelatorios y) => { + if (y.get_Campo() != x.get_Header()) + { + return false; + } + return y.get_Relatorio() == x.get_Relatorio(); + }).get_Id(); + restricao = restricaoUsuarioCamposRelatorios2.First((RestricaoUsuarioCamposRelatorios y) => { + if (y.get_Campo() != x.get_Header()) + { + return false; + } + return y.get_Relatorio() == x.get_Relatorio(); + }).get_Restricao(); + } + RestricaoUsuarioCamposRelatorios restricaoUsuarioCamposRelatorio = new RestricaoUsuarioCamposRelatorios(); + restricaoUsuarioCamposRelatorio.set_Id(id); + restricaoUsuarioCamposRelatorio.set_Campo(x.get_Header()); + restricaoUsuarioCamposRelatorio.set_Relatorio(x.get_Relatorio()); + restricaoUsuarioCamposRelatorio.set_Restricao(restricao); + restricaoUsuarioCamposRelatorios.Add(restricaoUsuarioCamposRelatorio); + }); + List restricaoUsuarioCamposRelatorios3 = restricaoUsuarioCamposRelatorios; + parametrosRelatorios = null; + return restricaoUsuarioCamposRelatorios3; + } + + private async void WorkOnSelectedUsuario(Usuario value) + { + if (value != null && value.get_Id() != 0) + { + List permissoes = await this.GetPermissoes(value); + Usuario usuario = value; + List restricoes = await this.GetRestricoes(value); + List permissoesArquivoDigital = await this.GetPermissoesArquivoDigital(value); + List restricoesCamposRelatorios = await this.GetRestricoesCamposRelatorios(value); + this.UsuarioParameter = new Tuple, Usuario, List, List, List>(permissoes, usuario, restricoes, permissoesArquivoDigital, restricoesCamposRelatorios); + permissoes = null; + usuario = null; + restricoes = null; + permissoesArquivoDigital = null; + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/DialogEditarParcelasViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/DialogEditarParcelasViewModel.cs new file mode 100644 index 0000000..bf96cfe --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/DialogEditarParcelasViewModel.cs @@ -0,0 +1,342 @@ +using Gestor.Application.Actions; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Model.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Resources; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Generic +{ + public class DialogEditarParcelasViewModel : BaseViewModel + { + private List _parcelasOriginais; + + internal Gestor.Application.Servicos.ParcelaServico ParcelaServico; + + private ObservableCollection _parcelas; + + private bool _isFatura; + + private string _status; + + private Parcela _selectedParcela; + + private Documento _selectedDocumento; + + public bool IsFatura + { + get + { + return this._isFatura; + } + set + { + this._isFatura = value; + base.OnPropertyChanged("IsFatura"); + } + } + + public ObservableCollection Parcelas + { + get + { + return this._parcelas; + } + set + { + this._parcelas = value; + base.OnPropertyChanged("Parcelas"); + } + } + + public Documento SelectedDocumento + { + get + { + return this._selectedDocumento; + } + set + { + this._selectedDocumento = value; + base.OnPropertyChanged("SelectedDocumento"); + } + } + + public Parcela SelectedParcela + { + get + { + return this._selectedParcela; + } + set + { + this._selectedParcela = value; + base.OnPropertyChanged("SelectedParcela"); + } + } + + public string Status + { + get + { + return this._status; + } + set + { + this._status = value; + base.OnPropertyChanged("Status"); + } + } + + public DialogEditarParcelasViewModel(Documento documento) + { + this.SelectedDocumento = documento; + this.ParcelaServico = new Gestor.Application.Servicos.ParcelaServico(); + this.Carregar(documento.get_Id()); + TipoRecebimento? tipoRecebimento = documento.get_TipoRecebimento(); + this.IsFatura = tipoRecebimento.GetValueOrDefault(1) == 2; + } + + public void AlterandoValor() + { + if (this.SelectedParcela.get_Documento() == null) + { + this.SelectedParcela.set_Documento(this.SelectedDocumento); + } + this.SelectedParcela.get_Documento().set_Parcelas(this.Parcelas); + if (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 1 && this.SelectedParcela.get_SubTipo() == 1 && this.SelectedParcela.get_Comissao() == decimal.Zero) + { + this.SelectedParcela.set_Comissao(this.SelectedDocumento.get_Comissao()); + } + this.SelectedParcela.set_Baixando(false); + this.AlterarValor(); + } + + public void AlterandoVencimento(Parcela parcela) + { + DateTime vencimento; + ObservableCollection parcelas; + if (Recursos.Configuracoes.All((ConfiguracaoSistema y) => y.get_Configuracao() != 11)) + { + DateTime? vigencia2 = parcela.get_Documento().get_Vigencia2(); + if (vigencia2.HasValue) + { + vencimento = parcela.get_Vencimento(); + vigencia2 = parcela.get_Documento().get_Vigencia2(); + if ((vigencia2.HasValue ? vencimento > vigencia2.GetValueOrDefault() : false) && parcela.get_Documento().get_Controle().get_Ramo().get_Id() != (long)23) + { + Action acionarSnackbar = Gestor.Application.Actions.Actions.AcionarSnackbar; + if (acionarSnackbar != null) + { + acionarSnackbar(string.Concat("DATA INVÁLIDA. ", Messages.get_VencimentoMaior())); + } + else + { + } + parcela.set_Vencimento(this._parcelasOriginais.First((Parcela x) => x.get_Id() == parcela.get_Id()).get_Vencimento()); + } + } + } + if (Recursos.Configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 9)) + { + if (parcela.get_Documento().get_Vigencia1() > DateTime.MinValue && parcela.get_NumeroParcela() == 1) + { + DateTime dateTime = parcela.get_Vencimento(); + vencimento = parcela.get_Documento().get_Vigencia1(); + if (dateTime < vencimento.AddDays(-30)) + { + goto Label0; + } + } + if (parcela.get_NumeroParcela() == 1 || !(parcela.get_Vencimento() < parcela.get_Documento().get_Vigencia1())) + { + parcelas = this.Parcelas; + this.Parcelas = new ObservableCollection( + from x in parcelas + orderby x.get_NumeroParcela() + select x); + return; + } + Label0: + Action action = Gestor.Application.Actions.Actions.AcionarSnackbar; + if (action != null) + { + action(string.Concat("DATA INVÁLIDA. ", Messages.get_VencimentoMenor())); + } + else + { + } + parcela.set_Vencimento(this._parcelasOriginais.First((Parcela x) => x.get_Id() == parcela.get_Id()).get_Vencimento()); + } + parcelas = this.Parcelas; + this.Parcelas = new ObservableCollection( + from x in parcelas + orderby x.get_NumeroParcela() + select x); + } + + public void AlterarValor() + { + if (this.SelectedParcela == null) + { + return; + } + if (this.SelectedParcela.get_SubTipo() != 1 || this.IsFatura) + { + this.SelectedParcela.set_Documento(this.SelectedDocumento); + return; + } + decimal premioTotal = this.SelectedDocumento.get_PremioTotal() - this.Parcelas.Where((Parcela x) => { + if (x.get_SubTipo() != 1) + { + return false; + } + return x.get_Id() != this.SelectedParcela.get_Id(); + }).Sum((Parcela x) => x.get_Valor()); + decimal valor = this.SelectedDocumento.get_PremioTotal() - this.Parcelas.Where((Parcela x) => { + if (x.get_SubTipo() != 1) + { + return false; + } + return x.get_Id() < this.SelectedParcela.get_Id(); + }).Sum((Parcela x) => x.get_Valor()); + valor -= this.SelectedParcela.get_Valor(); + decimal numeroParcelas = this.SelectedDocumento.get_NumeroParcelas() - this.SelectedParcela.get_NumeroParcela(); + if (numeroParcelas == decimal.Zero) + { + numeroParcelas = decimal.One; + } + decimal num = (numeroParcelas > decimal.Zero ? valor / numeroParcelas : decimal.Zero); + if (num == decimal.Zero) + { + this.SelectedParcela.set_Valor(premioTotal); + } + List parcelas = new List() + { + this.SelectedParcela + }; + decimal num1 = Math.Abs(num); + decimal? tolerancia = this.SelectedDocumento.get_Controle().get_Seguradora().get_Tolerancia(); + if ((num1 > tolerancia.GetValueOrDefault()) & tolerancia.HasValue && !this.Parcelas.Any((Parcela x) => { + if (x.get_SubTipo() != 1) + { + return false; + } + return x.get_NumeroParcela() > this.SelectedParcela.get_NumeroParcela(); + })) + { + this.SelectedParcela.set_Valor(premioTotal); + } + this.Parcelas.Where((Parcela x) => { + if (x.get_SubTipo() != 1) + { + return false; + } + return x.get_NumeroParcela() != this.SelectedParcela.get_NumeroParcela(); + }).ToList().ForEach((Parcela x) => { + if (x.get_NumeroParcela() > this.SelectedParcela.get_NumeroParcela()) + { + x.set_Valor((num > decimal.Zero ? num : x.get_Valor())); + x.set_Comissao((x.get_Comissao() == decimal.Zero ? this.SelectedDocumento.get_Comissao() : x.get_Comissao())); + } + parcelas.Add(x); + }); + foreach (Parcela parcela in + from x in parcelas + where x.get_NumeroParcela() >= this.SelectedParcela.get_NumeroParcela() + select x) + { + parcela.set_Documento(this.SelectedDocumento); + if (parcela.get_Id() == this.SelectedParcela.get_Id()) + { + continue; + } + parcela.set_Valor(num); + } + this.Parcelas = new ObservableCollection( + from x in parcelas + orderby x.get_NumeroParcela() + select x); + } + + public async void Carregar(long id) + { + await this.CarregarParcelas(id); + } + + public async Task CarregarParcelas(long id) + { + ObservableCollection observableCollection; + ObservableCollection observableCollection1 = await (new Gestor.Application.Servicos.ParcelaServico()).BuscarParcelasAsync(id); + this._parcelasOriginais = new List(); + foreach (Parcela parcela in observableCollection1) + { + this._parcelasOriginais.Add((Parcela)parcela.Clone()); + } + DialogEditarParcelasViewModel dialogEditarParcelasViewModel = this; + if (this.IsFatura) + { + ObservableCollection observableCollection2 = observableCollection1; + observableCollection = new ObservableCollection( + from x in observableCollection2 + orderby x.get_NumeroParcela() + select x); + } + else + { + observableCollection = observableCollection1; + } + dialogEditarParcelasViewModel.Parcelas = observableCollection; + } + + public async Task SalvarParcelas() + { + bool flag; + foreach (Parcela parcela in this.Parcelas) + { + Parcela parcela1 = this._parcelasOriginais.First((Parcela x) => x.get_Id() == parcela.get_Id()); + if (!(parcela.get_Vencimento() != parcela1.get_Vencimento()) && !(parcela.get_Valor() != parcela1.get_Valor())) + { + continue; + } + parcela1.set_Vencimento(parcela.get_Vencimento()); + parcela1.set_Valor(parcela.get_Valor()); + Parcela selectedParcela = this.SelectedParcela; + List configuracoes = Recursos.Configuracoes; + bool flag1 = configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 9); + List configuracaoSistemas = Recursos.Configuracoes; + bool flag2 = configuracaoSistemas.Any((ConfiguracaoSistema y) => y.get_Configuracao() == 11); + List configuracoes1 = Recursos.Configuracoes; + List> keyValuePairs = selectedParcela.Validate(flag1, flag2, true, configuracoes1.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 16)); + if (keyValuePairs.Count <= 0) + { + await (new Gestor.Application.Servicos.ParcelaServico()).Save(parcela1, this._parcelasOriginais, null, true); + } + else + { + List> keyValuePairs1 = keyValuePairs; + string str = string.Join(", ", keyValuePairs1.Select, string>((KeyValuePair x) => { + string[] strArrays = x.Key.Split(new char[] { '|' }); + return string.Concat(((int)strArrays.Length > 1 ? strArrays[1] : x.Key), ": ", x.Value, Environment.NewLine); + })); + this.Status = string.Concat("NÃO FOI POSSÍVEL SALVAR DEVIDO AOS ERROS ABAIXO:", Environment.NewLine, str); + flag = false; + return flag; + } + } + base.RegistrarAcao(string.Format("EDITOU VENCIMENTO E/OU VALORES DAS PARCELAS/FATURAS DO DOCUMENTO DE ID {0}", this.Parcelas[0].get_Documento().get_Id()), this.Parcelas[0].get_Documento().get_Id(), new TipoTela?(5), null); + flag = true; + return flag; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/DialogEnviarEmailsViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/DialogEnviarEmailsViewModel.cs new file mode 100644 index 0000000..646d94e --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/DialogEnviarEmailsViewModel.cs @@ -0,0 +1,394 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.MalaDireta; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Generic +{ + public class DialogEnviarEmailsViewModel : BaseSegurosViewModel + { + private ObservableCollection _listaTela = new ObservableCollection(); + + private string _infoEnvio = "CLIQUE EM ENVIAR PARA INCIAR O ENVIO"; + + private List _arquivosAnexados + { + get; + set; + } + + private bool _assinatura + { + get; + set; + } + + private string _assunto + { + get; + set; + } + + private bool _confirmarLeitura + { + get; + set; + } + + private string _corpo + { + get; + set; + } + + private Credencial _credencial + { + get; + set; + } + + private FiltroArquivoDigital _filtro + { + get; + set; + } + + private bool _original + { + get; + set; + } + + private bool _salvarAd + { + get; + set; + } + + public string InfoEnvio + { + get + { + return this._infoEnvio; + } + set + { + this._infoEnvio = value; + base.OnPropertyChanged("InfoEnvio"); + } + } + + public List Lista + { + get; + set; + } + + public ObservableCollection ListaTela + { + get + { + return this._listaTela; + } + set + { + this._listaTela = value; + base.OnPropertyChanged("ListaTela"); + } + } + + public DialogEnviarEmailsViewModel(List lista, bool assinatura, bool original, List arquivosAnexados, string assunto, string corpo, Credencial credencial, FiltroArquivoDigital filtro, bool salvarAd, bool confirmarLeitura) + { + lista.ForEach((MalaDireta x) => x.set_InfoEnvio(null)); + this.Lista = lista; + this.PrepararLista(); + this._assinatura = assinatura; + this._original = original; + this._arquivosAnexados = arquivosAnexados; + this._assunto = assunto; + this._corpo = corpo; + this._credencial = credencial; + this._filtro = filtro; + this._salvarAd = salvarAd; + this._confirmarLeitura = confirmarLeitura; + } + + public void Enviar() + { + this.Enviar(this._assinatura, this._original, this._arquivosAnexados, this._assunto, this._corpo, this._credencial, this._filtro, this._salvarAd, this._confirmarLeitura); + } + + private async void Enviar(bool assinatura, bool original, List arquivosAnexados, string assunto, string corpo, Credencial credencial, FiltroArquivoDigital filtro, bool salvarAd, bool confirmarLeitura) + { + base.Loading(true); + this.InfoEnvio = "ENVIANDO, AGUARDE ATÉ O PROCESSO TERMINAR."; + await this.EnviarEmails(assinatura, original, arquivosAnexados, assunto, corpo, credencial, filtro, salvarAd, confirmarLeitura); + this.InfoEnvio = "TENTATIVA DE ENVIO CONCLUÍDA, CONFIRA O STATUS ABAIXO."; + base.Loading(false); + } + + private async Task EnviarEmails(bool assinatura, bool original, List arquivosAnexados, string assunto, string corpo, Credencial credencial, FiltroArquivoDigital filtro, bool salvarAd, bool confirmarLeitura) + { + int i; + List arquivoDigitals; + List arquivoDigitals1; + bool flag; + bool arquivoDigital; + List copiaComum; + List copiaOculta; + string str; + long? nullable; + bool valueOrDefault; + List strs = new List(); + VariaveisMalaDireta[] values = (VariaveisMalaDireta[])Enum.GetValues(typeof(VariaveisMalaDireta)); + for (i = 0; i < (int)values.Length; i++) + { + strs.Add(ValidationHelper.GetEntity(values[i])); + } + if (strs.Any(new Func(assunto.Contains)) || strs.Any(new Func(corpo.Contains))) + { + flag = true; + } + else + { + List lista = this.Lista; + flag = lista.Any((MalaDireta x) => { + if (x.get_ArquivoDigital() == null) + { + return false; + } + return x.get_ArquivoDigital().Count > 0; + }); + } + bool flag1 = flag; + Credencial credencial1 = credencial; + MailHelper mailHelper = new MailHelper(); + bool flag2 = false; + if (salvarAd) + { + Gestor.Application.Servicos.ArquivoDigitalServico arquivoDigitalServico = new Gestor.Application.Servicos.ArquivoDigitalServico(); + foreach (MalaDireta listum in this.Lista) + { + arquivosAnexados.ForEach((Gestor.Model.Domain.Common.ArquivoDigital a) => { + a.set_IdCliente((listum.get_Tela() == 1 ? listum.get_Cliente().get_Id() : (long)0)); + a.set_IdDocumento((listum.get_Tela() == 2 ? listum.get_Apolice().get_Id() : (long)0)); + a.set_IdItem((listum.get_Tela() == 3 ? listum.get_Item().get_Id() : (long)0)); + a.set_IdParcela((listum.get_Tela() == 5 ? listum.get_Parcela().get_Id() : (long)0)); + a.set_IdProspeccao((listum.get_Tela() == 33 ? listum.get_Prospeccao().get_Id() : (long)0)); + a.set_IdSinistro((listum.get_Tela() == 7 ? listum.get_Sinistro().get_Id() : (long)0)); + a.set_IdEmpresa(Recursos.Usuario.get_IdEmpresa()); + }); + List indiceArquivoDigitals = await arquivoDigitalServico.Insert(arquivosAnexados.ToList()); + List arquivoDigitals2 = arquivosAnexados; + if (!arquivoDigitals2.Any((Gestor.Model.Domain.Common.ArquivoDigital arquivo) => arquivo.get_Arquivo() == null)) + { + continue; + } + arquivoDigitals = await arquivoDigitalServico.Buscar(indiceArquivoDigitals); + arquivosAnexados = arquivoDigitals; + } + arquivoDigitalServico = null; + } + if (!string.IsNullOrWhiteSpace(credencial.get_Cabecalho())) + { + corpo = string.Concat(credencial.get_Cabecalho(), corpo); + } + if (!string.IsNullOrWhiteSpace(credencial.get_Assinatura())) + { + corpo = string.Concat(corpo, "

", credencial.get_Assinatura()); + } + if (flag1) + { + for (int j = 0; j < this.Lista.Count; j = i + 1) + { + MalaDireta item = this.Lista[j]; + if (item.get_ArquivoDigital() == null) + { + arquivoDigitals = new List(); + } + else + { + if (!(!assinatura | original)) + { + Gestor.Application.Servicos.ArquivoDigitalServico arquivoDigitalServico1 = this.ArquivoDigitalServico; + List arquivoDigital1 = item.get_ArquivoDigital(); + arquivoDigitals1 = await arquivoDigitalServico1.Buscar(( + from x in arquivoDigital1 + where string.IsNullOrWhiteSpace(x.get_UrlAssinatura()) + select x).ToList()); + } + else + { + arquivoDigitals1 = await this.ArquivoDigitalServico.Buscar(item.get_ArquivoDigital().ToList()); + } + arquivoDigitals = arquivoDigitals1; + } + List arquivoDigitals3 = arquivoDigitals; + if (arquivosAnexados != null && arquivosAnexados.Count > 0) + { + arquivoDigitals3.AddRange(arquivosAnexados); + } + MalaDireta malaDiretum = item; + if (malaDiretum != null) + { + arquivoDigital = malaDiretum.get_ArquivoDigital(); + } + else + { + arquivoDigital = false; + } + if (!arquivoDigital) + { + MalaDireta malaDiretum1 = item; + if (malaDiretum1 != null) + { + Documento apolice = malaDiretum1.get_Apolice(); + if (apolice != null) + { + nullable = new long?(apolice.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long num = (long)0; + valueOrDefault = nullable1.GetValueOrDefault() > num & nullable1.HasValue; + } + else + { + valueOrDefault = false; + } + if (valueOrDefault) + { + MalaDireta malaDiretum2 = item; + List indiceArquivoDigitals1 = await this.ArquivoDigitalServico.BuscarPorTipo(2, item.get_Apolice().get_Id()); + malaDiretum2.set_ArquivoDigital(indiceArquivoDigitals1); + malaDiretum2 = null; + } + } + Destinatario destinatario = new Destinatario(); + destinatario.set_Assunto(Funcoes.SubstituirVariaveis(assunto, item)); + destinatario.set_Corpo(Funcoes.SubstituirVariaveis(corpo, item)); + destinatario.set_Email(item.get_Email()); + Copia copia = item.get_Copia(); + if (copia != null) + { + copiaComum = copia.get_CopiaComum(); + } + else + { + copiaComum = null; + } + destinatario.set_Encaminhar(copiaComum); + Copia copium = item.get_Copia(); + if (copium != null) + { + copiaOculta = copium.get_CopiaOculta(); + } + else + { + copiaOculta = null; + } + destinatario.set_EncaminharOculto(copiaOculta); + destinatario.set_Nome(item.get_Cliente().get_Nome()); + destinatario.set_Anexos(arquivoDigitals3); + Destinatario destinatario1 = destinatario; + List malaDiretas = new List() + { + item + }; + LogEnvio logEnvio = await mailHelper.SendAsync(credencial, destinatario1, filtro, malaDiretas, 0, confirmarLeitura); + item.set_Enviado(new bool?(logEnvio.get_Enviado())); + MalaDireta malaDiretum3 = item; + str = (logEnvio.get_Enviado() ? "ENVIADO COM SUCESSO" : string.Concat("NÃO ENVIADO, ENTRE EM CONTATO COM SEU PROVEDOR/SERVIÇO DE E-MAIL E INFORME OS DADOS ABAIXO: \r\n", logEnvio.get_Erro())); + malaDiretum3.set_InfoEnvio(str); + item.set_ArquivoDigital(null); + this.Lista = this.Lista; + item = null; + arquivoDigitals3 = null; + i = j; + } + } + else + { + while (!flag2) + { + List lista1 = this.Lista; + List list = ( + from x in lista1 + where !x.get_Enviado().HasValue + select x).Take(200).ToList(); + List malaDiretas1 = list; + List list1 = ( + from x in malaDiretas1 + select x.get_Email()).ToList(); + list.ForEach((MalaDireta x) => { + if (x.get_Copia() == null) + { + return; + } + list1.AddRange(x.get_Copia().get_CopiaComum()); + list1.AddRange(x.get_Copia().get_CopiaOculta()); + }); + list1 = list1.Distinct().ToList(); + Destinatario destinatario2 = new Destinatario(); + destinatario2.set_Assunto(assunto); + destinatario2.set_Corpo(corpo); + destinatario2.set_Email(credencial1.get_Email()); + destinatario2.set_Nome(credencial1.get_Descricao()); + destinatario2.set_Encaminhar(new List()); + destinatario2.set_EncaminharOculto(list1); + destinatario2.set_Anexos(arquivosAnexados.ToList()); + Destinatario destinatario3 = destinatario2; + LogEnvio logEnvio1 = await mailHelper.SendAsync(credencial, destinatario3, filtro, this.Lista.ToList(), 0, confirmarLeitura); + LogEnvio logEnvio2 = logEnvio1; + List list2 = this.Lista.ToList(); + list2.ForEach((MalaDireta x) => { + x.set_Enviado(new bool?(logEnvio2.get_Enviado())); + x.set_InfoEnvio((logEnvio2.get_Enviado() ? "ENVIADO COM SUCESSO" : string.Concat("NÃO ENVIADO, ENTRE EM CONTATO COM SEU PROVEDOR/SERVIÇO DE E-MAIL E INFORME OS DADOS ABAIXO: \r\n", logEnvio2.get_Erro()))); + }); + this.Lista = list2; + List lista2 = this.Lista; + flag2 = lista2.All((MalaDireta x) => x.get_Enviado().HasValue); + } + } + this.PrepararLista(); + credencial1 = null; + mailHelper = null; + } + + private void PrepararLista() + { + List malaDiretas = new List(); + this.Lista.ForEach((MalaDireta x) => { + malaDiretas.Add(x); + if (x.get_Copia() == null) + { + return; + } + malaDiretas.AddRange(x.get_Copia().get_CopiaOculta().Select((string c) => { + MalaDireta malaDiretum = new MalaDireta(); + malaDiretum.set_Cliente(x.get_Cliente()); + malaDiretum.set_Email(c); + malaDiretum.set_Enviado(x.get_Enviado()); + malaDiretum.set_InfoEnvio(x.get_InfoEnvio()); + return malaDiretum; + }).ToList()); + }); + this.ListaTela = new ObservableCollection(malaDiretas); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/DialogExportarPermissaoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/DialogExportarPermissaoViewModel.cs new file mode 100644 index 0000000..dd39cab --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/DialogExportarPermissaoViewModel.cs @@ -0,0 +1,122 @@ +using Gestor.Application.Servicos.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Generic +{ + public class DialogExportarPermissaoViewModel : BaseSegurosViewModel + { + private bool _enableGrid = true; + + private List _usuarios; + + private ObservableCollection _usuariosFiltrados = new ObservableCollection(); + + public bool EnableGrid + { + get + { + return this._enableGrid; + } + set + { + this._enableGrid = value; + base.OnPropertyChanged("EnableGrid"); + } + } + + public List Usuarios + { + get + { + return this._usuarios; + } + set + { + this._usuarios = value; + base.OnPropertyChanged("Usuarios"); + } + } + + public ObservableCollection UsuariosFiltrados + { + get + { + return this._usuariosFiltrados; + } + set + { + this._usuariosFiltrados = value; + base.OnPropertyChanged("UsuariosFiltrados"); + } + } + + public DialogExportarPermissaoViewModel(long idUsuario) + { + this.Seleciona(idUsuario); + } + + internal async Task> Filtrar(string value) + { + List usuarios = await Task.Run>(() => this.FiltrarUsuario(value)); + return usuarios; + } + + public List FiltrarUsuario(string filter) + { + this.UsuariosFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Usuarios) : new ObservableCollection( + from x in this.Usuarios + where ValidationHelper.RemoveDiacritics(x.get_Nome().ToUpper().Trim()).Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby !x.get_Excluido() descending, x.get_Nome() + select x)); + return this.UsuariosFiltrados.ToList(); + } + + private async void Seleciona(long idUsuario) + { + base.Loading(true); + await this.SelecionaUsuarios(idUsuario); + base.Loading(false); + } + + public void Selecionar() + { + if (this.UsuariosFiltrados == null || this.UsuariosFiltrados.Count == 0) + { + return; + } + this.UsuariosFiltrados.ToList().ForEach((Usuario x) => x.set_Selecionado(!x.get_Selecionado())); + this.UsuariosFiltrados = new ObservableCollection(this.UsuariosFiltrados); + } + + private async Task SelecionaUsuarios(long idUsuario) + { + this.EnableGrid = false; + base.Loading(true); + List usuarios = await (new BaseServico()).BuscarUsuariosAsync(); + DialogExportarPermissaoViewModel list = this; + IEnumerable usuarios1 = usuarios.Where((Usuario x) => { + if (x.get_Excluido()) + { + return false; + } + return x.get_Id() != idUsuario; + }); + list.Usuarios = ( + from x in usuarios1 + orderby x.get_Nome() + select x).ToList(); + this.UsuariosFiltrados = new ObservableCollection(this.Usuarios); + base.Loading(false); + this.EnableGrid = true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/DialogGraficoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/DialogGraficoViewModel.cs new file mode 100644 index 0000000..94b332a --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/DialogGraficoViewModel.cs @@ -0,0 +1,45 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Model; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Gestor.Application.ViewModels.Generic +{ + public class DialogGraficoViewModel : INotifyPropertyChanged + { + private SinteticoSource _source; + + public SinteticoSource Source + { + get + { + return this._source; + } + set + { + this.MutateVerbose(ref this._source, value, this.RaisePropertyChanged(), "Source"); + } + } + + public DialogGraficoViewModel(SinteticoSource series) + { + this.Source = series; + } + + private Action RaisePropertyChanged() + { + return (PropertyChangedEventArgs args) => { + PropertyChangedEventHandler propertyChangedEventHandler = this.PropertyChanged; + if (propertyChangedEventHandler == null) + { + return; + } + propertyChangedEventHandler(this, args); + }; + } + + public event PropertyChangedEventHandler PropertyChanged; + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/DialogMedalhaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/DialogMedalhaViewModel.cs new file mode 100644 index 0000000..49eb58b --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/DialogMedalhaViewModel.cs @@ -0,0 +1,75 @@ +using System; + +namespace Gestor.Application.ViewModels.Generic +{ + public class DialogMedalhaViewModel : BaseSegurosViewModel + { + private int _liquido; + + private int _comissao; + + private int _resultado; + + private int _media; + + public int Comissao + { + get + { + return this._comissao; + } + set + { + this._comissao = value; + base.OnPropertyChanged("Comissao"); + } + } + + public int Liquido + { + get + { + return this._liquido; + } + set + { + this._liquido = value; + base.OnPropertyChanged("Liquido"); + } + } + + public int Media + { + get + { + return this._media; + } + set + { + this._media = value; + base.OnPropertyChanged("Media"); + } + } + + public int Resultado + { + get + { + return this._resultado; + } + set + { + this._resultado = value; + base.OnPropertyChanged("Resultado"); + } + } + + public DialogMedalhaViewModel(int liquido, int comissao, int resultado, int media) + { + this.Liquido = liquido; + this.Comissao = comissao; + this.Resultado = resultado; + this.Media = media; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/DialogPesquisaAvancadaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/DialogPesquisaAvancadaViewModel.cs new file mode 100644 index 0000000..284d821 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/DialogPesquisaAvancadaViewModel.cs @@ -0,0 +1,604 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Generic +{ + public class DialogPesquisaAvancadaViewModel : BaseSegurosViewModel + { + private ObservableCollection _pesquisas = new ObservableCollection(); + + private PesquisaAvancada _resultado = new PesquisaAvancada(); + + private string _pesquisa; + + private FiltroStatusDocumento _status; + + private TipoTela _tela; + + private TipoFiltroBusca _tipoFiltro; + + private bool _habilitarFiltroBuscar; + + private FiltroStatusDocumento _oldStatus; + + private bool _enableStatus = true; + + public bool TipoBusca; + + private TipoPesquisa _tipo { get; set; } = 14; + + public bool EnableStatus + { + get + { + return this._enableStatus; + } + set + { + this._enableStatus = value; + base.OnPropertyChanged("EnableStatus"); + } + } + + public bool HabilitarFiltroBuscar + { + get + { + return this._habilitarFiltroBuscar; + } + set + { + this._habilitarFiltroBuscar = value; + base.OnPropertyChanged("HabilitarFiltroBuscar"); + } + } + + public string Informacao + { + get + { + return "O LIMITE DA PESQUISA É EM MIL ITENS,\r\nPARA OBTER UMA EXATIDÃO NA PESQUISA É NECESSÁRIO ESPECIFICAR O ITEM PROCURADO."; + } + } + + public string Pesquisa + { + get + { + return this._pesquisa; + } + set + { + this._pesquisa = value; + base.OnPropertyChanged("Pesquisa"); + } + } + + public ObservableCollection Pesquisas + { + get + { + return this._pesquisas; + } + set + { + this._pesquisas = value; + base.OnPropertyChanged("Pesquisas"); + } + } + + public PesquisaAvancada Resultado + { + get + { + return this._resultado; + } + set + { + if (value != null) + { + value.set_Status(this.Status); + } + this._resultado = value; + base.OnPropertyChanged("Resultado"); + } + } + + public FiltroStatusDocumento Status + { + get + { + return this._status; + } + set + { + this._status = value; + this._oldStatus = value; + if (this.Resultado != null) + { + this.Resultado.set_Status(this.Status); + } + base.OnPropertyChanged("Status"); + } + } + + public TipoTela Tela + { + get + { + return this._tela; + } + set + { + this._tela = value; + base.OnPropertyChanged("Tela"); + } + } + + public TipoPesquisa Tipo + { + get + { + return this._tipo; + } + set + { + if (value == 1 || value == 2 || value == 17 || value == 9) + { + this.EnableStatus = false; + FiltroStatusDocumento filtroStatusDocumento = this._oldStatus; + this.Status = 4; + this._oldStatus = filtroStatusDocumento; + } + else if (this._tipo == 1 || this._tipo == 2) + { + this.EnableStatus = true; + this.Status = this._oldStatus; + } + this._tipo = value; + this.GetTipoTela(); + this.HabilitarBusca(); + base.OnPropertyChanged("Tipo"); + } + } + + public TipoFiltroBusca TipoFiltro + { + get + { + return this._tipoFiltro; + } + set + { + this._tipoFiltro = value; + base.OnPropertyChanged("TipoFiltro"); + } + } + + public DialogPesquisaAvancadaViewModel() + { + } + + public void GetTipoPesquisa() + { + TipoFiltroBusca tipoFiltroBusca = this._tipoFiltro; + if (tipoFiltroBusca == null) + { + this.TipoBusca = false; + return; + } + if (tipoFiltroBusca != 1) + { + return; + } + this.TipoBusca = true; + } + + public void GetTipoTela() + { + switch (this.Tipo) + { + case 0: + case 14: + { + this.Tela = 3; + return; + } + case 1: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + case 10: + case 11: + case 12: + case 13: + case 15: + case 16: + case 17: + { + this.Tela = 21; + return; + } + case 2: + case 9: + { + this.Tela = 7; + return; + } + default: + { + return; + } + } + } + + public void HabilitarBusca() + { + switch (this.Tipo) + { + case 0: + case 4: + case 6: + case 8: + case 10: + case 13: + case 14: + { + this.HabilitarFiltroBuscar = true; + return; + } + case 1: + case 2: + { + this.TipoFiltro = 1; + this.HabilitarFiltroBuscar = false; + return; + } + case 3: + case 5: + case 7: + case 9: + case 11: + case 12: + { + this.TipoFiltro = 0; + this.HabilitarFiltroBuscar = false; + return; + } + default: + { + this.TipoFiltro = 0; + this.HabilitarFiltroBuscar = false; + return; + } + } + } + + public async Task Pesquisar() + { + List vendedorUsuarios; + long id; + ObservableCollection observableCollection; + PesquisaAvancada pesquisaAvancada2; + int num; + ObservableCollection observableCollection1; + if (Recursos.Usuario != null) + { + vendedorUsuarios = await base.VerificaVinculoVendedor(Recursos.Usuario); + } + else + { + vendedorUsuarios = new List(); + } + List vendedorUsuarios1 = vendedorUsuarios; + this.GetTipoPesquisa(); + switch (this.Tipo) + { + case 0: + { + this.Pesquisas = new ObservableCollection(await (new AutoServico()).BuscarChassi(this.Pesquisa, this.Status, vendedorUsuarios1, this.TipoBusca)); + break; + } + case 1: + { + if (long.TryParse(this.Pesquisa, out id)) + { + Documento documento = await (new ApoliceServico()).BuscarCodDocumento(long.Parse(this.Pesquisa), vendedorUsuarios1); + DialogPesquisaAvancadaViewModel dialogPesquisaAvancadaViewModel = this; + if (documento == null || documento.get_Excluido()) + { + observableCollection1 = new ObservableCollection(); + } + else + { + observableCollection = new ObservableCollection(); + pesquisaAvancada2 = new PesquisaAvancada(); + pesquisaAvancada2.set_Nome(documento.get_Controle().get_Cliente().get_Nome()); + pesquisaAvancada2.set_IdDocumento(documento.get_Id()); + string[] proposta = new string[] { "CÓDIGO DO COCUMENTO: ", null, null, null, null, null, null, null }; + id = documento.get_Id(); + proposta[1] = id.ToString(); + proposta[2] = " - NÚMERO DA PROPOSTA: "; + proposta[3] = documento.get_Proposta(); + proposta[4] = " - NÚMERO DA APÓLICE: "; + proposta[5] = documento.get_Apolice(); + proposta[6] = " - NÚMERO DO ENDOSSO: "; + proposta[7] = documento.get_Endosso(); + pesquisaAvancada2.set_Pesquisa(string.Concat(proposta)); + pesquisaAvancada2.set_IdCliente(documento.get_Controle().get_Cliente().get_Id()); + observableCollection.Add(pesquisaAvancada2); + observableCollection1 = observableCollection; + } + dialogPesquisaAvancadaViewModel.Pesquisas = observableCollection1; + break; + } + else + { + return; + } + } + case 2: + { + SinistroServico sinistroServico = new SinistroServico(); + if (int.TryParse(this.Pesquisa, out num)) + { + Sinistro sinistro = await sinistroServico.BuscarSinistro(long.Parse(this.Pesquisa)); + if (sinistro != null) + { + observableCollection = new ObservableCollection(); + pesquisaAvancada2 = new PesquisaAvancada(); + pesquisaAvancada2.set_IdCliente(sinistro.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Cliente().get_Id()); + pesquisaAvancada2.set_IdDocumento(sinistro.get_ControleSinistro().get_Item().get_Documento().get_Id()); + pesquisaAvancada2.set_IdItem(sinistro.get_ControleSinistro().get_Item().get_Id()); + pesquisaAvancada2.set_IdSinistro(sinistro.get_Id()); + pesquisaAvancada2.set_Nome(sinistro.get_ControleSinistro().get_Item().get_Documento().get_NomeProponente()); + string[] itemSinistrado = new string[] { "CÓDIGO DO SINISTRO: ", null, null, null, null, null }; + id = sinistro.get_ControleSinistro().get_Id(); + itemSinistrado[1] = id.ToString(); + itemSinistrado[2] = " - NÚMERO DA APÓLICE: "; + itemSinistrado[3] = sinistro.get_ControleSinistro().get_Item().get_Documento().get_Apolice(); + itemSinistrado[4] = " - ITEM "; + itemSinistrado[5] = sinistro.get_ItemSinistrado(); + pesquisaAvancada2.set_Pesquisa(string.Concat(itemSinistrado)); + observableCollection.Add(pesquisaAvancada2); + this.Pesquisas = observableCollection; + break; + } + else + { + this.Pesquisas = new ObservableCollection(); + break; + } + } + else + { + return; + } + } + case 3: + { + List clienteEmails = await (new EmailServico()).BuscarEmail(this.Pesquisa); + DialogPesquisaAvancadaViewModel dialogPesquisaAvancadaViewModel1 = this; + List clienteEmails1 = clienteEmails; + dialogPesquisaAvancadaViewModel1.Pesquisas = new ObservableCollection(clienteEmails1.Select((ClienteEmail x) => { + PesquisaAvancada pesquisaAvancada = new PesquisaAvancada(); + pesquisaAvancada.set_Nome(x.get_Cliente().get_Nome()); + pesquisaAvancada.set_Pesquisa(string.Concat("E-MAIL: ", x.get_Email())); + pesquisaAvancada.set_IdCliente(x.get_Cliente().get_Id()); + return pesquisaAvancada; + }).ToList()); + break; + } + case 4: + { + List documentos = await (new ApoliceServico()).BuscarApolice(this.Pesquisa, this.Status, vendedorUsuarios1, "Estipulante", this.TipoBusca); + DialogPesquisaAvancadaViewModel observableCollection2 = this; + List documentos1 = documentos; + observableCollection2.Pesquisas = new ObservableCollection(documentos1.Select((Documento x) => { + PesquisaAvancada pesquisaAvancada = new PesquisaAvancada(); + pesquisaAvancada.set_IdCliente(x.get_Controle().get_Cliente().get_Id()); + pesquisaAvancada.set_IdDocumento(x.get_Id()); + pesquisaAvancada.set_Nome(x.get_Controle().get_Cliente().get_Nome()); + pesquisaAvancada.set_Pesquisa(string.Concat(" NÚMERO DA APÓLICE: ", x.get_Apolice())); + return pesquisaAvancada; + }).ToList()); + break; + } + case 5: + { + this.Pesquisas = new ObservableCollection(await (new PatrimonialServico()).BuscarImobiliaria(this.Pesquisa, this.Status, vendedorUsuarios1)); + break; + } + case 6: + { + this.Pesquisas = new ObservableCollection(await (new AutoServico()).BuscarItem(this.Pesquisa, this.Status, vendedorUsuarios1, this.TipoBusca)); + break; + } + case 7: + { + this.Pesquisas = new ObservableCollection(await (new PatrimonialServico()).BuscarLocatario(this.Pesquisa, this.Status, vendedorUsuarios1)); + break; + } + case 8: + { + List documentos2 = await (new ApoliceServico()).BuscarApolice(this.Pesquisa, this.Status, vendedorUsuarios1, "", this.TipoBusca); + DialogPesquisaAvancadaViewModel dialogPesquisaAvancadaViewModel2 = this; + List documentos3 = documentos2; + dialogPesquisaAvancadaViewModel2.Pesquisas = new ObservableCollection(documentos3.Select((Documento x) => { + string str; + PesquisaAvancada pesquisaAvancada = new PesquisaAvancada(); + pesquisaAvancada.set_IdCliente(x.get_Controle().get_Cliente().get_Id()); + pesquisaAvancada.set_IdDocumento(x.get_Id()); + pesquisaAvancada.set_Nome(x.get_Controle().get_Cliente().get_Nome()); + PesquisaAvancada pesquisaAvancada1 = pesquisaAvancada; + if (!x.get_Vigencia2().HasValue) + { + str = string.Format("NÚMERO DA APÓLICE: {0} - VIGÊNCIA INICIAL: {1:d} - NÚMERO DO ENDOSSO: {2}", x.get_Apolice(), x.get_Vigencia1(), x.get_Endosso()); + } + else + { + object[] apolice = new object[] { x.get_Apolice(), x.get_Vigencia1(), null, null }; + apolice[2] = x.get_Vigencia2().Value; + apolice[3] = x.get_Endosso(); + str = string.Format("NÚMERO DA APÓLICE: {0} - VIGÊNCIA INICIAL: {1:d} - VIGÊNCIA FINAL: {2:d} - NÚMERO DO ENDOSSO: {3}", apolice); + } + pesquisaAvancada1.set_Pesquisa(str); + return pesquisaAvancada; + }).ToList()); + break; + } + case 9: + { + List sinistros = await (new SinistroServico()).BuscarSinistros(this.Pesquisa); + DialogPesquisaAvancadaViewModel observableCollection3 = this; + List sinistros1 = sinistros; + observableCollection3.Pesquisas = new ObservableCollection(sinistros1.Select((Sinistro x) => { + PesquisaAvancada pesquisaAvancada = new PesquisaAvancada(); + pesquisaAvancada.set_Nome(x.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Cliente().get_Nome()); + pesquisaAvancada.set_Pesquisa(string.Concat(new string[] { "NÚMERO DO SINISTRO: ", x.get_Numero(), " - NÚMERO DA APÓLICE: ", x.get_ControleSinistro().get_Item().get_Documento().get_Apolice(), " - ITEM: ", x.get_ItemSinistrado() })); + pesquisaAvancada.set_IdCliente(x.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Cliente().get_Id()); + pesquisaAvancada.set_IdDocumento(x.get_ControleSinistro().get_Item().get_Documento().get_Id()); + pesquisaAvancada.set_IdItem(x.get_ControleSinistro().get_Item().get_Id()); + pesquisaAvancada.set_IdSinistro(x.get_Id()); + return pesquisaAvancada; + }).ToList()); + break; + } + case 10: + { + List documentos4 = await (new ApoliceServico()).BuscarApolice(this.Pesquisa, this.Status, vendedorUsuarios1, "Proposta", this.TipoBusca); + DialogPesquisaAvancadaViewModel dialogPesquisaAvancadaViewModel3 = this; + List documentos5 = documentos4; + dialogPesquisaAvancadaViewModel3.Pesquisas = new ObservableCollection(documentos5.Select((Documento x) => { + PesquisaAvancada pesquisaAvancada = new PesquisaAvancada(); + pesquisaAvancada.set_IdCliente(x.get_Controle().get_Cliente().get_Id()); + pesquisaAvancada.set_IdDocumento(x.get_Id()); + pesquisaAvancada.set_Nome(x.get_Controle().get_Cliente().get_Nome()); + pesquisaAvancada.set_Pesquisa(string.Concat(new string[] { "NÚMERO DA PROPOSTA: ", x.get_Proposta(), " - NÚMERO DA APÓLICE: ", x.get_Apolice(), " - NÚMERO DO ENDOSSO: ", x.get_Endosso() })); + return pesquisaAvancada; + }).ToList()); + break; + } + case 11: + { + List documentos6 = await (new ApoliceServico()).BuscarApolice(this.Pesquisa, this.Status, vendedorUsuarios1, "NumeroEndosso", this.TipoBusca); + DialogPesquisaAvancadaViewModel observableCollection4 = this; + List documentos7 = documentos6; + observableCollection4.Pesquisas = new ObservableCollection(documentos7.Select((Documento x) => { + PesquisaAvancada pesquisaAvancada = new PesquisaAvancada(); + pesquisaAvancada.set_IdCliente(x.get_Controle().get_Cliente().get_Id()); + pesquisaAvancada.set_IdDocumento(x.get_Id()); + pesquisaAvancada.set_Nome(x.get_Controle().get_Cliente().get_Nome()); + pesquisaAvancada.set_Pesquisa(string.Concat("NÚMERO DA APÓLICE: ", x.get_Apolice(), " - NÚMERO DO ENDOSSO: ", x.get_Endosso())); + return pesquisaAvancada; + }).ToList()); + break; + } + case 12: + { + List clientes = await (new ClienteServico()).BuscarObsCliente(this.Pesquisa); + DialogPesquisaAvancadaViewModel dialogPesquisaAvancadaViewModel4 = this; + List clientes1 = clientes; + dialogPesquisaAvancadaViewModel4.Pesquisas = new ObservableCollection(clientes1.Select((Cliente x) => { + PesquisaAvancada pesquisaAvancada = new PesquisaAvancada(); + pesquisaAvancada.set_Nome(x.get_Nome()); + pesquisaAvancada.set_Pesquisa(string.Concat("OBSERVAÇÃO: ", x.get_Observacao())); + pesquisaAvancada.set_IdCliente(x.get_Id()); + return pesquisaAvancada; + }).ToList()); + break; + } + case 13: + { + List clientes2 = await (new ClienteServico()).BuscarPastaCliente(this.Pesquisa, this.TipoBusca); + DialogPesquisaAvancadaViewModel observableCollection5 = this; + List clientes3 = clientes2; + observableCollection5.Pesquisas = new ObservableCollection(clientes3.Select((Cliente x) => { + PesquisaAvancada pesquisaAvancada = new PesquisaAvancada(); + pesquisaAvancada.set_Nome(x.get_Nome()); + pesquisaAvancada.set_Pesquisa(string.Concat("PASTA: ", x.get_Pasta())); + pesquisaAvancada.set_IdCliente(x.get_Id()); + return pesquisaAvancada; + }).ToList()); + break; + } + case 14: + { + this.Pesquisas = new ObservableCollection(await (new AutoServico()).BuscarPlaca(this.Pesquisa, this.Status, vendedorUsuarios1, this.TipoBusca)); + break; + } + case 15: + { + List documentos8 = await (new ApoliceServico()).BuscarApolice(this.Pesquisa, this.Status, vendedorUsuarios1, "PedidoEndosso", this.TipoBusca); + DialogPesquisaAvancadaViewModel dialogPesquisaAvancadaViewModel5 = this; + List documentos9 = documentos8; + dialogPesquisaAvancadaViewModel5.Pesquisas = new ObservableCollection(documentos9.Select((Documento x) => { + PesquisaAvancada pesquisaAvancada = new PesquisaAvancada(); + pesquisaAvancada.set_IdCliente(x.get_Controle().get_Cliente().get_Id()); + pesquisaAvancada.set_IdDocumento(x.get_Id()); + pesquisaAvancada.set_Nome(x.get_Controle().get_Cliente().get_Nome()); + pesquisaAvancada.set_Pesquisa(string.Concat(new string[] { "PROPOSTA ENDOSSO: ", x.get_PropostaEndosso(), " - NÚMERO DA APÓLICE: ", x.get_Apolice(), " - NÚMERO DO ENDOSSO: ", x.get_Endosso() })); + return pesquisaAvancada; + }).ToList()); + break; + } + case 16: + { + ClienteServico clienteServico = new ClienteServico(); + string str1 = ValidationHelper.FormatarTelefone(this.Pesquisa); + string str2 = str1; + this.Pesquisa = str1; + List clienteTelefones = await clienteServico.BuscarTelefonesClientes(str2); + DialogPesquisaAvancadaViewModel observableCollection6 = this; + List clienteTelefones1 = clienteTelefones; + observableCollection6.Pesquisas = new ObservableCollection(clienteTelefones1.Select((ClienteTelefone x) => { + PesquisaAvancada pesquisaAvancada = new PesquisaAvancada(); + pesquisaAvancada.set_Nome(x.get_Cliente().get_Nome()); + pesquisaAvancada.set_Pesquisa(string.Concat("TELEFONE: ", x.get_Prefixo(), "-", x.get_Numero())); + pesquisaAvancada.set_IdCliente(x.get_Cliente().get_Id()); + return pesquisaAvancada; + }).ToList()); + break; + } + case 17: + { + List documentos10 = await (new ParcelaServico()).BuscarFatura(this.Pesquisa); + DialogPesquisaAvancadaViewModel dialogPesquisaAvancadaViewModel6 = this; + List documentos11 = documentos10; + dialogPesquisaAvancadaViewModel6.Pesquisas = new ObservableCollection(documentos11.Select((Documento x) => { + PesquisaAvancada pesquisaAvancada = new PesquisaAvancada(); + pesquisaAvancada.set_IdDocumento(x.get_Id()); + pesquisaAvancada.set_Nome(x.get_Controle().get_Cliente().get_Nome()); + pesquisaAvancada.set_Pesquisa(string.Concat("CÓDIGO DA FATURA: ", x.get_Endosso())); + pesquisaAvancada.set_IdCliente(x.get_Controle().get_Cliente().get_Id()); + return pesquisaAvancada; + }).ToList()); + break; + } + case 18: + { + this.Pesquisas = new ObservableCollection(await (new ItemServico()).BuscaItensPorObs(this.Pesquisa, this.Status, vendedorUsuarios1, this.TipoBusca)); + break; + } + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/DialogProspeccaoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/DialogProspeccaoViewModel.cs new file mode 100644 index 0000000..f95e6d6 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/DialogProspeccaoViewModel.cs @@ -0,0 +1,352 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Seguros; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Generic +{ + public class DialogProspeccaoViewModel : BaseSegurosViewModel + { + private readonly ClienteServico _servico; + + private Prospeccao _selectedProspeccao; + + private bool _isVisibleAnexos; + + private ObservableCollection _arquivosAnexados = new ObservableCollection(); + + private Gestor.Model.Domain.Common.ArquivoDigital _selectedAnexado = new Gestor.Model.Domain.Common.ArquivoDigital(); + + private ObservableCollection _arquivos = new ObservableCollection(); + + private Visibility _visibilityStatusPersonalizado; + + private ObservableCollection _usuarios; + + private ObservableCollection _vendedores; + + private DateTime _dataAgendamento; + + private DateTime _horaAgendamento; + + private List _produtos = Recursos.Produtos; + + private ObservableCollection _statusProspeccao; + + private List _ramos = Recursos.Ramos; + + public ObservableCollection Arquivos + { + get + { + return this._arquivos; + } + set + { + this._arquivos = value; + base.OnPropertyChanged("Arquivos"); + } + } + + public ObservableCollection ArquivosAnexados + { + get + { + return this._arquivosAnexados; + } + set + { + List list; + this._arquivosAnexados = value; + base.OnPropertyChanged("ArquivosAnexados"); + this.IsVisibleAnexos = (value != null ? value.Count > 0 : false); + Prospeccao selectedProspeccao = this.SelectedProspeccao; + if (value != null) + { + list = value.ToList(); + } + else + { + list = null; + } + selectedProspeccao.set_Anexos(list); + } + } + + public DateTime DataAgendamento + { + get + { + return this._dataAgendamento; + } + set + { + this._dataAgendamento = value; + if (this.SelectedProspeccao.get_Tarefa() != null) + { + this.SelectedProspeccao.get_Tarefa().set_Agendamento(DateTime.Parse(string.Format("{0:d} {1:T}", value, this.SelectedProspeccao.get_Tarefa().get_Agendamento()))); + } + base.OnPropertyChanged("DataAgendamento"); + } + } + + public DateTime HoraAgendamento + { + get + { + return this._horaAgendamento; + } + set + { + this._horaAgendamento = value; + if (this.SelectedProspeccao.get_Tarefa() != null) + { + this.SelectedProspeccao.get_Tarefa().set_Agendamento(DateTime.Parse(string.Format("{0:d} {1:T}", this.SelectedProspeccao.get_Tarefa().get_Agendamento(), value))); + } + base.OnPropertyChanged("HoraAgendamento"); + } + } + + public bool IsVisibleAnexos + { + get + { + return this._isVisibleAnexos; + } + set + { + this._isVisibleAnexos = value; + base.OnPropertyChanged("IsVisibleAnexos"); + } + } + + public List Produtos + { + get + { + return this._produtos; + } + set + { + this._produtos = value; + base.OnPropertyChanged("Produtos"); + } + } + + public List Ramos + { + get + { + return this._ramos; + } + set + { + this._ramos = value; + base.OnPropertyChanged("Ramos"); + } + } + + public Gestor.Model.Domain.Common.ArquivoDigital SelectedAnexado + { + get + { + return this._selectedAnexado; + } + set + { + this._selectedAnexado = value; + base.OnPropertyChanged("SelectedAnexado"); + } + } + + public Prospeccao SelectedProspeccao + { + get + { + return this._selectedProspeccao; + } + set + { + this._selectedProspeccao = value; + base.OnPropertyChanged("SelectedProspeccao"); + } + } + + public ObservableCollection StatusProspeccao + { + get + { + return this._statusProspeccao; + } + set + { + this._statusProspeccao = value; + base.OnPropertyChanged("StatusProspeccao"); + } + } + + public ObservableCollection Usuarios + { + get + { + return this._usuarios; + } + set + { + this._usuarios = value; + base.OnPropertyChanged("Usuarios"); + } + } + + public ObservableCollection Vendedores + { + get + { + return this._vendedores; + } + set + { + this._vendedores = value; + base.OnPropertyChanged("Vendedores"); + } + } + + public Visibility VisibilityStatusPersonalizado + { + get + { + return this._visibilityStatusPersonalizado; + } + set + { + this._visibilityStatusPersonalizado = value; + base.OnPropertyChanged("VisibilityStatusPersonalizado"); + } + } + + public DialogProspeccaoViewModel(Prospeccao prospeccao) + { + DateTime? vigenciaFinal; + DateTime? nullable; + DateTime? nullable1; + this._servico = new ClienteServico(); + this.Usuarios = new ObservableCollection(Recursos.Usuarios.Where((Usuario x) => { + if (Recursos.Usuario.get_IdEmpresa() != (long)1 && x.get_IdEmpresa() != Recursos.Usuario.get_IdEmpresa()) + { + return false; + } + return !x.get_Excluido(); + }).OrderBy((Usuario x) => x.get_Nome()).ToList()); + this.Vendedores = new ObservableCollection(Recursos.Vendedores.Where((Vendedor x) => { + if (Recursos.Usuario.get_IdEmpresa() != (long)1 && x.get_IdEmpresa() != Recursos.Usuario.get_IdEmpresa()) + { + return false; + } + return x.get_Ativo(); + }).OrderBy((Vendedor x) => x.get_Nome()).ToList()); + this.StatusProspeccao = new ObservableCollection(( + from x in Recursos.StatusProspeccao + where x.get_Ativo() + orderby x.get_Nome() + select x).ToList()); + if (this.StatusProspeccao == null || this.StatusProspeccao.Count == 0) + { + this.VisibilityStatusPersonalizado = Visibility.Collapsed; + } + if (prospeccao.get_Vendedor() == null) + { + prospeccao.set_Vendedor(this.Vendedores.First((Vendedor x) => x.get_Corretora())); + } + if (prospeccao.get_Tarefa() == null) + { + Prospeccao prospeccao1 = prospeccao; + Tarefa tarefa = new Tarefa(); + tarefa.set_Titulo("PROSPECÇÃO"); + tarefa.set_Entidade(5); + tarefa.set_IdEntidade(prospeccao.get_Id()); + tarefa.set_Usuario(Recursos.Usuario); + vigenciaFinal = prospeccao.get_VigenciaFinal(); + tarefa.set_Agendamento((vigenciaFinal.HasValue ? vigenciaFinal.GetValueOrDefault() : Funcoes.GetNetworkTime())); + tarefa.set_Cliente(prospeccao.get_Nome()); + prospeccao1.set_Tarefa(tarefa); + } + this.SelectedProspeccao = prospeccao; + Tarefa tarefa1 = prospeccao.get_Tarefa(); + if (tarefa1 != null) + { + nullable = new DateTime?(tarefa1.get_Agendamento()); + } + else + { + vigenciaFinal = null; + nullable = vigenciaFinal; + } + vigenciaFinal = nullable; + this.DataAgendamento = vigenciaFinal.Value; + Tarefa tarefa2 = prospeccao.get_Tarefa(); + if (tarefa2 != null) + { + nullable1 = new DateTime?(tarefa2.get_Agendamento()); + } + else + { + vigenciaFinal = null; + nullable1 = vigenciaFinal; + } + vigenciaFinal = nullable1; + this.HoraAgendamento = vigenciaFinal.Value; + } + + public async void Anexar() + { + ObservableCollection arquivos = this.Arquivos; + List list = arquivos.Select((IndiceArquivoDigital x) => { + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital = new Gestor.Model.Domain.Common.ArquivoDigital(); + arquivoDigital.set_Descricao(x.get_Descricao()); + arquivoDigital.set_Extensao(x.get_Extensao()); + return arquivoDigital; + }).ToList(); + List arquivoDigitals = await base.AddAttachments(this.ArquivosAnexados.ToList(), list); + if (arquivoDigitals != null) + { + arquivoDigitals.AddRange(this.ArquivosAnexados); + this.ArquivosAnexados = new ObservableCollection(arquivoDigitals); + } + } + + public async Task BuscarInfoCliente(Cliente cliente) + { + cliente = await this._servico.BuscarCliente(cliente.get_Id()); + Cliente cliente1 = cliente; + ObservableCollection observableCollection = await this._servico.BuscarTelefonesAsync(cliente.get_Id()); + cliente1.set_Telefones(observableCollection); + cliente1 = null; + cliente1 = cliente; + ObservableCollection observableCollection1 = await this._servico.BuscarEmailsAsync(cliente.get_Id()); + cliente1.set_Emails(observableCollection1); + cliente1 = null; + return cliente; + } + + public void Delete(Gestor.Model.Domain.Common.ArquivoDigital arquivo) + { + if (this.SelectedAnexado == null) + { + return; + } + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital = this.ArquivosAnexados.First((Gestor.Model.Domain.Common.ArquivoDigital x) => x.get_Descricao() == arquivo.get_Descricao()); + this.ArquivosAnexados.Remove(arquivoDigital); + this.ArquivosAnexados = new ObservableCollection(this.ArquivosAnexados); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/DialogTarefaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/DialogTarefaViewModel.cs new file mode 100644 index 0000000..9041cd3 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/DialogTarefaViewModel.cs @@ -0,0 +1,296 @@ +using CsQuery.ExtensionMethods.Internal; +using Gestor.Application.Helpers; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Windows; + +namespace Gestor.Application.ViewModels.Generic +{ + public class DialogTarefaViewModel : BaseSegurosViewModel + { + private bool _showPublica; + + private bool _nota; + + private Visibility _cabecalho; + + private Visibility _agendamento; + + private Visibility _status; + + private List _telefones; + + private ObservableCollection _usuarios; + + private Gestor.Model.Domain.Ferramentas.Tarefa _tarefa; + + private DateTime _dataAgendamento = Funcoes.GetNetworkTime(); + + private DateTime _horaAgendamento = Funcoes.GetNetworkTime(); + + private ObservableCollection _responsaveis = new ObservableCollection(); + + private Usuario _selectedUsuario; + + private bool _isAnotacoes = true; + + public Visibility Agendamento + { + get + { + return this._agendamento; + } + set + { + this._agendamento = value; + this.MutateVerbose(ref this._agendamento, value, this.OnRaisePropertyChanged(), "Agendamento"); + } + } + + public Visibility Cabecalho + { + get + { + return this._cabecalho; + } + set + { + this._cabecalho = value; + this.MutateVerbose(ref this._cabecalho, value, this.OnRaisePropertyChanged(), "Cabecalho"); + } + } + + public DateTime DataAgendamento + { + get + { + return this._dataAgendamento; + } + set + { + this._dataAgendamento = value; + if (this.Tarefa != null) + { + this.Tarefa.set_Agendamento(DateTime.Parse(string.Format("{0:d} {1:T}", value, this.Tarefa.get_Agendamento()))); + } + this.MutateVerbose(ref this._dataAgendamento, value, this.OnRaisePropertyChanged(), "DataAgendamento"); + } + } + + public DateTime HoraAgendamento + { + get + { + return this._horaAgendamento; + } + set + { + this._horaAgendamento = value; + if (this.Tarefa != null) + { + this.Tarefa.set_Agendamento(DateTime.Parse(string.Format("{0:d} {1:T}", this.Tarefa.get_Agendamento(), value))); + } + this.MutateVerbose(ref this._horaAgendamento, value, this.OnRaisePropertyChanged(), "HoraAgendamento"); + } + } + + public bool IsAnotacoes + { + get + { + return this._isAnotacoes; + } + set + { + this._isAnotacoes = value; + base.OnPropertyChanged("IsAnotacoes"); + } + } + + public bool Nota + { + get + { + return this._nota; + } + set + { + this._nota = value; + if (!value) + { + return; + } + this.Cabecalho = Visibility.Collapsed; + this.Status = Visibility.Collapsed; + } + } + + public ObservableCollection Responsaveis + { + get + { + return this._responsaveis; + } + set + { + this._responsaveis = value; + base.OnPropertyChanged("Responsaveis"); + } + } + + public Usuario SelectedUsuario + { + get + { + return this._selectedUsuario; + } + set + { + this._selectedUsuario = value; + base.OnPropertyChanged("SelectedUsuario"); + } + } + + public bool ShowPublica + { + get + { + return this._showPublica; + } + set + { + this._showPublica = value; + base.OnPropertyChanged("ShowPublica"); + } + } + + public Visibility Status + { + get + { + return this._status; + } + set + { + this._status = value; + this.MutateVerbose(ref this._status, value, this.OnRaisePropertyChanged(), "Status"); + } + } + + public Gestor.Model.Domain.Ferramentas.Tarefa Tarefa + { + get + { + return this._tarefa; + } + set + { + DateTime networkTime = Funcoes.GetNetworkTime(); + this.DataAgendamento = (value != null ? value.get_Agendamento() : networkTime); + this.HoraAgendamento = (value != null ? value.get_Agendamento() : networkTime); + this.MutateVerbose(ref this._tarefa, value, this.OnRaisePropertyChanged(), "Tarefa"); + } + } + + public List Telefones + { + get + { + return this._telefones; + } + set + { + this._telefones = value; + this.MutateVerbose>(ref this._telefones, value, this.OnRaisePropertyChanged(), "Telefones"); + } + } + + public ObservableCollection Usuarios + { + get + { + return this._usuarios; + } + set + { + this._usuarios = value; + this.MutateVerbose>(ref this._usuarios, value, this.OnRaisePropertyChanged(), "Usuarios"); + } + } + + public DialogTarefaViewModel(Gestor.Model.Domain.Ferramentas.Tarefa tarefa, List telefones, bool nota = false, bool agendamento = false) + { + this.ShowPublica = (!nota ? false : tarefa.get_HabilitarPublica()); + this.Telefones = telefones; + this.Usuarios = new ObservableCollection(Recursos.Usuarios.Where((Usuario x) => { + if (Recursos.Usuario.get_IdEmpresa() != (long)1 && x.get_IdEmpresa() != Recursos.Usuario.get_IdEmpresa()) + { + return false; + } + return !x.get_Excluido(); + }).OrderBy((Usuario x) => x.get_Nome()).ToList()); + this.Nota = nota; + if (tarefa.get_Entidade() == 1) + { + tarefa.set_Anotacoes(tarefa.get_Descricao()); + tarefa.set_Descricao(string.Empty); + } + if (agendamento) + { + this.Agendamento = Visibility.Collapsed; + } + if (tarefa.get_UsuariosVinculados() != null) + { + ExtensionMethods.AddRange(this.Responsaveis, tarefa.get_UsuariosVinculados()); + } + this.Responsaveis.ToList().ForEach((Usuario x) => this.Usuarios.Remove(this.Usuarios.FirstOrDefault((Usuario u) => u.get_Id() == x.get_Id()))); + this.Tarefa = tarefa; + } + + public void AdcionarResponsavel() + { + if (this.SelectedUsuario == null || this.Responsaveis.Any((Usuario x) => (object)x == (object)this.SelectedUsuario)) + { + return; + } + this.Responsaveis.Add(this.SelectedUsuario); + this.Tarefa.set_UsuariosVinculados(this.Responsaveis.ToList()); + this.Usuarios.Remove(this.SelectedUsuario); + this.SelectedUsuario = null; + } + + private Action OnRaisePropertyChanged() + { + return (PropertyChangedEventArgs args) => { + PropertyChangedEventHandler propertyChangedEventHandler = this.RaisePropertyChanged; + if (propertyChangedEventHandler == null) + { + return; + } + propertyChangedEventHandler(this, args); + }; + } + + public void RemoverResponsavel(Usuario selectedUsuario) + { + if (selectedUsuario == null) + { + return; + } + this.Responsaveis.Remove(selectedUsuario); + this.Tarefa.set_UsuariosVinculados(this.Responsaveis.ToList()); + this.Usuarios.Add(selectedUsuario); + selectedUsuario = null; + } + + public event PropertyChangedEventHandler RaisePropertyChanged; + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/DialogTrilhaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/DialogTrilhaViewModel.cs new file mode 100644 index 0000000..1735419 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/DialogTrilhaViewModel.cs @@ -0,0 +1,102 @@ +using Gestor.Application.Helpers; +using Gestor.Model.Domain.Ferramentas; +using System; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Gestor.Application.ViewModels.Generic +{ + public class DialogTrilhaViewModel : INotifyPropertyChanged + { + private Gestor.Model.Domain.Ferramentas.Trilha _trilha; + + private ObservableCollection _fases; + + private Fase _selectedFase; + + public ObservableCollection Fases + { + get + { + return this._fases; + } + set + { + this.MutateVerbose>(ref this._fases, value, this.RaisePropertyChanged(), "Fases"); + } + } + + public Fase SelectedFase + { + get + { + return this._selectedFase; + } + set + { + this.MutateVerbose(ref this._selectedFase, value, this.RaisePropertyChanged(), "SelectedFase"); + } + } + + public Gestor.Model.Domain.Ferramentas.Trilha Trilha + { + get + { + return this._trilha; + } + set + { + this.MutateVerbose(ref this._trilha, value, this.RaisePropertyChanged(), "Trilha"); + } + } + + public DialogTrilhaViewModel() + { + } + + public void AdicionarFase() + { + if (this.Fases == null) + { + this.Fases = new ObservableCollection(); + } + ObservableCollection fases = this.Fases; + Fase fase = new Fase(); + fase.set_Titulo("TÍTULO"); + fase.set_Descricao("DESCRIÇÃO"); + fases.Add(fase); + this.Fases = new ObservableCollection(this.Fases); + this.Trilha.set_Fases(this.Fases.ToList()); + } + + public void ExcluirFase(Fase fase) + { + this.Fases.RemoveAt(this.Fases.IndexOf(fase)); + this.Fases = new ObservableCollection(this.Fases); + this.Trilha.set_Fases(this.Fases.ToList()); + } + + private Action RaisePropertyChanged() + { + return (PropertyChangedEventArgs args) => { + PropertyChangedEventHandler propertyChangedEventHandler = this.PropertyChanged; + if (propertyChangedEventHandler == null) + { + return; + } + propertyChangedEventHandler(this, args); + }; + } + + public void UpdateFase(int index) + { + this.Fases[index] = this.SelectedFase; + this.Trilha.set_Fases(this.Fases.ToList()); + } + + public event PropertyChangedEventHandler PropertyChanged; + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/DialogViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/DialogViewModel.cs new file mode 100644 index 0000000..523b64f --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/DialogViewModel.cs @@ -0,0 +1,87 @@ +using Gestor.Application.Helpers; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Windows; + +namespace Gestor.Application.ViewModels.Generic +{ + public class DialogViewModel : INotifyPropertyChanged + { + private string _message; + + private string _acceptContent; + + private string _cancelContent; + + private Visibility _cancelVisibility; + + public string AcceptContent + { + get + { + return this._acceptContent; + } + set + { + this.MutateVerbose(ref this._acceptContent, value, this.RaisePropertyChanged(), "AcceptContent"); + } + } + + public string CancelContent + { + get + { + return this._cancelContent; + } + set + { + this.CancelVisibility = (string.IsNullOrEmpty(value) ? Visibility.Collapsed : Visibility.Visible); + this.MutateVerbose(ref this._cancelContent, value, this.RaisePropertyChanged(), "CancelContent"); + } + } + + public Visibility CancelVisibility + { + get + { + return this._cancelVisibility; + } + set + { + this.MutateVerbose(ref this._cancelVisibility, value, this.RaisePropertyChanged(), "CancelVisibility"); + } + } + + public string Message + { + get + { + return this._message; + } + set + { + this.MutateVerbose(ref this._message, value, this.RaisePropertyChanged(), "Message"); + } + } + + public DialogViewModel() + { + } + + private Action RaisePropertyChanged() + { + return (PropertyChangedEventArgs args) => { + PropertyChangedEventHandler propertyChangedEventHandler = this.PropertyChanged; + if (propertyChangedEventHandler == null) + { + return; + } + propertyChangedEventHandler(this, args); + }; + } + + public event PropertyChangedEventHandler PropertyChanged; + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/DialogVinculoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/DialogVinculoViewModel.cs new file mode 100644 index 0000000..1d526ea --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/DialogVinculoViewModel.cs @@ -0,0 +1,257 @@ +using Gestor.Application.Helpers; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Gestor.Application.ViewModels.Generic +{ + public class DialogVinculoViewModel : BaseViewModel + { + private Gestor.Model.Domain.Seguros.Repasse _repasse; + + private List _tiposVendedor; + + private ObservableCollection _vendedoresAtivos; + + private Vendedor _selectedVendedor; + + private ObservableCollection _repassesVinculo; + + private Gestor.Model.Domain.Seguros.Repasse _selectedRepasse; + + private TipoVendedor _selectedTipo; + + private TipoVendedor _selectedTipoVinculo; + + public Gestor.Model.Domain.Seguros.Repasse Repasse + { + get + { + return this._repasse; + } + set + { + this._repasse = value; + base.OnPropertyChanged("Repasse"); + } + } + + public List Repasses + { + get; + set; + } + + public ObservableCollection RepassesVinculo + { + get + { + return this._repassesVinculo; + } + set + { + this._repassesVinculo = value; + base.OnPropertyChanged("RepassesVinculo"); + } + } + + public Gestor.Model.Domain.Seguros.Repasse SelectedRepasse + { + get + { + return this._selectedRepasse; + } + set + { + this._selectedRepasse = value; + this.Vinculo.set_RepasseVinculo(value); + base.OnPropertyChanged("SelectedRepasse"); + } + } + + public TipoVendedor SelectedTipo + { + get + { + return this._selectedTipo; + } + set + { + this._selectedTipo = value; + this.Vinculo.set_TipoVendedor(value); + base.OnPropertyChanged("SelectedTipo"); + } + } + + public TipoVendedor SelectedTipoVinculo + { + get + { + return this._selectedTipoVinculo; + } + set + { + this._selectedTipoVinculo = value; + this.Vinculo.set_TipoVendedorVinculo(value); + base.OnPropertyChanged("SelectedTipoVinculo"); + } + } + + public Vendedor SelectedVendedor + { + get + { + return this._selectedVendedor; + } + set + { + ObservableCollection observableCollection; + this._selectedVendedor = value; + if (value == null) + { + observableCollection = null; + } + else + { + observableCollection = new ObservableCollection( + from x in this.Repasses + where x.get_Vendedor().get_Id() == value.get_Id() + select x); + } + this.RepassesVinculo = observableCollection; + base.OnPropertyChanged("SelectedVendedor"); + } + } + + public List TiposVendedor + { + get + { + return this._tiposVendedor; + } + set + { + this._tiposVendedor = value; + base.OnPropertyChanged("TiposVendedor"); + } + } + + public List Vendedores + { + get; + set; + } + + public ObservableCollection VendedoresAtivos + { + get + { + return this._vendedoresAtivos; + } + set + { + this._vendedoresAtivos = value; + base.OnPropertyChanged("VendedoresAtivos"); + } + } + + public VinculoRepasse Vinculo + { + get; + set; + } + + public DialogVinculoViewModel(VinculoRepasse vinculo, List repasses, Gestor.Model.Domain.Seguros.Repasse repasse) + { + List tipoVendedor = Recursos.TipoVendedor; + if (tipoVendedor != null) + { + list = tipoVendedor.Where((TipoVendedor x) => { + if (!x.get_Ativo().HasValue) + { + return true; + } + return x.get_Ativo().Value; + }).ToList(); + } + else + { + list = null; + } + this._tiposVendedor = list; + this._vendedoresAtivos = new ObservableCollection(); + this._selectedVendedor = new Vendedor(); + this._repassesVinculo = new ObservableCollection(); + this._selectedRepasse = new Gestor.Model.Domain.Seguros.Repasse(); + this._selectedTipo = new TipoVendedor(); + this._selectedTipoVinculo = new TipoVendedor(); + base(); + List list; + Vendedor vendedor; + Gestor.Model.Domain.Seguros.Repasse repasse1; + TipoVendedor tipoVendedor1; + TipoVendedor tipoVendedor2; + DialogVinculoViewModel dialogVinculoViewModel = this; + this.Repasse = repasse; + this.Repasses = repasses; + VinculoRepasse vinculoRepasse = new VinculoRepasse(); + vinculoRepasse.set_IdRepasse(vinculo.get_IdRepasse()); + vinculoRepasse.set_Id(vinculo.get_Id()); + this.Vinculo = vinculoRepasse; + this.Vendedores = ( + from x in this.Repasses + group x by x.get_Vendedor().get_Id() into x + select x.First().get_Vendedor() into x + orderby x.get_Nome() + select x).ToList(); + long id = this.Repasses.First((Gestor.Model.Domain.Seguros.Repasse x) => x.get_Id() == dialogVinculoViewModel.Vinculo.get_IdRepasse()).get_Vendedor().get_Id(); + this.VendedoresAtivos = new ObservableCollection(this.Vendedores.Where((Vendedor x) => { + if (x.get_IdEmpresa() != Recursos.Usuario.get_IdEmpresa() || !x.get_Ativo() || x.get_Corretora()) + { + return false; + } + return x.get_Id() != id; + })); + if (vinculo.get_RepasseVinculo() != null) + { + vendedor = this.VendedoresAtivos.FirstOrDefault((Vendedor x) => x.get_Id() == vinculo.get_RepasseVinculo().get_Vendedor().get_Id()); + } + else + { + vendedor = null; + } + this.SelectedVendedor = vendedor; + if (vinculo.get_RepasseVinculo() != null) + { + repasse1 = this.RepassesVinculo.FirstOrDefault((Gestor.Model.Domain.Seguros.Repasse x) => x.get_Id() == vinculo.get_RepasseVinculo().get_Id()); + } + else + { + repasse1 = null; + } + this.SelectedRepasse = repasse1; + if (vinculo.get_TipoVendedor() != null) + { + tipoVendedor1 = this.TiposVendedor.FirstOrDefault((TipoVendedor x) => x.get_Id() == vinculo.get_TipoVendedor().get_Id()); + } + else + { + tipoVendedor1 = null; + } + this.SelectedTipo = tipoVendedor1; + if (vinculo.get_TipoVendedorVinculo() != null) + { + tipoVendedor2 = this.TiposVendedor.FirstOrDefault((TipoVendedor x) => x.get_Id() == vinculo.get_TipoVendedorVinculo().get_Id()); + } + else + { + tipoVendedor2 = null; + } + this.SelectedTipoVinculo = tipoVendedor2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/ErrorDialogViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/ErrorDialogViewModel.cs new file mode 100644 index 0000000..0a9224b --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/ErrorDialogViewModel.cs @@ -0,0 +1,49 @@ +using Gestor.Application.Helpers; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Gestor.Application.ViewModels.Generic +{ + public class ErrorDialogViewModel : DialogViewModel, INotifyPropertyChanged + { + private List> _erros; + + public List> Erros + { + get + { + List> keyValuePairs = new List>(); + foreach (KeyValuePair _erro in this._erros) + { + keyValuePairs.Add(new KeyValuePair(_erro.Key.ToUpper(), _erro.Value.ToUpper())); + } + return keyValuePairs; + } + set + { + this.MutateVerbose>>(ref this._erros, value, this.RaisePropertyChanged(), "Erros"); + } + } + + public ErrorDialogViewModel() + { + } + + private Action RaisePropertyChanged() + { + return (PropertyChangedEventArgs args) => { + PropertyChangedEventHandler propertyChangedEventHandler = this.PropertyChanged; + if (propertyChangedEventHandler == null) + { + return; + } + propertyChangedEventHandler(this, args); + }; + } + + public event PropertyChangedEventHandler PropertyChanged; + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/ExtratoComissaoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/ExtratoComissaoViewModel.cs new file mode 100644 index 0000000..7630bbd --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/ExtratoComissaoViewModel.cs @@ -0,0 +1,147 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Generic +{ + public class ExtratoComissaoViewModel : BaseViewModel + { + private ServicoExtrato _servico; + + private bool _apelido; + + private List _seguradoras; + + private DateTime _inicio; + + private DateTime _fim; + + private ObservableCollection _extratos; + + public bool Apelido + { + get + { + return this._apelido; + } + set + { + this._apelido = value; + base.OnPropertyChanged("Apelido"); + } + } + + public ObservableCollection Extratos + { + get + { + return this._extratos; + } + set + { + this._extratos = value; + base.OnPropertyChanged("Extratos"); + } + } + + public DateTime Fim + { + get + { + return this._fim; + } + set + { + this._fim = value; + base.OnPropertyChanged("Fim"); + } + } + + public DateTime Inicio + { + get + { + return this._inicio; + } + set + { + this._inicio = value; + base.OnPropertyChanged("Inicio"); + } + } + + public List Seguradoras + { + get + { + return this._seguradoras; + } + set + { + this._seguradoras = value; + base.OnPropertyChanged("Seguradoras"); + } + } + + public ExtratoComissaoViewModel(List seguradoras) + { + DateTime date = Funcoes.GetNetworkTime().Date; + int year = date.Year; + date = Funcoes.GetNetworkTime().Date; + this._inicio = new DateTime(year, date.Month, 1); + this._fim = Funcoes.GetNetworkTime().Date; + base(); + this._servico = new ServicoExtrato(); + this.Apelido = Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 6); + this.Seguradoras = seguradoras; + } + + public async Task CarregarExtratos(Seguradora seguradora, DateTime inicio, DateTime fim) + { + this.Extratos = new ObservableCollection(await this._servico.BuscarExtrato(seguradora.get_Id(), (long)0, 4, inicio, fim)); + } + + internal List Selecionar() + { + if (this.Extratos == null) + { + return null; + } + return ( + from x in this.Extratos + where x.get_Selecionado() + select x).Select((Extrato x) => { + NotaFiscal notaFiscal = new NotaFiscal(); + notaFiscal.set_IdExtrato(new long?(x.get_Id())); + notaFiscal.set_Seguradora(x.get_Seguradora()); + notaFiscal.set_Data(x.get_Data()); + notaFiscal.set_Iss(x.get_Iss().GetValueOrDefault()); + notaFiscal.set_Ir(x.get_Ir().GetValueOrDefault()); + notaFiscal.set_ValorBruto(x.get_Bruto().GetValueOrDefault()); + notaFiscal.set_ValorLiquido(x.get_Liquido().GetValueOrDefault()); + notaFiscal.set_Extrato(x.get_Numero()); + return notaFiscal; + }).ToList(); + } + + internal void SelecionarTudo() + { + if (this.Extratos == null) + { + return; + } + this.Extratos.ToList().ForEach((Extrato x) => x.set_Selecionado(!x.get_Selecionado())); + this.Extratos = new ObservableCollection(this.Extratos); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/ItemViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/ItemViewModel.cs new file mode 100644 index 0000000..b8c015a --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/ItemViewModel.cs @@ -0,0 +1,843 @@ +using CsQuery.ExtensionMethods.Internal; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Microsoft.CSharp.RuntimeBinder; +using Microsoft.Office.Interop.Excel; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Data; +using System.Diagnostics; +using System.Globalization; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Forms; + +namespace Gestor.Application.ViewModels.Generic +{ + public class ItemViewModel : BaseSegurosViewModel + { + private bool _alterandoFiltros; + + public Gestor.Application.ViewModels.CoberturaViewModel CoberturaViewModel; + + public ItemServico _itemServico; + + private Visibility _alteracaoTitularesVisibility = Visibility.Collapsed; + + private bool _enableAlterarExcluirTitulares; + + private List _excluirTlitulares = new List(); + + private TitularesVida _titularAlteracao = new TitularesVida(); + + private bool _codigo; + + private bool _inicio; + + private bool _fim; + + private bool _fatura; + + private bool _nome; + + private bool _observacao; + + private bool _nascimento; + + private bool _cpf; + + private bool _matricula; + + private bool _premio; + + private bool _capital; + + private bool _tipo; + + private ObservableCollection _titulares = new ObservableCollection(); + + private bool? _allSelected = new bool?(false); + + private bool _allSelectedChanging; + + private List _oldTitulares = new List(); + + public bool? AllSelected + { + get + { + return this._allSelected; + } + set + { + bool? nullable = value; + bool? nullable1 = this._allSelected; + if (nullable.GetValueOrDefault() == nullable1.GetValueOrDefault() & nullable.HasValue == nullable1.HasValue) + { + return; + } + nullable1 = value; + bool flag = false; + this.EnableAlterarExcluirTitulares = !(nullable1.GetValueOrDefault() == flag & nullable1.HasValue); + nullable1 = value; + if (!nullable1.GetValueOrDefault() & nullable1.HasValue) + { + this.AlteracaoTitularesVisibility = Visibility.Collapsed; + } + this._allSelected = value; + this.AllSelectedChanged(); + this.Titulares = new ObservableCollection(this.Titulares); + base.OnPropertyChanged("AllSelected"); + } + } + + public Visibility AlteracaoTitularesVisibility + { + get + { + return this._alteracaoTitularesVisibility; + } + set + { + this._alteracaoTitularesVisibility = value; + base.OnPropertyChanged("AlteracaoTitularesVisibility"); + } + } + + public bool Capital + { + get + { + return this._capital; + } + set + { + this._capital = value; + base.OnPropertyChanged("Capital"); + } + } + + public bool Codigo + { + get + { + return this._codigo; + } + set + { + this._codigo = value; + base.OnPropertyChanged("Codigo"); + } + } + + public bool Cpf + { + get + { + return this._cpf; + } + set + { + this._cpf = value; + base.OnPropertyChanged("Cpf"); + } + } + + public AutoCompleteFilterPredicate DependenteItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_980 = ItemViewModel.u003cu003ec.u003cu003e9__98_0; + if (u003cu003e9_980 == null) + { + u003cu003e9_980 = new AutoCompleteFilterPredicate(ItemViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (!((TitularesVida)obj).get_Nome().ToUpper().Contains(searchText.ToUpper())) + { + return false; + } + return ((TitularesVida)obj).get_Tipo().GetValueOrDefault() != 2; + }); + ItemViewModel.u003cu003ec.u003cu003e9__98_0 = u003cu003e9_980; + } + return u003cu003e9_980; + } + } + + public bool EnableAlterarExcluirTitulares + { + get + { + return this._enableAlterarExcluirTitulares; + } + set + { + this._enableAlterarExcluirTitulares = value; + base.OnPropertyChanged("EnableAlterarExcluirTitulares"); + } + } + + public List ExcluirTitulares + { + get + { + return this._excluirTlitulares; + } + set + { + this._excluirTlitulares = value; + base.OnPropertyChanged("ExcluirTitulares"); + } + } + + public bool Fatura + { + get + { + return this._fatura; + } + set + { + this._fatura = value; + base.OnPropertyChanged("Fatura"); + } + } + + public bool Fim + { + get + { + return this._fim; + } + set + { + this._fim = value; + base.OnPropertyChanged("Fim"); + } + } + + public bool Inicio + { + get + { + return this._inicio; + } + set + { + this._inicio = value; + base.OnPropertyChanged("Inicio"); + } + } + + public Item ItemSubstituido + { + get; + set; + } + + public bool Mantido + { + get; + set; + } + + public bool Matricula + { + get + { + return this._matricula; + } + set + { + this._matricula = value; + base.OnPropertyChanged("Matricula"); + } + } + + public bool Nascimento + { + get + { + return this._nascimento; + } + set + { + this._nascimento = value; + base.OnPropertyChanged("Nascimento"); + } + } + + public bool Nome + { + get + { + return this._nome; + } + set + { + this._nome = value; + base.OnPropertyChanged("Nome"); + } + } + + public bool Observacao + { + get + { + return this._observacao; + } + set + { + this._observacao = value; + base.OnPropertyChanged("Observacao"); + } + } + + public List OldTitulares + { + get + { + return this._oldTitulares; + } + set + { + this._oldTitulares = value; + base.OnPropertyChanged("OldTitulares"); + } + } + + public bool Premio + { + get + { + return this._premio; + } + set + { + this._premio = value; + base.OnPropertyChanged("Premio"); + } + } + + public bool Tipo + { + get + { + return this._tipo; + } + set + { + this._tipo = value; + base.OnPropertyChanged("Tipo"); + } + } + + public TitularesVida TitularAlteracao + { + get + { + return this._titularAlteracao; + } + set + { + this._titularAlteracao = value; + base.OnPropertyChanged("TitularAlteracao"); + } + } + + public ObservableCollection Titulares + { + get + { + return this._titulares; + } + set + { + this._titulares = value; + foreach (TitularesVida titulare in this.Titulares) + { + titulare.add_PropertyChanged(new PropertyChangedEventHandler(this.TitularesOnPropertyChanged)); + } + base.OnPropertyChanged("Titulares"); + } + } + + public ItemViewModel() + { + this.CoberturaViewModel = new Gestor.Application.ViewModels.CoberturaViewModel(null, null); + this._itemServico = new ItemServico(); + } + + private void AllSelectedChanged() + { + if (this._allSelectedChanging) + { + return; + } + try + { + this._alterandoFiltros = true; + this._allSelectedChanging = true; + if (this.AllSelected.HasValue) + { + foreach (TitularesVida titulare in this.Titulares) + { + titulare.set_Selecionado(this.AllSelected.Value); + } + this._alterandoFiltros = false; + } + } + finally + { + this._allSelectedChanging = false; + } + } + + public void AlterarTitular() + { + if (this.AlteracaoTitularesVisibility == Visibility.Visible) + { + this.AlteracaoTitularesVisibility = Visibility.Collapsed; + return; + } + this.TitularAlteracao = new TitularesVida(); + this.Codigo = false; + this.Inicio = false; + this.Fim = false; + this.Fatura = false; + this.Nome = false; + this.Nascimento = false; + this.Cpf = false; + this.Matricula = false; + this.Premio = false; + this.Capital = false; + this.Tipo = false; + this.AlteracaoTitularesVisibility = Visibility.Visible; + } + + public void AplicarTitular() + { + foreach (TitularesVida list in ( + from x in this.Titulares + where x.get_Selecionado() + select x).ToList()) + { + if (this.Codigo) + { + list.set_Codigo(this.TitularAlteracao.get_Codigo()); + } + if (this.Inicio) + { + list.set_Inicio(this.TitularAlteracao.get_Inicio()); + } + if (this.Fim) + { + list.set_Fim(this.TitularAlteracao.get_Fim()); + } + if (this.Fatura) + { + list.set_Fatura(this.TitularAlteracao.get_Fatura()); + } + if (this.Nome) + { + list.set_Nome(this.TitularAlteracao.get_Nome()); + } + if (this.Observacao) + { + list.set_Observacao(this.TitularAlteracao.get_Observacao()); + } + if (this.Nascimento) + { + list.set_Nascimento(this.TitularAlteracao.get_Nascimento()); + } + if (this.Cpf) + { + list.set_Cpf(this.TitularAlteracao.get_Cpf()); + } + if (this.Matricula) + { + list.set_Matricula(this.TitularAlteracao.get_Matricula()); + } + if (this.Premio) + { + list.set_Premio(this.TitularAlteracao.get_Premio()); + } + if (this.Capital) + { + list.set_Capital(this.TitularAlteracao.get_Capital()); + } + if (!this.Tipo) + { + continue; + } + list.set_Tipo(this.TitularAlteracao.get_Tipo()); + } + this.Titulares = new ObservableCollection(this.Titulares); + this.AlteracaoTitularesVisibility = Visibility.Collapsed; + } + + internal async Task> BuscarTitulares(string value) + { + Func func1 = null; + List titularesVidas = await Task.Run>(() => { + ObservableCollection titulares = this.Titulares; + Func u003cu003e9_1 = func1; + if (u003cu003e9_1 == null) + { + Func valueOrDefault = (TitularesVida x) => { + if (x.get_Tipo().GetValueOrDefault() == 2 || x.get_Nome() == null) + { + return false; + } + return ValidationHelper.RemoveDiacritics(x.get_Nome().Trim()).ToUpper().Contains(value.ToUpper()); + }; + Func func = valueOrDefault; + func1 = valueOrDefault; + u003cu003e9_1 = func; + } + return titulares.Where(u003cu003e9_1).ToList(); + }); + return titularesVidas; + } + + public async Task CarregarTitulares(long id) + { + this.Titulares = new ObservableCollection(await this._itemServico.BuscaTitularesVida(id)); + ItemViewModel list = this; + List titularesVidas = this.Titulares.ToList(); + list.OldTitulares = titularesVidas.Select((TitularesVida x) => { + TitularesVida titularesVida = new TitularesVida(); + titularesVida.set_Id(x.get_Id()); + titularesVida.set_IdItem(x.get_IdItem()); + titularesVida.set_Codigo(x.get_Codigo()); + titularesVida.set_Inicio(x.get_Inicio()); + titularesVida.set_Fim(x.get_Fim()); + titularesVida.set_Fatura(x.get_Fatura()); + titularesVida.set_Nome(x.get_Nome()); + titularesVida.set_Observacao(x.get_Observacao()); + titularesVida.set_Nascimento(x.get_Nascimento()); + titularesVida.set_Cpf(x.get_Cpf()); + titularesVida.set_Matricula(x.get_Matricula()); + titularesVida.set_Premio(x.get_Premio()); + titularesVida.set_Capital(x.get_Capital()); + titularesVida.set_Tipo(x.get_Tipo()); + titularesVida.set_Dependente(x.get_Dependente()); + return titularesVida; + }).ToList(); + } + + public void ExcluirTitular() + { + List list = ( + from x in this.Titulares + where x.get_Selecionado() + select x).ToList(); + this.ExcluirTitulares.AddRange( + from x in list + where x.get_Id() > (long)0 + select x); + foreach (TitularesVida titularesVida in list) + { + this.Titulares.Remove(titularesVida); + } + this.AllSelected = new bool?(false); + } + + public async Task ImportarTitulares() + { + string fileName; + using (OpenFileDialog openFileDialog = new OpenFileDialog()) + { + openFileDialog.Filter = "Excel|*.xls;*.xlsx"; + openFileDialog.InitialDirectory = Environment.SpecialFolder.Desktop.ToString(); + if (DialogResult.OK == openFileDialog.ShowDialog()) + { + fileName = openFileDialog.FileName; + } + else + { + return; + } + } + base.Loading(true); + int num1 = 0; + try + { + List titularesVidas2 = await Task.Run>(() => { + string shortDateString; + DateTime dateTime; + Microsoft.Office.Interop.Excel.Application variable = (Microsoft.Office.Interop.Excel.Application)Activator.CreateInstance(Marshal.GetTypeFromCLSID(new Guid("00024500-0000-0000-C000-000000000046"))); + Workbook variable1 = variable.Workbooks.Open(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); + List strs = new List() + { + "codigo", + "inicio", + "fim", + "fatura", + "nome", + "nascimento", + "cpf", + "matricula", + "premio", + "capital", + "tipo", + "observacao", + "titulardependente" + }; + List dataTables = new List(); + foreach (object worksheet in variable1.Worksheets) + { + DataTable dataTable = new DataTable(); + Microsoft.Office.Interop.Excel.Range usedRange = ((Worksheet)worksheet).UsedRange; + if (ItemViewModel.u003cu003eo__93.u003cu003ep__0 == null) + { + ItemViewModel.u003cu003eo__93.u003cu003ep__0 = CallSite>.Create(Binder.Convert(CSharpBinderFlags.None, typeof(object[,]), typeof(ItemViewModel))); + } + object[,] target = ItemViewModel.u003cu003eo__93.u003cu003ep__0.Target(ItemViewModel.u003cu003eo__93.u003cu003ep__0, usedRange.Value2); + int num = 0; + if (target == null) + { + continue; + } + for (int i = 0; i <= usedRange.Columns.Count - 1; i++) + { + if (target[1, i + 1] == null || !strs.Contains(Funcoes.RemoverAcentos(target[1, i + 1].ToString().ToLower().Trim()))) + { + num--; + } + else + { + DataColumn dataColumn = new DataColumn() + { + DataType = Type.GetType("System.String"), + ColumnName = Funcoes.RemoverAcentos(target[1, i + 1].ToString().ToLower().Trim()) + }; + dataTable.Columns.Add(dataColumn); + for (int j = 0; j <= usedRange.Rows.Count - 2; j++) + { + object obj = target[j + 2, i + 1]; + target[1, i + 1].ToString().ToLower(); + if (Funcoes.RemoverAcentos(target[1, i + 1].ToString().Trim().ToLower()) != "inicio" && Funcoes.RemoverAcentos(target[1, i + 1].ToString().Trim().ToLower()) != "fim" && Funcoes.RemoverAcentos(target[1, i + 1].ToString().Trim().ToLower()) != "nascimento") + { + string str = obj as string; + shortDateString = (str != null ? Funcoes.RemoverAcentos(str).ToUpper().Trim() : (!(obj is double) ? (!(obj is bool) ? "" : ((bool)obj ? "1" : "0")) : ((double)obj).ToString(CultureInfo.InvariantCulture))); + } + else if (obj is double) + { + dateTime = DateTime.FromOADate((double)obj); + shortDateString = dateTime.ToShortDateString(); + } + else if (!DateTime.TryParse((string)obj, out dateTime)) + { + shortDateString = ""; + } + else + { + dateTime = DateTime.Parse((string)obj); + shortDateString = dateTime.ToShortDateString(); + } + if (i + num != 0) + { + dataTable.Rows[j][i + num] = shortDateString; + } + else + { + dataTable.Rows.Add(dataTable.NewRow()); + dataTable.Rows[j][i + num] = shortDateString; + } + } + } + } + dataTables.Add(dataTable); + } + variable.Quit(); + List titularesVidas = new List(); + foreach (DataTable dataTable1 in dataTables) + { + List titularesVidas1 = titularesVidas; + EnumerableRowCollection dataRows = dataTable1.AsEnumerable(); + Func u003cu003e9_931 = ItemViewModel.u003cu003ec.u003cu003e9__93_1; + if (u003cu003e9_931 == null) + { + u003cu003e9_931 = (DataRow x) => { + if (x.Field("nome") == null) + { + return false; + } + return !string.IsNullOrEmpty(x.Field("nome").ToString()); + }; + ItemViewModel.u003cu003ec.u003cu003e9__93_1 = u003cu003e9_931; + } + titularesVidas1.AddRange(dataRows.Where(u003cu003e9_931).ToList().Select((DataRow x) => { + DateTime? nullable; + decimal? nullable1; + TipoTitular? nullable2; + DateTime? nullable3; + DateTime? nullable4; + DateTime? nullable5; + decimal? nullable6; + decimal? nullable7; + TipoTitular? nullable8; + TitularesVida titularesVida = new TitularesVida(); + titularesVida.set_Codigo((!dataTable1.Columns.Contains("codigo") || string.IsNullOrWhiteSpace(x.Field("codigo").ToString()) ? null : x.Field("codigo").ToString().ToUpper())); + if (!dataTable1.Columns.Contains("inicio") || string.IsNullOrWhiteSpace(x.Field("inicio").ToString())) + { + nullable = null; + nullable3 = nullable; + } + else + { + nullable3 = new DateTime?(DateTime.Parse(x.Field("inicio").ToString())); + } + titularesVida.set_Inicio(nullable3); + if (!dataTable1.Columns.Contains("fim") | string.IsNullOrWhiteSpace(x.Field("fim").ToString())) + { + nullable = null; + nullable4 = nullable; + } + else + { + nullable4 = new DateTime?(DateTime.Parse(x.Field("fim").ToString())); + } + titularesVida.set_Fim(nullable4); + titularesVida.set_Fatura((!dataTable1.Columns.Contains("fatura") || string.IsNullOrWhiteSpace(x.Field("fatura").ToString()) ? null : x.Field("fatura").ToString().ToUpper())); + titularesVida.set_Nome((!dataTable1.Columns.Contains("nome") || string.IsNullOrWhiteSpace(x.Field("nome").ToString()) ? null : x.Field("nome").ToString().ToUpper())); + titularesVida.set_Observacao((!dataTable1.Columns.Contains("observacao") || string.IsNullOrWhiteSpace(x.Field("observacao").ToString()) ? null : x.Field("observacao").ToString().ToUpper())); + if (!dataTable1.Columns.Contains("nascimento") || string.IsNullOrWhiteSpace(x.Field("nascimento").ToString())) + { + nullable = null; + nullable5 = nullable; + } + else + { + nullable5 = new DateTime?(DateTime.Parse(x.Field("nascimento").ToString())); + } + titularesVida.set_Nascimento(nullable5); + titularesVida.set_Cpf((!dataTable1.Columns.Contains("cpf") || string.IsNullOrWhiteSpace(x.Field("cpf").ToString()) ? null : x.Field("cpf").ToString())); + titularesVida.set_Matricula((!dataTable1.Columns.Contains("matricula") || string.IsNullOrWhiteSpace(x.Field("matricula").ToString()) ? null : x.Field("matricula").ToString().ToUpper())); + if (!dataTable1.Columns.Contains("premio") || string.IsNullOrWhiteSpace(x.Field("premio").ToString())) + { + nullable1 = null; + nullable6 = nullable1; + } + else + { + nullable6 = new decimal?(decimal.Parse(x.Field("premio").ToString(), NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands, CultureInfo.InvariantCulture)); + } + titularesVida.set_Premio(nullable6); + if (!dataTable1.Columns.Contains("capital") || string.IsNullOrWhiteSpace(x.Field("capital").ToString())) + { + nullable1 = null; + nullable7 = nullable1; + } + else + { + nullable7 = new decimal?(decimal.Parse(x.Field("capital").ToString(), NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands, CultureInfo.InvariantCulture)); + } + titularesVida.set_Capital(nullable7); + if (!dataTable1.Columns.Contains("tipo") || string.IsNullOrWhiteSpace(x.Field("tipo").ToString())) + { + nullable2 = null; + nullable8 = nullable2; + } + else if (x.Field("tipo").ToString() == "SOCIO") + { + nullable8 = new TipoTitular?(0); + } + else if (x.Field("tipo").ToString() == "FUNCIONARIO") + { + nullable8 = new TipoTitular?(1); + } + else + { + nullable2 = null; + nullable8 = nullable2; + } + titularesVida.set_Tipo(nullable8); + return titularesVida; + }).ToList()); + } + return titularesVidas; + }); + base.Loading(false); + if (titularesVidas2.Count != 0) + { + ExtensionMethods.AddRange(this.Titulares, titularesVidas2); + } + else + { + await base.ShowMessage("NENHUMA COLUNA FOI ENCONTRADA", "OK", "", false); + return; + } + } + catch + { + num1 = 1; + } + if (num1 == 1) + { + base.Loading(false); + await base.ShowMessage("FALHA AO IMPORTAR O EXCEL, VERIFIQUE SE O ARQUIVO POSSUI ALGUM ERRO.", "OK", "", false); + } + } + + public void IncluirTitular() + { + this.Titulares.Insert(0, new TitularesVida()); + this.Titulares = new ObservableCollection(this.Titulares); + } + + public async Task QuantidadeDeItens(long id) + { + return await (new ItemServico()).BuscarProximoItem(id); + } + + public void RecheckAllSelected() + { + if (this._allSelectedChanging) + { + return; + } + try + { + this._allSelectedChanging = true; + if (this.Titulares.All((TitularesVida e) => e.get_Selecionado())) + { + this.AllSelected = new bool?(true); + } + else if (!this.Titulares.All((TitularesVida e) => !e.get_Selecionado())) + { + this.AllSelected = null; + } + else + { + this.AllSelected = new bool?(false); + } + } + finally + { + this._allSelectedChanging = false; + } + } + + private void TitularesOnPropertyChanged(object sender, PropertyChangedEventArgs args) + { + if (this._alterandoFiltros) + { + return; + } + this.RecheckAllSelected(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/ProtocoloViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/ProtocoloViewModel.cs new file mode 100644 index 0000000..d1d8836 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/ProtocoloViewModel.cs @@ -0,0 +1,30 @@ +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; + +namespace Gestor.Application.ViewModels.Generic +{ + public class ProtocoloViewModel : BaseSegurosViewModel + { + private ObservableCollection _itens = new ObservableCollection(); + + public ObservableCollection Itens + { + get + { + return this._itens; + } + set + { + this._itens = value; + base.OnPropertyChanged("Itens"); + } + } + + public ProtocoloViewModel(List itens) + { + this.Itens = new ObservableCollection(itens); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/ReordenarItensViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/ReordenarItensViewModel.cs new file mode 100644 index 0000000..f44c811 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/ReordenarItensViewModel.cs @@ -0,0 +1,68 @@ +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Generic +{ + public class ReordenarItensViewModel : BaseSegurosViewModel + { + private readonly ItemServico _itemServico; + + private bool _carregando; + + private ObservableCollection _itens = new ObservableCollection(); + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.OnPropertyChanged("Carregando"); + } + } + + public ObservableCollection Itens + { + get + { + return this._itens; + } + set + { + this._itens = value; + base.OnPropertyChanged("Itens"); + } + } + + public ReordenarItensViewModel(List ids) + { + this._itemServico = new ItemServico(); + this.CarregarItens(ids); + } + + private async void CarregarItens(List ids) + { + this.Carregando = true; + this.Itens = await this._itemServico.BuscarItens(ids); + this.Carregando = false; + } + + public void ReordenarAutomaticamente() + { + foreach (Item iten in this.Itens) + { + iten.set_Ordem(new int?(this.Itens.IndexOf(iten) + 1)); + } + this.Itens = new ObservableCollection(this.Itens); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/SelecionarItensViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/SelecionarItensViewModel.cs new file mode 100644 index 0000000..852bedd --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/SelecionarItensViewModel.cs @@ -0,0 +1,89 @@ +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Generic +{ + public class SelecionarItensViewModel : BaseSegurosViewModel + { + private ItemServico _itemServico; + + private ObservableCollection _itens = new ObservableCollection(); + + private bool? _allSelected; + + private bool _allSelectedChanging; + + public bool? AllSelected + { + get + { + return this._allSelected; + } + set + { + bool? nullable = value; + bool? nullable1 = this._allSelected; + if (nullable.GetValueOrDefault() == nullable1.GetValueOrDefault() & nullable.HasValue == nullable1.HasValue) + { + return; + } + this._allSelected = value; + this.AllSelectedChanged(); + base.OnPropertyChanged("AllSelected"); + } + } + + public ObservableCollection Itens + { + get + { + return this._itens; + } + set + { + this._itens = value; + base.OnPropertyChanged("Itens"); + } + } + + public SelecionarItensViewModel(long id) + { + this._itemServico = new ItemServico(); + this.CarregarItens(id); + } + + private void AllSelectedChanged() + { + if (this._allSelectedChanging) + { + return; + } + try + { + this._allSelectedChanging = true; + if (this.AllSelected.HasValue) + { + foreach (Item iten in this.Itens) + { + iten.set_Selecionado(this.AllSelected.Value); + } + } + } + finally + { + this._allSelectedChanging = false; + } + } + + private async void CarregarItens(long id) + { + this.Itens = await this._itemServico.BuscarItens(id, 0); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/ImportViewModel.cs b/Codemerx/Gestor.Application/ViewModels/ImportViewModel.cs new file mode 100644 index 0000000..48249e7 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/ImportViewModel.cs @@ -0,0 +1,105 @@ +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.Generic; +using Microsoft.Win32; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels +{ + public class ImportViewModel : BaseViewModel + { + private ObservableCollection _arquivos = new ObservableCollection(); + + public ObservableCollection Arquivos + { + get + { + return this._arquivos; + } + set + { + this._arquivos = value; + base.OnPropertyChanged("Arquivos"); + } + } + + public ImportViewModel() + { + } + + public void CarregarArquivos() + { + OpenFileDialog openFileDialog = new OpenFileDialog() + { + Title = "Selecione o PDF", + Filter = "Arquivos PDF|*.pdf", + Multiselect = true + }; + if (!openFileDialog.ShowDialog().GetValueOrDefault()) + { + return; + } + this.Arquivos = new ObservableCollection(); + openFileDialog.FileNames.ToList().ForEach((string x) => this.Arquivos.Add(new Arquivo() + { + Nome = x, + Processo = 0 + })); + } + + public async Task Import(Arquivo arquivo) + { + await Task.Run(() => { + try + { + Process process = new Process() + { + StartInfo = new ProcessStartInfo() + { + FileName = "C:\\AggerSeguros\\Agger.Import201911261630\\Agger.ImportPDF.exe", + Arguments = string.Format(" {0} {1} NOVOGESTOR {2}", Recursos.Empresa.get_Id(), Recursos.Usuario.get_Id(), arquivo.Nome), + UseShellExecute = false, + RedirectStandardOutput = true, + CreateNoWindow = true + } + }; + process.Start(); + process.WaitForExit(); + string end = process.StandardError.ReadToEnd(); + string str = process.StandardOutput.ReadToEnd(); + if (process.ExitCode != 0) + { + string[] strArrays = new string[] { "netsh exit code: ", null, null, null, null, null }; + strArrays[1] = process.ExitCode.ToString(); + strArrays[2] = " "; + strArrays[3] = (!string.IsNullOrEmpty(end) ? string.Concat(" ", end) : ""); + strArrays[4] = " "; + strArrays[5] = (!string.IsNullOrEmpty(str) ? string.Concat(" ", str) : ""); + throw new Exception(string.Concat(strArrays)); + } + } + catch (Exception exception) + { + } + }); + } + + public void Importar() + { + (new TaskFactory()).StartNew>(() => this.Importar(this.Arquivos.ToList())); + } + + public async Task Importar(List arquivos) + { + arquivos.ForEach(async (Arquivo x) => await this.Import(x)); + return true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/LoginImageModel.cs b/Codemerx/Gestor.Application/ViewModels/LoginImageModel.cs new file mode 100644 index 0000000..36f880e --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/LoginImageModel.cs @@ -0,0 +1,24 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Application.ViewModels +{ + public class LoginImageModel + { + public string Imagem + { + get; + set; + } + + public string UrlFixa + { + get; + set; + } + + public LoginImageModel() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/LoginViewModel.cs b/Codemerx/Gestor.Application/ViewModels/LoginViewModel.cs new file mode 100644 index 0000000..8981f60 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/LoginViewModel.cs @@ -0,0 +1,1495 @@ +using Agger.Registro; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Command; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Security; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using System; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Input; + +namespace Gestor.Application.ViewModels +{ + internal class LoginViewModel : BaseSegurosViewModel + { + private bool _enableRegistro; + + private bool _enableTrocaSenha; + + private bool _aggerUser; + + private string _imagemLink = "https://calendly.com/treinamentocs"; + + private string _imagem = "https://docs.agger.com.br/treinamentoprimeirasemana.png"; + + private string _head; + + private string _login; + + private string _novaNovaSenha; + + private string _senha; + + private string _confirmacaoSenha; + + private Gestor.Model.Domain.Seguros.Usuario _usuario; + + private string userJson = string.Concat(AppDomain.CurrentDomain.BaseDirectory, "user.json"); + + private LoginImageModel _selectedImage; + + private int _selectedIndex; + + private string _version; + + private string _labelVersion = ""; + + private bool _loadingVisibility; + + private bool _fieldsVisibility; + + private string _errorLogin = "DADOS DE ACESSO INVÁLIDOS"; + + private Visibility _errorLoginVisibility = Visibility.Hidden; + + private Visibility _acessoVisibility = Visibility.Collapsed; + + private Visibility _trocaSenhaVisibility = Visibility.Collapsed; + + private Visibility _loginVisibility; + + private Visibility _registrarVisibility = Visibility.Collapsed; + + private Visibility _visibilityCancelarRegitro = Visibility.Collapsed; + + private string _chave; + + private string _mensagem; + + private string _centralAtendimento = Address.get_CentralAtendimento().ToString(); + + public Visibility AcessoVisibility + { + get + { + return this._acessoVisibility; + } + set + { + this._acessoVisibility = value; + base.OnPropertyChanged("AcessoVisibility"); + } + } + + public bool AggerUser + { + get + { + return this._aggerUser; + } + set + { + this._aggerUser = value; + base.OnPropertyChanged("AggerUser"); + } + } + + public string CentralAtendimento + { + get + { + return this._centralAtendimento; + } + set + { + this._centralAtendimento = value; + base.OnPropertyChanged("CentralAtendimento"); + } + } + + public string Chave + { + get + { + return this._chave; + } + set + { + this._chave = value; + this.EnableRegistro = Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(this.Chave); + base.OnPropertyChanged("Chave"); + } + } + + public string ConfirmacaoSenha + { + get + { + return this._confirmacaoSenha; + } + set + { + this._confirmacaoSenha = value; + this.EnableTrocaSenha = (!Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(this.NovaSenha) || !Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(this.ConfirmacaoSenha) ? false : this.NovaSenha.Equals(this.ConfirmacaoSenha)); + base.OnPropertyChanged("ConfirmacaoSenha"); + } + } + + public bool EnableRegistro + { + get + { + return this._enableRegistro; + } + set + { + this._enableRegistro = value; + base.OnPropertyChanged("EnableRegistro"); + } + } + + public bool EnableTrocaSenha + { + get + { + return this._enableTrocaSenha; + } + set + { + this._enableTrocaSenha = value; + base.OnPropertyChanged("EnableTrocaSenha"); + } + } + + public string ErrorLogin + { + get + { + return this._errorLogin; + } + set + { + this._errorLogin = value; + base.OnPropertyChanged("ErrorLogin"); + } + } + + public Visibility ErrorLoginVisibility + { + get + { + return this._errorLoginVisibility; + } + set + { + this._errorLoginVisibility = value; + base.OnPropertyChanged("ErrorLoginVisibility"); + } + } + + public bool FieldsVisibility + { + get + { + return this._fieldsVisibility; + } + set + { + this._fieldsVisibility = value; + base.OnPropertyChanged("FieldsVisibility"); + } + } + + public string Head + { + get + { + return this._head; + } + set + { + string upper; + if (value != null) + { + upper = value.ToUpper(); + } + else + { + upper = null; + } + this._head = upper; + base.OnPropertyChanged("Head"); + } + } + + public ICommand ImageClickCommand + { + get + { + return new RelayCommand(() => { + bool flag; + LoginImageModel selectedImage = this.SelectedImage; + flag = (selectedImage != null ? Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(selectedImage.UrlFixa) : false); + if (flag) + { + Process.Start(new ProcessStartInfo() + { + FileName = this.SelectedImage.UrlFixa, + UseShellExecute = true + }); + } + }); + } + } + + public string Imagem + { + get + { + return this._imagem; + } + set + { + this._imagem = value; + base.OnPropertyChanged("Imagem"); + } + } + + public string ImagemLink + { + get + { + return this._imagemLink; + } + set + { + this._imagemLink = value; + base.OnPropertyChanged("ImagemLink"); + } + } + + public string LabelVersion + { + get + { + return this._labelVersion; + } + set + { + this._labelVersion = value; + base.OnPropertyChanged("LabelVersion"); + } + } + + public bool LoadingVisibility + { + get + { + return this._loadingVisibility; + } + set + { + this._loadingVisibility = value; + base.OnPropertyChanged("LoadingVisibility"); + } + } + + public string Login + { + get + { + return this._login; + } + set + { + bool flag; + bool flag1; + this._login = value; + string login = this.Login; + if (login != null) + { + flag = login.ToUpper().StartsWith("AGGER@"); + } + else + { + flag = false; + } + if (flag) + { + flag1 = true; + } + else + { + string senha = this.Senha; + if (senha != null) + { + flag1 = senha.ToUpper().StartsWith("AGGER@"); + } + else + { + flag1 = false; + } + } + this.AggerUser = flag1; + base.OnPropertyChanged("Login"); + } + } + + public ObservableCollection LoginImages { get; set; } = new ObservableCollection(); + + public Visibility LoginVisibility + { + get + { + return this._loginVisibility; + } + set + { + this._loginVisibility = value; + base.OnPropertyChanged("LoginVisibility"); + } + } + + public string Mensagem + { + get + { + return this._mensagem; + } + set + { + this._mensagem = value; + base.OnPropertyChanged("Mensagem"); + } + } + + public string NovaSenha + { + get + { + return this._novaNovaSenha; + } + set + { + this._novaNovaSenha = value; + this.EnableTrocaSenha = (!Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(this.NovaSenha) || !Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(this.ConfirmacaoSenha) ? false : this.NovaSenha.Equals(this.ConfirmacaoSenha)); + base.OnPropertyChanged("NovaSenha"); + } + } + + public Visibility RegistrarVisibility + { + get + { + return this._registrarVisibility; + } + set + { + this._registrarVisibility = value; + base.OnPropertyChanged("RegistrarVisibility"); + } + } + + public LoginImageModel SelectedImage + { + get + { + return this._selectedImage; + } + set + { + this._selectedImage = value; + base.OnPropertyChanged("SelectedImage"); + } + } + + public int SelectedIndex + { + get + { + return this._selectedIndex; + } + set + { + this._selectedIndex = value; + this.SelectedImage = this.LoginImages.ElementAtOrDefault(value); + base.OnPropertyChanged("SelectedIndex"); + } + } + + public string Senha + { + get + { + return this._senha; + } + set + { + bool flag; + bool flag1; + this._senha = value; + string login = this.Login; + if (login != null) + { + flag = login.ToUpper().StartsWith("AGGER@"); + } + else + { + flag = false; + } + if (flag) + { + flag1 = true; + } + else + { + string senha = this.Senha; + if (senha != null) + { + flag1 = senha.ToUpper().StartsWith("AGGER@"); + } + else + { + flag1 = false; + } + } + this.AggerUser = flag1; + base.OnPropertyChanged("Senha"); + } + } + + public Visibility TrocaSenhaVisibility + { + get + { + return this._trocaSenhaVisibility; + } + set + { + this._trocaSenhaVisibility = value; + base.OnPropertyChanged("TrocaSenhaVisibility"); + } + } + + public Gestor.Model.Domain.Seguros.Usuario Usuario + { + get + { + return this._usuario; + } + set + { + this._usuario = value; + base.OnPropertyChanged("Usuario"); + } + } + + public static string VersaoAtual + { + get; + set; + } + + public string Version + { + get + { + return this._version; + } + set + { + this._version = value; + base.OnPropertyChanged("Version"); + } + } + + public Visibility VisibilityCancelarRegitro + { + get + { + return this._visibilityCancelarRegitro; + } + set + { + this._visibilityCancelarRegitro = value; + base.OnPropertyChanged("VisibilityCancelarRegitro"); + } + } + + public LoginViewModel() + { + string login; + base.EnableButtons = true; + ApplicationHelper.Versao = Assembly.GetExecutingAssembly().GetName().Version; + this.Version = ApplicationHelper.Versao.ToString(); + this.LabelVersion = string.Concat("Gestor ", this.Version); + LoginViewModel.VersaoAtual = this.LabelVersion; + if (!File.Exists(this.userJson)) + { + return; + } + Gestor.Model.Domain.Seguros.Usuario usuario = JsonConvert.DeserializeObject(File.ReadAllText(this.userJson)); + if (usuario != null) + { + login = usuario.get_Login(); + } + else + { + login = null; + } + this.Login = login; + } + + public void AbrirRegistro() + { + this.LoginVisibility = Visibility.Collapsed; + this.AcessoVisibility = Visibility.Collapsed; + this.RegistrarVisibility = Visibility.Visible; + this.VisibilityCancelarRegitro = (ApplicationHelper.IdFornecedor == 0 ? Visibility.Collapsed : Visibility.Visible); + this.Chave = string.Empty; + } + + public async Task AbrirTrocaSenha() + { + bool flag; + UsuarioServico usuarioServico = new UsuarioServico(); + flag = (Gestor.Common.Validation.ValidationHelper.IsNullOrEmpty(this.Senha) ? true : Gestor.Common.Validation.ValidationHelper.IsNullOrEmpty(this.Login)); + bool flag1 = flag; + if (!flag1) + { + bool flag2 = Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(this.Login); + if (flag2) + { + Gestor.Model.Domain.Seguros.Usuario usuario = await usuarioServico.BuscarLogin(this.Login); + Gestor.Model.Domain.Seguros.Usuario usuario1 = usuario; + this.Usuario = usuario; + flag2 = usuario1 == null; + } + flag1 = flag2; + } + if (!flag1) + { + this.TrocaSenhaVisibility = Visibility.Visible; + this.LoginVisibility = Visibility.Collapsed; + } + else + { + await base.ShowMessage("NECESSÁRIO INSERIR UM USUÁRIO E SENHA VÁLIDOS PARA REALIZAR A TROCA DE SENHA.", "OK", "", false); + } + } + + public void AcessoNegado(string message) + { + this.Mensagem = message; + this.RegistrarVisibility = Visibility.Collapsed; + this.LoginVisibility = Visibility.Collapsed; + this.AcessoVisibility = Visibility.Visible; + } + + public void FecharRegistro() + { + this.RegistrarVisibility = Visibility.Collapsed; + this.LoginVisibility = Visibility.Visible; + this.Chave = string.Empty; + } + + public async Task GetCfgJson() + { + bool flag; + string str; + string str1; + string str2; + string str3; + string str4; + string str5; + string str6; + string str7; + string str8; + string str9; + string str10; + string str11; + string str12; + string str13; + string str14; + string str15; + string str16; + object uri; + object apiGestorBeta; + object assinadorApiOficial; + object assinadorApiBeta; + object card; + object assistance; + object apiAD; + object apiArquivo; + object apiFipe; + object apiSso; + object apiMonitor; + object apiCep; + object loginJson; + object surveyJson; + object promo; + object betaPromo; + object centralAtendimento; + HttpResponseMessage async = null; + try + { + using (HttpClient httpClient = new HttpClient()) + { + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + httpClient.set_Timeout(TimeSpan.FromSeconds(30)); + int num = 0; + try + { + async = await httpClient.GetAsync(Address.get_JsonGestor()); + async.EnsureSuccessStatusCode(); + } + catch + { + num = 1; + } + if (num == 1) + { + async = await httpClient.GetAsync(Address.get_JsonGestorAzure()); + } + if (!async.get_IsSuccessStatusCode()) + { + async = null; + } + else + { + JObject jObject = JObject.Parse(await async.get_Content().ReadAsStringAsync()); + JToken item = jObject.get_Item("ApiGestor"); + if (item != null) + { + str = Extensions.Value(item); + } + else + { + str = null; + } + string str17 = str; + JToken jToken = jObject.get_Item("ApiGestorBeta"); + if (jToken != null) + { + str1 = Extensions.Value(jToken); + } + else + { + str1 = null; + } + string str18 = str1; + JToken item1 = jObject.get_Item("ApiAssinador"); + if (item1 != null) + { + str2 = Extensions.Value(item1); + } + else + { + str2 = null; + } + string str19 = str2; + JToken jToken1 = jObject.get_Item("ApiAssinadorBeta"); + if (jToken1 != null) + { + str3 = Extensions.Value(jToken1); + } + else + { + str3 = null; + } + string str20 = str3; + JToken item2 = jObject.get_Item("ApiCard"); + if (item2 != null) + { + str4 = Extensions.Value(item2); + } + else + { + str4 = null; + } + string str21 = str4; + JToken jToken2 = jObject.get_Item("ApiAssistencia"); + if (jToken2 != null) + { + str5 = Extensions.Value(jToken2); + } + else + { + str5 = null; + } + string str22 = str5; + JToken item3 = jObject.get_Item("ApiAD"); + if (item3 != null) + { + str6 = Extensions.Value(item3); + } + else + { + str6 = null; + } + string str23 = str6; + JToken jToken3 = jObject.get_Item("ApiAttachment"); + if (jToken3 != null) + { + str7 = Extensions.Value(jToken3); + } + else + { + str7 = null; + } + string str24 = str7; + JToken item4 = jObject.get_Item("ApiFipe"); + if (item4 != null) + { + str8 = Extensions.Value(item4); + } + else + { + str8 = null; + } + string str25 = str8; + JToken jToken4 = jObject.get_Item("ApiSso"); + if (jToken4 != null) + { + str9 = Extensions.Value(jToken4); + } + else + { + str9 = null; + } + string str26 = str9; + JToken item5 = jObject.get_Item("ApiCep"); + if (item5 != null) + { + str10 = Extensions.Value(item5); + } + else + { + str10 = null; + } + string str27 = str10; + JToken jToken5 = jObject.get_Item("ApiMonitor"); + if (jToken5 != null) + { + str11 = Extensions.Value(jToken5); + } + else + { + str11 = null; + } + string str28 = str11; + JToken item6 = jObject.get_Item("LoginJson"); + if (item6 != null) + { + str12 = Extensions.Value(item6); + } + else + { + str12 = null; + } + string str29 = str12; + JToken jToken6 = jObject.get_Item("PromoJson"); + if (jToken6 != null) + { + str13 = Extensions.Value(jToken6); + } + else + { + str13 = null; + } + string str30 = str13; + JToken item7 = jObject.get_Item("BetaPromoJson"); + if (item7 != null) + { + str14 = Extensions.Value(item7); + } + else + { + str14 = null; + } + string str31 = str14; + JToken jToken7 = jObject.get_Item("SurveyJson"); + if (jToken7 != null) + { + str15 = Extensions.Value(jToken7); + } + else + { + str15 = null; + } + string str32 = str15; + JToken item8 = jObject.get_Item("CentralAtendimento"); + if (item8 != null) + { + str16 = Extensions.Value(item8); + } + else + { + str16 = null; + } + string str33 = str16; + JToken jToken8 = jObject.get_Item("UsarApis"); + if (jToken8 != null) + { + Extensions.Value(jToken8); + } + else + { + } + if (str17 != null) + { + uri = str17.ToUri(); + } + else + { + uri = null; + } + if (uri == null) + { + uri = Address.get_ApiGestorOficial(); + } + Address.set_ApiGestorOficial((Uri)uri); + if (str18 != null) + { + apiGestorBeta = str18.ToUri(); + } + else + { + apiGestorBeta = null; + } + if (apiGestorBeta == null) + { + apiGestorBeta = Address.get_ApiGestorBeta(); + } + Address.set_ApiGestorBeta((Uri)apiGestorBeta); + if (str19 != null) + { + assinadorApiOficial = str19.ToUri(); + } + else + { + assinadorApiOficial = null; + } + if (assinadorApiOficial == null) + { + assinadorApiOficial = Address.get_AssinadorApiOficial(); + } + Address.set_AssinadorApiOficial((Uri)assinadorApiOficial); + if (str20 != null) + { + assinadorApiBeta = str20.ToUri(); + } + else + { + assinadorApiBeta = null; + } + if (assinadorApiBeta == null) + { + assinadorApiBeta = Address.get_AssinadorApiBeta(); + } + Address.set_AssinadorApiBeta((Uri)assinadorApiBeta); + if (str21 != null) + { + card = str21.ToUri(); + } + else + { + card = null; + } + if (card == null) + { + card = Address.get_Card(); + } + Address.set_Card((Uri)card); + if (str22 != null) + { + assistance = str22.ToUri(); + } + else + { + assistance = null; + } + if (assistance == null) + { + assistance = Address.get_Assistance(); + } + Address.set_Assistance((Uri)assistance); + if (str23 != null) + { + apiAD = str23.ToUri(); + } + else + { + apiAD = null; + } + if (apiAD == null) + { + apiAD = Address.get_ApiAD(); + } + Address.set_ApiAD((Uri)apiAD); + if (str24 != null) + { + apiArquivo = str24.ToUri(); + } + else + { + apiArquivo = null; + } + if (apiArquivo == null) + { + apiArquivo = Address.get_ApiArquivo(); + } + Address.set_ApiArquivo((Uri)apiArquivo); + if (str25 != null) + { + apiFipe = str25.ToUri(); + } + else + { + apiFipe = null; + } + if (apiFipe == null) + { + apiFipe = Address.get_ApiFipe(); + } + Address.set_ApiFipe((Uri)apiFipe); + if (str26 != null) + { + apiSso = str26.ToUri(); + } + else + { + apiSso = null; + } + if (apiSso == null) + { + apiSso = Address.get_ApiSso(); + } + Address.set_ApiSso((Uri)apiSso); + if (str28 != null) + { + apiMonitor = str28.ToUri(); + } + else + { + apiMonitor = null; + } + if (apiMonitor == null) + { + apiMonitor = Address.get_ApiMonitor(); + } + Address.set_ApiMonitor((Uri)apiMonitor); + if (str27 != null) + { + apiCep = str27.ToUri(); + } + else + { + apiCep = null; + } + if (apiCep == null) + { + apiCep = Address.get_ApiCep(); + } + Address.set_ApiCep((Uri)apiCep); + if (str29 != null) + { + loginJson = str29.ToUri(); + } + else + { + loginJson = null; + } + if (loginJson == null) + { + loginJson = Address.get_LoginJson(); + } + Address.set_LoginJson((Uri)loginJson); + if (str32 != null) + { + surveyJson = str32.ToUri(); + } + else + { + surveyJson = null; + } + if (surveyJson == null) + { + surveyJson = Address.get_SurveyJson(); + } + Address.set_SurveyJson((Uri)surveyJson); + if (str30 != null) + { + promo = str30.ToUri(); + } + else + { + promo = null; + } + if (promo == null) + { + promo = Address.Promo; + } + Address.Promo = (Uri)promo; + if (str31 != null) + { + betaPromo = str31.ToUri(); + } + else + { + betaPromo = null; + } + if (betaPromo == null) + { + betaPromo = Address.BetaPromo; + } + Address.BetaPromo = (Uri)betaPromo; + if (str33 != null) + { + centralAtendimento = str33.ToUri(); + } + else + { + centralAtendimento = null; + } + if (centralAtendimento == null) + { + centralAtendimento = Address.get_CentralAtendimento(); + } + Address.set_CentralAtendimento((Uri)centralAtendimento); + flag = true; + return flag; + } + } + httpClient = null; + } + catch + { + } + flag = false; + return flag; + } + + public async Task GetImagesFromJson() + { + HttpResponseMessage async; + string str; + string str1; + try + { + using (HttpClient httpClient = new HttpClient()) + { + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + httpClient.set_Timeout(TimeSpan.FromSeconds(30)); + try + { + async = await httpClient.GetAsync(Address.get_LoginJson()); + async.EnsureSuccessStatusCode(); + } + catch + { + return; + } + if (async.get_IsSuccessStatusCode()) + { + JObject jObject = JObject.Parse(await async.get_Content().ReadAsStringAsync()); + JToken item = jObject.get_Item("Imagem"); + if (item != null) + { + str = Extensions.Value(item); + } + else + { + str = null; + } + string str2 = str; + JToken jToken = jObject.get_Item("Url"); + if (jToken != null) + { + str1 = Extensions.Value(jToken); + } + else + { + str1 = null; + } + string str3 = str1; + if (Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(str2) && Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(str3)) + { + this.Imagem = str2; + this.ImagemLink = str3; + } + } + } + httpClient = null; + } + catch + { + } + } + + public async Task Load() + { + bool flag1 = await Task.Run(async () => { + bool flag; + try + { + flag = await (new BaseServico()).LoadInicialParameters(); + } + catch (Exception exception) + { + flag = false; + } + return flag; + }); + return flag1; + } + + public async Task TrocaSenha() + { + bool flag; + long? nullable; + bool valueOrDefault; + object obj = null; + if (string.IsNullOrEmpty(this.Senha)) + { + await base.ShowMessage("NECESSÁRIO PREENCHER A SENHA ANTERIOR PARA REALIZAR A TROCA DE SENHA.", "OK", "", false); + flag = false; + } + else if (!string.IsNullOrEmpty(this.NovaSenha)) + { + Token token = new Token(); + if (this.Senha == this.NovaSenha) + { + await base.ShowMessage("A NOVA SENHA NÃO PODE SER IGUAL A SENHA ANTERIOR.", "OK", "", false); + flag = false; + } + else if (this.NovaSenha == this.ConfirmacaoSenha) + { + if (this.Senha.ToUpper().Contains("AGGER@")) + { + string senha = this.Senha; + string[] strArrays = senha.Split(new char[] { '@' }); + if ((int)strArrays.Length >= 3) + { + LoginViewModel.AggerAccess aggerAccess = new LoginViewModel.AggerAccess(); + LoginViewModel.Client client = new LoginViewModel.Client() + { + Login = strArrays[1].ToUpper(), + Password = (new Token()).AggerEncrypt(strArrays[2]) + }; + aggerAccess.Usuario = client; + aggerAccess.Acao = string.Format("TrocaSenha - {0}|{1}", this.Usuario.get_Id(), this.Usuario.get_Login()); + aggerAccess.Log = string.Concat("ANG - ", ApplicationHelper.NumeroSerial); + aggerAccess.Serial = ApplicationHelper.NumeroSerial; + LoginViewModel.AggerAccess aggerAccess1 = aggerAccess; + LoginViewModel.AggerAccess aggerAccess2 = null; + int num = 0; + try + { + aggerAccess2 = await Gestor.Application.Helpers.Connection.Post("Access/AggerLogin", aggerAccess1); + } + catch (Exception exception) + { + obj = exception; + num = 1; + } + if (num != 1) + { + obj = null; + LoginViewModel.AggerAccess aggerAccess3 = aggerAccess2; + if (aggerAccess3 != null) + { + LoginViewModel.Client usuario = aggerAccess3.Usuario; + if (usuario != null) + { + nullable = new long?(usuario.Id); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long num1 = (long)0; + valueOrDefault = nullable1.GetValueOrDefault() > num1 & nullable1.HasValue; + } + else + { + valueOrDefault = false; + } + if (valueOrDefault) + { + aggerAccess2 = null; + } + else + { + await base.ShowMessage("SENHA ANTERIOR INVÁLIDA.", "OK", "", false); + flag = false; + return flag; + } + } + else + { + Exception exception1 = (Exception)obj; + await base.ShowMessage("SENHA ANTERIOR INVÁLIDA.", "OK", "", false); + flag = false; + return flag; + } + } + else + { + await base.ShowMessage("SENHA ANTERIOR INVÁLIDA.", "OK", "", false); + flag = false; + return flag; + } + } + else if (Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(this.Usuario.get_Senha()) && this.Senha != token.AggerDecrypt(this.Usuario.get_Senha())) + { + await base.ShowMessage("SENHA ANTERIOR INVÁLIDA.", "OK", "", false); + flag = false; + return flag; + } + UsuarioServico usuarioServico = new UsuarioServico(); + this.Usuario.set_SenhaAnterior(token.AggerEncrypt(this.Senha)); + this.Usuario.set_Senha(token.AggerEncrypt(this.NovaSenha)); + await usuarioServico.Save(this.Usuario); + if (!usuarioServico.Sucesso) + { + this.Usuario.set_SenhaAnterior(string.Empty); + this.Usuario.set_Senha(string.Empty); + await base.ShowMessage("VERIFIQUE OS DADOS DIGITADOS E TENTE NOVAMENTE.", "OK", "", false); + flag = false; + } + else + { + this.Senha = this.NovaSenha; + flag = true; + } + } + else + { + await base.ShowMessage("A SENHA E A CONFIRMAÇÃO DA SENHA DEVEM SER IGUAIS.", "OK", "", false); + flag = false; + } + } + else + { + await base.ShowMessage("NECESSÁRIO PREENCHER A NOVA SENHA PARA REALIZAR A TROCA DE SENHA.", "OK", "", false); + flag = false; + } + return flag; + } + + public async Task Validate(string login, string password) + { + bool flag; + string str; + long? nullable; + Gestor.Model.Domain.Seguros.Usuario usuario; + this.ErrorLoginVisibility = Visibility.Hidden; + if (!login.Contains("AGGER@")) + { + usuario = await (new BaseServico()).BuscarUsuario(login, password); + if (usuario != null) + { + str = await base.VerificarAcesso(usuario.get_Id()); + } + else + { + str = "DADOS DE ACESSO INVÁLIDOS"; + } + string str1 = str; + if (str1 == null) + { + Recursos.Usuario = usuario; + Recursos.Empresa = (new BaseServico()).BuscarEmpresa(Recursos.Usuario.get_IdEmpresa()); + Recursos.Usuario.set_Senha(string.Empty); + File.WriteAllText(this.userJson, JsonConvert.SerializeObject(usuario)); + flag = true; + } + else + { + this.ErrorLogin = str1; + this.ErrorLoginVisibility = Visibility.Visible; + flag = false; + } + } + else + { + string[] strArrays = login.Split(new char[] { '@' }); + LoginViewModel.AggerAccess aggerAccess = new LoginViewModel.AggerAccess(); + LoginViewModel.Client client = new LoginViewModel.Client() + { + Login = strArrays[1], + Password = (new Token()).AggerEncrypt(password) + }; + aggerAccess.Usuario = client; + aggerAccess.Acao = "AggerAccessNovoGestor"; + aggerAccess.Log = string.Concat("ANG - ", ApplicationHelper.NumeroSerial); + aggerAccess.Serial = ApplicationHelper.NumeroSerial; + LoginViewModel.AggerAccess aggerAccess1 = await Gestor.Application.Helpers.Connection.Post("Access/AggerLogin", aggerAccess); + if (aggerAccess1 != null) + { + LoginViewModel.Client usuario1 = aggerAccess1.Usuario; + if (usuario1 != null) + { + nullable = new long?(usuario1.Id); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long num = (long)0; + if (nullable1.GetValueOrDefault() > num & nullable1.HasValue) + { + Gestor.Model.Domain.Seguros.Usuario usuario2 = new Gestor.Model.Domain.Seguros.Usuario(); + usuario2.set_Nome(string.Concat("ACESSO AGGER - USUÁRIO ", aggerAccess1.Usuario.Name)); + usuario2.set_Login(aggerAccess1.Usuario.Login); + usuario2.set_IdEmpresa((long)1); + usuario2.set_PermissaoAggilizador(new long?((long)1)); + Recursos.Usuario = usuario2; + Recursos.Empresa = (new BaseServico()).BuscarEmpresa(Recursos.Usuario.get_IdEmpresa()); + flag = true; + usuario = null; + return flag; + } + } + this.ErrorLoginVisibility = Visibility.Visible; + flag = false; + } + usuario = null; + return flag; + } + + private class AggerAccess + { + public string Acao + { + get; + set; + } + + public DateTime? Data + { + get; + set; + } + + public long Id + { + get; + set; + } + + public string Ip + { + get; + set; + } + + public string Log + { + get; + set; + } + + public string Serial + { + get; + set; + } + + public LoginViewModel.Client Usuario + { + get; + set; + } + + public AggerAccess() + { + } + } + + private class Client + { + public bool AttendancePrivate + { + get; + set; + } + + public DateTime? DateLoginFinal + { + get; + set; + } + + public DateTime? DateLoginStart + { + get; + set; + } + + public bool Deleted + { + get; + set; + } + + public string Email + { + get; + set; + } + + public DateTime? ExpirationPassDate + { + get; + set; + } + + public long Id + { + get; + set; + } + + public string Login + { + get; + set; + } + + public string Name + { + get; + set; + } + + public string Password + { + get; + set; + } + + public Client() + { + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/MainViewModel.cs b/Codemerx/Gestor.Application/ViewModels/MainViewModel.cs new file mode 100644 index 0000000..26324af --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/MainViewModel.cs @@ -0,0 +1,1273 @@ +using Gestor.Application.Actions; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Application.Views.Financeiro; +using Gestor.Model.API; +using Gestor.Model.Common; +using Gestor.Model.Domain.Card; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.License; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Threading; + +namespace Gestor.Application.ViewModels +{ + public class MainViewModel : BaseSegurosViewModel + { + public Gestor.Application.Views.Financeiro.FinanceiroView FinanceiroView; + + public Gestor.Application.ViewModels.Seguros.ConsultaViewModel ConsultaViewModel; + + public Gestor.Application.ViewModels.Seguros.ClienteViewModel ClienteViewModel; + + private readonly ClienteServico _servico; + + public Gestor.Application.ViewModels.DashboardViewModel DashboardViewModel; + + private List _boletos; + + private BitmapImage _qrCode; + + private string _code; + + private Geometry _maximizeRestore = Geometry.Parse((string)System.Windows.Application.Current.Resources["Restore"]); + + private object _content; + + private double _headMaxWidth; + + private string _head; + + private string _tela; + + private TipoTela? _telaAberta; + + private string _versao; + + private long _selectedRamo = (long)5; + + public bool PesquisaAvançada; + + private Cliente _selectedCliente; + + private bool _isEnableDocumento; + + private bool _isEnableItens; + + private Gestor.Model.Common.TipoDocumento _tipoDocumento; + + private string _documentoPrincipal = ""; + + private ObservableCollection _ajuda = new ObservableCollection(); + + private bool _matrizFilial = LicenseHelper.Produtos.Any(new Func((Licenca x) => { + if (x.get_Produto() != 2) + { + return false; + } + return x.get_Status() == 1; + })); + + private readonly bool _temEpic = LicenseHelper.Produtos.Any(new Func((Licenca produto) => { + if (produto.get_Produto() != 83) + { + return false; + } + return produto.get_Status() == 1; + })); + + private bool _carregandoAjuda; + + private string _empresa = ""; + + private ObservableCollection _contatos = new ObservableCollection(); + + private int _liquido; + + private int _mediaComissao; + + private int _resultado; + + private Visibility _visibleChaveInstalacao = Visibility.Collapsed; + + private Visibility _visibleSeguros = Visibility.Collapsed; + + private Visibility _visibleBi = Visibility.Collapsed; + + private FiltroStatusDocumento _selectedStatus; + + private TipoFiltroCliente _selectedFiltroCliente = 1; + + private bool _buscaNome = true; + + private bool _enableSeguros; + + private bool _enableBuscar; + + private Visibility _visibilityVoltar = Visibility.Collapsed; + + private int _notasBadge; + + private int _tarefasBadge; + + private int _badges; + + private int _ultimoUpdate; + + private Visibility _mensagemTarefasVisibility = Visibility.Collapsed; + + private string _mensagemTarefas = ""; + + private string _pesquisa = ""; + + private int _medalhaCor; + + private Visibility _medalhaVisibility = Visibility.Collapsed; + + private string _placeHolderAutoComplete = "PESQUISAR CLIENTE POR NOME OU NOME SOCIAL"; + + public ObservableCollection Ajuda + { + get + { + return this._ajuda; + } + set + { + this._ajuda = value; + base.OnPropertyChanged("Ajuda"); + } + } + + public int Badges + { + get + { + return this._badges; + } + set + { + this._badges = value; + base.OnPropertyChanged("Badges"); + } + } + + public List Boletos + { + get + { + return this._boletos; + } + set + { + this._boletos = value; + base.OnPropertyChanged("Boletos"); + } + } + + public bool BuscaNome + { + get + { + return this._buscaNome; + } + set + { + this._buscaNome = value; + base.OnPropertyChanged("BuscaNome"); + } + } + + public bool CarregandoAjuda + { + get + { + return this._carregandoAjuda; + } + set + { + this._carregandoAjuda = value; + base.OnPropertyChanged("CarregandoAjuda"); + } + } + + public static Cliente ClienteSelecionado + { + get; + set; + } + + public List ClientesEncontrados + { + get; + set; + } + + public List ClientesFiltrados + { + get; + set; + } + + public string Code + { + get + { + return this._code; + } + set + { + this._code = value; + base.OnPropertyChanged("Code"); + } + } + + public ObservableCollection Contatos + { + get + { + return this._contatos; + } + set + { + this._contatos = value; + base.OnPropertyChanged("Contatos"); + } + } + + public object Content + { + get + { + return this._content; + } + set + { + this._content = value; + base.OnPropertyChanged("Content"); + } + } + + public string DocumentoPrincipal + { + get + { + return this._documentoPrincipal; + } + set + { + this._documentoPrincipal = value; + base.OnPropertyChanged("DocumentoPrincipal"); + } + } + + public string Empresa + { + get + { + return this._empresa; + } + set + { + this._empresa = value; + base.OnPropertyChanged("Empresa"); + } + } + + public bool EnableBuscar + { + get + { + return this._enableBuscar; + } + set + { + this._enableBuscar = value; + base.OnPropertyChanged("EnableBuscar"); + } + } + + public bool EnableSeguros + { + get + { + return this._enableSeguros; + } + set + { + this._enableSeguros = value; + base.OnPropertyChanged("EnableSeguros"); + } + } + + public string Head + { + get + { + return this._head; + } + set + { + this._head = value; + base.OnPropertyChanged("Head"); + } + } + + public double HeadMaxWidth + { + get + { + return this._headMaxWidth; + } + set + { + this._headMaxWidth = value; + base.OnPropertyChanged("HeadMaxWidth"); + } + } + + public bool Invoke { get; set; } = true; + + public bool Isdropped + { + get; + set; + } + + public bool IsEnableDocumento + { + get + { + return this._isEnableDocumento; + } + set + { + this._isEnableDocumento = value; + base.OnPropertyChanged("IsEnableDocumento"); + } + } + + public bool IsEnableItens + { + get + { + return this._isEnableItens; + } + set + { + this._isEnableItens = value; + base.OnPropertyChanged("IsEnableItens"); + } + } + + public bool IsPopulating + { + get; + set; + } + + public bool MatrizFilial + { + get + { + return this._matrizFilial; + } + set + { + this._matrizFilial = value; + base.OnPropertyChanged("MatrizFilial"); + } + } + + public Geometry MaximizeRestore + { + get + { + return this._maximizeRestore; + } + set + { + this._maximizeRestore = value; + base.OnPropertyChanged("MaximizeRestore"); + } + } + + public int MedalhaCor + { + get + { + return this._medalhaCor; + } + set + { + this._medalhaCor = value; + base.OnPropertyChanged("MedalhaCor"); + } + } + + public Visibility MedalhaVisibility + { + get + { + return this._medalhaVisibility; + } + set + { + this._medalhaVisibility = value; + base.OnPropertyChanged("MedalhaVisibility"); + } + } + + public string MensagemTarefas + { + get + { + return this._mensagemTarefas; + } + set + { + this._mensagemTarefas = value; + base.OnPropertyChanged("MensagemTarefas"); + } + } + + public Visibility MensagemTarefasVisibility + { + get + { + return this._mensagemTarefasVisibility; + } + set + { + this._mensagemTarefasVisibility = value; + base.OnPropertyChanged("MensagemTarefasVisibility"); + } + } + + public int NotasBadge + { + get + { + return this._notasBadge; + } + set + { + this._notasBadge = value; + this.Badges = value + this.TarefasBadge; + base.OnPropertyChanged("NotasBadge"); + } + } + + public string Pesquisa + { + get + { + return this._pesquisa; + } + set + { + this._pesquisa = value; + base.OnPropertyChanged("Pesquisa"); + } + } + + public string PlaceHolderAutoComplete + { + get + { + return this._placeHolderAutoComplete; + } + set + { + this._placeHolderAutoComplete = value; + base.OnPropertyChanged("PlaceHolderAutoComplete"); + } + } + + public BitmapImage QrCode + { + get + { + return this._qrCode; + } + set + { + this._qrCode = value; + base.OnPropertyChanged("QrCode"); + } + } + + public Cliente SelectedCliente + { + get + { + return this._selectedCliente; + } + set + { + long? nullable; + if (this.Invoke) + { + if (value != null) + { + long id = value.get_Id(); + Cliente selectedCliente = this.SelectedCliente; + if (selectedCliente != null) + { + nullable = new long?(selectedCliente.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + if (id == nullable1.GetValueOrDefault() & nullable1.HasValue) + { + this._selectedCliente = value; + base.OnPropertyChanged("SelectedCliente"); + return; + } + } + MainViewModel.ClienteSelecionado = value; + } + this._selectedCliente = value; + base.OnPropertyChanged("SelectedCliente"); + } + } + + public TipoFiltroCliente SelectedFiltroCliente + { + get + { + return this._selectedFiltroCliente; + } + set + { + this._selectedFiltroCliente = value; + this.BuscaNome = value == 1; + this.PlaceHolderAutoComplete = (this._selectedFiltroCliente == null ? "PESQUISAR CLIENTE POR NOME OU SOBRENOME" : "PESQUISAR CLIENTE POR NOME OU DOCUMENTO"); + base.OnPropertyChanged("SelectedFiltroCliente"); + } + } + + public long SelectedRamo + { + get + { + return this._selectedRamo; + } + set + { + this._selectedRamo = value; + base.OnPropertyChanged("SelectedRamo"); + } + } + + public FiltroStatusDocumento SelectedStatus + { + get + { + return this._selectedStatus; + } + set + { + this._selectedStatus = value; + this.WorkOnSelectedStatus(value); + base.OnPropertyChanged("SelectedStatus"); + } + } + + public static FiltroStatusDocumento StatusSelecionado + { + get; + set; + } + + public int TarefasBadge + { + get + { + return this._tarefasBadge; + } + set + { + this._tarefasBadge = value; + this.Badges = value + this.NotasBadge; + base.OnPropertyChanged("TarefasBadge"); + } + } + + public string Tela + { + get + { + return this._tela; + } + set + { + this._tela = value; + base.OnPropertyChanged("Tela"); + } + } + + public TipoTela? TelaAberta + { + get + { + return this._telaAberta; + } + set + { + this._telaAberta = value; + base.OnPropertyChanged("TelaAberta"); + } + } + + public Visibility TemEpic + { + get + { + if (!this._temEpic) + { + return Visibility.Collapsed; + } + return Visibility.Visible; + } + } + + public Gestor.Model.Common.TipoDocumento TipoDocumento + { + get + { + return this._tipoDocumento; + } + set + { + this._tipoDocumento = value; + base.OnPropertyChanged("TipoDocumento"); + } + } + + public List VendedorUsuario + { + get; + set; + } + + public string Versao + { + get + { + return this._versao; + } + set + { + this._versao = value; + base.OnPropertyChanged("Versao"); + } + } + + public static string ViewAberta + { + get; + set; + } + + public Visibility VisibilityVoltar + { + get + { + return this._visibilityVoltar; + } + set + { + this._visibilityVoltar = value; + base.OnPropertyChanged("VisibilityVoltar"); + } + } + + public Visibility VisibleBi + { + get + { + return this._visibleBi; + } + set + { + this._visibleBi = value; + base.OnPropertyChanged("VisibleBi"); + } + } + + public Visibility VisibleChaveInstalacao + { + get + { + return this._visibleChaveInstalacao; + } + set + { + this._visibleChaveInstalacao = value; + base.OnPropertyChanged("VisibleChaveInstalacao"); + } + } + + public Visibility VisibleSeguros + { + get + { + return this._visibleSeguros; + } + set + { + this._visibleSeguros = value; + base.OnPropertyChanged("VisibleSeguros"); + } + } + + public MainViewModel() + { + TipoFiltroCliente? nullable; + TipoFiltroCliente? filtroInicial; + Gestor.Application.Actions.Actions.AtualizaBadges = new Action(this.AtualizarBadges); + Gestor.Application.Actions.Actions.LimparCliente = new Action(this.LimparCliente); + this._servico = new ClienteServico(); + Gestor.Application.Actions.Actions.UpdateDocumento = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.UpdateDocumento, new Action(this.UpdateRamoIcon)); + Gestor.Application.Actions.Actions.SelectCliente = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.SelectCliente, new Action(this.SelectCliente)); + Gestor.Application.Actions.Actions.AtualizaContatos = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.AtualizaContatos, new Action(this.AtualizarContatos)); + Gestor.Application.Actions.Actions.EnableItens = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.EnableItens, new Action(this.EnableItens)); + Gestor.Application.Actions.Actions.EnableDocumento = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.EnableDocumento, new Action(this.EnableDocumento)); + this.Versao = string.Concat(Recursos.Empresa.get_Nome(), " | ", LoginViewModel.VersaoAtual); + Usuario usuario = Recursos.Usuario; + if (usuario != null) + { + filtroInicial = usuario.get_FiltroInicial(); + } + else + { + nullable = null; + filtroInicial = nullable; + } + nullable = filtroInicial; + this.SelectedFiltroCliente = nullable.GetValueOrDefault(); + (new DispatcherTimer(TimeSpan.FromHours(1), DispatcherPriority.Background, (object sender, EventArgs args) => this.AtualizarBadges(), System.Windows.Application.Current.Dispatcher)).Start(); + } + + private async void AtualizarBadges() + { + object obj; + object obj1; + try + { + int[] numArray = await (new TarefaServico()).AtualizarNotasTarefas(); + this.NotasBadge = numArray[0]; + this.TarefasBadge = numArray[1]; + if (numArray[1] > this._ultimoUpdate) + { + MainViewModel mainViewModel = this; + object obj2 = numArray[1]; + obj = (numArray[1] > 1 ? "S" : ""); + obj1 = (numArray[1] > 1 ? "S" : ""); + mainViewModel.MensagemTarefas = string.Format("{0} NOVA{1} TAREFA{2}", obj2, obj, obj1); + this.MensagemTarefasVisibility = Visibility.Visible; + } + this._ultimoUpdate = numArray[1]; + } + catch + { + } + } + + private async void AtualizarContatos() + { + ObservableCollection observableCollection; + List contatos = new List(); + if (this.SelectedCliente != null) + { + observableCollection = await this._servico.BuscarTelefonesAsync(this.SelectedCliente.get_Id()); + ObservableCollection observableCollection1 = await this._servico.BuscarEmailsAsync(this.SelectedCliente.get_Id()); + if (observableCollection != null) + { + List contatos1 = contatos; + ObservableCollection observableCollection2 = observableCollection; + contatos1.AddRange(observableCollection2.Select((ClienteTelefone x) => { + Contato contato = new Contato(); + contato.set_Tipo(0); + contato.set_TipoTelefone(new TipoTelefone?(x.get_Tipo().GetValueOrDefault(1))); + contato.set_Numero(string.Concat(x.get_Prefixo(), " ", x.get_Numero())); + return contato; + }).Take(2).ToList()); + } + if (observableCollection1 != null) + { + List contatos2 = contatos; + ObservableCollection observableCollection3 = observableCollection1; + contatos2.AddRange(observableCollection3.Select((ClienteEmail x) => { + Contato contato = new Contato(); + contato.set_Tipo(1); + contato.set_TipoTelefone(null); + contato.set_Numero(x.get_Email()); + return contato; + }).Take(1).ToList()); + } + this.Contatos = new ObservableCollection(contatos); + } + contatos = null; + observableCollection = null; + } + + private async void AtualizarMedalha(List apolices) + { + decimal zero; + Qualificacao qualificacao = await this._servico.BuscarQualificacaoAsync(); + if (qualificacao.get_Id() == 0) + { + Qualificacao qualificacao1 = new Qualificacao(); + qualificacao1.set_Liquido1(decimal.Zero); + qualificacao1.set_Liquido2(new decimal(1000)); + qualificacao1.set_Liquido3(new decimal(5000)); + qualificacao1.set_Comissao1(new decimal(10)); + qualificacao1.set_Comissao2(new decimal(15)); + qualificacao1.set_Comissao3(new decimal(20)); + qualificacao1.set_Resultado1(new decimal(100)); + qualificacao1.set_Resultado2(new decimal(200)); + qualificacao1.set_Resultado3(new decimal(300)); + qualificacao1.set_Id((long)1); + qualificacao = qualificacao1; + } + this._liquido = 0; + this._mediaComissao = 0; + this._resultado = 0; + List documentos = apolices; + decimal num = documentos.Sum((Documento p) => p.get_PremioLiquido()); + if (num >= qualificacao.get_Liquido3()) + { + this._liquido = 3; + } + else if (num >= qualificacao.get_Liquido2()) + { + this._liquido = 2; + } + else if (num >= qualificacao.get_Liquido1()) + { + this._liquido = 1; + } + List documentos1 = apolices; + if (documentos1.Any((Documento c) => c.get_Comissao() > decimal.Zero)) + { + List documentos2 = apolices; + decimal num1 = documentos2.Sum((Documento c) => c.get_Comissao()); + zero = decimal.Round(num1 / apolices.Count((Documento c) => c.get_Comissao() > decimal.Zero), 2); + } + else + { + zero = decimal.Zero; + } + decimal num2 = zero; + if (num2 >= qualificacao.get_Comissao3()) + { + this._mediaComissao = 3; + } + else if (num2 >= qualificacao.get_Comissao2()) + { + this._mediaComissao = 2; + } + else if (num2 >= qualificacao.get_Comissao1()) + { + this._mediaComissao = 1; + } + List documentos3 = apolices; + decimal num3 = documentos3.Sum((Documento p) => ((p.get_PremioLiquido() + (p.get_AdicionalComiss() ? p.get_PremioAdicional() : decimal.Zero)) * p.get_Comissao()) * new decimal(1, 0, 0, false, 2)); + if (num3 >= qualificacao.get_Resultado3()) + { + this._resultado = 3; + } + else if (num3 >= qualificacao.get_Resultado2()) + { + this._resultado = 2; + } + else if (num3 >= qualificacao.get_Resultado1()) + { + this._resultado = 1; + } + this.MedalhaCor = (int)Math.Round((double)(((float)this._liquido + (float)this._mediaComissao + (float)this._resultado) / 3f)); + this.MedalhaVisibility = Visibility.Visible; + } + + public async Task CarregarAjuda() + { + if (this.TelaAberta.HasValue) + { + if (!this.Ajuda.Any((AjudaTela x) => { + TipoTela tela = x.get_Tela(); + TipoTela? telaAberta = this.TelaAberta; + return tela == telaAberta.GetValueOrDefault() & telaAberta.HasValue; + })) + { + this.CarregandoAjuda = true; + TipoTela? nullable = this.TelaAberta; + this.Ajuda = new ObservableCollection(await Connection.Get>(string.Format("Help/{0}", (int)nullable.Value), true, false)); + this.CarregandoAjuda = false; + } + } + } + + private void EnableDocumento(bool enabled) + { + this.IsEnableDocumento = enabled; + } + + private void EnableItens(bool enabled) + { + this.IsEnableItens = enabled; + } + + public List FiltrarClientes(string value) + { + return base.FilterCliente(this.ClientesEncontrados, value); + } + + private void LimparCliente() + { + this.SelectedCliente = null; + this.Contatos = null; + this.DocumentoPrincipal = ""; + this.Pesquisa = ""; + } + + public async void LimparDocumentos() + { + Task task; + this.Contatos = null; + this.DocumentoPrincipal = ""; + string viewAberta = MainViewModel.ViewAberta; + if (viewAberta != "ConsultaOriginalView") + { + if (viewAberta == "ClienteView") + { + Gestor.Application.ViewModels.Seguros.ClienteViewModel clienteViewModel = this.ClienteViewModel; + if (clienteViewModel != null) + { + clienteViewModel.SelecionaCliente(null); + } + else + { + } + } + } + else if (this.ConsultaViewModel != null) + { + Gestor.Application.ViewModels.Seguros.ConsultaViewModel consultaViewModel = this.ConsultaViewModel; + if (consultaViewModel != null) + { + task = consultaViewModel.SelecionaCliente(null, true); + } + else + { + task = null; + } + await task; + } + } + + public async void Medalha() + { + await base.ShowMedalha(this._liquido, this._mediaComissao, this._resultado, this.MedalhaCor); + } + + public async Task SelecionarCliente(Cliente value) + { + this.IsEnableDocumento = false; + this.IsEnableItens = false; + this.LimparDocumentos(); + if (value != null) + { + if (this.Invoke) + { + MainViewModel.ClienteSelecionado = value; + } + await this.WorkOnSelectedCliente(value); + this.IsEnableDocumento = true; + } + } + + private void SelectCliente(Cliente cliente) + { + string str; + string str1; + this.SelectedCliente = cliente; + string pesquisa = this.Pesquisa; + if (cliente != null) + { + string nomeSocial = cliente.get_NomeSocial(); + if (nomeSocial != null) + { + str = nomeSocial.Trim(); + } + else + { + str = null; + } + } + else + { + str = null; + } + if (pesquisa != str) + { + if (cliente != null) + { + string nomeSocial1 = cliente.get_NomeSocial(); + if (nomeSocial1 != null) + { + str1 = nomeSocial1.Trim(); + } + else + { + str1 = null; + } + } + else + { + str1 = null; + } + this.Pesquisa = str1; + } + } + + private void UpdateRamoIcon(Documento documento) + { + if (documento == null || documento.get_Id() == 0) + { + return; + } + this.SelectedRamo = documento.get_Controle().get_Ramo().get_Id(); + } + + public async void VerificarLogo() + { + if (string.IsNullOrEmpty(Recursos.Empresa.get_LogoId()) && Recursos.Empresa.get_Logo() != null) + { + Logo logo = new Logo(); + logo.set_CustomId(ApplicationHelper.NumeroSerial); + logo.set_Data(Recursos.Empresa.get_Logo()); + Gestor.Model.Domain.Common.Empresa empresa = Recursos.Empresa; + empresa.set_LogoId(await Funcoes.Criarlogo(logo)); + empresa = null; + (new EmpresaServico()).AtualizarLogoId(Recursos.Empresa.get_Id(), Recursos.Empresa.get_LogoId()); + } + } + + private async Task WorkOnSelectedCliente(Cliente value) + { + object nome; + string nomeSocial; + Task task; + long? nullable; + base.IsEnabled = false; + List contatos = new List(); + ObservableCollection observableCollection = await this._servico.BuscarTelefonesAsync(value.get_Id()); + ObservableCollection observableCollection1 = await this._servico.BuscarEmailsAsync(value.get_Id()); + if (observableCollection != null) + { + List contatos1 = contatos; + ObservableCollection observableCollection2 = observableCollection; + contatos1.AddRange(observableCollection2.Select((ClienteTelefone x) => { + Contato contato = new Contato(); + contato.set_Tipo(0); + contato.set_TipoTelefone(new TipoTelefone?(x.get_Tipo().GetValueOrDefault(1))); + contato.set_Numero(string.Concat(x.get_Prefixo(), " ", x.get_Numero())); + return contato; + }).Take(2).ToList()); + } + if (observableCollection1 != null) + { + List contatos2 = contatos; + ObservableCollection observableCollection3 = observableCollection1; + contatos2.AddRange(observableCollection3.Select((ClienteEmail x) => { + Contato contato = new Contato(); + contato.set_Tipo(1); + contato.set_TipoTelefone(null); + contato.set_Numero(x.get_Email()); + return contato; + }).Take(1).ToList()); + } + this.Contatos = new ObservableCollection(contatos); + this.TipoDocumento = value.get_DocumentoPrincipal().GetValueOrDefault(); + MainViewModel mainViewModel = this; + Gestor.Model.Domain.Common.Empresa empresa = Recursos.Empresas.FirstOrDefault((Gestor.Model.Domain.Common.Empresa x) => x.get_Id() == value.get_IdEmpresa()); + if (empresa != null) + { + nome = empresa.get_Nome(); + } + else + { + nome = null; + } + if (nome == null) + { + nome = Recursos.Empresa.get_Nome(); + } + mainViewModel.Empresa = (string)nome; + switch (this.TipoDocumento) + { + case 0: + { + MainViewModel mainViewModel1 = this; + string documento = value.get_Documento(); + if (documento == null) + { + documento = ""; + } + mainViewModel1.DocumentoPrincipal = documento; + break; + } + case 1: + { + MainViewModel mainViewModel2 = this; + string rne = value.get_Rne(); + if (rne == null) + { + rne = ""; + } + mainViewModel2.DocumentoPrincipal = rne; + break; + } + case 2: + { + MainViewModel mainViewModel3 = this; + string cei = value.get_Cei(); + if (cei == null) + { + cei = ""; + } + mainViewModel3.DocumentoPrincipal = cei; + break; + } + case 3: + { + MainViewModel mainViewModel4 = this; + string caepf = value.get_Caepf(); + if (caepf == null) + { + caepf = ""; + } + mainViewModel4.DocumentoPrincipal = caepf; + break; + } + } + if (MainViewModel.ClienteSelecionado != null) + { + MainViewModel.ClienteSelecionado.set_Telefones(observableCollection); + MainViewModel.ClienteSelecionado.set_Emails(observableCollection1); + } + string viewAberta = MainViewModel.ViewAberta; + if (viewAberta != "ConsultaOriginalView") + { + if (viewAberta == "ClienteView") + { + Gestor.Application.ViewModels.Seguros.ClienteViewModel clienteViewModel = this.ClienteViewModel; + if (clienteViewModel != null) + { + clienteViewModel.SelecionaCliente(this.SelectedCliente); + } + else + { + } + MainViewModel mainViewModel5 = this; + string str = string.Concat("ACESSOU CLIENTE \"", this.SelectedCliente.get_Nome(), "\""); + long id = this.SelectedCliente.get_Id(); + TipoTela? nullable1 = new TipoTela?(1); + Cliente selectedCliente = this.SelectedCliente; + if (selectedCliente != null) + { + nullable = new long?(selectedCliente.get_Id()); + } + else + { + nullable = null; + } + mainViewModel5.RegistrarAcao(str, id, nullable1, string.Format("ID CLIENTE: {0}", nullable)); + } + } + else if (this.ConsultaViewModel != null) + { + Gestor.Application.ViewModels.Seguros.ConsultaViewModel consultaViewModel = this.ConsultaViewModel; + if (consultaViewModel != null) + { + task = consultaViewModel.SelecionaCliente(value, true); + } + else + { + task = null; + } + await task; + this.AtualizarMedalha(this.ConsultaViewModel.Apolices.ToList()); + } + base.IsEnabled = true; + MainViewModel mainViewModel6 = this; + Cliente cliente = this.SelectedCliente; + if (cliente != null) + { + nomeSocial = cliente.get_NomeSocial(); + } + else + { + nomeSocial = null; + } + mainViewModel6.Pesquisa = nomeSocial; + contatos = null; + observableCollection = null; + } + + private void WorkOnSelectedStatus(FiltroStatusDocumento value) + { + MainViewModel.StatusSelecionado = value; + if (this.SelectedCliente == null) + { + return; + } + if (!this.Invoke) + { + return; + } + string viewAberta = MainViewModel.ViewAberta; + if (viewAberta == "ConsultaOriginalView") + { + Gestor.Application.ViewModels.Seguros.ConsultaViewModel consultaViewModel = this.ConsultaViewModel; + if (consultaViewModel == null) + { + return; + } + consultaViewModel.SelecionarCliente(this.SelectedCliente); + return; + } + if (viewAberta != "ClienteView") + { + return; + } + Gestor.Application.ViewModels.Seguros.ClienteViewModel clienteViewModel = this.ClienteViewModel; + if (clienteViewModel == null) + { + return; + } + clienteViewModel.SelecionaCliente(this.SelectedCliente); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/MenuBIViewModel.cs b/Codemerx/Gestor.Application/ViewModels/MenuBIViewModel.cs new file mode 100644 index 0000000..9114678 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/MenuBIViewModel.cs @@ -0,0 +1,12 @@ +using Gestor.Application.ViewModels.Generic; +using System; + +namespace Gestor.Application.ViewModels +{ + public class MenuBIViewModel : BaseSegurosViewModel + { + public MenuBIViewModel() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/MenuFerramentasViewModel.cs b/Codemerx/Gestor.Application/ViewModels/MenuFerramentasViewModel.cs new file mode 100644 index 0000000..abbe3b1 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/MenuFerramentasViewModel.cs @@ -0,0 +1,88 @@ +using Gestor.Application.ViewModels.Ferramentas; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Runtime.CompilerServices; +using System.Windows; + +namespace Gestor.Application.ViewModels +{ + internal class MenuFerramentasViewModel : BaseSegurosViewModel + { + private Usuario _selectedUsuario = new Usuario(); + + private Visibility _visibilityUsuario; + + private Visibility _visibilityEmpresa; + + private object _content; + + public object Content + { + get + { + return this._content; + } + set + { + this._content = value; + base.OnPropertyChanged("Content"); + } + } + + public Usuario SelectedUsuario + { + get + { + return this._selectedUsuario; + } + set + { + this._selectedUsuario = value; + base.OnPropertyChanged("SelectedUsuario"); + } + } + + public static Usuario UsuarioSelecionado + { + get; + set; + } + + public Gestor.Application.ViewModels.Ferramentas.UsuarioViewModel UsuarioViewModel + { + get; + set; + } + + public Visibility VisibilityEmpresa + { + get + { + return this._visibilityEmpresa; + } + set + { + this._visibilityEmpresa = value; + base.OnPropertyChanged("VisibilityEmpresa"); + } + } + + public Visibility VisibilityUsuario + { + get + { + return this._visibilityUsuario; + } + set + { + this._visibilityUsuario = value; + base.OnPropertyChanged("VisibilityUsuario"); + } + } + + public MenuFerramentasViewModel() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/MenuItemViewModel.cs b/Codemerx/Gestor.Application/ViewModels/MenuItemViewModel.cs new file mode 100644 index 0000000..e51f2f6 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/MenuItemViewModel.cs @@ -0,0 +1,1048 @@ +using Gestor.Application.Actions; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Application.Views.Seguros.Itens; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels +{ + public class MenuItemViewModel : BaseSegurosViewModel + { + private readonly ItemServico _servico; + + private string _acaoItens = "MANTER"; + + private readonly Documento _documentoSelecionado; + + public bool AlterandoSelectedItem; + + private bool _endossoRenovacao; + + private ObservableCollection _itens = new ObservableCollection(); + + private ObservableCollection _itensFiltrados = new ObservableCollection(); + + private Item _selectedItem = new Item(); + + private bool _mostrarLista; + + private bool _isExpanded = true; + + private ManutencaoItem _manutencao; + + private object _view; + + private bool _allSelectedChanging; + + private bool? _allSelected = new bool?(false); + + private string _manterTodosText = "MANTER TODOS OS ITENS"; + + private string _manterText = "MANTER ITENS"; + + public bool? AllSelected + { + get + { + return this._allSelected; + } + set + { + bool? nullable = value; + bool? nullable1 = this._allSelected; + if (nullable.GetValueOrDefault() == nullable1.GetValueOrDefault() & nullable.HasValue == nullable1.HasValue) + { + return; + } + this._allSelected = value; + this.AllSelectedChanged(); + this.Itens = new ObservableCollection(this.Itens); + base.OnPropertyChanged("AllSelected"); + } + } + + private bool Carregando + { + get; + set; + } + + public bool EndossoRenovacao + { + get + { + return this._endossoRenovacao; + } + set + { + this._endossoRenovacao = value; + base.OnPropertyChanged("EndossoRenovacao"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public ObservableCollection Itens + { + get + { + return this._itens; + } + set + { + this._itens = value; + base.OnPropertyChanged("Itens"); + } + } + + public ObservableCollection ItensFiltrados + { + get + { + return this._itensFiltrados; + } + set + { + this._itensFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + foreach (Item itensFiltrado in this.ItensFiltrados) + { + itensFiltrado.add_PropertyChanged(new PropertyChangedEventHandler(this.EntryOnPropertyChanged)); + } + base.OnPropertyChanged("ItensFiltrados"); + } + } + + public string ManterText + { + get + { + return this._manterText; + } + set + { + this._manterText = value; + base.OnPropertyChanged("ManterText"); + } + } + + public string ManterTodosText + { + get + { + return this._manterTodosText; + } + set + { + this._manterTodosText = value; + base.OnPropertyChanged("ManterTodosText"); + } + } + + public ManutencaoItem Manutencao + { + get + { + return this._manutencao; + } + set + { + this._manutencao = value; + base.OnPropertyChanged("Manutencao"); + } + } + + public bool MostrarLista + { + get + { + return this._mostrarLista; + } + set + { + this._mostrarLista = value; + base.OnPropertyChanged("MostrarLista"); + } + } + + public long Ramo + { + get; + set; + } + + public Item SelectedItem + { + get + { + return this._selectedItem; + } + set + { + this.WorkOnSelectedItem(value); + this._selectedItem = value; + base.OnPropertyChanged("SelectedItem"); + } + } + + public object View + { + get + { + return this._view; + } + set + { + this._view = value; + base.OnPropertyChanged("View"); + } + } + + public MenuItemViewModel(long ramo, ManutencaoItem manutencao) + { + if (ramo == (long)6 || ramo == (long)7 || ramo == (long)9 || ramo == (long)10 || ramo == (long)53 || ramo == (long)66) + { + this._acaoItens = "MOVER"; + } + this._manterTodosText = string.Concat(this._acaoItens, " TODOS OS ITENS"); + this._manterText = string.Concat(this._acaoItens, " ITEM"); + this.Ramo = ramo; + this._servico = new ItemServico(); + this._documentoSelecionado = (manutencao == null ? ConsultaViewModel.DocumentoSelecionado : manutencao.get_Documento()); + if (manutencao != null && manutencao.get_Tipo() == 2) + { + ConsultaViewModel.FiltrarItens = 4; + } + this.Seleciona(manutencao == null); + if (manutencao == null) + { + return; + } + this.Manutencao = manutencao; + this.MostrarLista = true; + } + + private void AllSelectedChanged() + { + if (this._allSelectedChanging) + { + return; + } + try + { + this._allSelectedChanging = true; + if (this.AllSelected.HasValue) + { + this.ManterTodosText = (this.AllSelected.Value ? string.Concat(this._acaoItens, " ITENS SELECIONADOS") : string.Concat(this._acaoItens, " TODOS OS ITENS")); + foreach (Item iten in this.Itens) + { + iten.set_Selecionado(this.AllSelected.Value); + } + } + } + finally + { + this._allSelectedChanging = false; + } + } + + public async void CancelarItem(Item item) + { + if (item != null) + { + base.Loading(true); + await this._servico.Cancelar(item, string.Format("CANCELADO NO ENDOSSO ORDEM {0}", this.Manutencao.get_Documento().get_Ordem()), this.Manutencao.get_Documento().get_Id()); + base.ToggleSnackBar("ITEM CANCELADO COM SUCESSO", true); + base.Loading(false); + this.RecarregarItens(item); + } + } + + private void EntryOnPropertyChanged(object sender, PropertyChangedEventArgs args) + { + if (args.PropertyName == "Selecionado") + { + this.RecheckAllSelected(); + } + } + + internal async Task> Filtrar(string value) + { + List items = await Task.Run>(() => this.FiltrarItem(value)); + return items; + } + + public List FiltrarItem(string filter) + { + this.ItensFiltrados = (string.IsNullOrWhiteSpace(filter) ? this.Itens : new ObservableCollection( + from x in this.Itens + where ValidationHelper.RemoveDiacritics(x.get_Descricao().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby x.get_Ordem() + select x)); + return this.ItensFiltrados.ToList(); + } + + private async void Load(bool substituir = false, ManutencaoItem manutencao = null) + { + long ramo = this.Ramo; + if (ramo <= (long)38) + { + long num = ramo - (long)1; + if (num <= (long)19) + { + switch ((uint)num) + { + case 0: + case 1: + case 2: + case 14: + case 17: + { + goto Label3; + } + case 3: + case 7: + case 10: + case 11: + case 13: + case 15: + case 16: + case 18: + { + if (this.View == null || !(this.View.GetType() == typeof(RiscosDiversosView))) + { + this.View = new RiscosDiversosView(this, false, substituir, manutencao, null, null, this.EndossoRenovacao); + } + else + { + await ((RiscosDiversosView)this.View).Selecionar(ConsultaViewModel.ItemSelecionado); + if (substituir) + { + ((RiscosDiversosView)this.View).Substituir(); + } + if (manutencao != null) + { + ((RiscosDiversosView)this.View).Manter(manutencao); + } + return; + } + base.IsVisible = Visibility.Visible; + return; + } + case 4: + { + goto Label5; + } + case 5: + case 6: + case 8: + case 9: + { + goto Label0; + } + case 12: + { + if (this.View == null || !(this.View.GetType() == typeof(AeronauticoView))) + { + this.View = new AeronauticoView(this, false, substituir, manutencao, null, null, this.EndossoRenovacao); + base.IsVisible = Visibility.Visible; + return; + } + else + { + await ((AeronauticoView)this.View).Selecionar(ConsultaViewModel.ItemSelecionado); + if (substituir) + { + ((AeronauticoView)this.View).Substituir(); + } + if (manutencao != null) + { + ((AeronauticoView)this.View).Manter(manutencao); + } + return; + } + } + case 19: + { + if (this.View == null || !(this.View.GetType() == typeof(GranizoView))) + { + this.View = new GranizoView(this, false, substituir, manutencao, null, null, this.EndossoRenovacao); + base.IsVisible = Visibility.Visible; + return; + } + else + { + await ((GranizoView)this.View).Selecionar(ConsultaViewModel.ItemSelecionado); + if (substituir) + { + ((GranizoView)this.View).Substituir(); + } + if (manutencao != null) + { + ((GranizoView)this.View).Manter(manutencao); + } + return; + } + } + } + } + else + { + } + if (ramo != (long)30) + { + long num1 = ramo - (long)36; + if (num1 <= (long)2) + { + switch ((uint)num1) + { + case 0: + { + if (this.View == null || !(this.View.GetType() == typeof(ConsorcioView))) + { + this.View = new ConsorcioView(this, false, substituir, manutencao, null, null, this.EndossoRenovacao); + base.IsVisible = Visibility.Visible; + return; + } + else + { + await ((ConsorcioView)this.View).Selecionar(ConsultaViewModel.ItemSelecionado); + if (substituir) + { + ((ConsorcioView)this.View).Substituir(); + } + if (manutencao != null) + { + ((ConsorcioView)this.View).Manter(manutencao); + } + return; + } + } + case 1: + { + goto Label5; + } + case 2: + { + break; + } + default: + { + if (this.View == null || !(this.View.GetType() == typeof(RiscosDiversosView))) + { + this.View = new RiscosDiversosView(this, false, substituir, manutencao, null, null, this.EndossoRenovacao); + } + else + { + await ((RiscosDiversosView)this.View).Selecionar(ConsultaViewModel.ItemSelecionado); + if (substituir) + { + ((RiscosDiversosView)this.View).Substituir(); + } + if (manutencao != null) + { + ((RiscosDiversosView)this.View).Manter(manutencao); + } + return; + } + base.IsVisible = Visibility.Visible; + return; + } + } + } + else + { + if (this.View == null || !(this.View.GetType() == typeof(RiscosDiversosView))) + { + this.View = new RiscosDiversosView(this, false, substituir, manutencao, null, null, this.EndossoRenovacao); + } + else + { + await ((RiscosDiversosView)this.View).Selecionar(ConsultaViewModel.ItemSelecionado); + if (substituir) + { + ((RiscosDiversosView)this.View).Substituir(); + } + if (manutencao != null) + { + ((RiscosDiversosView)this.View).Manter(manutencao); + } + return; + } + base.IsVisible = Visibility.Visible; + return; + } + } + Label3: + if (this.View == null || !(this.View.GetType() == typeof(PatrimonialView))) + { + this.View = new PatrimonialView(this, false, substituir, manutencao, null, null, this.EndossoRenovacao); + base.IsVisible = Visibility.Visible; + return; + } + else + { + await ((PatrimonialView)this.View).Selecionar(ConsultaViewModel.ItemSelecionado); + if (substituir) + { + ((PatrimonialView)this.View).Substituir(); + } + if (manutencao != null) + { + ((PatrimonialView)this.View).Manter(manutencao); + } + return; + } + } + else if (ramo == (long)47 || ramo == (long)53 || ramo == (long)66) + { + goto Label0; + } + if (this.View == null || !(this.View.GetType() == typeof(RiscosDiversosView))) + { + this.View = new RiscosDiversosView(this, false, substituir, manutencao, null, null, this.EndossoRenovacao); + } + else + { + await ((RiscosDiversosView)this.View).Selecionar(ConsultaViewModel.ItemSelecionado); + if (substituir) + { + ((RiscosDiversosView)this.View).Substituir(); + } + if (manutencao != null) + { + ((RiscosDiversosView)this.View).Manter(manutencao); + } + return; + } + base.IsVisible = Visibility.Visible; + return; + Label0: + if (this.View == null || !(this.View.GetType() == typeof(VidaView))) + { + this.View = new VidaView(this, false, substituir, manutencao, null, null, this.EndossoRenovacao); + base.IsVisible = Visibility.Visible; + return; + } + else + { + await ((VidaView)this.View).Selecionar(ConsultaViewModel.ItemSelecionado); + if (substituir) + { + ((VidaView)this.View).Substituir(); + } + if (manutencao != null) + { + ((VidaView)this.View).Manter(manutencao); + } + return; + } + Label5: + if (this.View == null || !(this.View.GetType() == typeof(AutoView))) + { + this.View = new AutoView(this, false, substituir, manutencao, null, null, this.EndossoRenovacao); + base.IsVisible = Visibility.Visible; + return; + } + else + { + await ((AutoView)this.View).Selecionar(ConsultaViewModel.ItemSelecionado); + if (substituir) + { + ((AutoView)this.View).Substituir(); + } + if (manutencao != null) + { + ((AutoView)this.View).Manter(manutencao); + } + return; + } + } + + public void Manter(Item item) + { + Action enableMenu = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu != null) + { + enableMenu(false); + } + else + { + } + ConsultaViewModel.ItemSelecionado = item; + this.Load(false, this.Manutencao); + } + + public async void ManterItens() + { + Item item; + List items; + Item item1; + bool flag; + Item item2; + Action enableMenu = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu != null) + { + enableMenu(false); + } + else + { + } + Action enableMainMenu = Gestor.Application.Actions.Actions.EnableMainMenu; + if (enableMainMenu != null) + { + enableMainMenu(false); + } + else + { + } + base.Loading(true); + int num = 1; + if (this.ManterTodosText == string.Concat(this._acaoItens, " TODOS OS ITENS")) + { + items = new List(this.Itens); + } + else + { + ObservableCollection itens = this.Itens; + items = new List( + from x in itens + where x.get_Selecionado() + select x); + } + Label6: + foreach (Item item3 in items) + { + item = await this._servico.BuscarItemPorIdAsync(item3.get_Id()); + item2 = item; + item1 = item2; + ObservableCollection observableCollection = await this._servico.BuscarCoberturasPorItemAsync(item3.get_Id()); + item1.set_Coberturas(observableCollection); + item1 = null; + flag = false; + item2.set_Id((long)0); + item2.set_Sinistrado(false); + item2.set_Sinistros(null); + item2.set_Documento(ConsultaViewModel.DocumentoSelecionado); + item2.set_Ordem(new int?(num)); + num++; + foreach (Cobertura cobertura in item2.get_Coberturas()) + { + cobertura.set_Id((long)0); + cobertura.set_Item(item2); + } + long ramo = this.Ramo; + if (ramo > (long)36) + { + if (ramo == (long)37) + { + goto Label1; + } + if (ramo == (long)53 || ramo == (long)66) + { + goto Label2; + } + } + else + { + long num1 = ramo - (long)1; + if (num1 <= (long)19) + { + switch ((uint)num1) + { + case 0: + case 1: + case 2: + case 14: + case 17: + { + item1 = item2; + Patrimonial patrimonial = await this._servico.BuscaPatrimonial(item3.get_Id()); + item1.set_Patrimonial(patrimonial); + item1 = null; + item2.get_Patrimonial().set_Item(item2); + item2.get_Patrimonial().set_Id((long)0); + goto Label3; + } + case 3: + case 7: + case 10: + case 11: + case 13: + case 15: + case 16: + case 18: + { + goto Label4; + } + case 4: + { + goto Label1; + } + case 5: + case 6: + case 8: + case 9: + { + goto Label2; + } + case 12: + { + item1 = item2; + Aeronautico aeronautico = await this._servico.BuscaAeronautico(item3.get_Id()); + item1.set_Aeronautico(aeronautico); + item1 = null; + item2.get_Aeronautico().set_Item(item2); + item2.get_Aeronautico().set_Id((long)0); + goto Label3; + } + case 19: + { + item1 = item2; + Granizo granizo = await this._servico.BuscaGranizo(item3.get_Id()); + item1.set_Granizo(granizo); + item1 = null; + item2.get_Granizo().set_Item(item2); + item2.get_Granizo().set_Id((long)0); + goto Label3; + } + } + } + else + { + } + if (ramo != (long)36) + { + goto Label4; + } + item1 = item2; + Consorcio consorcio = await this._servico.BuscaConsorcio(item3.get_Id()); + item1.set_Consorcio(consorcio); + item1 = null; + item2.get_Consorcio().set_Item(item2); + item2.get_Consorcio().set_Id((long)0); + goto Label3; + } + Label4: + item1 = item2; + RiscosDiversos riscosDiverso = await this._servico.BuscaRiscosDiversos(item3.get_Id()); + item1.set_RiscosDiversos(riscosDiverso); + item1 = null; + item2.get_RiscosDiversos().set_Item(item2); + item2.get_RiscosDiversos().set_Id((long)0); + goto Label3; + } + base.Loading(false); + Action action = Gestor.Application.Actions.Actions.EnableMenu; + if (action != null) + { + action(true); + } + else + { + } + Action enableMainMenu1 = Gestor.Application.Actions.Actions.EnableMainMenu; + if (enableMainMenu1 != null) + { + enableMainMenu1(true); + } + else + { + } + if (this.ItensFiltrados.Count != 0) + { + this.AllSelected = new bool?(false); + this.ManterTodosText = string.Concat(this._acaoItens, " TODOS OS ITENS"); + this.SelecionaItem(this.ItensFiltrados.First()); + } + else + { + Action acessaTela = Gestor.Application.Actions.Actions.AcessaTela; + if (acessaTela != null) + { + acessaTela(21, ""); + } + else + { + } + } + return; + Label1: + item1 = item2; + Auto auto = await this._servico.BuscaAuto(item3.get_Id()); + item1.set_Auto(auto); + item1 = null; + item2.get_Auto().set_Item(item2); + item2.get_Auto().set_Id((long)0); + if (item2.get_Auto() != null && item2.get_Auto().get_Placa() == null) + { + await base.ShowMessage(string.Format("ITEM {0} ENCONTRADO SEM PLACA.", item2.get_Ordem()), "OK", "", false); + base.Loading(false); + Action enableMenu1 = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu1 != null) + { + enableMenu1(true); + } + else + { + } + Action action1 = Gestor.Application.Actions.Actions.EnableMainMenu; + if (action1 != null) + { + action1(true); + } + else + { + } + return; + } + Label3: + item2.set_Status(""); + item3.set_Substituido(null); + item = await this._servico.Save(item2); + item2 = item; + if (flag && item2.get_Id() != item3.get_Id()) + { + List titularesVidas = await this._servico.BuscaTitularesVida(item3.get_Id()); + if (titularesVidas.Count > 0) + { + titularesVidas.ForEach((TitularesVida t) => t.set_IdItem(this.itemManter.get_Id())); + await this._servico.SaveTitulares(titularesVidas); + } + } + this.ItensFiltrados.Remove(item3); + this.Itens.Remove(item3); + item3 = null; + goto Label6; + Label2: + item1 = item2; + Vida vida = await this._servico.BuscaVida(item3.get_Id()); + item1.set_Vida(vida); + item1 = null; + item2.get_Vida().set_Item(item2); + item2.get_Vida().set_Id((long)0); + flag = true; + goto Label3; + goto Label4; + } + + public async void Reativar(Item item) + { + if (item != null) + { + base.Loading(true); + await this._servico.Reativar(item, string.Concat("ITEM REATIVADO PELO USUARIO ", Recursos.Usuario.get_Nome())); + base.ToggleSnackBar("ITEM REATIVADO COM SUCESSO", true); + base.Loading(false); + this.RecarregarItens(item); + } + } + + public async void RecarregarItens(Item item) + { + // + // Current member / type: System.Void Gestor.Application.ViewModels.MenuItemViewModel::RecarregarItens(Gestor.Model.Domain.Seguros.Item) + // File path: C:\AggerSeguros\Gestor.Application.exe + // + // Product version: 0.0.0.0 + // Exception in: System.Void RecarregarItens(Gestor.Model.Domain.Seguros.Item) + // + // Object reference not set to an instance of an object. + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.FindLowestCommonAncestor(ICollection`1 typeNodes) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 515 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.MergeWithLowestCommonAncestor() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 459 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.ProcessSingleConstraints() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 378 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.InferTypes() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 331 + // at Telerik.JustDecompiler.Decompiler.ExpressionDecompilerStep.Process(DecompilationContext theContext, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\ExpressionDecompilerStep.cs:line 104 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.Extensions.DecompileStateMachine(MethodBody body, DecompilationContext enclosingContext, BaseStateMachineRemoverStep removeStateMachineStep, Func`2 stateMachineDataSelector, DecompilationContext& decompilationContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 104 + // at Telerik.JustDecompiler.Decompiler.Extensions.DecompileAsyncStateMachine(MethodBody body, DecompilationContext enclosingContext, AsyncData& asyncData) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 150 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.GetMoveNextStatements() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 155 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.Match() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 76 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.Process(DecompilationContext context, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 36 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61 + // at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 133 + // + // mailto: JustDecompilePublicFeedback@telerik.com + + } + + private void RecheckAllSelected() + { + if (this._allSelectedChanging) + { + return; + } + try + { + this._allSelectedChanging = true; + if (this.Itens.All((Item e) => e.get_Selecionado())) + { + this.AllSelected = new bool?(true); + this.ManterTodosText = string.Concat(this._acaoItens, " ITENS SELECIONADOS"); + } + else if (!this.Itens.All((Item e) => !e.get_Selecionado())) + { + this.AllSelected = null; + this.ManterTodosText = string.Concat(this._acaoItens, " ITENS SELECIONADOS"); + } + else + { + this.AllSelected = new bool?(false); + this.ManterTodosText = string.Concat(this._acaoItens, " TODOS OS ITENS"); + } + } + finally + { + this._allSelectedChanging = false; + } + } + + public async void Seleciona(bool item = true) + { + if (!item || ConsultaViewModel.ItemSelecionado != null) + { + await this.SelecionaItens(ConsultaViewModel.FiltrarItens, ConsultaViewModel.ItemSelecionado); + } + else + { + this.Load(false, null); + } + } + + public void SelecionaItem(Item item) + { + if (this.Carregando) + { + return; + } + this.AlterandoSelectedItem = true; + this.SelectedItem = item; + ConsultaViewModel.ItemSelecionado = this.SelectedItem; + this.AlterandoSelectedItem = false; + } + + public async Task SelecionaItens(int type, Item item = null) + { + bool count; + Item item1; + base.Loading(true); + this.Carregando = true; + switch (type) + { + case 1: + case 2: + { + this.Itens = await this._servico.BuscarItens(this._documentoSelecionado.get_Id(), 2); + break; + } + case 3: + { + this.Itens = await this._servico.BuscarItens(this._documentoSelecionado.get_Controle().get_Id(), 1); + break; + } + case 4: + { + this.Itens = await this._servico.BuscarItens(this._documentoSelecionado.get_Controle().get_Id(), 3); + break; + } + default: + { + this.Itens = await this._servico.BuscarItens(this._documentoSelecionado.get_Controle().get_Id(), 0); + break; + } + } + this.ItensFiltrados = this.Itens; + if (item != null && item.get_Id() > (long)0) + { + this.AlterandoSelectedItem = true; + MenuItemViewModel menuItemViewModel = this; + if (this.ItensFiltrados == null || this.ItensFiltrados.Count <= 0) + { + item1 = null; + } + else + { + item1 = this.ItensFiltrados.FirstOrDefault((Item x) => x.get_Id() == item.get_Id()); + } + menuItemViewModel.SelectedItem = item1; + Action scrollToItem = Gestor.Application.Actions.Actions.ScrollToItem; + if (scrollToItem != null) + { + scrollToItem(); + } + else + { + } + this.AlterandoSelectedItem = false; + } + MenuItemViewModel menuItemViewModel1 = this; + if (this.MostrarLista) + { + count = true; + } + else + { + ObservableCollection itens = this.Itens; + if (itens != null) + { + count = itens.Count > 1; + } + else + { + count = false; + } + } + menuItemViewModel1.MostrarLista = count; + this.Carregando = false; + base.Loading(false); + } + + public void Substituir(Item item) + { + Action enableMenu = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu != null) + { + enableMenu(false); + } + else + { + } + ConsultaViewModel.ItemSelecionado = item; + this.Load(true, null); + } + + private void WorkOnSelectedItem(Item value) + { + ConsultaViewModel.ItemSelecionado = value; + this.Load(false, null); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Relatorios/DialogPrintViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Relatorios/DialogPrintViewModel.cs new file mode 100644 index 0000000..537bed2 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Relatorios/DialogPrintViewModel.cs @@ -0,0 +1,193 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Configuracoes; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Relatorios; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Relatorios +{ + public class DialogPrintViewModel : BaseViewModel + { + private bool _carregando; + + private ConfiguracaoImpressao _configuracoes; + + private List _tamanhos = new List() + { + "GRANDE", + "MÉDIO", + "PEQUENO" + }; + + private bool _orientacaoImpressaoPortrait; + + private bool _orientacaoImpressaoLandscape; + + private string _tamanhoFonte = "PEQUENO"; + + private Relatorio _relatorio + { + get; + set; + } + + private Type _tipo + { + get; + set; + } + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.OnPropertyChanged("Carregando"); + } + } + + public ConfiguracaoImpressao Configuracoes + { + get + { + return this._configuracoes; + } + set + { + this._configuracoes = value; + base.OnPropertyChanged("Configuracoes"); + } + } + + public bool OrientacaoImpressao + { + get; + set; + } + + public bool OrientacaoImpressaoLandscape + { + get + { + return this._orientacaoImpressaoLandscape; + } + set + { + this._orientacaoImpressaoLandscape = value; + base.OnPropertyChanged("OrientacaoImpressaoLandscape"); + } + } + + public bool OrientacaoImpressaoPortrait + { + get + { + return this._orientacaoImpressaoPortrait; + } + set + { + this._orientacaoImpressaoPortrait = value; + base.OnPropertyChanged("OrientacaoImpressaoPortrait"); + } + } + + public string TamanhoFonte + { + get + { + return this._tamanhoFonte; + } + set + { + this._tamanhoFonte = value; + if (value == "MÉDIO") + { + this.Configuracoes.set_TamanhoFonte(6); + } + else if (value == "GRANDE") + { + this.Configuracoes.set_TamanhoFonte(5); + } + else + { + this.Configuracoes.set_TamanhoFonte(7); + } + base.OnPropertyChanged("TamanhoFonte"); + } + } + + public List Tamanhos + { + get + { + return this._tamanhos; + } + set + { + this._tamanhos = value; + base.OnPropertyChanged("Tamanhos"); + } + } + + public DialogPrintViewModel(Relatorio relatorio, Type tipo) + { + this._relatorio = relatorio; + this._tipo = tipo; + } + + public async Task Carregar() + { + List list = await (new ConfuguracoesServico()).BuscarParametros(this._relatorio); + if (list == null || list.Count == 0) + { + list = this._tipo.GetProperties(BindingFlags.Instance | BindingFlags.Public).Select((PropertyInfo x) => { + ParametrosRelatorio parametrosRelatorio = new ParametrosRelatorio(); + parametrosRelatorio.set_Campo(x.Name); + parametrosRelatorio.set_Header(x.GetDescriptionAttribute()); + parametrosRelatorio.set_Tipo(x.GetTypeAttribute()); + parametrosRelatorio.set_Relatorio(this._relatorio); + parametrosRelatorio.set_Width(0); + parametrosRelatorio.set_Ordem(0); + return parametrosRelatorio; + }).ToList(); + } + List parametrosRelatorios = list; + parametrosRelatorios.ForEach((ParametrosRelatorio x) => x.set_Selecionado(true)); + ConfiguracaoImpressao configuracaoImpressao = new ConfiguracaoImpressao(); + configuracaoImpressao.set_TamanhoFonte(7); + configuracaoImpressao.set_Campos(list); + configuracaoImpressao.set_OrientacaoImpressao(new bool?(false)); + this.Configuracoes = configuracaoImpressao; + } + + public void Selecionar() + { + if (this.Carregando) + { + return; + } + ConfiguracaoImpressao configuracoes = this.Configuracoes; + if (configuracoes == null) + { + return; + } + List campos = configuracoes.get_Campos(); + if (campos == null) + { + return; + } + campos.ForEach((ParametrosRelatorio x) => x.set_Selecionado(!x.get_Selecionado())); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Relatorios/RelatorioViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Relatorios/RelatorioViewModel.cs new file mode 100644 index 0000000..f85b039 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Relatorios/RelatorioViewModel.cs @@ -0,0 +1,14619 @@ +using Agger.Registro; +using ClosedXML.Excel; +using CsQuery.ExtensionMethods; +using Gestor.Application.Actions; +using Gestor.Application.Componentes; +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Configuracoes; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.BI; +using Gestor.Application.Views.Ferramentas; +using Gestor.Application.Views.Generic; +using Gestor.Application.Views.Relatorios; +using Gestor.Common.Converters; +using Gestor.Common.Helpers; +using Gestor.Common.Validation; +using Gestor.Model.API; +using Gestor.Model.Common; +using Gestor.Model.Domain.Aggilizador; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.MalaDireta; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Relatorios.ApolicePendente; +using Gestor.Model.Domain.Relatorios.Auditoria; +using Gestor.Model.Domain.Relatorios.Classificacao; +using Gestor.Model.Domain.Relatorios.Cliente; +using Gestor.Model.Domain.Relatorios.ClientesAtivosInativos; +using Gestor.Model.Domain.Relatorios.Comissao; +using Gestor.Model.Domain.Relatorios.CriticaApolice; +using Gestor.Model.Domain.Relatorios.EndossoCancelamento; +using Gestor.Model.Domain.Relatorios.ExtratoBaixado; +using Gestor.Model.Domain.Relatorios.FaturaPendente; +using Gestor.Model.Domain.Relatorios.Fechamento; +using Gestor.Model.Domain.Relatorios.Licenciamento; +using Gestor.Model.Domain.Relatorios.Log; +using Gestor.Model.Domain.Relatorios.LogsEnvio; +using Gestor.Model.Domain.Relatorios.MetaSeguradora; +using Gestor.Model.Domain.Relatorios.MetaVendedor; +using Gestor.Model.Domain.Relatorios.NotaFiscal; +using Gestor.Model.Domain.Relatorios.Pagamento; +using Gestor.Model.Domain.Relatorios.Pendente; +using Gestor.Model.Domain.Relatorios.Placa; +using Gestor.Model.Domain.Relatorios.PrevisaoPagamentoComissao; +using Gestor.Model.Domain.Relatorios.Producao; +using Gestor.Model.Domain.Relatorios.Renovacao; +using Gestor.Model.Domain.Relatorios.Sinistro; +using Gestor.Model.Domain.Relatorios.Tarefa; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.License; +using MaterialDesignThemes.Wpf; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Forms; +using System.Windows.Threading; + +namespace Gestor.Application.ViewModels.Relatorios +{ + public class RelatorioViewModel : BaseSegurosViewModel + { + private bool _alterandoFiltros; + + private readonly ApoliceServico _apoliceServico; + + private readonly ParcelaServico _parcelaServico; + + private readonly SinistroServico _sinistroServico; + + private readonly ClienteServico _clienteServico; + + private readonly LogServico _logServico; + + private readonly CriticaApoliceServico _criticaServico; + + private readonly ServicoExtrato _extratoServico; + + private readonly MetaSeguradoraServico _metaSeguradoraServico; + + private readonly MetaVendedorServico _metaVendedorServico; + + private readonly NotaFiscalServico _notaFiscalServico; + + private readonly Func funcProducaoDistinctByDocumentoId = new Func((Gestor.Model.Domain.Relatorios.Producao.Producao p) => p.get_Documento().get_Id()); + + private readonly Func funcProducaoSegurosNovos = new Func((Gestor.Model.Domain.Relatorios.Producao.Producao p) => p.get_Documento().get_Situacao() == 1); + + private readonly Func funcProducaoSegurosRenovacao = new Func((Gestor.Model.Domain.Relatorios.Producao.Producao p) => p.get_Documento().get_Situacao() == 2); + + private readonly Func funcProducaoNegociosNovos = new Func((Gestor.Model.Domain.Relatorios.Producao.Producao p) => { + NegocioCorretora? negocioCorretora = p.get_Documento().get_NegocioCorretora(); + return negocioCorretora.GetValueOrDefault() == 0 & negocioCorretora.HasValue; + }); + + private readonly Func funcProducaoNegociosProprios = new Func((Gestor.Model.Domain.Relatorios.Producao.Producao p) => p.get_Documento().get_NegocioCorretora().GetValueOrDefault() == 1); + + private bool _totalizacao = true; + + private bool _enableEmpresa; + + private bool _apelido; + + private List _empresas; + + private Gestor.Model.Domain.Common.Empresa _empresa; + + private bool? _allSelectedSeguradora; + + private bool? _allSelectedRamo; + + private bool? _allSelectedVendedor; + + private bool? _allSelectedTipoVendedor; + + private bool? _allSelectedStatus; + + private bool? _allSelectedNegocio; + + private bool? _allSelectedEstipulante; + + private bool? _allSelectedProduto; + + private bool _allSelectedChanging; + + private string _filtro; + + private bool _visibilityHtml; + + private bool _relatorioVisibility; + + private string _htmlContent; + + private List _relatorios = new List(); + + private Gestor.Model.Common.Relatorio _relatorio = 2; + + private bool _extratosEnabled; + + private Visibility _planilhaVisibility; + + private object _report; + + private bool _permitirFiltrosPersonalizados; + + private Visibility _filtrosPersonalizados = Visibility.Collapsed; + + private bool _somenteNaoPagos; + + private bool _visibilityDesconsiderarNegativos = Recursos.Configuracoes.Any(new Func((ConfiguracaoSistema x) => x.get_Configuracao() == 50)); + + private bool _desconsiderarNegativos; + + private bool _segundaViaReciboPagamento; + + private bool _documentosEmitidos; + + private bool _sinteticosPagamento; + + private bool _visibilityUsuarios; + + private Visibility _visibilityDocumentoAtivo; + + private Visibility _visibilityReferencia = Visibility.Collapsed; + + private Visibility _visibilityOrdem = Visibility.Collapsed; + + private string _referencia; + + private ObservableCollection _referencias = new ObservableCollection(); + + private ObservableCollection _ordens = new ObservableCollection(); + + private string _ordemSelecionada; + + private DateTime _inicio = Funcoes.GetNetworkTime().Date.AddMonths(-1); + + private DateTime _fim = Funcoes.GetNetworkTime().Date; + + private int _inicioValor; + + private int _fimValor; + + private Gestor.Model.Common.Agrupamento _agrupamento; + + private List _producao; + + private List _licenciamento; + + private List _placas; + + private List _tarefa; + + private List _endosso; + + private List _classificacao; + + private ObservableCollection _licenciamentoFiltrado; + + private ObservableCollection _placaFiltrado; + + private ObservableCollection _tarefaFiltrado; + + private List _renovacao; + + private List _faturaPendente; + + private ObservableCollection _faturaPendenteFiltrado; + + private List _sinistro; + + private List _comissao; + + private List _pendente; + + private List _pagamentos; + + private List _pagamentosSintetico; + + private List _clientesAtivosInativos; + + private List _logsEnvio; + + private ObservableCollection _apoliceCriticaFiltrado; + + private ObservableCollection _logUtilizacaoFiltrado; + + private ObservableCollection _fechamento; + + private ObservableCollection _previsao; + + private ObservableCollection _previsaoSintetico; + + private List _auditoria; + + private ObservableCollection _auditoriaFiltrado; + + private List _apolicePendente; + + private List _extratos; + + private ObservableCollection _apolicePendenteFiltrado; + + private ObservableCollection _extratosFiltrado; + + private List _metaSeguradora; + + private List _metaVendedor; + + private ObservableCollection _metaSeguradoraFiltrado; + + private ObservableCollection _metaVendedorFiltrado; + + private ObservableCollection _producaoFiltrado; + + private ObservableCollection _endossoFiltrado; + + private ObservableCollection _notaFiscalFiltrado; + + private ObservableCollection _renovacaoFiltrado; + + private ObservableCollection _sinistroFiltrado; + + private ObservableCollection _comissaoFiltrado; + + private ObservableCollection _pendenteFiltrado; + + private ObservableCollection _clientesAtivosInativosFiltrado; + + private ObservableCollection _classificacaoFiltrado; + + private ObservableCollection _logsEnvioFiltrado; + + private ObservableCollection _fechamentoFiltrado; + + private ObservableCollection _previsaoFiltrado; + + private bool _totais; + + private ObservableCollection _sinteticoRelatorio; + + private SinteticoClientes _sinteticoCliente; + + private ObservableCollection _sintetic; + + private bool _comparativo; + + private bool _completo; + + private bool _notaFiscalPorSeguradora; + + private Mes _selectedMes; + + private int _selectedAno; + + private Visibility _infoVisibility = Visibility.Collapsed; + + private string _info; + + private string _erroRelatorio = "NÃO HÁ DADOS NO PERÍODO E FILTROS SELECIONADOS."; + + private bool _carregando; + + private bool _documentosAtivos; + + private List _seguradoras = Recursos.Seguradoras.Where(new Func((Seguradora x) => x.get_Ativo())).OrderBy(new Func((Seguradora x) => x.get_Nome())).ToList(); + + private List _ramos = Recursos.Ramos.Where(new Func((Ramo x) => x.get_Ativo())).OrderBy(new Func((Ramo x) => x.get_Nome())).ToList(); + + private List _notasFiscais = new List(); + + private bool _inativo = true; + + private List _vendedores = new List(); + + private List _tipoVendedor = Recursos.TipoVendedor.Where(new Func((Gestor.Model.Domain.Seguros.TipoVendedor x) => x.get_Ativo().GetValueOrDefault())).OrderBy(new Func((Gestor.Model.Domain.Seguros.TipoVendedor x) => x.get_Descricao())).ToList(); + + private List _produtos = Recursos.Produtos.Where(new Func((Gestor.Model.Domain.Seguros.Produto x) => x.get_Ativo())).OrderBy(new Func((Gestor.Model.Domain.Seguros.Produto x) => x.get_Nome())).ToList(); + + private List _estipulantes = Recursos.Estipulantes.Where(new Func((Estipulante x) => { + if (Recursos.Usuario.get_IdEmpresa() != (long)1 && Recursos.Usuario.get_IdEmpresa() != x.get_IdEmpresa()) + { + return false; + } + return x.get_Ativo(); + })).OrderBy(new Func((Estipulante x) => x.get_Nome())).ToList(); + + private readonly static List NegocioList; + + private List _negocios = RelatorioViewModel.NegocioList; + + private readonly static List TipoSegurosList; + + private List _tipoSeguros = RelatorioViewModel.TipoSegurosList; + + private bool _isVisibleGrid1 = true; + + private bool _isVisibleGrid2 = true; + + private bool _isVisibleGrid3 = true; + + private bool _isVisibleGrid4 = true; + + private List _filtroRelatorioPersonalizado; + + private Gestor.Model.Domain.Relatorios.FiltroPersonalizado _filtroPersonalizado; + + private Type _tipoString = typeof(string); + + private Type _tipoEnum = typeof(Enum); + + private Type _tipoDateTime = typeof(DateTime); + + private Type _tipoDecimal = typeof(decimal); + + private Type _tipoInt = typeof(int); + + private Type _tipoLong = typeof(long); + + private ObservableCollection _ramosSelecionados; + + private bool _novosNegocios; + + private Ramo _ramoSelecionado; + + private string _valorIncial = ""; + + private string _valorFinal = ""; + + private bool _semValor; + + private bool _valorIgual; + + private Visibility _visibilitySemValor = Visibility.Collapsed; + + private Visibility _visibilityOpcoesFiltros = Visibility.Collapsed; + + private ObservableCollection _filtroPersonalizadoSelecionado; + + private ObservableCollection _filtroRelatorioSelecionado = new ObservableCollection(); + + private Visibility _visibilityFiltros; + + private Visibility _visibilityEtiqueta; + + private Visibility _visibiltyProtocolo; + + private Visibility _visibiltySincronizar; + + private Visibility _visibilityEmail; + + private Visibility _visibilityApolice; + + private Visibility _visibilityExtratos; + + private Visibility _visibilityData; + + private Visibility _visibilityMeta; + + private Visibility _visibilityMaisFiltros; + + private Visibility _visibilityGridFiltros; + + private Visibility _visibilityAgrupamento; + + private Visibility _visibilityOlho; + + private Visibility _visibilityEspecial; + + private Visibility _visibilityComparativo; + + private Visibility _visibilityCompleto; + + private Visibility _visibilityNotaFiscalPorSeguradora; + + private Visibility _visibilityPagamento; + + private Visibility _visibilitySintetizar; + + private Visibility _visibilityConfigurar; + + private Visibility _visibilityFiltroPersonalizadoButton; + + private Visibility _visibilityTarefas; + + private Visibility _visibilityAcompanhamento; + + private Visibility _visibilityValor; + + private Visibility _visibilityFiltroPersonalizado = Visibility.Collapsed; + + private string _head; + + private List _parcelasEspeciais; + + private ObservableCollection _ajuda; + + private bool _carregandoAjuda; + + private ObservableCollection _parametrosRelatorio; + + private ObservableCollection _parametrosRelatorioAdicionados; + + private ObservableCollection _parametrosTotalizacao; + + private ObservableCollection _parametrosTotalizacaoAdicionados; + + private bool _isCampo; + + private Gestor.Model.Domain.Relatorios.ParametrosRelatorio _selectedParametrosRelatorio; + + private Gestor.Model.Domain.Relatorios.ParametrosTotalizacao _selectedParametrosTotalizacao; + + private ObservableCollection _usuariosFiltrados; + + public Gestor.Model.Common.Agrupamento Agrupamento + { + get + { + return this._agrupamento; + } + set + { + this._agrupamento = value; + base.OnPropertyChanged("Agrupamento"); + } + } + + public ObservableCollection Ajuda + { + get + { + return this._ajuda; + } + set + { + this._ajuda = value; + base.OnPropertyChanged("Ajuda"); + } + } + + public bool? AllSelectedEstipulante + { + get + { + return this._allSelectedEstipulante; + } + set + { + bool? nullable = value; + bool? nullable1 = this._allSelectedEstipulante; + if (nullable.GetValueOrDefault() == nullable1.GetValueOrDefault() & nullable.HasValue == nullable1.HasValue) + { + return; + } + this._allSelectedEstipulante = value; + this.AllSelectedChanged(7); + this.Estipulantes = new List(this.Estipulantes); + base.OnPropertyChanged("AllSelectedEstipulante"); + } + } + + public bool? AllSelectedNegocio + { + get + { + return this._allSelectedNegocio; + } + set + { + bool? nullable = value; + bool? nullable1 = this._allSelectedNegocio; + if (nullable.GetValueOrDefault() == nullable1.GetValueOrDefault() & nullable.HasValue == nullable1.HasValue) + { + return; + } + this._allSelectedNegocio = value; + this.AllSelectedChanged(5); + this.Negocios = new List(this.Negocios); + base.OnPropertyChanged("AllSelectedNegocio"); + } + } + + public bool? AllSelectedProduto + { + get + { + return this._allSelectedProduto; + } + set + { + bool? nullable = value; + bool? nullable1 = this._allSelectedProduto; + if (nullable.GetValueOrDefault() == nullable1.GetValueOrDefault() & nullable.HasValue == nullable1.HasValue) + { + return; + } + this._allSelectedProduto = value; + this.AllSelectedChanged(6); + this.Produtos = new List(this.Produtos); + base.OnPropertyChanged("AllSelectedProduto"); + } + } + + public bool? AllSelectedRamo + { + get + { + return this._allSelectedRamo; + } + set + { + bool? nullable = value; + bool? nullable1 = this._allSelectedRamo; + if (nullable.GetValueOrDefault() == nullable1.GetValueOrDefault() & nullable.HasValue == nullable1.HasValue) + { + return; + } + this._allSelectedRamo = value; + this.AllSelectedChanged(1); + this.Ramos = new List(this.Ramos); + base.OnPropertyChanged("AllSelectedRamo"); + } + } + + public bool? AllSelectedSeguradora + { + get + { + return this._allSelectedSeguradora; + } + set + { + bool? nullable = value; + bool? nullable1 = this._allSelectedSeguradora; + if (nullable.GetValueOrDefault() == nullable1.GetValueOrDefault() & nullable.HasValue == nullable1.HasValue) + { + return; + } + this._allSelectedSeguradora = value; + this.AllSelectedChanged(0); + this.Seguradoras = new List(this.Seguradoras); + base.OnPropertyChanged("AllSelectedSeguradora"); + } + } + + public bool? AllSelectedStatus + { + get + { + return this._allSelectedStatus; + } + set + { + bool? nullable = value; + bool? nullable1 = this._allSelectedStatus; + if (nullable.GetValueOrDefault() == nullable1.GetValueOrDefault() & nullable.HasValue == nullable1.HasValue) + { + return; + } + this._allSelectedStatus = value; + this.AllSelectedChanged(3); + this.TipoSeguros = new List(this.TipoSeguros); + base.OnPropertyChanged("AllSelectedStatus"); + } + } + + public bool? AllSelectedTipoVendedor + { + get + { + return this._allSelectedTipoVendedor; + } + set + { + bool? nullable = value; + bool? nullable1 = this._allSelectedTipoVendedor; + if (nullable.GetValueOrDefault() == nullable1.GetValueOrDefault() & nullable.HasValue == nullable1.HasValue) + { + return; + } + this._allSelectedTipoVendedor = value; + this.AllSelectedChanged(4); + this.TipoVendedor = new List(this.TipoVendedor); + base.OnPropertyChanged("AllSelectedTipoVendedor"); + } + } + + public bool? AllSelectedVendedor + { + get + { + return this._allSelectedVendedor; + } + set + { + bool? nullable = value; + bool? nullable1 = this._allSelectedVendedor; + if (nullable.GetValueOrDefault() == nullable1.GetValueOrDefault() & nullable.HasValue == nullable1.HasValue) + { + return; + } + this._allSelectedVendedor = value; + this.AllSelectedChanged(2); + this.Vendedores = new List(this.Vendedores); + base.OnPropertyChanged("AllSelectedVendedor"); + } + } + + public bool Apelido + { + get + { + return this._apelido; + } + set + { + this._apelido = value; + base.OnPropertyChanged("Apelido"); + } + } + + public List ApoliceCritica + { + get; + set; + } + + public ObservableCollection ApoliceCriticaFiltrado + { + get + { + return this._apoliceCriticaFiltrado; + } + set + { + this._apoliceCriticaFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("ApoliceCriticaFiltrado"); + } + } + + public List ApolicePendente + { + get + { + return this._apolicePendente; + } + set + { + this._apolicePendente = value; + base.OnPropertyChanged("ApolicePendente"); + } + } + + public ObservableCollection ApolicePendenteFiltrado + { + get + { + return this._apolicePendenteFiltrado; + } + set + { + this._apolicePendenteFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("ApolicePendenteFiltrado"); + } + } + + public List Auditoria + { + get + { + return this._auditoria; + } + set + { + this._auditoria = value; + base.OnPropertyChanged("Auditoria"); + } + } + + public ObservableCollection AuditoriaFiltrado + { + get + { + return this._auditoriaFiltrado; + } + set + { + this._auditoriaFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("AuditoriaFiltrado"); + } + } + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.OnPropertyChanged("Carregando"); + } + } + + public bool CarregandoAjuda + { + get + { + return this._carregandoAjuda; + } + set + { + this._carregandoAjuda = value; + base.OnPropertyChanged("CarregandoAjuda"); + } + } + + public List Classificacao + { + get + { + return this._classificacao; + } + set + { + this._classificacao = value; + base.OnPropertyChanged("Classificacao"); + } + } + + public ObservableCollection ClassificacaoFiltrado + { + get + { + return this._classificacaoFiltrado; + } + set + { + this._classificacaoFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("ClassificacaoFiltrado"); + } + } + + public List ClientesAtivosInativos + { + get + { + return this._clientesAtivosInativos; + } + set + { + this._clientesAtivosInativos = value; + SinteticoClientes sinteticoCliente = new SinteticoClientes(); + sinteticoCliente.set_Total((value != null ? value.Count : 0)); + this.SinteticoCliente = sinteticoCliente; + base.OnPropertyChanged("ClientesAtivosInativos"); + } + } + + public ObservableCollection ClientesAtivosInativosFiltrado + { + get + { + return this._clientesAtivosInativosFiltrado; + } + set + { + this._clientesAtivosInativosFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("ClientesAtivosInativosFiltrado"); + } + } + + public List ColunasOcultas { get; set; } = new List(); + + public List Comissao + { + get + { + return this._comissao; + } + set + { + this._comissao = value; + base.OnPropertyChanged("Comissao"); + } + } + + public ObservableCollection ComissaoFiltrado + { + get + { + return this._comissaoFiltrado; + } + set + { + this._comissaoFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("ComissaoFiltrado"); + } + } + + public bool Comparativo + { + get + { + return this._comparativo; + } + set + { + this._comparativo = value; + base.OnPropertyChanged("Comparativo"); + } + } + + public bool Completo + { + get + { + return this._completo; + } + set + { + this._completo = value; + base.OnPropertyChanged("Completo"); + } + } + + public bool DesconsiderarNegativos + { + get + { + return this._desconsiderarNegativos; + } + set + { + this.LimparRelatorio(); + this._desconsiderarNegativos = value; + base.OnPropertyChanged("DesconsiderarNegativos"); + } + } + + public bool DocumentosAtivos + { + get + { + return this._documentosAtivos; + } + set + { + this._documentosAtivos = value; + base.OnPropertyChanged("DocumentosAtivos"); + } + } + + public bool DocumentosEmitidos + { + get + { + return this._documentosEmitidos; + } + set + { + this.LimparRelatorio(); + this._documentosEmitidos = value; + base.OnPropertyChanged("DocumentosEmitidos"); + } + } + + public static DrawerHost Drawer + { + get; + set; + } + + public Gestor.Model.Domain.Common.Empresa Empresa + { + get + { + return this._empresa; + } + set + { + this._empresa = value; + base.OnPropertyChanged("Empresa"); + } + } + + public List Empresas + { + get + { + return this._empresas; + } + set + { + this._empresas = value; + base.OnPropertyChanged("Empresas"); + } + } + + public bool EnableEmpresa + { + get + { + return this._enableEmpresa; + } + set + { + this._enableEmpresa = value; + base.OnPropertyChanged("EnableEmpresa"); + } + } + + public ObservableCollection EndossoFiltrado + { + get + { + return this._endossoFiltrado; + } + set + { + this._endossoFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("EndossoFiltrado"); + } + } + + public List Endossoo + { + get + { + return this._endosso; + } + set + { + this._endosso = value; + base.OnPropertyChanged("Endossoo"); + } + } + + public string ErroRelatorio + { + get + { + return this._erroRelatorio; + } + set + { + this._erroRelatorio = value; + base.OnPropertyChanged("ErroRelatorio"); + } + } + + public List Estipulantes + { + get + { + return this._estipulantes; + } + set + { + this._estipulantes = value; + foreach (Estipulante estipulante in this.Estipulantes) + { + estipulante.add_PropertyChanged(new PropertyChangedEventHandler(this.EstipulanteOnPropertyChanged)); + } + base.OnPropertyChanged("Estipulantes"); + } + } + + public List Extratos + { + get + { + return this._extratos; + } + set + { + this._extratos = value; + base.OnPropertyChanged("Extratos"); + } + } + + public bool ExtratosEnabled + { + get + { + return this._extratosEnabled; + } + set + { + this._extratosEnabled = value; + base.OnPropertyChanged("ExtratosEnabled"); + } + } + + public ObservableCollection ExtratosFiltrado + { + get + { + return this._extratosFiltrado; + } + set + { + this._extratosFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("ExtratosFiltrado"); + } + } + + public List FaturaPendente + { + get + { + return this._faturaPendente; + } + set + { + this._faturaPendente = value; + base.OnPropertyChanged("FaturaPendente"); + } + } + + public ObservableCollection FaturaPendenteFiltrado + { + get + { + return this._faturaPendenteFiltrado; + } + set + { + this._faturaPendenteFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("FaturaPendenteFiltrado"); + } + } + + public ObservableCollection Fechamento + { + get + { + return this._fechamento; + } + set + { + this._fechamento = value; + this.Sintetic = null; + base.OnPropertyChanged("Fechamento"); + } + } + + public ObservableCollection FechamentoFiltrado + { + get + { + return this._fechamentoFiltrado; + } + set + { + this._fechamentoFiltrado = value; + this.SintetizarRelatorio(); + this.Sintetic = null; + base.OnPropertyChanged("FechamentoFiltrado"); + } + } + + public string Filtro + { + get + { + return this._filtro; + } + set + { + this._filtro = value; + this.Filtrar(); + base.OnPropertyChanged("Filtro"); + } + } + + public Gestor.Model.Domain.Relatorios.FiltroPersonalizado FiltroPersonalizado + { + get + { + return this._filtroPersonalizado; + } + set + { + char chr; + this._filtroPersonalizado = value; + this.VisibilitySemValor = (value != null ? Visibility.Visible : Visibility.Collapsed); + this.VisibilityOpcoesFiltros = Visibility.Collapsed; + base.OnPropertyChanged("FiltroPersonalizado"); + if (value == null) + { + return; + } + string name = value.get_Tipo().Name; + if (name != null) + { + switch (name.Length) + { + case 3: + { + if (name == "int") + { + break; + } + return; + } + case 4: + { + chr = name[0]; + if (chr == 'E') + { + if (name == "Enum") + { + this.ValorInicial = null; + this.ValorFinal = null; + return; + } + return; + } + else + { + if (chr != 'l') + { + return; + } + if (name == "long") + { + break; + } + return; + } + } + case 5: + { + chr = name[3]; + if (chr == '3') + { + if (name == "int32") + { + break; + } + return; + } + else + { + if (chr != '6') + { + return; + } + if (name == "int64") + { + break; + } + return; + } + } + case 6: + { + if (name != "String") + { + return; + } + this.ValorInicial = ""; + this.ValorFinal = ""; + this.VisibilityOpcoesFiltros = (value != null ? Visibility.Visible : Visibility.Collapsed); + return; + } + case 7: + { + if (name != "Decimal") + { + return; + } + this.ValorInicial = "0,00"; + this.ValorFinal = "0,00"; + return; + } + case 8: + { + if (name == "DateTime") + { + this.ValorInicial = null; + this.ValorFinal = null; + return; + } + return; + } + default: + { + return; + } + } + this.ValorInicial = "0"; + this.ValorFinal = "0"; + } + } + } + + public ObservableCollection FiltroPersonalizadoSelecionado + { + get + { + return this._filtroPersonalizadoSelecionado; + } + set + { + this._filtroPersonalizadoSelecionado = value; + base.OnPropertyChanged("FiltroPersonalizadoSelecionado"); + } + } + + public ObservableCollection FiltroRelatorioSelecionado + { + get + { + return this._filtroRelatorioSelecionado; + } + set + { + this._filtroRelatorioSelecionado = value; + base.OnPropertyChanged("FiltroRelatorioSelecionado"); + } + } + + public Gestor.Model.Domain.Relatorios.Filtros Filtros + { + get; + set; + } + + public Visibility FiltrosPersonalizados + { + get + { + return this._filtrosPersonalizados; + } + set + { + this._filtrosPersonalizados = value; + base.OnPropertyChanged("FiltrosPersonalizados"); + } + } + + public DateTime Fim + { + get + { + return this._fim; + } + set + { + if (value < new DateTime(1754, 1, 1)) + { + value = new DateTime(1754, 1, 1); + } + if (value > new DateTime(9999, 12, 31)) + { + value = new DateTime(9999, 12, 31); + } + this._fim = value; + base.OnPropertyChanged("Fim"); + } + } + + public int FimValor + { + get + { + return this._fimValor; + } + set + { + this._fimValor = value; + base.OnPropertyChanged("FimValor"); + } + } + + public string Head + { + get + { + return this._head; + } + set + { + this._head = value; + base.OnPropertyChanged("Head"); + } + } + + public string HtmlContent + { + get + { + return this._htmlContent; + } + set + { + this._htmlContent = value; + base.OnPropertyChanged("HtmlContent"); + } + } + + public bool Inativo + { + get + { + return this._inativo; + } + set + { + this._inativo = value; + this.ReloadVendedores(); + base.OnPropertyChanged("Inativo"); + } + } + + public string Info + { + get + { + return this._info; + } + set + { + this._info = value; + base.OnPropertyChanged("Info"); + } + } + + public Visibility InfoVisibility + { + get + { + return this._infoVisibility; + } + set + { + this._infoVisibility = value; + base.OnPropertyChanged("InfoVisibility"); + } + } + + public DateTime Inicio + { + get + { + return this._inicio; + } + set + { + if (value < new DateTime(1754, 1, 1)) + { + value = new DateTime(1754, 1, 1); + } + if (value > new DateTime(9999, 12, 31)) + { + value = new DateTime(9999, 12, 31); + } + this._inicio = value; + base.OnPropertyChanged("Inicio"); + } + } + + public int InicioValor + { + get + { + return this._inicioValor; + } + set + { + this._inicioValor = value; + base.OnPropertyChanged("InicioValor"); + } + } + + public bool IsCampo + { + get + { + return this._isCampo; + } + set + { + this._isCampo = value; + base.OnPropertyChanged("IsCampo"); + } + } + + public bool IsVisibleGrid1 + { + get + { + return this._isVisibleGrid1; + } + set + { + this._isVisibleGrid1 = value; + base.OnPropertyChanged("IsVisibleGrid1"); + } + } + + public bool IsVisibleGrid2 + { + get + { + return this._isVisibleGrid2; + } + set + { + this._isVisibleGrid2 = value; + base.OnPropertyChanged("IsVisibleGrid2"); + } + } + + public bool IsVisibleGrid3 + { + get + { + return this._isVisibleGrid3; + } + set + { + this._isVisibleGrid3 = value; + base.OnPropertyChanged("IsVisibleGrid3"); + } + } + + public bool IsVisibleGrid4 + { + get + { + return this._isVisibleGrid4; + } + set + { + this._isVisibleGrid4 = value; + base.OnPropertyChanged("IsVisibleGrid4"); + } + } + + public List Licenciamento + { + get + { + return this._licenciamento; + } + set + { + this._licenciamento = value; + base.OnPropertyChanged("Licenciamento"); + } + } + + public ObservableCollection LicenciamentoFiltrado + { + get + { + return this._licenciamentoFiltrado; + } + set + { + this._licenciamentoFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("LicenciamentoFiltrado"); + } + } + + public List LogsEnvio + { + get + { + return this._logsEnvio; + } + set + { + this._logsEnvio = value; + base.OnPropertyChanged("LogsEnvio"); + } + } + + public ObservableCollection LogsEnvioFiltrado + { + get + { + return this._logsEnvioFiltrado; + } + set + { + this._logsEnvioFiltrado = value; + this.Sintetic = null; + base.OnPropertyChanged("LogsEnvioFiltrado"); + } + } + + public List LogUtilizacao + { + get; + set; + } + + public ObservableCollection LogUtilizacaoFiltrado + { + get + { + return this._logUtilizacaoFiltrado; + } + set + { + this._logUtilizacaoFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("LogUtilizacaoFiltrado"); + } + } + + public List MetaSeguradora + { + get + { + return this._metaSeguradora; + } + set + { + this._metaSeguradora = value; + base.OnPropertyChanged("MetaSeguradora"); + } + } + + public ObservableCollection MetaSeguradoraFiltrado + { + get + { + return this._metaSeguradoraFiltrado; + } + set + { + this._metaSeguradoraFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("MetaSeguradoraFiltrado"); + } + } + + public List MetaVendedor + { + get + { + return this._metaVendedor; + } + set + { + this._metaVendedor = value; + base.OnPropertyChanged("MetaVendedor"); + } + } + + public ObservableCollection MetaVendedorFiltrado + { + get + { + return this._metaVendedorFiltrado; + } + set + { + this._metaVendedorFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("MetaVendedorFiltrado"); + } + } + + public List Negocios + { + get + { + return this._negocios; + } + set + { + this._negocios = value; + foreach (NegocioRelatorio negocio in this.Negocios) + { + negocio.add_PropertyChanged(new PropertyChangedEventHandler(this.NegocioOnPropertyChanged)); + } + base.OnPropertyChanged("Negocios"); + } + } + + public ObservableCollection NotaFiscalFiltrado + { + get + { + return this._notaFiscalFiltrado; + } + set + { + this._notaFiscalFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("NotaFiscalFiltrado"); + } + } + + public bool NotaFiscalPorSeguradora + { + get + { + return this._notaFiscalPorSeguradora; + } + set + { + this._notaFiscalPorSeguradora = value; + base.OnPropertyChanged("NotaFiscalPorSeguradora"); + } + } + + public List NotasFiscais + { + get + { + return this._notasFiscais; + } + set + { + this._notasFiscais = value; + base.OnPropertyChanged("NotasFiscais"); + } + } + + public bool NovosNegocios + { + get + { + return this._novosNegocios; + } + set + { + this._novosNegocios = value; + base.OnPropertyChanged("NovosNegocios"); + } + } + + public string OrdemSelecionada + { + get + { + return this._ordemSelecionada; + } + set + { + this._ordemSelecionada = value; + base.OnPropertyChanged("OrdemSelecionada"); + } + } + + public ObservableCollection Ordens + { + get + { + return this._ordens; + } + set + { + this._ordens = value; + base.OnPropertyChanged("Ordens"); + } + } + + public List Pagamentos + { + get + { + return this._pagamentos; + } + set + { + this._pagamentos = value; + this.Sintetic = null; + base.OnPropertyChanged("Pagamentos"); + } + } + + public List PagamentosSintetico + { + get + { + return this._pagamentosSintetico; + } + set + { + this._pagamentosSintetico = value; + this.Sintetic = null; + base.OnPropertyChanged("PagamentosSintetico"); + } + } + + public ObservableCollection ParametrosRelatorio + { + get + { + return this._parametrosRelatorio; + } + set + { + if (value == null) + { + value = new ObservableCollection(); + } + Gestor.Model.Domain.Relatorios.ParametrosRelatorio parametrosRelatorio = new Gestor.Model.Domain.Relatorios.ParametrosRelatorio(); + parametrosRelatorio.set_Id((long)0); + parametrosRelatorio.set_Header("SELECIONE UM CAMPO"); + value.Insert(0, parametrosRelatorio); + this._parametrosRelatorio = value; + this.SelectedParametrosRelatorio = value[0]; + base.OnPropertyChanged("ParametrosRelatorio"); + } + } + + public ObservableCollection ParametrosRelatorioAdicionados + { + get + { + return this._parametrosRelatorioAdicionados; + } + set + { + this._parametrosRelatorioAdicionados = value; + base.OnPropertyChanged("ParametrosRelatorioAdicionados"); + } + } + + public ObservableCollection ParametrosTotalizacao + { + get + { + return this._parametrosTotalizacao; + } + set + { + if (value == null) + { + value = new ObservableCollection(); + } + Gestor.Model.Domain.Relatorios.ParametrosTotalizacao parametrosTotalizacao = new Gestor.Model.Domain.Relatorios.ParametrosTotalizacao(); + parametrosTotalizacao.set_Id((long)0); + parametrosTotalizacao.set_Header("SELECIONE UMA TOTALIZAÇÃO"); + value.Insert(0, parametrosTotalizacao); + this._parametrosTotalizacao = value; + this.SelectedParametrosTotalizacao = value[0]; + base.OnPropertyChanged("ParametrosTotalizacao"); + } + } + + public ObservableCollection ParametrosTotalizacaoAdicionados + { + get + { + return this._parametrosTotalizacaoAdicionados; + } + set + { + this._parametrosTotalizacaoAdicionados = value; + base.OnPropertyChanged("ParametrosTotalizacaoAdicionados"); + } + } + + public List ParcelasEspeciais + { + get + { + return this._parcelasEspeciais; + } + set + { + this._parcelasEspeciais = value; + base.OnPropertyChanged("ParcelasEspeciais"); + } + } + + public List Pendente + { + get + { + return this._pendente; + } + set + { + this._pendente = value; + base.OnPropertyChanged("Pendente"); + } + } + + public ObservableCollection PendenteFiltrado + { + get + { + return this._pendenteFiltrado; + } + set + { + this._pendenteFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("PendenteFiltrado"); + } + } + + public bool PermitirFiltrosPersonalizados + { + get + { + return this._permitirFiltrosPersonalizados; + } + set + { + this._permitirFiltrosPersonalizados = value; + base.OnPropertyChanged("PermitirFiltrosPersonalizados"); + } + } + + public ObservableCollection PlacaFiltrado + { + get + { + return this._placaFiltrado; + } + set + { + this._placaFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("PlacaFiltrado"); + } + } + + public List Placas + { + get + { + return this._placas; + } + set + { + this._placas = value; + base.OnPropertyChanged("Placas"); + } + } + + public Visibility PlanilhaVisibility + { + get + { + return this._planilhaVisibility; + } + set + { + this._planilhaVisibility = value; + base.OnPropertyChanged("PlanilhaVisibility"); + } + } + + public ObservableCollection Previsao + { + get + { + return this._previsao; + } + set + { + this._previsao = value; + this.Sintetic = null; + base.OnPropertyChanged("Previsao"); + } + } + + public ObservableCollection PrevisaoFiltrado + { + get + { + return this._previsaoFiltrado; + } + set + { + this._previsaoFiltrado = value; + this.SintetizarRelatorio(); + this.Sintetic = null; + base.OnPropertyChanged("PrevisaoFiltrado"); + } + } + + public ObservableCollection PrevisaoSintetico + { + get + { + return this._previsaoSintetico; + } + set + { + this._previsaoSintetico = value; + this.Sintetic = null; + base.OnPropertyChanged("PrevisaoSintetico"); + } + } + + public List Producao + { + get + { + return this._producao; + } + set + { + this._producao = value; + base.OnPropertyChanged("Producao"); + } + } + + public ObservableCollection ProducaoFiltrado + { + get + { + return this._producaoFiltrado; + } + set + { + this._producaoFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("ProducaoFiltrado"); + } + } + + public List Produtos + { + get + { + return this._produtos; + } + set + { + this._produtos = value; + foreach (Gestor.Model.Domain.Seguros.Produto produto in this.Produtos) + { + produto.add_PropertyChanged(new PropertyChangedEventHandler(this.ProdutoOnPropertyChanged)); + } + base.OnPropertyChanged("Produtos"); + } + } + + public List Ramos + { + get + { + return this._ramos; + } + set + { + this._ramos = value; + foreach (Ramo ramo in this.Ramos) + { + ramo.add_PropertyChanged(new PropertyChangedEventHandler(this.RamoOnPropertyChanged)); + } + base.OnPropertyChanged("Ramos"); + } + } + + public Ramo RamoSelecionado + { + get + { + return this._ramoSelecionado; + } + set + { + this._ramoSelecionado = value; + base.OnPropertyChanged("RamoSelecionado"); + } + } + + public ObservableCollection RamosSelecionados + { + get + { + return this._ramosSelecionados; + } + set + { + this._ramosSelecionados = value; + base.OnPropertyChanged("RamosSelecionados"); + } + } + + private bool ReciboPagamento + { + get; + set; + } + + public string Referencia + { + get + { + return this._referencia; + } + set + { + this._referencia = value; + base.OnPropertyChanged("Referencia"); + } + } + + public ObservableCollection Referencias + { + get + { + return this._referencias; + } + set + { + this._referencias = value; + base.OnPropertyChanged("Referencias"); + } + } + + public Gestor.Model.Common.Relatorio Relatorio + { + get + { + return this._relatorio; + } + set + { + this._relatorio = value; + this.WorkOnRelatorio(value); + base.OnPropertyChanged("Relatorio"); + } + } + + public List RelatorioFiltroPersonalizado + { + get + { + return this._filtroRelatorioPersonalizado; + } + set + { + this._filtroRelatorioPersonalizado = value; + base.OnPropertyChanged("RelatorioFiltroPersonalizado"); + } + } + + public List Relatorios + { + get + { + return this._relatorios; + } + set + { + this._relatorios = value; + base.OnPropertyChanged("Relatorios"); + } + } + + public bool RelatorioVisibility + { + get + { + return this._relatorioVisibility; + } + set + { + this._relatorioVisibility = value; + base.OnPropertyChanged("RelatorioVisibility"); + } + } + + public List Renovacao + { + get + { + return this._renovacao; + } + set + { + this._renovacao = value; + base.OnPropertyChanged("Renovacao"); + } + } + + public ObservableCollection RenovacaoFiltrado + { + get + { + return this._renovacaoFiltrado; + } + set + { + this._renovacaoFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("RenovacaoFiltrado"); + } + } + + public object Report + { + get + { + return this._report; + } + set + { + this._report = value; + this.FiltrosPersonalizados = (value == null || !this.PermitirFiltrosPersonalizados ? Visibility.Collapsed : Visibility.Visible); + base.OnPropertyChanged("Report"); + } + } + + public bool SegundaViaReciboPagamento + { + get + { + return this._segundaViaReciboPagamento; + } + set + { + this.LimparRelatorio(); + this._segundaViaReciboPagamento = value; + if (value) + { + this.SomenteNaoPagos = false; + } + base.OnPropertyChanged("SegundaViaReciboPagamento"); + } + } + + public List Seguradoras + { + get + { + return this._seguradoras; + } + set + { + this._seguradoras = value; + foreach (Seguradora seguradora in this.Seguradoras) + { + seguradora.add_PropertyChanged(new PropertyChangedEventHandler(this.SeguradoraOnPropertyChanged)); + } + base.OnPropertyChanged("Seguradoras"); + } + } + + public int SelectedAno + { + get + { + return this._selectedAno; + } + set + { + this._selectedAno = value; + base.OnPropertyChanged("SelectedAno"); + } + } + + public Mes SelectedMes + { + get + { + return this._selectedMes; + } + set + { + this._selectedMes = value; + base.OnPropertyChanged("SelectedMes"); + } + } + + public Gestor.Model.Domain.Relatorios.ParametrosRelatorio SelectedParametrosRelatorio + { + get + { + return this._selectedParametrosRelatorio; + } + set + { + this._selectedParametrosRelatorio = value; + base.OnPropertyChanged("SelectedParametrosRelatorio"); + } + } + + public Gestor.Model.Domain.Relatorios.ParametrosTotalizacao SelectedParametrosTotalizacao + { + get + { + return this._selectedParametrosTotalizacao; + } + set + { + this._selectedParametrosTotalizacao = value; + base.OnPropertyChanged("SelectedParametrosTotalizacao"); + } + } + + public bool SemValor + { + get + { + return this._semValor; + } + set + { + this._semValor = value; + if (value) + { + this.ValorInicial = null; + this.ValorFinal = null; + } + base.OnPropertyChanged("SemValor"); + } + } + + public string Sessao + { + get; + set; + } + + public List Sinistro + { + get + { + return this._sinistro; + } + set + { + this._sinistro = value; + base.OnPropertyChanged("Sinistro"); + } + } + + public ObservableCollection SinistroFiltrado + { + get + { + return this._sinistroFiltrado; + } + set + { + this._sinistroFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("SinistroFiltrado"); + } + } + + public ObservableCollection Sintetic + { + get + { + return this._sintetic; + } + set + { + this._sintetic = value; + base.OnPropertyChanged("Sintetic"); + } + } + + public SinteticoClientes SinteticoCliente + { + get + { + return this._sinteticoCliente; + } + set + { + this._sinteticoCliente = value; + base.OnPropertyChanged("SinteticoCliente"); + } + } + + public ObservableCollection SinteticoRelatorio + { + get + { + return this._sinteticoRelatorio; + } + set + { + this._sinteticoRelatorio = value; + base.OnPropertyChanged("SinteticoRelatorio"); + this.Totais = (value == null ? false : value.Count > 0); + if (value == null || value.Count == 0) + { + return; + } + List sinteticModels = value.FirstOrDefault().ConstruirSintetico(this.Relatorio); + this.Sintetic = new ObservableCollection(sinteticModels); + } + } + + public bool SinteticosPagamento + { + get + { + return this._sinteticosPagamento; + } + set + { + this._sinteticosPagamento = value; + base.OnPropertyChanged("SinteticosPagamento"); + } + } + + public bool SomenteNaoPagos + { + get + { + return this._somenteNaoPagos; + } + set + { + this.LimparRelatorio(); + this._somenteNaoPagos = value; + if (value) + { + this.SegundaViaReciboPagamento = false; + } + base.OnPropertyChanged("SomenteNaoPagos"); + } + } + + public List Tarefa + { + get + { + return this._tarefa; + } + set + { + this._tarefa = value; + base.OnPropertyChanged("Tarefa"); + } + } + + public ObservableCollection TarefaFiltrado + { + get + { + return this._tarefaFiltrado; + } + set + { + this._tarefaFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("TarefaFiltrado"); + } + } + + public Type TipoDateTime + { + get + { + return this._tipoDateTime; + } + set + { + this._tipoDateTime = value; + base.OnPropertyChanged("TipoDateTime"); + } + } + + public Type TipoDecimal + { + get + { + return this._tipoDecimal; + } + set + { + this._tipoDecimal = value; + base.OnPropertyChanged("TipoDecimal"); + } + } + + public Type TipoEnum + { + get + { + return this._tipoEnum; + } + set + { + this._tipoEnum = value; + base.OnPropertyChanged("TipoEnum"); + } + } + + public Type TipoInt + { + get + { + return this._tipoInt; + } + set + { + this._tipoInt = value; + base.OnPropertyChanged("TipoInt"); + } + } + + public Type TipoLong + { + get + { + return this._tipoLong; + } + set + { + this._tipoLong = value; + base.OnPropertyChanged("TipoLong"); + } + } + + public List TipoSeguros + { + get + { + return this._tipoSeguros; + } + set + { + this._tipoSeguros = value; + foreach (StatusRelatorio tipoSeguro in this.TipoSeguros) + { + tipoSeguro.add_PropertyChanged(new PropertyChangedEventHandler(this.StatusOnPropertyChanged)); + } + base.OnPropertyChanged("TipoSeguros"); + } + } + + public Type TipoString + { + get + { + return this._tipoString; + } + set + { + this._tipoString = value; + base.OnPropertyChanged("TipoString"); + } + } + + public List TipoVendedor + { + get + { + return this._tipoVendedor; + } + set + { + this._tipoVendedor = value; + foreach (Gestor.Model.Domain.Seguros.TipoVendedor tipoVendedor in this.TipoVendedor) + { + tipoVendedor.add_PropertyChanged(new PropertyChangedEventHandler(this.TipoVendedorOnPropertyChanged)); + } + base.OnPropertyChanged("TipoVendedor"); + } + } + + public bool Totais + { + get + { + return this._totais; + } + set + { + this._totais = value; + base.OnPropertyChanged("Totais"); + } + } + + public bool Totalizacao + { + get + { + return this._totalizacao; + } + set + { + this._totalizacao = value; + base.OnPropertyChanged("Totalizacao"); + } + } + + public List Usuarios + { + get; + set; + } + + public ObservableCollection UsuariosFiltrados + { + get + { + return this._usuariosFiltrados; + } + set + { + this._usuariosFiltrados = value; + base.OnPropertyChanged("UsuariosFiltrados"); + } + } + + public string ValorFinal + { + get + { + return this._valorFinal; + } + set + { + this._valorFinal = value; + base.OnPropertyChanged("ValorFinal"); + } + } + + public bool ValorIgual + { + get + { + return this._valorIgual; + } + set + { + this._valorIgual = value; + base.OnPropertyChanged("ValorIgual"); + } + } + + public string ValorInicial + { + get + { + return this._valorIncial; + } + set + { + this._valorIncial = value; + base.OnPropertyChanged("ValorInicial"); + } + } + + public List Vendedores + { + get + { + return this._vendedores; + } + set + { + this._vendedores = value; + foreach (Vendedor vendedore in this.Vendedores) + { + vendedore.add_PropertyChanged(new PropertyChangedEventHandler(this.VendedorOnPropertyChanged)); + } + base.OnPropertyChanged("Vendedores"); + } + } + + private List Vinculo + { + get; + set; + } + + public Visibility VisibilityAcompanhamento + { + get + { + return this._visibilityAcompanhamento; + } + set + { + this._visibilityAcompanhamento = value; + base.OnPropertyChanged("VisibilityAcompanhamento"); + } + } + + public Visibility VisibilityAgrupamento + { + get + { + return this._visibilityAgrupamento; + } + set + { + this._visibilityAgrupamento = value; + base.OnPropertyChanged("VisibilityAgrupamento"); + } + } + + public Visibility VisibilityApolice + { + get + { + return this._visibilityApolice; + } + set + { + this._visibilityApolice = value; + base.OnPropertyChanged("VisibilityApolice"); + } + } + + public Visibility VisibilityComparativo + { + get + { + return this._visibilityComparativo; + } + set + { + this._visibilityComparativo = value; + base.OnPropertyChanged("VisibilityComparativo"); + } + } + + public Visibility VisibilityCompleto + { + get + { + return this._visibilityCompleto; + } + set + { + this._visibilityCompleto = value; + base.OnPropertyChanged("VisibilityCompleto"); + } + } + + public Visibility VisibilityConfigurar + { + get + { + return this._visibilityConfigurar; + } + set + { + this._visibilityConfigurar = value; + base.OnPropertyChanged("VisibilityConfigurar"); + } + } + + public Visibility VisibilityData + { + get + { + return this._visibilityData; + } + set + { + this._visibilityData = value; + base.OnPropertyChanged("VisibilityData"); + } + } + + public bool VisibilityDesconsiderarNegativos + { + get + { + return this._visibilityDesconsiderarNegativos; + } + set + { + this._visibilityDesconsiderarNegativos = value; + base.OnPropertyChanged("VisibilityDesconsiderarNegativos"); + } + } + + public Visibility VisibilityDocumentoAtivo + { + get + { + return this._visibilityDocumentoAtivo; + } + set + { + this._visibilityDocumentoAtivo = value; + base.OnPropertyChanged("VisibilityDocumentoAtivo"); + } + } + + public Visibility VisibilityEmail + { + get + { + return this._visibilityEmail; + } + set + { + this._visibilityEmail = value; + base.OnPropertyChanged("VisibilityEmail"); + } + } + + public Visibility VisibilityEspecial + { + get + { + return this._visibilityEspecial; + } + set + { + this._visibilityEspecial = value; + base.OnPropertyChanged("VisibilityEspecial"); + } + } + + public Visibility VisibilityEtiqueta + { + get + { + return this._visibilityEtiqueta; + } + set + { + this._visibilityEtiqueta = value; + base.OnPropertyChanged("VisibilityEtiqueta"); + } + } + + public Visibility VisibilityExtratos + { + get + { + return this._visibilityExtratos; + } + set + { + this._visibilityExtratos = value; + base.OnPropertyChanged("VisibilityExtratos"); + } + } + + public Visibility VisibilityFiltroPersonalizado + { + get + { + return this._visibilityFiltroPersonalizado; + } + set + { + this._visibilityFiltroPersonalizado = value; + base.OnPropertyChanged("VisibilityFiltroPersonalizado"); + } + } + + public Visibility VisibilityFiltroPersonalizadoButton + { + get + { + return this._visibilityFiltroPersonalizadoButton; + } + set + { + this._visibilityFiltroPersonalizadoButton = value; + base.OnPropertyChanged("VisibilityFiltroPersonalizadoButton"); + } + } + + public Visibility VisibilityFiltros + { + get + { + return this._visibilityFiltros; + } + set + { + this._visibilityFiltros = value; + base.OnPropertyChanged("VisibilityFiltros"); + } + } + + public Visibility VisibilityGridFiltros + { + get + { + return this._visibilityGridFiltros; + } + set + { + this._visibilityGridFiltros = value; + base.OnPropertyChanged("VisibilityGridFiltros"); + } + } + + public bool VisibilityHtml + { + get + { + return this._visibilityHtml; + } + set + { + this._visibilityHtml = value; + base.OnPropertyChanged("VisibilityHtml"); + } + } + + public Visibility VisibilityMaisFiltros + { + get + { + return this._visibilityMaisFiltros; + } + set + { + this._visibilityMaisFiltros = value; + base.OnPropertyChanged("VisibilityMaisFiltros"); + } + } + + public Visibility VisibilityMeta + { + get + { + return this._visibilityMeta; + } + set + { + this._visibilityMeta = value; + base.OnPropertyChanged("VisibilityMeta"); + } + } + + public Visibility VisibilityNotaFiscalPorSeguradora + { + get + { + return this._visibilityNotaFiscalPorSeguradora; + } + set + { + this._visibilityNotaFiscalPorSeguradora = value; + base.OnPropertyChanged("VisibilityNotaFiscalPorSeguradora"); + } + } + + public Visibility VisibilityOlho + { + get + { + return this._visibilityOlho; + } + set + { + this._visibilityOlho = value; + base.OnPropertyChanged("VisibilityOlho"); + } + } + + public Visibility VisibilityOpcoesFiltros + { + get + { + return this._visibilityOpcoesFiltros; + } + set + { + this._visibilityOpcoesFiltros = value; + base.OnPropertyChanged("VisibilityOpcoesFiltros"); + } + } + + public Visibility VisibilityOrdem + { + get + { + return this._visibilityOrdem; + } + set + { + this._visibilityOrdem = value; + base.OnPropertyChanged("VisibilityOrdem"); + } + } + + public Visibility VisibilityPagamento + { + get + { + return this._visibilityPagamento; + } + set + { + this._visibilityPagamento = value; + base.OnPropertyChanged("VisibilityPagamento"); + } + } + + public Visibility VisibilityReferencia + { + get + { + return this._visibilityReferencia; + } + set + { + this._visibilityReferencia = value; + base.OnPropertyChanged("VisibilityReferencia"); + } + } + + public Visibility VisibilitySemValor + { + get + { + return this._visibilitySemValor; + } + set + { + this._visibilitySemValor = value; + base.OnPropertyChanged("VisibilitySemValor"); + } + } + + public Visibility VisibilitySintetizar + { + get + { + return this._visibilitySintetizar; + } + set + { + this._visibilitySintetizar = value; + base.OnPropertyChanged("VisibilitySintetizar"); + } + } + + public Visibility VisibilityTarefas + { + get + { + return this._visibilityTarefas; + } + set + { + this._visibilityTarefas = value; + base.OnPropertyChanged("VisibilityTarefas"); + } + } + + public bool VisibilityUsuarios + { + get + { + return this._visibilityUsuarios; + } + set + { + this._visibilityUsuarios = value; + base.OnPropertyChanged("VisibilityUsuarios"); + } + } + + public Visibility VisibilityValor + { + get + { + return this._visibilityValor; + } + set + { + this._visibilityValor = value; + base.OnPropertyChanged("VisibilityValor"); + } + } + + public Visibility VisibiltyProtocolo + { + get + { + return this._visibiltyProtocolo; + } + set + { + this._visibiltyProtocolo = value; + base.OnPropertyChanged("VisibiltyProtocolo"); + } + } + + public Visibility VisibiltySincronizar + { + get + { + return this._visibiltySincronizar; + } + set + { + this._visibiltySincronizar = value; + base.OnPropertyChanged("VisibiltySincronizar"); + } + } + + static RelatorioViewModel() + { + List negocioRelatorios = new List(); + NegocioRelatorio negocioRelatorio = new NegocioRelatorio(); + negocioRelatorio.set_Id(0); + negocioRelatorio.set_Selecionado(false); + negocioRelatorio.set_Negocio(0); + negocioRelatorios.Add(negocioRelatorio); + NegocioRelatorio negocioRelatorio1 = new NegocioRelatorio(); + negocioRelatorio1.set_Id(1); + negocioRelatorio1.set_Selecionado(false); + negocioRelatorio1.set_Negocio(1); + negocioRelatorios.Add(negocioRelatorio1); + RelatorioViewModel.NegocioList = negocioRelatorios; + List statusRelatorios = new List(); + StatusRelatorio statusRelatorio = new StatusRelatorio(); + statusRelatorio.set_Id(1); + statusRelatorio.set_Selecionado(false); + statusRelatorio.set_Status(1); + statusRelatorios.Add(statusRelatorio); + StatusRelatorio statusRelatorio1 = new StatusRelatorio(); + statusRelatorio1.set_Id(2); + statusRelatorio1.set_Selecionado(false); + statusRelatorio1.set_Status(2); + statusRelatorios.Add(statusRelatorio1); + StatusRelatorio statusRelatorio2 = new StatusRelatorio(); + statusRelatorio2.set_Id(3); + statusRelatorio2.set_Selecionado(false); + statusRelatorio2.set_Status(3); + statusRelatorios.Add(statusRelatorio2); + StatusRelatorio statusRelatorio3 = new StatusRelatorio(); + statusRelatorio3.set_Id(4); + statusRelatorio3.set_Selecionado(false); + statusRelatorio3.set_Status(7); + statusRelatorios.Add(statusRelatorio3); + StatusRelatorio statusRelatorio4 = new StatusRelatorio(); + statusRelatorio4.set_Id(5); + statusRelatorio4.set_Selecionado(false); + statusRelatorio4.set_Status(5); + statusRelatorios.Add(statusRelatorio4); + StatusRelatorio statusRelatorio5 = new StatusRelatorio(); + statusRelatorio5.set_Id(6); + statusRelatorio5.set_Selecionado(false); + statusRelatorio5.set_Status(6); + statusRelatorios.Add(statusRelatorio5); + StatusRelatorio statusRelatorio6 = new StatusRelatorio(); + statusRelatorio6.set_Id(7); + statusRelatorio6.set_Selecionado(false); + statusRelatorio6.set_Status(4); + statusRelatorios.Add(statusRelatorio6); + RelatorioViewModel.TipoSegurosList = statusRelatorios; + } + + public RelatorioViewModel(string opcao) + { + this.funcProducaoDistinctByDocumentoId = (Gestor.Model.Domain.Relatorios.Producao.Producao p) => p.get_Documento().get_Id(); + this.funcProducaoSegurosNovos = (Gestor.Model.Domain.Relatorios.Producao.Producao p) => p.get_Documento().get_Situacao() == 1; + this.funcProducaoSegurosRenovacao = (Gestor.Model.Domain.Relatorios.Producao.Producao p) => p.get_Documento().get_Situacao() == 2; + this.funcProducaoNegociosNovos = (Gestor.Model.Domain.Relatorios.Producao.Producao p) => { + NegocioCorretora? negocioCorretora = p.get_Documento().get_NegocioCorretora(); + return negocioCorretora.GetValueOrDefault() == 0 & negocioCorretora.HasValue; + }; + this.funcProducaoNegociosProprios = (Gestor.Model.Domain.Relatorios.Producao.Producao p) => p.get_Documento().get_NegocioCorretora().GetValueOrDefault() == 1; + this._totalizacao = true; + this._relatorios = new List(); + this._relatorio = 2; + this._filtrosPersonalizados = Visibility.Collapsed; + this._visibilityDesconsiderarNegativos = Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 50); + this._visibilityReferencia = Visibility.Collapsed; + this._visibilityOrdem = Visibility.Collapsed; + this._referencias = new ObservableCollection(); + this._ordens = new ObservableCollection(); + DateTime date = Funcoes.GetNetworkTime().Date; + this._inicio = date.AddMonths(-1); + this._fim = Funcoes.GetNetworkTime().Date; + this._infoVisibility = Visibility.Collapsed; + this._erroRelatorio = "NÃO HÁ DADOS NO PERÍODO E FILTROS SELECIONADOS."; + this.ColunasOcultas = new List(); + this._seguradoras = ( + from x in Recursos.Seguradoras + where x.get_Ativo() + orderby x.get_Nome() + select x).ToList(); + this._ramos = ( + from x in Recursos.Ramos + where x.get_Ativo() + orderby x.get_Nome() + select x).ToList(); + this._notasFiscais = new List(); + this._inativo = true; + this._vendedores = new List(); + this._tipoVendedor = ( + from x in Recursos.TipoVendedor + where x.get_Ativo().GetValueOrDefault() + orderby x.get_Descricao() + select x).ToList(); + this._produtos = ( + from x in Recursos.Produtos + where x.get_Ativo() + orderby x.get_Nome() + select x).ToList(); + this._estipulantes = Recursos.Estipulantes.Where((Estipulante x) => { + if (Recursos.Usuario.get_IdEmpresa() != (long)1 && Recursos.Usuario.get_IdEmpresa() != x.get_IdEmpresa()) + { + return false; + } + return x.get_Ativo(); + }).OrderBy((Estipulante x) => x.get_Nome()).ToList(); + this._negocios = RelatorioViewModel.NegocioList; + this._tipoSeguros = RelatorioViewModel.TipoSegurosList; + this._isVisibleGrid1 = true; + this._isVisibleGrid2 = true; + this._isVisibleGrid3 = true; + this._isVisibleGrid4 = true; + this._tipoString = typeof(string); + this._tipoEnum = typeof(Enum); + this._tipoDateTime = typeof(DateTime); + this._tipoDecimal = typeof(decimal); + this._tipoInt = typeof(int); + this._tipoLong = typeof(long); + this._valorIncial = ""; + this._valorFinal = ""; + this._visibilitySemValor = Visibility.Collapsed; + this._visibilityOpcoesFiltros = Visibility.Collapsed; + this._filtroRelatorioSelecionado = new ObservableCollection(); + this._visibilityFiltroPersonalizado = Visibility.Collapsed; + List filtroTipoParcelas = new List(); + FiltroTipoParcela filtroTipoParcela = new FiltroTipoParcela(); + filtroTipoParcela.set_Selecionado(true); + filtroTipoParcela.set_Tipo(1); + filtroTipoParcelas.Add(filtroTipoParcela); + FiltroTipoParcela filtroTipoParcela1 = new FiltroTipoParcela(); + filtroTipoParcela1.set_Selecionado(true); + filtroTipoParcela1.set_Tipo(6); + filtroTipoParcelas.Add(filtroTipoParcela1); + FiltroTipoParcela filtroTipoParcela2 = new FiltroTipoParcela(); + filtroTipoParcela2.set_Selecionado(true); + filtroTipoParcela2.set_Tipo(3); + filtroTipoParcelas.Add(filtroTipoParcela2); + FiltroTipoParcela filtroTipoParcela3 = new FiltroTipoParcela(); + filtroTipoParcela3.set_Selecionado(true); + filtroTipoParcela3.set_Tipo(2); + filtroTipoParcelas.Add(filtroTipoParcela3); + FiltroTipoParcela filtroTipoParcela4 = new FiltroTipoParcela(); + filtroTipoParcela4.set_Selecionado(true); + filtroTipoParcela4.set_Tipo(5); + filtroTipoParcelas.Add(filtroTipoParcela4); + FiltroTipoParcela filtroTipoParcela5 = new FiltroTipoParcela(); + filtroTipoParcela5.set_Selecionado(true); + filtroTipoParcela5.set_Tipo(4); + filtroTipoParcelas.Add(filtroTipoParcela5); + this._parcelasEspeciais = filtroTipoParcelas; + this._ajuda = new ObservableCollection(); + this._isCampo = true; + this._usuariosFiltrados = new ObservableCollection(); + base(); + this._apoliceServico = new ApoliceServico(); + this._parcelaServico = new ParcelaServico(); + this._sinistroServico = new SinistroServico(); + this._clienteServico = new ClienteServico(); + this._logServico = new LogServico(); + this._extratoServico = new ServicoExtrato(); + this._metaSeguradoraServico = new MetaSeguradoraServico(); + this._metaVendedorServico = new MetaVendedorServico(); + this._notaFiscalServico = new NotaFiscalServico(); + this._criticaServico = new CriticaApoliceServico(); + this.Sessao = Guid.NewGuid().ToString(); + base.IsEnabled = true; + this.Apelido = Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 6); + List list = ( + from x in Recursos.Empresas + orderby x.get_Id() + select x).ToList(); + Gestor.Model.Domain.Common.Empresa empresa = new Gestor.Model.Domain.Common.Empresa(); + empresa.set_Id((long)0); + empresa.set_Nome("TODAS, MATRIZ E FILIAIS"); + list.Insert(0, empresa); + this.Empresas = list; + this.Empresa = (Recursos.Usuario.get_IdEmpresa() <= (long)1 ? this.Empresas.First() : this.Empresas.Find((Gestor.Model.Domain.Common.Empresa x) => x.get_Id() == Recursos.Usuario.get_IdEmpresa())); + this.EnableEmpresa = Recursos.Usuario.get_IdEmpresa() <= (long)1; + base.EnableMenu = true; + this.LoadVendedores(); + this.PopularRelatorio(opcao); + } + + public async Task Acompanhamento() + { + Trilha trilha; + List tarefas; + if (this.RenovacaoFiltrado != null && this.RenovacaoFiltrado.Count != 0) + { + ObservableCollection renovacaoFiltrado = this.RenovacaoFiltrado; + if (!renovacaoFiltrado.All((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => !x.get_Selecionado())) + { + Trilha trilha1 = new Trilha(); + trilha1.set_Ativo(true); + trilha1.set_Titulo("ACOMPANHAMENTO DE RENOVAÇÃO"); + trilha1.set_Tipo(0); + List fases = new List(); + Fase fase = new Fase(); + fase.set_Titulo("A RENOVAR"); + fases.Add(fase); + Fase fase1 = new Fase(); + fase1.set_Titulo("EM RENOVAÇÃO"); + fases.Add(fase1); + Fase fase2 = new Fase(); + fase2.set_Titulo("RENOVADOS"); + fases.Add(fase2); + Fase fase3 = new Fase(); + fase3.set_Titulo("PERDIDOS"); + fases.Add(fase3); + trilha1.set_Fases(fases); + trilha = trilha1; + trilha = await this.SalvarTrilha(trilha); + if (trilha != null) + { + tarefas = await (new TarefaServico()).BuscarTarefas(trilha.get_Id()); + ObservableCollection observableCollection = this.RenovacaoFiltrado; + foreach (Gestor.Model.Domain.Relatorios.Renovacao.Renovacao renovacao in + from x in observableCollection + where x.get_Selecionado() + select x) + { + if (tarefas.Any((Gestor.Model.Domain.Ferramentas.Tarefa x) => x.get_IdEntidade() == renovacao.get_Documento().get_Id())) + { + continue; + } + Gestor.Model.Domain.Ferramentas.Tarefa tarefa = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa.set_Entidade(0); + tarefa.set_IdEntidade(renovacao.get_Documento().get_Id()); + tarefa.set_IdCliente(renovacao.get_Documento().get_Controle().get_Cliente().get_Id()); + tarefa.set_Cliente(renovacao.get_Cliente()); + tarefa.set_Titulo(string.Concat("APÓLICE NÚMERO ", renovacao.get_Apolice())); + tarefa.set_Usuario(Recursos.Usuario); + tarefa.set_Agendamento(Funcoes.GetNetworkTime()); + tarefa.set_Trilha(trilha); + tarefa.set_Fase(trilha.get_Fases().First()); + object[] vigenciaFinal = new object[] { renovacao.get_VigenciaFinal(), renovacao.get_Seguradora(), renovacao.get_Ramo(), renovacao.get_Item() }; + tarefa.set_Referencia(string.Format("VIGÊNCIA FINAL: {0}\nSEGURADORA: {1}\nRAMO: {2}\nITEM: {3}", vigenciaFinal)); + await (new TarefaServico()).Salvar(tarefa); + } + if (Funcoes.IsWindowOpen("ACOMPANHAMENTO DE RENOVAÇÃO")) + { + Funcoes.Destroy("ACOMPANHAMENTO DE RENOVAÇÃO"); + } + (new HosterWindow(new AcompanhamentoView(), "ACOMPANHAMENTO DE RENOVAÇÃO", new double?((double)910), new double?((double)600), true)).Show(); + trilha = null; + tarefas = null; + return; + } + else + { + trilha = null; + tarefas = null; + return; + } + } + } + await base.ShowMessage("NECESSÁRIO SELECIONAR AO MENOS UM ITEM NA LISTA PARA GERAR O ACOMPANHAMENTO.", "OK", "", false); + trilha = null; + tarefas = null; + } + + public async void AdcionarFiltroPersonalizado() + { + string str; + DateTime dateTime; + decimal num; + int num1; + long num2; + List filtroPersonalizados; + List filtroPersonalizados1; + if (this.FiltroPersonalizado != null) + { + if (this.SemValor) + { + filtroPersonalizados = (this.FiltroPersonalizadoSelecionado == null ? new List() : ( + from x in this.FiltroPersonalizadoSelecionado + where x.get_Propriedade() == this.FiltroPersonalizado.get_Propriedade() + select x).ToList()); + List filtroPersonalizados2 = filtroPersonalizados; + if (filtroPersonalizados2.Count > 0) + { + filtroPersonalizados2.ForEach((Gestor.Model.Domain.Relatorios.FiltroPersonalizado x) => this.FiltroPersonalizadoSelecionado.Remove(x)); + } + str = string.Concat(this.FiltroPersonalizado.get_Nome(), ": EM BRANCO"); + } + else + { + filtroPersonalizados1 = (this.FiltroPersonalizadoSelecionado == null ? new List() : this.FiltroPersonalizadoSelecionado.Where((Gestor.Model.Domain.Relatorios.FiltroPersonalizado x) => { + if (x.get_Propriedade() != this.FiltroPersonalizado.get_Propriedade()) + { + return false; + } + return x.get_SemValor(); + }).ToList()); + List filtroPersonalizados3 = filtroPersonalizados1; + if (filtroPersonalizados3.Count > 0) + { + filtroPersonalizados3.ForEach((Gestor.Model.Domain.Relatorios.FiltroPersonalizado x) => this.FiltroPersonalizadoSelecionado.Remove(x)); + } + string name = this.FiltroPersonalizado.get_Tipo().Name; + if (name == "DateTime") + { + if (!DateTime.TryParse(this.ValorInicial, out dateTime) || !DateTime.TryParse(this.ValorFinal, out dateTime) || DateTime.Parse(this.ValorInicial) > DateTime.Parse(this.ValorFinal)) + { + await base.ShowMessage("O VALOR DE INTERVALO DEVE SER PREENCHIDO CORRETAMENTE.", "OK", "", false); + return; + } + else + { + str = string.Format("{0}: {1:d} até {2:d}", this.FiltroPersonalizado.get_Nome(), DateTime.Parse(this.ValorInicial), DateTime.Parse(this.ValorFinal)); + } + } + else if (name == "Decimal") + { + if (!decimal.TryParse(this.ValorInicial, out num) || !decimal.TryParse(this.ValorFinal, out num) || decimal.Parse(this.ValorInicial) > decimal.Parse(this.ValorFinal)) + { + await base.ShowMessage("O VALOR DE INTERVALO DEVE SER PREENCHIDO CORRETAMENTE.", "OK", "", false); + return; + } + else + { + str = string.Format("{0}: {1:n2} até {2:n2}", this.FiltroPersonalizado.get_Nome(), decimal.Parse(this.ValorInicial), decimal.Parse(this.ValorFinal)); + } + } + else if (name == "Int32") + { + if (!int.TryParse(this.ValorInicial, out num1) || !int.TryParse(this.ValorFinal, out num1) || int.Parse(this.ValorInicial) > int.Parse(this.ValorFinal)) + { + await base.ShowMessage("O VALOR DE INTERVALO DEVE SER PREENCHIDO CORRETAMENTE.", "OK", "", false); + return; + } + else + { + str = string.Format("{0}: {1:n0} até {2:n0}", this.FiltroPersonalizado.get_Nome(), int.Parse(this.ValorInicial), int.Parse(this.ValorFinal)); + } + } + else if (name != "Int64") + { + if (!string.IsNullOrEmpty(this.ValorInicial)) + { + str = string.Concat(this.FiltroPersonalizado.get_Nome(), " = ", this.ValorInicial); + } + else + { + await base.ShowMessage("O VALOR DEVE SER PREENCHIDO CORRETAMENTE.", "OK", "", false); + return; + } + } + else if (!long.TryParse(this.ValorInicial, out num2) || !long.TryParse(this.ValorFinal, out num2) || long.Parse(this.ValorInicial) > (long)int.Parse(this.ValorFinal)) + { + await base.ShowMessage("O VALOR DE INTERVALO DEVE SER PREENCHIDO CORRETAMENTE.", "OK", "", false); + return; + } + else + { + str = string.Format("{0}: {1:n0} até {2:n0}", this.FiltroPersonalizado.get_Nome(), long.Parse(this.ValorInicial), long.Parse(this.ValorFinal)); + } + } + if (this.FiltroPersonalizadoSelecionado == null) + { + this.FiltroPersonalizadoSelecionado = new ObservableCollection(); + } + ObservableCollection filtroPersonalizadoSelecionado = this.FiltroPersonalizadoSelecionado; + Gestor.Model.Domain.Relatorios.FiltroPersonalizado filtroPersonalizado = new Gestor.Model.Domain.Relatorios.FiltroPersonalizado(); + filtroPersonalizado.set_Nome(this.FiltroPersonalizado.get_Nome()); + filtroPersonalizado.set_Propriedade(this.FiltroPersonalizado.get_Propriedade()); + filtroPersonalizado.set_Tipo(this.FiltroPersonalizado.get_Tipo()); + filtroPersonalizado.set_ValorIncial(this.ValorInicial); + filtroPersonalizado.set_ValorFinal(this.ValorFinal); + filtroPersonalizado.set_SemValor(this.SemValor); + filtroPersonalizado.set_Descricao(str); + filtroPersonalizadoSelecionado.Add(filtroPersonalizado); + this.FiltroPersonalizado = null; + this.ValorInicial = string.Empty; + this.ValorFinal = string.Empty; + this.PesquisaPersonalizada(); + } + } + + public void AdicionarFiltro(FiltroRelatorio filtro) + { + if (filtro == null) + { + return; + } + if (this.FiltroRelatorioSelecionado == null) + { + this.FiltroRelatorioSelecionado = new ObservableCollection(); + } + if (this.FiltroRelatorioSelecionado.Any((FiltroRelatorio x) => { + if (x.get_Id() != filtro.get_Id()) + { + return false; + } + return x.get_Tipo() == filtro.get_Tipo(); + })) + { + return; + } + this.FiltroRelatorioSelecionado.Add(filtro); + switch (filtro.get_Tipo()) + { + case 0: + { + Seguradora seguradora = this.Seguradoras.FirstOrDefault((Seguradora x) => x.get_Id() == filtro.get_Id()); + if (seguradora == null) + { + break; + } + seguradora.set_Selecionado(true); + return; + } + case 1: + { + Ramo ramo = this.Ramos.FirstOrDefault((Ramo x) => x.get_Id() == filtro.get_Id()); + if (ramo == null) + { + break; + } + ramo.set_Selecionado(true); + return; + } + case 2: + { + Vendedor vendedor = this.Vendedores.FirstOrDefault((Vendedor x) => x.get_Id() == filtro.get_Id()); + if (vendedor == null) + { + break; + } + vendedor.set_Selecionado(true); + return; + } + case 3: + { + Estipulante estipulante = this.Estipulantes.FirstOrDefault((Estipulante x) => x.get_Id() == filtro.get_Id()); + if (estipulante == null) + { + break; + } + estipulante.set_Selecionado(true); + return; + } + case 4: + { + Gestor.Model.Domain.Seguros.Produto produto = this.Produtos.FirstOrDefault((Gestor.Model.Domain.Seguros.Produto x) => x.get_Id() == filtro.get_Id()); + if (produto == null) + { + break; + } + produto.set_Selecionado(true); + return; + } + case 5: + { + StatusRelatorio statusRelatorio = this.TipoSeguros.FirstOrDefault((StatusRelatorio x) => (long)x.get_Status() == filtro.get_Id()); + if (statusRelatorio == null) + { + break; + } + statusRelatorio.set_Selecionado(true); + return; + } + case 6: + { + Gestor.Model.Domain.Seguros.TipoVendedor tipoVendedor = this.TipoVendedor.FirstOrDefault((Gestor.Model.Domain.Seguros.TipoVendedor x) => x.get_Id() == filtro.get_Id()); + if (tipoVendedor == null) + { + break; + } + tipoVendedor.set_Selecionado(true); + return; + } + case 7: + { + NegocioRelatorio negocioRelatorio = this.Negocios.FirstOrDefault((NegocioRelatorio x) => (long)x.get_Id() == filtro.get_Id()); + if (negocioRelatorio == null) + { + break; + } + negocioRelatorio.set_Selecionado(true); + break; + } + default: + { + return; + } + } + } + + public void AdicionarFiltros() + { + List filtroRelatorios = new List(); + List list = ( + from x in this.Seguradoras + where x.get_Selecionado() + select x).Select((Seguradora x) => { + FiltroRelatorio filtroRelatorio = new FiltroRelatorio(); + filtroRelatorio.set_Id(x.get_Id()); + filtroRelatorio.set_Descricao(x.get_Nome()); + filtroRelatorio.set_Tipo(0); + return filtroRelatorio; + }).ToList(); + filtroRelatorios.AddRange(list); + list = ( + from x in this.Ramos + where x.get_Selecionado() + select x).Select((Ramo x) => { + FiltroRelatorio filtroRelatorio = new FiltroRelatorio(); + filtroRelatorio.set_Id(x.get_Id()); + filtroRelatorio.set_Descricao(x.get_Nome()); + filtroRelatorio.set_Tipo(1); + return filtroRelatorio; + }).ToList(); + filtroRelatorios.AddRange(list); + list = ( + from x in this.Vendedores + where x.get_Selecionado() + select x).Select((Vendedor x) => { + FiltroRelatorio filtroRelatorio = new FiltroRelatorio(); + filtroRelatorio.set_Id(x.get_Id()); + filtroRelatorio.set_Descricao(x.get_Nome()); + filtroRelatorio.set_Tipo(2); + return filtroRelatorio; + }).ToList(); + filtroRelatorios.AddRange(list); + list = ( + from x in this.TipoVendedor + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Seguros.TipoVendedor x) => { + FiltroRelatorio filtroRelatorio = new FiltroRelatorio(); + filtroRelatorio.set_Id(x.get_Id()); + filtroRelatorio.set_Descricao(x.get_Descricao()); + filtroRelatorio.set_Tipo(6); + return filtroRelatorio; + }).ToList(); + filtroRelatorios.AddRange(list); + list = ( + from x in this.Estipulantes + where x.get_Selecionado() + select x).Select((Estipulante x) => { + FiltroRelatorio filtroRelatorio = new FiltroRelatorio(); + filtroRelatorio.set_Id(x.get_Id()); + filtroRelatorio.set_Descricao(x.get_Nome()); + filtroRelatorio.set_Tipo(3); + return filtroRelatorio; + }).ToList(); + filtroRelatorios.AddRange(list); + list = ( + from x in this.Produtos + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Seguros.Produto x) => { + FiltroRelatorio filtroRelatorio = new FiltroRelatorio(); + filtroRelatorio.set_Id(x.get_Id()); + filtroRelatorio.set_Descricao(x.get_Nome()); + filtroRelatorio.set_Tipo(4); + return filtroRelatorio; + }).ToList(); + filtroRelatorios.AddRange(list); + list = ( + from x in this.TipoSeguros + where x.get_Selecionado() + select x).Select((StatusRelatorio x) => { + FiltroRelatorio filtroRelatorio = new FiltroRelatorio(); + filtroRelatorio.set_Id((long)x.get_Status()); + filtroRelatorio.set_Descricao(EnumHelper.GetDescription(x.get_Status())); + filtroRelatorio.set_Tipo(5); + return filtroRelatorio; + }).ToList(); + filtroRelatorios.AddRange(list); + list = ( + from x in this.Negocios + where x.get_Selecionado() + select x).Select((NegocioRelatorio x) => { + FiltroRelatorio filtroRelatorio = new FiltroRelatorio(); + filtroRelatorio.set_Id((long)x.get_Negocio()); + filtroRelatorio.set_Descricao(EnumHelper.GetDescription(x.get_Negocio())); + filtroRelatorio.set_Tipo(7); + return filtroRelatorio; + }).ToList(); + filtroRelatorios.AddRange(list); + this.FiltroRelatorioSelecionado = new ObservableCollection(filtroRelatorios); + } + + public void AdicionarParametro(Gestor.Model.Domain.Relatorios.ParametrosRelatorio parametro) + { + if (parametro != null && parametro.get_Header() != "SELECIONE UM CAMPO") + { + this.ParametrosRelatorio.Remove(parametro); + this.ParametrosRelatorioAdicionados.Add(parametro); + this.SelectedParametrosRelatorio = this.ParametrosRelatorio[0]; + } + } + + public void AdicionarRamo() + { + if (this.RamoSelecionado == null) + { + return; + } + if (this.RamosSelecionados == null) + { + this.RamosSelecionados = new ObservableCollection(); + } + if (this.RamosSelecionados.All((Ramo x) => x.get_Id() != this.RamoSelecionado.get_Id())) + { + this.RamosSelecionados.Add(this.RamoSelecionado); + } + this.RamoSelecionado = null; + this.FiltrarRamo(); + } + + public void AdicionarTotalizacao(Gestor.Model.Domain.Relatorios.ParametrosTotalizacao parametro) + { + if (parametro != null && parametro.get_Header() != "SELECIONE UMA TOTALIZAÇÃO") + { + this.ParametrosTotalizacao.Remove(parametro); + this.ParametrosTotalizacaoAdicionados.Add(parametro); + this.SelectedParametrosTotalizacao = this.ParametrosTotalizacao[0]; + } + } + + private void AllSelectedChanged(int tipo) + { + if (this._allSelectedChanging) + { + return; + } + try + { + this._alterandoFiltros = true; + this._allSelectedChanging = true; + switch (tipo) + { + case 0: + { + if (this.AllSelectedSeguradora.HasValue) + { + List.Enumerator enumerator = this.Seguradoras.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + enumerator.Current.set_Selecionado(this.AllSelectedSeguradora.Value); + } + break; + } + finally + { + ((IDisposable)enumerator).Dispose(); + } + } + else + { + return; + } + break; + } + case 1: + { + if (this.AllSelectedRamo.HasValue) + { + List.Enumerator enumerator1 = this.Ramos.GetEnumerator(); + try + { + while (enumerator1.MoveNext()) + { + enumerator1.Current.set_Selecionado(this.AllSelectedRamo.Value); + } + break; + } + finally + { + ((IDisposable)enumerator1).Dispose(); + } + } + else + { + return; + } + break; + } + case 2: + { + if (this.AllSelectedVendedor.HasValue) + { + List.Enumerator enumerator2 = this.Vendedores.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + enumerator2.Current.set_Selecionado(this.AllSelectedVendedor.Value); + } + break; + } + finally + { + ((IDisposable)enumerator2).Dispose(); + } + } + else + { + return; + } + break; + } + case 3: + { + if (this.AllSelectedStatus.HasValue) + { + List.Enumerator enumerator3 = this.TipoSeguros.GetEnumerator(); + try + { + while (enumerator3.MoveNext()) + { + enumerator3.Current.set_Selecionado(this.AllSelectedStatus.Value); + } + break; + } + finally + { + ((IDisposable)enumerator3).Dispose(); + } + } + else + { + return; + } + break; + } + case 4: + { + if (this.AllSelectedTipoVendedor.HasValue) + { + List.Enumerator enumerator4 = this.TipoVendedor.GetEnumerator(); + try + { + while (enumerator4.MoveNext()) + { + enumerator4.Current.set_Selecionado(this.AllSelectedTipoVendedor.Value); + } + break; + } + finally + { + ((IDisposable)enumerator4).Dispose(); + } + } + else + { + return; + } + break; + } + case 5: + { + if (this.AllSelectedNegocio.HasValue) + { + List.Enumerator enumerator5 = this.Negocios.GetEnumerator(); + try + { + while (enumerator5.MoveNext()) + { + enumerator5.Current.set_Selecionado(this.AllSelectedNegocio.Value); + } + break; + } + finally + { + ((IDisposable)enumerator5).Dispose(); + } + } + else + { + return; + } + break; + } + case 6: + { + if (this.AllSelectedProduto.HasValue) + { + List.Enumerator enumerator6 = this.Produtos.GetEnumerator(); + try + { + while (enumerator6.MoveNext()) + { + enumerator6.Current.set_Selecionado(this.AllSelectedProduto.Value); + } + break; + } + finally + { + ((IDisposable)enumerator6).Dispose(); + } + } + else + { + return; + } + break; + } + case 7: + { + if (this.AllSelectedEstipulante.HasValue) + { + List.Enumerator enumerator7 = this.Estipulantes.GetEnumerator(); + try + { + while (enumerator7.MoveNext()) + { + enumerator7.Current.set_Selecionado(this.AllSelectedEstipulante.Value); + } + break; + } + finally + { + ((IDisposable)enumerator7).Dispose(); + } + } + else + { + return; + } + break; + } + } + this._alterandoFiltros = false; + this.AdicionarFiltros(); + } + finally + { + this._allSelectedChanging = false; + } + } + + public void Bind() + { + ((GridRelatorio)this.Report).DataGrid.CancelEdit(); + ((GridRelatorio)this.Report).DataGrid.CancelEdit(); + switch (this.Relatorio) + { + case 0: + case 1: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.ClientesAtivosInativosFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 2: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.ProducaoFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 3: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.ApolicePendenteFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 4: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.RenovacaoFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 5: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.ComissaoFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 6: + case 16: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.PendenteFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 7: + case 11: + case 20: + case 21: + case 22: + { + return; + } + case 8: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.AuditoriaFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 9: + case 10: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.SinistroFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 12: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.FaturaPendenteFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 13: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.ExtratosFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 14: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.MetaSeguradoraFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 15: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.MetaVendedorFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 17: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.LicenciamentoFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 18: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.TarefaFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 19: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.NotaFiscalFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 23: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.LogsEnvioFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 24: + case 25: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.LogUtilizacaoFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 26: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.ApoliceCriticaFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 27: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.PlacaFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 28: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.EndossoFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 29: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.ClassificacaoFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + default: + { + return; + } + } + } + + public async Task CarregarAjuda() + { + if (!this.Ajuda.Any((AjudaTela x) => x.get_Tela() == int.Parse(EnumHelper.GetOldValue(this.Relatorio)))) + { + this.CarregandoAjuda = true; + List ajudaTelas = await Gestor.Application.Helpers.Connection.Get>(string.Format("Help/{0}", int.Parse(EnumHelper.GetOldValue(this.Relatorio))), true, false); + if (ajudaTelas != null) + { + this.Ajuda = new ObservableCollection(ajudaTelas); + this.CarregandoAjuda = false; + } + } + } + + public async Task CarregarConfiguracoes() + { + List parametrosRelatorios = new List(); + List parametrosRelatorios1 = await (new ConfuguracoesServico()).BuscarParametros(this.Relatorio); + switch (this.Relatorio) + { + case 0: + case 1: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 2: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 3: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 4: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 5: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 6: + case 16: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 7: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 8: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 9: + case 10: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 11: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 12: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 13: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 14: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 15: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 17: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 18: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 19: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 20: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 21: + case 22: + { + this.ParametrosRelatorio = new ObservableCollection(parametrosRelatorios); + RelatorioViewModel observableCollection = this; + List parametrosRelatorios2 = parametrosRelatorios1; + observableCollection.ParametrosRelatorioAdicionados = new ObservableCollection( + from x in parametrosRelatorios2 + orderby x.get_Ordem() + select x); + List parametrosTotalizacaos = await (new ConfuguracoesServico()).BuscarParametroTotalizacaoAsync(this.Relatorio); + this.ParametrosTotalizacao = new ObservableCollection(Funcoes.TotalizacoesRelatorio(this.Relatorio, parametrosTotalizacaos)); + this.ParametrosTotalizacaoAdicionados = new ObservableCollection(parametrosTotalizacaos); + break; + } + case 23: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 24: + case 25: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 26: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 27: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 28: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 29: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + default: + { + goto case 22; + } + } + parametrosRelatorios = null; + } + + public async Task> CriarLista() + { + List malaDiretas1 = await Task.Run>(() => { + Gestor.Model.Common.Relatorio relatorio = this.Relatorio; + switch (relatorio) + { + case 0: + { + if (this.ClientesAtivosInativosFiltrado != null && this.ClientesAtivosInativosFiltrado.Count != 0) + { + if (this.ClientesAtivosInativosFiltrado.Any((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => x.get_Selecionado())) + { + return ( + from x in this.ClientesAtivosInativosFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => { + MalaDireta malaDiretum = new MalaDireta(); + Cliente cliente = new Cliente(); + cliente.set_Id(x.get_Id()); + cliente.set_Nome(x.get_Nome()); + cliente.set_Nascimento(x.get_Nascimento()); + cliente.set_Documento(x.get_Documento()); + cliente.set_VencimentoHabilitacao(x.get_VencimentoCnh()); + cliente.set_NomeSocialRg(x.get_EntidadeCliente().get_NomeSocialRg()); + cliente.set_MalaDireta(x.get_EntidadeCliente().get_MalaDireta()); + malaDiretum.set_Cliente(cliente); + malaDiretum.set_Tela(1); + malaDiretum.set_Relatorio(this.Relatorio); + return malaDiretum; + }).ToList(); + } + } + return new List(); + } + case 1: + { + if (this.ClientesAtivosInativosFiltrado != null && this.ClientesAtivosInativosFiltrado.Count != 0) + { + if (this.ClientesAtivosInativosFiltrado.Any((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => x.get_Selecionado())) + { + return ( + from x in this.ClientesAtivosInativosFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => { + MalaDireta malaDiretum = new MalaDireta(); + Cliente cliente = new Cliente(); + cliente.set_Id(x.get_Id()); + cliente.set_Nome(x.get_Nome()); + cliente.set_Nascimento(x.get_Nascimento()); + cliente.set_Documento(x.get_Documento()); + cliente.set_VencimentoHabilitacao(x.get_VencimentoCnh()); + cliente.set_MalaDireta(x.get_EntidadeCliente().get_MalaDireta()); + malaDiretum.set_Cliente(cliente); + malaDiretum.set_Tela(1); + malaDiretum.set_Relatorio(this.Relatorio); + return malaDiretum; + }).ToList(); + } + } + return new List(); + } + case 2: + { + if (this.ProducaoFiltrado != null && this.ProducaoFiltrado.Count != 0) + { + if (this.ProducaoFiltrado.Any((Gestor.Model.Domain.Relatorios.Producao.Producao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Documento() != null; + })) + { + return this.ProducaoFiltrado.Where((Gestor.Model.Domain.Relatorios.Producao.Producao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Documento() != null; + }).Select((Gestor.Model.Domain.Relatorios.Producao.Producao x) => { + MalaDireta malaDiretum = new MalaDireta(); + malaDiretum.set_Cliente(x.get_Documento().get_Controle().get_Cliente()); + malaDiretum.set_Apolice(x.get_Documento()); + Item item = new Item(); + item.set_Descricao(x.get_Item()); + malaDiretum.set_Item(item); + malaDiretum.set_Tela(2); + malaDiretum.set_Relatorio(this.Relatorio); + return malaDiretum; + }).ToList(); + } + } + return new List(); + } + case 3: + { + if (this.ApolicePendenteFiltrado != null && this.ApolicePendenteFiltrado.Count != 0) + { + if (this.ApolicePendenteFiltrado.Any((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Documento() != null; + })) + { + return this.ApolicePendenteFiltrado.Where((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Documento() != null; + }).Select((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => { + MalaDireta malaDiretum = new MalaDireta(); + malaDiretum.set_Cliente(x.get_Documento().get_Controle().get_Cliente()); + malaDiretum.set_Apolice(x.get_Documento()); + Item item = new Item(); + item.set_Descricao(x.get_Item()); + malaDiretum.set_Item(item); + malaDiretum.set_Tela(2); + malaDiretum.set_Relatorio(this.Relatorio); + return malaDiretum; + }).ToList(); + } + } + return new List(); + } + case 4: + { + if (this.RenovacaoFiltrado != null && this.RenovacaoFiltrado.Count != 0) + { + if (this.RenovacaoFiltrado.Any((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.get_Selecionado())) + { + List list = this.RenovacaoFiltrado.Where((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Documento() != null; + }).Select((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => { + MalaDireta malaDiretum = new MalaDireta(); + malaDiretum.set_Cliente(x.get_Documento().get_Controle().get_Cliente()); + malaDiretum.set_Apolice(x.get_Documento()); + malaDiretum.set_Tela(2); + Item item = new Item(); + item.set_Descricao(x.get_Item()); + malaDiretum.set_Item(item); + malaDiretum.set_Relatorio(this.Relatorio); + return malaDiretum; + }).ToList(); + List malaDiretas = this.RenovacaoFiltrado.Where((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Prospeccao() != null; + }).Select((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => { + MalaDireta malaDiretum = new MalaDireta(); + Cliente cliente = new Cliente(); + cliente.set_Nome(x.get_Prospeccao().get_Nome()); + cliente.set_Id((long)0); + malaDiretum.set_Cliente(cliente); + malaDiretum.set_Prospeccao(x.get_Prospeccao()); + malaDiretum.set_Tela(33); + Item item = new Item(); + item.set_Descricao(x.get_Item()); + malaDiretum.set_Item(item); + malaDiretum.set_Relatorio(this.Relatorio); + return malaDiretum; + }).ToList(); + if (malaDiretas.Count > 0) + { + list.AddRange(malaDiretas); + } + return list; + } + } + return new List(); + } + case 5: + { + if (this.ComissaoFiltrado != null && this.ComissaoFiltrado.Count != 0) + { + if (this.ComissaoFiltrado.Any((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Documento() != null; + })) + { + return this.ComissaoFiltrado.Where((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Documento() != null; + }).Select((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => { + MalaDireta malaDiretum = new MalaDireta(); + malaDiretum.set_Cliente(x.get_Documento().get_Controle().get_Cliente()); + malaDiretum.set_Apolice(x.get_Documento()); + malaDiretum.set_Parcela(x.get_ParcelaEntity()); + Item item = new Item(); + item.set_Descricao(x.get_Item()); + malaDiretum.set_Item(item); + malaDiretum.set_Tela(5); + malaDiretum.set_Relatorio(this.Relatorio); + return malaDiretum; + }).ToList(); + } + } + return new List(); + } + case 6: + case 16: + { + if (this.PendenteFiltrado != null && this.PendenteFiltrado.Count != 0) + { + if (this.PendenteFiltrado.Any((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Documento() != null; + })) + { + return this.PendenteFiltrado.Where((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Documento() != null; + }).Select((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => { + MalaDireta malaDiretum = new MalaDireta(); + malaDiretum.set_Cliente(x.get_Documento().get_Controle().get_Cliente()); + malaDiretum.set_Apolice(x.get_Documento()); + Item item = new Item(); + item.set_Descricao(x.get_Item()); + malaDiretum.set_Item(item); + malaDiretum.set_Parcela(x.get_ParcelaEntity()); + malaDiretum.set_Tela(5); + malaDiretum.set_Relatorio(this.Relatorio); + return malaDiretum; + }).ToList(); + } + } + return new List(); + } + case 7: + case 8: + case 11: + case 12: + case 13: + case 14: + case 15: + { + return null; + } + case 9: + case 10: + { + if (this.SinistroFiltrado != null && this.SinistroFiltrado.Count != 0) + { + if (this.SinistroFiltrado.Any((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_Selecionado())) + { + return ( + from x in this.SinistroFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => { + MalaDireta malaDiretum = new MalaDireta(); + malaDiretum.set_Cliente(x.get_Cliente()); + malaDiretum.set_Apolice(x.get_Documento()); + Item item = new Item(); + item.set_Descricao(x.get_Item()); + malaDiretum.set_Item(item); + malaDiretum.set_Sinistro(x.get_EntidadeSinistro()); + malaDiretum.set_Tela(7); + malaDiretum.set_Relatorio(this.Relatorio); + return malaDiretum; + }).ToList(); + } + } + return new List(); + } + case 17: + { + if (this.LicenciamentoFiltrado != null && this.LicenciamentoFiltrado.Count != 0) + { + if (this.LicenciamentoFiltrado.Any((Gestor.Model.Domain.Relatorios.Licenciamento.Licenciamento x) => x.get_Selecionado())) + { + return ( + from x in this.LicenciamentoFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.Licenciamento.Licenciamento x) => { + MalaDireta malaDiretum = new MalaDireta(); + malaDiretum.set_Cliente(x.get_Documento().get_Controle().get_Cliente()); + malaDiretum.set_Apolice(x.get_Documento()); + malaDiretum.set_Item(x.get_EntidadeItem()); + malaDiretum.set_Tela(3); + malaDiretum.set_Relatorio(this.Relatorio); + return malaDiretum; + }).ToList(); + } + } + return new List(); + } + default: + { + if (relatorio == 26) + { + if (this.ApoliceCriticaFiltrado != null && this.ApoliceCriticaFiltrado.Count != 0) + { + if (this.ApoliceCriticaFiltrado.Any((Gestor.Model.Domain.Relatorios.CriticaApolice.ApoliceCritica x) => x.get_Selecionado())) + { + return ( + from x in this.ApoliceCriticaFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.CriticaApolice.ApoliceCritica x) => { + MalaDireta malaDiretum = new MalaDireta(); + malaDiretum.set_Cliente(x.get_Critica().get_Documento().get_Controle().get_Cliente()); + malaDiretum.set_Apolice(x.get_Critica().get_Documento()); + malaDiretum.set_Tela(2); + Item item = new Item(); + item.set_Descricao((x.get_Critica().get_Documento().get_ItensAtivo() != null ? (x.get_Critica().get_Documento().get_ItensAtivo().Count > 1 ? "APÓLICE COLETIVA" : (x.get_Critica().get_Documento().get_ItensAtivo().Count == 1 ? x.get_Critica().get_Documento().get_ItensAtivo().First().get_Descricao() : "")) : "")); + malaDiretum.set_Item(item); + malaDiretum.set_Relatorio(this.Relatorio); + return malaDiretum; + }).ToList(); + } + } + return new List(); + } + return null; + } + } + }); + return malaDiretas1; + } + + public async Task> CriarListaEtiqueta() + { + List documentos = await Task.Run>(() => { + switch (this.Relatorio) + { + case 0: + { + if (this.ClientesAtivosInativosFiltrado != null && this.ClientesAtivosInativosFiltrado.Count != 0) + { + if (this.ClientesAtivosInativosFiltrado.Any((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => x.get_Selecionado())) + { + return ( + from x in this.ClientesAtivosInativosFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => { + Documento documento = new Documento(); + Controle controle = new Controle(); + Cliente cliente = new Cliente(); + cliente.set_Id(x.get_Id()); + cliente.set_Nome(x.get_Nome()); + controle.set_Cliente(cliente); + documento.set_Controle(controle); + return documento; + }).ToList(); + } + } + return null; + } + case 1: + { + if (this.ClientesAtivosInativosFiltrado != null && this.ClientesAtivosInativosFiltrado.Count != 0) + { + if (this.ClientesAtivosInativosFiltrado.Any((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => x.get_Selecionado())) + { + return ( + from x in this.ClientesAtivosInativosFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => { + Documento documento = new Documento(); + Controle controle = new Controle(); + Cliente cliente = new Cliente(); + cliente.set_Id(x.get_Id()); + cliente.set_Nome(x.get_Nome()); + controle.set_Cliente(cliente); + documento.set_Controle(controle); + return documento; + }).ToList(); + } + } + return null; + } + case 2: + { + if (this.Producao != null && this.Producao.Count != 0) + { + if (this.Producao.Any((Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Selecionado())) + { + return ( + from x in this.Producao + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.Producao.Producao x) => { + Documento documento = new Documento(); + documento.set_Id(x.get_Documento().get_Id()); + documento.set_Vigencia1(x.get_Documento().get_Vigencia1()); + documento.set_Vigencia2(x.get_Documento().get_Vigencia2()); + documento.set_Apolice(x.get_Documento().get_Apolice()); + documento.set_Endosso(x.get_Documento().get_Endosso()); + documento.set_VendedorPrincipal(x.get_Documento().get_VendedorPrincipal()); + Controle controle = new Controle(); + Seguradora seguradora = new Seguradora(); + seguradora.set_Id(x.get_Documento().get_Controle().get_Seguradora().get_Id()); + seguradora.set_Nome(x.get_Documento().get_Controle().get_Seguradora().get_Nome()); + controle.set_Seguradora(seguradora); + Ramo ramo = new Ramo(); + ramo.set_Id(x.get_Documento().get_Controle().get_Ramo().get_Id()); + ramo.set_Nome(x.get_Documento().get_Controle().get_Ramo().get_Nome()); + controle.set_Ramo(ramo); + Cliente cliente = new Cliente(); + cliente.set_Id(x.get_Documento().get_Controle().get_Cliente().get_Id()); + cliente.set_Nome(x.get_Documento().get_Controle().get_Cliente().get_Nome()); + controle.set_Cliente(cliente); + documento.set_Controle(controle); + return documento; + }).ToList(); + } + } + return null; + } + case 3: + { + if (this.ApolicePendente != null && this.ApolicePendente.Count != 0) + { + if (this.ApolicePendente.Any((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => x.get_Selecionado())) + { + return ( + from x in this.ApolicePendente + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => { + Documento documento = new Documento(); + documento.set_Id(x.get_Documento().get_Id()); + documento.set_Vigencia1(x.get_Documento().get_Vigencia1()); + documento.set_Vigencia2(x.get_Documento().get_Vigencia2()); + documento.set_Apolice(x.get_Documento().get_Apolice()); + documento.set_Endosso(x.get_Documento().get_Endosso()); + documento.set_VendedorPrincipal(x.get_Documento().get_VendedorPrincipal()); + Controle controle = new Controle(); + Seguradora seguradora = new Seguradora(); + seguradora.set_Id(x.get_Documento().get_Controle().get_Seguradora().get_Id()); + seguradora.set_Nome(x.get_Documento().get_Controle().get_Seguradora().get_Nome()); + controle.set_Seguradora(seguradora); + Ramo ramo = new Ramo(); + ramo.set_Id(x.get_Documento().get_Controle().get_Ramo().get_Id()); + ramo.set_Nome(x.get_Documento().get_Controle().get_Ramo().get_Nome()); + controle.set_Ramo(ramo); + Cliente cliente = new Cliente(); + cliente.set_Id(x.get_Documento().get_Controle().get_Cliente().get_Id()); + cliente.set_Nome(x.get_Documento().get_Controle().get_Cliente().get_Nome()); + controle.set_Cliente(cliente); + documento.set_Controle(controle); + return documento; + }).ToList(); + } + } + return null; + } + case 4: + { + if (this.RenovacaoFiltrado != null && this.RenovacaoFiltrado.Count != 0) + { + if (this.RenovacaoFiltrado.Any((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.get_Selecionado())) + { + return ( + from x in this.RenovacaoFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => { + Vendedor vendedor; + Seguradora seguradora; + Ramo ramo; + Cliente cliente; + Documento documento = new Documento(); + documento.set_Id((x.get_Apolice() == "PROSPECÇÃO" ? x.get_Prospeccao().get_Id() : x.get_Documento().get_Id())); + documento.set_Vigencia1((x.get_Apolice() == "PROSPECÇÃO" ? new DateTime() : x.get_Documento().get_Vigencia1())); + documento.set_Vigencia2(x.get_VigenciaFinal()); + documento.set_Apolice(x.get_Apolice()); + documento.set_Endosso((x.get_Apolice() == "PROSPECÇÃO" ? "" : x.get_Documento().get_Endosso())); + if (x.get_Apolice() == "PROSPECÇÃO") + { + vendedor = new Vendedor(); + vendedor.set_Nome(x.get_Vendedor()); + } + else + { + vendedor = x.get_Documento().get_VendedorPrincipal(); + } + documento.set_VendedorPrincipal(vendedor); + Controle controle = new Controle(); + if (x.get_Apolice() == "PROSPECÇÃO") + { + seguradora = new Seguradora(); + } + else + { + seguradora = new Seguradora(); + seguradora.set_Id(x.get_Documento().get_Controle().get_Seguradora().get_Id()); + seguradora.set_Nome(x.get_Documento().get_Controle().get_Seguradora().get_Nome()); + } + controle.set_Seguradora(seguradora); + if (x.get_Apolice() == "PROSPECÇÃO") + { + ramo = new Ramo(); + } + else + { + ramo = new Ramo(); + ramo.set_Id(x.get_Documento().get_Controle().get_Ramo().get_Id()); + ramo.set_Nome(x.get_Documento().get_Controle().get_Ramo().get_Nome()); + } + controle.set_Ramo(ramo); + if (x.get_Apolice() == "PROSPECÇÃO") + { + cliente = new Cliente(); + cliente.set_Nome(x.get_Cliente()); + } + else + { + cliente = new Cliente(); + cliente.set_Id(x.get_Documento().get_Controle().get_Cliente().get_Id()); + cliente.set_Nome(x.get_Documento().get_Controle().get_Cliente().get_Nome()); + } + controle.set_Cliente(cliente); + documento.set_Controle(controle); + List items = new List(); + Item item = new Item(); + item.set_Descricao(x.get_Item()); + items.Add(item); + documento.set_ItensAtivo(items); + return documento; + }).ToList(); + } + } + return null; + } + case 5: + { + if (this.ComissaoFiltrado != null && this.ComissaoFiltrado.Count != 0) + { + if (this.ComissaoFiltrado.Any((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Selecionado())) + { + return ( + from x in this.ComissaoFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => { + Documento documento = new Documento(); + documento.set_Id(x.get_Documento().get_Id()); + documento.set_Vigencia1(x.get_Documento().get_Vigencia1()); + documento.set_Vigencia2(x.get_Documento().get_Vigencia2()); + documento.set_Apolice(x.get_Documento().get_Apolice()); + documento.set_Endosso(x.get_Documento().get_Endosso()); + documento.set_VendedorPrincipal(x.get_Documento().get_VendedorPrincipal()); + Controle controle = new Controle(); + Seguradora seguradora = new Seguradora(); + seguradora.set_Id(x.get_Documento().get_Controle().get_Seguradora().get_Id()); + seguradora.set_Nome(x.get_Documento().get_Controle().get_Seguradora().get_Nome()); + controle.set_Seguradora(seguradora); + Ramo ramo = new Ramo(); + ramo.set_Id(x.get_Documento().get_Controle().get_Ramo().get_Id()); + ramo.set_Nome(x.get_Documento().get_Controle().get_Ramo().get_Nome()); + controle.set_Ramo(ramo); + Cliente cliente = new Cliente(); + cliente.set_Id(x.get_Documento().get_Controle().get_Cliente().get_Id()); + cliente.set_Nome(x.get_Documento().get_Controle().get_Cliente().get_Nome()); + controle.set_Cliente(cliente); + documento.set_Controle(controle); + return documento; + }).ToList(); + } + } + return null; + } + case 6: + case 16: + { + if (this.PendenteFiltrado != null && this.PendenteFiltrado.Count != 0) + { + if (this.PendenteFiltrado.Any((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_Selecionado())) + { + return ( + from x in this.PendenteFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => { + Documento documento = new Documento(); + documento.set_Id(x.get_Documento().get_Id()); + documento.set_Vigencia1(x.get_Documento().get_Vigencia1()); + documento.set_Vigencia2(x.get_Documento().get_Vigencia2()); + documento.set_Apolice(x.get_Documento().get_Apolice()); + documento.set_Endosso(x.get_Documento().get_Endosso()); + documento.set_VendedorPrincipal(x.get_Documento().get_VendedorPrincipal()); + Controle controle = new Controle(); + Seguradora seguradora = new Seguradora(); + seguradora.set_Id(x.get_Documento().get_Controle().get_Seguradora().get_Id()); + seguradora.set_Nome(x.get_Documento().get_Controle().get_Seguradora().get_Nome()); + controle.set_Seguradora(seguradora); + Ramo ramo = new Ramo(); + ramo.set_Id(x.get_Documento().get_Controle().get_Ramo().get_Id()); + ramo.set_Nome(x.get_Documento().get_Controle().get_Ramo().get_Nome()); + controle.set_Ramo(ramo); + Cliente cliente = new Cliente(); + cliente.set_Id(x.get_Documento().get_Controle().get_Cliente().get_Id()); + cliente.set_Nome(x.get_Documento().get_Controle().get_Cliente().get_Nome()); + controle.set_Cliente(cliente); + documento.set_Controle(controle); + return documento; + }).ToList(); + } + } + return null; + } + case 7: + case 11: + case 13: + case 14: + case 15: + { + return null; + } + case 8: + { + if (this.Auditoria != null && this.Auditoria.Count != 0) + { + if (this.Auditoria.Any((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => x.get_Selecionado())) + { + return ( + from x in this.Auditoria + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => { + Documento documento = new Documento(); + documento.set_Id(x.get_Documento().get_Id()); + documento.set_Vigencia1(x.get_Documento().get_Vigencia1()); + documento.set_Vigencia2(x.get_Documento().get_Vigencia2()); + documento.set_Apolice(x.get_Documento().get_Apolice()); + documento.set_Endosso(x.get_Documento().get_Endosso()); + documento.set_VendedorPrincipal(x.get_Documento().get_VendedorPrincipal()); + Controle controle = new Controle(); + Seguradora seguradora = new Seguradora(); + seguradora.set_Id(x.get_Documento().get_Controle().get_Seguradora().get_Id()); + seguradora.set_Nome(x.get_Documento().get_Controle().get_Seguradora().get_Nome()); + controle.set_Seguradora(seguradora); + Ramo ramo = new Ramo(); + ramo.set_Id(x.get_Documento().get_Controle().get_Ramo().get_Id()); + ramo.set_Nome(x.get_Documento().get_Controle().get_Ramo().get_Nome()); + controle.set_Ramo(ramo); + Cliente cliente = new Cliente(); + cliente.set_Id(x.get_Documento().get_Controle().get_Cliente().get_Id()); + cliente.set_Nome(x.get_Documento().get_Controle().get_Cliente().get_Nome()); + controle.set_Cliente(cliente); + documento.set_Controle(controle); + return documento; + }).ToList(); + } + } + return null; + } + case 9: + { + if (this.Sinistro != null && this.Sinistro.Count != 0) + { + if (this.Sinistro.Any((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_Selecionado())) + { + return ( + from x in this.Sinistro + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => { + Documento documento = new Documento(); + documento.set_Id(x.get_Documento().get_Id()); + documento.set_Vigencia1(x.get_Documento().get_Vigencia1()); + documento.set_Vigencia2(x.get_Documento().get_Vigencia2()); + documento.set_Apolice(x.get_Documento().get_Apolice()); + documento.set_Endosso(x.get_Documento().get_Endosso()); + documento.set_VendedorPrincipal(x.get_Documento().get_VendedorPrincipal()); + Controle controle = new Controle(); + Seguradora seguradora = new Seguradora(); + seguradora.set_Id(x.get_Documento().get_Controle().get_Seguradora().get_Id()); + seguradora.set_Nome(x.get_Documento().get_Controle().get_Seguradora().get_Nome()); + controle.set_Seguradora(seguradora); + Ramo ramo = new Ramo(); + ramo.set_Id(x.get_Documento().get_Controle().get_Ramo().get_Id()); + ramo.set_Nome(x.get_Documento().get_Controle().get_Ramo().get_Nome()); + controle.set_Ramo(ramo); + Cliente cliente = new Cliente(); + cliente.set_Id(x.get_Documento().get_Controle().get_Cliente().get_Id()); + cliente.set_Nome(x.get_Documento().get_Controle().get_Cliente().get_Nome()); + controle.set_Cliente(cliente); + documento.set_Controle(controle); + return documento; + }).ToList(); + } + } + return null; + } + case 10: + { + if (this.Sinistro != null && this.Sinistro.Count != 0) + { + if (this.Sinistro.Any((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_Selecionado())) + { + return ( + from x in this.Sinistro + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => { + Documento documento = new Documento(); + documento.set_Id(x.get_Documento().get_Id()); + documento.set_Vigencia1(x.get_Documento().get_Vigencia1()); + documento.set_Vigencia2(x.get_Documento().get_Vigencia2()); + documento.set_Apolice(x.get_Documento().get_Apolice()); + documento.set_Endosso(x.get_Documento().get_Endosso()); + documento.set_VendedorPrincipal(x.get_Documento().get_VendedorPrincipal()); + Controle controle = new Controle(); + Seguradora seguradora = new Seguradora(); + seguradora.set_Id(x.get_Documento().get_Controle().get_Seguradora().get_Id()); + seguradora.set_Nome(x.get_Documento().get_Controle().get_Seguradora().get_Nome()); + controle.set_Seguradora(seguradora); + Ramo ramo = new Ramo(); + ramo.set_Id(x.get_Documento().get_Controle().get_Ramo().get_Id()); + ramo.set_Nome(x.get_Documento().get_Controle().get_Ramo().get_Nome()); + controle.set_Ramo(ramo); + Cliente cliente = new Cliente(); + cliente.set_Id(x.get_Documento().get_Controle().get_Cliente().get_Id()); + cliente.set_Nome(x.get_Documento().get_Controle().get_Cliente().get_Nome()); + controle.set_Cliente(cliente); + documento.set_Controle(controle); + return documento; + }).ToList(); + } + } + return null; + } + case 12: + { + if (this.FaturaPendenteFiltrado != null && this.FaturaPendenteFiltrado.Count != 0) + { + if (this.FaturaPendenteFiltrado.Any((Gestor.Model.Domain.Relatorios.FaturaPendente.FaturaPendente x) => x.get_Selecionado())) + { + return ( + from x in this.FaturaPendenteFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.FaturaPendente.FaturaPendente x) => { + Documento documento = new Documento(); + documento.set_Id(x.get_Documento().get_Id()); + documento.set_Vigencia1(x.get_Documento().get_Vigencia1()); + documento.set_Vigencia2(x.get_Documento().get_Vigencia2()); + documento.set_Apolice(x.get_Documento().get_Apolice()); + documento.set_Endosso(x.get_Documento().get_Endosso()); + documento.set_VendedorPrincipal(x.get_Documento().get_VendedorPrincipal()); + Controle controle = new Controle(); + Seguradora seguradora = new Seguradora(); + seguradora.set_Id(x.get_Documento().get_Controle().get_Seguradora().get_Id()); + seguradora.set_Nome(x.get_Documento().get_Controle().get_Seguradora().get_Nome()); + controle.set_Seguradora(seguradora); + Ramo ramo = new Ramo(); + ramo.set_Id(x.get_Documento().get_Controle().get_Ramo().get_Id()); + ramo.set_Nome(x.get_Documento().get_Controle().get_Ramo().get_Nome()); + controle.set_Ramo(ramo); + Cliente cliente = new Cliente(); + cliente.set_Id(x.get_Documento().get_Controle().get_Cliente().get_Id()); + cliente.set_Nome(x.get_Documento().get_Controle().get_Cliente().get_Nome()); + controle.set_Cliente(cliente); + documento.set_Controle(controle); + return documento; + }).ToList(); + } + } + return null; + } + default: + { + return null; + } + } + }); + return documentos; + } + + public void DescerParametro(Gestor.Model.Domain.Relatorios.ParametrosRelatorio parametro) + { + if (parametro == null) + { + return; + } + int num = this.ParametrosRelatorioAdicionados.IndexOf(parametro); + if (num == this.ParametrosRelatorioAdicionados.Count - 1) + { + return; + } + this.ParametrosRelatorioAdicionados.Move(num, num + 1); + } + + private void EstipulanteOnPropertyChanged(object sender, PropertyChangedEventArgs args) + { + if (this._alterandoFiltros) + { + return; + } + this.RecheckAllSelected(6); + } + + public void ExcluirParametro(Gestor.Model.Domain.Relatorios.ParametrosRelatorio parametro) + { + if (parametro == null) + { + return; + } + this.ParametrosRelatorioAdicionados.Remove(parametro); + this.ParametrosRelatorio.Add(parametro); + this.ParametrosRelatorio = new ObservableCollection( + from x in this.ParametrosRelatorio + orderby x.get_Header() + select x); + } + + public void ExcluirTotalizacao(Gestor.Model.Domain.Relatorios.ParametrosTotalizacao parametro) + { + if (parametro == null) + { + return; + } + this.ParametrosTotalizacaoAdicionados.Remove(parametro); + this.ParametrosTotalizacao.Add(parametro); + this.ParametrosTotalizacao = new ObservableCollection( + from x in this.ParametrosTotalizacao + orderby x.get_Header() + select x); + } + + public async void ExibirExtratoDrawer() + { + List documentos = new List(); + List prospeccaos = new List(); + List clientesAtivosInativos = new List(); + List nums = new List(); + List nums1 = new List(); + switch (this.Relatorio) + { + case 0: + { + foreach (Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos list in ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList()) + { + Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos clientesAtivosInativo = new Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos(); + clientesAtivosInativo.set_Id(list.get_Id()); + clientesAtivosInativo.set_Nome(list.get_Nome()); + clientesAtivosInativo.set_Documento(list.get_Documento()); + clientesAtivosInativo.set_Selecionado(list.get_Selecionado()); + clientesAtivosInativos.Add(clientesAtivosInativo); + } + base.ShowDrawer(new ExtratosDrawer(clientesAtivosInativos, null, new Gestor.Model.Common.Relatorio?(this.Relatorio), null, null, null), 0, false); + break; + } + case 1: + case 3: + { + if (nums.Count != 0 || nums1.Count != 0) + { + base.ShowDrawer(new ExtratosDrawer(null, documentos, new Gestor.Model.Common.Relatorio?(this.Relatorio), nums, nums1, prospeccaos), 0, false); + break; + } + else + { + await base.ShowMessage("É NECESSÁRIO HAVER AO MENOS UM DOCUMENTO SELECIONADO", "OK", "", false); + break; + } + } + case 2: + { + List.Enumerator enumerator = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList().GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Gestor.Model.Domain.Relatorios.Producao.Producao current = enumerator.Current; + documentos.Add(current.get_Documento()); + if (!current.get_Selecionado()) + { + continue; + } + nums.Add(current.get_Documento().get_Id()); + } + goto case 3; + } + finally + { + ((IDisposable)enumerator).Dispose(); + } + break; + } + case 4: + { + List.Enumerator enumerator1 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList().GetEnumerator(); + try + { + while (enumerator1.MoveNext()) + { + Gestor.Model.Domain.Relatorios.Renovacao.Renovacao renovacao = enumerator1.Current; + if (renovacao.get_Documento() != null) + { + documentos.Add(renovacao.get_Documento()); + if (renovacao.get_Selecionado()) + { + nums.Add(renovacao.get_Documento().get_Id()); + } + } + if (renovacao.get_Prospeccao() == null) + { + continue; + } + prospeccaos.Add(renovacao.get_Prospeccao()); + if (!renovacao.get_Selecionado()) + { + continue; + } + nums1.Add(renovacao.get_Prospeccao().get_Id()); + } + goto case 3; + } + finally + { + ((IDisposable)enumerator1).Dispose(); + } + break; + } + default: + { + goto case 3; + } + } + } + + private void Filtrar() + { + this.Seguradoras = Recursos.Seguradoras.Where((Seguradora x) => { + if (!x.get_Ativo()) + { + return false; + } + return x.get_Nome().Contains(this.Filtro); + }).OrderBy((Seguradora x) => x.get_Nome()).ToList(); + this.Ramos = Recursos.Ramos.Where((Ramo x) => { + if (!x.get_Ativo()) + { + return false; + } + return x.get_Nome().Contains(this.Filtro); + }).OrderBy((Ramo x) => x.get_Nome()).ToList(); + this.Estipulantes = Recursos.Estipulantes.Where((Estipulante x) => { + if (!x.get_Ativo()) + { + return false; + } + return x.get_Nome().Contains(this.Filtro); + }).OrderBy((Estipulante x) => x.get_Nome()).ToList(); + this.Vendedores = (this.Vinculo.Count > 0 ? Recursos.Vendedores.Where((Vendedor x) => { + if (!this.Vinculo.Any((VendedorUsuario y) => y.get_Vendedor().get_Id() == x.get_Id()) || !x.get_Nome().Contains(this.Filtro)) + { + return false; + } + return x.get_Ativo(); + }).OrderBy((Vendedor x) => x.get_Nome()).ToList() : Recursos.Vendedores.Where((Vendedor x) => { + if (!x.get_Nome().Contains(this.Filtro)) + { + return false; + } + if (this.Inativo) + { + return true; + } + return x.get_Ativo(); + }).OrderBy((Vendedor x) => x.get_Nome()).ToList()); + this.TipoVendedor = Recursos.TipoVendedor.Where((Gestor.Model.Domain.Seguros.TipoVendedor x) => { + if (!x.get_Ativo().GetValueOrDefault()) + { + return false; + } + return x.get_Descricao().Contains(this.Filtro); + }).OrderBy((Gestor.Model.Domain.Seguros.TipoVendedor x) => x.get_Descricao()).ToList(); + this.Produtos = Recursos.Produtos.Where((Gestor.Model.Domain.Seguros.Produto x) => { + if (!x.get_Ativo()) + { + return false; + } + return x.get_Nome().Contains(this.Filtro); + }).OrderBy((Gestor.Model.Domain.Seguros.Produto x) => x.get_Nome()).ToList(); + this.TipoSeguros = ( + from x in RelatorioViewModel.TipoSegurosList + where EnumHelper.GetDescription(x.get_Status()).Contains(this.Filtro) + orderby x.get_Status() + select x).ToList(); + this.Negocios = ( + from x in RelatorioViewModel.NegocioList + where EnumHelper.GetDescription(x.get_Negocio()).Contains(this.Filtro) + orderby x.get_Negocio() + select x).ToList(); + } + + internal async Task> Filtrar(string value) + { + List usuarios = await Task.Run>(() => this.FiltrarUsuario(value)); + return usuarios; + } + + private void FiltrarRamo() + { + List filtroPersonalizados = (this.RamosSelecionados == null ? new List() : this.RamosSelecionados.Select((Ramo x) => { + Gestor.Model.Domain.Relatorios.FiltroPersonalizado filtroPersonalizado = new Gestor.Model.Domain.Relatorios.FiltroPersonalizado(); + filtroPersonalizado.set_Nome(x.get_Nome()); + filtroPersonalizado.set_Propriedade("Ramo"); + filtroPersonalizado.set_Tipo(typeof(string)); + filtroPersonalizado.set_ValorIncial(x.get_Nome()); + filtroPersonalizado.set_SemValor(false); + filtroPersonalizado.set_Descricao(x.get_Nome()); + filtroPersonalizado.set_Diferente(true); + return filtroPersonalizado; + }).ToList()); + this.ClientesAtivosInativosFiltrado = new ObservableCollection(this.ClientesAtivosInativos.CustomNot(filtroPersonalizados)); + if (this.FiltroPersonalizadoSelecionado != null) + { + this.ClientesAtivosInativosFiltrado = new ObservableCollection(this.ClientesAtivosInativosFiltrado.ToList().CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), false)); + } + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.ClientesAtivosInativosFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + } + + public List FiltrarUsuario(string filter) + { + this.UsuariosFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Usuarios) : new ObservableCollection( + from x in this.Usuarios + where Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Nome().Trim()).ToUpper().Contains(Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(filter)) + orderby !x.get_Excluido() descending, x.get_Nome() + select x)); + return this.UsuariosFiltrados.ToList(); + } + + public async Task GerarExcel() + { + string str; + Gestor.Model.Common.Agrupamento agrupamento; + Gestor.Model.Common.Agrupamento agrupamento1; + List list; + List producaos; + List list1; + List producaos1; + List list2; + List producaos2; + List list3; + List producaos3; + List list4; + List producaos4; + List list5; + List producaos5; + List apolicePendentes; + List apolicePendentes1; + List apolicePendentes2; + List apolicePendentes3; + List apolicePendentes4; + List apolicePendentes5; + List list6; + List apolicePendentes6; + List list7; + List apolicePendentes7; + List list8; + List renovacaos; + List renovacaos1; + List renovacaos2; + List renovacaos3; + List renovacaos4; + List renovacaos5; + List renovacaos6; + List renovacaos7; + List renovacaos8; + List list9; + List renovacaos9; + List comissaos; + List comissaos1; + List comissaos2; + List comissaos3; + List comissaos4; + List comissaos5; + List comissaos6; + List comissaos7; + List comissaos8; + List comissaos9; + List list10; + List pendentes; + List pendentes1; + List pendentes2; + List pendentes3; + List pendentes4; + List pendentes5; + List pendentes6; + List pendentes7; + List pendentes8; + List pendentes9; + List pendentes10; + List auditorias; + List auditorias1; + List auditorias2; + List auditorias3; + List auditorias4; + List auditorias5; + List auditorias6; + List auditorias7; + List auditorias8; + List auditorias9; + List auditorias10; + List sinistros; + List sinistros1; + List sinistros2; + List sinistros3; + List sinistros4; + List sinistros5; + List sinistros6; + List sinistros7; + List sinistros8; + List sinistros9; + List sinistros10; + List faturaPendentes; + List extratoBaixadoRelatorios; + List metaSeguradoraRelatorios; + List metaVendedorRelatorios; + List licenciamentos; + List tarefas; + List notaFiscalRelatorios; + List logsEnvios; + List logAcaoRelatorios; + List apoliceCriticas; + List placas; + List placas1; + List placas2; + List placas3; + List placas4; + List placas5; + List placas6; + List placas7; + List placas8; + List endossos; + List classificacaos; + XLWorkbook xLWorkbook; + List producaos6; + List strs; + List apolicePendentes8; + List renovacaos10; + List comissaos10; + List list11; + List auditorias11; + List sinistros11; + List placas9; + string tempPath = ""; + string str1 = ""; + List configuracoes = Recursos.Configuracoes; + if (!configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 41)) + { + tempPath = Path.GetTempPath(); + str1 = string.Format("{0}{1}.xlsx", tempPath, Guid.NewGuid()); + } + else + { + using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog()) + { + if (DialogResult.OK == folderBrowserDialog.ShowDialog()) + { + tempPath = string.Concat(folderBrowserDialog.SelectedPath, "\\"); + Directory.CreateDirectory(tempPath); + } + else + { + str1 = null; + xLWorkbook = null; + strs = null; + return; + } + } + string[] description = new string[] { tempPath, EnumHelper.GetDescription(this.Relatorio), " ", null, null }; + DateTime date = Functions.GetNetworkTime().Date; + description[3] = date.ToShortDateString().Replace("/", ""); + description[4] = ".xlsx"; + str1 = string.Concat(description); + } + xLWorkbook = new XLWorkbook(); + int num = 1; + switch (this.Relatorio) + { + case 0: + case 1: + { + List clientesAtivosInativos = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.ClientesAtivosInativosFiltrado == null || clientesAtivosInativos.Count == 0) + { + break; + } + else + { + List clientesAtivosInativos1 = clientesAtivosInativos; + if (clientesAtivosInativos1.Any((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => x.get_Selecionado())) + { + List clientesAtivosInativos2 = clientesAtivosInativos; + list = ( + from x in clientesAtivosInativos2 + where x.get_Selecionado() + select x).ToList(); + } + else + { + list = clientesAtivosInativos; + } + List clientesAtivosInativos3 = list; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", clientesAtivosInativos3, this.Relatorio, true); + goto case 22; + } + } + case 2: + { + producaos6 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.ProducaoFiltrado == null || producaos6.Count == 0) + { + break; + } + else + { + switch (this.Agrupamento) + { + case 1: + { + List producaos7 = producaos6; + IOrderedEnumerable seguradora = + from x in producaos7 + orderby x.get_Seguradora() + select x; + strs = ( + from x in seguradora + select x.get_Seguradora()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str2 in strs) + { + if (string.IsNullOrWhiteSpace(str2)) + { + continue; + } + List producaos8 = producaos6; + if (producaos8.Any((Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Selecionado())) + { + IEnumerable producaos9 = producaos6.Where((Gestor.Model.Domain.Relatorios.Producao.Producao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Seguradora() == str2; + }); + producaos = ( + from x in producaos9 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + else + { + IEnumerable seguradora1 = + from x in producaos6 + where x.get_Seguradora() == str2 + select x; + producaos = ( + from x in seguradora1 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + List producaos10 = producaos; + if (producaos10.Count == 0) + { + continue; + } + string str3 = str2; + agrupamento1 = this.Agrupamento; + str = str3.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, producaos10, this.Relatorio, true); + } + goto Label1; + } + else + { + List producaos11 = producaos6; + if (producaos11.Any((Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Selecionado())) + { + List producaos12 = producaos6; + List list12 = ( + from x in producaos12 + where x.get_Selecionado() + select x).ToList(); + list1 = ( + from x in list12 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + else + { + List producaos13 = producaos6; + list1 = ( + from x in producaos13 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + List producaos14 = list1; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", producaos14, this.Relatorio, true); + goto Label1; + } + } + case 2: + { + List producaos15 = producaos6; + IOrderedEnumerable ramo = + from x in producaos15 + orderby x.get_Ramo() + select x; + strs = ( + from x in ramo + select x.get_Ramo()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str4 in strs) + { + if (string.IsNullOrWhiteSpace(str4)) + { + continue; + } + List producaos16 = producaos6; + if (producaos16.Any((Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Selecionado())) + { + IEnumerable producaos17 = producaos6.Where((Gestor.Model.Domain.Relatorios.Producao.Producao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Ramo() == str4; + }); + producaos1 = ( + from x in producaos17 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + else + { + IEnumerable ramo1 = + from x in producaos6 + where x.get_Ramo() == str4 + select x; + producaos1 = ( + from x in ramo1 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + List producaos18 = producaos1; + if (producaos18.Count == 0) + { + continue; + } + string str5 = str4; + agrupamento1 = this.Agrupamento; + str = str5.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, producaos18, this.Relatorio, true); + } + goto Label1; + } + else + { + List producaos19 = producaos6; + if (producaos19.Any((Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Selecionado())) + { + List producaos20 = producaos6; + List list13 = ( + from x in producaos20 + where x.get_Selecionado() + select x).ToList(); + list2 = ( + from x in list13 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + else + { + List producaos21 = producaos6; + list2 = ( + from x in producaos21 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + List producaos22 = list2; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", producaos22, this.Relatorio, true); + goto Label1; + } + } + case 3: + { + List producaos23 = producaos6; + IOrderedEnumerable vendedor = + from x in producaos23 + orderby x.get_Vendedor() + select x; + strs = ( + from x in vendedor + select x.get_Vendedor()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + num = 1; + foreach (string str6 in strs) + { + if (string.IsNullOrWhiteSpace(str6)) + { + continue; + } + List producaos24 = producaos6; + if (producaos24.Any((Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Selecionado())) + { + IEnumerable producaos25 = producaos6.Where((Gestor.Model.Domain.Relatorios.Producao.Producao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Vendedor() == str6; + }); + producaos2 = ( + from x in producaos25 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + else + { + IEnumerable vendedor1 = + from x in producaos6 + where x.get_Vendedor() == str6 + select x; + producaos2 = ( + from x in vendedor1 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + List producaos26 = producaos2; + if (producaos26.Count == 0) + { + continue; + } + string str7 = str6; + agrupamento1 = this.Agrupamento; + str = str7.ValidaNomePlanilha(agrupamento1.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, producaos26, this.Relatorio, true); + num++; + } + goto Label1; + } + else + { + List producaos27 = producaos6; + if (producaos27.Any((Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Selecionado())) + { + List producaos28 = producaos6; + List list14 = ( + from x in producaos28 + where x.get_Selecionado() + select x).ToList(); + list3 = ( + from x in list14 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + else + { + List producaos29 = producaos6; + list3 = ( + from x in producaos29 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + List producaos30 = list3; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", producaos30, this.Relatorio, true); + goto Label1; + } + } + case 4: + { + List producaos31 = producaos6; + IOrderedEnumerable estipulante = + from x in producaos31 + orderby x.get_Estipulante() + select x; + strs = ( + from x in estipulante + select x.get_Estipulante()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + num = 1; + foreach (string str8 in strs) + { + if (string.IsNullOrWhiteSpace(str8)) + { + continue; + } + List producaos32 = producaos6; + if (producaos32.Any((Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Selecionado())) + { + IEnumerable producaos33 = producaos6.Where((Gestor.Model.Domain.Relatorios.Producao.Producao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Estipulante() == str8; + }); + producaos3 = ( + from x in producaos33 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + else + { + IEnumerable estipulante1 = + from x in producaos6 + where x.get_Estipulante() == str8 + select x; + producaos3 = ( + from x in estipulante1 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + List producaos34 = producaos3; + if (producaos34.Count == 0) + { + continue; + } + string str9 = str8; + agrupamento1 = this.Agrupamento; + str = str9.ValidaNomePlanilha(agrupamento1.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, producaos34, this.Relatorio, true); + num++; + } + goto Label1; + } + else + { + List producaos35 = producaos6; + if (producaos35.Any((Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Selecionado())) + { + List producaos36 = producaos6; + List list15 = ( + from x in producaos36 + where x.get_Selecionado() + select x).ToList(); + list4 = ( + from x in list15 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + else + { + List producaos37 = producaos6; + list4 = ( + from x in producaos37 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + List producaos38 = list4; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", producaos38, this.Relatorio, true); + goto Label1; + } + } + case 5: + { + List producaos39 = producaos6; + IOrderedEnumerable status = + from x in producaos39 + orderby x.get_Status() + select x; + strs = ( + from x in status + select x.get_Status()).Distinct().ToList(); + this.ColunasOcultas = await Funcoes.OcultarColunas(this.Relatorio); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str10 in strs) + { + if (string.IsNullOrWhiteSpace(str10)) + { + continue; + } + List producaos40 = producaos6; + if (producaos40.Any((Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Selecionado())) + { + IEnumerable producaos41 = producaos6.Where((Gestor.Model.Domain.Relatorios.Producao.Producao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Status() == str10; + }); + producaos4 = ( + from x in producaos41 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + else + { + IEnumerable status1 = + from x in producaos6 + where x.get_Status() == str10 + select x; + producaos4 = ( + from x in status1 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + List producaos42 = producaos4; + if (producaos42.Count == 0) + { + continue; + } + string str11 = str10; + agrupamento1 = this.Agrupamento; + str = str11.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, producaos42, this.ColunasOcultas); + } + goto Label1; + } + else + { + List producaos43 = producaos6; + if (producaos43.Any((Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Selecionado())) + { + List producaos44 = producaos6; + List list16 = ( + from x in producaos44 + where x.get_Selecionado() + select x).ToList(); + list5 = ( + from x in list16 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + else + { + List producaos45 = producaos6; + list5 = ( + from x in producaos45 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + List producaos46 = list5; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", producaos46, this.ColunasOcultas); + goto Label1; + } + } + default: + { + List producaos47 = producaos6; + if (producaos47.Any((Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Selecionado())) + { + List producaos48 = producaos6; + IEnumerable selecionado = + from x in producaos48 + where x.get_Selecionado() + select x; + producaos5 = ( + from x in selecionado + orderby x.get_VigenciaInicial() + select x).ToList(); + } + else + { + List producaos49 = producaos6; + producaos5 = ( + from x in producaos49 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + List producaos50 = producaos5; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", producaos50.ToList(), this.Relatorio, true); + goto Label1; + } + } + } + break; + } + case 3: + { + apolicePendentes8 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.ApolicePendenteFiltrado == null || apolicePendentes8.Count == 0) + { + break; + } + else + { + switch (this.Agrupamento) + { + case 1: + { + List apolicePendentes9 = apolicePendentes8; + IOrderedEnumerable seguradora2 = + from x in apolicePendentes9 + orderby x.get_Seguradora() + select x; + strs = ( + from x in seguradora2 + select x.get_Seguradora()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str12 in strs) + { + if (string.IsNullOrWhiteSpace(str12)) + { + continue; + } + List apolicePendentes10 = apolicePendentes8; + if (apolicePendentes10.Any((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => x.get_Selecionado())) + { + IEnumerable apolicePendentes11 = apolicePendentes8.Where((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Seguradora() == str12; + }); + apolicePendentes = ( + from x in apolicePendentes11 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + else + { + IEnumerable seguradora3 = + from x in apolicePendentes8 + where x.get_Seguradora() == str12 + select x; + apolicePendentes = ( + from x in seguradora3 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + List apolicePendentes12 = apolicePendentes; + if (apolicePendentes12.Count == 0) + { + continue; + } + string str13 = str12; + agrupamento1 = this.Agrupamento; + str = str13.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, apolicePendentes12, this.Relatorio, true); + } + goto Label1; + } + else + { + List apolicePendentes13 = apolicePendentes8; + if (apolicePendentes13.Any((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => x.get_Selecionado())) + { + List apolicePendentes14 = apolicePendentes8; + apolicePendentes1 = ( + from x in apolicePendentes14 + where x.get_Selecionado() + select x).ToList(); + } + else + { + apolicePendentes1 = apolicePendentes8; + } + List apolicePendentes15 = apolicePendentes1; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", apolicePendentes15, this.Relatorio, true); + goto Label1; + } + } + case 2: + { + List apolicePendentes16 = apolicePendentes8; + IOrderedEnumerable ramo2 = + from x in apolicePendentes16 + orderby x.get_Ramo() + select x; + strs = ( + from x in ramo2 + select x.get_Ramo()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str14 in strs) + { + if (string.IsNullOrWhiteSpace(str14)) + { + continue; + } + List apolicePendentes17 = apolicePendentes8; + if (apolicePendentes17.Any((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => x.get_Selecionado())) + { + IEnumerable apolicePendentes18 = apolicePendentes8.Where((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Ramo() == str14; + }); + apolicePendentes2 = ( + from x in apolicePendentes18 + orderby x.get_Seguradora() + select x).ToList(); + } + else + { + IEnumerable ramo3 = + from x in apolicePendentes8 + where x.get_Ramo() == str14 + select x; + apolicePendentes2 = ( + from x in ramo3 + orderby x.get_Seguradora() + select x).ToList(); + } + List apolicePendentes19 = apolicePendentes2; + if (apolicePendentes19.Count == 0) + { + continue; + } + string str15 = str14; + agrupamento1 = this.Agrupamento; + str = str15.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, apolicePendentes19, this.Relatorio, true); + } + goto Label1; + } + else + { + List apolicePendentes20 = apolicePendentes8; + if (apolicePendentes20.Any((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => x.get_Selecionado())) + { + List apolicePendentes21 = apolicePendentes8; + apolicePendentes3 = ( + from x in apolicePendentes21 + where x.get_Selecionado() + select x).ToList(); + } + else + { + apolicePendentes3 = apolicePendentes8; + } + List apolicePendentes22 = apolicePendentes3; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", apolicePendentes22, this.Relatorio, true); + goto Label1; + } + } + case 3: + { + List apolicePendentes23 = apolicePendentes8; + IOrderedEnumerable vendedor2 = + from x in apolicePendentes23 + orderby x.get_Vendedor() + select x; + strs = ( + from x in vendedor2 + select x.get_Vendedor()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + num = 1; + foreach (string str16 in strs) + { + if (string.IsNullOrWhiteSpace(str16)) + { + continue; + } + List apolicePendentes24 = apolicePendentes8; + if (apolicePendentes24.Any((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => x.get_Selecionado())) + { + IEnumerable apolicePendentes25 = apolicePendentes8.Where((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Vendedor() == str16; + }); + apolicePendentes4 = ( + from x in apolicePendentes25 + orderby x.get_Seguradora() + select x).ToList(); + } + else + { + IEnumerable vendedor3 = + from x in apolicePendentes8 + where x.get_Vendedor() == str16 + select x; + apolicePendentes4 = ( + from x in vendedor3 + orderby x.get_Seguradora() + select x).ToList(); + } + List apolicePendentes26 = apolicePendentes4; + if (apolicePendentes26.Count == 0) + { + continue; + } + string str17 = str16; + agrupamento1 = this.Agrupamento; + str = str17.ValidaNomePlanilha(agrupamento1.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, apolicePendentes26, this.Relatorio, true); + num++; + } + goto Label1; + } + else + { + List apolicePendentes27 = apolicePendentes8; + if (apolicePendentes27.Any((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => x.get_Selecionado())) + { + List apolicePendentes28 = apolicePendentes8; + apolicePendentes5 = ( + from x in apolicePendentes28 + where x.get_Selecionado() + select x).ToList(); + } + else + { + apolicePendentes5 = apolicePendentes8; + } + List apolicePendentes29 = apolicePendentes5; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", apolicePendentes29, this.Relatorio, true); + goto Label1; + } + } + case 4: + { + List apolicePendentes30 = apolicePendentes8; + IOrderedEnumerable estipulante2 = + from x in apolicePendentes30 + orderby x.get_Estipulante() + select x; + strs = ( + from x in estipulante2 + select x.get_Estipulante()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + num = 1; + foreach (string str18 in strs) + { + if (string.IsNullOrWhiteSpace(str18)) + { + continue; + } + List apolicePendentes31 = apolicePendentes8; + if (apolicePendentes31.Any((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => x.get_Selecionado())) + { + IEnumerable apolicePendentes32 = apolicePendentes8.Where((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Estipulante() == str18; + }); + list6 = ( + from x in apolicePendentes32 + orderby x.get_Seguradora() + select x).ToList(); + } + else + { + IEnumerable estipulante3 = + from x in apolicePendentes8 + where x.get_Estipulante() == str18 + select x; + list6 = ( + from x in estipulante3 + orderby x.get_Seguradora() + select x).ToList(); + } + List apolicePendentes33 = list6; + if (apolicePendentes33.Count == 0) + { + continue; + } + string str19 = str18; + agrupamento1 = this.Agrupamento; + str = str19.ValidaNomePlanilha(agrupamento1.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, apolicePendentes33, this.Relatorio, true); + num++; + } + goto Label1; + } + else + { + List apolicePendentes34 = apolicePendentes8; + if (apolicePendentes34.Any((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => x.get_Selecionado())) + { + List apolicePendentes35 = apolicePendentes8; + apolicePendentes6 = ( + from x in apolicePendentes35 + where x.get_Selecionado() + select x).ToList(); + } + else + { + apolicePendentes6 = apolicePendentes8; + } + List apolicePendentes36 = apolicePendentes6; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", apolicePendentes36, this.Relatorio, true); + goto Label1; + } + } + case 5: + { + List apolicePendentes37 = apolicePendentes8; + IOrderedEnumerable status2 = + from x in apolicePendentes37 + orderby x.get_Status() + select x; + strs = ( + from x in status2 + select x.get_Status()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str20 in strs) + { + if (string.IsNullOrWhiteSpace(str20)) + { + continue; + } + List apolicePendentes38 = apolicePendentes8; + if (apolicePendentes38.Any((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => x.get_Selecionado())) + { + IEnumerable apolicePendentes39 = apolicePendentes8.Where((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Status() == str20; + }); + list7 = ( + from x in apolicePendentes39 + orderby x.get_Seguradora() + select x).ToList(); + } + else + { + IEnumerable status3 = + from x in apolicePendentes8 + where x.get_Status() == str20 + select x; + list7 = ( + from x in status3 + orderby x.get_Seguradora() + select x).ToList(); + } + List apolicePendentes40 = list7; + if (apolicePendentes40.Count == 0) + { + continue; + } + string str21 = str20; + agrupamento1 = this.Agrupamento; + str = str21.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, apolicePendentes40, this.ColunasOcultas); + } + goto Label1; + } + else + { + List apolicePendentes41 = apolicePendentes8; + if (apolicePendentes41.Any((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => x.get_Selecionado())) + { + List apolicePendentes42 = apolicePendentes8; + apolicePendentes7 = ( + from x in apolicePendentes42 + where x.get_Selecionado() + select x).ToList(); + } + else + { + apolicePendentes7 = apolicePendentes8; + } + List apolicePendentes43 = apolicePendentes7; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", apolicePendentes43, this.ColunasOcultas); + goto Label1; + } + } + default: + { + List apolicePendentes44 = apolicePendentes8; + if (apolicePendentes44.Any((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => x.get_Selecionado())) + { + List apolicePendentes45 = apolicePendentes8; + list8 = ( + from x in apolicePendentes45 + where x.get_Selecionado() + select x).ToList(); + } + else + { + list8 = apolicePendentes8; + } + List apolicePendentes46 = list8; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", apolicePendentes46, this.Relatorio, true); + goto Label1; + } + } + } + break; + } + case 4: + { + renovacaos10 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.RenovacaoFiltrado == null || renovacaos10.Count == 0) + { + break; + } + else + { + switch (this.Agrupamento) + { + case 1: + { + List renovacaos11 = renovacaos10; + IOrderedEnumerable seguradora4 = + from x in renovacaos11 + orderby x.get_Seguradora() + select x; + strs = ( + from x in seguradora4 + select x.get_Seguradora()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str22 in strs) + { + if (string.IsNullOrWhiteSpace(str22)) + { + continue; + } + List renovacaos12 = renovacaos10; + if (renovacaos12.Any((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.get_Selecionado())) + { + IEnumerable renovacaos13 = renovacaos10.Where((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Seguradora() == str22; + }); + renovacaos = ( + from x in renovacaos13 + orderby x.get_VigenciaFinal() + select x).ToList(); + } + else + { + IEnumerable seguradora5 = + from x in renovacaos10 + where x.get_Seguradora() == str22 + select x; + renovacaos = ( + from x in seguradora5 + orderby x.get_VigenciaFinal() + select x).ToList(); + } + List renovacaos14 = renovacaos; + if (renovacaos14.Count == 0) + { + continue; + } + string str23 = str22; + agrupamento1 = this.Agrupamento; + str = str23.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, renovacaos14, this.Relatorio, true); + } + goto Label1; + } + else + { + List renovacaos15 = renovacaos10; + if (renovacaos15.Any((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.get_Selecionado())) + { + List renovacaos16 = renovacaos10; + renovacaos1 = ( + from x in renovacaos16 + where x.get_Selecionado() + select x).ToList(); + } + else + { + renovacaos1 = renovacaos10.ToList(); + } + List renovacaos17 = renovacaos1; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", renovacaos17, this.Relatorio, true); + goto Label1; + } + } + case 2: + { + List renovacaos18 = renovacaos10; + IOrderedEnumerable ramo4 = + from x in renovacaos18 + orderby x.get_Ramo() + select x; + strs = ( + from x in ramo4 + select x.get_Ramo()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str24 in strs) + { + if (string.IsNullOrWhiteSpace(str24)) + { + continue; + } + List renovacaos19 = renovacaos10; + if (renovacaos19.Any((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.get_Selecionado())) + { + IEnumerable renovacaos20 = renovacaos10.Where((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Ramo() == str24; + }); + renovacaos2 = ( + from x in renovacaos20 + orderby x.get_VigenciaFinal() + select x).ToList(); + } + else + { + IEnumerable ramo5 = + from x in renovacaos10 + where x.get_Ramo() == str24 + select x; + renovacaos2 = ( + from x in ramo5 + orderby x.get_VigenciaFinal() + select x).ToList(); + } + List renovacaos21 = renovacaos2; + if (renovacaos21.Count == 0) + { + continue; + } + string str25 = str24; + agrupamento1 = this.Agrupamento; + str = str25.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, renovacaos21, this.Relatorio, true); + num++; + } + goto Label1; + } + else + { + List renovacaos22 = renovacaos10; + if (renovacaos22.Any((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.get_Selecionado())) + { + List renovacaos23 = renovacaos10; + renovacaos3 = ( + from x in renovacaos23 + where x.get_Selecionado() + select x).ToList(); + } + else + { + renovacaos3 = renovacaos10.ToList(); + } + List renovacaos24 = renovacaos3; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", renovacaos24, this.Relatorio, true); + goto Label1; + } + } + case 3: + { + List renovacaos25 = renovacaos10; + IOrderedEnumerable vendedor4 = + from x in renovacaos25 + orderby x.get_Vendedor() + select x; + strs = ( + from x in vendedor4 + select x.get_Vendedor()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + num = 1; + foreach (string str26 in strs) + { + if (string.IsNullOrWhiteSpace(str26)) + { + continue; + } + List renovacaos26 = renovacaos10; + if (renovacaos26.Any((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.get_Selecionado())) + { + IEnumerable renovacaos27 = renovacaos10.Where((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Vendedor() == str26; + }); + renovacaos4 = ( + from x in renovacaos27 + orderby x.get_VigenciaFinal() + select x).ToList(); + } + else + { + IEnumerable vendedor5 = + from x in renovacaos10 + where x.get_Vendedor() == str26 + select x; + renovacaos4 = ( + from x in vendedor5 + orderby x.get_VigenciaFinal() + select x).ToList(); + } + List renovacaos28 = renovacaos4; + if (renovacaos28.Count == 0) + { + continue; + } + string str27 = str26; + agrupamento1 = this.Agrupamento; + str = str27.ValidaNomePlanilha(agrupamento1.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, renovacaos28, this.Relatorio, true); + num++; + } + goto Label1; + } + else + { + List renovacaos29 = renovacaos10; + if (renovacaos29.Any((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.get_Selecionado())) + { + List renovacaos30 = renovacaos10; + renovacaos5 = ( + from x in renovacaos30 + where x.get_Selecionado() + select x).ToList(); + } + else + { + renovacaos5 = renovacaos10.ToList(); + } + List renovacaos31 = renovacaos5; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", renovacaos31, this.Relatorio, true); + goto Label1; + } + } + case 4: + { + List renovacaos32 = renovacaos10; + IOrderedEnumerable estipulante4 = + from x in renovacaos32 + orderby x.get_Estipulante() + select x; + strs = ( + from x in estipulante4 + select x.get_Estipulante()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + num = 1; + foreach (string str28 in strs) + { + if (string.IsNullOrWhiteSpace(str28)) + { + continue; + } + List renovacaos33 = renovacaos10; + if (renovacaos33.Any((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.get_Selecionado())) + { + IEnumerable renovacaos34 = renovacaos10.Where((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Estipulante() == str28; + }); + renovacaos6 = ( + from x in renovacaos34 + orderby x.get_VigenciaFinal() + select x).ToList(); + } + else + { + IEnumerable estipulante5 = + from x in renovacaos10 + where x.get_Estipulante() == str28 + select x; + renovacaos6 = ( + from x in estipulante5 + orderby x.get_VigenciaFinal() + select x).ToList(); + } + List renovacaos35 = renovacaos6; + if (renovacaos35.Count == 0) + { + continue; + } + string str29 = str28; + agrupamento1 = this.Agrupamento; + str = str29.ValidaNomePlanilha(agrupamento1.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, renovacaos35, this.Relatorio, true); + num++; + } + goto Label1; + } + else + { + List renovacaos36 = renovacaos10; + if (renovacaos36.Any((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.get_Selecionado())) + { + List renovacaos37 = renovacaos10; + renovacaos7 = ( + from x in renovacaos37 + where x.get_Selecionado() + select x).ToList(); + } + else + { + renovacaos7 = renovacaos10.ToList(); + } + List renovacaos38 = renovacaos7; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", renovacaos38, this.Relatorio, true); + goto Label1; + } + } + case 5: + { + this.ColunasOcultas = await Funcoes.OcultarColunas(this.Relatorio); + List renovacaos39 = renovacaos10; + IOrderedEnumerable status4 = + from x in renovacaos39 + orderby x.get_Status() + select x; + strs = ( + from x in status4 + select x.get_Status()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str30 in strs) + { + if (string.IsNullOrWhiteSpace(str30)) + { + continue; + } + List renovacaos40 = renovacaos10; + if (renovacaos40.Any((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.get_Selecionado())) + { + IEnumerable renovacaos41 = renovacaos10.Where((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Status() == str30; + }); + renovacaos8 = ( + from x in renovacaos41 + orderby x.get_VigenciaFinal() + select x).ToList(); + } + else + { + IEnumerable status5 = + from x in renovacaos10 + where x.get_Status() == str30 + select x; + renovacaos8 = ( + from x in status5 + orderby x.get_VigenciaFinal() + select x).ToList(); + } + List renovacaos42 = renovacaos8; + if (renovacaos42.Count == 0) + { + continue; + } + string str31 = str30; + agrupamento1 = this.Agrupamento; + str = str31.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, renovacaos42, this.Relatorio, true); + } + goto Label1; + } + else + { + List renovacaos43 = renovacaos10; + if (renovacaos43.Any((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.get_Selecionado())) + { + List renovacaos44 = renovacaos10; + list9 = ( + from x in renovacaos44 + where x.get_Selecionado() + select x).ToList(); + } + else + { + list9 = renovacaos10.ToList(); + } + List renovacaos45 = list9; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", renovacaos45, this.Relatorio, true); + goto Label1; + } + } + default: + { + List renovacaos46 = renovacaos10; + if (renovacaos46.Any((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.get_Selecionado())) + { + List renovacaos47 = renovacaos10; + renovacaos9 = ( + from x in renovacaos47 + where x.get_Selecionado() + select x).ToList(); + } + else + { + renovacaos9 = renovacaos10.ToList(); + } + List renovacaos48 = renovacaos9; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", renovacaos48, this.Relatorio, true); + goto Label1; + } + } + } + break; + } + case 5: + { + comissaos10 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.ComissaoFiltrado == null || comissaos10.Count == 0) + { + break; + } + else + { + switch (this.Agrupamento) + { + case 1: + { + List comissaos11 = comissaos10; + IOrderedEnumerable seguradora6 = + from x in comissaos11 + orderby x.get_Seguradora() + select x; + strs = ( + from x in seguradora6 + select x.get_Seguradora()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str32 in strs) + { + if (string.IsNullOrWhiteSpace(str32)) + { + continue; + } + List comissaos12 = comissaos10; + if (comissaos12.Any((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Selecionado())) + { + IEnumerable comissaos13 = comissaos10.Where((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Seguradora() == str32; + }); + comissaos = ( + from x in comissaos13 + orderby x.get_Recebimento() + select x).ToList(); + } + else + { + IEnumerable seguradora7 = + from x in comissaos10 + where x.get_Seguradora() == str32 + select x; + comissaos = ( + from x in seguradora7 + orderby x.get_Recebimento() + select x).ToList(); + } + List comissaos14 = comissaos; + if (comissaos14.Count == 0) + { + continue; + } + string str33 = str32; + agrupamento1 = this.Agrupamento; + str = str33.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, comissaos14, this.Relatorio, true); + } + goto Label1; + } + else + { + List comissaos15 = comissaos10; + if (comissaos15.Any((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Selecionado())) + { + List comissaos16 = comissaos10; + comissaos1 = ( + from x in comissaos16 + where x.get_Selecionado() + select x).ToList(); + } + else + { + comissaos1 = comissaos10; + } + List comissaos17 = comissaos1; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", comissaos17, this.Relatorio, true); + goto Label1; + } + } + case 2: + { + List comissaos18 = comissaos10; + IOrderedEnumerable ramo6 = + from x in comissaos18 + orderby x.get_Ramo() + select x; + strs = ( + from x in ramo6 + select x.get_Ramo()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str34 in strs) + { + if (string.IsNullOrWhiteSpace(str34)) + { + continue; + } + List comissaos19 = comissaos10; + if (comissaos19.Any((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Selecionado())) + { + IEnumerable comissaos20 = comissaos10.Where((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Ramo() == str34; + }); + comissaos2 = ( + from x in comissaos20 + orderby x.get_Recebimento() + select x).ToList(); + } + else + { + IEnumerable ramo7 = + from x in comissaos10 + where x.get_Ramo() == str34 + select x; + comissaos2 = ( + from x in ramo7 + orderby x.get_Recebimento() + select x).ToList(); + } + List comissaos21 = comissaos2; + if (comissaos21.Count == 0) + { + continue; + } + string str35 = str34; + agrupamento1 = this.Agrupamento; + str = str35.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, comissaos21, this.Relatorio, true); + } + goto Label1; + } + else + { + List comissaos22 = comissaos10; + if (comissaos22.Any((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Selecionado())) + { + List comissaos23 = comissaos10; + comissaos3 = ( + from x in comissaos23 + where x.get_Selecionado() + select x).ToList(); + } + else + { + comissaos3 = comissaos10; + } + List comissaos24 = comissaos3; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", comissaos24, this.Relatorio, true); + goto Label1; + } + } + case 3: + { + List comissaos25 = comissaos10; + IOrderedEnumerable vendedor6 = + from x in comissaos25 + orderby x.get_Vendedor() + select x; + strs = ( + from x in vendedor6 + select x.get_Vendedor()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + num = 1; + foreach (string str36 in strs) + { + if (string.IsNullOrWhiteSpace(str36)) + { + continue; + } + List comissaos26 = comissaos10; + if (comissaos26.Any((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Selecionado())) + { + IEnumerable comissaos27 = comissaos10.Where((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Vendedor() == str36; + }); + comissaos4 = ( + from x in comissaos27 + orderby x.get_Recebimento() + select x).ToList(); + } + else + { + IEnumerable vendedor7 = + from x in comissaos10 + where x.get_Vendedor() == str36 + select x; + comissaos4 = ( + from x in vendedor7 + orderby x.get_Recebimento() + select x).ToList(); + } + List comissaos28 = comissaos4; + if (comissaos28.Count == 0) + { + continue; + } + string str37 = str36; + agrupamento1 = this.Agrupamento; + str = str37.ValidaNomePlanilha(agrupamento1.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, comissaos28, this.Relatorio, true); + num++; + } + goto Label1; + } + else + { + List comissaos29 = comissaos10; + if (comissaos29.Any((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Selecionado())) + { + List comissaos30 = comissaos10; + comissaos5 = ( + from x in comissaos30 + where x.get_Selecionado() + select x).ToList(); + } + else + { + comissaos5 = comissaos10; + } + List comissaos31 = comissaos5; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", comissaos31, this.Relatorio, true); + goto Label1; + } + } + case 4: + { + List comissaos32 = comissaos10; + IOrderedEnumerable estipulante6 = + from x in comissaos32 + orderby x.get_Estipulante() + select x; + strs = ( + from x in estipulante6 + select x.get_Estipulante()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + num = 1; + foreach (string str38 in strs) + { + if (string.IsNullOrWhiteSpace(str38)) + { + continue; + } + List comissaos33 = comissaos10; + if (comissaos33.Any((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Selecionado())) + { + IEnumerable comissaos34 = comissaos10.Where((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Estipulante() == str38; + }); + comissaos6 = ( + from x in comissaos34 + orderby x.get_Recebimento() + select x).ToList(); + } + else + { + IEnumerable estipulante7 = + from x in comissaos10 + where x.get_Estipulante() == str38 + select x; + comissaos6 = ( + from x in estipulante7 + orderby x.get_Recebimento() + select x).ToList(); + } + List comissaos35 = comissaos6; + if (comissaos35.Count == 0) + { + continue; + } + string str39 = str38; + agrupamento1 = this.Agrupamento; + str = str39.ValidaNomePlanilha(agrupamento1.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, comissaos35, this.Relatorio, true); + num++; + } + goto Label1; + } + else + { + List comissaos36 = comissaos10; + if (comissaos36.Any((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Selecionado())) + { + List comissaos37 = comissaos10; + comissaos7 = ( + from x in comissaos37 + where x.get_Selecionado() + select x).ToList(); + } + else + { + comissaos7 = comissaos10; + } + List comissaos38 = comissaos7; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", comissaos38, this.Relatorio, true); + goto Label1; + } + } + case 5: + { + List comissaos39 = comissaos10; + IOrderedEnumerable status6 = + from x in comissaos39 + orderby x.get_Status() + select x; + strs = ( + from x in status6 + select x.get_Status()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str40 in strs) + { + if (string.IsNullOrWhiteSpace(str40)) + { + continue; + } + List comissaos40 = comissaos10; + if (comissaos40.Any((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Selecionado())) + { + IEnumerable comissaos41 = comissaos10.Where((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Status() == str40; + }); + comissaos8 = ( + from x in comissaos41 + orderby x.get_Recebimento() + select x).ToList(); + } + else + { + IEnumerable status7 = + from x in comissaos10 + where x.get_Status() == str40 + select x; + comissaos8 = ( + from x in status7 + orderby x.get_Recebimento() + select x).ToList(); + } + List comissaos42 = comissaos8; + if (comissaos42.Count == 0) + { + continue; + } + string str41 = str40; + agrupamento1 = this.Agrupamento; + str = str41.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, comissaos42, this.ColunasOcultas); + } + goto Label1; + } + else + { + List comissaos43 = comissaos10; + if (comissaos43.Any((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Selecionado())) + { + List comissaos44 = comissaos10; + comissaos9 = ( + from x in comissaos44 + where x.get_Selecionado() + select x).ToList(); + } + else + { + comissaos9 = comissaos10; + } + List comissaos45 = comissaos9; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", comissaos45, this.ColunasOcultas); + goto Label1; + } + } + default: + { + List comissaos46 = comissaos10; + if (comissaos46.Any((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Selecionado())) + { + List comissaos47 = comissaos10; + list10 = ( + from x in comissaos47 + where x.get_Selecionado() + select x).ToList(); + } + else + { + list10 = comissaos10; + } + List comissaos48 = list10; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", comissaos48, this.Relatorio, true); + goto Label1; + } + } + } + break; + } + case 6: + case 16: + { + list11 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.PendenteFiltrado == null || list11.Count == 0) + { + break; + } + else + { + switch (this.Agrupamento) + { + case 1: + { + List pendentes11 = list11; + IOrderedEnumerable seguradora8 = + from x in pendentes11 + orderby x.get_Seguradora() + select x; + strs = ( + from x in seguradora8 + select x.get_Seguradora()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str42 in strs) + { + if (string.IsNullOrWhiteSpace(str42)) + { + continue; + } + List pendentes12 = list11; + if (pendentes12.Any((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_Selecionado())) + { + IEnumerable pendentes13 = list11.Where((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Seguradora() == str42; + }); + pendentes = ( + from x in pendentes13 + orderby x.get_Vencimento() + select x).ToList(); + } + else + { + IEnumerable seguradora9 = + from x in list11 + where x.get_Seguradora() == str42 + select x; + pendentes = ( + from x in seguradora9 + orderby x.get_Vencimento() + select x).ToList(); + } + List pendentes14 = pendentes; + if (pendentes14.Count == 0) + { + continue; + } + string str43 = str42; + agrupamento1 = this.Agrupamento; + str = str43.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, pendentes14, this.Relatorio, true); + } + goto Label1; + } + else + { + List pendentes15 = list11; + if (pendentes15.Any((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_Selecionado())) + { + List pendentes16 = list11; + pendentes1 = ( + from x in pendentes16 + where x.get_Selecionado() + select x).ToList(); + } + else + { + pendentes1 = list11; + } + List pendentes17 = pendentes1; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", pendentes17, this.Relatorio, true); + goto Label1; + } + } + case 2: + { + List pendentes18 = list11; + IOrderedEnumerable ramo8 = + from x in pendentes18 + orderby x.get_Ramo() + select x; + strs = ( + from x in ramo8 + select x.get_Ramo()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str44 in strs) + { + if (string.IsNullOrWhiteSpace(str44)) + { + continue; + } + List pendentes19 = list11; + if (pendentes19.Any((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_Selecionado())) + { + IEnumerable pendentes20 = list11.Where((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Ramo() == str44; + }); + pendentes2 = ( + from x in pendentes20 + orderby x.get_Vencimento() + select x).ToList(); + } + else + { + IEnumerable ramo9 = + from x in list11 + where x.get_Ramo() == str44 + select x; + pendentes2 = ( + from x in ramo9 + orderby x.get_Vencimento() + select x).ToList(); + } + List pendentes21 = pendentes2; + if (pendentes21.Count == 0) + { + continue; + } + string str45 = str44; + agrupamento1 = this.Agrupamento; + str = str45.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, pendentes21, this.Relatorio, true); + } + goto Label1; + } + else + { + List pendentes22 = list11; + if (pendentes22.Any((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_Selecionado())) + { + List pendentes23 = list11; + pendentes3 = ( + from x in pendentes23 + where x.get_Selecionado() + select x).ToList(); + } + else + { + pendentes3 = list11; + } + List pendentes24 = pendentes3; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", pendentes24, this.Relatorio, true); + goto Label1; + } + } + case 3: + { + List pendentes25 = list11; + IOrderedEnumerable vendedor8 = + from x in pendentes25 + orderby x.get_Vendedor() + select x; + strs = ( + from x in vendedor8 + select x.get_Vendedor()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + num = 1; + foreach (string str46 in strs) + { + if (string.IsNullOrWhiteSpace(str46)) + { + continue; + } + List pendentes26 = list11; + if (pendentes26.Any((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_Selecionado())) + { + IEnumerable pendentes27 = list11.Where((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Vendedor() == str46; + }); + pendentes4 = ( + from x in pendentes27 + orderby x.get_Vencimento() + select x).ToList(); + } + else + { + IEnumerable vendedor9 = + from x in list11 + where x.get_Vendedor() == str46 + select x; + pendentes4 = ( + from x in vendedor9 + orderby x.get_Vencimento() + select x).ToList(); + } + List pendentes28 = pendentes4; + if (pendentes28.Count == 0) + { + continue; + } + string str47 = str46; + agrupamento1 = this.Agrupamento; + str = str47.ValidaNomePlanilha(agrupamento1.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, pendentes28, this.Relatorio, true); + num++; + } + goto Label1; + } + else + { + List pendentes29 = list11; + if (pendentes29.Any((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_Selecionado())) + { + List pendentes30 = list11; + pendentes5 = ( + from x in pendentes30 + where x.get_Selecionado() + select x).ToList(); + } + else + { + pendentes5 = list11; + } + List pendentes31 = pendentes5; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", pendentes31, this.Relatorio, true); + goto Label1; + } + } + case 4: + { + List pendentes32 = list11; + IOrderedEnumerable estipulante8 = + from x in pendentes32 + orderby x.get_Estipulante() + select x; + strs = ( + from x in estipulante8 + select x.get_Estipulante()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + num = 1; + foreach (string str48 in strs) + { + if (string.IsNullOrWhiteSpace(str48)) + { + continue; + } + List pendentes33 = list11; + if (pendentes33.Any((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_Selecionado())) + { + IEnumerable pendentes34 = list11.Where((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Estipulante() == str48; + }); + pendentes6 = ( + from x in pendentes34 + orderby x.get_Vencimento() + select x).ToList(); + } + else + { + IEnumerable estipulante9 = + from x in list11 + where x.get_Estipulante() == str48 + select x; + pendentes6 = ( + from x in estipulante9 + orderby x.get_Vencimento() + select x).ToList(); + } + List pendentes35 = pendentes6; + if (pendentes35.Count == 0) + { + continue; + } + string str49 = str48; + agrupamento1 = this.Agrupamento; + str = str49.ValidaNomePlanilha(agrupamento1.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, pendentes35, this.Relatorio, true); + num++; + } + goto Label1; + } + else + { + List pendentes36 = list11; + if (pendentes36.Any((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_Selecionado())) + { + List pendentes37 = list11; + pendentes7 = ( + from x in pendentes37 + where x.get_Selecionado() + select x).ToList(); + } + else + { + pendentes7 = list11; + } + List pendentes38 = pendentes7; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", pendentes38, this.Relatorio, true); + goto Label1; + } + } + case 5: + { + List pendentes39 = list11; + IOrderedEnumerable status8 = + from x in pendentes39 + orderby x.get_Status() + select x; + strs = ( + from x in status8 + select x.get_Status()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str50 in strs) + { + if (string.IsNullOrWhiteSpace(str50)) + { + continue; + } + List pendentes40 = list11; + if (pendentes40.Any((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_Selecionado())) + { + IEnumerable pendentes41 = list11.Where((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Status() == str50; + }); + pendentes8 = ( + from x in pendentes41 + orderby x.get_Vencimento() + select x).ToList(); + } + else + { + IEnumerable status9 = + from x in list11 + where x.get_Status() == str50 + select x; + pendentes8 = ( + from x in status9 + orderby x.get_Vencimento() + select x).ToList(); + } + List pendentes42 = pendentes8; + if (pendentes42.Count == 0) + { + continue; + } + string str51 = str50; + agrupamento1 = this.Agrupamento; + str = str51.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, pendentes42, this.ColunasOcultas); + } + goto Label1; + } + else + { + List pendentes43 = list11; + if (pendentes43.Any((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_Selecionado())) + { + List pendentes44 = list11; + pendentes9 = ( + from x in pendentes44 + where x.get_Selecionado() + select x).ToList(); + } + else + { + pendentes9 = list11; + } + List pendentes45 = pendentes9; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", pendentes45, this.ColunasOcultas); + goto Label1; + } + } + default: + { + List pendentes46 = list11; + if (pendentes46.Any((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_Selecionado())) + { + List pendentes47 = list11; + pendentes10 = ( + from x in pendentes47 + where x.get_Selecionado() + select x).ToList(); + } + else + { + pendentes10 = list11; + } + List pendentes48 = pendentes10; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", pendentes48, this.Relatorio, true); + goto Label1; + } + } + } + break; + } + case 7: + { + if (this.Pagamentos != null) + { + List pagamentosSintetico = this.PagamentosSintetico; + List pagamentoSinteticos = ( + from x in pagamentosSintetico + orderby x.get_Titulo() descending + select x).ToList(); + foreach (PagamentoSintetico pagamentoSintetico in pagamentoSinteticos) + { + string titulo = pagamentoSintetico.get_Titulo(); + agrupamento = this.Agrupamento; + string str52 = titulo.ValidaNomePlanilha(agrupamento.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str52, pagamentoSintetico.get_Agrupamento().ToList(), this.Relatorio, true); + } + num = 1; + List pagamentos = this.Pagamentos; + List pagamentos1 = ( + from x in pagamentos + orderby x.get_Title() descending + select x).ToList(); + foreach (Pagamento pagamento in pagamentos1) + { + string title = pagamento.get_Title(); + agrupamento = this.Agrupamento; + string str53 = title.ValidaNomePlanilha(agrupamento.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str53, pagamento.get_Dados().ToList(), this.Relatorio, true); + num++; + } + List agrupamentoVendedors = new List(); + List pagamentos2 = this.Pagamentos; + foreach (Pagamento pagamento1 in + from x in pagamentos2 + orderby x.get_Title() + select x) + { + agrupamentoVendedors.Add(pagamento1.get_Vendedores()); + } + List agrupamentoVendedors1 = agrupamentoVendedors; + AgrupamentoVendedor agrupamentoVendedor = new AgrupamentoVendedor(); + agrupamentoVendedor.set_Vendedor("TOTAL"); + List agrupamentoVendedors2 = agrupamentoVendedors; + agrupamentoVendedor.set_Repasse(agrupamentoVendedors2.Sum((AgrupamentoVendedor p) => p.get_Repasse())); + List agrupamentoVendedors3 = agrupamentoVendedors; + agrupamentoVendedor.set_Debito(agrupamentoVendedors3.Sum((AgrupamentoVendedor p) => p.get_Debito())); + List agrupamentoVendedors4 = agrupamentoVendedors; + agrupamentoVendedor.set_Credito(agrupamentoVendedors4.Sum((AgrupamentoVendedor p) => p.get_Credito())); + List agrupamentoVendedors5 = agrupamentoVendedors; + agrupamentoVendedor.set_Desconto(agrupamentoVendedors5.Sum((AgrupamentoVendedor p) => p.get_Desconto())); + List agrupamentoVendedors6 = agrupamentoVendedors; + agrupamentoVendedor.set_Adiantamento(agrupamentoVendedors6.Sum((AgrupamentoVendedor p) => p.get_Adiantamento())); + List agrupamentoVendedors7 = agrupamentoVendedors; + agrupamentoVendedor.set_ValorLiquido(agrupamentoVendedors7.Sum((AgrupamentoVendedor p) => p.get_ValorLiquido())); + agrupamentoVendedors1.Add(agrupamentoVendedor); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "DADOS BANCÁRIOS", agrupamentoVendedors, this.Relatorio, false); + goto case 22; + } + else + { + break; + } + } + case 8: + { + auditorias11 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.AuditoriaFiltrado == null || auditorias11.Count == 0) + { + break; + } + else + { + switch (this.Agrupamento) + { + case 1: + { + List auditorias12 = auditorias11; + IOrderedEnumerable seguradora10 = + from x in auditorias12 + orderby x.get_Seguradora() + select x; + strs = ( + from x in seguradora10 + select x.get_Seguradora()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str54 in strs) + { + if (string.IsNullOrWhiteSpace(str54)) + { + continue; + } + List auditorias13 = auditorias11; + if (auditorias13.Any((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => x.get_Selecionado())) + { + IEnumerable auditorias14 = auditorias11.Where((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Seguradora() == str54; + }); + auditorias = ( + from x in auditorias14 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + else + { + IEnumerable seguradora11 = + from x in auditorias11 + where x.get_Seguradora() == str54 + select x; + auditorias = ( + from x in seguradora11 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + List auditorias15 = auditorias; + if (auditorias15.Count == 0) + { + continue; + } + string str55 = str54; + agrupamento1 = this.Agrupamento; + str = str55.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, auditorias15, this.Relatorio, true); + } + goto Label1; + } + else + { + List auditorias16 = auditorias11; + if (auditorias16.Any((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => x.get_Selecionado())) + { + List auditorias17 = auditorias11; + auditorias1 = ( + from x in auditorias17 + where x.get_Selecionado() + select x).ToList(); + } + else + { + auditorias1 = auditorias11; + } + List auditorias18 = auditorias1; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", auditorias18, this.Relatorio, true); + goto Label1; + } + } + case 2: + { + List auditorias19 = auditorias11; + IOrderedEnumerable ramo10 = + from x in auditorias19 + orderby x.get_Ramo() + select x; + strs = ( + from x in ramo10 + select x.get_Ramo()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str56 in strs) + { + if (string.IsNullOrWhiteSpace(str56)) + { + continue; + } + List auditorias20 = auditorias11; + if (auditorias20.Any((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => x.get_Selecionado())) + { + IEnumerable auditorias21 = auditorias11.Where((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Ramo() == str56; + }); + auditorias2 = ( + from x in auditorias21 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + else + { + IEnumerable ramo11 = + from x in auditorias11 + where x.get_Ramo() == str56 + select x; + auditorias2 = ( + from x in ramo11 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + List auditorias22 = auditorias2; + if (auditorias22.Count == 0) + { + continue; + } + string str57 = str56; + agrupamento1 = this.Agrupamento; + str = str57.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, auditorias22, this.Relatorio, true); + } + goto Label1; + } + else + { + List auditorias23 = auditorias11; + if (auditorias23.Any((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => x.get_Selecionado())) + { + List auditorias24 = auditorias11; + auditorias3 = ( + from x in auditorias24 + where x.get_Selecionado() + select x).ToList(); + } + else + { + auditorias3 = auditorias11; + } + List auditorias25 = auditorias3; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", auditorias25, this.Relatorio, true); + goto Label1; + } + } + case 3: + { + List auditorias26 = auditorias11; + IOrderedEnumerable vendedor10 = + from x in auditorias26 + orderby x.get_Vendedor() + select x; + strs = ( + from x in vendedor10 + select x.get_Vendedor()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + num = 1; + foreach (string str58 in strs) + { + if (string.IsNullOrWhiteSpace(str58)) + { + continue; + } + List auditorias27 = auditorias11; + if (auditorias27.Any((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => x.get_Selecionado())) + { + IEnumerable auditorias28 = auditorias11.Where((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Vendedor() == str58; + }); + auditorias4 = ( + from x in auditorias28 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + else + { + IEnumerable vendedor11 = + from x in auditorias11 + where x.get_Vendedor() == str58 + select x; + auditorias4 = ( + from x in vendedor11 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + List auditorias29 = auditorias4; + if (auditorias29.Count == 0) + { + continue; + } + string str59 = str58; + agrupamento1 = this.Agrupamento; + str = str59.ValidaNomePlanilha(agrupamento1.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, auditorias29, this.Relatorio, true); + num++; + } + goto Label1; + } + else + { + List auditorias30 = auditorias11; + if (auditorias30.Any((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => x.get_Selecionado())) + { + List auditorias31 = auditorias11; + auditorias5 = ( + from x in auditorias31 + where x.get_Selecionado() + select x).ToList(); + } + else + { + auditorias5 = auditorias11; + } + List auditorias32 = auditorias5; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", auditorias32, this.Relatorio, true); + goto Label1; + } + } + case 4: + { + List auditorias33 = auditorias11; + IOrderedEnumerable estipulante10 = + from x in auditorias33 + orderby x.get_Estipulante() + select x; + strs = ( + from x in estipulante10 + select x.get_Estipulante()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + num = 1; + foreach (string str60 in strs) + { + if (string.IsNullOrWhiteSpace(str60)) + { + continue; + } + List auditorias34 = auditorias11; + if (auditorias34.Any((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => x.get_Selecionado())) + { + IEnumerable auditorias35 = auditorias11.Where((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Estipulante() == str60; + }); + auditorias6 = ( + from x in auditorias35 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + else + { + IEnumerable estipulante11 = + from x in auditorias11 + where x.get_Estipulante() == str60 + select x; + auditorias6 = ( + from x in estipulante11 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + List auditorias36 = auditorias6; + if (auditorias36.Count == 0) + { + continue; + } + string str61 = str60; + agrupamento1 = this.Agrupamento; + str = str61.ValidaNomePlanilha(agrupamento1.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, auditorias36, this.Relatorio, true); + num++; + } + goto Label1; + } + else + { + List auditorias37 = auditorias11; + if (auditorias37.Any((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => x.get_Selecionado())) + { + List auditorias38 = auditorias11; + auditorias7 = ( + from x in auditorias38 + where x.get_Selecionado() + select x).ToList(); + } + else + { + auditorias7 = auditorias11; + } + List auditorias39 = auditorias7; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", auditorias39, this.Relatorio, true); + goto Label1; + } + } + case 5: + { + List auditorias40 = auditorias11; + IOrderedEnumerable status10 = + from x in auditorias40 + orderby x.get_Status() + select x; + strs = ( + from x in status10 + select x.get_Status()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str62 in strs) + { + if (string.IsNullOrWhiteSpace(str62)) + { + continue; + } + List auditorias41 = auditorias11; + if (auditorias41.Any((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => x.get_Selecionado())) + { + IEnumerable auditorias42 = auditorias11.Where((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Status() == str62; + }); + auditorias8 = ( + from x in auditorias42 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + else + { + IEnumerable status11 = + from x in auditorias11 + where x.get_Status() == str62 + select x; + auditorias8 = ( + from x in status11 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + List auditorias43 = auditorias8; + if (auditorias43.Count == 0) + { + continue; + } + string str63 = str62; + agrupamento1 = this.Agrupamento; + str = str63.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, auditorias43, this.ColunasOcultas); + } + goto Label1; + } + else + { + List auditorias44 = auditorias11; + if (auditorias44.Any((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => x.get_Selecionado())) + { + List auditorias45 = auditorias11; + auditorias9 = ( + from x in auditorias45 + where x.get_Selecionado() + select x).ToList(); + } + else + { + auditorias9 = auditorias11; + } + List auditorias46 = auditorias9; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", auditorias46, this.ColunasOcultas); + goto Label1; + } + } + default: + { + List auditorias47 = auditorias11; + if (auditorias47.Any((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => x.get_Selecionado())) + { + List auditorias48 = auditorias11; + auditorias10 = ( + from x in auditorias48 + where x.get_Selecionado() + select x).ToList(); + } + else + { + auditorias10 = auditorias11; + } + List auditorias49 = auditorias10; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", auditorias49, this.Relatorio, true); + goto Label1; + } + } + } + break; + } + case 9: + case 10: + { + sinistros11 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.SinistroFiltrado == null || sinistros11.Count == 0) + { + break; + } + else + { + switch (this.Agrupamento) + { + case 1: + { + IEnumerable sinistros12 = ((GridRelatorio)this.Report).DataGrid.Items.Cast(); + IOrderedEnumerable seguradora12 = + from x in sinistros12 + orderby x.get_Seguradora() + select x; + strs = ( + from x in seguradora12 + select x.get_Seguradora()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str64 in strs) + { + if (string.IsNullOrWhiteSpace(str64)) + { + continue; + } + List sinistros13 = sinistros11; + if (sinistros13.Any((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_Selecionado())) + { + IEnumerable sinistros14 = sinistros11.Where((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Seguradora() == str64; + }); + sinistros = ( + from x in sinistros14 + orderby x.get_DataSinistro() + select x).ToList(); + } + else + { + IEnumerable seguradora13 = + from x in sinistros11 + where x.get_Seguradora() == str64 + select x; + sinistros = ( + from x in seguradora13 + orderby x.get_DataSinistro() + select x).ToList(); + } + List sinistros15 = sinistros; + if (sinistros15.Count == 0) + { + continue; + } + string str65 = str64; + agrupamento1 = this.Agrupamento; + str = str65.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, sinistros15, this.Relatorio, true); + } + goto Label1; + } + else + { + List sinistros16 = sinistros11; + if (sinistros16.Any((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_Selecionado())) + { + List sinistros17 = sinistros11; + sinistros1 = ( + from x in sinistros17 + where x.get_Selecionado() + select x).ToList(); + } + else + { + sinistros1 = sinistros11; + } + List sinistros18 = sinistros1; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", sinistros18, this.Relatorio, true); + goto Label1; + } + } + case 2: + { + IEnumerable sinistros19 = ((GridRelatorio)this.Report).DataGrid.Items.Cast(); + IOrderedEnumerable ramo12 = + from x in sinistros19 + orderby x.get_Ramo() + select x; + strs = ( + from x in ramo12 + select x.get_Ramo()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str66 in strs) + { + if (string.IsNullOrWhiteSpace(str66)) + { + continue; + } + List sinistros20 = sinistros11; + if (sinistros20.Any((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_Selecionado())) + { + IEnumerable sinistros21 = sinistros11.Where((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Ramo() == str66; + }); + sinistros2 = ( + from x in sinistros21 + orderby x.get_DataSinistro() + select x).ToList(); + } + else + { + IEnumerable ramo13 = + from x in sinistros11 + where x.get_Ramo() == str66 + select x; + sinistros2 = ( + from x in ramo13 + orderby x.get_DataSinistro() + select x).ToList(); + } + List sinistros22 = sinistros2; + if (sinistros22.Count == 0) + { + continue; + } + string str67 = str66; + agrupamento1 = this.Agrupamento; + str = str67.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, sinistros22, this.Relatorio, true); + } + goto Label1; + } + else + { + List sinistros23 = sinistros11; + if (sinistros23.Any((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_Selecionado())) + { + List sinistros24 = sinistros11; + sinistros3 = ( + from x in sinistros24 + where x.get_Selecionado() + select x).ToList(); + } + else + { + sinistros3 = sinistros11; + } + List sinistros25 = sinistros3; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", sinistros25, this.Relatorio, true); + goto Label1; + } + } + case 3: + { + IEnumerable sinistros26 = ((GridRelatorio)this.Report).DataGrid.Items.Cast(); + IOrderedEnumerable vendedor12 = + from x in sinistros26 + orderby x.get_Vendedor() + select x; + strs = ( + from x in vendedor12 + select x.get_Vendedor()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + num = 1; + foreach (string str68 in strs) + { + if (string.IsNullOrWhiteSpace(str68)) + { + continue; + } + List sinistros27 = sinistros11; + if (sinistros27.Any((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_Selecionado())) + { + IEnumerable sinistros28 = sinistros11.Where((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Vendedor() == str68; + }); + sinistros4 = ( + from x in sinistros28 + orderby x.get_DataSinistro() + select x).ToList(); + } + else + { + IEnumerable vendedor13 = + from x in sinistros11 + where x.get_Vendedor() == str68 + select x; + sinistros4 = ( + from x in vendedor13 + orderby x.get_DataSinistro() + select x).ToList(); + } + List sinistros29 = sinistros4; + if (sinistros29.Count == 0) + { + continue; + } + string str69 = str68; + agrupamento1 = this.Agrupamento; + str = str69.ValidaNomePlanilha(agrupamento1.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, sinistros29, this.Relatorio, true); + num++; + } + goto Label1; + } + else + { + List sinistros30 = sinistros11; + if (sinistros30.Any((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_Selecionado())) + { + List sinistros31 = sinistros11; + sinistros5 = ( + from x in sinistros31 + where x.get_Selecionado() + select x).ToList(); + } + else + { + sinistros5 = sinistros11; + } + List sinistros32 = sinistros5; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", sinistros32, this.Relatorio, true); + goto Label1; + } + } + case 4: + { + IEnumerable sinistros33 = ((GridRelatorio)this.Report).DataGrid.Items.Cast(); + IOrderedEnumerable estipulante12 = + from x in sinistros33 + orderby x.get_Estipulante() + select x; + strs = ( + from x in estipulante12 + select x.get_Estipulante()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + num = 1; + foreach (string str70 in strs) + { + if (string.IsNullOrWhiteSpace(str70)) + { + continue; + } + List sinistros34 = sinistros11; + if (sinistros34.Any((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_Selecionado())) + { + IEnumerable sinistros35 = sinistros11.Where((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Estipulante() == str70; + }); + sinistros6 = ( + from x in sinistros35 + orderby x.get_DataSinistro() + select x).ToList(); + } + else + { + IEnumerable estipulante13 = + from x in sinistros11 + where x.get_Estipulante() == str70 + select x; + sinistros6 = ( + from x in estipulante13 + orderby x.get_DataSinistro() + select x).ToList(); + } + List sinistros36 = sinistros6; + if (sinistros36.Count == 0) + { + continue; + } + string str71 = str70; + agrupamento1 = this.Agrupamento; + str = str71.ValidaNomePlanilha(agrupamento1.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, sinistros36, this.Relatorio, true); + num++; + } + goto Label1; + } + else + { + List sinistros37 = sinistros11; + if (sinistros37.Any((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_Selecionado())) + { + List sinistros38 = sinistros11; + sinistros7 = ( + from x in sinistros38 + where x.get_Selecionado() + select x).ToList(); + } + else + { + sinistros7 = sinistros11; + } + List sinistros39 = sinistros7; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", sinistros39, this.Relatorio, true); + goto Label1; + } + } + case 5: + { + IEnumerable sinistros40 = ((GridRelatorio)this.Report).DataGrid.Items.Cast(); + IOrderedEnumerable statusApolice = + from x in sinistros40 + orderby x.get_StatusApolice() + select x; + strs = ( + from x in statusApolice + select EnumHelper.GetDescription(x.get_StatusSinistro())).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str72 in strs) + { + if (string.IsNullOrWhiteSpace(str72)) + { + continue; + } + List sinistros41 = sinistros11; + if (sinistros41.Any((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_Selecionado())) + { + IEnumerable sinistros42 = sinistros11.Where((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_StatusApolice() == str72; + }); + sinistros8 = ( + from x in sinistros42 + orderby x.get_DataSinistro() + select x).ToList(); + } + else + { + IEnumerable statusApolice1 = + from x in sinistros11 + where x.get_StatusApolice() == str72 + select x; + sinistros8 = ( + from x in statusApolice1 + orderby x.get_DataSinistro() + select x).ToList(); + } + List sinistros43 = sinistros8; + if (sinistros43.Count == 0) + { + continue; + } + string str73 = str72; + agrupamento1 = this.Agrupamento; + str = str73.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, sinistros43, this.ColunasOcultas); + } + goto Label1; + } + else + { + List sinistros44 = sinistros11; + if (sinistros44.Any((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_Selecionado())) + { + List sinistros45 = sinistros11; + sinistros9 = ( + from x in sinistros45 + where x.get_Selecionado() + select x).ToList(); + } + else + { + sinistros9 = sinistros11; + } + List sinistros46 = sinistros9; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", sinistros46, this.ColunasOcultas); + goto Label1; + } + } + default: + { + List sinistros47 = sinistros11; + if (sinistros47.Any((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_Selecionado())) + { + List sinistros48 = sinistros11; + sinistros10 = ( + from x in sinistros48 + where x.get_Selecionado() + select x).ToList(); + } + else + { + sinistros10 = sinistros11; + } + List sinistros49 = sinistros10; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", sinistros49, this.Relatorio, true); + goto Label1; + } + } + } + break; + } + case 11: + { + List fechamentos = new List(); + if ((GridRelatorio)this.Report != null) + { + fechamentos = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + } + if (this.FechamentoFiltrado == null || fechamentos.Count == 0 && (GridRelatorio)this.Report != null) + { + break; + } + else + { + num = 1; + foreach (Fechamentos fechamento in this.Fechamento) + { + string title1 = fechamento.get_Title(); + agrupamento = this.Agrupamento; + string str74 = title1.ValidaNomePlanilha(agrupamento.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str74, fechamento.get_Fechamento().ToList(), this.Relatorio, true); + num++; + } + goto case 22; + } + } + case 12: + { + List faturaPendentes1 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.FaturaPendenteFiltrado == null || faturaPendentes1.Count == 0) + { + break; + } + else + { + List faturaPendentes2 = faturaPendentes1; + if (faturaPendentes2.Any((Gestor.Model.Domain.Relatorios.FaturaPendente.FaturaPendente x) => x.get_Selecionado())) + { + List faturaPendentes3 = faturaPendentes1; + faturaPendentes = ( + from x in faturaPendentes3 + where x.get_Selecionado() + select x).ToList(); + } + else + { + faturaPendentes = faturaPendentes1; + } + List faturaPendentes4 = faturaPendentes; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", faturaPendentes4, this.Relatorio, true); + goto case 22; + } + } + case 13: + { + List extratoBaixadoRelatorios1 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.ExtratosFiltrado == null || extratoBaixadoRelatorios1.Count == 0) + { + break; + } + else + { + List extratoBaixadoRelatorios2 = extratoBaixadoRelatorios1; + if (extratoBaixadoRelatorios2.Any((ExtratoBaixadoRelatorio x) => x.get_Selecionado())) + { + List extratoBaixadoRelatorios3 = extratoBaixadoRelatorios1; + extratoBaixadoRelatorios = ( + from x in extratoBaixadoRelatorios3 + where x.get_Selecionado() + select x).ToList(); + } + else + { + extratoBaixadoRelatorios = extratoBaixadoRelatorios1; + } + List extratoBaixadoRelatorios4 = extratoBaixadoRelatorios; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", extratoBaixadoRelatorios4, this.Relatorio, true); + goto case 22; + } + } + case 14: + { + List metaSeguradoraRelatorios1 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.MetaSeguradoraFiltrado == null || metaSeguradoraRelatorios1.Count == 0) + { + break; + } + else + { + List metaSeguradoraRelatorios2 = metaSeguradoraRelatorios1; + if (metaSeguradoraRelatorios2.Any((MetaSeguradoraRelatorio x) => x.get_Selecionado())) + { + List metaSeguradoraRelatorios3 = metaSeguradoraRelatorios1; + metaSeguradoraRelatorios = ( + from x in metaSeguradoraRelatorios3 + where x.get_Selecionado() + select x).ToList(); + } + else + { + metaSeguradoraRelatorios = metaSeguradoraRelatorios1; + } + List metaSeguradoraRelatorios4 = metaSeguradoraRelatorios; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", metaSeguradoraRelatorios4, this.Relatorio, true); + goto case 22; + } + } + case 15: + { + List metaVendedorRelatorios1 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.MetaVendedorFiltrado == null || metaVendedorRelatorios1.Count == 0) + { + break; + } + else + { + List metaVendedorRelatorios2 = metaVendedorRelatorios1; + if (metaVendedorRelatorios2.Any((MetaVendedorRelatorio x) => x.get_Selecionado())) + { + List metaVendedorRelatorios3 = metaVendedorRelatorios1; + metaVendedorRelatorios = ( + from x in metaVendedorRelatorios3 + where x.get_Selecionado() + select x).ToList(); + } + else + { + metaVendedorRelatorios = metaVendedorRelatorios1; + } + List metaVendedorRelatorios4 = metaVendedorRelatorios; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", metaVendedorRelatorios4, this.Relatorio, true); + goto case 22; + } + } + case 17: + { + List licenciamentos1 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.LicenciamentoFiltrado == null || licenciamentos1.Count == 0) + { + break; + } + else + { + List licenciamentos2 = licenciamentos1; + if (licenciamentos2.Any((Gestor.Model.Domain.Relatorios.Licenciamento.Licenciamento x) => x.get_Selecionado())) + { + List licenciamentos3 = licenciamentos1; + licenciamentos = ( + from x in licenciamentos3 + where x.get_Selecionado() + select x).ToList(); + } + else + { + licenciamentos = licenciamentos1; + } + List licenciamentos4 = licenciamentos; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", licenciamentos4, this.Relatorio, true); + goto case 22; + } + } + case 18: + { + List tarefas1 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.TarefaFiltrado == null || tarefas1.Count == 0) + { + break; + } + else + { + List tarefas2 = tarefas1; + if (tarefas2.Any((Gestor.Model.Domain.Relatorios.Tarefa.Tarefa x) => x.get_Selecionado())) + { + List tarefas3 = tarefas1; + tarefas = ( + from x in tarefas3 + where x.get_Selecionado() + select x).ToList(); + } + else + { + tarefas = tarefas1; + } + List tarefas4 = tarefas; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", tarefas4, this.Relatorio, true); + goto case 22; + } + } + case 19: + { + List notaFiscalRelatorios1 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.NotaFiscalFiltrado == null || notaFiscalRelatorios1.Count == 0) + { + break; + } + else + { + List notaFiscalRelatorios2 = notaFiscalRelatorios1; + if (notaFiscalRelatorios2.Any((NotaFiscalRelatorio x) => x.get_Selecionado())) + { + List notaFiscalRelatorios3 = notaFiscalRelatorios1; + notaFiscalRelatorios = ( + from x in notaFiscalRelatorios3 + where x.get_Selecionado() + select x).ToList(); + } + else + { + notaFiscalRelatorios = notaFiscalRelatorios1; + } + List notaFiscalRelatorios4 = notaFiscalRelatorios; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", notaFiscalRelatorios4, this.Relatorio, true); + goto case 22; + } + } + case 20: + { + if (this.PrevisaoFiltrado != null) + { + ObservableCollection previsaoSintetico = this.PrevisaoSintetico; + List previsaoPagamentoComissaoSinteticos = ( + from x in previsaoSintetico + orderby x.get_Titulo() descending + select x).ToList(); + foreach (PrevisaoPagamentoComissaoSintetico previsaoPagamentoComissaoSintetico in previsaoPagamentoComissaoSinteticos) + { + string titulo1 = previsaoPagamentoComissaoSintetico.get_Titulo(); + agrupamento = this.Agrupamento; + string str75 = titulo1.ValidaNomePlanilha(agrupamento.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str75, previsaoPagamentoComissaoSintetico.get_Agrupamento().ToList(), this.Relatorio, false); + } + num = 1; + foreach (PrevisaoPagamentoComissao previsao in this.Previsao) + { + string vendedor14 = previsao.get_Vendedor(); + agrupamento = this.Agrupamento; + string str76 = vendedor14.ValidaNomePlanilha(agrupamento.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str76, previsao.get_PrevisaoPagamento().ToList(), this.Relatorio, true); + num++; + } + goto case 22; + } + else + { + break; + } + } + case 21: + case 22: + { + Label1: + renovacaos10 = null; + producaos6 = null; + apolicePendentes8 = null; + comissaos10 = null; + list11 = null; + sinistros11 = null; + auditorias11 = null; + placas9 = null; + if (this.SinteticoRelatorio != null && this.SinteticoRelatorio.Count > 0) + { + xLWorkbook = await Funcoes.GerarXlsSintetico(xLWorkbook, "SINTÉTICO", this.Sintetic.ToList()); + } + if (this.FiltroRelatorioSelecionado != null && this.FiltroRelatorioSelecionado.Count > 0) + { + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "FILTROS", this.FiltroRelatorioSelecionado.ToList(), this.ColunasOcultas); + } + base.RegistrarAcao(string.Format("EMITIU EXCEL DO RELATÓRIO PERÍODO ENTRE {0:d} E {1:d}", this.Inicio, this.Fim), new Gestor.Model.Common.Relatorio?(this.Relatorio), this.Filtros); + xLWorkbook.SaveAs(str1); + Process.Start(str1); + break; + } + case 23: + { + List logsEnvios1 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.LogsEnvioFiltrado == null || logsEnvios1.Count == 0) + { + break; + } + else + { + List logsEnvios2 = logsEnvios1; + if (logsEnvios2.Any((Gestor.Model.Domain.Relatorios.LogsEnvio.LogsEnvio x) => x.get_Selecionado())) + { + List logsEnvios3 = logsEnvios1; + logsEnvios = ( + from x in logsEnvios3 + where x.get_Selecionado() + select x).ToList(); + } + else + { + logsEnvios = logsEnvios1; + } + List logsEnvios4 = logsEnvios; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", logsEnvios4, this.Relatorio, true); + goto case 22; + } + } + case 24: + case 25: + { + List logAcaoRelatorios1 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.LogUtilizacaoFiltrado == null || logAcaoRelatorios1.Count == 0) + { + break; + } + else + { + List logAcaoRelatorios2 = logAcaoRelatorios1; + if (logAcaoRelatorios2.Any((LogAcaoRelatorio x) => x.get_Selecionado())) + { + List logAcaoRelatorios3 = logAcaoRelatorios1; + logAcaoRelatorios = ( + from x in logAcaoRelatorios3 + where x.get_Selecionado() + select x).ToList(); + } + else + { + logAcaoRelatorios = logAcaoRelatorios1; + } + List logAcaoRelatorios4 = logAcaoRelatorios; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", logAcaoRelatorios4, this.Relatorio, true); + goto case 22; + } + } + case 26: + { + List apoliceCriticas1 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.ApoliceCriticaFiltrado == null || apoliceCriticas1.Count == 0) + { + break; + } + else + { + List apoliceCriticas2 = apoliceCriticas1; + if (apoliceCriticas2.Any((Gestor.Model.Domain.Relatorios.CriticaApolice.ApoliceCritica x) => x.get_Selecionado())) + { + List apoliceCriticas3 = apoliceCriticas1; + apoliceCriticas = ( + from x in apoliceCriticas3 + where x.get_Selecionado() + select x).ToList(); + } + else + { + apoliceCriticas = apoliceCriticas1; + } + List apoliceCriticas4 = apoliceCriticas; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", apoliceCriticas4, this.Relatorio, true); + goto case 22; + } + } + case 27: + { + placas9 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.PlacaFiltrado == null || placas9.Count == 0) + { + break; + } + else + { + switch (this.Agrupamento) + { + case 1: + { + List placas10 = placas9; + IOrderedEnumerable placas11 = + from x in placas10 + orderby x.get_Seguradora() + select x; + strs = ( + from x in placas11 + select x.get_Seguradora()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str77 in strs) + { + if (string.IsNullOrWhiteSpace(str77)) + { + continue; + } + List placas12 = placas9; + placas = (placas12.Any((Gestor.Model.Domain.Relatorios.Placa.Placas x) => x.get_Selecionado()) ? placas9.Where((Gestor.Model.Domain.Relatorios.Placa.Placas x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Seguradora() == str77; + }).ToList() : ( + from x in placas9 + where x.get_Seguradora() == str77 + select x).ToList()); + List placas13 = placas; + if (placas13.Count == 0) + { + continue; + } + string str78 = str77; + agrupamento1 = this.Agrupamento; + str = str78.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, placas13, this.Relatorio, true); + } + goto Label1; + } + else + { + List placas14 = placas9; + if (placas14.Any((Gestor.Model.Domain.Relatorios.Placa.Placas x) => x.get_Selecionado())) + { + List placas15 = placas9; + placas1 = ( + from x in placas15 + where x.get_Selecionado() + select x).ToList(); + } + else + { + placas1 = placas9; + } + List placas16 = placas1; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", placas16, this.Relatorio, true); + goto Label1; + } + } + case 2: + { + List placas17 = placas9; + IOrderedEnumerable ramo14 = + from x in placas17 + orderby x.get_Ramo() + select x; + strs = ( + from x in ramo14 + select x.get_Ramo()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str79 in strs) + { + if (string.IsNullOrWhiteSpace(str79)) + { + continue; + } + List placas18 = placas9; + placas2 = (placas18.Any((Gestor.Model.Domain.Relatorios.Placa.Placas x) => x.get_Selecionado()) ? placas9.Where((Gestor.Model.Domain.Relatorios.Placa.Placas x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Ramo() == str79; + }).ToList() : ( + from x in placas9 + where x.get_Ramo() == str79 + select x).ToList()); + List placas19 = placas2; + if (placas19.Count == 0) + { + continue; + } + string str80 = str79; + agrupamento1 = this.Agrupamento; + str = str80.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, placas19, this.Relatorio, true); + } + goto Label1; + } + else + { + List placas20 = placas9; + if (placas20.Any((Gestor.Model.Domain.Relatorios.Placa.Placas x) => x.get_Selecionado())) + { + List placas21 = placas9; + placas3 = ( + from x in placas21 + where x.get_Selecionado() + select x).ToList(); + } + else + { + placas3 = placas9; + } + List placas22 = placas3; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", placas22, this.Relatorio, true); + goto Label1; + } + } + case 3: + { + List placas23 = placas9; + IOrderedEnumerable vendedor15 = + from x in placas23 + orderby x.get_Vendedor() + select x; + strs = ( + from x in vendedor15 + select x.get_Vendedor()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + num = 1; + foreach (string str81 in strs) + { + if (string.IsNullOrWhiteSpace(str81)) + { + continue; + } + List placas24 = placas9; + placas4 = (placas24.Any((Gestor.Model.Domain.Relatorios.Placa.Placas x) => x.get_Selecionado()) ? placas9.Where((Gestor.Model.Domain.Relatorios.Placa.Placas x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Vendedor() == str81; + }).ToList() : ( + from x in placas9 + where x.get_Vendedor() == str81 + select x).ToList()); + List placas25 = placas4; + if (placas25.Count == 0) + { + continue; + } + string str82 = str81; + agrupamento1 = this.Agrupamento; + str = str82.ValidaNomePlanilha(agrupamento1.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, placas25, this.Relatorio, true); + num++; + } + goto Label1; + } + else + { + List placas26 = placas9; + if (placas26.Any((Gestor.Model.Domain.Relatorios.Placa.Placas x) => x.get_Selecionado())) + { + List placas27 = placas9; + placas5 = ( + from x in placas27 + where x.get_Selecionado() + select x).ToList(); + } + else + { + placas5 = placas9; + } + List placas28 = placas5; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", placas28, this.Relatorio, true); + goto Label1; + } + } + case 4: + { + List placas29 = placas9; + IOrderedEnumerable estipulante14 = + from x in placas29 + orderby x.get_Estipulante() + select x; + strs = ( + from x in estipulante14 + select x.get_Estipulante()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + num = 1; + foreach (string str83 in strs) + { + if (string.IsNullOrWhiteSpace(str83)) + { + continue; + } + List placas30 = placas9; + placas6 = (placas30.Any((Gestor.Model.Domain.Relatorios.Placa.Placas x) => x.get_Selecionado()) ? placas9.Where((Gestor.Model.Domain.Relatorios.Placa.Placas x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Estipulante() == str83; + }).ToList() : ( + from x in placas9 + where x.get_Estipulante() == str83 + select x).ToList()); + List placas31 = placas6; + if (placas31.Count == 0) + { + continue; + } + string str84 = str83; + agrupamento1 = this.Agrupamento; + str = str84.ValidaNomePlanilha(agrupamento1.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, placas31, this.Relatorio, true); + num++; + } + goto Label1; + } + else + { + List placas32 = placas9; + if (placas32.Any((Gestor.Model.Domain.Relatorios.Placa.Placas x) => x.get_Selecionado())) + { + List placas33 = placas9; + placas7 = ( + from x in placas33 + where x.get_Selecionado() + select x).ToList(); + } + else + { + placas7 = placas9; + } + List placas34 = placas7; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", placas34, this.Relatorio, true); + goto Label1; + } + } + default: + { + List placas35 = placas9; + if (placas35.Any((Gestor.Model.Domain.Relatorios.Placa.Placas x) => x.get_Selecionado())) + { + List placas36 = placas9; + placas8 = ( + from x in placas36 + where x.get_Selecionado() + select x).ToList(); + } + else + { + placas8 = placas9; + } + List placas37 = placas8; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", placas37, this.Relatorio, true); + goto Label1; + } + } + } + break; + } + case 28: + { + List endossos1 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.EndossoFiltrado == null || endossos1.Count == 0) + { + break; + } + else + { + List endossos2 = endossos1; + if (endossos2.Any((Endosso x) => x.get_Selecionado())) + { + List endossos3 = endossos1; + endossos = ( + from x in endossos3 + where x.get_Selecionado() + select x).ToList(); + } + else + { + endossos = endossos1; + } + List endossos4 = endossos; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", endossos4, this.Relatorio, true); + goto case 22; + } + } + case 29: + { + List classificacaos1 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.ClassificacaoFiltrado == null || classificacaos1.Count == 0) + { + break; + } + else + { + List classificacaos2 = classificacaos1; + if (classificacaos2.Any((Gestor.Model.Domain.Relatorios.Classificacao.Classificacao x) => x.get_Selecionado())) + { + List classificacaos3 = classificacaos1; + classificacaos = ( + from x in classificacaos3 + where x.get_Selecionado() + select x).ToList(); + } + else + { + classificacaos = classificacaos1; + } + List classificacaos4 = classificacaos; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", classificacaos4, this.Relatorio, true); + goto case 22; + } + } + default: + { + goto case 22; + } + } + str1 = null; + xLWorkbook = null; + strs = null; + } + + public async Task GerarHtml(bool screen = false, bool pageBreak = false, ConfiguracaoImpressao config = null, bool portrait = false) + { + // + // Current member / type: System.Threading.Tasks.Task`1 Gestor.Application.ViewModels.Relatorios.RelatorioViewModel::GerarHtml(System.Boolean,System.Boolean,Gestor.Model.Common.ConfiguracaoImpressao,System.Boolean) + // File path: C:\AggerSeguros\Gestor.Application.exe + // + // Product version: 0.0.0.0 + // Exception in: System.Threading.Tasks.Task GerarHtml(System.Boolean,System.Boolean,Gestor.Model.Common.ConfiguracaoImpressao,System.Boolean) + // + // Object reference not set to an instance of an object. + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.FindLowestCommonAncestor(ICollection`1 typeNodes) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 526 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.MergeWithLowestCommonAncestor() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 459 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.ProcessSingleConstraints() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 378 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.InferTypes() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 331 + // at Telerik.JustDecompiler.Decompiler.ExpressionDecompilerStep.Process(DecompilationContext theContext, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\ExpressionDecompilerStep.cs:line 104 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.Extensions.DecompileStateMachine(MethodBody body, DecompilationContext enclosingContext, BaseStateMachineRemoverStep removeStateMachineStep, Func`2 stateMachineDataSelector, DecompilationContext& decompilationContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 112 + // at Telerik.JustDecompiler.Decompiler.Extensions.DecompileAsyncStateMachine(MethodBody body, DecompilationContext enclosingContext, AsyncData& asyncData) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 150 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.GetMoveNextStatements() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 161 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.Match() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 76 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.Process(DecompilationContext context, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 36 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61 + // at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 133 + // + // mailto: JustDecompilePublicFeedback@telerik.com + + } + + private async Task GerarPagamento(List pagamentos) + { + ParcelaServico parcelaServico = new ParcelaServico(); + List pagamentos1 = pagamentos; + List list = pagamentos1.SelectMany((Pagamento x) => x.get_Dados()).ToList(); + List dadosRelatorios = list; + IEnumerable entidadeVendedorParcela = + from x in dadosRelatorios + where x.get_EntidadeVendedorParcela() != null + select x; + if (await parcelaServico.GerarPagamento(( + from x in entidadeVendedorParcela + select x.get_EntidadeVendedorParcela()).ToList())) + { + AdiantamentoServico adiantamentoServico = new AdiantamentoServico(); + List dadosRelatorios1 = list; + IEnumerable dadosRelatorios2 = dadosRelatorios1.Where((DadosRelatorio x) => { + if (x.get_EntidadeAdiantamento() == null) + { + return false; + } + return !x.get_DataPagamento().HasValue; + }); + await adiantamentoServico.GerarPagamento(( + from x in dadosRelatorios2 + select x.get_EntidadeAdiantamento()).ToList()); + base.RegistrarAcao(string.Format("GEROU EMISSÃO DE RECIBO ENTRE {0:d} E {1:d}", this.Inicio, this.Fim), new Gestor.Model.Common.Relatorio?(this.Relatorio), this.Filtros); + } + list = null; + } + + public async Task GerarPlanilhaCompleta() + { + List nums; + List planilhaCompletas; + bool restricao; + object list; + object obj; + bool count; + bool flag; + bool count1; + List list1; + object nums1; + object obj1; + object list2; + List nums2; + List nums3; + List planilhaCompletas1; + List planilhaCompletas2; + string str; + List restricaoUsuarios = await this.ServicoRestriUsuario.BuscarRestricoes(Recursos.Usuario.get_Id()); + RestricaoUsuario restricaoUsuario = restricaoUsuarios.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 99); + if (restricaoUsuario != null) + { + restricao = restricaoUsuario.get_Restricao(); + } + else + { + restricao = false; + } + if (restricao) + { + await base.ShowMessage("VOCÊ NÃO TEM PERMISSÃO PARA ACESSAR O PLANILHA COMPLETA", "OK", "", false); + } + else if ((this.Fim - this.Inicio).TotalDays <= 31) + { + base.Loading(true); + nums2 = new List(); + nums3 = new List(); + List configuracoes = Recursos.Configuracoes; + bool flag1 = configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 40); + bool flag2 = false; + Gestor.Model.Common.Relatorio relatorio = this.Relatorio; + if (relatorio == 2) + { + ObservableCollection producaoFiltrado = this.ProducaoFiltrado; + if (producaoFiltrado != null) + { + IEnumerable producaos = producaoFiltrado.Where((Gestor.Model.Domain.Relatorios.Producao.Producao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Tipo() != 2; + }); + list = ( + from x in producaos + select x.get_Documento().get_Id()).ToList(); + } + else + { + list = null; + } + if (list == null) + { + list = new List(); + } + nums = (List)list; + ObservableCollection observableCollection = this.ProducaoFiltrado; + if (observableCollection != null) + { + IEnumerable producaos1 = observableCollection.Where((Gestor.Model.Domain.Relatorios.Producao.Producao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Tipo() == 2; + }); + obj = ( + from x in producaos1 + select x.get_Documento().get_Id()).ToList(); + } + else + { + obj = null; + } + if (obj == null) + { + obj = new List(); + } + nums3 = (List)obj; + if (nums.Count == 0 && nums3.Count == 0) + { + await base.ShowMessage("É NECESSÁRIO SELECIONAR AO MENOS UM DOCUMENTO", "OK", "", false); + nums2 = null; + nums3 = null; + planilhaCompletas1 = null; + planilhaCompletas2 = null; + str = null; + return; + } + } + else if (relatorio == 4) + { + List configuracaoSistemas = Recursos.Configuracoes; + flag2 = configuracaoSistemas.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 31); + ObservableCollection renovacaoFiltrado = this.RenovacaoFiltrado; + if (renovacaoFiltrado != null) + { + ( + from x in renovacaoFiltrado + where x.get_Selecionado() + select x).ToList(); + } + else + { + } + ObservableCollection renovacaoFiltrado1 = this.RenovacaoFiltrado; + if (renovacaoFiltrado1 != null) + { + IEnumerable renovacaos = renovacaoFiltrado1.Where((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => { + if (!x.get_Selecionado() || x.get_Documento() == null) + { + return false; + } + return !x.get_TipoPagamento().Equals("FATURA"); + }); + nums1 = ( + from x in renovacaos + select x.get_Documento().get_Id()).ToList(); + } + else + { + nums1 = null; + } + if (nums1 == null) + { + nums1 = new List(); + } + nums = (List)nums1; + ObservableCollection observableCollection1 = this.RenovacaoFiltrado; + if (observableCollection1 != null) + { + IEnumerable renovacaos1 = observableCollection1.Where((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => { + if (!x.get_Selecionado() || x.get_Documento() == null) + { + return false; + } + return x.get_TipoPagamento().Equals("FATURA"); + }); + obj1 = ( + from x in renovacaos1 + select x.get_Documento().get_Id()).ToList(); + } + else + { + obj1 = null; + } + if (obj1 == null) + { + obj1 = new List(); + } + nums3 = (List)obj1; + ObservableCollection renovacaoFiltrado2 = this.RenovacaoFiltrado; + if (renovacaoFiltrado2 != null) + { + IEnumerable renovacaos2 = renovacaoFiltrado2.Where((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Prospeccao() != null; + }); + list2 = ( + from x in renovacaos2 + select x.get_Prospeccao().get_Id()).ToList(); + } + else + { + list2 = null; + } + if (list2 == null) + { + list2 = new List(); + } + nums2 = (List)list2; + if (nums.Count == 0 && nums3.Count == 0 && nums2.Count == 0) + { + await base.ShowMessage("É NECESSÁRIO SELECIONAR AO MENOS UM DOCUMENTO", "OK", "", false); + nums2 = null; + nums3 = null; + planilhaCompletas1 = null; + planilhaCompletas2 = null; + str = null; + return; + } + } + else + { + base.Loading(false); + nums2 = null; + nums3 = null; + planilhaCompletas1 = null; + planilhaCompletas2 = null; + str = null; + return; + } + if (nums == null || nums.Count <= 0) + { + planilhaCompletas = new List(); + } + else + { + planilhaCompletas = await this._apoliceServico.BuscarPlanilhaCompleta(nums, flag1, flag2); + } + planilhaCompletas1 = planilhaCompletas; + List nums4 = nums3; + if (nums4 != null) + { + count = nums4.Count > 0; + } + else + { + count = false; + } + if (!count) + { + planilhaCompletas = new List(); + } + else + { + planilhaCompletas = await this._apoliceServico.BuscarPlanilhaCompletaFatura(nums3, this.Relatorio, this.Filtros.get_Inicio(), this.Filtros.get_Fim(), flag1, flag2); + } + planilhaCompletas2 = planilhaCompletas; + List nums5 = nums2; + if (nums5 != null) + { + flag = nums5.Count > 0; + } + else + { + flag = false; + } + if (!flag) + { + planilhaCompletas = new List(); + } + else + { + planilhaCompletas = await this._apoliceServico.BuscarPlanilhaCompletaProspeccao(nums2); + } + List planilhaCompletas3 = planilhaCompletas; + if (planilhaCompletas1 == null || planilhaCompletas2 == null || planilhaCompletas3 == null) + { + await base.ShowMessage("ERRO AO GERAR PLANILHA COMPLETA, TENTE NOVAMENTE MAIS TARDE.", "OK", "", false); + base.Loading(false); + } + else + { + planilhaCompletas1.AddRange(planilhaCompletas2); + planilhaCompletas1.AddRange(planilhaCompletas3); + List planilhaCompletas4 = planilhaCompletas1; + if (planilhaCompletas4 != null) + { + count1 = planilhaCompletas4.Count == 0; + } + else + { + count1 = false; + } + if (!count1) + { + if (this.Relatorio == 4) + { + List planilhaCompletas5 = planilhaCompletas1; + list1 = ( + from x in planilhaCompletas5 + orderby x.get_VigenciaFinal() + select x).ToList(); + } + else + { + List planilhaCompletas6 = planilhaCompletas1; + list1 = ( + from x in planilhaCompletas6 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + planilhaCompletas1 = list1; + string tempPath = ""; + str = ""; + List configuracoes1 = Recursos.Configuracoes; + if (!configuracoes1.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 41)) + { + tempPath = Path.GetTempPath(); + str = string.Format("{0}{1}.xlsx", tempPath, Guid.NewGuid()); + } + else + { + using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog()) + { + if (DialogResult.OK == folderBrowserDialog.ShowDialog()) + { + tempPath = string.Concat(folderBrowserDialog.SelectedPath, "\\"); + Directory.CreateDirectory(tempPath); + } + else + { + nums2 = null; + nums3 = null; + planilhaCompletas1 = null; + planilhaCompletas2 = null; + str = null; + return; + } + } + string[] description = new string[] { tempPath, EnumHelper.GetDescription(this.Relatorio), " ", null, null }; + DateTime date = Functions.GetNetworkTime().Date; + description[3] = date.ToShortDateString().Replace("/", ""); + description[4] = ".xlsx"; + str = string.Concat(description); + } + await Funcoes.GerarXls(new XLWorkbook(), "PLANILHA COMPLETA", planilhaCompletas1, new List()).SaveAs(str); + Process.Start(str); + base.Loading(false); + } + else + { + await base.ShowMessage("NÃO HÁ DADOS PARA EMISSÃO DA PLANILHA COMPLETA.", "OK", "", false); + base.Loading(false); + } + } + } + else + { + await base.ShowMessage("NÃO É POSSÍVEL GERAR A PLANILHA COMPLETA COM INTERVALO MAIOR QUE 31 DIAS FILTRADOS.", "OK", "", false); + } + nums2 = null; + nums3 = null; + planilhaCompletas1 = null; + planilhaCompletas2 = null; + str = null; + } + + public async Task GerarRelatorio(DateTime? inicio, DateTime? fim) + { + // + // Current member / type: System.Threading.Tasks.Task`1 Gestor.Application.ViewModels.Relatorios.RelatorioViewModel::GerarRelatorio(System.Nullable`1,System.Nullable`1) + // File path: C:\AggerSeguros\Gestor.Application.exe + // + // Product version: 0.0.0.0 + // Exception in: System.Threading.Tasks.Task GerarRelatorio(System.Nullable,System.Nullable) + // + // An item with the same key has already been added. Key: Label0 + // at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior) + // at System.Collections.Generic.Dictionary`2.System.Collections.Generic.ICollection>.Add(KeyValuePair`2 keyValuePair) + // at Telerik.JustDecompiler.Common.Extensions.AddRange[TKey,TValue](IDictionary`2 self, IDictionary`2 source) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Common\Extensions.cs:line 101 + // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.AnonymousDelegateRebuilder.VisitObjectCreationExpression(ObjectCreationExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 351 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit[TCollection,TElement](TCollection original) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 312 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitMethodInvocationExpression(MethodInvocationExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 500 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit[TCollection,TElement](TCollection original) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 312 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitMethodInvocationExpression(MethodInvocationExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 500 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitBinaryExpression(BinaryExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 531 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitExpressionStatement(ExpressionStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 384 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit[TCollection,TElement](TCollection original) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 312 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitBlockStatement(BlockStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 338 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitIfStatement(IfStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 363 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit[TCollection,TElement](TCollection original) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 312 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitBlockStatement(BlockStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 338 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitConditionCase(ConditionCase node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 452 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit[TCollection,TElement](TCollection original) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 312 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitSwitchStatement(SwitchStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 470 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 + // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.AnonymousDelegateRebuilder.Match(BlockStatement theBlock, Int32 index) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 74 + // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.VisitBlockStatement(BlockStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 33 + // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 351 + // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.VisitTryStatement(TryStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 510 + // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 351 + // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.Visit(IEnumerable collection) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 384 + // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.Process(DecompilationContext context, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 23 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61 + // at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 133 + // + // mailto: JustDecompilePublicFeedback@telerik.com + + } + + public List GerarTarefas(Gestor.Model.Domain.Ferramentas.Tarefa tarefa) + { + List tarefas = new List(); + Usuario usuario = tarefa.get_Usuario(); + switch (this.Relatorio) + { + case 0: + { + if (this.ClientesAtivosInativosFiltrado != null && this.ClientesAtivosInativosFiltrado.Count != 0) + { + if (this.ClientesAtivosInativosFiltrado.Any((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => x.get_Selecionado())) + { + tarefas = ( + from x in this.ClientesAtivosInativosFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => { + Gestor.Model.Domain.Ferramentas.Tarefa tarefa1 = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa1.set_Entidade(2); + tarefa1.set_IdEntidade(x.get_Id()); + tarefa1.set_Agendamento(tarefa.get_Agendamento()); + tarefa1.set_Titulo(tarefa.get_Titulo()); + tarefa1.set_Descricao(tarefa.get_Anotacoes()); + tarefa1.set_Responsaveis(tarefa.get_Responsaveis()); + tarefa1.set_Usuario(usuario); + tarefa1.set_UsuarioCadastro(Recursos.Usuario); + tarefa1.set_Cliente(x.get_Nome()); + tarefa1.set_IdCliente(x.get_Id()); + return tarefa1; + }).ToList(); + return tarefas; + } + } + return null; + } + case 1: + { + if (this.ClientesAtivosInativosFiltrado != null && this.ClientesAtivosInativosFiltrado.Count != 0) + { + if (this.ClientesAtivosInativosFiltrado.Any((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => x.get_Selecionado())) + { + tarefas = ( + from x in this.ClientesAtivosInativosFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => { + Gestor.Model.Domain.Ferramentas.Tarefa tarefa2 = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa2.set_Entidade(2); + tarefa2.set_IdEntidade(x.get_Id()); + tarefa2.set_Agendamento(tarefa.get_Agendamento()); + tarefa2.set_Titulo(tarefa.get_Titulo()); + tarefa2.set_Descricao(tarefa.get_Anotacoes()); + tarefa2.set_Responsaveis(tarefa.get_Responsaveis()); + tarefa2.set_Usuario(usuario); + tarefa2.set_UsuarioCadastro(Recursos.Usuario); + tarefa2.set_Cliente(x.get_Nome()); + tarefa2.set_IdCliente(x.get_Id()); + return tarefa2; + }).ToList(); + return tarefas; + } + } + return null; + } + case 2: + case 7: + case 11: + case 12: + case 13: + { + if (this.ProducaoFiltrado != null && this.ProducaoFiltrado.Count != 0) + { + if (this.ProducaoFiltrado.Any((Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Selecionado())) + { + tarefas = ( + from x in this.ProducaoFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.Producao.Producao x) => { + Gestor.Model.Domain.Ferramentas.Tarefa tarefa3 = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa3.set_Entidade(0); + tarefa3.set_IdEntidade(x.get_Documento().get_Id()); + tarefa3.set_Agendamento(tarefa.get_Agendamento()); + tarefa3.set_Titulo(tarefa.get_Titulo()); + tarefa3.set_Descricao(tarefa.get_Anotacoes()); + tarefa3.set_Responsaveis(tarefa.get_Responsaveis()); + tarefa3.set_Usuario(usuario); + tarefa3.set_UsuarioCadastro(Recursos.Usuario); + tarefa3.set_Cliente(x.get_Documento().get_Controle().get_Cliente().get_Nome()); + tarefa3.set_IdCliente(x.get_Documento().get_Controle().get_Cliente().get_Id()); + tarefa3.set_Referencia((x.get_Documento().get_Tipo() != 0 || string.IsNullOrWhiteSpace(x.get_Documento().get_Apolice()) ? (x.get_Documento().get_Tipo() > 0 ? string.Concat("APÓLICE NÚMERO ", x.get_Documento().get_Apolice(), " ENDOSSO ", x.get_Documento().get_Endosso()) : string.Concat("PROPOSTA NÚMERO ", x.get_Documento().get_Proposta())) : string.Concat("APÓLICE NÚMERO ", x.get_Documento().get_Apolice()))); + return tarefa3; + }).ToList(); + return tarefas; + } + } + return null; + } + case 3: + { + if (this.ApolicePendenteFiltrado != null && this.ApolicePendenteFiltrado.Count != 0) + { + if (this.ApolicePendenteFiltrado.Any((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => x.get_Selecionado())) + { + tarefas = ( + from x in this.ApolicePendenteFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => { + Gestor.Model.Domain.Ferramentas.Tarefa tarefa4 = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa4.set_Entidade(0); + tarefa4.set_IdEntidade(x.get_Documento().get_Id()); + tarefa4.set_Agendamento(tarefa.get_Agendamento()); + tarefa4.set_Titulo(tarefa.get_Titulo()); + tarefa4.set_Descricao(tarefa.get_Anotacoes()); + tarefa4.set_Responsaveis(tarefa.get_Responsaveis()); + tarefa4.set_Usuario(usuario); + tarefa4.set_UsuarioCadastro(Recursos.Usuario); + tarefa4.set_Cliente(x.get_Documento().get_Controle().get_Cliente().get_Nome()); + tarefa4.set_IdCliente(x.get_Documento().get_Controle().get_Cliente().get_Id()); + tarefa4.set_Referencia((x.get_Documento().get_Tipo() != 0 || string.IsNullOrWhiteSpace(x.get_Documento().get_Apolice()) ? (x.get_Documento().get_Tipo() > 0 ? string.Concat("APÓLICE NÚMERO ", x.get_Documento().get_Apolice(), " ENDOSSO ", x.get_Documento().get_Endosso()) : string.Concat("PROPOSTA NÚMERO ", x.get_Documento().get_Proposta())) : string.Concat("APÓLICE NÚMERO ", x.get_Documento().get_Apolice()))); + return tarefa4; + }).ToList(); + return tarefas; + } + } + return null; + } + case 4: + { + if (this.RenovacaoFiltrado != null && this.RenovacaoFiltrado.Count != 0) + { + if (this.RenovacaoFiltrado.Any((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.get_Selecionado())) + { + IEnumerable renovacaoFiltrado = + from x in this.RenovacaoFiltrado + where x.get_Documento() != null + select x; + IEnumerable renovacaos = + from x in this.RenovacaoFiltrado + where x.get_Prospeccao() != null + select x; + List list = new List(); + List tarefas1 = new List(); + Gestor.Model.Domain.Relatorios.Renovacao.Renovacao[] array = renovacaoFiltrado as Gestor.Model.Domain.Relatorios.Renovacao.Renovacao[] ?? renovacaoFiltrado.ToArray(); + if (array.Any()) + { + list = ( + from x in array + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => { + Gestor.Model.Domain.Ferramentas.Tarefa tarefa5 = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa5.set_Entidade(0); + tarefa5.set_IdEntidade(x.get_Documento().get_Id()); + tarefa5.set_Agendamento(tarefa.get_Agendamento()); + tarefa5.set_Titulo(tarefa.get_Titulo()); + tarefa5.set_Descricao(tarefa.get_Anotacoes()); + tarefa5.set_Responsaveis(tarefa.get_Responsaveis()); + tarefa5.set_Usuario(usuario); + tarefa5.set_UsuarioCadastro(Recursos.Usuario); + tarefa5.set_Cliente(x.get_Documento().get_Controle().get_Cliente().get_Nome()); + tarefa5.set_IdCliente(x.get_Documento().get_Controle().get_Cliente().get_Id()); + tarefa5.set_Referencia((x.get_Documento().get_Tipo() != 0 || string.IsNullOrWhiteSpace(x.get_Documento().get_Apolice()) ? (x.get_Documento().get_Tipo() > 0 ? string.Concat("APÓLICE NÚMERO ", x.get_Documento().get_Apolice(), " ENDOSSO ", x.get_Documento().get_Endosso()) : string.Concat("PROPOSTA NÚMERO ", x.get_Documento().get_Proposta())) : string.Concat("APÓLICE NÚMERO ", x.get_Documento().get_Apolice()))); + return tarefa5; + }).ToList(); + } + Gestor.Model.Domain.Relatorios.Renovacao.Renovacao[] renovacaoArray = renovacaos as Gestor.Model.Domain.Relatorios.Renovacao.Renovacao[] ?? renovacaos.ToArray(); + if (renovacaoArray.Any()) + { + tarefas1 = ( + from x in renovacaoArray + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => { + Gestor.Model.Domain.Ferramentas.Tarefa tarefa6 = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa6.set_Entidade(5); + tarefa6.set_IdEntidade(x.get_Prospeccao().get_Id()); + tarefa6.set_Agendamento(tarefa.get_Agendamento()); + tarefa6.set_Titulo(tarefa.get_Titulo()); + tarefa6.set_Descricao(tarefa.get_Anotacoes()); + tarefa6.set_Responsaveis(tarefa.get_Responsaveis()); + tarefa6.set_Usuario(usuario); + tarefa6.set_UsuarioCadastro(Recursos.Usuario); + tarefa6.set_Cliente(x.get_Prospeccao().get_Nome()); + DateTime? vigenciaFinal = x.get_VigenciaFinal(); + tarefa6.set_Referencia(string.Concat("PROSPECÇÃO ", (vigenciaFinal.HasValue ? vigenciaFinal.GetValueOrDefault().ToString("d") : null))); + return tarefa6; + }).ToList(); + } + tarefas.AddRange(list); + tarefas.AddRange(tarefas1); + if (tarefas.Count <= 0) + { + return null; + } + return tarefas; + } + } + return null; + } + case 5: + { + if (this.ComissaoFiltrado != null && this.ComissaoFiltrado.Count != 0) + { + if (this.ComissaoFiltrado.Any((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Selecionado())) + { + tarefas = ( + from x in this.ComissaoFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => { + Gestor.Model.Domain.Ferramentas.Tarefa tarefa7 = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa7.set_Entidade(3); + tarefa7.set_IdEntidade(x.get_ParcelaEntity().get_Id()); + tarefa7.set_Agendamento(tarefa.get_Agendamento()); + tarefa7.set_Titulo(tarefa.get_Titulo()); + tarefa7.set_Descricao(tarefa.get_Anotacoes()); + tarefa7.set_Usuario(usuario); + tarefa7.set_UsuarioCadastro(Recursos.Usuario); + tarefa7.set_Cliente(x.get_Documento().get_Controle().get_Cliente().get_Nome()); + tarefa7.set_IdCliente(x.get_Documento().get_Controle().get_Cliente().get_Id()); + tarefa7.set_Referencia((x.get_Documento().get_Tipo() != 0 || string.IsNullOrWhiteSpace(x.get_Documento().get_Apolice()) ? (x.get_Documento().get_Tipo() > 0 ? string.Concat(new string[] { "PARCELA ", x.get_Parcela(), " DA APÓLICE ", x.get_Documento().get_Apolice(), " ENDOSSO ", x.get_Documento().get_Endosso() }) : string.Concat("PARCELA ", x.get_Parcela(), " DA PROPOSTA ", x.get_Documento().get_Proposta())) : string.Concat("PARCELA ", x.get_Parcela(), " DA APÓLICE ", x.get_Documento().get_Apolice()))); + tarefa7.set_Responsaveis(tarefa.get_Responsaveis()); + return tarefa7; + }).ToList(); + return tarefas; + } + } + return null; + } + case 6: + case 16: + { + if (this.PendenteFiltrado != null && this.PendenteFiltrado.Count != 0) + { + if (this.PendenteFiltrado.Any((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_Selecionado())) + { + tarefas = ( + from x in this.PendenteFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => { + Gestor.Model.Domain.Ferramentas.Tarefa tarefa8 = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa8.set_Entidade(3); + tarefa8.set_IdEntidade(x.get_ParcelaEntity().get_Id()); + tarefa8.set_Agendamento(tarefa.get_Agendamento()); + tarefa8.set_Titulo(tarefa.get_Titulo()); + tarefa8.set_Descricao(tarefa.get_Anotacoes()); + tarefa8.set_Usuario(usuario); + tarefa8.set_UsuarioCadastro(Recursos.Usuario); + tarefa8.set_Cliente(x.get_Documento().get_Controle().get_Cliente().get_Nome()); + tarefa8.set_IdCliente(x.get_Documento().get_Controle().get_Cliente().get_Id()); + tarefa8.set_Referencia((x.get_Documento().get_Tipo() != 0 || string.IsNullOrWhiteSpace(x.get_Documento().get_Apolice()) ? (x.get_Documento().get_Tipo() > 0 ? string.Format("PARCELA {0} DA APÓLICE {1} ENDOSSO {2}", x.get_ParcelaEntity().get_NumeroParcela(), x.get_Documento().get_Apolice(), x.get_Documento().get_Endosso()) : string.Format("PARCELA {0} DA PROPOSTA {1}", x.get_ParcelaEntity().get_NumeroParcela(), x.get_Documento().get_Proposta())) : string.Format("PARCELA {0} DA APÓLICE {1}", x.get_ParcelaEntity().get_NumeroParcela(), x.get_Documento().get_Apolice()))); + tarefa8.set_Responsaveis(tarefa.get_Responsaveis()); + return tarefa8; + }).ToList(); + return tarefas; + } + } + return null; + } + case 8: + { + if (this.AuditoriaFiltrado != null && this.AuditoriaFiltrado.Count != 0) + { + if (this.AuditoriaFiltrado.Any((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => x.get_Selecionado())) + { + tarefas = ( + from x in this.AuditoriaFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => { + Gestor.Model.Domain.Ferramentas.Tarefa tarefa9 = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa9.set_Entidade(0); + tarefa9.set_IdEntidade(x.get_Documento().get_Id()); + tarefa9.set_Agendamento(tarefa.get_Agendamento()); + tarefa9.set_Titulo(tarefa.get_Titulo()); + tarefa9.set_Descricao(tarefa.get_Anotacoes()); + tarefa9.set_Responsaveis(tarefa.get_Responsaveis()); + tarefa9.set_Usuario(usuario); + tarefa9.set_UsuarioCadastro(Recursos.Usuario); + tarefa9.set_Cliente(x.get_Documento().get_Controle().get_Cliente().get_Nome()); + tarefa9.set_IdCliente(x.get_Documento().get_Controle().get_Cliente().get_Id()); + tarefa9.set_Referencia((x.get_Documento().get_Tipo() != 0 || string.IsNullOrWhiteSpace(x.get_Documento().get_Apolice()) ? (x.get_Documento().get_Tipo() > 0 ? string.Concat("APÓLICE NÚMERO ", x.get_Documento().get_Apolice(), " ENDOSSO ", x.get_Documento().get_Endosso()) : string.Concat("PROPOSTA NÚMERO ", x.get_Documento().get_Proposta())) : string.Concat("APÓLICE NÚMERO ", x.get_Documento().get_Apolice()))); + return tarefa9; + }).ToList(); + return tarefas; + } + } + return null; + } + case 9: + case 10: + { + if (this.SinistroFiltrado != null && this.SinistroFiltrado.Count != 0) + { + if (this.SinistroFiltrado.Any((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_Selecionado())) + { + tarefas = ( + from x in this.SinistroFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => { + Gestor.Model.Domain.Ferramentas.Tarefa tarefa10 = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa10.set_Entidade(4); + tarefa10.set_IdEntidade(x.get_EntidadeSinistro().get_Id()); + tarefa10.set_Agendamento(tarefa.get_Agendamento()); + tarefa10.set_Titulo(tarefa.get_Titulo()); + tarefa10.set_Descricao(tarefa.get_Anotacoes()); + tarefa10.set_Usuario(usuario); + tarefa10.set_UsuarioCadastro(Recursos.Usuario); + tarefa10.set_Cliente(x.get_Nome()); + tarefa10.set_IdCliente(x.get_EntidadeSinistro().get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Cliente().get_Id()); + tarefa10.set_Referencia(string.Concat("SINISTRO ", x.get_NumeroSinistro(), " - ITEM ", x.get_Item())); + tarefa10.set_Responsaveis(tarefa.get_Responsaveis()); + return tarefa10; + }).ToList(); + return tarefas; + } + } + return null; + } + case 14: + { + if (this.MetaSeguradoraFiltrado != null && this.MetaSeguradoraFiltrado.Count != 0) + { + if (this.MetaSeguradoraFiltrado.Any((MetaSeguradoraRelatorio x) => x.get_Selecionado())) + { + tarefas = ( + from x in this.MetaSeguradoraFiltrado + where x.get_Selecionado() + select x).Select((MetaSeguradoraRelatorio x) => { + Gestor.Model.Domain.Ferramentas.Tarefa tarefa11 = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa11.set_Entidade(7); + tarefa11.set_IdEntidade(x.get_Id()); + tarefa11.set_Agendamento(tarefa.get_Agendamento()); + tarefa11.set_Titulo(tarefa.get_Titulo()); + tarefa11.set_Descricao(tarefa.get_Anotacoes()); + tarefa11.set_Responsaveis(tarefa.get_Responsaveis()); + tarefa11.set_Usuario(usuario); + tarefa11.set_UsuarioCadastro(Recursos.Usuario); + tarefa11.set_Cliente(x.get_Seguradora()); + tarefa11.set_Referencia(string.Concat("SEGURADORA ", x.get_Seguradora())); + return tarefa11; + }).ToList(); + return tarefas; + } + } + return null; + } + case 15: + { + if (this.MetaVendedorFiltrado != null && this.MetaVendedorFiltrado.Count != 0) + { + if (this.MetaVendedorFiltrado.Any((MetaVendedorRelatorio x) => x.get_Selecionado())) + { + tarefas = ( + from x in this.MetaVendedorFiltrado + where x.get_Selecionado() + select x).Select((MetaVendedorRelatorio x) => { + Gestor.Model.Domain.Ferramentas.Tarefa tarefa12 = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa12.set_Entidade(6); + tarefa12.set_IdEntidade(x.get_Id()); + tarefa12.set_Agendamento(tarefa.get_Agendamento()); + tarefa12.set_Titulo(tarefa.get_Titulo()); + tarefa12.set_Descricao(tarefa.get_Anotacoes()); + tarefa12.set_Responsaveis(tarefa.get_Responsaveis()); + tarefa12.set_Usuario(usuario); + tarefa12.set_UsuarioCadastro(Recursos.Usuario); + tarefa12.set_Cliente(x.get_Vendedor()); + tarefa12.set_Referencia(string.Concat("VENDEDOR ", x.get_Vendedor())); + return tarefa12; + }).ToList(); + return tarefas; + } + } + return null; + } + case 17: + { + if (this.LicenciamentoFiltrado != null && this.LicenciamentoFiltrado.Count != 0) + { + if (this.LicenciamentoFiltrado.Any((Gestor.Model.Domain.Relatorios.Licenciamento.Licenciamento x) => x.get_Selecionado())) + { + tarefas = ( + from x in this.LicenciamentoFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.Licenciamento.Licenciamento x) => { + Gestor.Model.Domain.Ferramentas.Tarefa tarefa13 = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa13.set_Entidade(2); + tarefa13.set_IdEntidade(x.get_Documento().get_Controle().get_Cliente().get_Id()); + tarefa13.set_Agendamento(tarefa.get_Agendamento()); + tarefa13.set_Titulo(tarefa.get_Titulo()); + tarefa13.set_Descricao(tarefa.get_Anotacoes()); + tarefa13.set_Usuario(usuario); + tarefa13.set_UsuarioCadastro(Recursos.Usuario); + tarefa13.set_Cliente(x.get_Cliente()); + tarefa13.set_IdCliente(x.get_Documento().get_Controle().get_Cliente().get_Id()); + tarefa13.set_Referencia(string.Concat("VENCIMENTO CRLV ", x.get_Placa(), " - ITEM ", x.get_Item())); + tarefa13.set_Responsaveis(tarefa.get_Responsaveis()); + return tarefa13; + }).ToList(); + return tarefas; + } + } + return null; + } + default: + { + goto case 13; + } + } + } + + private static string JoinEmails(List emails) + { + if (emails == null) + { + return ""; + } + return string.Join(" | ", ( + from v in emails + where !string.IsNullOrEmpty(v.get_Email()) + select v.get_Email()).Distinct()); + } + + private static string JoinTelefones(List telefones) + { + if (telefones == null) + { + return ""; + } + return string.Join(" | ", + from v in telefones + select string.Concat(v.get_Prefixo(), " ", v.get_Numero())); + } + + public void LimparFiltros() + { + this._alterandoFiltros = true; + this.FiltroRelatorioSelecionado = null; + foreach (StatusRelatorio statusRelatorio in + from x in this.TipoSeguros + where x.get_Selecionado() + select x) + { + statusRelatorio.set_Selecionado(false); + } + foreach (Seguradora seguradora in + from x in this.Seguradoras + where x.get_Selecionado() + select x) + { + seguradora.set_Selecionado(false); + } + foreach (Ramo ramo in + from x in this.Ramos + where x.get_Selecionado() + select x) + { + ramo.set_Selecionado(false); + } + foreach (Estipulante estipulante in + from x in this.Estipulantes + where x.get_Selecionado() + select x) + { + estipulante.set_Selecionado(false); + } + foreach (Vendedor vendedor in + from x in this.Vendedores + where x.get_Selecionado() + select x) + { + vendedor.set_Selecionado(false); + } + foreach (Gestor.Model.Domain.Seguros.TipoVendedor tipoVendedor in + from x in this.TipoVendedor + where x.get_Selecionado() + select x) + { + tipoVendedor.set_Selecionado(false); + } + foreach (Gestor.Model.Domain.Seguros.Produto produto in + from x in this.Produtos + where x.get_Selecionado() + select x) + { + produto.set_Selecionado(false); + } + foreach (NegocioRelatorio negocioRelatorio in + from x in this.Negocios + where x.get_Selecionado() + select x) + { + negocioRelatorio.set_Selecionado(false); + } + this._alterandoFiltros = false; + } + + private void LimparFiltroUsuario() + { + ExtensionMethods.ForEach(this.UsuariosFiltrados, (Usuario x) => x.set_Selecionado(false)); + } + + public void LimparRelatorio() + { + this.RelatorioVisibility = false; + this.VisibilityFiltroPersonalizado = Visibility.Collapsed; + } + + private async Task LoadVendedores() + { + List list; + this.Vinculo = await base.VerificaVinculoVendedor(Recursos.Usuario); + RelatorioViewModel relatorioViewModel = this; + if (this.Vinculo.Count > 0) + { + IEnumerable vendedores = + from x in Recursos.Vendedores + where this.Vinculo.Any((VendedorUsuario y) => y.get_Vendedor().get_Id() == x.get_Id()) + select x; + list = ( + from x in vendedores + orderby x.get_Nome() + select x).ToList(); + } + else + { + List vendedors = Recursos.Vendedores; + IEnumerable vendedors1 = vendedors.Where((Vendedor x) => { + if (Recursos.Usuario.get_IdEmpresa() == (long)1) + { + return true; + } + return x.get_IdEmpresa() == Recursos.Usuario.get_IdEmpresa(); + }); + list = ( + from x in vendedors1 + orderby x.get_Nome() + select x).ToList(); + } + relatorioViewModel.Vendedores = list; + RelatorioViewModel list1 = this; + List usuarios = Recursos.Usuarios; + IEnumerable excluido = + from x in usuarios + where !x.get_Excluido() + select x; + list1.Usuarios = ( + from x in excluido + orderby x.get_Nome() + select x).ToList(); + this.UsuariosFiltrados = new ObservableCollection(this.Usuarios); + } + + public async void MostrarProtocolo() + { + switch (this.Relatorio) + { + case 2: + { + ObservableCollection producaoFiltrado = this.ProducaoFiltrado; + if (producaoFiltrado.Any((Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Selecionado())) + { + RelatorioViewModel relatorioViewModel = this; + ObservableCollection observableCollection = this.ProducaoFiltrado; + IEnumerable selecionado = + from x in observableCollection + where x.get_Selecionado() + select x; + this.PrepararProtocolo(await relatorioViewModel.ShowProtocoloDialog(( + from x in selecionado + select x.get_Documento()).ToList())); + break; + } + else + { + await base.ShowMessage("NECESSÁRIO SELECIONAR OS DOCUMENTOS PARA EMISSÃO DE PROTOCOLO", "OK", "", false); + break; + } + } + case 3: + { + ObservableCollection apolicePendenteFiltrado = this.ApolicePendenteFiltrado; + if (apolicePendenteFiltrado.Any((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => x.get_Selecionado())) + { + RelatorioViewModel relatorioViewModel1 = this; + ObservableCollection apolicePendenteFiltrado1 = this.ApolicePendenteFiltrado; + IEnumerable apolicePendentes = + from x in apolicePendenteFiltrado1 + where x.get_Selecionado() + select x; + this.PrepararProtocolo(await relatorioViewModel1.ShowProtocoloDialog(( + from x in apolicePendentes + select x.get_Documento()).ToList())); + break; + } + else + { + await base.ShowMessage("NECESSÁRIO SELECIONAR OS DOCUMENTOS PARA EMISSÃO DE PROTOCOLO", "OK", "", false); + break; + } + } + case 4: + { + ObservableCollection renovacaoFiltrado = this.RenovacaoFiltrado; + if (renovacaoFiltrado.Any((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.get_Selecionado())) + { + RelatorioViewModel relatorioViewModel2 = this; + ObservableCollection renovacaoFiltrado1 = this.RenovacaoFiltrado; + IEnumerable renovacaos = + from x in renovacaoFiltrado1 + where x.get_Selecionado() + select x; + this.PrepararProtocolo(await relatorioViewModel2.ShowProtocoloDialog(( + from x in renovacaos + select x.get_Documento()).ToList())); + break; + } + else + { + await base.ShowMessage("NECESSÁRIO SELECIONAR OS DOCUMENTOS PARA EMISSÃO DE PROTOCOLO", "OK", "", false); + break; + } + } + } + } + + private void NegocioOnPropertyChanged(object sender, PropertyChangedEventArgs args) + { + if (this._alterandoFiltros) + { + return; + } + this.RecheckAllSelected(9); + } + + public void PesquisaPersonalizada() + { + switch (this.Relatorio) + { + case 0: + { + this.FiltrarRamo(); + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 1: + { + this.ClientesAtivosInativosFiltrado = new ObservableCollection(this.ClientesAtivosInativos.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.ClientesAtivosInativosFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 2: + { + this.ProducaoFiltrado = new ObservableCollection(this.Producao.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.ProducaoFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 3: + { + this.ApolicePendenteFiltrado = new ObservableCollection(this.ApolicePendente.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.ApolicePendenteFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 4: + { + this.RenovacaoFiltrado = new ObservableCollection(this.Renovacao.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.RenovacaoFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 5: + { + this.ComissaoFiltrado = new ObservableCollection(this.Comissao.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.ComissaoFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 6: + case 16: + { + this.PendenteFiltrado = new ObservableCollection(this.Pendente.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.PendenteFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 7: + case 11: + case 20: + case 21: + case 22: + { + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 8: + { + this.AuditoriaFiltrado = new ObservableCollection(this.Auditoria.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.AuditoriaFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 9: + case 10: + { + this.SinistroFiltrado = new ObservableCollection(this.Sinistro.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.SinistroFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 12: + { + this.FaturaPendenteFiltrado = new ObservableCollection(this.FaturaPendente.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.FaturaPendenteFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 13: + { + this.ExtratosFiltrado = new ObservableCollection(this.Extratos.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.ExtratosFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 14: + { + this.MetaSeguradoraFiltrado = new ObservableCollection(this.MetaSeguradora.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.MetaSeguradoraFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 15: + { + this.MetaVendedorFiltrado = new ObservableCollection(this.MetaVendedor.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.MetaVendedorFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 17: + { + this.LicenciamentoFiltrado = new ObservableCollection(this.Licenciamento.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.LicenciamentoFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 18: + { + this.TarefaFiltrado = new ObservableCollection(this.Tarefa.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.TarefaFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 19: + { + this.NotaFiscalFiltrado = new ObservableCollection(this.NotasFiscais.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.NotaFiscalFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 23: + { + this.LogsEnvioFiltrado = new ObservableCollection(this.LogsEnvio.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.LogsEnvioFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 24: + case 25: + { + this.LogUtilizacaoFiltrado = new ObservableCollection(this.LogUtilizacao.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.LogUtilizacaoFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 26: + { + this.ApoliceCriticaFiltrado = new ObservableCollection(this.ApoliceCritica.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.ApoliceCriticaFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 27: + { + this.PlacaFiltrado = new ObservableCollection(this.Placas.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.PlacaFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 28: + { + this.EndossoFiltrado = new ObservableCollection(this.Endossoo.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.EndossoFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 29: + { + this.ClassificacaoFiltrado = new ObservableCollection(this.Classificacao.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.ClassificacaoFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + default: + { + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + } + } + + private async void PopularRelatorio(string opcao) + { + bool restricao; + bool flag; + bool restricao1; + bool flag1; + bool restricao2; + bool flag2; + bool restricao3; + bool flag3; + bool restricao4; + bool flag4; + bool restricao5; + bool flag5; + bool restricao6; + bool flag6; + bool restricao7; + bool flag7; + bool restricao8; + bool flag8; + bool restricao9; + bool flag9; + bool restricao10; + bool flag10; + bool restricao11; + bool flag11; + bool restricao12; + bool flag12; + bool restricao13; + bool flag13; + this.Relatorios = new List(); + List restricaoUsuarios = await this.ServicoRestriUsuario.BuscarRestricoes(Recursos.Usuario.get_Id()); + Gestor.Model.Common.Relatorio[] values = (Gestor.Model.Common.Relatorio[])Enum.GetValues(typeof(Gestor.Model.Common.Relatorio)); + foreach (Gestor.Model.Common.Relatorio relatorio in + from x in values + orderby EnumHelper.GetDescription(x) + select x) + { + if (Gestor.Common.Validation.ValidationHelper.GetTipo(relatorio) != opcao) + { + continue; + } + switch (relatorio) + { + case 0: + { + List restricaoUsuarios1 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario = restricaoUsuarios1.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 30); + if (restricaoUsuario != null) + { + restricao = restricaoUsuario.get_Restricao(); + } + else + { + restricao = false; + } + if (restricao) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 1: + { + List restricaoUsuarios2 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario1 = restricaoUsuarios2.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 49); + if (restricaoUsuario1 != null) + { + flag = restricaoUsuario1.get_Restricao(); + } + else + { + flag = false; + } + if (flag) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 2: + { + List restricaoUsuarios3 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario2 = restricaoUsuarios3.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 23); + if (restricaoUsuario2 != null) + { + restricao1 = restricaoUsuario2.get_Restricao(); + } + else + { + restricao1 = false; + } + if (restricao1) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 3: + { + List restricaoUsuarios4 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario3 = restricaoUsuarios4.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 34); + if (restricaoUsuario3 != null) + { + flag1 = restricaoUsuario3.get_Restricao(); + } + else + { + flag1 = false; + } + if (flag1) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 4: + { + List restricaoUsuarios5 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario4 = restricaoUsuarios5.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 24); + if (restricaoUsuario4 != null) + { + restricao2 = restricaoUsuario4.get_Restricao(); + } + else + { + restricao2 = false; + } + if (restricao2) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 5: + { + List restricaoUsuarios6 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario5 = restricaoUsuarios6.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 27); + if (restricaoUsuario5 != null) + { + flag2 = restricaoUsuario5.get_Restricao(); + } + else + { + flag2 = false; + } + if (flag2) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 6: + { + List restricaoUsuarios7 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario6 = restricaoUsuarios7.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 29); + if (restricaoUsuario6 != null) + { + restricao3 = restricaoUsuario6.get_Restricao(); + } + else + { + restricao3 = false; + } + if (restricao3) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 7: + { + List restricaoUsuarios8 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario7 = restricaoUsuarios8.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 28); + if (restricaoUsuario7 != null) + { + flag3 = restricaoUsuario7.get_Restricao(); + } + else + { + flag3 = false; + } + if (flag3) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 8: + { + List restricaoUsuarios9 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario8 = restricaoUsuarios9.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 46); + if (restricaoUsuario8 != null) + { + restricao4 = restricaoUsuario8.get_Restricao(); + } + else + { + restricao4 = false; + } + if (restricao4) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 9: + { + List restricaoUsuarios10 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario9 = restricaoUsuarios10.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 25); + if (restricaoUsuario9 != null) + { + flag4 = restricaoUsuario9.get_Restricao(); + } + else + { + flag4 = false; + } + if (flag4) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 10: + { + List restricaoUsuarios11 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario10 = restricaoUsuarios11.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 26); + if (restricaoUsuario10 != null) + { + restricao5 = restricaoUsuario10.get_Restricao(); + } + else + { + restricao5 = false; + } + if (restricao5) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 11: + { + List restricaoUsuarios12 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario11 = restricaoUsuarios12.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 41); + if (restricaoUsuario11 != null) + { + flag5 = restricaoUsuario11.get_Restricao(); + } + else + { + flag5 = false; + } + if (flag5) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 12: + { + List restricaoUsuarios13 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario12 = restricaoUsuarios13.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 51); + if (restricaoUsuario12 != null) + { + restricao6 = restricaoUsuario12.get_Restricao(); + } + else + { + restricao6 = false; + } + if (restricao6) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 13: + { + List restricaoUsuarios14 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario13 = restricaoUsuarios14.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 50); + if (restricaoUsuario13 != null) + { + flag6 = restricaoUsuario13.get_Restricao(); + } + else + { + flag6 = false; + } + if (flag6) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 14: + { + List restricaoUsuarios15 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario14 = restricaoUsuarios15.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 52); + if (restricaoUsuario14 != null) + { + restricao7 = restricaoUsuario14.get_Restricao(); + } + else + { + restricao7 = false; + } + if (restricao7) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 15: + { + List restricaoUsuarios16 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario15 = restricaoUsuarios16.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 53); + if (restricaoUsuario15 != null) + { + flag7 = restricaoUsuario15.get_Restricao(); + } + else + { + flag7 = false; + } + if (flag7) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 16: + { + List restricaoUsuarios17 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario16 = restricaoUsuarios17.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 62); + if (restricaoUsuario16 != null) + { + restricao8 = restricaoUsuario16.get_Restricao(); + } + else + { + restricao8 = false; + } + if (restricao8) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 17: + { + List restricaoUsuarios18 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario17 = restricaoUsuarios18.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 63); + if (restricaoUsuario17 != null) + { + flag8 = restricaoUsuario17.get_Restricao(); + } + else + { + flag8 = false; + } + if (flag8) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 18: + { + List restricaoUsuarios19 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario18 = restricaoUsuarios19.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 31); + if (restricaoUsuario18 != null) + { + restricao9 = restricaoUsuario18.get_Restricao(); + } + else + { + restricao9 = false; + } + if (restricao9) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 19: + { + List restricaoUsuarios20 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario19 = restricaoUsuarios20.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 90); + if (restricaoUsuario19 != null) + { + flag9 = restricaoUsuario19.get_Restricao(); + } + else + { + flag9 = false; + } + if (flag9) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 20: + { + List restricaoUsuarios21 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario20 = restricaoUsuarios21.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 91); + if (restricaoUsuario20 != null) + { + restricao10 = restricaoUsuario20.get_Restricao(); + } + else + { + restricao10 = false; + } + if (restricao10) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 23: + { + List restricaoUsuarios22 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario21 = restricaoUsuarios22.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 96); + if (restricaoUsuario21 != null) + { + flag10 = restricaoUsuario21.get_Restricao(); + } + else + { + flag10 = false; + } + if (flag10) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 24: + { + List restricaoUsuarios23 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario22 = restricaoUsuarios23.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 98); + if (restricaoUsuario22 != null) + { + restricao11 = restricaoUsuario22.get_Restricao(); + } + else + { + restricao11 = false; + } + if (restricao11) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 25: + { + List restricaoUsuarios24 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario23 = restricaoUsuarios24.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 98); + if (restricaoUsuario23 != null) + { + flag11 = restricaoUsuario23.get_Restricao(); + } + else + { + flag11 = false; + } + if (flag11) + { + continue; + } + List configuracoes = Recursos.Configuracoes; + if (configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 22)) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 26: + { + List restricaoUsuarios25 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario24 = restricaoUsuarios25.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 107); + if (restricaoUsuario24 != null) + { + restricao12 = restricaoUsuario24.get_Restricao(); + } + else + { + restricao12 = false; + } + if (restricao12) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 27: + { + List restricaoUsuarios26 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario25 = restricaoUsuarios26.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 111); + if (restricaoUsuario25 != null) + { + flag12 = restricaoUsuario25.get_Restricao(); + } + else + { + flag12 = false; + } + if (flag12) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 28: + { + List restricaoUsuarios27 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario26 = restricaoUsuarios27.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 112); + if (restricaoUsuario26 != null) + { + restricao13 = restricaoUsuario26.get_Restricao(); + } + else + { + restricao13 = false; + } + if (restricao13) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 29: + { + List restricaoUsuarios28 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario27 = restricaoUsuarios28.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 30); + if (restricaoUsuario27 != null) + { + flag13 = restricaoUsuario27.get_Restricao(); + } + else + { + flag13 = false; + } + if (flag13) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + default: + { + continue; + } + } + } + this.Relatorio = this.Relatorios.FirstOrDefault(); + } + + private async Task PostMonitor() + { + try + { + using (HttpClient httpClient = new HttpClient()) + { + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + httpClient.set_Timeout(TimeSpan.FromSeconds(10)); + object idFornecedor = ApplicationHelper.IdFornecedor; + object relatorio = (int)this.Relatorio; + DateTime universalTime = Funcoes.GetNetworkTime().ToUniversalTime(); + string str = string.Format("{0}:{1}:{2}", idFornecedor, relatorio, universalTime.Ticks).EncodeBase64(); + Uri apiMonitor = Address.get_ApiMonitor(); + string[] strArrays = new string[] { "report" }; + Uri uri = apiMonitor.Append(strArrays).AddQuery("reportQuery", str); + await httpClient.GetAsync(uri); + } + httpClient = null; + } + catch + { + } + } + + public async void PrepararProtocolo(List itens) + { + List> tuples; + if (itens != null) + { + this.Carregando = true; + base.IsEnabled = false; + if (await base.ShowMessage("DESEJA EMITIR O CHECKLIST?", "SIM", "NÃO", false)) + { + await base.EmitirCheckList(itens); + } + tuples = new List>(); + foreach (Documento iten in itens) + { + tuples.Add(new Tuple(iten.get_Id(), iten.get_ObsProtocolo())); + } + bool flag = await base.ShowMessage(string.Concat("DESEJA EMITIR DOIS PROTOCOLOS POR PÁGINA?", Environment.NewLine, "A QUANTIDADE DE INFORMÃÇÕES PODE IMPEDIR QUE ESSA FUNÇÃO FUNCIONE CORRETAMENTE"), "SIM", "NÃO", false); + await base.EmitirProtocolos(tuples, flag, itens); + base.IsEnabled = true; + this.Carregando = false; + } + tuples = null; + } + + public async Task Print(bool pageBreak = false) + { + bool flag; + ConfiguracaoImpressao configuracaoImpressao; + string str = ""; + switch (this.Relatorio) + { + case 0: + case 1: + { + if (this.ClientesAtivosInativosFiltrado == null || this.ClientesAtivosInativosFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.ClientesAtivosInativosFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 2: + { + if (this.ProducaoFiltrado == null || this.ProducaoFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.ProducaoFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 3: + { + if (this.ApolicePendenteFiltrado == null || this.ApolicePendenteFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.ApolicePendenteFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 4: + { + if (this.RenovacaoFiltrado == null || this.RenovacaoFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.RenovacaoFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 5: + { + if (this.ComissaoFiltrado == null || this.ComissaoFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.ComissaoFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 6: + case 16: + { + if (this.PendenteFiltrado == null || this.PendenteFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.PendenteFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 7: + { + if (this.Pagamentos == null || this.Pagamentos.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.Pagamentos.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + List pagamentos = this.Pagamentos; + flag = (!pagamentos.All((Pagamento x) => x.get_Dados().Any((DadosRelatorio p) => !p.get_DataPagamento().HasValue)) ? false : this.SomenteNaoPagos); + bool flag1 = flag; + if (flag1) + { + flag1 = await base.ShowMessage(string.Concat("DESEJA REALMENTE EMITIR O RECIBO DE PAGAMENTO DOS VENDEDORES LISTADOS?", Environment.NewLine, "ESSE PROCEDIMENTO IRÁ GERAR O PAGAMENTO DO REPASSE DAS PARCELAS PRESENTES NA LISTAGEM."), "SIM", "NÃO", false); + } + if (flag1) + { + this.ReciboPagamento = true; + } + this.Carregando = true; + base.IsEnabled = false; + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + if (this.ReciboPagamento) + { + await this.GerarPagamento(this.Pagamentos.ToList()); + } + this.ReciboPagamento = false; + goto case 22; + } + } + } + case 8: + { + if (this.AuditoriaFiltrado == null || this.AuditoriaFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.AuditoriaFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 9: + case 10: + { + if (this.SinistroFiltrado == null || this.SinistroFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.SinistroFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 11: + { + if (this.FechamentoFiltrado == null || this.FechamentoFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.FechamentoFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 12: + { + if (this.FaturaPendenteFiltrado == null || this.FaturaPendenteFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.FaturaPendenteFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 13: + { + if (this.ExtratosFiltrado == null || this.ExtratosFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.ExtratosFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 14: + { + if (this.MetaSeguradoraFiltrado == null || this.MetaSeguradoraFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.MetaSeguradoraFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 15: + { + if (this.MetaVendedorFiltrado == null || this.MetaVendedorFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.MetaVendedorFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 17: + { + if (this.LicenciamentoFiltrado == null || this.LicenciamentoFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.LicenciamentoFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 18: + { + if (this.TarefaFiltrado == null || this.TarefaFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.TarefaFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 19: + { + if (this.NotaFiscalFiltrado == null || this.NotaFiscalFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.NotaFiscalFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 20: + { + if (this.PrevisaoFiltrado == null || this.PrevisaoFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.PrevisaoFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 21: + case 22: + { + if (!string.IsNullOrEmpty(str)) + { + base.RegistrarAcao(string.Format("IMPRIMIU RELATÓRIO PERÍODO ENTRE {0:d} E {1:d}", this.Inicio, this.Fim), new Gestor.Model.Common.Relatorio?(this.Relatorio), this.Filtros); + string tempPath = Path.GetTempPath(); + string str1 = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.html", tempPath, (new Regex(string.Concat("[", Regex.Escape(string.Concat(new string(Path.GetInvalidFileNameChars()), new string(Path.GetInvalidPathChars()))), "]"))).Replace(EnumHelper.GetDescription(this.Relatorio), ""), Funcoes.GetNetworkTime()); + StreamWriter streamWriter = new StreamWriter(str1, true, Encoding.UTF8); + streamWriter.Write(str); + streamWriter.Close(); + int num = 0; + try + { + Process.Start(str1); + } + catch + { + num = 1; + } + if (num == 1) + { + await base.ShowMessage("NÃO FOI ENCONTRADO O APLICATIVO PADRÃO DE HTML. \nACESSE AS CONFIGURAÇÕES DO SISTEMA OPERACIONAL PARA CONFIGURAR OU CONTATE UM TÉCNICO PARA AUXILIÁ-LO.", "OK", "", false); + } + break; + } + else + { + break; + } + } + case 23: + { + if (this.LogsEnvioFiltrado == null || this.LogsEnvioFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.LogsEnvioFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 24: + case 25: + { + if (this.LogUtilizacaoFiltrado == null || this.LogUtilizacaoFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.LogUtilizacaoFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 26: + { + if (this.ApoliceCriticaFiltrado == null || this.ApoliceCriticaFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.ApoliceCriticaFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 27: + { + if (this.PlacaFiltrado == null || this.PlacaFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.PlacaFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 28: + { + if (this.EndossoFiltrado == null || this.EndossoFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.EndossoFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 29: + { + if (this.ClassificacaoFiltrado == null || this.ClassificacaoFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.ClassificacaoFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + default: + { + goto case 22; + } + } + } + + private void ProdutoOnPropertyChanged(object sender, PropertyChangedEventArgs args) + { + if (this._alterandoFiltros) + { + return; + } + this.RecheckAllSelected(5); + } + + private void RamoOnPropertyChanged(object sender, PropertyChangedEventArgs args) + { + if (this._alterandoFiltros) + { + return; + } + this.RecheckAllSelected(1); + } + + public void RecheckAllLists() + { + for (int i = 0; i <= 9; i++) + { + this.RecheckAllSelected(i); + } + } + + public void RecheckAllSelected(int tipo) + { + bool? nullable; + if (this._allSelectedChanging) + { + return; + } + try + { + this._allSelectedChanging = true; + switch (tipo) + { + case 0: + { + if (this.Seguradoras.All((Seguradora e) => e.get_Selecionado())) + { + this.AllSelectedSeguradora = new bool?(true); + break; + } + else if (!this.Seguradoras.All((Seguradora e) => !e.get_Selecionado())) + { + nullable = null; + this.AllSelectedSeguradora = nullable; + break; + } + else + { + this.AllSelectedSeguradora = new bool?(false); + break; + } + } + case 1: + { + if (this.Ramos.All((Ramo e) => e.get_Selecionado())) + { + this.AllSelectedRamo = new bool?(true); + break; + } + else if (!this.Ramos.All((Ramo e) => !e.get_Selecionado())) + { + nullable = null; + this.AllSelectedRamo = nullable; + break; + } + else + { + this.AllSelectedRamo = new bool?(false); + break; + } + } + case 2: + { + if (this.Vendedores.All((Vendedor e) => e.get_Selecionado())) + { + this.AllSelectedVendedor = new bool?(true); + break; + } + else if (!this.Vendedores.All((Vendedor e) => !e.get_Selecionado())) + { + nullable = null; + this.AllSelectedVendedor = nullable; + break; + } + else + { + this.AllSelectedVendedor = new bool?(false); + break; + } + } + case 3: + { + if (this.TipoSeguros.All((StatusRelatorio e) => e.get_Selecionado())) + { + this.AllSelectedStatus = new bool?(true); + break; + } + else if (!this.TipoSeguros.All((StatusRelatorio e) => !e.get_Selecionado())) + { + nullable = null; + this.AllSelectedStatus = nullable; + break; + } + else + { + this.AllSelectedStatus = new bool?(false); + break; + } + } + case 4: + { + if (this.TipoVendedor.All((Gestor.Model.Domain.Seguros.TipoVendedor e) => e.get_Selecionado())) + { + this.AllSelectedTipoVendedor = new bool?(true); + break; + } + else if (!this.TipoVendedor.All((Gestor.Model.Domain.Seguros.TipoVendedor e) => !e.get_Selecionado())) + { + nullable = null; + this.AllSelectedTipoVendedor = nullable; + break; + } + else + { + this.AllSelectedTipoVendedor = new bool?(false); + break; + } + } + case 5: + { + if (this.Negocios.All((NegocioRelatorio e) => e.get_Selecionado())) + { + this.AllSelectedNegocio = new bool?(true); + break; + } + else if (!this.Negocios.All((NegocioRelatorio e) => !e.get_Selecionado())) + { + nullable = null; + this.AllSelectedNegocio = nullable; + break; + } + else + { + this.AllSelectedNegocio = new bool?(false); + break; + } + } + case 6: + { + if (this.Produtos.All((Gestor.Model.Domain.Seguros.Produto e) => e.get_Selecionado())) + { + this.AllSelectedProduto = new bool?(true); + break; + } + else if (!this.Produtos.All((Gestor.Model.Domain.Seguros.Produto e) => !e.get_Selecionado())) + { + nullable = null; + this.AllSelectedProduto = nullable; + break; + } + else + { + this.AllSelectedProduto = new bool?(false); + break; + } + } + case 7: + { + if (this.Estipulantes.All((Estipulante e) => e.get_Selecionado())) + { + this.AllSelectedEstipulante = new bool?(true); + break; + } + else if (!this.Estipulantes.All((Estipulante e) => !e.get_Selecionado())) + { + nullable = null; + this.AllSelectedEstipulante = nullable; + break; + } + else + { + this.AllSelectedEstipulante = new bool?(false); + break; + } + } + } + this.AdicionarFiltros(); + } + finally + { + this._allSelectedChanging = false; + } + } + + public void ReloadVendedores() + { + if (this.Inativo) + { + this.Vendedores = (this.Vinculo.Count > 0 ? ( + from x in Recursos.Vendedores + where this.Vinculo.Any((VendedorUsuario y) => y.get_Vendedor().get_Id() == x.get_Id()) + orderby x.get_Nome() + select x).ToList() : Recursos.Vendedores.Where((Vendedor x) => { + if (Recursos.Usuario.get_IdEmpresa() == (long)1) + { + return true; + } + return x.get_IdEmpresa() == Recursos.Usuario.get_IdEmpresa(); + }).OrderBy((Vendedor x) => x.get_Nome()).ToList()); + } + else + { + this.Vendedores = (this.Vinculo.Count > 0 ? Recursos.Vendedores.Where((Vendedor x) => { + if (!this.Vinculo.Any((VendedorUsuario y) => y.get_Vendedor().get_Id() == x.get_Id())) + { + return false; + } + return x.get_Ativo(); + }).OrderBy((Vendedor x) => x.get_Nome()).ToList() : Recursos.Vendedores.Where((Vendedor x) => { + if (Recursos.Usuario.get_IdEmpresa() != (long)1 && x.get_IdEmpresa() != Recursos.Usuario.get_IdEmpresa()) + { + return false; + } + return x.get_Ativo(); + }).OrderBy((Vendedor x) => x.get_Nome()).ToList()); + } + base.OnPropertyChanged("ReloadVendedores"); + } + + public void RemoverRamo(Ramo ramo) + { + if (ramo == null) + { + return; + } + if (this.RamosSelecionados.Any((Ramo x) => x.get_Id() == ramo.get_Id())) + { + this.RamosSelecionados.Remove(ramo); + } + this.FiltrarRamo(); + } + + internal async Task RemoverVinculo(Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente pendencia) + { + base.Loading(true); + VinculoDocumento vinculo = pendencia.get_Documento().get_Vinculo(); + if (vinculo != null && vinculo.get_Id() != 0) + { + await this._apoliceServico.ExcluirVinculo(vinculo.get_Id()); + Action recarregarRelatorios = Gestor.Application.Actions.Actions.RecarregarRelatorios; + if (recarregarRelatorios != null) + { + recarregarRelatorios(this.Sessao); + } + else + { + } + base.Loading(false); + } + } + + public async Task SalvarParametros() + { + bool flag; + if (!await (new ConfuguracoesServico()).Salvar(this.ParametrosRelatorioAdicionados.ToList(), this.ParametrosRelatorio.ToList())) + { + flag = false; + } + else if (await (new ConfuguracoesServico()).SalvarTotalizacoes(this.ParametrosTotalizacaoAdicionados.ToList(), this.ParametrosTotalizacao.ToList())) + { + base.RegistrarAcao("SALVOU CONFIGURAÇÃO DO RELATORIO", new Gestor.Model.Common.Relatorio?(this.Relatorio), this.Filtros); + await this.CarregarConfiguracoes(); + flag = true; + } + else + { + flag = false; + } + return flag; + } + + public async Task SalvarTarefas(List tarefas) + { + await (new TarefaServico()).Salvar(tarefas); + } + + public async Task SalvarTrilha(Trilha destino) + { + Trilha trilha; + List fases = destino.get_Fases(); + TarefaServico tarefaServico = new TarefaServico(); + List trilhas = await tarefaServico.BuscarTrilhas(); + if (!trilhas.Any((Trilha x) => x.get_Tipo() == destino.get_Tipo())) + { + Trilha trilha1 = await tarefaServico.Salvar(destino); + if (tarefaServico.Sucesso) + { + fases.ForEach((Fase x) => x.set_Trilha(trilha1)); + fases = await tarefaServico.Salvar(fases); + if (tarefaServico.Sucesso) + { + trilha1.set_Fases(fases); + trilha = trilha1; + } + else + { + trilha = null; + } + } + else + { + trilha = null; + } + } + else + { + Trilha trilha2 = trilhas.First((Trilha x) => x.get_Tipo() == destino.get_Tipo()); + Trilha trilha3 = trilha2; + List fases1 = await tarefaServico.BuscarFases(trilha2.get_Id()); + trilha3.set_Fases(fases1); + trilha3 = null; + trilha = trilha2; + } + fases = null; + tarefaServico = null; + return trilha; + } + + private void SeguradoraOnPropertyChanged(object sender, PropertyChangedEventArgs args) + { + if (this._alterandoFiltros) + { + return; + } + this.RecheckAllSelected(0); + } + + public async Task Selecionar() + { + await Task.Run(() => { + Dispatcher dispatcher; + Dispatcher dispatcher1; + DispatcherOperation dispatcherOperation; + switch (this.Relatorio) + { + case 0: + case 1: + { + if (this.ClientesAtivosInativosFiltrado == null || this.ClientesAtivosInativosFiltrado.Count == 0) + { + return; + } + this.ClientesAtivosInativosFiltrado.ToList().ForEach((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => x.set_Selecionado(!x.get_Selecionado())); + this.ClientesAtivosInativosFiltrado = new ObservableCollection(this.ClientesAtivosInativosFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 2: + { + if (this.ProducaoFiltrado == null || this.ProducaoFiltrado.Count == 0) + { + return; + } + this.ProducaoFiltrado.ToList().ForEach((Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.set_Selecionado(!x.get_Selecionado())); + this.ProducaoFiltrado = new ObservableCollection(this.ProducaoFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 3: + { + if (this.ApolicePendenteFiltrado == null || this.ApolicePendenteFiltrado.Count == 0) + { + return; + } + this.ApolicePendenteFiltrado.ToList().ForEach((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => x.set_Selecionado(!x.get_Selecionado())); + this.ApolicePendenteFiltrado = new ObservableCollection(this.ApolicePendenteFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 4: + { + if (this.RenovacaoFiltrado == null || this.RenovacaoFiltrado.Count == 0) + { + return; + } + this.RenovacaoFiltrado.ToList().ForEach((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.set_Selecionado(!x.get_Selecionado())); + this.RenovacaoFiltrado = new ObservableCollection(this.RenovacaoFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 5: + { + if (this.ComissaoFiltrado == null || this.ComissaoFiltrado.Count == 0) + { + return; + } + this.ComissaoFiltrado.ToList().ForEach((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.set_Selecionado(!x.get_Selecionado())); + this.ComissaoFiltrado = new ObservableCollection(this.ComissaoFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 6: + case 16: + { + if (this.PendenteFiltrado == null || this.PendenteFiltrado.Count == 0) + { + return; + } + this.PendenteFiltrado.ToList().ForEach((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.set_Selecionado(!x.get_Selecionado())); + this.PendenteFiltrado = new ObservableCollection(this.PendenteFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 7: + case 11: + case 20: + case 21: + case 22: + { + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 8: + { + if (this.AuditoriaFiltrado == null || this.AuditoriaFiltrado.Count == 0) + { + return; + } + this.AuditoriaFiltrado.ToList().ForEach((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => x.set_Selecionado(!x.get_Selecionado())); + this.AuditoriaFiltrado = new ObservableCollection(this.AuditoriaFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 9: + case 10: + { + if (this.SinistroFiltrado == null || this.SinistroFiltrado.Count == 0) + { + return; + } + this.SinistroFiltrado.ToList().ForEach((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.set_Selecionado(!x.get_Selecionado())); + this.SinistroFiltrado = new ObservableCollection(this.SinistroFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 12: + { + if (this.FaturaPendenteFiltrado == null || this.FaturaPendenteFiltrado.Count == 0) + { + return; + } + this.FaturaPendenteFiltrado.ToList().ForEach((Gestor.Model.Domain.Relatorios.FaturaPendente.FaturaPendente x) => x.set_Selecionado(!x.get_Selecionado())); + this.FaturaPendenteFiltrado = new ObservableCollection(this.FaturaPendenteFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 13: + { + if (this.ExtratosFiltrado == null || this.ExtratosFiltrado.Count == 0) + { + return; + } + this.ExtratosFiltrado.ToList().ForEach((ExtratoBaixadoRelatorio x) => x.set_Selecionado(!x.get_Selecionado())); + this.ExtratosFiltrado = new ObservableCollection(this.ExtratosFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 14: + { + if (this.MetaSeguradoraFiltrado == null || this.MetaSeguradoraFiltrado.Count == 0) + { + return; + } + this.MetaSeguradoraFiltrado.ToList().ForEach((MetaSeguradoraRelatorio x) => x.set_Selecionado(!x.get_Selecionado())); + this.MetaSeguradoraFiltrado = new ObservableCollection(this.MetaSeguradoraFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 15: + { + if (this.MetaVendedorFiltrado == null || this.MetaVendedorFiltrado.Count == 0) + { + return; + } + this.MetaVendedorFiltrado.ToList().ForEach((MetaVendedorRelatorio x) => x.set_Selecionado(!x.get_Selecionado())); + this.MetaVendedorFiltrado = new ObservableCollection(this.MetaVendedorFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 17: + { + if (this.LicenciamentoFiltrado == null || this.LicenciamentoFiltrado.Count == 0) + { + return; + } + this.LicenciamentoFiltrado.ToList().ForEach((Gestor.Model.Domain.Relatorios.Licenciamento.Licenciamento x) => x.set_Selecionado(!x.get_Selecionado())); + this.LicenciamentoFiltrado = new ObservableCollection(this.LicenciamentoFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 18: + { + if (this.TarefaFiltrado == null || this.TarefaFiltrado.Count == 0) + { + return; + } + this.TarefaFiltrado.ToList().ForEach((Gestor.Model.Domain.Relatorios.Tarefa.Tarefa x) => x.set_Selecionado(!x.get_Selecionado())); + this.TarefaFiltrado = new ObservableCollection(this.TarefaFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 19: + { + if (this.NotaFiscalFiltrado == null || this.NotaFiscalFiltrado.Count == 0) + { + return; + } + this.NotaFiscalFiltrado.ToList().ForEach((NotaFiscalRelatorio x) => x.set_Selecionado(!x.get_Selecionado())); + this.NotaFiscalFiltrado = new ObservableCollection(this.NotaFiscalFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 23: + { + if (this.LogsEnvioFiltrado == null || this.LogsEnvioFiltrado.Count == 0) + { + return; + } + this.LogsEnvioFiltrado.ToList().ForEach((Gestor.Model.Domain.Relatorios.LogsEnvio.LogsEnvio x) => x.set_Selecionado(!x.get_Selecionado())); + this.LogsEnvioFiltrado = new ObservableCollection(this.LogsEnvioFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 24: + case 25: + { + if (this.LogUtilizacaoFiltrado == null || this.LogUtilizacaoFiltrado.Count == 0) + { + return; + } + this.LogUtilizacaoFiltrado.ToList().ForEach((LogAcaoRelatorio x) => x.set_Selecionado(!x.get_Selecionado())); + this.LogUtilizacaoFiltrado = new ObservableCollection(this.LogUtilizacaoFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 26: + { + if (this.ApoliceCriticaFiltrado == null || this.ApoliceCriticaFiltrado.Count == 0) + { + return; + } + this.ApoliceCriticaFiltrado.ToList().ForEach((Gestor.Model.Domain.Relatorios.CriticaApolice.ApoliceCritica x) => x.set_Selecionado(!x.get_Selecionado())); + this.ApoliceCriticaFiltrado = new ObservableCollection(this.ApoliceCriticaFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 27: + { + if (this.PlacaFiltrado == null || this.PlacaFiltrado.Count == 0) + { + return; + } + this.PlacaFiltrado.ToList().ForEach((Gestor.Model.Domain.Relatorios.Placa.Placas x) => x.set_Selecionado(!x.get_Selecionado())); + this.PlacaFiltrado = new ObservableCollection(this.PlacaFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 28: + { + if (this.EndossoFiltrado == null || this.EndossoFiltrado.Count == 0) + { + return; + } + this.EndossoFiltrado.ToList().ForEach((Endosso x) => x.set_Selecionado(!x.get_Selecionado())); + this.EndossoFiltrado = new ObservableCollection(this.EndossoFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 29: + { + if (this.ClassificacaoFiltrado == null || this.ClassificacaoFiltrado.Count == 0) + { + return; + } + this.ClassificacaoFiltrado.ToList().ForEach((Gestor.Model.Domain.Relatorios.Classificacao.Classificacao x) => x.set_Selecionado(!x.get_Selecionado())); + this.ClassificacaoFiltrado = new ObservableCollection(this.ClassificacaoFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + default: + { + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + } + }); + } + + public async Task Sincronizar() + { + List produtos = LicenseHelper.Produtos; + if (produtos.All((Licenca x) => x.get_Produto() != 77)) + { + List licencas = LicenseHelper.Produtos; + if (licencas.All((Licenca x) => x.get_Produto() != 84)) + { + await base.ShowMessage("VOCÊ AINDA NÃO POSSUI O AGGILIZADOR DE DOCUMENTOS, NAVEGUE POR NOSSO PORTAL E ENCONTRE A OFERTA QUE MAIS ENCAIXE EM SEU DIA-A-DIA.", "OK", "", false); + Process.Start("https://agger.com.br"); + return; + } + } + Gestor.Model.Common.Relatorio relatorio = this.Relatorio; + if (relatorio != 3) + { + if (relatorio == 16) + { + if (this.PendenteFiltrado == null || !this.PendenteFiltrado.Any()) + { + await base.ShowMessage("NÃO HÁ DADOS PARA SINCRONIZAÇÃO", "OK", "", false); + return; + } + else + { + ObservableCollection pendenteFiltrado = this.PendenteFiltrado; + List list = ( + from x in pendenteFiltrado + select x.get_ParcelaEntity().get_Id()).ToList(); + int[] numArray = await this._parcelaServico.Sincronizar(this.Inicio, list); + if (numArray[0] == 0) + { + await base.ShowMessage("NÃO HÁ PARCELAS PENDENTES NO PERIODO SELECIONADO.", "OK", "", false); + return; + } + else if (numArray[0] <= 0 || numArray[1] != 0) + { + Action recarregarRelatorios = Gestor.Application.Actions.Actions.RecarregarRelatorios; + if (recarregarRelatorios != null) + { + recarregarRelatorios(this.Sessao); + } + else + { + } + base.ToggleSnackBar(string.Format("{0} PARCELAS VINCULADAS", numArray[1]), true); + } + else + { + return; + } + } + } + } + else if (this.ApolicePendenteFiltrado == null || !this.ApolicePendenteFiltrado.Any()) + { + await base.ShowMessage("NÃO HÁ DADOS PARA SINCRONIZAÇÃO", "OK", "", false); + return; + } + else + { + ObservableCollection apolicePendenteFiltrado = this.ApolicePendenteFiltrado; + IEnumerable apolicePendentes = apolicePendenteFiltrado.Where((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => { + long? idAggilizador; + bool hasValue; + bool vinculo; + long? nullable; + Documento documento = x.get_Documento(); + if (documento != null) + { + Controle controle = documento.get_Controle(); + if (controle != null) + { + Seguradora seguradora = controle.get_Seguradora(); + if (seguradora != null) + { + idAggilizador = seguradora.get_IdAggilizador(); + hasValue = idAggilizador.HasValue; + } + else + { + hasValue = false; + } + } + else + { + hasValue = false; + } + } + else + { + hasValue = false; + } + if (!hasValue) + { + return false; + } + Documento documento1 = x.get_Documento(); + if (documento1 != null) + { + vinculo = documento1.get_Vinculo(); + } + else + { + vinculo = false; + } + if (!vinculo) + { + return true; + } + Documento documento2 = x.get_Documento(); + if (documento2 == null) + { + return false; + } + VinculoDocumento vinculoDocumento = documento2.get_Vinculo(); + if (vinculoDocumento != null) + { + nullable = new long?(vinculoDocumento.get_IdApoliceDigital()); + } + else + { + nullable = null; + } + idAggilizador = nullable; + long num = (long)0; + return idAggilizador.GetValueOrDefault() == num & idAggilizador.HasValue; + }); + List dadosVinculos = apolicePendentes.Select((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => { + string proposta; + object placa; + DadosVinculo dadosVinculo = new DadosVinculo(); + dadosVinculo.set_Id(x.get_Documento().get_Id()); + if (x.get_Documento().get_Controle().get_Seguradora().get_IdAggilizador().Value != (long)1 || x.get_Documento().get_Controle().get_Ramo().get_Id() != (long)5) + { + proposta = x.get_Documento().get_Proposta(); + } + else + { + ObservableCollection result = Task.Run>(() => (new ItemServico()).BuscarItems(x.get_Documento().get_Id(), 2, false)).Result; + if (result != null) + { + Item item = result.FirstOrDefault(); + if (item != null) + { + placa = item.get_Auto().get_Placa(); + } + else + { + placa = null; + } + } + else + { + placa = null; + } + if (placa != null) + { + proposta = ((string)placa).Replace("-", string.Empty); + } + else + { + proposta = null; + } + } + dadosVinculo.set_Proposta(proposta); + dadosVinculo.set_Apolice(x.get_Documento().get_Apolice()); + dadosVinculo.set_Documento(x.get_Documento().get_Controle().get_Cliente().get_Documento()); + dadosVinculo.set_Endosso(x.get_Documento().get_PropostaEndosso()); + dadosVinculo.set_IdSeguradora(x.get_Documento().get_Controle().get_Seguradora().get_IdAggilizador().Value); + dadosVinculo.set_VigenciaInicial(x.get_Documento().get_Vigencia1()); + dadosVinculo.set_Vigenciafinal(x.get_Documento().get_Vigencia2()); + dadosVinculo.set_Vinculo(x.get_Documento().get_Vinculo()); + return dadosVinculo; + }).ToList(); + Gestor.Model.Domain.Relatorios.Filtros filtro = new Gestor.Model.Domain.Relatorios.Filtros(); + filtro.set_Inicio(this.Inicio); + filtro.set_Fim(this.Fim); + int num1 = await this._apoliceServico.Sincronizar(dadosVinculos, filtro); + Action action = Gestor.Application.Actions.Actions.RecarregarRelatorios; + if (action != null) + { + action(this.Sessao); + } + else + { + } + ObservableCollection observableCollection = this.ApolicePendenteFiltrado; + if (!observableCollection.All((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => { + long? nullable; + Documento documento = x.get_Documento(); + if (documento == null) + { + return false; + } + VinculoDocumento vinculo = documento.get_Vinculo(); + if (vinculo != null) + { + nullable = new long?(vinculo.get_IdApoliceDigital()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long num = (long)0; + return nullable1.GetValueOrDefault() == num & nullable1.HasValue; + })) + { + if (num1 != 0) + { + base.ToggleSnackBar(string.Format("{0} DOCUMENTOS SINCRONIZADOS", num1), true); + RelatorioViewModel relatorioViewModel = this; + ObservableCollection apolicePendenteFiltrado1 = this.ApolicePendenteFiltrado; + if (!await relatorioViewModel.ShowMessage(string.Format("{0} DOCUMENTOS SINCRONIZADOS, DESEJA INICIAR A IMPORTAÇÃO DESSES DOCUMENTOS?", apolicePendenteFiltrado1.Count((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => { + long? nullable; + Documento documento = x.get_Documento(); + if (documento == null) + { + return false; + } + VinculoDocumento vinculo = documento.get_Vinculo(); + if (vinculo != null) + { + nullable = new long?(vinculo.get_IdApoliceDigital()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long num = (long)0; + return nullable1.GetValueOrDefault() > num & nullable1.HasValue; + })), "SIM", "NÃO", false)) + { + return; + } + } + else if (!await base.ShowMessage("NENHUM NOVO DOCUMENTO FOI SINCRONIZADO, DESEJA IMPORTAR OS DOCUMENTOS ANTERIORMENTE SINCRONIZADOS?", "SIM", "NÃO", false)) + { + return; + } + ObservableCollection observableCollection1 = this.ApolicePendenteFiltrado; + IEnumerable apolicePendentes1 = observableCollection1.Where((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => { + long? nullable; + Documento documento = x.get_Documento(); + if (documento == null) + { + return false; + } + VinculoDocumento vinculo = documento.get_Vinculo(); + if (vinculo != null) + { + nullable = new long?(vinculo.get_IdApoliceDigital()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long num = (long)0; + return nullable1.GetValueOrDefault() > num & nullable1.HasValue; + }); + List nums = ( + from x in apolicePendentes1 + select x.get_Documento().get_Vinculo().get_IdApoliceDigital()).ToList(); + await base.DownloadAll(nums, 1); + Parameters parameter = new Parameters(); + parameter.set_Beta(false); + parameter.set_Type(4); + parameter.set_Application("Agger.ImportPDF.exe"); + parameter.set_Directory("Agger.Import"); + object[] id = new object[] { Recursos.Empresa.get_Id(), Recursos.Usuario.get_Id(), ApplicationHelper.Subkey, ApplicationHelper.NumeroSerial }; + parameter.set_Arguments(string.Format("{0} {1} NOVOGESTOR PERFIL:{2} SERIAL:{3}", id)); + parameter.set_Run(true); + (new DownloadWindow(parameter)).Show(); + } + else + { + await base.ShowMessage("NENHUM NOVO DOCUMENTO FOI SINCRONIZADO", "OK", "", false); + return; + } + } + } + + public async Task Sintetico() + { + List list = null; + if ((GridRelatorio)this.Report != null || this.Relatorio == 7 || this.Relatorio == 11) + { + switch (this.Relatorio) + { + case 2: + { + List producaos = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.ProducaoFiltrado == null || producaos.Count == 0) + { + break; + } + else + { + if (this.Agrupamento == 3) + { + List producaos1 = producaos; + producaos = ( + from producao in producaos1 + where producao.get_Vendedor() != null + select producao).ToList(); + } + list = producaos.GroupBy((Gestor.Model.Domain.Relatorios.Producao.Producao x) => { + if (this.Agrupamento == 1) + { + return x.get_Seguradora(); + } + if (this.Agrupamento == 2) + { + return x.get_Ramo(); + } + if (this.Agrupamento == 3) + { + return x.get_Vendedor(); + } + if (this.Agrupamento != 4) + { + return x.get_Status(); + } + return x.get_Estipulante(); + }).Select, Sintetico>((IGrouping x) => { + Sintetico sintetico = new Sintetico(); + sintetico.set_Agrupamento(x.Key); + sintetico.set_PremioTotal(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Producao.Producao c) => c.get_PremioTotal()))); + sintetico.set_PremioLiquido(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Producao.Producao p) => p.get_PremioLiquido()))); + sintetico.set_MediaComissao(new decimal?((x.Sum((Gestor.Model.Domain.Relatorios.Producao.Producao c) => c.get_Comissao()) > decimal.Zero ? decimal.Round(x.Sum((Gestor.Model.Domain.Relatorios.Producao.Producao c) => c.get_Comissao()) / x.Count((Gestor.Model.Domain.Relatorios.Producao.Producao c) => c.get_Comissao() > decimal.Zero), 2) * new decimal(100) : decimal.Zero))); + sintetico.set_ComissaoGerada(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Producao.Producao c) => ((c.get_PremioLiquido() + (c.get_Documento().get_AdicionalComiss() ? c.get_Documento().get_PremioAdicional() : decimal.Zero)) * c.get_Comissao()) * new decimal(1, 0, 0, false, 2)))); + sintetico.set_Cancelamentos(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Producao.Producao c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Producao.Producao c) => c.get_Documento().get_Situacao() == 3))); + sintetico.set_Novos(new int?(Funcoes.DistinctBy(x, this.funcProducaoDistinctByDocumentoId).Count(this.funcProducaoNegociosNovos))); + sintetico.set_NegociosProprios(new int?(Funcoes.DistinctBy(x, this.funcProducaoDistinctByDocumentoId).Count(this.funcProducaoNegociosProprios))); + sintetico.set_SegurosNovos(new int?(Funcoes.DistinctBy(x, this.funcProducaoDistinctByDocumentoId).Count(this.funcProducaoSegurosNovos))); + sintetico.set_Renovacoes(new int?(Funcoes.DistinctBy(x, this.funcProducaoDistinctByDocumentoId).Count(this.funcProducaoSegurosRenovacao))); + sintetico.set_Apolices(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Producao.Producao c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Producao.Producao c) => { + if (c.get_Tipo() != 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico.set_Endossos(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Producao.Producao c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Producao.Producao c) => { + if (c.get_Tipo() == 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico.set_Faturas(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Producao.Producao c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Producao.Producao c) => c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 2))); + sintetico.set_TotalLiquido(new int?(x.Count((Gestor.Model.Domain.Relatorios.Producao.Producao c) => c.get_Documento().get_Situacao() != 3))); + sintetico.set_TotalGeral(new int?(x.Count())); + sintetico.set_MediaPonderada(new decimal?((x.Sum((Gestor.Model.Domain.Relatorios.Producao.Producao p) => p.get_PremioLiquido()) > decimal.Zero ? decimal.Round(x.Sum((Gestor.Model.Domain.Relatorios.Producao.Producao c) => (c.get_PremioLiquido() + (c.get_Documento().get_AdicionalComiss() ? c.get_Documento().get_PremioAdicional() : decimal.Zero)) * c.get_Comissao()) / x.Sum((Gestor.Model.Domain.Relatorios.Producao.Producao p) => p.get_PremioLiquido()), 2) * new decimal(100) : decimal.Zero))); + return sintetico; + }).ToList(); + goto case 13; + } + } + case 3: + { + List apolicePendentes = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.ApolicePendenteFiltrado == null || apolicePendentes.Count == 0) + { + break; + } + else + { + IEnumerable> groupings = apolicePendentes.GroupBy((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => { + if (this.Agrupamento == 1) + { + return x.get_Seguradora(); + } + if (this.Agrupamento == 2) + { + return x.get_Ramo(); + } + if (this.Agrupamento == 3) + { + return x.get_Vendedor(); + } + if (this.Agrupamento != 4) + { + return x.get_Status(); + } + return x.get_Estipulante(); + }); + list = groupings.Select, Sintetico>((IGrouping x) => { + Sintetico sintetico = new Sintetico(); + sintetico.set_Agrupamento(x.Key); + sintetico.set_Cancelamentos(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => c.get_Documento().get_Situacao() == 3))); + sintetico.set_Novos(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => { + if (c.get_Documento().get_Situacao() == 1) + { + return true; + } + if (c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 2; + }))); + sintetico.set_Renovacoes(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => { + if (c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 1; + }))); + sintetico.set_Apolices(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => { + if (c.get_Tipo() != 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico.set_Endossos(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => { + if (c.get_Tipo() == 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico.set_Faturas(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 2))); + sintetico.set_TotalGeral(new int?(x.Count())); + return sintetico; + }).ToList(); + goto case 13; + } + } + case 4: + { + List renovacaos = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.RenovacaoFiltrado == null || renovacaos.Count == 0) + { + break; + } + else + { + List renovacaos1 = renovacaos; + IEnumerable> groupings1 = ( + from x in renovacaos1 + where x.get_Documento() != null + select x).GroupBy((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => { + if (this.Agrupamento == 1) + { + return x.get_Seguradora(); + } + if (this.Agrupamento == 2) + { + return x.get_Ramo(); + } + if (this.Agrupamento == 3) + { + return x.get_Vendedor(); + } + if (this.Agrupamento != 4) + { + return x.get_Status(); + } + return x.get_Estipulante(); + }); + list = groupings1.Select, Sintetico>((IGrouping x) => { + Sintetico sintetico = new Sintetico(); + sintetico.set_Agrupamento(x.Key); + sintetico.set_PremioTotal(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_PremioTotal()))); + sintetico.set_PremioLiquido(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao p) => p.get_PremioLiquido()))); + sintetico.set_MediaComissao(new decimal?((x.Sum((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_Comissao()) > decimal.Zero ? decimal.Round(x.Sum((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_Comissao()) / x.Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_Comissao() > decimal.Zero), 2) * new decimal(100) : decimal.Zero))); + sintetico.set_ComissaoGerada(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => ((c.get_PremioLiquido() + (c.get_Documento().get_AdicionalComiss() ? c.get_Documento().get_PremioAdicional() : decimal.Zero)) * c.get_Comissao()) * new decimal(1, 0, 0, false, 2)))); + sintetico.set_Cancelamentos(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_Documento().get_Situacao() == 3))); + sintetico.set_Novos(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => { + if (c.get_Documento().get_Situacao() == 1) + { + return true; + } + if (c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 2; + }))); + sintetico.set_Renovacoes(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => { + if (c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 1; + }))); + sintetico.set_Apolices(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => { + if (c.get_Tipo() != 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico.set_Endossos(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => { + if (c.get_Tipo() == 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico.set_Faturas(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 2))); + sintetico.set_TotalProspeccao(new int?(x.Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_Tipo() == 3))); + sintetico.set_TotalGeral(new int?(x.Count())); + return sintetico; + }).ToList(); + goto case 13; + } + } + case 5: + { + List comissaos = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.ComissaoFiltrado == null || comissaos.Count == 0) + { + break; + } + else + { + IEnumerable> groupings2 = comissaos.GroupBy((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => { + if (this.Agrupamento == 1) + { + return x.get_Seguradora(); + } + if (this.Agrupamento == 2) + { + return x.get_Ramo(); + } + if (this.Agrupamento == 3) + { + return x.get_Vendedor(); + } + if (this.Agrupamento != 4) + { + return x.get_Status(); + } + return x.get_Estipulante(); + }); + list = groupings2.Select, Sintetico>((IGrouping x) => { + Sintetico sintetico = new Sintetico(); + sintetico.set_Agrupamento(x.Key); + sintetico.set_Cancelamentos(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => c.get_Documento().get_Situacao() == 3))); + sintetico.set_Novos(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => { + if (c.get_Documento().get_Situacao() == 1) + { + return true; + } + if (c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 2; + }))); + sintetico.set_Renovacoes(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => { + if (c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 1; + }))); + sintetico.set_Apolices(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => { + if (c.get_Documento().get_Tipo() != 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico.set_Endossos(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => { + if (c.get_Documento().get_Tipo() == 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico.set_Faturas(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 2))); + sintetico.set_ComissaoRecebidaBruta(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => c.get_ComissaoBruta()))); + sintetico.set_ComissaoRecebidaLiquida(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => c.get_ComissaoRecebida()))); + sintetico.set_Repasse(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => c.get_Repasse()))); + sintetico.set_MediaComissao(new decimal?((x.Any((Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => c.get_ComissaoPerc() > decimal.Zero) ? decimal.Round(x.Sum((Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => c.get_ComissaoPerc()) / x.Count((Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => c.get_ComissaoPerc() > decimal.Zero), 2) : decimal.Zero) * new decimal(100))); + sintetico.set_ComissaoPrevista(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => c.get_ValorLiquido()))); + sintetico.set_TotalGeral(new int?(x.Count())); + return sintetico; + }).ToList(); + goto case 13; + } + } + case 6: + case 16: + { + if (this.PendenteFiltrado == null || this.PendenteFiltrado.Count == 0) + { + break; + } + else + { + IEnumerable> groupings3 = this.PendenteFiltrado.GroupBy((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => { + if (this.Agrupamento == 1) + { + return x.get_Seguradora(); + } + if (this.Agrupamento == 2) + { + return x.get_Ramo(); + } + if (this.Agrupamento == 3) + { + return x.get_Vendedor(); + } + if (this.Agrupamento != 4) + { + return x.get_Status(); + } + return x.get_Estipulante(); + }); + list = groupings3.Select, Sintetico>((IGrouping x) => { + Sintetico sintetico = new Sintetico(); + sintetico.set_Agrupamento(x.Key); + sintetico.set_Cancelamentos(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Pendente.Pendente c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Pendente.Pendente c) => c.get_Documento().get_Situacao() == 3))); + sintetico.set_Novos(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Pendente.Pendente c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Pendente.Pendente c) => { + if (c.get_Documento().get_Situacao() == 1) + { + return true; + } + if (c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 2; + }))); + sintetico.set_Renovacoes(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Pendente.Pendente c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Pendente.Pendente c) => { + if (c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 1; + }))); + sintetico.set_Apolices(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Pendente.Pendente c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Pendente.Pendente c) => { + if (c.get_Documento().get_Tipo() != 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico.set_Endossos(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Pendente.Pendente c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Pendente.Pendente c) => { + if (c.get_Documento().get_Tipo() == 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico.set_Faturas(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Pendente.Pendente c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Pendente.Pendente c) => c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 2))); + sintetico.set_ComissaoPrevista(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Pendente.Pendente c) => c.get_ComissaoPrevista()))); + sintetico.set_TotalPrevista(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Pendente.Pendente c) => c.get_TotalPrevisto()))); + sintetico.set_TotalGeral(new int?(x.Count())); + return sintetico; + }).ToList(); + goto case 13; + } + } + case 7: + { + if (this.Pagamentos == null || this.Pagamentos.Count == 0) + { + break; + } + else + { + List pagamentos = this.Pagamentos; + list = pagamentos.Select((Pagamento x) => { + Sintetico sintetico = new Sintetico(); + sintetico.set_Agrupamento(x.get_Vendedores().get_Vendedor()); + sintetico.set_ValorLiquido(new decimal?(( + from c in x.get_Dados() + where c.get_Id() != (long)0 + select c).Sum((DadosRelatorio c) => c.get_ValorLiquido()))); + sintetico.set_ValorParcela(( + from c in x.get_Dados() + where c.get_Id() != (long)0 + select c).Sum((DadosRelatorio c) => c.get_ValorParcela())); + sintetico.set_Repasse(new decimal?(( + from c in x.get_Dados() + where c.get_Id() != (long)0 + select c).Sum((DadosRelatorio c) => c.get_Repasse()))); + sintetico.set_TotalGeral(new int?(x.get_Dados().Count((DadosRelatorio c) => c.get_Id() != (long)0))); + return sintetico; + }).ToList(); + goto case 13; + } + } + case 8: + { + List auditorias = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.AuditoriaFiltrado == null || auditorias.Count == 0) + { + break; + } + else + { + IEnumerable> groupings4 = auditorias.GroupBy((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => { + if (this.Agrupamento == 1) + { + return x.get_Seguradora(); + } + if (this.Agrupamento == 2) + { + return x.get_Ramo(); + } + if (this.Agrupamento == 3) + { + return x.get_Vendedor(); + } + if (this.Agrupamento != 4) + { + return x.get_Status(); + } + return x.get_Estipulante(); + }); + list = groupings4.Select, Sintetico>((IGrouping x) => { + Sintetico sintetico = new Sintetico(); + sintetico.set_Agrupamento(x.Key); + sintetico.set_PremioTotal(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_PremioTotal()))); + sintetico.set_PremioLiquido(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria p) => p.get_PremioLiquido()))); + sintetico.set_MediaComissao(new decimal?((x.Sum((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_Comissao()) > decimal.Zero ? decimal.Round(x.Sum((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_Comissao()) / x.Count((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_Comissao() > decimal.Zero), 2) : decimal.Zero) * new decimal(100))); + sintetico.set_ComissaoGerada(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => ((c.get_PremioLiquido() + (c.get_Documento().get_AdicionalComiss() ? c.get_Documento().get_PremioAdicional() : decimal.Zero)) * c.get_Comissao()) * new decimal(1, 0, 0, false, 2)))); + sintetico.set_ComissaoPrevista(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_ComissaoPrevista()))); + sintetico.set_ComissaoRecebidaBruta(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_ComissaoRecebida()))); + sintetico.set_ComissaoPendente(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_ComissaoPendente()))); + sintetico.set_Cancelamentos(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_Documento().get_Situacao() == 3))); + sintetico.set_Novos(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => { + if (c.get_Documento().get_Situacao() == 1) + { + return true; + } + if (c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 2; + }))); + sintetico.set_Renovacoes(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => { + if (c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 1; + }))); + sintetico.set_Apolices(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => { + if (c.get_Tipo() != 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico.set_Endossos(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => { + if (c.get_Tipo() == 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico.set_Faturas(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 2))); + sintetico.set_TotalLiquido(new int?(x.Count((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_Documento().get_Situacao() != 3))); + sintetico.set_TotalGeral(new int?(x.Count())); + return sintetico; + }).ToList(); + goto case 13; + } + } + case 9: + case 10: + { + List sinistros = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.SinistroFiltrado == null || sinistros.Count == 0) + { + break; + } + else + { + list = sinistros.GroupBy((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => { + if (this.Agrupamento == 1) + { + return x.get_Seguradora(); + } + if (this.Agrupamento == 2) + { + return x.get_Ramo(); + } + if (this.Agrupamento == 3) + { + return x.get_Vendedor(); + } + if (this.Agrupamento == 4) + { + return x.get_Estipulante(); + } + return EnumHelper.GetDescription(x.get_StatusSinistro()); + }).Select, Sintetico>((IGrouping x) => { + Sintetico sintetico = new Sintetico(); + sintetico.set_Agrupamento(x.Key); + sintetico.set_Liquidado((this.Relatorio == 9 ? null : new int?(( + from s in x + where s.get_Liquidacao().HasValue + select s.get_EntidadeSinistro().get_ControleSinistro().get_Id()).Distinct().Count()))); + sintetico.set_Valor(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro s) => s.get_Valor()))); + sintetico.set_ValorOrcado(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro s) => s.get_ValorOrcado()))); + sintetico.set_ValorLiberado(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro s) => s.get_ValorLiberado()))); + sintetico.set_ValorPago(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro s) => s.get_ValorPago()))); + sintetico.set_ValorLiquidado((this.Relatorio == 9 ? null : new decimal?(( + from s in x + where s.get_Liquidacao().HasValue + select s).Sum((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro s) => s.get_ValorPago())))); + sintetico.set_ValorSalvado(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro s) => s.get_ValorSalvado()))); + sintetico.set_ValorFranquia(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro s) => s.get_ValorFranquia()))); + sintetico.set_Pendente(new int?(( + from s in x + where !s.get_Liquidacao().HasValue + select s.get_EntidadeSinistro().get_ControleSinistro().get_Id()).Distinct().Count())); + sintetico.set_TotalGeral(new int?(( + from s in x + select s.get_EntidadeSinistro().get_ControleSinistro().get_Id()).Distinct().Count())); + return sintetico; + }).ToList(); + goto case 13; + } + } + case 11: + { + if (this.FechamentoFiltrado == null || this.FechamentoFiltrado.Count == 0) + { + break; + } + else + { + list = new List(); + Gestor.Model.Domain.Relatorios.Fechamento.Fechamento fechamento = this.FechamentoFiltrado.First().get_Fechamento().Last(); + Sintetico sintetico1 = new Sintetico(); + int year = this.Inicio.Year; + sintetico1.set_Agrupamento(string.Concat("ATUAL: ", year.ToString())); + sintetico1.set_TotalGeral(new int?(fechamento.get_Apolice())); + sintetico1.set_ValorPago(new decimal?(fechamento.get_Paga())); + sintetico1.set_ComissaoRecebidaBruta(new decimal?(fechamento.get_Recebida())); + sintetico1.set_ComissaoGerada(new decimal?(fechamento.get_Gerada())); + sintetico1.set_PremioLiquido(new decimal?(fechamento.get_PremioLiquido())); + sintetico1.set_PremioTotal(new decimal?(fechamento.get_PremioTotal())); + list.Add(sintetico1); + Sintetico sintetico2 = new Sintetico(); + year = this.Inicio.Year - 1; + sintetico2.set_Agrupamento(string.Concat("ANTERIOR: ", year.ToString())); + sintetico2.set_TotalGeral(new int?(fechamento.get_ApoliceAnterior())); + sintetico2.set_ValorPago(new decimal?(fechamento.get_PagaAnterior())); + sintetico2.set_ComissaoRecebidaBruta(new decimal?(fechamento.get_RecebidaAnterior())); + sintetico2.set_ComissaoGerada(new decimal?(fechamento.get_GeradaAnterior())); + sintetico2.set_PremioLiquido(new decimal?(fechamento.get_PremioLiquidoAnterior())); + sintetico2.set_PremioTotal(new decimal?(fechamento.get_PremioTotalAnterior())); + list.Add(sintetico2); + goto case 13; + } + } + case 12: + case 13: + { + if (list != null) + { + (new SinteticoView(list, EnumHelper.GetDescription(this.Relatorio), new DateTime?(this.Inicio), new DateTime?(this.Fim))).Show(); + break; + } + else + { + break; + } + } + case 14: + { + if (this.MetaSeguradora == null || this.MetaSeguradora.Count == 0) + { + break; + } + else + { + List metaSeguradora = this.MetaSeguradora; + IEnumerable> seguradora = + from g in metaSeguradora + group g by g.get_Seguradora(); + list = seguradora.Select, Sintetico>((IGrouping x) => { + Sintetico sintetico = new Sintetico(); + sintetico.set_Agrupamento(x.Key); + sintetico.set_Meta(new decimal?(Math.Round(( + from m in x + where m.get_MetaAtingir() > decimal.Zero + select m).Sum((MetaSeguradoraRelatorio m) => (m.get_MetaCumprida() * new decimal(100)) / m.get_MetaAtingir()) * new decimal(100), 2))); + sintetico.set_MetaAtingir(new decimal?(Math.Round(x.Sum((MetaSeguradoraRelatorio m) => m.get_MetaAtingir()), 2))); + sintetico.set_MetaCumprida(new decimal?(Math.Round(x.Sum((MetaSeguradoraRelatorio m) => m.get_MetaCumprida()), 2))); + return sintetico; + }).ToList(); + goto case 13; + } + } + case 15: + { + if (this.MetaVendedor == null || this.MetaVendedor.Count == 0) + { + break; + } + else + { + List metaVendedor = this.MetaVendedor; + IEnumerable> vendedor = + from g in metaVendedor + group g by g.get_Vendedor(); + list = vendedor.Select, Sintetico>((IGrouping x) => { + Sintetico sintetico = new Sintetico(); + sintetico.set_Agrupamento(x.Key); + sintetico.set_Meta(new decimal?(Math.Round(( + from m in x + where m.get_MetaAtingir() > decimal.Zero + select m).Sum((MetaVendedorRelatorio m) => (m.get_MetaCumprida() * new decimal(100)) / m.get_MetaAtingir()) * new decimal(100), 2))); + sintetico.set_MetaAtingir(new decimal?(Math.Round(x.Sum((MetaVendedorRelatorio m) => m.get_MetaAtingir()), 2))); + sintetico.set_MetaCumprida(new decimal?(Math.Round(x.Sum((MetaVendedorRelatorio m) => m.get_MetaCumprida()), 2))); + return sintetico; + }).ToList(); + goto case 13; + } + } + default: + { + goto case 13; + } + } + } + else + { + await base.ShowMessage("NECESSARIO GERAR UM RELATÓRIO COM DADOS PARA SINTETIZAR", "OK", "", false); + } + } + + public void SintetizarRelatorio() + { + this.SinteticoRelatorio = new ObservableCollection(); + switch (this.Relatorio) + { + case 0: + case 1: + { + if (this.ClientesAtivosInativosFiltrado == null || this.ClientesAtivosInativosFiltrado.Count == 0) + { + return; + } + List clientesAtivosInativos = (this.ClientesAtivosInativosFiltrado.Any((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => x.get_Selecionado()) ? ( + from x in this.ClientesAtivosInativosFiltrado + where x.get_Selecionado() + select x).ToList() : this.ClientesAtivosInativosFiltrado.ToList()); + List sinteticos = new List(); + Sintetico sintetico = new Sintetico(); + sintetico.set_TotalClientes(new int?(clientesAtivosInativos.Count)); + sintetico.set_TotalClientesAtivos(new int?(clientesAtivosInativos.Count((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => x.get_Ativo() == "SIM"))); + sintetico.set_TotalClientesInativos(new int?(clientesAtivosInativos.Count((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => x.get_Ativo() == "NÃO"))); + sinteticos.Add(sintetico); + this.SinteticoRelatorio = new ObservableCollection(sinteticos); + return; + } + case 2: + { + if (this.ProducaoFiltrado == null || this.ProducaoFiltrado.Count == 0) + { + return; + } + List producaos = (this.ProducaoFiltrado.Any((Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Selecionado()) ? ( + from x in this.ProducaoFiltrado + where x.get_Selecionado() + select x).ToList() : this.ProducaoFiltrado.ToList()); + List sinteticos1 = new List(); + Sintetico sintetico1 = new Sintetico(); + sintetico1.set_PremioTotal(new decimal?(producaos.Sum((Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_PremioTotal()))); + sintetico1.set_PremioLiquido(new decimal?(producaos.Sum((Gestor.Model.Domain.Relatorios.Producao.Producao p) => p.get_PremioLiquido()))); + sintetico1.set_MediaPonderada(new decimal?((producaos.Sum((Gestor.Model.Domain.Relatorios.Producao.Producao p) => p.get_PremioLiquido()) > decimal.Zero ? decimal.Round(producaos.Sum((Gestor.Model.Domain.Relatorios.Producao.Producao c) => (c.get_PremioLiquido() + (c.get_Documento().get_AdicionalComiss() ? c.get_Documento().get_PremioAdicional() : decimal.Zero)) * c.get_Comissao()) / producaos.Sum((Gestor.Model.Domain.Relatorios.Producao.Producao p) => p.get_PremioLiquido()), 2) : decimal.Zero))); + sintetico1.set_MediaComissao(new decimal?((producaos.Any((Gestor.Model.Domain.Relatorios.Producao.Producao c) => c.get_Comissao() > decimal.Zero) ? decimal.Round(producaos.Sum((Gestor.Model.Domain.Relatorios.Producao.Producao c) => c.get_Comissao()) / producaos.Count((Gestor.Model.Domain.Relatorios.Producao.Producao c) => c.get_Comissao() > decimal.Zero), 2) : decimal.Zero))); + sintetico1.set_ComissaoGerada(new decimal?(producaos.Sum((Gestor.Model.Domain.Relatorios.Producao.Producao c) => ((c.get_PremioLiquido() + (c.get_Documento().get_AdicionalComiss() ? c.get_Documento().get_PremioAdicional() : decimal.Zero)) * c.get_Comissao()) * new decimal(1, 0, 0, false, 2)))); + sintetico1.set_Cancelamentos(new int?(Funcoes.DistinctBy(producaos, (Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Documento().get_Controle().get_Id()).Count((Gestor.Model.Domain.Relatorios.Producao.Producao c) => c.get_Documento().get_Situacao() == 3))); + sintetico1.set_Novos(new int?(Funcoes.DistinctBy(producaos, this.funcProducaoDistinctByDocumentoId).Count(this.funcProducaoNegociosNovos))); + sintetico1.set_NegociosProprios(new int?(Funcoes.DistinctBy(producaos, this.funcProducaoDistinctByDocumentoId).Count(this.funcProducaoNegociosProprios))); + sintetico1.set_SegurosNovos(new int?(Funcoes.DistinctBy(producaos, this.funcProducaoDistinctByDocumentoId).Count(this.funcProducaoSegurosNovos))); + sintetico1.set_Renovacoes(new int?(Funcoes.DistinctBy(producaos, this.funcProducaoDistinctByDocumentoId).Count(this.funcProducaoSegurosRenovacao))); + sintetico1.set_Apolices(new int?(Funcoes.DistinctBy(producaos, (Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Producao.Producao c) => { + if (c.get_Tipo() != 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico1.set_Endossos(new int?(Funcoes.DistinctBy(producaos, (Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Producao.Producao c) => { + if (c.get_Tipo() == 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico1.set_Faturas(new int?(Funcoes.DistinctBy(producaos, (Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Producao.Producao c) => c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 2))); + sintetico1.set_TotalGeral(new int?(producaos.Count)); + sintetico1.set_TotalLiquido(new int?(producaos.Count((Gestor.Model.Domain.Relatorios.Producao.Producao c) => c.get_Documento().get_Situacao() != 3))); + sinteticos1.Add(sintetico1); + this.SinteticoRelatorio = new ObservableCollection(sinteticos1); + return; + } + case 3: + { + if (this.ApolicePendenteFiltrado == null || this.ApolicePendenteFiltrado.Count == 0) + { + return; + } + List apolicePendentes = (this.ApolicePendenteFiltrado.Any((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => x.get_Selecionado()) ? ( + from x in this.ApolicePendenteFiltrado + where x.get_Selecionado() + select x).ToList() : this.ApolicePendenteFiltrado.ToList()); + List sinteticos2 = new List(); + Sintetico sintetico2 = new Sintetico(); + sintetico2.set_PremioTotal(new decimal?(apolicePendentes.Sum((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => x.get_PremioTotal()))); + sintetico2.set_PremioLiquido(new decimal?(apolicePendentes.Sum((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente p) => p.get_PremioLiquido()))); + sintetico2.set_MediaComissao(new decimal?((apolicePendentes.Count((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => c.get_Comissao() > decimal.Zero) > 0 ? decimal.Round(apolicePendentes.Sum((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => c.get_Comissao()) / apolicePendentes.Count((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => c.get_Comissao() > decimal.Zero), 2) : decimal.Zero))); + sintetico2.set_ComissaoGerada(new decimal?(apolicePendentes.Sum((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => ((c.get_PremioLiquido() + (c.get_Documento().get_AdicionalComiss() ? c.get_Documento().get_PremioAdicional() : decimal.Zero)) * c.get_Comissao()) * new decimal(1, 0, 0, false, 2)))); + sintetico2.set_Cancelamentos(new int?(apolicePendentes.Count((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => c.get_Documento().get_Situacao() == 3))); + sintetico2.set_Novos(new int?(apolicePendentes.Count((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => { + if (c.get_Documento().get_Situacao() == 1) + { + return true; + } + if (c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 2; + }))); + sintetico2.set_Renovacoes(new int?(apolicePendentes.Count((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => { + if (c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 1; + }))); + sintetico2.set_Apolices(new int?(apolicePendentes.Count((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => { + if (c.get_Tipo() != 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico2.set_Endossos(new int?(apolicePendentes.Count((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => { + if (c.get_Tipo() == 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico2.set_Faturas(new int?(apolicePendentes.Count((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 2))); + sintetico2.set_TotalGeral(new int?(apolicePendentes.Count)); + sinteticos2.Add(sintetico2); + this.SinteticoRelatorio = new ObservableCollection(sinteticos2); + return; + } + case 4: + { + if (this.RenovacaoFiltrado == null || this.RenovacaoFiltrado.Count == 0) + { + return; + } + List renovacaos = (this.RenovacaoFiltrado.Any((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.get_Selecionado()) ? ( + from x in this.RenovacaoFiltrado + where x.get_Selecionado() + select x).ToList() : this.RenovacaoFiltrado.ToList()); + List sinteticos3 = new List(); + Sintetico sintetico3 = new Sintetico(); + sintetico3.set_PremioTotal(new decimal?(renovacaos.Sum((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.get_PremioTotal()))); + sintetico3.set_PremioLiquido(new decimal?(renovacaos.Sum((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao p) => p.get_PremioLiquido()))); + sintetico3.set_MediaComissao(new decimal?((renovacaos.Sum((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_Comissao()) > decimal.Zero ? decimal.Round(renovacaos.Sum((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_Comissao()) / renovacaos.Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_Comissao() > decimal.Zero), 2) : decimal.Zero))); + sintetico3.set_ComissaoGerada(new decimal?(renovacaos.Where((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => { + if (x.get_Tipo() == 3) + { + return false; + } + return x.get_Comissao() > decimal.Zero; + }).Sum((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => ((c.get_PremioLiquido() + (c.get_Documento().get_AdicionalComiss() ? c.get_Documento().get_PremioAdicional() : decimal.Zero)) * c.get_Comissao()) * new decimal(1, 0, 0, false, 2)))); + sintetico3.set_Cancelamentos(new int?(renovacaos.Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => { + if (c.get_Tipo() == 3) + { + return false; + } + return c.get_Documento().get_Situacao() == 3; + }))); + sintetico3.set_Novos(new int?(renovacaos.Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => { + if (c.get_Tipo() != 3 && c.get_Documento().get_Situacao() == 1) + { + return true; + } + if (c.get_Tipo() == 3 || c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 2; + }))); + sintetico3.set_Renovacoes(new int?(renovacaos.Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => { + if (c.get_Tipo() == 3 || c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 1; + }))); + sintetico3.set_Apolices(new int?(renovacaos.Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => { + if (c.get_Tipo() == 3) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico3.set_Endossos(null); + sintetico3.set_Faturas(new int?(renovacaos.Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => { + if (c.get_Tipo() == 3) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 2; + }))); + sintetico3.set_TotalProspeccao(new int?(renovacaos.Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_Tipo() == 3))); + sintetico3.set_TotalGeral(new int?(renovacaos.Count)); + sinteticos3.Add(sintetico3); + this.SinteticoRelatorio = new ObservableCollection(sinteticos3); + return; + } + case 5: + { + if (this.ComissaoFiltrado == null || this.ComissaoFiltrado.Count == 0) + { + return; + } + List comissaos = (this.ComissaoFiltrado.Any((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Selecionado()) ? ( + from x in this.ComissaoFiltrado + where x.get_Selecionado() + select x).ToList() : this.ComissaoFiltrado.ToList()); + List sinteticos4 = new List(); + Sintetico sintetico4 = new Sintetico(); + sintetico4.set_ComissaoRecebidaBruta(new decimal?(comissaos.Sum((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_ComissaoBruta()))); + sintetico4.set_ComissaoRecebidaLiquida(new decimal?(comissaos.Sum((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_ComissaoRecebida()))); + sintetico4.set_Impostos(new decimal?((comissaos.Sum((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Ir()) + comissaos.Sum((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Iss())) + comissaos.Sum((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Outros()))); + sintetico4.set_PremioLiquido(new decimal?(Funcoes.DistinctBy(comissaos, (Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Documento().get_Id()).Sum((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_PremioLiquido()))); + sintetico4.set_PremioTotal(new decimal?(Funcoes.DistinctBy(comissaos, (Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Documento().get_Id()).Sum((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_PremioTotal()))); + sintetico4.set_ComissaoPrevista(new decimal?(comissaos.Sum((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_ValorLiquido()))); + sintetico4.set_Repasse(new decimal?(comissaos.Sum((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Repasse()))); + sinteticos4.Add(sintetico4); + this.SinteticoRelatorio = new ObservableCollection(sinteticos4); + return; + } + case 6: + case 16: + { + if (this.PendenteFiltrado == null || this.PendenteFiltrado.Count == 0) + { + return; + } + List pendentes = (this.PendenteFiltrado.Any((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_Selecionado()) ? ( + from x in this.PendenteFiltrado + where x.get_Selecionado() + select x).ToList() : this.PendenteFiltrado.ToList()); + List sinteticos5 = new List(); + Sintetico sintetico5 = new Sintetico(); + sintetico5.set_ComissaoPrevista(new decimal?(pendentes.Sum((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_ComissaoPrevista()))); + sintetico5.set_TotalPrevista(new decimal?(Funcoes.DistinctBy(pendentes, (Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_Documento().get_Id()).Sum((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_TotalPrevisto()))); + sintetico5.set_TotalGeral(new int?(pendentes.Count)); + sintetico5.set_TotalParcela(new decimal?(pendentes.Sum((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_ValorParcela()))); + sinteticos5.Add(sintetico5); + this.SinteticoRelatorio = new ObservableCollection(sinteticos5); + return; + } + case 7: + case 11: + case 20: + case 21: + case 22: + case 23: + case 24: + case 25: + case 26: + case 27: + case 28: + { + return; + } + case 8: + { + if (this.AuditoriaFiltrado == null || this.AuditoriaFiltrado.Count == 0) + { + return; + } + List auditorias = (this.AuditoriaFiltrado.Any((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => x.get_Selecionado()) ? ( + from x in this.AuditoriaFiltrado + where x.get_Selecionado() + select x).ToList() : this.AuditoriaFiltrado.ToList()); + List sinteticos6 = new List(); + Sintetico sintetico6 = new Sintetico(); + sintetico6.set_PremioTotal(new decimal?(auditorias.Sum((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => x.get_PremioTotal()))); + sintetico6.set_PremioLiquido(new decimal?(auditorias.Sum((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria p) => p.get_PremioLiquido()))); + sintetico6.set_ComissaoRecebidaBruta(new decimal?(auditorias.Sum((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria p) => p.get_ComissaoRecebida()))); + sintetico6.set_MediaComissao(new decimal?((auditorias.Any((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_Comissao() > decimal.Zero) ? decimal.Round(auditorias.Sum((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_Comissao()) / auditorias.Count((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_Comissao() > decimal.Zero), 2) : decimal.Zero))); + sintetico6.set_ComissaoPrevista(new decimal?(auditorias.Sum((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_ComissaoPrevista()))); + sintetico6.set_ComissaoPendente(new decimal?(auditorias.Sum((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_ComissaoPendente()))); + sintetico6.set_Cancelamentos(new int?(auditorias.Count((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_Documento().get_Situacao() == 3))); + sintetico6.set_Novos(new int?(auditorias.Count((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => { + if (c.get_Documento().get_Situacao() == 1) + { + return true; + } + if (c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 2; + }))); + sintetico6.set_Renovacoes(new int?(auditorias.Count((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => { + if (c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 1; + }))); + sintetico6.set_Apolices(new int?(auditorias.Count((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => { + if (c.get_Tipo() != 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico6.set_Endossos(new int?(auditorias.Count((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => { + if (c.get_Tipo() == 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico6.set_Faturas(new int?(auditorias.Count((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 2))); + sintetico6.set_TotalGeral(new int?(auditorias.Count)); + sinteticos6.Add(sintetico6); + this.SinteticoRelatorio = new ObservableCollection(sinteticos6); + return; + } + case 9: + case 10: + { + if (this.SinistroFiltrado == null || this.SinistroFiltrado.Count == 0) + { + return; + } + List sinistros = (this.SinistroFiltrado.Any((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_Selecionado()) ? ( + from x in this.SinistroFiltrado + where x.get_Selecionado() + select x).ToList() : this.SinistroFiltrado.ToList()); + List sinteticos7 = new List(); + Sintetico sintetico7 = new Sintetico(); + sintetico7.set_Liquidado(new int?(sinistros.Count((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => { + if (x.get_StatusSinistro() != 2) + { + return false; + } + return x.get_TipoSinistro() == 0; + }))); + sintetico7.set_Valor(new decimal?(sinistros.Sum((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_Valor()))); + sintetico7.set_ValorOrcado(new decimal?(sinistros.Sum((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_ValorOrcado()))); + sintetico7.set_ValorLiberado(new decimal?(sinistros.Sum((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_ValorLiberado()))); + sintetico7.set_ValorPago(new decimal?(sinistros.Sum((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_ValorPago()))); + sintetico7.set_ValorLiquidado(new decimal?(( + from x in sinistros + where x.get_StatusSinistro() == 2 + select x).Sum((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_ValorPago()))); + sintetico7.set_ValorSalvado(new decimal?(sinistros.Sum((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_ValorSalvado()))); + sintetico7.set_ValorFranquia(new decimal?(sinistros.Sum((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_ValorFranquia()))); + sintetico7.set_Pendente(new int?(sinistros.Count((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => !x.get_Liquidacao().HasValue))); + sintetico7.set_TotalGeral(new int?(sinistros.Distinct().Count())); + sintetico7.set_TotalClientes(new int?(sinistros.Count((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_TipoSinistro() == 0))); + sintetico7.set_TotalTerceiros(new int?(sinistros.Count((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_TipoSinistro() == 1))); + sinteticos7.Add(sintetico7); + this.SinteticoRelatorio = new ObservableCollection(sinteticos7); + return; + } + case 12: + { + if (this.FaturaPendenteFiltrado == null || this.FaturaPendenteFiltrado.Count == 0) + { + return; + } + List faturaPendentes = (this.FaturaPendenteFiltrado.Any((Gestor.Model.Domain.Relatorios.FaturaPendente.FaturaPendente x) => x.get_Selecionado()) ? ( + from x in this.FaturaPendenteFiltrado + where x.get_Selecionado() + select x).ToList() : this.FaturaPendenteFiltrado.ToList()); + List sinteticos8 = new List(); + Sintetico sintetico8 = new Sintetico(); + sintetico8.set_TotalClientes(new int?(( + from x in faturaPendentes + select x.get_Cliente()).Distinct().Count())); + sintetico8.set_Cancelamentos(new int?(faturaPendentes.Count((Gestor.Model.Domain.Relatorios.FaturaPendente.FaturaPendente c) => c.get_Documento().get_Situacao() == 3))); + sintetico8.set_Novos(new int?(faturaPendentes.Count((Gestor.Model.Domain.Relatorios.FaturaPendente.FaturaPendente c) => { + if (c.get_Documento().get_Situacao() == 1) + { + return true; + } + if (c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 2; + }))); + sintetico8.set_Renovacoes(new int?(faturaPendentes.Count((Gestor.Model.Domain.Relatorios.FaturaPendente.FaturaPendente c) => { + if (c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 1; + }))); + sintetico8.set_Apolices(new int?(faturaPendentes.Count((Gestor.Model.Domain.Relatorios.FaturaPendente.FaturaPendente c) => { + if (c.get_Documento().get_Tipo() != 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico8.set_Endossos(new int?(faturaPendentes.Count((Gestor.Model.Domain.Relatorios.FaturaPendente.FaturaPendente c) => { + if (c.get_Documento().get_Tipo() == 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico8.set_Faturas(new int?(faturaPendentes.Count((Gestor.Model.Domain.Relatorios.FaturaPendente.FaturaPendente c) => c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 2))); + sintetico8.set_TotalGeral(new int?(faturaPendentes.Count)); + sinteticos8.Add(sintetico8); + this.SinteticoRelatorio = new ObservableCollection(sinteticos8); + return; + } + case 13: + { + if (this.ExtratosFiltrado == null || this.ExtratosFiltrado.Count == 0) + { + return; + } + List extratoBaixadoRelatorios = (this.ExtratosFiltrado.Any((ExtratoBaixadoRelatorio x) => x.get_Selecionado()) ? ( + from x in this.ExtratosFiltrado + where x.get_Selecionado() + select x).ToList() : this.ExtratosFiltrado.ToList()); + List sinteticos9 = new List(); + Sintetico sintetico9 = new Sintetico(); + sintetico9.set_TotalGeral(new int?(extratoBaixadoRelatorios.Count)); + sinteticos9.Add(sintetico9); + this.SinteticoRelatorio = new ObservableCollection(sinteticos9); + return; + } + case 14: + { + if (this.MetaSeguradoraFiltrado == null || this.MetaSeguradoraFiltrado.Count == 0) + { + return; + } + List metaSeguradoraRelatorios = (this.MetaSeguradoraFiltrado.Any((MetaSeguradoraRelatorio x) => x.get_Selecionado()) ? ( + from x in this.MetaSeguradoraFiltrado + where x.get_Selecionado() + select x).ToList() : this.MetaSeguradoraFiltrado.ToList()); + List sinteticos10 = new List(); + Sintetico sintetico10 = new Sintetico(); + sintetico10.set_MetaAtingir(new decimal?(metaSeguradoraRelatorios.Sum((MetaSeguradoraRelatorio x) => x.get_MetaAtingir()))); + sintetico10.set_MetaCumprida(new decimal?(metaSeguradoraRelatorios.Sum((MetaSeguradoraRelatorio p) => p.get_MetaCumprida()))); + sinteticos10.Add(sintetico10); + this.SinteticoRelatorio = new ObservableCollection(sinteticos10); + return; + } + case 15: + { + if (this.MetaVendedorFiltrado == null || this.MetaVendedorFiltrado.Count == 0) + { + return; + } + List metaVendedorRelatorios = (this.MetaVendedorFiltrado.Any((MetaVendedorRelatorio x) => x.get_Selecionado()) ? ( + from x in this.MetaVendedorFiltrado + where x.get_Selecionado() + select x).ToList() : this.MetaVendedorFiltrado.ToList()); + List sinteticos11 = new List(); + Sintetico sintetico11 = new Sintetico(); + sintetico11.set_MetaAtingir(new decimal?(metaVendedorRelatorios.Sum((MetaVendedorRelatorio x) => x.get_MetaAtingir()))); + sintetico11.set_MetaCumprida(new decimal?(metaVendedorRelatorios.Sum((MetaVendedorRelatorio p) => p.get_MetaCumprida()))); + sinteticos11.Add(sintetico11); + this.SinteticoRelatorio = new ObservableCollection(sinteticos11); + return; + } + case 17: + { + if (this.LicenciamentoFiltrado == null || this.LicenciamentoFiltrado.Count == 0) + { + return; + } + List licenciamentos = (this.LicenciamentoFiltrado.Any((Gestor.Model.Domain.Relatorios.Licenciamento.Licenciamento x) => x.get_Selecionado()) ? ( + from x in this.LicenciamentoFiltrado + where x.get_Selecionado() + select x).ToList() : this.LicenciamentoFiltrado.ToList()); + List sinteticos12 = new List(); + Sintetico sintetico12 = new Sintetico(); + sintetico12.set_TotalClientes(new int?(licenciamentos.Count)); + sinteticos12.Add(sintetico12); + this.SinteticoRelatorio = new ObservableCollection(sinteticos12); + return; + } + case 18: + { + if (this.TarefaFiltrado == null || this.TarefaFiltrado.Count == 0) + { + return; + } + List tarefas = (this.TarefaFiltrado.Any((Gestor.Model.Domain.Relatorios.Tarefa.Tarefa x) => x.get_Selecionado()) ? ( + from x in this.TarefaFiltrado + where x.get_Selecionado() + select x).ToList() : this.TarefaFiltrado.ToList()); + List sinteticos13 = new List(); + Sintetico sintetico13 = new Sintetico(); + sintetico13.set_TotalTarefas(new int?(tarefas.Count)); + sinteticos13.Add(sintetico13); + this.SinteticoRelatorio = new ObservableCollection(sinteticos13); + return; + } + case 19: + { + if (this.NotaFiscalFiltrado == null || this.NotaFiscalFiltrado.Count == 0) + { + return; + } + List notaFiscalRelatorios = (this.NotaFiscalFiltrado.Any((NotaFiscalRelatorio x) => x.get_Selecionado()) ? ( + from x in this.NotaFiscalFiltrado + where x.get_Selecionado() + select x).ToList() : this.NotaFiscalFiltrado.ToList()); + List sinteticos14 = new List(); + Sintetico sintetico14 = new Sintetico(); + sintetico14.set_PremioLiquido(new decimal?(notaFiscalRelatorios.Sum((NotaFiscalRelatorio p) => p.get_Liquido()))); + sintetico14.set_Iss(new decimal?(notaFiscalRelatorios.Sum((NotaFiscalRelatorio p) => p.get_Iss()))); + sintetico14.set_PremioTotal(new decimal?(notaFiscalRelatorios.Sum((NotaFiscalRelatorio x) => x.get_Bruto()))); + sintetico14.set_TotalGeral(new int?(notaFiscalRelatorios.Count)); + sinteticos14.Add(sintetico14); + this.SinteticoRelatorio = new ObservableCollection(sinteticos14); + return; + } + case 29: + { + if (this.ClassificacaoFiltrado == null || this.ClassificacaoFiltrado.Count == 0) + { + return; + } + if (this.ClassificacaoFiltrado.Any((Gestor.Model.Domain.Relatorios.Classificacao.Classificacao x) => x.get_Selecionado())) + { + ( + from x in this.ClassificacaoFiltrado + where x.get_Selecionado() + select x).ToList(); + } + else + { + this.ClassificacaoFiltrado.ToList(); + } + List sinteticos15 = new List(); + Sintetico sintetico15 = new Sintetico(); + sintetico15.set_TotalClientes(new int?(this.ClassificacaoFiltrado.Count())); + sinteticos15.Add(sintetico15); + this.SinteticoRelatorio = new ObservableCollection(sinteticos15); + return; + } + default: + { + return; + } + } + } + + private static Sintetico SintetizarRenovacao(string grupo, List sintetico) + { + Sintetico sintetico1 = new Sintetico(); + sintetico1.set_Agrupamento(grupo); + sintetico1.set_Cancelamentos(new int?(sintetico.Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => { + if (c.get_Tipo() == 3) + { + return false; + } + return c.get_Documento().get_Situacao() == 3; + }))); + sintetico1.set_Novos(new int?(sintetico.Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => { + if (c.get_Tipo() != 3 && c.get_Documento().get_Situacao() == 1) + { + return true; + } + if (c.get_Tipo() == 3 || c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 2; + }))); + sintetico1.set_Renovacoes(new int?(sintetico.Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => { + if (c.get_Tipo() == 3 || c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 1; + }))); + sintetico1.set_Apolices(new int?(sintetico.Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => { + if (c.get_Tipo() == 3 || c.get_Tipo() != 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico1.set_Endossos(new int?(sintetico.Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => { + if (c.get_Tipo() == 3 || c.get_Tipo() == 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico1.set_Faturas(new int?(sintetico.Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => { + if (c.get_Tipo() == 3) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 2; + }))); + sintetico1.set_TotalProspeccao(new int?(sintetico.Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_Tipo() == 3))); + sintetico1.set_TotalGeral(new int?(sintetico.Count)); + return sintetico1; + } + + private void StatusOnPropertyChanged(object sender, PropertyChangedEventArgs args) + { + if (this._alterandoFiltros) + { + return; + } + this.RecheckAllSelected(3); + } + + public void SubirParametro(Gestor.Model.Domain.Relatorios.ParametrosRelatorio parametro) + { + if (parametro == null) + { + return; + } + int num = this.ParametrosRelatorioAdicionados.IndexOf(parametro); + if (num == 0) + { + return; + } + this.ParametrosRelatorioAdicionados.Move(num, num - 1); + } + + private void TipoVendedorOnPropertyChanged(object sender, PropertyChangedEventArgs args) + { + if (this._alterandoFiltros) + { + return; + } + this.RecheckAllSelected(4); + } + + private static string UltimaMovimentacaoSinistro(Gestor.Model.Domain.Seguros.Sinistro x) + { + x.get_IdUsuarioAlteracao(); + if (x.get_IdUsuarioAlteracao() != 0) + { + return string.Format("{0} / {1}", x.get_DataAlteracao(), Recursos.Usuarios.First((Usuario usuario) => usuario.get_Id() == x.get_IdUsuarioAlteracao()).get_Nome()); + } + x.get_IdUsuarioCriacao(); + if (x.get_IdUsuarioCriacao() == 0) + { + return ""; + } + return string.Format("{0} / {1}", x.get_DataCriacao(), Recursos.Usuarios.First((Usuario usuario) => usuario.get_Id() == x.get_IdUsuarioCriacao()).get_Nome()); + } + + public async Task ValidateTarefa() + { + bool flag; + bool flag1 = false; + await this.ServicoRestriUsuario.BuscarRestricoes(Recursos.Usuario.get_Id()); + switch (this.Relatorio) + { + case 0: + { + if (this.ClientesAtivosInativosFiltrado != null && this.ClientesAtivosInativosFiltrado.Count != 0) + { + ObservableCollection clientesAtivosInativosFiltrado = this.ClientesAtivosInativosFiltrado; + if (!clientesAtivosInativosFiltrado.All((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => !x.get_Selecionado())) + { + goto case 26; + } + } + flag1 = true; + goto case 26; + } + case 1: + { + if (this.ClientesAtivosInativosFiltrado != null && this.ClientesAtivosInativosFiltrado.Count != 0) + { + ObservableCollection observableCollection = this.ClientesAtivosInativosFiltrado; + if (!observableCollection.All((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => !x.get_Selecionado())) + { + goto case 26; + } + } + flag1 = true; + goto case 26; + } + case 2: + { + if (this.ProducaoFiltrado != null && this.ProducaoFiltrado.Count != 0) + { + ObservableCollection producaoFiltrado = this.ProducaoFiltrado; + if (!producaoFiltrado.All((Gestor.Model.Domain.Relatorios.Producao.Producao x) => !x.get_Selecionado())) + { + goto case 26; + } + } + flag1 = true; + goto case 26; + } + case 3: + { + if (this.ApolicePendenteFiltrado != null && this.ApolicePendenteFiltrado.Count != 0) + { + ObservableCollection apolicePendenteFiltrado = this.ApolicePendenteFiltrado; + if (!apolicePendenteFiltrado.All((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => !x.get_Selecionado())) + { + goto case 26; + } + } + flag1 = true; + goto case 26; + } + case 4: + { + if (this.RenovacaoFiltrado != null && this.RenovacaoFiltrado.Count != 0) + { + ObservableCollection renovacaoFiltrado = this.RenovacaoFiltrado; + if (!renovacaoFiltrado.All((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => !x.get_Selecionado())) + { + goto case 26; + } + } + flag1 = true; + goto case 26; + } + case 5: + { + if (this.ComissaoFiltrado != null && this.ComissaoFiltrado.Count != 0) + { + ObservableCollection comissaoFiltrado = this.ComissaoFiltrado; + if (!comissaoFiltrado.All((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => !x.get_Selecionado())) + { + goto case 26; + } + } + flag1 = true; + goto case 26; + } + case 6: + case 16: + { + if (this.PendenteFiltrado != null && this.PendenteFiltrado.Count != 0) + { + ObservableCollection pendenteFiltrado = this.PendenteFiltrado; + if (!pendenteFiltrado.All((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => !x.get_Selecionado())) + { + goto case 26; + } + } + flag1 = true; + goto case 26; + } + case 7: + { + flag1 = true; + goto case 26; + } + case 8: + { + if (this.Auditoria != null && this.Auditoria.Count != 0) + { + List auditoria = this.Auditoria; + if (!auditoria.All((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => !x.get_Selecionado())) + { + goto case 26; + } + } + flag1 = true; + goto case 26; + } + case 9: + case 10: + { + if (this.SinistroFiltrado != null && this.SinistroFiltrado.Count != 0) + { + ObservableCollection sinistroFiltrado = this.SinistroFiltrado; + if (!sinistroFiltrado.All((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => !x.get_Selecionado())) + { + goto case 26; + } + } + flag1 = true; + goto case 26; + } + case 11: + case 20: + { + flag1 = true; + goto case 26; + } + case 12: + { + if (this.FaturaPendente != null && this.FaturaPendente.Count != 0) + { + List faturaPendente = this.FaturaPendente; + if (!faturaPendente.All((Gestor.Model.Domain.Relatorios.FaturaPendente.FaturaPendente x) => !x.get_Selecionado())) + { + goto case 26; + } + } + flag1 = true; + goto case 26; + } + case 13: + { + if (this.ExtratosFiltrado != null && this.ExtratosFiltrado.Count != 0) + { + ObservableCollection extratosFiltrado = this.ExtratosFiltrado; + if (!extratosFiltrado.All((ExtratoBaixadoRelatorio x) => !x.get_Selecionado())) + { + goto case 26; + } + } + flag1 = true; + goto case 26; + } + case 14: + { + if (this.MetaSeguradoraFiltrado != null && this.MetaSeguradoraFiltrado.Count != 0) + { + ObservableCollection metaSeguradoraFiltrado = this.MetaSeguradoraFiltrado; + if (!metaSeguradoraFiltrado.All((MetaSeguradoraRelatorio x) => !x.get_Selecionado())) + { + goto case 26; + } + } + flag1 = true; + goto case 26; + } + case 15: + { + if (this.MetaVendedorFiltrado != null && this.MetaVendedorFiltrado.Count != 0) + { + ObservableCollection metaVendedorFiltrado = this.MetaVendedorFiltrado; + if (!metaVendedorFiltrado.All((MetaVendedorRelatorio x) => !x.get_Selecionado())) + { + goto case 26; + } + } + flag1 = true; + goto case 26; + } + case 17: + { + if (this.LicenciamentoFiltrado != null && this.LicenciamentoFiltrado.Count != 0) + { + ObservableCollection licenciamentoFiltrado = this.LicenciamentoFiltrado; + if (!licenciamentoFiltrado.All((Gestor.Model.Domain.Relatorios.Licenciamento.Licenciamento x) => !x.get_Selecionado())) + { + goto case 26; + } + } + flag1 = true; + goto case 26; + } + case 18: + case 19: + case 21: + case 22: + case 23: + case 24: + case 25: + case 26: + { + if (flag1) + { + await base.ShowMessage("NECESSÁRIO SELECIONAR AO MENOS UM ITEM NA LISTA PARA GERAR TAREFAS.", "OK", "", false); + } + flag = flag1; + break; + } + case 27: + { + if (this.PlacaFiltrado != null && this.PlacaFiltrado.Count != 0) + { + ObservableCollection placaFiltrado = this.PlacaFiltrado; + if (!placaFiltrado.All((Gestor.Model.Domain.Relatorios.Placa.Placas x) => !x.get_Selecionado())) + { + goto case 26; + } + } + flag1 = true; + goto case 26; + } + default: + { + goto case 26; + } + } + return flag; + } + + private void VendedorOnPropertyChanged(object sender, PropertyChangedEventArgs args) + { + if (this._alterandoFiltros) + { + return; + } + this.RecheckAllSelected(2); + } + + private void WorkOnRelatorio(Gestor.Model.Common.Relatorio value) + { + bool id; + bool flag; + this.HtmlContent = string.Empty; + this.VisibilityHtml = false; + this.FiltroRelatorioSelecionado = new ObservableCollection(); + this.LimparFiltros(); + this.VisibilityFiltros = Visibility.Visible; + this.VisibilityMaisFiltros = Visibility.Visible; + this.VisibilityGridFiltros = Visibility.Collapsed; + this.VisibilityData = Visibility.Visible; + this.VisibilityOlho = Visibility.Visible; + this.VisibilityEspecial = Visibility.Collapsed; + this.VisibilityPagamento = Visibility.Collapsed; + this.VisibilityExtratos = Visibility.Visible; + this.VisibilityEtiqueta = Visibility.Visible; + this.VisibilityEmail = Visibility.Visible; + this.VisibilityAgrupamento = Visibility.Visible; + this.VisibilitySintetizar = Visibility.Visible; + Usuario usuario = Recursos.Usuario; + if (usuario != null) + { + id = usuario.get_Id() > (long)0; + } + else + { + id = false; + } + this.VisibilityTarefas = (id ? Visibility.Visible : Visibility.Collapsed); + this.VisibilityAcompanhamento = Visibility.Collapsed; + this.VisibilityReferencia = Visibility.Collapsed; + this.VisibiltyProtocolo = Visibility.Collapsed; + this.VisibilityMeta = Visibility.Collapsed; + this.VisibilityApolice = Visibility.Collapsed; + this.VisibiltySincronizar = (value == 3 || value == 16 ? Visibility.Visible : Visibility.Collapsed); + this.VisibilityComparativo = Visibility.Collapsed; + this.VisibilityCompleto = Visibility.Collapsed; + this.VisibilityNotaFiscalPorSeguradora = Visibility.Collapsed; + this.Agrupamento = 0; + this.NovosNegocios = false; + this.ExtratosEnabled = false; + this.PermitirFiltrosPersonalizados = (value == 11 ? false : value != 7); + this.VisibilityFiltroPersonalizadoButton = Visibility.Visible; + Usuario usuario1 = Recursos.Usuario; + if (usuario1 != null) + { + flag = usuario1.get_Id() > (long)0; + } + else + { + flag = false; + } + this.VisibilityConfigurar = (flag ? Visibility.Visible : Visibility.Collapsed); + this.VisibilityUsuarios = false; + this.VisibilityOrdem = Visibility.Collapsed; + this.VisibilityValor = Visibility.Collapsed; + this.PlanilhaVisibility = Visibility.Collapsed; + this.VisibilityDocumentoAtivo = Visibility.Collapsed; + this.LimparFiltroUsuario(); + this.InicioValor = 0; + this.FimValor = 0; + switch (value) + { + case 0: + { + this.VisibilityAgrupamento = Visibility.Collapsed; + this.VisibilityData = Visibility.Collapsed; + this.VisibilitySintetizar = Visibility.Collapsed; + this.VisibilityMaisFiltros = Visibility.Collapsed; + this.VisibilityFiltros = Visibility.Collapsed; + this.VisibilityCompleto = Visibility.Visible; + this.InfoVisibility = Visibility.Collapsed; + return; + } + case 1: + { + this.VisibilityAgrupamento = Visibility.Collapsed; + this.VisibilitySintetizar = Visibility.Collapsed; + this.VisibilityMaisFiltros = Visibility.Collapsed; + this.VisibilityFiltros = Visibility.Collapsed; + this.VisibilityExtratos = Visibility.Collapsed; + this.Info = "O RELATÓRIO DE ANIVERSARIANTE CONSIDERA O DIA E MÊS FILTRADOS E DESCONSIDERA O ANO INFORMADO NA PESQUISA."; + this.InfoVisibility = Visibility.Visible; + return; + } + case 2: + { + this.VisibiltyProtocolo = Visibility.Visible; + FiltroRelatorio filtroRelatorio = new FiltroRelatorio(); + filtroRelatorio.set_Id((long)1); + filtroRelatorio.set_Descricao(EnumHelper.GetDescription(1)); + filtroRelatorio.set_Tipo(5); + this.AdicionarFiltro(filtroRelatorio); + FiltroRelatorio filtroRelatorio1 = new FiltroRelatorio(); + filtroRelatorio1.set_Id((long)2); + filtroRelatorio1.set_Descricao(EnumHelper.GetDescription(2)); + filtroRelatorio1.set_Tipo(5); + this.AdicionarFiltro(filtroRelatorio1); + this.Referencias = new ObservableCollection(new List() + { + "VIGÊNCIA INICIAL", + "EMISSÃO", + "TRANSMISSÃO PROPOSTA", + "DATA DE CADASTRO" + }); + this.Referencia = this.Referencias.First(); + this.VisibilityReferencia = Visibility.Visible; + this.VisibilityGridFiltros = Visibility.Visible; + this.VisibilityOlho = Visibility.Collapsed; + this.PlanilhaVisibility = Visibility.Visible; + return; + } + case 3: + { + this.VisibiltyProtocolo = Visibility.Visible; + this.VisibiltySincronizar = Visibility.Visible; + this.VisibilityExtratos = Visibility.Collapsed; + return; + } + case 4: + { + this.VisibiltyProtocolo = Visibility.Visible; + this.VisibilityAcompanhamento = Visibility.Visible; + this.PlanilhaVisibility = Visibility.Visible; + return; + } + case 5: + { + this.VisibilityExtratos = Visibility.Collapsed; + return; + } + case 6: + case 9: + { + this.VisibilityExtratos = Visibility.Collapsed; + this.PlanilhaVisibility = Visibility.Collapsed; + return; + } + case 7: + { + this.ParcelasEspeciais[0].set_IsEnable(true); + this.VisibilityEspecial = Visibility.Visible; + this.VisibilityPagamento = Visibility.Visible; + this.VisibilityExtratos = Visibility.Collapsed; + this.VisibilityEtiqueta = Visibility.Collapsed; + this.VisibilityEmail = Visibility.Collapsed; + this.VisibilityAgrupamento = Visibility.Collapsed; + this.VisibilityTarefas = Visibility.Collapsed; + this.SomenteNaoPagos = true; + this.ReciboPagamento = false; + this.VisibilityOrdem = (Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 8) ? Visibility.Visible : Visibility.Collapsed); + this.Ordens = new ObservableCollection(new List() + { + "DATA RECEBIMENTO", + "NOME CLIENTE", + "SEGURADORA, RAMO" + }); + this.OrdemSelecionada = this.Ordens.First(); + this.VisibilityHtml = true; + return; + } + case 8: + { + this.ParcelasEspeciais[0].set_IsEnable(false); + this.VisibilityEspecial = Visibility.Visible; + this.VisibilityExtratos = Visibility.Collapsed; + this.Info = "AGORA O RELATÓRIO DE AUDITORIA SELECIONA TODOS OS SEGUROS, MESMO TENDO PARCELAS PENDENTES, PARA FILTRAR APENAS OS SEGUROS SEM PARCELAS PENDENTES, BASTA UTILIZAR O FILTRO PERSONALIZADO 'RECEBIDO POR COMPLETO', PREENCHER 'SIM' EM SEU VALOR E APLICAR O FILTRO"; + this.InfoVisibility = Visibility.Visible; + FiltroRelatorio filtroRelatorio2 = new FiltroRelatorio(); + filtroRelatorio2.set_Id((long)1); + filtroRelatorio2.set_Descricao(EnumHelper.GetDescription(1)); + filtroRelatorio2.set_Tipo(5); + this.AdicionarFiltro(filtroRelatorio2); + FiltroRelatorio filtroRelatorio3 = new FiltroRelatorio(); + filtroRelatorio3.set_Id((long)2); + filtroRelatorio3.set_Descricao(EnumHelper.GetDescription(2)); + filtroRelatorio3.set_Tipo(5); + this.AdicionarFiltro(filtroRelatorio3); + FiltroRelatorio filtroRelatorio4 = new FiltroRelatorio(); + filtroRelatorio4.set_Id((long)3); + filtroRelatorio4.set_Descricao(EnumHelper.GetDescription(3)); + filtroRelatorio4.set_Tipo(5); + this.AdicionarFiltro(filtroRelatorio4); + FiltroRelatorio filtroRelatorio5 = new FiltroRelatorio(); + filtroRelatorio5.set_Id((long)4); + filtroRelatorio5.set_Descricao(EnumHelper.GetDescription(4)); + filtroRelatorio5.set_Tipo(5); + this.AdicionarFiltro(filtroRelatorio5); + FiltroRelatorio filtroRelatorio6 = new FiltroRelatorio(); + filtroRelatorio6.set_Id((long)5); + filtroRelatorio6.set_Descricao(EnumHelper.GetDescription(5)); + filtroRelatorio6.set_Tipo(5); + this.AdicionarFiltro(filtroRelatorio6); + FiltroRelatorio filtroRelatorio7 = new FiltroRelatorio(); + filtroRelatorio7.set_Id((long)6); + filtroRelatorio7.set_Descricao(EnumHelper.GetDescription(6)); + filtroRelatorio7.set_Tipo(5); + this.AdicionarFiltro(filtroRelatorio7); + return; + } + case 10: + { + this.VisibilityExtratos = Visibility.Collapsed; + this.VisibilityReferencia = Visibility.Visible; + this.Referencias = new ObservableCollection(new List() + { + "DATA SINISTRO", + "DATA LIQUIDAÇÃO", + "DATA RECLAMAÇÃO" + }); + this.Referencia = this.Referencias.First(); + return; + } + case 11: + { + this.VisibilityComparativo = Visibility.Visible; + this.VisibilityEspecial = Visibility.Collapsed; + this.VisibilityExtratos = Visibility.Collapsed; + this.VisibilityEtiqueta = Visibility.Collapsed; + this.VisibilityEmail = Visibility.Collapsed; + this.VisibilityAgrupamento = Visibility.Collapsed; + this.VisibilitySintetizar = Visibility.Visible; + this.VisibilityTarefas = Visibility.Collapsed; + this.VisibilityReferencia = Visibility.Visible; + this.Referencias = new ObservableCollection(new List() + { + "VIGÊNCIA INICIAL", + "EMISSÃO" + }); + this.Referencia = this.Referencias.First(); + return; + } + case 12: + { + this.Referencias = new ObservableCollection(new List() + { + "VIGÊNCIA", + "VENCIMENTO" + }); + this.Referencia = this.Referencias.First(); + this.VisibilityReferencia = Visibility.Visible; + this.VisibilityExtratos = Visibility.Collapsed; + this.VisibilitySintetizar = Visibility.Collapsed; + return; + } + case 13: + case 20: + { + this.Referencias = new ObservableCollection(new List() + { + "DATA IMPORTAÇÃO", + "DATA DO EXTRATO", + "DATA DO CRÉDITO" + }); + this.Referencia = this.Referencias.First(); + if (this.Relatorio == 13) + { + this.VisibilityReferencia = Visibility.Visible; + this.VisibilityMaisFiltros = Visibility.Collapsed; + } + this.VisibilityEspecial = Visibility.Collapsed; + this.VisibilityExtratos = Visibility.Collapsed; + this.VisibilityEtiqueta = Visibility.Collapsed; + this.VisibilityEmail = Visibility.Collapsed; + this.VisibilityAgrupamento = Visibility.Collapsed; + this.VisibilitySintetizar = Visibility.Collapsed; + this.VisibilityTarefas = Visibility.Collapsed; + return; + } + case 14: + case 15: + { + this.VisibilityEtiqueta = Visibility.Collapsed; + this.VisibilityAgrupamento = Visibility.Collapsed; + this.VisibilityData = Visibility.Collapsed; + this.VisibilitySintetizar = Visibility.Visible; + this.VisibilityExtratos = Visibility.Collapsed; + this.VisibilityMeta = Visibility.Visible; + this.Agrupamento = (this.Relatorio == 15 ? 3 : 1); + DateTime date = Funcoes.GetNetworkTime().Date; + this.SelectedMes = date.Month; + this.SelectedAno = date.Year; + return; + } + case 16: + { + this.VisibilityExtratos = Visibility.Collapsed; + this.PlanilhaVisibility = Visibility.Collapsed; + this.VisibilityDocumentoAtivo = Visibility.Visible; + return; + } + case 17: + { + this.VisibilityExtratos = Visibility.Collapsed; + this.VisibilitySintetizar = Visibility.Collapsed; + this.VisibilityAgrupamento = Visibility.Collapsed; + this.VisibilityMaisFiltros = Visibility.Collapsed; + this.VisibilityTarefas = Visibility.Collapsed; + this.VisibilityEtiqueta = Visibility.Collapsed; + this.VisibilityData = Visibility.Collapsed; + this.VisibilityValor = Visibility.Visible; + this.InfoVisibility = Visibility.Collapsed; + return; + } + case 18: + { + this.VisibilityExtratos = Visibility.Collapsed; + this.VisibilitySintetizar = Visibility.Collapsed; + this.VisibilityAgrupamento = Visibility.Collapsed; + this.VisibilityMaisFiltros = Visibility.Collapsed; + this.VisibilityTarefas = Visibility.Collapsed; + this.VisibilityEtiqueta = Visibility.Collapsed; + this.VisibilityEmail = Visibility.Collapsed; + return; + } + case 19: + { + this.VisibilityExtratos = Visibility.Collapsed; + this.VisibilityEtiqueta = Visibility.Collapsed; + this.VisibilityAgrupamento = Visibility.Collapsed; + this.VisibilityNotaFiscalPorSeguradora = Visibility.Visible; + this.VisibilitySintetizar = Visibility.Collapsed; + this.VisibilityEmail = Visibility.Collapsed; + this.VisibilityTarefas = Visibility.Collapsed; + return; + } + case 21: + case 22: + { + return; + } + case 23: + { + this.VisibilitySintetizar = Visibility.Collapsed; + this.VisibilityEtiqueta = Visibility.Collapsed; + this.VisibilityMaisFiltros = Visibility.Collapsed; + this.VisibilityTarefas = Visibility.Collapsed; + this.VisibilityEmail = Visibility.Collapsed; + this.VisibilityExtratos = Visibility.Collapsed; + return; + } + case 24: + case 25: + { + this.VisibilityExtratos = Visibility.Collapsed; + this.VisibilitySintetizar = Visibility.Collapsed; + this.VisibilityAgrupamento = Visibility.Collapsed; + this.VisibilityMaisFiltros = Visibility.Visible; + this.VisibilityTarefas = Visibility.Collapsed; + this.VisibilityEtiqueta = Visibility.Collapsed; + this.VisibilityEmail = Visibility.Collapsed; + return; + } + case 26: + { + this.VisibilityExtratos = Visibility.Collapsed; + this.VisibilitySintetizar = Visibility.Collapsed; + this.VisibilityAgrupamento = Visibility.Collapsed; + this.VisibilityMaisFiltros = Visibility.Collapsed; + this.VisibilityTarefas = Visibility.Collapsed; + this.VisibilityEtiqueta = Visibility.Collapsed; + this.PlanilhaVisibility = Visibility.Collapsed; + return; + } + case 27: + { + this.VisibilitySintetizar = Visibility.Collapsed; + this.VisibilityEtiqueta = Visibility.Collapsed; + this.VisibilityMaisFiltros = Visibility.Collapsed; + this.VisibilityTarefas = Visibility.Collapsed; + this.VisibilityEmail = Visibility.Collapsed; + this.VisibilityExtratos = Visibility.Collapsed; + return; + } + case 28: + { + this.VisibilitySintetizar = Visibility.Collapsed; + this.VisibilityEtiqueta = Visibility.Collapsed; + this.VisibilityMaisFiltros = Visibility.Collapsed; + this.VisibilityTarefas = Visibility.Collapsed; + this.VisibilityEmail = Visibility.Collapsed; + this.VisibilityExtratos = Visibility.Collapsed; + this.Referencias = new ObservableCollection(new List() + { + "VIGÊNCIA INICIAL", + "EMISSÃO", + "TRANSMISSÃO PROPOSTA", + "DATA DE CADASTRO" + }); + this.Referencia = this.Referencias.First(); + this.VisibilityReferencia = Visibility.Visible; + this.VisibilityGridFiltros = Visibility.Visible; + this.PlanilhaVisibility = Visibility.Visible; + return; + } + case 29: + { + this.VisibilityExtratos = Visibility.Collapsed; + this.VisibilitySintetizar = Visibility.Collapsed; + this.VisibilityAgrupamento = Visibility.Collapsed; + this.VisibilityData = Visibility.Collapsed; + this.VisibilitySintetizar = Visibility.Collapsed; + this.VisibilityMaisFiltros = Visibility.Collapsed; + this.VisibilityFiltros = Visibility.Collapsed; + this.VisibilityCompleto = Visibility.Collapsed; + this.InfoVisibility = Visibility.Collapsed; + this.Info = ""; + return; + } + default: + { + return; + } + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Relatorios/SinteticoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Relatorios/SinteticoViewModel.cs new file mode 100644 index 0000000..6adc8e5 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Relatorios/SinteticoViewModel.cs @@ -0,0 +1,424 @@ +using ClosedXML.Excel; +using Gestor.Application.Componentes; +using Gestor.Application.Helpers; +using Gestor.Application.Model; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Helpers; +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Relatorios; +using LiveCharts; +using LiveCharts.Definitions.Series; +using LiveCharts.Helpers; +using LiveCharts.Wpf; +using NReco.PdfGenerator; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Forms; +using System.Windows.Media; + +namespace Gestor.Application.ViewModels.Relatorios +{ + public class SinteticoViewModel : BaseSegurosViewModel + { + private Visibility _unicaPaginaVisibility = Visibility.Collapsed; + + private Geometry _maximizeRestore = Geometry.Parse((string)System.Windows.Application.Current.Resources["Restore"]); + + private ObservableCollection _series; + + private string _titulotela = string.Format("RELATÓRIO SINTÉTICO | VERSÃO GESTOR {0}", ApplicationHelper.Versao); + + public Geometry MaximizeRestore + { + get + { + return this._maximizeRestore; + } + set + { + this._maximizeRestore = value; + base.OnPropertyChanged("MaximizeRestore"); + } + } + + public string Relatorio + { + get; + set; + } + + public ObservableCollection Series + { + get + { + return this._series; + } + set + { + this._series = value; + base.OnPropertyChanged("Series"); + } + } + + public string Titulotela + { + get + { + return this._titulotela; + } + set + { + this._titulotela = value; + base.OnPropertyChanged("Titulotela"); + } + } + + public Visibility UnicaPaginaVisibility + { + get + { + return this._unicaPaginaVisibility; + } + set + { + this._unicaPaginaVisibility = value; + base.OnPropertyChanged("UnicaPaginaVisibility"); + } + } + + public SinteticoViewModel(List sintetico, string relatorio) + { + this.Relatorio = relatorio; + this.GerarSintetico(sintetico); + } + + public async Task GerarExcel(SinteticoSource sintetico) + { + List listagems = SinteticoViewModel.GerarRelacao(sintetico.Lista.ToList()); + string tempPath = ""; + string str = ""; + List configuracoes = Recursos.Configuracoes; + if (!configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 41)) + { + tempPath = Path.GetTempPath(); + str = string.Format("{0}{1}.xlsx", tempPath, Guid.NewGuid()); + } + else + { + using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog()) + { + if (DialogResult.OK == folderBrowserDialog.ShowDialog()) + { + tempPath = string.Concat(folderBrowserDialog.SelectedPath, "\\"); + Directory.CreateDirectory(tempPath); + } + else + { + str = null; + return; + } + } + DateTime date = Functions.GetNetworkTime().Date; + str = string.Concat(tempPath, "SINTETICO ", date.ToShortDateString().Replace("/", ""), ".xlsx"); + } + await Funcoes.GerarXls(new XLWorkbook(), "SINTÉTICO", listagems, null).SaveAs(str); + Process.Start(str); + str = null; + } + + public async Task GerarPdf(SinteticoSource sintetico) + { + string str = await Funcoes.GenerateTable(SinteticoViewModel.GerarRelacao(sintetico.Lista.ToList()), new List(), false, false, "", null); + TipoRelatorio tipoRelatorio = new TipoRelatorio(); + tipoRelatorio.set_Nome(sintetico.Titulo); + tipoRelatorio.set_Inicio(DateTime.MinValue); + tipoRelatorio.set_Fim(DateTime.MinValue); + string str1 = Funcoes.ExportarHtml(tipoRelatorio, str, "60", "landscape", false, ""); + NRecoHtmlToPdfConverter nRecoHtmlToPdfConverter = new NRecoHtmlToPdfConverter(); + ((HtmlToPdfConverter)nRecoHtmlToPdfConverter).set_Orientation(1); + ((HtmlToPdfConverter)nRecoHtmlToPdfConverter).set_Zoom(0.5f); + byte[] numArray = ((HtmlToPdfConverter)nRecoHtmlToPdfConverter).GeneratePdf(str1); + using (SaveFileDialog saveFileDialog = new SaveFileDialog()) + { + saveFileDialog.Filter = "All Files|*.*"; + saveFileDialog.FileName = string.Format("RELATORIO FINANCEIRO_{0:ddMMyyyyhhmmss}", Funcoes.GetNetworkTime()); + if (DialogResult.OK != saveFileDialog.ShowDialog()) + { + return; + } + else if (!File.Exists(string.Concat(saveFileDialog.FileName, ".pdf"))) + { + File.WriteAllBytes(string.Concat(saveFileDialog.FileName, ".pdf"), numArray); + Process.Start(string.Concat(saveFileDialog.FileName, ".pdf")); + } + else + { + string[] fileName = new string[] { "JÁ EXISTE UM ARQUIVO COM O NOME DE ", saveFileDialog.FileName, ".pdf NA PASTA SELECIONADA. ", Environment.NewLine, "TENTE NOVAMENTE EM OUTRA PASTA." }; + await base.ShowMessage(string.Concat(fileName), "OK", "", false); + return; + } + } + saveFileDialog = null; + } + + private static List GerarRelacao(List lista) + { + return lista.Select((ValorSintetico x) => { + Listagem listagem = new Listagem(); + listagem.set_Agrupamento(x.get_Indice()); + listagem.set_Valor((x.get_Formato() == "VALOR" ? x.get_Valor().ToString("c2") : (x.get_Formato() == "PERCENTUAL" ? x.get_Valor().ToString("p2") : x.get_Valor().ToString(new CultureInfo("pt-BR"))))); + listagem.set_NomeRelatorio(x.get_NomeRelatorio()); + return listagem; + }).ToList(); + } + + private static List> GerarRelacao(List> listas) + { + List> lists = new List>(); + foreach (List lista in listas) + { + lists.Add(SinteticoViewModel.GerarRelacao(lista)); + } + return lists; + } + + private void GerarSintetico(List sintetico) + { + IChartValues chartValue; + decimal num; + this.UnicaPaginaVisibility = (this.Relatorio == "RELATÓRIO DE FECHAMENTO" ? Visibility.Visible : Visibility.Collapsed); + this.Series = new ObservableCollection(); + PropertyInfo[] properties = sintetico.First().GetType().GetProperties(); + for (int i = 0; i < (int)properties.Length; i++) + { + PropertyInfo propertyInfo = properties[i]; + if (!(propertyInfo.Name == "ValidationEvent") && !(propertyInfo.Name == "Agrupamento") && !sintetico.All((Sintetico s) => { + object value; + PropertyInfo property = s.GetType().GetProperty(propertyInfo.Name); + value = (property != null ? property.GetValue(s, null) : null); + return value == null; + })) + { + object obj = propertyInfo.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault(); + if (obj != null) + { + string description = ((DescriptionAttribute)obj).Description; + SinteticoSource sinteticoSource = new SinteticoSource() + { + Titulo = description, + Colecao = new SeriesCollection(), + Lista = new ObservableCollection() + }; + object obj1 = propertyInfo.GetCustomAttributes(typeof(TipoAttribute), true).FirstOrDefault(); + string str = ""; + if (obj1 != null) + { + str = ((TipoAttribute)obj1).get_Description(); + } + sintetico = ( + from x in sintetico + orderby propertyInfo.GetValue(x, null) descending + select x).ToList(); + foreach (Sintetico sintetico1 in sintetico) + { + bool flag = false; + PieSeries pieSeries = new PieSeries(); + pieSeries.set_Title(sintetico1.get_Agrupamento()); + pieSeries.set_DataLabels(false); + PieSeries pieSeries1 = pieSeries; + if (str == "PERCENTUAL") + { + flag = (decimal)propertyInfo.GetValue(sintetico1) < decimal.Zero; + ChartValues chartValue1 = new ChartValues(); + chartValue1.Add(Math.Abs((decimal)propertyInfo.GetValue(sintetico1))); + chartValue = chartValue1; + ObservableCollection lista = sinteticoSource.Lista; + ValorSintetico valorSintetico = new ValorSintetico(); + valorSintetico.set_Indice(string.Concat(sintetico1.get_Agrupamento(), (flag ? " (-)" : ""))); + valorSintetico.set_Valor(Math.Round((decimal)propertyInfo.GetValue(sintetico1) * new decimal(1, 0, 0, false, 2), 2)); + valorSintetico.set_Unidate("%"); + valorSintetico.set_Sinal((flag ? 1 : 0)); + valorSintetico.set_NomeRelatorio(description); + lista.Add(valorSintetico); + pieSeries1.set_LabelPoint((ChartPoint chartPoint) => ((decimal)propertyInfo.GetValue(sintetico1)).ToString("n2")); + } + else if (str == "VALOR") + { + flag = (decimal)propertyInfo.GetValue(sintetico1) < decimal.Zero; + ChartValues chartValue2 = new ChartValues(); + chartValue2.Add(Math.Abs((decimal)propertyInfo.GetValue(sintetico1))); + chartValue = chartValue2; + ObservableCollection observableCollection = sinteticoSource.Lista; + ValorSintetico valorSintetico1 = new ValorSintetico(); + valorSintetico1.set_Indice(string.Concat(sintetico1.get_Agrupamento(), (flag ? " (-)" : ""))); + valorSintetico1.set_Valor(Math.Round((decimal)propertyInfo.GetValue(sintetico1), 2)); + valorSintetico1.set_Formato(str); + valorSintetico1.set_Unidate("R$"); + valorSintetico1.set_Sinal((flag ? 1 : 0)); + valorSintetico1.set_NomeRelatorio(description); + observableCollection.Add(valorSintetico1); + pieSeries1.set_LabelPoint((ChartPoint chartPoint) => ((decimal)propertyInfo.GetValue(sintetico1)).ToString("n2")); + } + else + { + flag = (int)propertyInfo.GetValue(sintetico1) < 0; + ChartValues chartValue3 = new ChartValues(); + chartValue3.Add(Math.Abs((int)propertyInfo.GetValue(sintetico1))); + chartValue = chartValue3; + ObservableCollection lista1 = sinteticoSource.Lista; + ValorSintetico valorSintetico2 = new ValorSintetico(); + valorSintetico2.set_Indice(string.Concat(sintetico1.get_Agrupamento(), (flag ? " (-)" : ""))); + valorSintetico2.set_Valor(decimal.Parse(propertyInfo.GetValue(sintetico1).ToString())); + valorSintetico2.set_Formato(str); + valorSintetico2.set_Sinal((flag ? 1 : 0)); + valorSintetico2.set_NomeRelatorio(description); + lista1.Add(valorSintetico2); + pieSeries1.set_LabelPoint((ChartPoint chartPoint) => ((int)propertyInfo.GetValue(sintetico1)).ToString("n")); + } + pieSeries1.set_Values(chartValue); + sinteticoSource.Colecao.Add(pieSeries1); + } + if (obj1 != null && !(str == "PERCENTUAL")) + { + if (str != "VALOR") + { + if (this.Relatorio.Equals("RELATÓRIO DE FECHAMENTO")) + { + int num1 = sintetico.Sum((Sintetico x) => (int)propertyInfo.GetValue(x, null)); + if (num1 != 0) + { + foreach (ValorSintetico listum in sinteticoSource.Lista) + { + num = (new decimal(100) * listum.get_Valor()) / num1; + listum.set_Porcentagem(string.Concat(num.ToString("F"), "%")); + } + } + } + else + { + int num2 = sintetico.Sum((Sintetico x) => (int)propertyInfo.GetValue(x, null)); + if (num2 != 0) + { + foreach (ValorSintetico listum1 in sinteticoSource.Lista) + { + num = (new decimal(100) * listum1.get_Valor()) / num2; + listum1.set_Porcentagem(string.Concat(num.ToString("F"), "%")); + } + } + ObservableCollection observableCollection1 = sinteticoSource.Lista; + ValorSintetico valorSintetico3 = new ValorSintetico(); + valorSintetico3.set_Indice("TOTAL"); + valorSintetico3.set_Valor(num2); + valorSintetico3.set_Formato(str); + valorSintetico3.set_Sinal((sintetico.Sum((Sintetico x) => (int)propertyInfo.GetValue(x, null)) < 0 ? 1 : 0)); + valorSintetico3.set_Porcentagem("100%"); + observableCollection1.Add(valorSintetico3); + } + } + else if (this.Relatorio.Equals("RELATÓRIO DE FECHAMENTO")) + { + decimal num3 = Math.Round(sintetico.Sum((Sintetico x) => (decimal)propertyInfo.GetValue(x, null)), 2); + if (num3 != decimal.Zero) + { + foreach (ValorSintetico listum2 in sinteticoSource.Lista) + { + num = (new decimal(100) * listum2.get_Valor()) / num3; + listum2.set_Porcentagem(string.Concat(num.ToString("F"), "%")); + } + } + } + else + { + decimal num4 = Math.Round(sintetico.Sum((Sintetico x) => (decimal)propertyInfo.GetValue(x, null)), 2); + if (num4 != decimal.Zero) + { + foreach (ValorSintetico listum3 in sinteticoSource.Lista) + { + num = (new decimal(100) * listum3.get_Valor()) / num4; + listum3.set_Porcentagem(string.Concat(num.ToString("F"), "%")); + } + } + ObservableCollection lista2 = sinteticoSource.Lista; + ValorSintetico valorSintetico4 = new ValorSintetico(); + valorSintetico4.set_Indice("TOTAL"); + valorSintetico4.set_Valor(num4); + valorSintetico4.set_Unidate("R$"); + valorSintetico4.set_Formato(str); + valorSintetico4.set_Sinal((sintetico.Sum((Sintetico x) => (decimal)propertyInfo.GetValue(x, null)) < decimal.Zero ? 1 : 0)); + valorSintetico4.set_Porcentagem("100%"); + lista2.Add(valorSintetico4); + } + } + this.Series.Add(sinteticoSource); + } + } + } + } + + public async Task Print(SinteticoSource sintetico) + { + DateTime dateTime; + DateTime dateTime1; + string str = Funcoes.GerarGrafico(sintetico.Lista.ToList()); + string str1 = await Funcoes.GenerateTable(SinteticoViewModel.GerarRelacao(sintetico.Lista.ToList()), new List(), true, false, "", null); + TipoRelatorio tipoRelatorio = new TipoRelatorio(); + tipoRelatorio.set_Nome(sintetico.Titulo); + DateTime? dateStart = sintetico.DateStart; + dateTime = (dateStart.HasValue ? dateStart.GetValueOrDefault() : DateTime.MinValue); + tipoRelatorio.set_Inicio(dateTime); + dateStart = sintetico.DateFinal; + dateTime1 = (dateStart.HasValue ? dateStart.GetValueOrDefault() : DateTime.MinValue); + tipoRelatorio.set_Fim(dateTime1); + string str2 = Funcoes.ExportarHtml(tipoRelatorio, str1, "60", "landscape", false, str); + string tempPath = Path.GetTempPath(); + string str3 = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.html", tempPath, (new Regex(string.Concat("[", Regex.Escape(string.Concat(new string(Path.GetInvalidFileNameChars()), new string(Path.GetInvalidPathChars()))), "]"))).Replace(this.Relatorio, ""), Funcoes.GetNetworkTime()); + StreamWriter streamWriter = new StreamWriter(str3, true, Encoding.UTF8); + streamWriter.Write(str2); + streamWriter.Close(); + Process.Start(str3); + str = null; + } + + public async Task PrintUnica(SinteticoSource sintetico) + { + DateTime dateTime; + DateTime dateTime1; + List> lists = new List>(); + foreach (SinteticoSource series in this.Series) + { + lists.Add(series.Lista.ToList()); + } + string str = Funcoes.GerarGraficoUnico(lists); + string str1 = await Funcoes.GenerateMultipleTable(SinteticoViewModel.GerarRelacao(lists), new List(), true, false, "", null); + TipoRelatorio tipoRelatorio = new TipoRelatorio(); + tipoRelatorio.set_Nome("RELATÓRIOS"); + DateTime? dateStart = sintetico.DateStart; + dateTime = (dateStart.HasValue ? dateStart.GetValueOrDefault() : DateTime.MinValue); + tipoRelatorio.set_Inicio(dateTime); + dateStart = sintetico.DateFinal; + dateTime1 = (dateStart.HasValue ? dateStart.GetValueOrDefault() : DateTime.MinValue); + tipoRelatorio.set_Fim(dateTime1); + string str2 = Funcoes.ExportarMultipleHtml(tipoRelatorio, str1, "60", "landscape", false, str); + string tempPath = Path.GetTempPath(); + string str3 = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.html", tempPath, (new Regex(string.Concat("[", Regex.Escape(string.Concat(new string(Path.GetInvalidFileNameChars()), new string(Path.GetInvalidPathChars()))), "]"))).Replace(this.Relatorio, ""), Funcoes.GetNetworkTime()); + StreamWriter streamWriter = new StreamWriter(str3, true, Encoding.UTF8); + streamWriter.Write(str2); + streamWriter.Close(); + Process.Start(str3); + str = null; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Seguros/ApoliceViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Seguros/ApoliceViewModel.cs new file mode 100644 index 0000000..94fc4be --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Seguros/ApoliceViewModel.cs @@ -0,0 +1,124 @@ +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Seguros +{ + public class ApoliceViewModel : BaseApoliceViewModel + { + private bool _documentoExcluido; + + public bool DocumentoExcluido + { + get + { + return this._documentoExcluido; + } + set + { + this._documentoExcluido = value; + base.OnPropertyChanged("DocumentoExcluido"); + } + } + + public ApoliceViewModel(AcessoApolice acesso, Documento documentoSelecionado, bool invoke = true, long idparcela = 0L) + { + long id; + base.Invoke = invoke; + base.Acesso = acesso; + base.DocumentoSelecionado = documentoSelecionado; + if (invoke) + { + Parcela parcelaSelecionada = ConsultaViewModel.ParcelaSelecionada; + if (parcelaSelecionada != null) + { + id = parcelaSelecionada.get_Id(); + } + else + { + id = (long)0; + } + } + else + { + id = idparcela; + } + base.ParcelaSelecionada = id; + this.DocumentoExcluido = (base.DocumentoSelecionado != null ? base.DocumentoSelecionado.get_Excluido() : false); + base.Seleciona(base.DocumentoSelecionado); + } + + public void AbrirInfo() + { + base.ShowDrawer(new InfoDrawer(base.SelectedDocumento, true), 0, false); + } + + public async Task Alteracao(bool alterar) + { + if (base.AllowEditApolice) + { + ObservableCollection parcelas = base.Parcelas; + if (!parcelas.Any((Parcela x) => x.get_DataRecebimento().HasValue)) + { + List repasses = base.Repasses; + if (!repasses.Any((VendedorParcela x) => x.get_DataPagamento().HasValue)) + { + List list = Recursos.Seguradoras.Where((Seguradora x) => { + if (x.get_Ativo()) + { + return true; + } + return x.get_Id() == base.SelectedDocumento.get_Controle().get_Seguradora().get_Id(); + }).ToList(); + base.Seguradoras = list; + base.SeguradorasAnteriores = Recursos.Seguradoras; + List ramos = Recursos.Ramos.Where((Ramo x) => { + if (x.get_Ativo()) + { + return true; + } + return x.get_Id() == base.SelectedDocumento.get_Controle().get_Ramo().get_Id(); + }).ToList(); + base.Ramos = ramos; + List produtos = Recursos.Produtos.Where((Produto x) => { + if (x.get_Ativo()) + { + return true; + } + if (base.SelectedDocumento.get_Controle().get_Produto() == null) + { + return false; + } + return x.get_Id() == base.SelectedDocumento.get_Controle().get_Produto().get_Id(); + }).ToList(); + base.Produtos = produtos; + List statuses = Recursos.Status.Where((Gestor.Model.Domain.Seguros.Status x) => { + if (x.get_Ativo()) + { + return true; + } + if (base.SelectedDocumento.get_Status() == null) + { + return false; + } + return x.get_Id() == base.SelectedDocumento.get_Status().get_Id(); + }).ToList(); + base.Status = statuses; + return; + } + } + } + await base.ShowMessage("DOCUMENTO POSSUI BAIXAS DE COMISSÃO OU PAGAMENTO DE VENDEDORES.\nNÃO SERÁ POSSÍVEL ALTERAR ALGUMAS INFORMAÇÕES DO DOCUMENTO.\nPARA ISSO, EXCLUA AS BAIXAS E O PAGAMENTO DO VENDEDOR", "OK", "", false); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Seguros/ClienteViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Seguros/ClienteViewModel.cs new file mode 100644 index 0000000..b68e57d --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Seguros/ClienteViewModel.cs @@ -0,0 +1,1787 @@ +using Agger.Registro; +using Gestor.Application.Actions; +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Command; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Security; +using Gestor.Common.Validation; +using Gestor.Model.API; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Net.Http; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Input; + +namespace Gestor.Application.ViewModels.Seguros +{ + public class ClienteViewModel : BaseSegurosViewModel + { + private const int NumeroMaximoCadastros = 9; + + private readonly ClienteServico _servico; + + private const string AddCentralSegurado = "ADICIONAR CENTRAL SEGURADO"; + + private const string UpdateCentralSegurado = "ALTERAR DADOS/SENHA CENTRAL SEGURADO"; + + private bool _visibilityLogAntigo = Recursos.Configuracoes.Any(new Func((ConfiguracaoSistema x) => x.get_Configuracao() == 22)); + + private ObservableCollection _telefones = new ObservableCollection(); + + private ObservableCollection _emails = new ObservableCollection(); + + private ObservableCollection _enderecos = new ObservableCollection(); + + private ObservableCollection _contatos = new ObservableCollection(); + + private ObservableCollection _vinculos = new ObservableCollection(); + + private Cliente _vinculo; + + private bool _isLoading; + + private bool _clienteExcluido; + + private DateTime? _nascimentoCliente; + + private DateTime? _habilitaCliente; + + private DateTime? _vencimentoHabCliente; + + private DateTime? _expedicaoCliente; + + private Cliente _selectedCliente; + + private string _fieldNascimento = "NASCIMENTO"; + + private string _fieldDocumento = "CPF"; + + private Visibility _visibilityJuridica = Visibility.Collapsed; + + private Visibility _visibilityFisica = Visibility.Collapsed; + + private bool _enableAddTelephone = true; + + private bool _enableAddAddress = true; + + private bool _enableAddEmail = true; + + private bool _enableAddContact = true; + + private string _profissaoText; + + private string _atividadeText; + + private bool _saving; + + private ObservableCollection _origens; + + private OrigemCliente _selectedOrigem; + + public Visibility AddUsuarioCentralSeguradoVisibility { get; set; } = (string.IsNullOrEmpty(Connection.UrlCentralSegurado) ? Visibility.Collapsed : Visibility.Visible); + + public string AtividadeText + { + get + { + return this._atividadeText; + } + set + { + this._atividadeText = value; + base.OnPropertyChanged("AtividadeText"); + } + } + + public bool ClienteExcluido + { + get + { + return this._clienteExcluido; + } + set + { + this._clienteExcluido = value; + base.OnPropertyChanged("ClienteExcluido"); + } + } + + private Cliente ClienteSelecionado + { + get; + set; + } + + public ICommand CommandAddUsuarioCentralSegurado + { + get; + set; + } + + public ObservableCollection Contatos + { + get + { + return this._contatos; + } + set + { + this._contatos = value; + base.OnPropertyChanged("Contatos"); + } + } + + public ObservableCollection Emails + { + get + { + return this._emails; + } + set + { + this._emails = value; + base.OnPropertyChanged("Emails"); + } + } + + public bool EnableAddAddress + { + get + { + return this._enableAddAddress; + } + set + { + this._enableAddAddress = value; + base.OnPropertyChanged("EnableAddAddress"); + } + } + + public bool EnableAddContact + { + get + { + return this._enableAddContact; + } + set + { + this._enableAddContact = value; + base.OnPropertyChanged("EnableAddContact"); + } + } + + public bool EnableAddEmail + { + get + { + return this._enableAddEmail; + } + set + { + this._enableAddEmail = value; + base.OnPropertyChanged("EnableAddEmail"); + } + } + + public bool EnableAddTelephone + { + get + { + return this._enableAddTelephone; + } + set + { + this._enableAddTelephone = value; + base.OnPropertyChanged("EnableAddTelephone"); + } + } + + public ObservableCollection Enderecos + { + get + { + return this._enderecos; + } + set + { + this._enderecos = value; + base.OnPropertyChanged("Enderecos"); + } + } + + public DateTime? ExpedicaoCliente + { + get + { + return this._expedicaoCliente; + } + set + { + this._expedicaoCliente = value; + base.OnPropertyChanged("ExpedicaoCliente"); + } + } + + public string FieldDocumento + { + get + { + return this._fieldDocumento; + } + set + { + this._fieldDocumento = value; + base.OnPropertyChanged("FieldDocumento"); + } + } + + public string FieldNascimento + { + get + { + return this._fieldNascimento; + } + set + { + this._fieldNascimento = value; + base.OnPropertyChanged("FieldNascimento"); + } + } + + public DateTime? HabilitaCliente + { + get + { + return this._habilitaCliente; + } + set + { + this._habilitaCliente = value; + base.OnPropertyChanged("HabilitaCliente"); + } + } + + private bool Invoke + { + get; + } + + private bool IsJuridica + { + get; + set; + } + + public bool IsLoading + { + get + { + return this._isLoading; + } + set + { + this._isLoading = value; + base.OnPropertyChanged("IsLoading"); + } + } + + public string LabelAddUsuarioCentralSegurado + { + get + { + if (this.SelectedCliente != null && this.SelectedCliente.get_EstaNaCentralSegurado()) + { + return "ALTERAR DADOS/SENHA CENTRAL SEGURADO"; + } + return "ADICIONAR CENTRAL SEGURADO"; + } + } + + public DateTime? NascimentoCliente + { + get + { + return this._nascimentoCliente; + } + set + { + this._nascimentoCliente = value; + base.OnPropertyChanged("NascimentoCliente"); + } + } + + public ObservableCollection Origens + { + get + { + return this._origens; + } + set + { + this._origens = value; + base.OnPropertyChanged("Origens"); + if (this.Origens != null) + { + this.SelectedOrigem = this.Origens.FirstOrDefault(); + } + } + } + + public string ProfissaoText + { + get + { + return this._profissaoText; + } + set + { + this._profissaoText = value; + base.OnPropertyChanged("ProfissaoText"); + } + } + + public bool Salvando + { + get; + set; + } + + public Cliente SelectedCliente + { + get + { + return this._selectedCliente; + } + set + { + long? nullable; + this._selectedCliente = value; + this.WorkOnSelectedCliente(value); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedCliente"); + base.OnPropertyChanged("LabelAddUsuarioCentralSegurado"); + } + } + + public OrigemCliente SelectedOrigem + { + get + { + return this._selectedOrigem; + } + set + { + this._selectedOrigem = value; + base.OnPropertyChanged("SelectedOrigem"); + } + } + + public ObservableCollection Telefones + { + get + { + return this._telefones; + } + set + { + this._telefones = value; + base.OnPropertyChanged("Telefones"); + } + } + + public DateTime? VencimentoHabCliente + { + get + { + return this._vencimentoHabCliente; + } + set + { + this._vencimentoHabCliente = value; + base.OnPropertyChanged("VencimentoHabCliente"); + } + } + + public Cliente Vinculo + { + get + { + return this._vinculo; + } + set + { + this._vinculo = value; + base.OnPropertyChanged("Vinculo"); + } + } + + public ObservableCollection Vinculos + { + get + { + return this._vinculos; + } + set + { + if (value != null && value.Count > 0 && this.SelectedCliente != null) + { + foreach (ClienteVinculo clienteVinculo in value) + { + if (clienteVinculo.get_Cliente2().get_Id() != this.SelectedCliente.get_Id()) + { + continue; + } + clienteVinculo.set_Parentesco(Funcoes.ParentescoInverso(clienteVinculo.get_Parentesco())); + } + } + this._vinculos = value; + base.OnPropertyChanged("Vinculos"); + } + } + + public Visibility VisibilityFisica + { + get + { + return this._visibilityFisica; + } + set + { + this._visibilityFisica = value; + base.OnPropertyChanged("VisibilityFisica"); + } + } + + public Visibility VisibilityJuridica + { + get + { + return this._visibilityJuridica; + } + set + { + this._visibilityJuridica = value; + base.OnPropertyChanged("VisibilityJuridica"); + } + } + + public bool VisibilityLogAntigo + { + get + { + return this._visibilityLogAntigo; + } + set + { + this._visibilityLogAntigo = value; + base.OnPropertyChanged("VisibilityLogAntigo"); + } + } + + public ClienteViewModel(Cliente cliente = null, bool invoke = true) + { + this.Invoke = invoke; + this._servico = new ClienteServico(); + this.ClienteSelecionado = cliente ?? MainViewModel.ClienteSelecionado; + this.SelecionaCliente(this.ClienteSelecionado); + this.CommandAddUsuarioCentralSegurado = new RelayCommand(() => this.AddUsuarioCentralSegurado()); + } + + public async void AbrirLogAntigo() + { + base.Loading(true); + string str = await this._servico.BuscarLogAntigo(this.SelectedCliente.get_Id()); + base.Loading(false); + if (!string.IsNullOrEmpty(str)) + { + base.ShowDrawer(new LogSistemaAntigo(this.SelectedCliente.get_Id(), str), 0, false); + } + else + { + await base.ShowMessage("NÃO HÁ LOG PARA ESSE CLIENTE", "OK", "", false); + } + } + + public async void AddUsuarioCentralSegurado() + { + string str; + string str1; + string str2; + string str3; + string str4; + string str5; + string str6; + string str7; + if (this.SelectedCliente != null && this.SelectedCliente.get_Emails().Count != 0) + { + base.Loading(true); + str7 = "CLIENTE CADASTRADO/ALTERADO COM SUCESSO!"; + try + { + str = (this.SelectedCliente.get_Telefones().Count == 0 ? string.Empty : string.Concat("(", this.SelectedCliente.get_Telefones()[0].get_Prefixo(), ") ", this.SelectedCliente.get_Telefones()[0].get_Numero())); + string str8 = str; + bool count = this.SelectedCliente.get_Enderecos().Count > 0; + Token token = new Token(); + UsuarioCentralSegurado usuarioCentralSegurado = new UsuarioCentralSegurado(); + usuarioCentralSegurado.set_Id(""); + usuarioCentralSegurado.set_Senha(""); + usuarioCentralSegurado.set_Serial(token.Encrypt(Recursos.Empresa.get_Serial())); + usuarioCentralSegurado.set_FornecedorId(ApplicationHelper.IdFornecedor); + usuarioCentralSegurado.set_Nome(token.Encrypt(this.SelectedCliente.get_Nome())); + usuarioCentralSegurado.set_Documento(token.Encrypt(this.SelectedCliente.get_Documento().Clear())); + usuarioCentralSegurado.set_Email(token.Encrypt(this.SelectedCliente.get_Emails()[0].get_Email())); + usuarioCentralSegurado.set_IdEmpresa(this.SelectedCliente.get_IdEmpresa()); + usuarioCentralSegurado.set_Telefone(token.Encrypt(str8)); + str1 = (count ? token.Encrypt(this.SelectedCliente.get_Enderecos()[0].get_Endereco()) : string.Empty); + usuarioCentralSegurado.set_Rua(str1); + str2 = (count ? token.Encrypt(this.SelectedCliente.get_Enderecos()[0].get_Numero()) : string.Empty); + usuarioCentralSegurado.set_Numero(str2); + str3 = (count ? token.Encrypt(this.SelectedCliente.get_Enderecos()[0].get_Bairro()) : string.Empty); + usuarioCentralSegurado.set_Bairro(str3); + str4 = (count ? token.Encrypt(this.SelectedCliente.get_Enderecos()[0].get_Cidade()) : string.Empty); + usuarioCentralSegurado.set_Cidade(str4); + str5 = (count ? token.Encrypt(this.SelectedCliente.get_Enderecos()[0].get_Estado()) : string.Empty); + usuarioCentralSegurado.set_Estado(str5); + str6 = (count ? token.Encrypt(this.SelectedCliente.get_Enderecos()[0].get_Cep()) : string.Empty); + usuarioCentralSegurado.set_Cep(str6); + usuarioCentralSegurado.set_Corretora(token.Encrypt(Recursos.Empresa.get_Nome())); + usuarioCentralSegurado.set_UriCorretora(token.Encrypt(Connection.UrlCentralSegurado)); + UsuarioCentralSegurado usuarioCentralSegurado1 = usuarioCentralSegurado; + using (HttpClient httpClient = new HttpClient()) + { + StringContent stringContent = new StringContent(JsonConvert.SerializeObject(usuarioCentralSegurado1), Encoding.UTF8, "application/json"); + Uri centralSegurado = Address.get_CentralSegurado(); + string[] strArrays = new string[] { "Usuario" }; + Uri uri = centralSegurado.Append(strArrays); + string[] strArrays1 = new string[] { "AddAggerApp" }; + Uri uri1 = uri.Append(strArrays1); + HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(uri1, stringContent); + await this._servico.AddCentralSegurado(this.SelectedCliente.get_Id(), httpResponseMessage.get_IsSuccessStatusCode()); + if (!httpResponseMessage.get_IsSuccessStatusCode()) + { + string str9 = await httpResponseMessage.get_Content().ReadAsStringAsync(); + str7 = string.Concat("HOUVE(RAM) O(S) SEGUINTE(S) ERROS: ", str9.Replace(";", ", ").ToUpper()); + } + httpResponseMessage = null; + } + httpClient = null; + } + catch + { + str7 = "HOUVERAM ERROS AO CADASTRAR/ALTERAR O CLIENTE!"; + } + base.OnPropertyChanged("LabelAddUsuarioCentralSegurado"); + base.Loading(false); + await base.ShowMessage(str7, "OK", "", false); + } + str7 = null; + } + + public async void CancelarAlteracao() + { + base.Loading(true); + this.IsLoading = true; + base.Alterar(false); + await this.CarregaCliente(this.ClienteSelecionado); + this.Salvando = false; + this.IsLoading = false; + base.Loading(false); + } + + public async Task CarregaCliente(Cliente value) + { + bool count; + bool flag; + bool count1; + bool flag1; + bool count2; + bool flag2; + bool count3; + Cliente cliente; + if (value == null || value.get_Id() == 0) + { + this.SelectedCliente = null; + this.Telefones = null; + this.Enderecos = null; + this.Emails = null; + this.Contatos = null; + this.Vinculos = null; + this.Origens = null; + } + else + { + cliente = value; + if (value.get_Id() != 0) + { + cliente = await this._servico.BuscarCliente(value.get_Id()); + Cliente cliente1 = cliente; + ObservableCollection observableCollection = await this._servico.BuscarTelefonesAsync(value.get_Id()); + cliente1.set_Telefones(observableCollection); + cliente1 = null; + ClienteViewModel clienteViewModel = this; + ObservableCollection telefones = cliente.get_Telefones(); + if (telefones != null) + { + count = telefones.Count <= 9; + } + else + { + count = false; + } + clienteViewModel.EnableAddTelephone = count; + cliente1 = cliente; + ObservableCollection observableCollection1 = await this._servico.BuscarEmailsAsync(value.get_Id()); + cliente1.set_Emails(observableCollection1); + cliente1 = null; + ClienteViewModel clienteViewModel1 = this; + ObservableCollection emails = cliente.get_Emails(); + if (emails != null) + { + flag = emails.Count <= 9; + } + else + { + flag = false; + } + clienteViewModel1.EnableAddEmail = flag; + cliente1 = cliente; + ObservableCollection observableCollection2 = await this._servico.BuscarEnderecosAsync(value.get_Id()); + cliente1.set_Enderecos(observableCollection2); + cliente1 = null; + ClienteViewModel clienteViewModel2 = this; + ObservableCollection enderecos = cliente.get_Enderecos(); + if (enderecos != null) + { + count1 = enderecos.Count <= 9; + } + else + { + count1 = false; + } + clienteViewModel2.EnableAddAddress = count1; + cliente1 = cliente; + ObservableCollection observableCollection3 = await this._servico.BuscarContatosAsync(value.get_Id()); + cliente1.set_Contatos(observableCollection3); + cliente1 = null; + ClienteViewModel clienteViewModel3 = this; + ObservableCollection contatos = cliente.get_Contatos(); + if (contatos != null) + { + flag1 = contatos.Count <= 9; + } + else + { + flag1 = false; + } + clienteViewModel3.EnableAddContact = flag1; + cliente1 = cliente; + ObservableCollection observableCollection4 = await this._servico.BuscarVinculosAsync(value.get_Id()); + cliente1.set_Vinculos(observableCollection4); + cliente1 = null; + this.Origens = await this._servico.BuscarOrigens(value.get_Id()); + this.Telefones = cliente.get_Telefones(); + ObservableCollection telefones1 = this.Telefones; + if (telefones1 != null) + { + count2 = telefones1.Count == 0; + } + else + { + count2 = false; + } + if (count2) + { + this.IncluirTelefone(); + } + this.Emails = cliente.get_Emails(); + ObservableCollection emails1 = this.Emails; + if (emails1 != null) + { + flag2 = emails1.Count == 0; + } + else + { + flag2 = false; + } + if (flag2) + { + this.IncluirEmail(); + } + this.Enderecos = cliente.get_Enderecos(); + ObservableCollection enderecos1 = this.Enderecos; + if (enderecos1 != null) + { + count3 = enderecos1.Count == 0; + } + else + { + count3 = false; + } + if (count3) + { + this.IncluirEndereco(); + } + this.Contatos = cliente.get_Contatos(); + this.Vinculos = cliente.get_Vinculos(); + } + if (!cliente.get_DocumentoPrincipal().HasValue) + { + cliente.set_DocumentoPrincipal(new TipoDocumento?(0)); + } + if (cliente.get_ResponsavelAssinatura() == null) + { + Cliente cliente2 = cliente; + ResponsavelAssinatura responsavelAssinatura = new ResponsavelAssinatura(); + responsavelAssinatura.set_IdCliente(cliente.get_Id()); + cliente2.set_ResponsavelAssinatura(responsavelAssinatura); + } + this.SelectedCliente = cliente; + this.JuridicaouFisica(this.SelectedCliente.get_Documento()); + this.SelectedCliente.Initialize(); + ObservableCollection telefones2 = this.SelectedCliente.get_Telefones(); + if (telefones2 != null) + { + List list = telefones2.ToList(); + list.ForEach((ClienteTelefone telefone) => telefone.Initialize()); + } + else + { + } + ObservableCollection enderecos2 = this.SelectedCliente.get_Enderecos(); + if (enderecos2 != null) + { + List clienteEnderecos = enderecos2.ToList(); + clienteEnderecos.ForEach((ClienteEndereco endereco) => endereco.Initialize()); + } + else + { + } + ObservableCollection contatos1 = this.SelectedCliente.get_Contatos(); + if (contatos1 != null) + { + List maisContatos = contatos1.ToList(); + maisContatos.ForEach((MaisContato contato) => contato.Initialize()); + } + else + { + } + ObservableCollection emails2 = this.SelectedCliente.get_Emails(); + if (emails2 != null) + { + List clienteEmails = emails2.ToList(); + clienteEmails.ForEach((ClienteEmail email) => email.Initialize()); + } + else + { + } + ObservableCollection vinculos = this.SelectedCliente.get_Vinculos(); + if (vinculos != null) + { + List clienteVinculos = vinculos.ToList(); + clienteVinculos.ForEach((ClienteVinculo vinculo) => vinculo.Initialize()); + } + else + { + } + this.Initialized = true; + } + cliente = null; + } + + public async void Excluir() + { + Cliente selectedCliente; + if (this.SelectedCliente != null && this.SelectedCliente.get_Id() != 0) + { + if (await (new ApoliceServico()).BuscarApolicesAsync(this.SelectedCliente.get_Id(), 4, null).Count > 0) + { + await base.ShowMessage("NÃO É POSSÍVEL EXCLUIR O CLIENTE POIS POSSUI APÓLICES CADASTRADAS.", "OK", "", false); + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + selectedCliente = this.SelectedCliente; + selectedCliente.set_Excluido(true); + if (await this._servico.Delete(selectedCliente)) + { + this.ClienteSelecionado = null; + MainViewModel.ClienteSelecionado = null; + Action limparCliente = Gestor.Application.Actions.Actions.LimparCliente; + if (limparCliente != null) + { + limparCliente(); + } + else + { + } + Cliente cliente = new Cliente(); + cliente.set_IdEmpresa(Recursos.Usuario.get_IdEmpresa()); + cliente.set_DocumentoPrincipal(new TipoDocumento?(0)); + cliente.set_ClienteDesde(new DateTime?(Funcoes.GetNetworkTime().Date)); + this.SelectedCliente = cliente; + ObservableCollection observableCollection = new ObservableCollection(); + ClienteTelefone clienteTelefone = new ClienteTelefone(); + clienteTelefone.set_Cliente(this.SelectedCliente); + clienteTelefone.set_Tipo(new TipoTelefone?(1)); + clienteTelefone.set_Ordem(new int?(1)); + observableCollection.Add(clienteTelefone); + this.Telefones = observableCollection; + ObservableCollection observableCollection1 = new ObservableCollection(); + ClienteEndereco clienteEndereco = new ClienteEndereco(); + clienteEndereco.set_Cliente(this.SelectedCliente); + clienteEndereco.set_Ordem(new int?(1)); + observableCollection1.Add(clienteEndereco); + this.Enderecos = observableCollection1; + ObservableCollection observableCollection2 = new ObservableCollection(); + ClienteEmail clienteEmail = new ClienteEmail(); + clienteEmail.set_Cliente(this.SelectedCliente); + clienteEmail.set_Ordem(new int?(1)); + observableCollection2.Add(clienteEmail); + this.Emails = observableCollection2; + this.Contatos = new ObservableCollection(); + this.Vinculos = new ObservableCollection(); + this.Origens = new ObservableCollection(); + string str = string.Format("EXCLUIU CLIENTE \"{0}\", ID: {1}", selectedCliente.get_Nome(), selectedCliente.get_Id()); + base.RegistrarAcao(str, selectedCliente.get_Id(), new TipoTela?(1), string.Format("CLIENTE \"{0}\", ID: {1}", this.SelectedCliente.get_Nome(), this.SelectedCliente.get_Id())); + base.ToggleSnackBar("CLIENTE EXCLUÍDO COM SUCESSO", true); + } + } + } + selectedCliente = null; + } + + public void ExcluirContato(MaisContato contato) + { + this.EnableAddContact = this.Contatos.Count <= 9; + this.Contatos.Remove(contato); + } + + public async void ExcluirEmail(ClienteEmail email) + { + if (this.Emails.Count < 2) + { + List configuracoes = Recursos.Configuracoes; + if (configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 29)) + { + await base.ShowMessage("É NECESSÁRIO TER AO MENOS UM CONTATO DE E-MAIL CADASTRADO.", "OK", "", false); + return; + } + } + this.EnableAddEmail = this.Emails.Count <= 9; + this.Emails.Remove(email); + } + + public async void ExcluirEndereco(ClienteEndereco endereco) + { + if (this.Enderecos.Count >= 2) + { + this.EnableAddAddress = this.Enderecos.Count <= 9; + this.Enderecos.Remove(endereco); + } + else + { + await base.ShowMessage("É NECESSÁRIO TER AO MENOS UM ENDEREÇO CADASTRADO.", "OK", "", false); + } + } + + public async Task ExcluirOrigem(OrigemCliente origem) + { + ClienteViewModel clienteViewModel = this; + clienteViewModel.Origens.Remove(origem); + clienteViewModel.OnPropertyChanged("Origens"); + } + + public async void ExcluirTelefone(ClienteTelefone telefone) + { + if (this.Telefones.Count >= 2) + { + this.EnableAddTelephone = this.Telefones.Count <= 9; + this.Telefones.Remove(telefone); + } + else + { + await base.ShowMessage("É NECESSÁRIO TER AO MENOS UM CONTATO TELEFÔNICO CADASTRADO.", "OK", "", false); + } + } + + public void ExcluirVinculo(ClienteVinculo vinculo) + { + this.Vinculos.Remove(vinculo); + } + + public void IncluirCliente() + { + DateTime date = Funcoes.GetNetworkTime().Date; + Cliente cliente = new Cliente(); + cliente.set_IdEmpresa(Recursos.Usuario.get_IdEmpresa()); + cliente.set_DocumentoPrincipal(new TipoDocumento?(0)); + cliente.set_ClienteDesde(new DateTime?(date)); + cliente.set_ResponsavelAssinatura(new ResponsavelAssinatura()); + this.SelectedCliente = cliente; + this.NascimentoCliente = new DateTime?(date); + this.HabilitaCliente = new DateTime?(date); + this.VencimentoHabCliente = new DateTime?(date); + this.ExpedicaoCliente = new DateTime?(date); + ObservableCollection observableCollection = new ObservableCollection(); + ClienteTelefone clienteTelefone = new ClienteTelefone(); + clienteTelefone.set_Cliente(this.SelectedCliente); + clienteTelefone.set_Tipo(new TipoTelefone?(1)); + clienteTelefone.set_Ordem(new int?(1)); + observableCollection.Add(clienteTelefone); + this.Telefones = observableCollection; + ObservableCollection observableCollection1 = new ObservableCollection(); + ClienteEndereco clienteEndereco = new ClienteEndereco(); + clienteEndereco.set_Cliente(this.SelectedCliente); + clienteEndereco.set_Ordem(new int?(1)); + observableCollection1.Add(clienteEndereco); + this.Enderecos = observableCollection1; + ObservableCollection observableCollection2 = new ObservableCollection(); + ClienteEmail clienteEmail = new ClienteEmail(); + clienteEmail.set_Cliente(this.SelectedCliente); + clienteEmail.set_Ordem(new int?(1)); + observableCollection2.Add(clienteEmail); + this.Emails = observableCollection2; + this.Contatos = new ObservableCollection(); + this.Vinculos = new ObservableCollection(); + this.Origens = new ObservableCollection(); + this.Salvando = true; + base.Alterar(true); + } + + public void IncluirContato() + { + if (this.SelectedCliente == null) + { + return; + } + if (this.Contatos == null) + { + this.Contatos = new ObservableCollection(); + } + MaisContato maisContato = new MaisContato(); + maisContato.set_Cliente(this.SelectedCliente); + MaisContato maisContato1 = maisContato; + this.EnableAddContact = this.Contatos.Count < 9; + this.Contatos.Add(maisContato1); + base.OnPropertyChanged("IncluirContato"); + } + + public void IncluirEmail() + { + if (this.SelectedCliente == null) + { + return; + } + if (this.Emails == null) + { + this.Emails = new ObservableCollection(); + } + this.EnableAddEmail = this.Emails.Count < 9; + ClienteEmail clienteEmail = new ClienteEmail(); + clienteEmail.set_Cliente(this.SelectedCliente); + clienteEmail.set_Ordem(new int?(this.Emails.Count + 1)); + this.Emails.Add(clienteEmail); + base.OnPropertyChanged("IncluirEmail"); + } + + public void IncluirEndereco() + { + if (this.SelectedCliente == null) + { + return; + } + if (this.Enderecos == null) + { + this.Enderecos = new ObservableCollection(); + } + this.EnableAddAddress = this.Enderecos.Count < 9; + ClienteEndereco clienteEndereco = new ClienteEndereco(); + clienteEndereco.set_Cliente(this.SelectedCliente); + clienteEndereco.set_Ordem(new int?(this.Enderecos.Count + 1)); + this.Enderecos.Add(clienteEndereco); + base.OnPropertyChanged("IncluirEndereco"); + } + + public async Task IncluirOrigem(string name) + { + if (this.SelectedCliente != null && !string.IsNullOrWhiteSpace(name)) + { + if (this.Origens == null) + { + this.Origens = new ObservableCollection(); + } + if (!this.Origens.Any((OrigemCliente x) => { + string str; + string nome = x.get_Nome(); + if (nome != null) + { + str = nome.Trim(); + } + else + { + str = null; + } + return str == name.Trim(); + })) + { + ObservableCollection origens = this.Origens; + OrigemCliente origemCliente = new OrigemCliente(); + origemCliente.set_Cliente(this.SelectedCliente); + origemCliente.set_Nome(name); + origemCliente.set_TipoOrigem((long)1); + origens.Insert(0, origemCliente); + base.OnPropertyChanged("Origens"); + } + else + { + await base.ShowMessage(string.Concat("JÁ EXISTE UMA ORIGEM ", name, ". PROCESSO CANCELADO."), "OK", "", false); + } + } + } + + public void IncluirTelefone() + { + if (this.SelectedCliente == null) + { + return; + } + if (this.Telefones == null) + { + this.Telefones = new ObservableCollection(); + } + this.EnableAddTelephone = this.Telefones.Count < 9; + ClienteTelefone clienteTelefone = new ClienteTelefone(); + clienteTelefone.set_Cliente(this.SelectedCliente); + clienteTelefone.set_Tipo(new TipoTelefone?(1)); + clienteTelefone.set_Ordem(new int?(this.Telefones.Count + 1)); + this.Telefones.Add(clienteTelefone); + base.OnPropertyChanged("IncluirTelefone"); + } + + public bool IncluirVinculo() + { + if (this.Vinculo == null || this.Vinculo.get_Id() == this.SelectedCliente.get_Id()) + { + return false; + } + if (this.Vinculos == null) + { + this.Vinculos = new ObservableCollection(); + } + if (this.Vinculos.Any((ClienteVinculo x) => { + if (x.get_Cliente1().get_Id() == this.Vinculo.get_Id()) + { + return true; + } + return x.get_Cliente2().get_Id() == this.Vinculo.get_Id(); + })) + { + return false; + } + ClienteVinculo clienteVinculo = new ClienteVinculo(); + clienteVinculo.set_Cliente1(this.SelectedCliente); + clienteVinculo.set_Cliente2(this.Vinculo); + this.Vinculos.Add(clienteVinculo); + this.Vinculo = null; + base.OnPropertyChanged("IncluirVinculo"); + return true; + } + + public void JuridicaouFisica(string documento) + { + if (this.SelectedCliente == null) + { + return; + } + this.ProfissaoText = ""; + this.AtividadeText = ""; + if (documento != null && ValidationHelper.OnlyNumber(documento).Length <= 11) + { + this.VisibilityJuridica = Visibility.Collapsed; + this.VisibilityFisica = Visibility.Visible; + this.FieldNascimento = "NASCIMENTO"; + this.FieldDocumento = "CPF"; + this.SelectedCliente.set_Atividade(null); + this.IsJuridica = false; + return; + } + this.VisibilityJuridica = Visibility.Visible; + this.VisibilityFisica = Visibility.Collapsed; + this.FieldNascimento = "FUNDAÇÃO"; + this.FieldDocumento = "CNPJ"; + this.SelectedCliente.set_Profissao(null); + this.IsJuridica = true; + } + + public async Task>> Salvar() + { + List> keyValuePairs; + long num; + long? nullable; + List list; + List clienteVinculos; + ObservableCollection observableCollection; + ObservableCollection observableCollection1; + List origemClientes; + bool id; + bool salvando; + long? nullable1; + long? nullable2; + ClienteViewModel.u003cu003ec__DisplayClass146_0 variable; + Cliente selectedCliente; + Func func = null; + ObservableCollection telefones = this.Telefones; + List clienteTelefones = ( + from x in telefones + where !string.IsNullOrEmpty(x.get_Numero()) + select x).ToList(); + ObservableCollection enderecos = this.Enderecos; + List clienteEnderecos = ( + from x in enderecos + where !string.IsNullOrEmpty(x.get_Endereco()) + select x).ToList(); + ObservableCollection contatos = this.Contatos; + if (contatos != null) + { + list = ( + from x in contatos + where !string.IsNullOrEmpty(x.get_Nome()) + select x).ToList(); + } + else + { + list = null; + } + List maisContatos = list; + ObservableCollection emails = this.Emails; + List clienteEmails = ( + from x in emails + where !string.IsNullOrEmpty(x.get_Email()) + select x).ToList(); + ObservableCollection vinculos = this.Vinculos; + if (vinculos != null) + { + clienteVinculos = vinculos.Where((ClienteVinculo x) => { + if (x.get_Cliente2() == null) + { + return false; + } + return x.get_Parentesco().HasValue; + }).ToList(); + } + else + { + clienteVinculos = null; + } + List clienteVinculos1 = clienteVinculos; + if (clienteVinculos1 != null && this.ClienteSelecionado != null) + { + List clienteVinculos2 = clienteVinculos1; + Func func1 = func; + if (func1 == null) + { + Func id1 = (ClienteVinculo c) => c.get_Cliente2().get_Id() == this.ClienteSelecionado.get_Id(); + Func func2 = id1; + func = id1; + func1 = func2; + } + foreach (ClienteVinculo clienteVinculo in clienteVinculos2.Where(func1)) + { + clienteVinculo.set_Parentesco(Funcoes.ParentescoInverso(clienteVinculo.get_Parentesco())); + } + } + this.SelectedCliente.set_Telefones(new ObservableCollection(clienteTelefones)); + this.SelectedCliente.set_Enderecos(new ObservableCollection(clienteEnderecos)); + Cliente cliente = this.SelectedCliente; + if (maisContatos != null) + { + observableCollection = new ObservableCollection(maisContatos); + } + else + { + observableCollection = null; + } + cliente.set_Contatos(observableCollection); + this.SelectedCliente.set_Emails(new ObservableCollection(clienteEmails)); + Cliente selectedCliente1 = this.SelectedCliente; + if (clienteVinculos1 != null) + { + observableCollection1 = new ObservableCollection(clienteVinculos1); + } + else + { + observableCollection1 = null; + } + selectedCliente1.set_Vinculos(observableCollection1); + Cliente cliente1 = this.SelectedCliente; + ObservableCollection origens = this.Origens; + if (origens != null) + { + origemClientes = origens.ToList(); + } + else + { + origemClientes = null; + } + cliente1.set_Origens(origemClientes); + if (ValidationHelper.OnlyNumber(this.SelectedCliente.get_Documento()).Length <= 11 && !string.IsNullOrWhiteSpace(this.ProfissaoText) && this.SelectedCliente.get_Profissao() == null) + { + ProfissaoServico profissaoServico = new ProfissaoServico(); + selectedCliente = this.SelectedCliente; + ProfissaoServico profissaoServico1 = profissaoServico; + Profissao profissao = new Profissao(); + profissao.set_Nome(this.ProfissaoText); + profissao.set_Codigo("0"); + Profissao profissao1 = profissao; + num = await profissaoServico.FindLastId(); + profissao1.set_Id(num + (long)1); + Profissao profissao2 = await profissaoServico1.Save(profissao); + profissaoServico1 = null; + profissao1 = null; + profissao = null; + selectedCliente.set_Profissao(profissao2); + selectedCliente = null; + if (profissaoServico.Sucesso) + { + profissaoServico = null; + } + else + { + keyValuePairs = null; + variable = null; + clienteEmails = null; + return keyValuePairs; + } + } + if (ValidationHelper.OnlyNumber(this.SelectedCliente.get_Documento()).Length > 11 && !string.IsNullOrWhiteSpace(this.AtividadeText) && this.SelectedCliente.get_Atividade() == null) + { + AtividadeServico atividadeServico = new AtividadeServico(); + selectedCliente = this.SelectedCliente; + AtividadeServico atividadeServico1 = atividadeServico; + Atividade atividade = new Atividade(); + atividade.set_Nome(this.AtividadeText); + atividade.set_Cnac("0"); + Atividade atividade1 = atividade; + num = await atividadeServico.FindLastId(); + atividade1.set_Id(num + (long)1); + Atividade atividade2 = await atividadeServico1.Save(atividade); + atividadeServico1 = null; + atividade1 = null; + atividade = null; + selectedCliente.set_Atividade(atividade2); + selectedCliente = null; + if (atividadeServico.Sucesso) + { + atividadeServico = null; + } + else + { + keyValuePairs = null; + variable = null; + clienteEmails = null; + return keyValuePairs; + } + } + if (this.IsJuridica) + { + this.SelectedCliente.set_Cei(null); + this.SelectedCliente.set_Rne(null); + this.SelectedCliente.set_Caepf(null); + } + List> keyValuePairs1 = this.SelectedCliente.Validate(); + clienteEmails.ForEach((ClienteEmail x) => keyValuePairs1.AddRange(x.Validate())); + List> keyValuePairs2 = keyValuePairs1; + keyValuePairs2.AddRange(await this.Validate()); + keyValuePairs2 = null; + foreach (MaisContato contato in this.Contatos) + { + keyValuePairs1.AddRange(contato.Validate()); + } + foreach (ClienteVinculo vinculo in this.Vinculos) + { + keyValuePairs1.AddRange(vinculo.Validate()); + } + if (keyValuePairs1.Count <= 0) + { + bool flag = this.SelectedCliente.get_Id() == (long)0; + this._saving = true; + Cliente clienteSelecionado = this.ClienteSelecionado; + if (clienteSelecionado != null) + { + id = clienteSelecionado.get_Id() != (long)0; + } + else + { + id = true; + } + if (id) + { + Cliente clienteSelecionado1 = this.ClienteSelecionado; + if (clienteSelecionado1 != null) + { + nullable1 = new long?(clienteSelecionado1.get_Id()); + } + else + { + nullable = null; + nullable1 = nullable; + } + long? nullable3 = nullable1; + Cliente selectedCliente2 = this.SelectedCliente; + if (selectedCliente2 != null) + { + nullable2 = new long?(selectedCliente2.get_Id()); + } + else + { + nullable = null; + nullable2 = nullable; + } + long? nullable4 = nullable2; + if (nullable3.GetValueOrDefault() != nullable4.GetValueOrDefault() | nullable3.HasValue != nullable4.HasValue) + { + goto Label2; + } + salvando = this.Salvando; + goto Label1; + } + Label2: + salvando = false; + Label1: + bool flag1 = salvando; + if (flag1) + { + flag1 = await base.ShowMessage("NÃO FOI POSSIVEL INCLUIR UM NOVO SEGURADO, TENTE NOVAMENTE", "OK", "", false); + } + if (!flag1) + { + this.SelectedCliente = await this._servico.Save(this.SelectedCliente, this.Salvando); + if (this._servico.Sucesso) + { + if (this.Invoke) + { + Action selectCliente = Gestor.Application.Actions.Actions.SelectCliente; + if (selectCliente != null) + { + selectCliente(this.SelectedCliente); + } + else + { + } + } + await this.CarregaCliente(this.SelectedCliente); + string str = (flag ? "INCLUIU" : "ALTEROU"); + base.RegistrarAcao(string.Concat(str, " CLIENTE \"", this.SelectedCliente.get_Nome(), "\""), this.SelectedCliente.get_Id(), new TipoTela?(1), string.Format("CLIENTE \"{0}\", ID: {1}", this.SelectedCliente.get_Nome(), this.SelectedCliente.get_Id())); + base.ToggleSnackBar("CLIENTE SALVO COM SUCESSO", true); + if (this.Invoke) + { + ConsultaViewModel.DocumentoSelecionado = null; + Action atualizaContatos = Gestor.Application.Actions.Actions.AtualizaContatos; + if (atualizaContatos != null) + { + atualizaContatos(); + } + else + { + } + if (flag) + { + MainViewModel.ClienteSelecionado = this.SelectedCliente; + if (await base.ShowMessage("DESEJA INCLUIR UMA APÓLICE AGORA?", "SIM", "NÃO", false)) + { + Action acessaTela = Gestor.Application.Actions.Actions.AcessaTela; + if (acessaTela != null) + { + acessaTela(2, ""); + } + else + { + } + } + } + } + this.Salvando = false; + base.Alterar(false); + this._saving = false; + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + variable = null; + clienteEmails = null; + return keyValuePairs; + } + + public async void SelecionaCliente(Cliente value) + { + if (!this._saving || !this.Invoke) + { + if (value == null) + { + this.ClienteSelecionado = new Cliente(); + value = this.ClienteSelecionado; + } + base.Loading(true); + await base.PermissaoTela(1); + await this.CarregaCliente(value); + base.Loading(false); + } + } + + public async Task Validate(ClienteEmail item) + { + bool flag; + if (!ValidationHelper.ValidateMail(item.get_Email())) + { + await base.ShowMessage("ENDEREÇO DE E-MAIL INVÁLIDO", "OK", "", false); + flag = false; + } + else + { + flag = true; + } + return flag; + } + + private async Task>> Validate() + { + List clientes; + long id; + List> keyValuePairs = new List>(); + bool flag = !string.IsNullOrEmpty(this.SelectedCliente.get_Nome()); + TipoDocumento? documentoPrincipal = this.SelectedCliente.get_DocumentoPrincipal(); + if (documentoPrincipal.HasValue) + { + switch (documentoPrincipal.GetValueOrDefault()) + { + case 0: + { + if (ValidationHelper.ValidateDocument(this.SelectedCliente.get_Documento())) + { + break; + } + flag = false; + break; + } + case 1: + { + if (ValidationHelper.ValidateRne(this.SelectedCliente.get_Rne())) + { + break; + } + flag = false; + break; + } + case 2: + { + if (ValidationHelper.ValidateCei(this.SelectedCliente.get_Cei())) + { + break; + } + flag = false; + break; + } + case 3: + { + if (ValidationHelper.ValidateCaepf(this.SelectedCliente.get_Caepf())) + { + break; + } + flag = false; + break; + } + } + } + if (ValidationHelper.ValidateDocument(this.SelectedCliente.get_Documento())) + { + documentoPrincipal = this.SelectedCliente.get_DocumentoPrincipal(); + if (documentoPrincipal.GetValueOrDefault() == 0 & documentoPrincipal.HasValue) + { + this.SelectedCliente.set_Documento(ValidationHelper.FormatDocument(this.SelectedCliente.get_Documento())); + } + } + if (!ValidationHelper.ValidateDocument(this.SelectedCliente.get_Documento())) + { + clientes = new List(); + } + else + { + clientes = await (new ClienteServico()).BuscarCliente(this.SelectedCliente.get_Documento(), null, 2); + } + List clientes1 = clientes; + if (!this.IsJuridica) + { + if (!ValidationHelper.ValidateCei(this.SelectedCliente.get_Cei())) + { + clientes = new List(); + } + else + { + clientes = await (new ClienteServico()).BuscarCliente(this.SelectedCliente.get_Cei(), null, 2); + } + List clientes2 = clientes; + if (!ValidationHelper.ValidateRne(this.SelectedCliente.get_Rne())) + { + clientes = new List(); + } + else + { + clientes = await (new ClienteServico()).BuscarCliente(this.SelectedCliente.get_Rne(), null, 2); + } + List clientes3 = clientes; + if (!ValidationHelper.ValidateCaepf(this.SelectedCliente.get_Caepf())) + { + clientes = new List(); + } + else + { + clientes = await (new ClienteServico()).BuscarCliente(this.SelectedCliente.get_Caepf(), null, 2); + } + List clientes4 = clientes; + List clientes5 = clientes1; + List clientes6 = clientes2; + if (clientes6 == null) + { + clientes6 = new List(); + } + clientes5.AddRange(clientes6); + List clientes7 = clientes1; + List clientes8 = clientes3; + if (clientes8 == null) + { + clientes8 = new List(); + } + clientes7.AddRange(clientes8); + List clientes9 = clientes1; + List clientes10 = clientes4; + if (clientes10 == null) + { + clientes10 = new List(); + } + clientes9.AddRange(clientes10); + clientes2 = null; + clientes3 = null; + } + string nome = ""; + string str = ""; + if (clientes1.Count > 0) + { + clientes1.ForEach((Cliente x) => { + if (x.get_Id() == this.SelectedCliente.get_Id()) + { + return; + } + if (x.get_IdEmpresa() != this.SelectedCliente.get_IdEmpresa()) + { + return; + } + if (!string.IsNullOrEmpty(this.SelectedCliente.get_Documento()) && x.get_Documento() == this.SelectedCliente.get_Documento()) + { + flag = false; + nome = x.get_Nome(); + } + if (!string.IsNullOrEmpty(this.SelectedCliente.get_Cei()) && x.get_Cei() == this.SelectedCliente.get_Cei()) + { + str = " (CEI)"; + flag = false; + nome = x.get_Nome(); + } + if (!string.IsNullOrEmpty(this.SelectedCliente.get_Rne()) && x.get_Rne() == this.SelectedCliente.get_Rne()) + { + str = " (RNE)"; + flag = false; + nome = x.get_Nome(); + } + if (!string.IsNullOrEmpty(this.SelectedCliente.get_Caepf()) && x.get_Caepf() == this.SelectedCliente.get_Caepf()) + { + str = " (CAEPF)"; + flag = false; + nome = x.get_Nome(); + } + }); + } + if (!flag && clientes1.Count((Cliente x) => x.get_Id() != this.SelectedCliente.get_Id()) > 0) + { + if (await (new VendedorUsuarioServico()).FindVinculoByUsuario(Recursos.Usuario.get_Id())) + { + Cliente cliente = clientes1.FirstOrDefault(); + if (cliente != null) + { + id = cliente.get_Id(); + } + else + { + id = (long)0; + } + List vendedors = await (new VendedorServico()).BuscarVinculosCliente(id); + string str1 = string.Join("|", + from vendedor in vendedors + select vendedor.get_Nome()); + List> keyValuePairs1 = keyValuePairs; + string[] strArrays = new string[] { "O DOCUMENTO", str, " JÁ ESTÁ CADASTRADO PARA O CLIENTE ", nome, ".\nEXISTENTE NO VINCULO COM VENDEDORES: ", str1, " " }; + keyValuePairs1.Add(new KeyValuePair("Documento", string.Concat(strArrays))); + } + else + { + keyValuePairs.Add(new KeyValuePair("Documento", string.Concat("O DOCUMENTO", str, " JÁ ESTÁ CADASTRADO PARA O CLIENTE ", nome))); + } + } + if (this.SelectedCliente.get_Telefones() == null || this.SelectedCliente.get_Telefones().Count == 0) + { + keyValuePairs.Add(new KeyValuePair("Telefones", "NECESSITA-SE AO MENOS UM TELEFONE VÁLIDO.")); + } + List configuracoes = Recursos.Configuracoes; + if (configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 29) && (this.SelectedCliente.get_Emails() == null || this.SelectedCliente.get_Emails().Count == 0)) + { + keyValuePairs.Add(new KeyValuePair("Emails|E-MAILS", "NECESSITA-SE AO MENOS UM E-MAIL VÁLIDO.")); + } + if (this.SelectedCliente.get_Enderecos() == null || this.SelectedCliente.get_Enderecos().Count == 0) + { + keyValuePairs.Add(new KeyValuePair("Enderecos|ENDEREÇOS", "NECESSITA-SE AO MENOS UM ENDEREÇO VÁLIDO.")); + } + List> keyValuePairs2 = keyValuePairs; + keyValuePairs = null; + clientes1 = null; + return keyValuePairs2; + } + + private async void WorkOnSelectedCliente(Cliente value) + { + DateTime networkTime; + DateTime? nullable; + DateTime? primeiraHabilitacao; + DateTime? vencimentoHabilitacao; + DateTime? expedicao; + Cliente cliente; + if (value != null && value.get_Id() != 0 && !this.IsLoading) + { + base.Loading(true); + cliente = await this._servico.BuscarCliente(value.get_Id()); + if (cliente.get_ResponsavelAssinatura() == null) + { + Cliente cliente1 = cliente; + ResponsavelAssinatura responsavelAssinatura = new ResponsavelAssinatura(); + responsavelAssinatura.set_IdCliente(cliente.get_Id()); + cliente1.set_ResponsavelAssinatura(responsavelAssinatura); + } + Cliente cliente2 = cliente; + ObservableCollection observableCollection = await this._servico.BuscarTelefonesAsync(value.get_Id()); + cliente2.set_Telefones(observableCollection); + cliente2 = null; + cliente2 = cliente; + ObservableCollection observableCollection1 = await this._servico.BuscarEmailsAsync(value.get_Id()); + cliente2.set_Emails(observableCollection1); + cliente2 = null; + cliente2 = cliente; + ObservableCollection observableCollection2 = await this._servico.BuscarEnderecosAsync(value.get_Id()); + cliente2.set_Enderecos(observableCollection2); + cliente2 = null; + cliente2 = cliente; + ObservableCollection observableCollection3 = await this._servico.BuscarContatosAsync(value.get_Id()); + cliente2.set_Contatos(observableCollection3); + cliente2 = null; + cliente2 = cliente; + ObservableCollection observableCollection4 = await this._servico.BuscarVinculosAsync(value.get_Id()); + cliente2.set_Vinculos(observableCollection4); + cliente2 = null; + this.Origens = await this._servico.BuscarOrigens(value.get_Id()); + Cliente cliente3 = cliente; + TipoDocumento? documentoPrincipal = cliente.get_DocumentoPrincipal(); + cliente3.set_DocumentoPrincipal(new TipoDocumento?(documentoPrincipal.GetValueOrDefault())); + this.ClienteExcluido = cliente.get_Excluido(); + if (this.SelectedCliente != null) + { + DomainBase.Copy(this.SelectedCliente, cliente); + this.JuridicaouFisica(this.SelectedCliente.get_Documento()); + this.SelectedCliente.Initialize(); + this.ClienteSelecionado = cliente; + } + ClienteViewModel clienteViewModel = this; + if (value == null || !value.get_Nascimento().HasValue) + { + networkTime = Funcoes.GetNetworkTime(); + nullable = new DateTime?(networkTime.Date); + } + else + { + nullable = value.get_Nascimento(); + } + clienteViewModel.NascimentoCliente = nullable; + ClienteViewModel clienteViewModel1 = this; + if (value == null || !value.get_PrimeiraHabilitacao().HasValue) + { + networkTime = Funcoes.GetNetworkTime(); + primeiraHabilitacao = new DateTime?(networkTime.Date); + } + else + { + primeiraHabilitacao = value.get_PrimeiraHabilitacao(); + } + clienteViewModel1.HabilitaCliente = primeiraHabilitacao; + ClienteViewModel clienteViewModel2 = this; + if (value == null || !value.get_VencimentoHabilitacao().HasValue) + { + networkTime = Funcoes.GetNetworkTime(); + vencimentoHabilitacao = new DateTime?(networkTime.Date); + } + else + { + vencimentoHabilitacao = value.get_VencimentoHabilitacao(); + } + clienteViewModel2.VencimentoHabCliente = vencimentoHabilitacao; + ClienteViewModel clienteViewModel3 = this; + if (value == null || !value.get_Expedicao().HasValue) + { + networkTime = Funcoes.GetNetworkTime(); + expedicao = new DateTime?(networkTime.Date); + } + else + { + expedicao = value.get_Expedicao(); + } + clienteViewModel3.ExpedicaoCliente = expedicao; + this.Initialized = true; + base.Loading(false); + } + cliente = null; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Seguros/ConsultaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Seguros/ConsultaViewModel.cs new file mode 100644 index 0000000..ad65045 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Seguros/ConsultaViewModel.cs @@ -0,0 +1,2425 @@ +using Assinador.Infrastructure.Helpers; +using ClosedXML.Excel; +using Gestor.Application.Actions; +using Gestor.Application.Helpers; +using Gestor.Application.Model; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Forms; +using System.Windows.Threading; + +namespace Gestor.Application.ViewModels.Seguros +{ + public class ConsultaViewModel : BaseSegurosViewModel + { + private readonly ApoliceServico _apoliceServico; + + private readonly ParcelaServico _parcelaServico; + + private readonly ItemServico _itemServico; + + private readonly VendedorServico _vendedorServico; + + public bool UpdatingScroll; + + public static Parcela ParcelaSelecionada; + + public static Item ItemSelecionado; + + private static Documento _documentoSelecionado; + + private bool _apelido; + + private Visibility _semDocumentos = Visibility.Collapsed; + + private Cliente _selectedCliente = new Cliente(); + + private bool _carregando; + + private bool _isLoading; + + private Visibility _visibilityParcelasVendedores; + + private ObservableCollection _apolices = new ObservableCollection(); + + private ObservableCollection _endossos = new ObservableCollection(); + + private Documento _selectedEndosso = new Documento(); + + private string _parcelasLabel = "PARCELAS"; + + private Documento _selectedControle = new Documento(); + + private bool _isFatura; + + private bool _isEnabledParcelaItem = true; + + private Item _selectedItem = new Item(); + + private ObservableCollection _itens = new ObservableCollection(); + + private Parcela _selectedParcela = new Parcela(); + + private ObservableCollection _parcelas = new ObservableCollection(); + + private Visibility _isVisibleRadioEndosso = Visibility.Collapsed; + + private Visibility _isVisibleEndosso = Visibility.Collapsed; + + private Visibility _isVisibleApolice; + + private string _pendenciaApolice = ""; + + private Visibility _isVisiblePendenciaApolice = Visibility.Collapsed; + + private decimal _gerada; + + private decimal _recebida; + + private decimal _pendente; + + private bool _isLoadingParcelas = true; + + private bool _isLoadingItens = true; + + private int _filterItens; + + private int _filterDocumento; + + private Visibility _manutencaoItemVisibility; + + private Visibility _recusaVisibility; + + private Visibility _renovarVisibility; + + private Visibility _endossarVisibility; + + private Visibility _trocarClienteVisibility; + + private Visibility _tarefasVisibility; + + private Visibility _comissaoVisibility; + + private Visibility _comissaoValorVisibility; + + private Visibility _mostrarItensVisibility = Visibility.Collapsed; + + private Visibility _mostrarSinistroVisibility; + + private ObservableCollection _telefones = new ObservableCollection(); + + public bool Apelido + { + get + { + return this._apelido; + } + set + { + this._apelido = value; + base.OnPropertyChanged("Apelido"); + } + } + + public ObservableCollection Apolices + { + get + { + return this._apolices; + } + set + { + this._apolices = value; + base.OnPropertyChanged("Apolices"); + } + } + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + this.SemDocumentos = (value || this.Apolices != null && this.Apolices.Count != 0 ? Visibility.Collapsed : Visibility.Visible); + } + } + + public Visibility ComissaoValorVisibility + { + get + { + return this._comissaoValorVisibility; + } + set + { + this._comissaoValorVisibility = (!base.Restricao(14) ? value : Visibility.Collapsed); + base.OnPropertyChanged("ComissaoValorVisibility"); + } + } + + public Visibility ComissaoVisibility + { + get + { + return this._comissaoVisibility; + } + set + { + this._comissaoVisibility = (!base.Restricao(95) ? value : Visibility.Collapsed); + base.OnPropertyChanged("ComissaoVisibility"); + } + } + + public static Documento DocumentoRenovado + { + get; + set; + } + + public static Documento DocumentoSelecionado + { + get + { + return ConsultaViewModel._documentoSelecionado; + } + set + { + ConsultaViewModel._documentoSelecionado = value; + Action enableItens = Gestor.Application.Actions.Actions.EnableItens; + if (enableItens != null) + { + enableItens((value == null ? false : value.get_Id() > (long)0)); + } + else + { + } + Action enableDocumento = Gestor.Application.Actions.Actions.EnableDocumento; + if (enableDocumento == null) + { + return; + } + enableDocumento((value == null ? false : value.get_Id() > (long)0)); + } + } + + public Visibility EndossarVisibility + { + get + { + return this._endossarVisibility; + } + set + { + this._endossarVisibility = (!base.Restricao(33) ? value : Visibility.Collapsed); + base.OnPropertyChanged("EndossarVisibility"); + } + } + + public ObservableCollection Endossos + { + get + { + return this._endossos; + } + set + { + this._endossos = value; + base.OnPropertyChanged("Endossos"); + } + } + + public int FilterDocumento + { + get + { + return this._filterDocumento; + } + set + { + this._filterDocumento = value; + Action updateRadioApolice = Gestor.Application.Actions.Actions.UpdateRadioApolice; + if (updateRadioApolice != null) + { + updateRadioApolice(this._filterDocumento); + } + else + { + } + base.OnPropertyChanged("FilterDocumento"); + } + } + + public int FilterItens + { + get + { + return this._filterItens; + } + set + { + this._filterItens = value; + ConsultaViewModel.FiltrarItens = value; + base.OnPropertyChanged("FilterItens"); + } + } + + public static int FiltrarItens + { + get; + set; + } + + public decimal Gerada + { + get + { + return this._gerada; + } + set + { + this._gerada = value; + base.OnPropertyChanged("Gerada"); + } + } + + public bool IsEnabledParcelaItem + { + get + { + return this._isEnabledParcelaItem; + } + set + { + this._isEnabledParcelaItem = value; + base.OnPropertyChanged("IsEnabledParcelaItem"); + } + } + + public bool IsFatura + { + get + { + return this._isFatura; + } + set + { + if (!value) + { + value = this.ComissaoValorVisibility == Visibility.Collapsed; + } + this._isFatura = value; + base.OnPropertyChanged("IsFatura"); + } + } + + public bool IsLoading + { + get + { + return this._isLoading; + } + set + { + this._isLoading = value; + base.OnPropertyChanged("IsLoading"); + } + } + + public bool IsLoadingItens + { + get + { + return this._isLoadingItens; + } + set + { + this._isLoadingItens = value; + base.OnPropertyChanged("IsLoadingItens"); + } + } + + public bool IsLoadingParcelas + { + get + { + return this._isLoadingParcelas; + } + set + { + this._isLoadingParcelas = value; + base.OnPropertyChanged("IsLoadingParcelas"); + } + } + + public Visibility IsVisibleApolice + { + get + { + return this._isVisibleApolice; + } + set + { + this._isVisibleApolice = value; + base.OnPropertyChanged("IsVisibleApolice"); + } + } + + public Visibility IsVisibleEndosso + { + get + { + return this._isVisibleEndosso; + } + set + { + this._isVisibleEndosso = value; + base.OnPropertyChanged("IsVisibleEndosso"); + } + } + + public Visibility IsVisiblePendenciaApolice + { + get + { + return this._isVisiblePendenciaApolice; + } + set + { + this._isVisiblePendenciaApolice = value; + base.OnPropertyChanged("IsVisiblePendenciaApolice"); + } + } + + public Visibility IsVisibleRadioEndosso + { + get + { + return this._isVisibleRadioEndosso; + } + set + { + this._isVisibleRadioEndosso = value; + base.OnPropertyChanged("IsVisibleRadioEndosso"); + } + } + + public ObservableCollection Itens + { + get + { + return this._itens; + } + set + { + this._itens = value; + base.OnPropertyChanged("Itens"); + } + } + + public bool ItensRevelados + { + get; + set; + } + + public Visibility ManutencaoItemVisibility + { + get + { + return this._manutencaoItemVisibility; + } + set + { + this._manutencaoItemVisibility = (!base.Restricao(22) ? value : Visibility.Collapsed); + base.OnPropertyChanged("ManutencaoItemVisibility"); + } + } + + public Visibility MostrarItensVisibility + { + get + { + return this._mostrarItensVisibility; + } + set + { + this._mostrarItensVisibility = value; + base.OnPropertyChanged("MostrarItensVisibility"); + } + } + + public Visibility MostrarSinistroVisibility + { + get + { + return this._mostrarSinistroVisibility; + } + set + { + this._mostrarSinistroVisibility = value; + base.OnPropertyChanged("MostrarSinistroVisibility"); + } + } + + public ObservableCollection Parcelas + { + get + { + return this._parcelas; + } + set + { + this._parcelas = value; + base.OnPropertyChanged("Parcelas"); + } + } + + public string ParcelasLabel + { + get + { + return this._parcelasLabel; + } + set + { + this._parcelasLabel = value; + base.OnPropertyChanged("ParcelasLabel"); + } + } + + public string PendenciaApolice + { + get + { + return this._pendenciaApolice; + } + set + { + this._pendenciaApolice = value; + this.IsVisiblePendenciaApolice = (string.IsNullOrEmpty(this._pendenciaApolice) ? Visibility.Collapsed : Visibility.Visible); + base.OnPropertyChanged("PendenciaApolice"); + } + } + + public decimal Pendente + { + get + { + return this._pendente; + } + set + { + this._pendente = value; + base.OnPropertyChanged("Pendente"); + } + } + + public bool Pesquisando + { + get; + set; + } + + public bool Recarregando + { + get; + set; + } + + public decimal Recebida + { + get + { + return this._recebida; + } + set + { + this._recebida = value; + base.OnPropertyChanged("Recebida"); + } + } + + public Visibility RecusaVisibility + { + get + { + return this._recusaVisibility; + } + set + { + this._recusaVisibility = (!base.Restricao(18) ? value : Visibility.Collapsed); + base.OnPropertyChanged("RecusaVisibility"); + } + } + + public Visibility RenovarVisibility + { + get + { + return this._renovarVisibility; + } + set + { + this._renovarVisibility = (!base.Restricao(17) ? value : Visibility.Collapsed); + base.OnPropertyChanged("RenovarVisibility"); + } + } + + public Cliente SelectedCliente + { + get + { + return this._selectedCliente; + } + set + { + this._selectedCliente = value; + base.OnPropertyChanged("SelectedCliente"); + } + } + + public Documento SelectedControle + { + get + { + return this._selectedControle; + } + set + { + bool id; + bool flag; + Visibility visibility; + string apolice; + this._selectedControle = value; + if (value == null || value.get_Id() <= (long)0) + { + id = false; + } + else + { + Usuario usuario = Recursos.Usuario; + if (usuario != null) + { + id = usuario.get_Id() > (long)0; + } + else + { + id = false; + } + } + base.EnableButtons = id; + bool flag1 = Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 13); + if (value == null || value.get_Id() <= (long)0) + { + flag = false; + } + else if (flag1) + { + flag = true; + } + else + { + flag = (string.IsNullOrWhiteSpace(value.get_Apolice()) || string.IsNullOrWhiteSpace(value.get_Proposta()) ? false : value.get_Emissao().HasValue); + } + base.EnableEndossar = flag; + base.EnableRenovar = (value == null || value.get_Id() <= (long)0 || !value.get_Vigencia2().HasValue ? false : !string.IsNullOrWhiteSpace(value.get_Apolice())); + this.WorkOnSelectedDocumento(value); + if (Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 19)) + { + if (value != null) + { + apolice = value.get_Apolice(); + } + else + { + apolice = null; + } + if (string.IsNullOrWhiteSpace(apolice) || !value.get_Emissao().HasValue) + { + visibility = Visibility.Visible; + this.RecusaVisibility = visibility; + this.ItensRevelados = false; + this.MostrarItensVisibility = Visibility.Collapsed; + this.MostrarSinistroVisibility = Visibility.Visible; + base.OnPropertyChanged("SelectedControle"); + return; + } + visibility = Visibility.Collapsed; + this.RecusaVisibility = visibility; + this.ItensRevelados = false; + this.MostrarItensVisibility = Visibility.Collapsed; + this.MostrarSinistroVisibility = Visibility.Visible; + base.OnPropertyChanged("SelectedControle"); + return; + } + visibility = Visibility.Visible; + this.RecusaVisibility = visibility; + this.ItensRevelados = false; + this.MostrarItensVisibility = Visibility.Collapsed; + this.MostrarSinistroVisibility = Visibility.Visible; + base.OnPropertyChanged("SelectedControle"); + } + } + + public Documento SelectedEndosso + { + get + { + return this._selectedEndosso; + } + set + { + this._selectedEndosso = value; + this.WorkOnSelectedDocumento(value); + base.OnPropertyChanged("SelectedEndosso"); + } + } + + public Item SelectedItem + { + get + { + return this._selectedItem; + } + set + { + this._selectedItem = value; + ConsultaViewModel.WorkOnSelectedItem(value); + base.OnPropertyChanged("SelectedItem"); + } + } + + public Parcela SelectedParcela + { + get + { + return this._selectedParcela; + } + set + { + this._selectedParcela = value; + base.OnPropertyChanged("SelectedParcela"); + } + } + + public Visibility SemDocumentos + { + get + { + return this._semDocumentos; + } + set + { + this._semDocumentos = value; + base.OnPropertyChanged("SemDocumentos"); + } + } + + public Visibility TarefasVisibility + { + get + { + return this._tarefasVisibility; + } + set + { + this._tarefasVisibility = (base.Permissao(38) ? value : Visibility.Collapsed); + base.OnPropertyChanged("TarefasVisibility"); + } + } + + public ObservableCollection Telefones + { + get + { + return this._telefones; + } + set + { + this._telefones = value; + base.OnPropertyChanged("Telefones"); + } + } + + public Visibility TrocarClienteVisibility + { + get + { + return this._trocarClienteVisibility; + } + set + { + this._trocarClienteVisibility = (!base.Restricao(21) ? value : Visibility.Collapsed); + base.OnPropertyChanged("TrocarClienteVisibility"); + } + } + + public Visibility VisibilityParcelasVendedores + { + get + { + return this._visibilityParcelasVendedores; + } + set + { + this._visibilityParcelasVendedores = value; + base.OnPropertyChanged("VisibilityParcelasVendedores"); + } + } + + public ConsultaViewModel() + { + this._apoliceServico = new ApoliceServico(); + this._parcelaServico = new ParcelaServico(); + this._vendedorServico = new VendedorServico(); + this._itemServico = new ItemServico(); + this.Apelido = Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 6); + this.SemDocumentos = Visibility.Visible; + base.EnableButtons = false; + if (MainViewModel.ClienteSelecionado != null && MainViewModel.ClienteSelecionado.get_Id() > (long)0) + { + this.SelecionarCliente(MainViewModel.ClienteSelecionado); + } + } + + public async Task AbrirDetalhes() + { + Documento selectedControle = this.SelectedControle; + if (this.FilterDocumento == 1) + { + Documento selectedEndosso = this.SelectedEndosso; + if (selectedEndosso == null) + { + selectedEndosso = this.SelectedControle; + } + selectedControle = selectedEndosso; + } + Documento documento = selectedControle; + List vendedorParcelas = await this._vendedorServico.BuscaRepasse(selectedControle.get_Id()); + documento.set_Pagamentos(vendedorParcelas); + documento = null; + documento = selectedControle; + ObservableCollection observableCollection = await this._parcelaServico.BuscarParcelasAsync(selectedControle.get_Id()); + documento.set_Parcelas(observableCollection); + documento = null; + Documento documento1 = selectedControle; + selectedControle = null; + return documento1; + } + + public async Task AbrirDetalhesParcela() + { + Parcela selectedParcela = this.SelectedParcela; + List vendedorParcelas = await this._vendedorServico.BuscaRepasseParcela(selectedParcela.get_Id()); + selectedParcela.set_Vendedores(new ObservableCollection(vendedorParcelas)); + Parcela parcela = selectedParcela; + selectedParcela = null; + return parcela; + } + + private void CalculaComissao(Documento documento, ObservableCollection parcelas) + { + decimal num = (documento.get_AdicionalComiss() ? documento.get_PremioLiquido() + documento.get_PremioAdicional() : documento.get_PremioLiquido()); + decimal comissao = documento.get_Comissao() * new decimal(1, 0, 0, false, 2); + this.Gerada = num * comissao; + this.Recebida = (Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 32) ? parcelas.Where((Parcela x) => { + if (x.get_SubTipo() == 1) + { + return true; + } + return x.get_SubTipo() == 6; + }).Sum((Parcela x) => x.get_ValorComissao()) : ( + from x in parcelas + where x.get_SubTipo() == 1 + select x).Sum((Parcela x) => x.get_ValorComissao())); + this.Pendente = this.Gerada - this.Recebida; + this.Pendente = (this.Pendente < new decimal(1, 0, 0, false, 2) ? new decimal(0, 0, 0, false, 2) : this.Pendente); + } + + public void CarregaDocumentos(int type) + { + this.IsVisibleApolice = Visibility.Collapsed; + this.IsVisibleEndosso = Visibility.Collapsed; + if (type != 1) + { + this.IsVisibleApolice = Visibility.Visible; + return; + } + this.IsVisibleEndosso = Visibility.Visible; + } + + public async Task CarregaItens(int type, Documento documento) + { + this.FilterItens = 0; + switch (type) + { + case 0: + { + this.Itens = await this._itemServico.BuscarItens(documento.get_Controle().get_Id(), 0); + break; + } + case 1: + { + this.FilterItens = 1; + this.Itens = await this._itemServico.BuscarItens(documento.get_Id(), 2); + break; + } + case 2: + { + this.FilterItens = 2; + Documento selectedEndosso = this.SelectedEndosso; + if (selectedEndosso == null) + { + selectedEndosso = documento; + } + documento = selectedEndosso; + this.Itens = await this._itemServico.BuscarItens(documento.get_Id(), 2); + break; + } + case 3: + { + this.FilterItens = 3; + this.Itens = await this._itemServico.BuscarItens(documento.get_Controle().get_Id(), 1); + break; + } + } + } + + private void Clear() + { + this.Apolices = null; + this.Parcelas = null; + this.Itens = null; + } + + public async Task CreateLink(Documento documento) + { + string str; + string descricao; + if (documento == null || this.SelectedCliente == null) + { + str = ""; + } + else + { + this.Telefones = new ObservableCollection((IEnumerable)await (new ClienteServico()).BuscarTelefonesAsync(this.SelectedCliente.get_Id())); + if (this.Itens == null) + { + descricao = ""; + } + else if (this.Itens.Count > 1) + { + descricao = "APÓLICE COLETIVA"; + } + else + { + Item item = this.Itens.FirstOrDefault(); + if (item != null) + { + descricao = item.get_Descricao(); + } + else + { + descricao = null; + } + } + str = await base.CreateLinkAssistencia(documento, descricao, true); + } + return str; + } + + public async Task EditarParcelas() + { + await base.ShowEditarParcelasDialog(ConsultaViewModel.DocumentoSelecionado); + await this.SelecionaParcelas(ConsultaViewModel.DocumentoSelecionado); + } + + public async Task GerarExcel(int type) + { + ObservableCollection observableCollection; + string str1; + ConsultaViewModel.u003cu003ec__DisplayClass212_0 variable; + string str2; + string str3; + if (this.SelectedControle != null) + { + base.Loading(true); + bool typeFromProgID = Type.GetTypeFromProgID("Excel.Application") != null; + str2 = "ATIVOS"; + switch (type) + { + case 1: + { + str2 = "DA APÓLICE"; + observableCollection = await this._itemServico.BuscarItems(this.SelectedControle.get_Id(), 2, true); + break; + } + case 2: + { + Documento selectedEndosso = this.SelectedEndosso; + if (selectedEndosso == null) + { + selectedEndosso = this.SelectedControle; + } + Documento documento = selectedEndosso; + str2 = (this.SelectedEndosso == null ? "DA APÓLICE" : "DO ENDOSSO"); + observableCollection = await this._itemServico.BuscarItems(documento.get_Id(), 2, true); + break; + } + case 3: + { + str2 = "INATIVOS"; + observableCollection = await this._itemServico.BuscarItems(this.SelectedControle.get_Controle().get_Id(), 1, true); + break; + } + default: + { + observableCollection = await this._itemServico.BuscarItems(this.SelectedControle.get_Controle().get_Id(), 0, true); + break; + } + } + if (observableCollection == null || observableCollection.Count == 0) + { + base.Loading(false); + await base.ShowMessage("NÃO HÁ ITENS PARA EXIBIR A RELAÇÃO", "OK", "", false); + } + else + { + List relacaoItens = new List(); + observableCollection.ToList().ForEach((Item x) => { + DateTime? nullable; + StatusSinistro? nullable1; + decimal? nullable2; + DateTime? dataSinistro; + string numero; + StatusSinistro? statusSinistro; + string itemSinistrado; + decimal? nullable3; + DateTime? dataLiquidacao; + DateTime? dataReclamacao; + string motivo; + string descricao; + string str = ""; + if (x.get_Coberturas().Count() > 0) + { + x.get_Coberturas().ToList().ForEach((Cobertura c) => str = string.Concat(str, string.Format("Cobertura: {0} | Premio: {1} | Franquia: {2} | LMI: {3}\n", new object[] { c.get_Observacao(), c.get_Premio(), c.get_Franquia(), c.get_Lmi() }))); + } + RelacaoItens relacaoIten = new RelacaoItens() + { + Nome = this.SelectedCliente.get_Nome(), + Documento = this.SelectedCliente.get_Documento(), + Apolice = this.SelectedControle.get_Apolice(), + VigenciaInicial = this.SelectedControle.get_Vigencia1(), + VigenciaFinal = this.SelectedControle.get_Vigencia2(), + Ordem = x.get_Ordem(), + Sinistrado = (x.get_Sinistrado() ? "SIM" : "NÃO") + }; + ControleSinistro controleSinistro = x.get_Sinistros().FirstOrDefault(); + if (controleSinistro != null) + { + dataSinistro = controleSinistro.get_DataSinistro(); + } + else + { + nullable = null; + dataSinistro = nullable; + } + relacaoIten.DataSinistro = dataSinistro; + ControleSinistro controleSinistro1 = x.get_Sinistros().FirstOrDefault(); + if (controleSinistro1 != null) + { + Sinistro sinistro = controleSinistro1.get_Sinistros().FirstOrDefault(); + if (sinistro != null) + { + numero = sinistro.get_Numero(); + } + else + { + numero = null; + } + } + else + { + numero = null; + } + relacaoIten.NumSinistro = numero; + ControleSinistro controleSinistro2 = x.get_Sinistros().FirstOrDefault(); + if (controleSinistro2 != null) + { + Sinistro sinistro1 = controleSinistro2.get_Sinistros().FirstOrDefault(); + if (sinistro1 != null) + { + statusSinistro = sinistro1.get_StatusSinistro(); + } + else + { + nullable1 = null; + statusSinistro = nullable1; + } + } + else + { + nullable1 = null; + statusSinistro = nullable1; + } + relacaoIten.StatusSinistro = statusSinistro; + ControleSinistro controleSinistro3 = x.get_Sinistros().FirstOrDefault(); + if (controleSinistro3 != null) + { + Sinistro sinistro2 = controleSinistro3.get_Sinistros().FirstOrDefault(); + if (sinistro2 != null) + { + itemSinistrado = sinistro2.get_ItemSinistrado(); + } + else + { + itemSinistrado = null; + } + } + else + { + itemSinistrado = null; + } + relacaoIten.ItemSinistrado = itemSinistrado; + ControleSinistro controleSinistro4 = x.get_Sinistros().FirstOrDefault(); + if (controleSinistro4 != null) + { + Sinistro sinistro3 = controleSinistro4.get_Sinistros().FirstOrDefault(); + if (sinistro3 != null) + { + nullable3 = new decimal?(sinistro3.get_Valor()); + } + else + { + nullable2 = null; + nullable3 = nullable2; + } + } + else + { + nullable2 = null; + nullable3 = nullable2; + } + relacaoIten.Valor = nullable3; + ControleSinistro controleSinistro5 = x.get_Sinistros().FirstOrDefault(); + if (controleSinistro5 != null) + { + Sinistro sinistro4 = controleSinistro5.get_Sinistros().FirstOrDefault(); + if (sinistro4 != null) + { + dataLiquidacao = sinistro4.get_DataLiquidacao(); + } + else + { + nullable = null; + dataLiquidacao = nullable; + } + } + else + { + nullable = null; + dataLiquidacao = nullable; + } + relacaoIten.DataLiq = dataLiquidacao; + ControleSinistro controleSinistro6 = x.get_Sinistros().FirstOrDefault(); + if (controleSinistro6 != null) + { + Sinistro sinistro5 = controleSinistro6.get_Sinistros().FirstOrDefault(); + if (sinistro5 != null) + { + dataReclamacao = sinistro5.get_DataReclamacao(); + } + else + { + nullable = null; + dataReclamacao = nullable; + } + } + else + { + nullable = null; + dataReclamacao = nullable; + } + relacaoIten.DataRec = dataReclamacao; + ControleSinistro controleSinistro7 = x.get_Sinistros().FirstOrDefault(); + if (controleSinistro7 != null) + { + Sinistro sinistro6 = controleSinistro7.get_Sinistros().FirstOrDefault(); + if (sinistro6 != null) + { + motivo = sinistro6.get_Motivo(); + } + else + { + motivo = null; + } + } + else + { + motivo = null; + } + relacaoIten.Motivo = motivo; + relacaoIten.Status = (string.IsNullOrEmpty(x.get_Status()) ? x.get_StatusInclusao() : x.get_Status()); + relacaoIten.Cobertura = (str.Length > 4000 ? str.Substring(0, 4000) : str); + RelacaoItens endereco = relacaoIten; + long id = this.SelectedControle.get_Controle().get_Ramo().get_Id(); + if (id > (long)5) + { + if (id == (long)18) + { + endereco.Endereco = x.get_Patrimonial().get_Endereco(); + endereco.Numero = x.get_Patrimonial().get_Numero(); + endereco.Bairro = x.get_Patrimonial().get_Bairro(); + endereco.Cidade = x.get_Patrimonial().get_Cidade(); + endereco.Estado = x.get_Patrimonial().get_Estado(); + endereco.Cep = x.get_Patrimonial().get_Cep(); + endereco.Complemento = x.get_Patrimonial().get_Complemento(); + endereco.Bens = x.get_Patrimonial().get_Bens(); + endereco.Descricao = x.get_Descricao(); + relacaoItens.Add(endereco); + return; + } + if (id == (long)37) + { + goto Label1; + } + } + else + { + if (id - (long)1 <= (long)2) + { + endereco.Endereco = x.get_Patrimonial().get_Endereco(); + endereco.Numero = x.get_Patrimonial().get_Numero(); + endereco.Bairro = x.get_Patrimonial().get_Bairro(); + endereco.Cidade = x.get_Patrimonial().get_Cidade(); + endereco.Estado = x.get_Patrimonial().get_Estado(); + endereco.Cep = x.get_Patrimonial().get_Cep(); + endereco.Complemento = x.get_Patrimonial().get_Complemento(); + endereco.Bens = x.get_Patrimonial().get_Bens(); + endereco.Descricao = x.get_Descricao(); + relacaoItens.Add(endereco); + return; + } + if (id == (long)5) + { + goto Label1; + } + } + endereco.Descricao = x.get_Descricao(); + relacaoItens.Add(endereco); + return; + Label1: + endereco.Fipe = x.get_Auto().get_Fipe(); + RelacaoItens relacaoIten1 = endereco; + Fabricante fabricante = x.get_Auto().get_Fabricante(); + if (fabricante != null) + { + descricao = fabricante.get_Descricao(); + } + else + { + descricao = null; + } + relacaoIten1.Fabricante = descricao; + endereco.Modelo = x.get_Auto().get_Modelo(); + endereco.AnoFab = x.get_Auto().get_AnoFabricacao(); + endereco.AnoMod = x.get_Auto().get_AnoModelo(); + endereco.Chassi = x.get_Auto().get_Chassi(); + endereco.Placa = x.get_Auto().get_Placa(); + endereco.RegiaoCirculacao = x.get_Auto().get_RegiaoCirculacao(); + endereco.Bonus = x.get_Auto().get_Bonus(); + endereco.Descricao = x.get_Descricao(); + relacaoItens.Add(endereco); + }); + string tempPath = ""; + str3 = ""; + List configuracoes = Recursos.Configuracoes; + if (!configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 41)) + { + tempPath = Path.GetTempPath(); + str3 = string.Format("{0}{1}.xlsx", tempPath, Guid.NewGuid()); + } + else + { + using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog()) + { + if (DialogResult.OK == folderBrowserDialog.ShowDialog()) + { + tempPath = string.Concat(folderBrowserDialog.SelectedPath, "\\"); + Directory.CreateDirectory(tempPath); + } + else + { + variable = null; + str2 = null; + str3 = null; + return; + } + } + object[] objArray = new object[] { tempPath, str2, this.SelectedControle.get_Apolice().Replace("/", ""), Guid.NewGuid() }; + str3 = string.Format("{0}ITENS - {1} {2} {3}.xlsx", objArray); + } + XLWorkbook xLWorkbook = new XLWorkbook(); + string apolice = this.SelectedControle.get_Apolice(); + if (apolice != null) + { + str1 = apolice.Replace("/", ""); + } + else + { + str1 = null; + } + await Funcoes.GerarXls(xLWorkbook, string.Concat("ITENS - ", str1), relacaoItens, null).SaveAs(str3); + if (!typeFromProgID) + { + await base.ShowMessage(string.Concat("ARQUIVO SALVO NO CAMINHO ", str3), "OK", "", false); + } + else + { + Process.Start(str3); + } + base.RegistrarAcao(string.Format("GEROU A RELAÇÃO DOS ITENS DO DOCUMENTO DE ID {0}", this.SelectedControle.get_Id()), this.SelectedControle.get_Id(), new TipoTela?(21), null); + base.Loading(false); + } + } + variable = null; + str2 = null; + str3 = null; + } + + public void ManutecaoItens() + { + Action acessaTela = Gestor.Application.Actions.Actions.AcessaTela; + if (acessaTela == null) + { + return; + } + acessaTela(3, "Manutencao"); + } + + public async Task MostrarItens(int type = 0) + { + bool count; + Item item; + this.IsLoadingItens = false; + this.MostrarItensVisibility = Visibility.Collapsed; + this.MostrarSinistroVisibility = Visibility.Visible; + this.ItensRevelados = true; + Documento documentoSelecionado = ConsultaViewModel.DocumentoSelecionado; + if (type == 1 && ConsultaViewModel.DocumentoSelecionado.get_Tipo() == 1) + { + documentoSelecionado = this.SelectedControle; + } + await this.CarregaItens(type, documentoSelecionado); + ObservableCollection itens = this.Itens; + if (itens != null) + { + count = itens.Count > 1; + } + else + { + count = false; + } + if (count) + { + ConsultaViewModel consultaViewModel = this; + ObservableCollection observableCollection = this.Itens; + if (observableCollection != null) + { + item = observableCollection.FirstOrDefault(); + } + else + { + item = null; + } + consultaViewModel.SelectedItem = item; + } + this.IsLoadingItens = true; + } + + public async Task Pesquisar(PesquisaAvancada pesquisa) + { + TimeSpan vigencia1; + string str; + Visibility visibility; + int num; + int num1; + string str1; + ConsultaViewModel.u003cu003ec__DisplayClass24_0 variable; + MainViewModel.StatusSelecionado = pesquisa.get_Status(); + if (pesquisa.get_IdDocumento() != 0) + { + this.Pesquisando = true; + await this.SelecionarCliente(pesquisa.get_IdCliente(), false); + base.Loading(true); + Documento documento = await this._apoliceServico.BuscarApoliceAsync(pesquisa.get_IdDocumento(), false, false); + Documento documento1 = documento; + if (documento1 == null || this.Apolices.Count == 0 || this.Apolices == null) + { + this.Pesquisando = false; + base.Loading(false); + } + else + { + Documento documento2 = this.Apolices.FirstOrDefault((Documento x) => x.get_Controle().get_Id() == documento1.get_Controle().get_Id()); + if (documento2 == null && documento1.get_Tipo() == 1) + { + documento2 = documento1; + documento2.set_TemEndosso(true); + if (documento2 == null) + { + this.Pesquisando = false; + base.Loading(false); + variable = null; + return; + } + } + this.SelectedControle = documento2; + this.IsVisibleApolice = Visibility.Visible; + this.VisibilityParcelasVendedores = Visibility.Collapsed; + DateTime date = Funcoes.GetNetworkTime().Date; + ConsultaViewModel consultaViewModel = this; + if (string.IsNullOrEmpty(documento2.get_Apolice())) + { + vigencia1 = date - documento2.get_Vigencia1(); + str = string.Format("{0} DIAS DE PENDÊNCIA", vigencia1.TotalDays); + } + else + { + str = ""; + } + consultaViewModel.PendenciaApolice = str; + ConsultaViewModel consultaViewModel1 = this; + visibility = (documento2.get_TemEndosso() ? Visibility.Visible : Visibility.Collapsed); + consultaViewModel1.IsVisibleRadioEndosso = visibility; + if (documento2.get_TemEndosso()) + { + this.IsVisibleRadioEndosso = Visibility.Visible; + ConsultaViewModel observableCollection = this; + IList documentos = documento2.get_Controle().get_Documentos(); + observableCollection.Endossos = new ObservableCollection(documentos.Where((Documento x) => { + if (x.get_Tipo() != 1) + { + return false; + } + return !x.get_Excluido(); + })); + } + if (documento1.get_Tipo() == 1) + { + documento1 = this.Endossos.First((Documento x) => x.get_Id() == documento1.get_Id()); + this.FilterDocumento = 1; + this.IsVisibleEndosso = Visibility.Visible; + this.SelectedEndosso = documento1; + ConsultaViewModel consultaViewModel2 = this; + if (string.IsNullOrEmpty(documento1.get_Endosso())) + { + vigencia1 = date - documento1.get_Vigencia1(); + str1 = string.Format("{0} DIAS DE PENDÊNCIA", vigencia1.TotalDays); + } + else + { + str1 = ""; + } + consultaViewModel2.PendenciaApolice = str1; + } + this.CarregaDocumentos(documento1.get_Tipo()); + await this.SelecionaParcelas(documento1); + this.VisibilityParcelasVendedores = Visibility.Visible; + this.Pesquisando = false; + if (pesquisa.get_IdItem() != 0) + { + ConsultaViewModel consultaViewModel3 = this; + num = (documento1.get_Tipo() == 0 ? 1 : 2); + await consultaViewModel3.SelecionaItens(num, documento1, pesquisa.get_IdItem(), true); + this.SelecionaItem(this.Itens.FirstOrDefault((Item x) => x.get_Id() == pesquisa.get_IdItem())); + base.Loading(false); + if (pesquisa.get_IdSinistro() != 0) + { + Action acessaTela = Gestor.Application.Actions.Actions.AcessaTela; + if (acessaTela != null) + { + acessaTela(7, ""); + } + else + { + } + } + } + else + { + ConsultaViewModel consultaViewModel4 = this; + num1 = (documento1.get_Tipo() == 0 ? 1 : 2); + await consultaViewModel4.SelecionaItens(num1, documento1, (long)0, false); + base.Loading(false); + } + } + } + else + { + await this.SelecionarCliente(pesquisa.get_IdCliente(), true); + } + variable = null; + } + + public async Task RecusarDocumento() + { + bool flag; + IList list; + string str; + Documento documento; + if (ConsultaViewModel.DocumentoSelecionado != null) + { + bool[] flagArray = await Funcoes.VerificarPagamento(ConsultaViewModel.DocumentoSelecionado.get_Id()); + List configuracoes = Recursos.Configuracoes; + if (configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 23)) + { + bool[] flagArray1 = flagArray; + if (((IEnumerable)flagArray1).Any((bool x) => x)) + { + await base.ShowMessage("NÃO É POSSÍVEL RECUSAR UMA APÓLICE ENQUANTO HOUVER RECEBIMENTO DE COMISSÃO OU PAGAMENTO DE VENDEDORES", "OK", "", false); + documento = null; + return; + } + } + List configuracaoSistemas = Recursos.Configuracoes; + flag = (!configuracaoSistemas.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 23) ? false : flagArray[1]); + bool flag1 = flag; + if (flag1) + { + flag1 = await base.ShowMessage("EXISTEM PAGAMENTOS PARA OS VENDEDORES DO CONTRATO, DESEJA CRIAR ESTORNOS PARA ESSES PAGAMENTOS?", "SIM", "NÃO", false); + } + bool flag2 = flag1; + documento = await this._apoliceServico.BuscarApoliceAsync(ConsultaViewModel.DocumentoSelecionado.get_Id(), false, false); + if (documento.get_Controle().get_Documentos().Count > 1) + { + IList documentos = documento.get_Controle().get_Documentos(); + IEnumerable excluido = + from x in documentos + where !x.get_Excluido() + select x; + list = ( + from x in excluido + orderby x.get_Ordem() + select x).ToList(); + } + else + { + list = documento.get_Controle().get_Documentos(); + } + IList documentos1 = list; + if (documentos1.Count > 1) + { + IList documentos2 = documentos1; + if (documentos2.Last((Documento x) => x.get_Situacao() != 7).get_Id() != ConsultaViewModel.DocumentoSelecionado.get_Id()) + { + await base.ShowMessage("NÃO É POSSÍVEL RECUSAR UM DOCUMENTO ENQUANTO HOUVER ENDOSSOS EM CIMA DO MESMO.", "OK", "", false); + documento = null; + return; + } + } + if (documento.get_Situacao() != 7) + { + if (documento.get_Tipo() != 0 || !string.IsNullOrEmpty(documento.get_Apolice())) + { + str = (documento.get_Tipo() != 0 || string.IsNullOrEmpty(documento.get_Apolice()) ? "O ENDOSSO SELECIONADO" : "A APÓLICE SELECIONADA"); + } + else + { + str = "A PROPOSTA SELECIONADA"; + } + string str1 = str; + if (await base.ShowMessage(string.Concat("DESEJA REALMENTE RECUSAR ", str1, "?"), "SIM", "NÃO", false)) + { + string str2 = null; + str2 = await base.ShowObservacaoDialog(); + if (str2 != null) + { + base.Loading(true); + await Funcoes.RecusarApolice(documento, str2, flag2); + ConsultaViewModel.DocumentoSelecionado = null; + await this.SelecionaCliente(this.SelectedCliente, true); + base.Loading(false); + } + } + } + else + { + await base.ShowMessage("NÃO É POSSÍVEL RECUSAR UM DOCUMENTO JÁ RECUSADO.", "OK", "", false); + } + } + documento = null; + } + + public async void SalvarOrdem(ObservableCollection itens) + { + if (itens != null) + { + ObservableCollection observableCollection = itens; + if (!observableCollection.Any((Item x) => { + int? ordem = x.get_Ordem(); + return ordem.GetValueOrDefault() == 0 & ordem.HasValue; + })) + { + ObservableCollection observableCollection1 = itens; + IEnumerable> groupings = + from item in observableCollection1 + group item by item.get_Ordem(); + if (!groupings.Any>((IGrouping x) => x.Count() > 1)) + { + base.Loading(true); + foreach (Item iten in itens) + { + await this._itemServico.Save(iten); + } + await this.SelecionaItens(this.FilterItens, null, (long)0, false); + base.Loading(false); + } + else + { + await base.ShowMessage("EXISTEM ITENS COM ORDEM REPETIDA. \nDEFINA UMA SEQUÊNCIA DIFERENTE PARA CADA ITEM.", "OK", "", false); + } + } + else + { + await base.ShowMessage("O CAMPO ORDEM DEVE SER MAIOR QUE ZERO.", "OK", "", false); + } + } + } + + public void ScrollDocumento() + { + if (this.UpdatingScroll) + { + return; + } + this.UpdatingScroll = true; + Task.Run(async () => { + await Task.Delay(300); + System.Windows.Application.Current.Dispatcher.Invoke(() => { + Action scrollDocumento = Gestor.Application.Actions.Actions.ScrollDocumento; + if (scrollDocumento == null) + { + return; + } + scrollDocumento(); + }); + }); + } + + public async Task SelecionaCliente(Cliente value, bool selecionar = true) + { + List vendedorUsuarios; + long? nullable1; + long? nullable2; + string str; + long? nullable3; + Documento documento; + long? nullable4; + long? nullable5; + long? nullable6; + bool flag; + Documento documento1; + this.Clear(); + if (value == null || value.get_Id() == 0) + { + base.IsVisible = Visibility.Collapsed; + } + else + { + try + { + this.Carregando = true; + base.Loading(true); + this.SelectedCliente = value; + ApoliceServico apoliceServico = this._apoliceServico; + long num = value.get_Id(); + FiltroStatusDocumento statusSelecionado = MainViewModel.StatusSelecionado; + if (Recursos.Usuario != null) + { + vendedorUsuarios = await base.VerificaVinculoVendedor(Recursos.Usuario); + } + else + { + vendedorUsuarios = new List(); + } + ObservableCollection observableCollection = await apoliceServico.BuscarApolicesAsync(num, statusSelecionado, vendedorUsuarios); + apoliceServico = null; + this.Apolices = observableCollection; + ConsultaViewModel consultaViewModel = this; + string[] nome = new string[] { "CONSULTOU ", null, null, null, null }; + str = (MainViewModel.StatusSelecionado != 4 ? string.Concat("OS ", Functions.GetDescription(MainViewModel.StatusSelecionado)) : "TODOS OS DOCUMENTOS"); + nome[1] = str; + nome[2] = " DO CLIENTE \""; + nome[3] = this.SelectedCliente.get_Nome(); + nome[4] = "\""; + string str1 = string.Concat(nome); + long num1 = this.SelectedCliente.get_Id(); + TipoTela? nullable7 = new TipoTela?(21); + Cliente selectedCliente = this.SelectedCliente; + if (selectedCliente != null) + { + nullable3 = new long?(selectedCliente.get_Id()); + } + else + { + nullable1 = null; + nullable3 = nullable1; + } + consultaViewModel.RegistrarAcao(str1, num1, nullable7, string.Format("ID CLIENTE: {0}", nullable3)); + if (this.Apolices == null || this.Apolices.Count <= 0) + { + this.SelectedControle = null; + this.SelectedEndosso = null; + this.SelectedItem = null; + this.SelectedParcela = null; + ConsultaViewModel.DocumentoSelecionado = null; + ConsultaViewModel.ItemSelecionado = null; + this.FilterDocumento = 0; + this.IsVisibleRadioEndosso = Visibility.Collapsed; + Action updateDocumento = Gestor.Application.Actions.Actions.UpdateDocumento; + if (updateDocumento != null) + { + updateDocumento(null); + } + else + { + } + } + else if (selecionar) + { + if (ConsultaViewModel.DocumentoSelecionado != null && ConsultaViewModel.DocumentoSelecionado.get_Tipo() != 0) + { + Controle controle = ConsultaViewModel.DocumentoSelecionado.get_Controle(); + if (controle != null) + { + Cliente cliente = controle.get_Cliente(); + if (cliente != null) + { + nullable4 = new long?(cliente.get_Id()); + } + else + { + nullable2 = null; + nullable4 = nullable2; + } + } + else + { + nullable2 = null; + nullable4 = nullable2; + } + nullable1 = nullable4; + long num2 = value.get_Id(); + if (nullable1.GetValueOrDefault() != num2 | !nullable1.HasValue) + { + goto Label2; + } + Controle controle1 = ConsultaViewModel.DocumentoSelecionado.get_Controle(); + if (controle1 != null) + { + IList documentos = controle1.get_Documentos(); + if (documentos != null) + { + Documento documento2 = documentos.FirstOrDefault((Documento x) => x.get_Tipo() == 0); + if (documento2 != null) + { + nullable5 = new long?(documento2.get_Id()); + } + else + { + nullable1 = null; + nullable5 = nullable1; + } + } + else + { + nullable1 = null; + nullable5 = nullable1; + } + } + else + { + nullable1 = null; + nullable5 = nullable1; + } + nullable1 = nullable5; + long valueOrDefault = nullable1.GetValueOrDefault(); + Documento documentoSelecionado = ConsultaViewModel.DocumentoSelecionado; + if (documentoSelecionado != null) + { + nullable6 = new long?(documentoSelecionado.get_Id()); + } + else + { + nullable1 = null; + nullable6 = nullable1; + } + long? nullable8 = nullable6; + if (valueOrDefault > (long)0) + { + flag = this.Apolices.FirstOrDefault((Documento x) => x.get_Id() == valueOrDefault); + } + else + { + flag = false; + } + if (!flag) + { + ConsultaViewModel consultaViewModel1 = this; + if (ConsultaViewModel.DocumentoSelecionado != null) + { + ObservableCollection apolices = this.Apolices; + documento1 = apolices.FirstOrDefault((Documento x) => x.get_Id() == ConsultaViewModel.DocumentoSelecionado.get_Id()); + if (documento1 == null) + { + documento1 = this.Apolices.FirstOrDefault(); + } + } + else + { + documento1 = this.Apolices.FirstOrDefault(); + } + await consultaViewModel1.SelecionaDocumento(0, documento1); + this.CarregaDocumentos(0); + } + else + { + await this.SelecionaDocumento(0, this.Apolices.FirstOrDefault((Documento x) => x.get_Id() == valueOrDefault)); + this.FilterDocumento = 1; + this.IsVisibleEndosso = Visibility.Visible; + ConsultaViewModel consultaViewModel2 = this; + Documento item = this.Endossos.FirstOrDefault((Documento x) => { + long id = x.get_Id(); + long? nullable = nullable8; + return id == nullable.GetValueOrDefault() & nullable.HasValue; + }); + if (item == null) + { + item = this.Endossos[0]; + } + consultaViewModel2.SelectedEndosso = item; + this.IsLoading = false; + await this.WorkOnSelectedEndosso(this.SelectedEndosso); + this.CarregaDocumentos(1); + } + goto Label1; + } + Label2: + ConsultaViewModel consultaViewModel3 = this; + if (ConsultaViewModel.DocumentoSelecionado != null) + { + ObservableCollection apolices1 = this.Apolices; + documento = apolices1.FirstOrDefault((Documento x) => x.get_Id() == ConsultaViewModel.DocumentoSelecionado.get_Id()); + if (documento == null) + { + documento = this.Apolices.FirstOrDefault(); + } + } + else + { + documento = this.Apolices.FirstOrDefault(); + } + await consultaViewModel3.SelecionaDocumento(0, documento); + this.CarregaDocumentos(0); + } + else + { + base.Loading(false); + this.Carregando = false; + return; + } + Label1: + this.ManutencaoItemVisibility = Visibility.Visible; + this.RenovarVisibility = Visibility.Visible; + this.TrocarClienteVisibility = Visibility.Visible; + this.TarefasVisibility = Visibility.Visible; + this.EndossarVisibility = Visibility.Visible; + this.ComissaoVisibility = Visibility.Visible; + base.Loading(false); + } + catch (Exception exception1) + { + Exception exception = exception1; + this.Clear(); + this.SelectedControle = null; + this.SelectedEndosso = null; + this.SelectedItem = null; + this.SelectedParcela = null; + ConsultaViewModel.DocumentoSelecionado = null; + ConsultaViewModel.ItemSelecionado = null; + this.FilterDocumento = 0; + this.IsVisibleRadioEndosso = Visibility.Collapsed; + Action action = Gestor.Application.Actions.Actions.UpdateDocumento; + if (action != null) + { + action(null); + } + else + { + } + (new BaseServico()).Registrar(exception, 1, 3, new { @value = value, selecionar = selecionar }, true); + } + this.Carregando = false; + } + } + + public async Task SelecionaDocumento(int type, Documento documento) + { + if (!this.Pesquisando) + { + if (documento != null) + { + documento.get_Controle().get_Cliente().set_Nome(this.SelectedCliente.get_Nome()); + if (type == 1) + { + this.FilterDocumento = 1; + this.IsVisibleEndosso = Visibility.Visible; + this.SelectedEndosso = documento; + await this.WorkOnSelectedEndosso(documento); + } + else + { + this.FilterDocumento = 0; + this.IsVisibleRadioEndosso = Visibility.Collapsed; + this.IsVisibleApolice = Visibility.Visible; + this.SelectedControle = documento; + await this.WorkOnSelectedControle(documento); + if (documento.get_TemEndosso()) + { + this.IsVisibleRadioEndosso = Visibility.Visible; + ConsultaViewModel observableCollection = this; + IList documentos = documento.get_Controle().get_Documentos(); + observableCollection.Endossos = new ObservableCollection(documentos.Where((Documento x) => { + if (x.get_Tipo() != 1) + { + return false; + } + if (Recursos.Usuario.get_Id() == 0) + { + return true; + } + return !x.get_Excluido(); + })); + } + else + { + return; + } + } + } + else + { + this.FilterDocumento = 0; + this.IsVisibleRadioEndosso = Visibility.Collapsed; + this.IsVisibleApolice = Visibility.Visible; + } + } + } + + public void SelecionaItem(Item item) + { + int num; + if (item == null || item.get_Id() == 0) + { + return; + } + if (item != null) + { + long? substituido = item.get_Substituido(); + long num1 = (long)0; + if (substituido.GetValueOrDefault() <= num1 | !substituido.HasValue) + { + num = 0; + this.FilterItens = num; + this.SelectedItem = item; + return; + } + num = 3; + this.FilterItens = num; + this.SelectedItem = item; + return; + } + num = 0; + this.FilterItens = num; + this.SelectedItem = item; + } + + public async Task SelecionaItens(int type, Documento documento = null, long iditem = 0L, bool pesquisaAvancada = false) + { + long? substituido; + long num; + Item item; + Item item1; + bool valueOrDefault; + Item item2; + Item item3; + bool flag; + Item item4; + Item item5; + if (documento == null) + { + documento = this.SelectedControle; + } + if (documento != null) + { + this.IsLoadingItens = false; + bool flag1 = !pesquisaAvancada; + if (flag1) + { + flag1 = await this.VerificaItens(documento); + } + if (!flag1) + { + await this.CarregaItens(type, documento); + int filterItens = this.FilterItens; + if (iditem == 0 && filterItens != 2) + { + ObservableCollection itens = this.Itens; + if (itens != null) + { + item = itens.FirstOrDefault((Item i) => { + long? nullable; + long id = i.get_Id(); + Item selectedItem = this.SelectedItem; + if (selectedItem != null) + { + nullable = new long?(selectedItem.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + return id == nullable1.GetValueOrDefault() & nullable1.HasValue; + }); + } + else + { + item = null; + } + Item item6 = item; + if (item6 != null || filterItens == 0) + { + ConsultaViewModel consultaViewModel = this; + if (item6 != null) + { + item1 = item6; + } + else + { + ObservableCollection observableCollection = this.Itens; + if (observableCollection != null) + { + item1 = observableCollection.FirstOrDefault(); + } + else + { + item1 = null; + } + } + consultaViewModel.SelectedItem = item1; + } + else if (item6 == null && filterItens == 1) + { + Item item7 = this.SelectedItem; + if (item7 != null) + { + substituido = item7.get_Substituicao(); + num = (long)0; + flag = substituido.GetValueOrDefault() > num & substituido.HasValue; + } + else + { + flag = false; + } + if (flag) + { + ObservableCollection itens1 = this.Itens; + if (itens1 != null) + { + item5 = itens1.FirstOrDefault((Item i) => { + long? substituicao; + long id = i.get_Id(); + Item selectedItem = this.SelectedItem; + if (selectedItem != null) + { + substituicao = selectedItem.get_Substituicao(); + } + else + { + substituicao = null; + } + long? nullable = substituicao; + return id == nullable.GetValueOrDefault() & nullable.HasValue; + }); + } + else + { + item5 = null; + } + item6 = item5; + } + ConsultaViewModel consultaViewModel1 = this; + if (item6 != null) + { + item4 = item6; + } + else + { + ObservableCollection observableCollection1 = this.Itens; + if (observableCollection1 != null) + { + item4 = observableCollection1.FirstOrDefault(); + } + else + { + item4 = null; + } + } + consultaViewModel1.SelectedItem = item4; + } + Item item8 = this.SelectedItem; + if (item8 != null) + { + substituido = item8.get_Substituido(); + num = (long)0; + valueOrDefault = substituido.GetValueOrDefault() > num & substituido.HasValue; + } + else + { + valueOrDefault = false; + } + if (valueOrDefault && filterItens != 1) + { + this.FilterItens = 3; + this.Itens = await this._itemServico.BuscarItens(documento.get_Controle().get_Id(), 1); + ObservableCollection itens2 = this.Itens; + if (itens2 != null) + { + item2 = itens2.FirstOrDefault((Item i) => { + long? nullable; + long id = i.get_Id(); + Item selectedItem = this.SelectedItem; + if (selectedItem != null) + { + nullable = new long?(selectedItem.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + return id == nullable1.GetValueOrDefault() & nullable1.HasValue; + }); + } + else + { + item2 = null; + } + item6 = item2; + ConsultaViewModel consultaViewModel2 = this; + if (item6 != null) + { + item3 = item6; + } + else + { + ObservableCollection observableCollection2 = this.Itens; + if (observableCollection2 != null) + { + item3 = observableCollection2.FirstOrDefault(); + } + else + { + item3 = null; + } + } + consultaViewModel2.SelectedItem = item3; + } + } + this.IsLoadingItens = true; + } + } + } + + public async Task SelecionaParcelas(Documento documento = null) + { + ObservableCollection observableCollection; + Parcela item; + if (documento == null) + { + documento = this.SelectedControle; + } + ObservableCollection observableCollection1 = await this._parcelaServico.BuscarParcelasPorDocumento(documento); + ConsultaViewModel consultaViewModel = this; + if (documento.get_TipoRecebimento().GetValueOrDefault() == 2) + { + ObservableCollection observableCollection2 = observableCollection1; + observableCollection = new ObservableCollection( + from x in observableCollection2 + orderby x.get_NumeroParcela() descending + select x); + } + else + { + observableCollection = observableCollection1; + } + consultaViewModel.Parcelas = observableCollection; + ConsultaViewModel consultaViewModel1 = this; + if (this.Parcelas == null || this.Parcelas.Count <= 0) + { + item = null; + } + else + { + item = this.Parcelas[0]; + } + consultaViewModel1.SelectedParcela = item; + this.CalculaComissao(documento, this.Parcelas); + this.IsLoadingParcelas = true; + } + + public async void SelecionarCliente(Cliente cliente) + { + await this.SelecionaCliente(cliente, true); + this.ScrollDocumento(); + } + + public async Task SelecionarCliente(long id, bool selecionar) + { + Cliente cliente = await (new ClienteServico()).BuscarCliente(id); + await this.SelecionaCliente(cliente, selecionar); + } + + public async Task VerificaItens(Documento documento) + { + bool flag; + if (!this.ItensRevelados) + { + if (await this._itemServico.ChecarQuantidade(documento.get_Id()) > 2) + { + this.Itens = new ObservableCollection(); + ObservableCollection itens = this.Itens; + Item item = new Item(); + item.set_Id((long)0); + item.set_Descricao("Item - Apólice Coletiva"); + itens.Add(item); + this.MostrarItensVisibility = Visibility.Visible; + this.MostrarSinistroVisibility = Visibility.Collapsed; + flag = true; + return flag; + } + } + flag = false; + return flag; + } + + private async Task WorkOnSelectedControle(Documento value) + { + string str; + Visibility visibility; + long id; + if (value != null && value.get_Id() != 0 && !this.IsLoading) + { + ConsultaViewModel.DocumentoSelecionado = value; + this.IsEnabledParcelaItem = false; + this.IsLoading = true; + this.VisibilityParcelasVendedores = Visibility.Collapsed; + ConsultaViewModel consultaViewModel = this; + if (string.IsNullOrEmpty(value.get_Apolice())) + { + DateTime networkTime = Funcoes.GetNetworkTime(); + TimeSpan date = networkTime.Date - value.get_Vigencia1(); + str = string.Format("{0} DIAS DE PENDÊNCIA", date.TotalDays); + } + else + { + str = ""; + } + consultaViewModel.PendenciaApolice = str; + ConsultaViewModel consultaViewModel1 = this; + visibility = (value.get_TemEndosso() ? Visibility.Visible : Visibility.Collapsed); + consultaViewModel1.IsVisibleRadioEndosso = visibility; + await this.SelecionaParcelas(value); + this.VisibilityParcelasVendedores = Visibility.Visible; + this.FilterItens = 0; + Item itemSelecionado = ConsultaViewModel.ItemSelecionado; + if (itemSelecionado != null) + { + id = itemSelecionado.get_Id(); + } + else + { + id = (long)0; + } + long num = id; + await this.SelecionaItens(this.FilterItens, value, (long)0, false); + if (num > (long)0 && this.Itens != null && this.Itens.Any((Item x) => x.get_Id() == num)) + { + ConsultaViewModel.ItemSelecionado = this.Itens.First((Item x) => x.get_Id() == num); + this.SelecionaItem(ConsultaViewModel.ItemSelecionado); + Action scrollToItem = Gestor.Application.Actions.Actions.ScrollToItem; + if (scrollToItem != null) + { + scrollToItem(); + } + else + { + } + } + this.IsLoading = false; + this.IsEnabledParcelaItem = true; + } + } + + private void WorkOnSelectedDocumento(Documento value) + { + if (value == null || value.get_Id() == 0 || this.Recarregando) + { + return; + } + ConsultaViewModel.DocumentoSelecionado = value; + this.ParcelasLabel = (ConsultaViewModel.DocumentoSelecionado.get_TipoRecebimento().GetValueOrDefault() == 2 ? "FATURAS" : "PARCELAS"); + TipoRecebimento? tipoRecebimento = ConsultaViewModel.DocumentoSelecionado.get_TipoRecebimento(); + this.IsFatura = tipoRecebimento.GetValueOrDefault() == 2; + Action updateDocumento = Gestor.Application.Actions.Actions.UpdateDocumento; + if (updateDocumento == null) + { + return; + } + updateDocumento(value); + } + + private async Task WorkOnSelectedEndosso(Documento value) + { + string str; + long id; + Visibility visibility; + string apolice; + if (value != null && value.get_Id() != 0 && !this.IsLoading) + { + ConsultaViewModel.DocumentoSelecionado = value; + base.IsEnabled = false; + this.IsLoading = true; + this.VisibilityParcelasVendedores = Visibility.Collapsed; + ConsultaViewModel consultaViewModel = this; + if (string.IsNullOrEmpty(value.get_Endosso())) + { + DateTime networkTime = Funcoes.GetNetworkTime(); + TimeSpan date = networkTime.Date - value.get_Vigencia1(); + str = string.Format("{0} DIAS DE PENDÊNCIA", date.TotalDays); + } + else + { + str = ""; + } + consultaViewModel.PendenciaApolice = str; + await this.SelecionaParcelas(value); + Item itemSelecionado = ConsultaViewModel.ItemSelecionado; + if (itemSelecionado != null) + { + id = itemSelecionado.get_Id(); + } + else + { + id = (long)0; + } + long num = id; + await this.SelecionaItens(this.FilterItens, null, (long)0, false); + if (num > (long)0 && this.Itens != null && this.Itens.Any((Item x) => x.get_Id() == num)) + { + ConsultaViewModel.ItemSelecionado = this.Itens.First((Item x) => x.get_Id() == num); + this.SelecionaItem(ConsultaViewModel.ItemSelecionado); + Action scrollToItem = Gestor.Application.Actions.Actions.ScrollToItem; + if (scrollToItem != null) + { + scrollToItem(); + } + else + { + } + } + this.VisibilityParcelasVendedores = Visibility.Visible; + ConsultaViewModel consultaViewModel1 = this; + List configuracoes = Recursos.Configuracoes; + if (configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 19)) + { + Documento documento = value; + if (documento != null) + { + apolice = documento.get_Apolice(); + } + else + { + apolice = null; + } + if (string.IsNullOrWhiteSpace(apolice) || !value.get_Emissao().HasValue) + { + goto Label1; + } + visibility = Visibility.Collapsed; + goto Label0; + } + Label1: + visibility = Visibility.Visible; + Label0: + consultaViewModel1.RecusaVisibility = visibility; + base.IsEnabled = true; + this.IsLoading = false; + } + } + + private static void WorkOnSelectedItem(Item value) + { + long? nullable; + if (value != null) + { + Item itemSelecionado = ConsultaViewModel.ItemSelecionado; + if (itemSelecionado != null) + { + nullable = new long?(itemSelecionado.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long id = value.get_Id(); + if (nullable1.GetValueOrDefault() == id & nullable1.HasValue) + { + return; + } + } + ConsultaViewModel.ItemSelecionado = value; + Action updateItem = Gestor.Application.Actions.Actions.UpdateItem; + if (updateItem == null) + { + return; + } + updateItem(value); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Seguros/CriticaApoliceViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Seguros/CriticaApoliceViewModel.cs new file mode 100644 index 0000000..7ec09a7 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Seguros/CriticaApoliceViewModel.cs @@ -0,0 +1,1486 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Seguros +{ + public class CriticaApoliceViewModel : BaseApoliceViewModel + { + private readonly CriticaApoliceServico _criticaServico; + + private readonly ClienteServico _clienteServico; + + private readonly ItemServico _itemServico; + + private List Vinculos; + + private ObservableCollection _usuarios = new ObservableCollection(); + + private ObservableCollection _seguradorasFiltro = new ObservableCollection(); + + private string _fieldNascimento = "NASCIMENTO"; + + private bool _isExpanded = true; + + private DateTime _inicio = Funcoes.GetNetworkTime().Date.AddDays(-7); + + private DateTime _fim = Funcoes.GetNetworkTime().Date; + + private Usuario _selectedUsuario; + + private Seguradora _selectedSeguradora; + + private bool _criticado; + + private ObservableCollection _criticas = new ObservableCollection(); + + private ObservableCollection _criticaFiltrada = new ObservableCollection(); + + private bool _isCriticaSelected; + + private CriticaApolice _selectedCritica; + + private bool _hasChange; + + private bool _isParcela; + + private DateTime? _emissaoCritica; + + private DateTime? _transmissaoCritica; + + private DateTime? _nascimentoCritica; + + private TipoSeguro? _situacao; + + private Cliente _selectedCliente; + + private string _documentoPrincipal; + + private Visibility _visibilityFisica = Visibility.Collapsed; + + private ObservableCollection _telefones = new ObservableCollection(); + + private ObservableCollection _emails = new ObservableCollection(); + + private ObservableCollection _itens = new ObservableCollection(); + + private bool _enableGrid = true; + + private string _pesquisa = ""; + + private ObservableCollection _pesquisaCritica = new ObservableCollection(); + + private string _profissaoText; + + private string _atividadeText; + + private Visibility _visibilityJuridica = Visibility.Collapsed; + + private string _fieldDocumento = "CPF"; + + private Visibility _valorComissao; + + public string AtividadeText + { + get + { + return this._atividadeText; + } + set + { + this._atividadeText = value; + base.OnPropertyChanged("AtividadeText"); + } + } + + public bool BuscaInicial { get; set; } = true; + + public bool Criticado + { + get + { + return this._criticado; + } + set + { + this._criticado = value; + base.OnPropertyChanged("Criticado"); + } + } + + public ObservableCollection CriticaFiltrada + { + get + { + return this._criticaFiltrada; + } + set + { + this._criticaFiltrada = value; + base.OnPropertyChanged("CriticaFiltrada"); + } + } + + public ObservableCollection Criticas + { + get + { + return this._criticas; + } + set + { + this._criticas = value; + base.OnPropertyChanged("Criticas"); + } + } + + public string DocumentoPrincipal + { + get + { + return this._documentoPrincipal; + } + set + { + if (value == null || ValidationHelper.OnlyNumber(value).Length > 11) + { + this.VisibilityFisica = Visibility.Collapsed; + this.FieldNascimento = "FUNDAÇÃO"; + } + else + { + this.VisibilityFisica = Visibility.Visible; + this.FieldNascimento = "NASCIMENTO"; + } + this._documentoPrincipal = value; + if (this.SelectedCliente != null) + { + TipoDocumento? documentoPrincipal = this.SelectedCliente.get_DocumentoPrincipal(); + if (documentoPrincipal.HasValue) + { + TipoDocumento valueOrDefault = documentoPrincipal.GetValueOrDefault(); + if (valueOrDefault == 1) + { + this.SelectedCliente.set_Rne(value); + base.OnPropertyChanged("DocumentoPrincipal"); + return; + } + else + { + if (valueOrDefault != 2) + { + goto Label1; + } + this.SelectedCliente.set_Cei(value); + base.OnPropertyChanged("DocumentoPrincipal"); + return; + } + } + Label1: + this.SelectedCliente.set_Documento(value); + } + base.OnPropertyChanged("DocumentoPrincipal"); + } + } + + public ObservableCollection Emails + { + get + { + return this._emails; + } + set + { + this._emails = value; + base.OnPropertyChanged("Emails"); + } + } + + public DateTime? EmissaoCritica + { + get + { + return this._emissaoCritica; + } + set + { + this._emissaoCritica = value; + base.OnPropertyChanged("EmissaoCritica"); + } + } + + public bool EnableGrid + { + get + { + return this._enableGrid; + } + set + { + this._enableGrid = value; + base.OnPropertyChanged("EnableGrid"); + } + } + + public string FieldDocumento + { + get + { + return this._fieldDocumento; + } + set + { + this._fieldDocumento = value; + base.OnPropertyChanged("FieldDocumento"); + } + } + + public string FieldNascimento + { + get + { + return this._fieldNascimento; + } + set + { + this._fieldNascimento = value; + base.OnPropertyChanged("FieldNascimento"); + } + } + + public DateTime Fim + { + get + { + return this._fim; + } + set + { + this._fim = value; + base.OnPropertyChanged("Fim"); + } + } + + public bool HasChange + { + get + { + return this._hasChange; + } + set + { + this._hasChange = value; + base.OnPropertyChanged("HasChange"); + } + } + + public int Index { get; set; } = -1; + + public DateTime Inicio + { + get + { + return this._inicio; + } + set + { + this._inicio = value; + base.OnPropertyChanged("Inicio"); + } + } + + public bool IsCriticaSelected + { + get + { + return this._isCriticaSelected; + } + set + { + this._isCriticaSelected = value; + base.OnPropertyChanged("IsCriticaSelected"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public bool IsLoading + { + get; + set; + } + + public bool IsParcela + { + get + { + return this._isParcela; + } + set + { + this._isParcela = value; + base.OnPropertyChanged("IsParcela"); + } + } + + public ObservableCollection Itens + { + get + { + return this._itens; + } + set + { + this._itens = value; + base.OnPropertyChanged("Itens"); + } + } + + public DateTime? NascimentoCritica + { + get + { + return this._nascimentoCritica; + } + set + { + this._nascimentoCritica = value; + base.OnPropertyChanged("NascimentoCritica"); + } + } + + public string Pesquisa + { + get + { + return this._pesquisa; + } + set + { + this._pesquisa = value; + base.OnPropertyChanged("Pesquisa"); + } + } + + public ObservableCollection PesquisaCritica + { + get + { + return this._pesquisaCritica; + } + set + { + this._pesquisaCritica = value; + base.OnPropertyChanged("PesquisaCritica"); + } + } + + public string ProfissaoText + { + get + { + return this._profissaoText; + } + set + { + this._profissaoText = value; + base.OnPropertyChanged("ProfissaoText"); + } + } + + public ObservableCollection SeguradorasFiltro + { + get + { + return this._seguradorasFiltro; + } + set + { + this._seguradorasFiltro = value; + this.SelectedSeguradora = this.SelectedSeguradora ?? value.FirstOrDefault(); + base.OnPropertyChanged("SeguradorasFiltro"); + } + } + + public bool SeguroCombinado + { + get; + set; + } + + public Cliente SelectedCliente + { + get + { + return this._selectedCliente; + } + set + { + this._selectedCliente = value; + base.OnPropertyChanged("SelectedCliente"); + } + } + + public CriticaApolice SelectedCritica + { + get + { + return this._selectedCritica; + } + set + { + this._selectedCritica = value; + this.IsCriticaSelected = value != null; + base.OnPropertyChanged("SelectedCritica"); + } + } + + public Seguradora SelectedSeguradora + { + get + { + return this._selectedSeguradora; + } + set + { + this._selectedSeguradora = value; + base.OnPropertyChanged("SelectedSeguradora"); + } + } + + public Usuario SelectedUsuario + { + get + { + return this._selectedUsuario; + } + set + { + this._selectedUsuario = value; + base.OnPropertyChanged("SelectedUsuario"); + } + } + + public TipoSeguro? StatusDocumento + { + get + { + return this._situacao; + } + set + { + this._situacao = value; + base.OnPropertyChanged("StatusDocumento"); + } + } + + public ObservableCollection Telefones + { + get + { + return this._telefones; + } + set + { + this._telefones = value; + base.OnPropertyChanged("Telefones"); + } + } + + public DateTime? TransmissaoCritica + { + get + { + return this._transmissaoCritica; + } + set + { + this._transmissaoCritica = value; + base.OnPropertyChanged("TransmissaoCritica"); + } + } + + public ObservableCollection Usuarios + { + get + { + return this._usuarios; + } + set + { + this._usuarios = value; + this.SelectedUsuario = this.SelectedUsuario ?? value.FirstOrDefault(); + base.OnPropertyChanged("Usuarios"); + } + } + + public Visibility ValorComissao + { + get + { + return this._valorComissao; + } + set + { + this._valorComissao = value; + base.OnPropertyChanged("ValorComissao"); + } + } + + public Visibility VisibilityFisica + { + get + { + return this._visibilityFisica; + } + set + { + this._visibilityFisica = value; + base.OnPropertyChanged("VisibilityFisica"); + } + } + + public Visibility VisibilityJuridica + { + get + { + return this._visibilityJuridica; + } + set + { + this._visibilityJuridica = value; + base.OnPropertyChanged("VisibilityJuridica"); + } + } + + public CriticaApoliceViewModel() + { + base.Invoke = false; + this._criticaServico = new CriticaApoliceServico(); + this._clienteServico = new ClienteServico(); + this._itemServico = new ItemServico(); + } + + public void AdcionarFiltro() + { + if (string.IsNullOrEmpty(this.Pesquisa)) + { + return; + } + if (string.IsNullOrWhiteSpace(this.Pesquisa.Replace("+", ""))) + { + return; + } + if (this.PesquisaCritica == null) + { + this.PesquisaCritica = new ObservableCollection(); + } + this.PesquisaCritica.Add(this.Pesquisa); + this.Pesquisa = string.Empty; + this.Pesquisar(); + } + + public void AlteraDocumentoPrincipal() + { + if (this.SelectedCliente == null) + { + return; + } + TipoDocumento? documentoPrincipal = this.SelectedCliente.get_DocumentoPrincipal(); + if (documentoPrincipal.HasValue) + { + TipoDocumento valueOrDefault = documentoPrincipal.GetValueOrDefault(); + if (valueOrDefault == 1) + { + this.DocumentoPrincipal = this.SelectedCliente.get_Rne(); + return; + } + if (valueOrDefault == 2) + { + this.DocumentoPrincipal = this.SelectedCliente.get_Cei(); + return; + } + } + this.DocumentoPrincipal = this.SelectedCliente.get_Documento(); + this.SelectedCliente.set_DocumentoPrincipal(new TipoDocumento?(0)); + } + + public async Task CarregaCritica(long usuario, long seguradora, bool criticado = false) + { + bool count; + Usuario usuario1; + Seguradora seguradora1; + object nome; + long num; + object obj; + long num1; + object obj1; + object obj2; + object nome1; + long num2; + object nome2; + long num3; + object obj3; + if (!this.IsLoading || this.BuscaInicial) + { + this.BuscaInicial = false; + this.EnableGrid = false; + base.Loading(true); + this.Criticado = criticado; + await this.CarregarUsuarios(usuario, this.Criticado); + List criticaApolices = await this._criticaServico.BuscarCritica(usuario, this.Inicio, this.Fim, (long)0, this.Criticado, this.Vinculos); + CriticaApoliceViewModel observableCollection = this; + IEnumerable criticaApolices1 = criticaApolices.Where((CriticaApolice x) => { + if (usuario != 0 && x.get_UsuarioImportacao().get_Id() != usuario) + { + return false; + } + if (seguradora == 0) + { + return true; + } + return x.get_Documento().get_Controle().get_Seguradora().get_Id() == seguradora; + }); + IOrderedEnumerable dataImportacao = + from x in criticaApolices1 + orderby x.get_DataImportacao() + select x; + observableCollection.Criticas = new ObservableCollection(dataImportacao.ThenByDescending((CriticaApolice x) => x.get_Documento().get_Controle().get_Cliente().get_Nome())); + this.CriticaFiltrada = this.Criticas; + if (this.CriticaFiltrada == null || this.CriticaFiltrada.Count <= 0) + { + this.IsCriticaSelected = false; + } + else + { + await this.SelecionaCritica(this.CriticaFiltrada.First()); + } + CriticaApoliceViewModel criticaApoliceViewModel = this; + ObservableCollection criticaFiltrada = this.CriticaFiltrada; + if (criticaFiltrada != null) + { + count = criticaFiltrada.Count > 0; + } + else + { + count = false; + } + criticaApoliceViewModel.IsExpanded = count; + base.Loading(false); + ObservableCollection usuarios = this.Usuarios; + if (usuarios != null) + { + usuario1 = usuarios.FirstOrDefault((Usuario x) => x.get_Id() == usuario); + } + else + { + usuario1 = null; + } + Usuario usuario2 = usuario1; + List seguradoras = base.Seguradoras; + if (seguradoras != null) + { + seguradora1 = seguradoras.FirstOrDefault((Seguradora x) => x.get_Id() == seguradora); + } + else + { + seguradora1 = null; + } + Seguradora seguradora2 = seguradora1; + CriticaApoliceViewModel criticaApoliceViewModel1 = this; + string str = string.Format("CONSULTOU CRÍTICAS NO PERÍODO ENTRE {0:d} E {1:d}", this.Inicio, this.Fim); + long num4 = (long)0; + TipoTela? nullable = new TipoTela?(20); + if (this.PesquisaCritica == null || this.PesquisaCritica.Count <= 0) + { + object[] objArray = new object[5]; + if (usuario2 != null) + { + nome = usuario2.get_Nome(); + } + else + { + nome = null; + } + if (nome == null) + { + nome = "TODOS USUÁRIOS"; + } + objArray[0] = nome; + num = (usuario2 != null ? usuario2.get_Id() : (long)0); + objArray[1] = num; + if (seguradora2 != null) + { + obj = seguradora2.get_Nome(); + } + else + { + obj = null; + } + if (obj == null) + { + obj = "TODAS AS SEGURADORAS"; + } + objArray[2] = obj; + num1 = (seguradora2 != null ? seguradora2.get_Id() : (long)0); + objArray[3] = num1; + obj1 = (this.Criticado ? "SIM" : "NÃO"); + objArray[4] = obj1; + obj2 = string.Format("USUÁRIO IMPORTAÇÃO: {0} ({1})\nSEGURADORA: {2} ({3})\nCRITICADOS: {4}", objArray); + } + else + { + object[] objArray1 = new object[6]; + if (usuario2 != null) + { + nome1 = usuario2.get_Nome(); + } + else + { + nome1 = null; + } + if (nome1 == null) + { + nome1 = "TODOS USUÁRIOS"; + } + objArray1[0] = nome1; + num2 = (usuario2 != null ? usuario2.get_Id() : (long)0); + objArray1[1] = num2; + if (seguradora2 != null) + { + nome2 = seguradora2.get_Nome(); + } + else + { + nome2 = null; + } + if (nome2 == null) + { + nome2 = "TODAS AS SEGURADORAS"; + } + objArray1[2] = nome2; + num3 = (seguradora2 != null ? seguradora2.get_Id() : (long)0); + objArray1[3] = num3; + obj3 = (this.Criticado ? "SIM" : "NÃO"); + objArray1[4] = obj3; + objArray1[5] = ValidationHelper.Join(this.PesquisaCritica, ", "); + obj2 = string.Format("USUÁRIO IMPORTAÇÃO: {0} ({1})\nSEGURADORA: {2} ({3})\nCRITICADOS: {4}\nPESQUISA PERSONALIZADA: \"{5}\"", objArray1); + } + criticaApoliceViewModel1.RegistrarAcao(str, num4, nullable, obj2); + this.EnableGrid = true; + } + } + + public async Task CarregarSeguradoras() + { + this.IsLoading = true; + List list = await this._criticaServico.BuscarSeguradorasAsync(); + List seguradoras = list; + list = ( + from x in seguradoras + orderby x.get_Nome() + select x).ToList(); + Seguradora seguradora = new Seguradora(); + seguradora.set_Id((long)0); + seguradora.set_Nome("TODAS AS SEGURADORAS"); + seguradora.set_Ativo(true); + list.Insert(0, seguradora); + CriticaApoliceViewModel observableCollection = this; + List seguradoras1 = list; + observableCollection.SeguradorasFiltro = new ObservableCollection( + from x in seguradoras1 + where x.get_Ativo() + select x); + this.SelectedSeguradora = this.SeguradorasFiltro.FirstOrDefault(); + this.IsLoading = false; + } + + public async Task CarregarUsuarios(long selected = 0L, bool criticado = false) + { + bool count; + this.IsLoading = true; + this.Criticado = criticado; + List usuarios = new List(); + List vinculos = this.Vinculos; + if (vinculos != null) + { + count = vinculos.Count > 0; + } + else + { + count = false; + } + if (!count) + { + usuarios = await this._criticaServico.BuscarUsuarioCritica(this.Inicio, this.Fim, this.Criticado); + Usuario usuario = new Usuario(); + usuario.set_Id((long)0); + usuario.set_Nome("TODOS OS USUÁRIOS"); + usuarios.Insert(0, usuario); + } + else + { + Usuario usuario1 = new Usuario(); + usuario1.set_Id(Recursos.Usuario.get_Id()); + usuario1.set_Nome(Recursos.Usuario.get_Nome()); + usuarios.Insert(0, usuario1); + } + this.Usuarios = new ObservableCollection(usuarios); + CriticaApoliceViewModel criticaApoliceViewModel = this; + Usuario usuario2 = this.Usuarios.FirstOrDefault((Usuario x) => x.get_Id() == selected); + if (usuario2 == null) + { + usuario2 = this.Usuarios.FirstOrDefault(); + } + criticaApoliceViewModel.SelectedUsuario = usuario2; + this.IsLoading = false; + } + + public async Task ConcluirCritica() + { + List criticaApolices; + string str; + string descricao; + DateTime networkTime = Funcoes.GetNetworkTime(); + this.SelectedCritica.set_Critica(new bool?(true)); + this.SelectedCritica.set_DataCritica(new DateTime?(networkTime)); + this.SelectedCritica.set_UsuarioCritica(new long?(Recursos.Usuario.get_Id())); + foreach (CriticaApolice criticaApolouse in await this._criticaServico.BuscarCritica(this.SelectedCritica.get_Documento().get_Id())) + { + criticaApolouse.set_Critica(new bool?(true)); + criticaApolouse.set_DataCritica(new DateTime?(networkTime)); + criticaApolouse.set_UsuarioCritica(new long?(Recursos.Usuario.get_Id())); + await this._criticaServico.Save(criticaApolouse); + } + if (this.SeguroCombinado) + { + List list = ((IEnumerable)await this._criticaServico.BuscarSeguroCombinado(this.SelectedCritica.get_Documento().get_Controle().get_Cliente().get_Id(), this.SelectedCritica.get_Documento().get_Vigencia1())).Where((CriticaApolice duo) => { + if (duo.get_Documento().get_Controle().get_Seguradora().get_Id() == this.SelectedCritica.get_Documento().get_Controle().get_Seguradora().get_Id() && duo.get_Documento().get_Controle().get_Cliente().get_Id() == this.SelectedCritica.get_Documento().get_Controle().get_Cliente().get_Id() && duo.get_Documento().get_Vigencia1() == this.SelectedCritica.get_Documento().get_Vigencia1()) + { + DateTime? vigencia2 = duo.get_Documento().get_Vigencia2(); + DateTime? nullable = this.SelectedCritica.get_Documento().get_Vigencia2(); + if ((vigencia2.HasValue == nullable.HasValue ? (vigencia2.HasValue ? vigencia2.GetValueOrDefault() == nullable.GetValueOrDefault() : true) : false) && duo.get_Documento().get_Id() != this.SelectedCritica.get_Documento().get_Id() && duo.get_Documento().get_Apolice() == this.SelectedCritica.get_Documento().get_Apolice() && duo.get_Documento().get_Proposta() == null) + { + return true; + } + } + return Regex.Replace(duo.get_Documento().get_Proposta(), "[^.'-,/]", "") == Regex.Replace(this.SelectedCritica.get_Documento().get_Proposta(), "[^.'-,/]", ""); + }).ToList(); + if (list == null || list.Count() <= 0) + { + criticaApolices = null; + } + else + { + criticaApolices = await this._criticaServico.BuscarCritica(list.FirstOrDefault().get_Documento().get_Id()); + } + list = criticaApolices; + if (list != null && list.Any()) + { + foreach (CriticaApolice criticaApolouse1 in list) + { + criticaApolouse1.set_Critica(new bool?(true)); + criticaApolouse1.set_DataCritica(new DateTime?(networkTime)); + criticaApolouse1.get_Documento().set_PremioLiquido(new decimal(1, 0, 0, false, 2)); + criticaApolouse1.get_Documento().set_PremioTotal(new decimal(1, 0, 0, false, 2)); + criticaApolouse1.get_Documento().set_Comissao(new decimal(1, 0, 0, false, 2)); + criticaApolouse1.set_UsuarioCritica(new long?(Recursos.Usuario.get_Id())); + await this._criticaServico.Save(criticaApolouse1); + await this.Servico.Save(criticaApolouse1.get_Documento(), false, false); + } + } + } + if (this.SelectedCritica.get_Tipo() == "0") + { + str = string.Concat("A PROPOSTA \"", this.CancelDocumento.get_Proposta(), "\""); + } + else + { + str = (this.SelectedCritica.get_Tipo() == "1" ? string.Concat("A APÓLICE \"", this.CancelDocumento.get_Apolice(), "\"") : string.Concat("O ENDOSSO \"", this.CancelDocumento.get_Endosso(), "\"")); + } + string str1 = str; + base.RegistrarAcao(string.Concat("CONCLUIU A CRÍTICA D", str1), this.SelectedCritica.get_Id(), new TipoTela?(20), null); + if (this.Itens == null) + { + descricao = ""; + } + else if (this.Itens.Count > 1) + { + descricao = "APÓLICE COLETIVA"; + } + else + { + Item item = this.Itens.FirstOrDefault(); + if (item != null) + { + descricao = item.get_Descricao(); + } + else + { + descricao = null; + } + } + string str2 = descricao; + try + { + if (string.IsNullOrEmpty(base.SelectedDocumento.get_Controle().get_AssistenciaId())) + { + await base.CreateLinkAssistencia(base.SelectedDocumento, str2, false); + } + } + catch (Exception exception) + { + } + base.SelectedDocumento = null; + this.SelectedCliente = null; + this.Telefones = null; + this.Emails = null; + this.Itens = null; + await this.CarregaCritica(this.SelectedUsuario.get_Id(), this.SelectedSeguradora.get_Id(), this.Criticado); + } + + public async void ExcluirEmail(ClienteEmail email) + { + if (this.Emails.Count >= 2) + { + this.HasChange = true; + int? nullable = email.get_Ordem(); + int count = this.Emails.Count; + int count1 = this.Emails.Count; + this.Emails.Remove(email); + if (!(nullable.GetValueOrDefault() == count & nullable.HasValue)) + { + if (this.Emails.FirstOrDefault((ClienteEmail x) => { + int? ordem = x.get_Ordem(); + int num = count1; + return ordem.GetValueOrDefault() == num & ordem.HasValue; + }) != null) + { + this.Emails.First((ClienteEmail x) => { + int? ordem = x.get_Ordem(); + int num = count1; + return ordem.GetValueOrDefault() == num & ordem.HasValue; + }).set_Ordem(email.get_Ordem()); + CriticaApoliceViewModel observableCollection = this; + ObservableCollection emails = this.Emails; + observableCollection.Emails = new ObservableCollection( + from x in emails + orderby x.get_Ordem() + select x); + } + } + } + else + { + await base.ShowMessage("É NECESSÁRIO TER AO MENOS UM CONTATO DE E-MAIL CADASTRADO.", "OK", "", false); + } + } + + public async void ExcluirTelefone(ClienteTelefone telefone) + { + if (this.Telefones.Count >= 2) + { + this.HasChange = true; + int? nullable = telefone.get_Ordem(); + int count = this.Telefones.Count; + int count1 = this.Telefones.Count; + this.Telefones.Remove(telefone); + if (!(nullable.GetValueOrDefault() == count & nullable.HasValue)) + { + if (this.Telefones.FirstOrDefault((ClienteTelefone x) => { + int? ordem = x.get_Ordem(); + int num = count1; + return ordem.GetValueOrDefault() == num & ordem.HasValue; + }) != null) + { + this.Telefones.First((ClienteTelefone x) => { + int? ordem = x.get_Ordem(); + int num = count1; + return ordem.GetValueOrDefault() == num & ordem.HasValue; + }).set_Ordem(telefone.get_Ordem()); + CriticaApoliceViewModel observableCollection = this; + ObservableCollection telefones = this.Telefones; + observableCollection.Telefones = new ObservableCollection( + from x in telefones + orderby x.get_Ordem() + select x); + } + } + } + else + { + await base.ShowMessage("É NECESSÁRIO TER AO MENOS UM TELEFONE CADASTRADO.", "OK", "", false); + } + } + + public async Task InitialLoad() + { + long id; + this.IsLoading = true; + base.Loading(true); + await base.PermissaoTela(2); + await this.SelecionaUsuario(); + await this.CarregarUsuarios((long)0, false); + await this.CarregarSeguradoras(); + CriticaApoliceViewModel criticaApoliceViewModel = this; + Usuario selectedUsuario = this.SelectedUsuario; + if (selectedUsuario != null) + { + id = selectedUsuario.get_Id(); + } + else + { + id = (long)0; + } + await criticaApoliceViewModel.CarregaCritica(id, (long)0, false); + base.Loading(false); + this.IsLoading = false; + } + + public void JuridicaouFisica(string documento) + { + if (this.SelectedCliente == null) + { + return; + } + this.ProfissaoText = ""; + this.AtividadeText = ""; + if (documento != null && ValidationHelper.OnlyNumber(documento).Length <= 11) + { + this.VisibilityJuridica = Visibility.Collapsed; + this.VisibilityFisica = Visibility.Visible; + this.FieldNascimento = "NASCIMENTO"; + this.FieldDocumento = "CPF"; + this.SelectedCliente.set_Atividade(null); + return; + } + this.VisibilityJuridica = Visibility.Visible; + this.VisibilityFisica = Visibility.Collapsed; + this.FieldNascimento = "FUNDAÇÃO"; + this.FieldDocumento = "CNPJ"; + this.SelectedCliente.set_Profissao(null); + } + + public async void Pesquisar() + { + this.EnableGrid = false; + if (this.PesquisaCritica == null || this.PesquisaCritica.Count == 0) + { + this.CriticaFiltrada = new ObservableCollection(this.Criticas); + } + else + { + CriticaApoliceViewModel observableCollection = this; + IEnumerable criticaApolices = this.Criticas.Where((CriticaApolice x) => { + Func func2 = null; + return this.PesquisaCritica.All((string s) => { + List list = s.Split(new char[] { '+' }).ToList(); + Func u003cu003e9_1484 = CriticaApoliceViewModel.u003cu003ec.u003cu003e9__148_4; + if (u003cu003e9_1484 == null) + { + u003cu003e9_1484 = (string f) => !string.IsNullOrWhiteSpace(f); + CriticaApoliceViewModel.u003cu003ec.u003cu003e9__148_4 = u003cu003e9_1484; + } + IEnumerable strs = list.Where(u003cu003e9_1484); + Func u003cu003e9_5 = func2; + if (u003cu003e9_5 == null) + { + Func func = (string f) => { + if (ValidationHelper.RemoveDiacritics(x.get_Documento().get_Controle().get_Cliente().get_Nome()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(f)) || x.get_Documento().get_Controle().get_Cliente().get_Documento() != null && x.get_Documento().get_Controle().get_Cliente().get_Documento().Contains(f) || x.get_Documento().get_Controle().get_Cliente().get_Cei() != null && x.get_Documento().get_Controle().get_Cliente().get_Cei().Contains(f) || x.get_Documento().get_Controle().get_Cliente().get_Rne() != null && x.get_Documento().get_Controle().get_Cliente().get_Rne().Contains(f) || x.get_UsuarioImportacao() != null && x.get_UsuarioImportacao().get_Nome().Contains(f) || x.get_DataImportacao().HasValue && x.get_DataImportacao().ToString().Contains(f) || x.get_Documento().get_Apolice() != null && x.get_Documento().get_Apolice().ToUpper().Contains(f.ToUpper())) + { + return true; + } + if (x.get_Documento().get_Proposta() == null) + { + return false; + } + return x.get_Documento().get_Proposta().ToUpper().Contains(f.ToUpper()); + }; + Func func1 = func; + func2 = func; + u003cu003e9_5 = func1; + } + return strs.Any(u003cu003e9_5); + }); + }); + IOrderedEnumerable dataImportacao = + from x in criticaApolices + orderby x.get_DataImportacao() + select x; + observableCollection.CriticaFiltrada = new ObservableCollection(dataImportacao.ThenByDescending((CriticaApolice x) => x.get_Documento().get_Controle().get_Cliente().get_Nome())); + } + await this.SelecionaCritica(this.CriticaFiltrada.FirstOrDefault()); + this.EnableGrid = true; + } + + public async Task>> SalvarCliente() + { + List> keyValuePairs; + List> keyValuePairs1; + Cliente cliente; + CriticaApoliceViewModel.u003cu003ec__DisplayClass132_0 variable; + List> keyValuePairs2; + List> keyValuePairs3; + if (!this.HasChange && !this.SelectedCliente.HasChange()) + { + ObservableCollection telefones = this.Telefones; + if (telefones.All((ClienteTelefone x) => !x.HasChange())) + { + ObservableCollection emails = this.Emails; + if (emails.All((ClienteEmail x) => !x.HasChange())) + { + keyValuePairs = null; + variable = null; + return keyValuePairs; + } + } + } + ObservableCollection observableCollection = this.Telefones; + List list = ( + from x in observableCollection + where !string.IsNullOrEmpty(x.get_Numero()) + select x).ToList(); + ObservableCollection emails1 = this.Emails; + List clienteEmails = ( + from x in emails1 + where !string.IsNullOrEmpty(x.get_Email()) + select x).ToList(); + this.SelectedCliente.set_Telefones(new ObservableCollection(list)); + this.SelectedCliente.set_Emails(new ObservableCollection(clienteEmails)); + TipoDocumento? documentoPrincipal = this.SelectedCliente.get_DocumentoPrincipal(); + if (documentoPrincipal.HasValue) + { + TipoDocumento valueOrDefault = documentoPrincipal.GetValueOrDefault(); + if (valueOrDefault == 1) + { + this.SelectedCliente.set_Rne(this.DocumentoPrincipal); + keyValuePairs3 = this.SelectedCliente.Validate(); + list.ForEach((ClienteTelefone x) => keyValuePairs3.AddRange(x.Validate())); + clienteEmails.ForEach((ClienteEmail x) => keyValuePairs3.AddRange(x.Validate())); + keyValuePairs2 = keyValuePairs3; + keyValuePairs1 = await this.Validate(); + keyValuePairs2.AddRange(keyValuePairs1); + keyValuePairs2 = null; + if (keyValuePairs3.Count <= 0) + { + cliente = await this._clienteServico.Save(this.SelectedCliente, false); + keyValuePairs = null; + } + else + { + keyValuePairs = keyValuePairs3; + } + variable = null; + return keyValuePairs; + } + else + { + if (valueOrDefault != 2) + { + goto Label2; + } + this.SelectedCliente.set_Cei(this.DocumentoPrincipal); + keyValuePairs3 = this.SelectedCliente.Validate(); + list.ForEach((ClienteTelefone x) => keyValuePairs3.AddRange(x.Validate())); + clienteEmails.ForEach((ClienteEmail x) => keyValuePairs3.AddRange(x.Validate())); + keyValuePairs2 = keyValuePairs3; + keyValuePairs1 = await this.Validate(); + keyValuePairs2.AddRange(keyValuePairs1); + keyValuePairs2 = null; + if (keyValuePairs3.Count <= 0) + { + cliente = await this._clienteServico.Save(this.SelectedCliente, false); + keyValuePairs = null; + } + else + { + keyValuePairs = keyValuePairs3; + } + variable = null; + return keyValuePairs; + } + } + Label2: + this.SelectedCliente.set_Documento(this.DocumentoPrincipal); + keyValuePairs3 = this.SelectedCliente.Validate(); + list.ForEach((ClienteTelefone x) => keyValuePairs3.AddRange(x.Validate())); + clienteEmails.ForEach((ClienteEmail x) => keyValuePairs3.AddRange(x.Validate())); + keyValuePairs2 = keyValuePairs3; + keyValuePairs1 = await this.Validate(); + keyValuePairs2.AddRange(keyValuePairs1); + keyValuePairs2 = null; + if (keyValuePairs3.Count <= 0) + { + cliente = await this._clienteServico.Save(this.SelectedCliente, false); + keyValuePairs = null; + } + else + { + keyValuePairs = keyValuePairs3; + } + variable = null; + return keyValuePairs; + } + + public async Task SelecionaCliente(Cliente cliente) + { + DateTime? nullable; + TipoDocumento? documentoPrincipal = cliente.get_DocumentoPrincipal(); + if (documentoPrincipal.HasValue) + { + TipoDocumento valueOrDefault = documentoPrincipal.GetValueOrDefault(); + if (valueOrDefault == 1) + { + this.DocumentoPrincipal = cliente.get_Rne(); + goto Label0; + } + else + { + if (valueOrDefault != 2) + { + goto Label1; + } + this.DocumentoPrincipal = cliente.get_Cei(); + goto Label0; + } + } + Label1: + this.DocumentoPrincipal = cliente.get_Documento(); + cliente.set_DocumentoPrincipal(new TipoDocumento?(0)); + Label0: + CriticaApoliceViewModel criticaApoliceViewModel = this; + nullable = (cliente == null || !cliente.get_Nascimento().HasValue ? new DateTime?(Funcoes.GetNetworkTime().Date) : cliente.get_Nascimento()); + criticaApoliceViewModel.NascimentoCritica = nullable; + this.SelectedCliente = cliente; + this.SelectedCliente.Initialize(); + this.Telefones = await this._clienteServico.BuscarTelefonesAsync(this.SelectedCliente.get_Id()); + if (this.Telefones.Count == 0) + { + ObservableCollection telefones = this.Telefones; + ClienteTelefone clienteTelefone = new ClienteTelefone(); + clienteTelefone.set_Cliente(this.SelectedCliente); + telefones.Add(clienteTelefone); + } + List list = this.Telefones.ToList(); + list.ForEach((ClienteTelefone x) => x.Initialize()); + this.Emails = await this._clienteServico.BuscarEmailsAsync(this.SelectedCliente.get_Id()); + if (this.Emails.Count == 0) + { + ObservableCollection emails = this.Emails; + ClienteEmail clienteEmail = new ClienteEmail(); + clienteEmail.set_Cliente(this.SelectedCliente); + emails.Add(clienteEmail); + } + List clienteEmails = this.Emails.ToList(); + clienteEmails.ForEach((ClienteEmail x) => x.Initialize()); + } + + public async Task SelecionaCritica(CriticaApolice critica) + { + DateTime networkTime; + DateTime? nullable; + DateTime? remessa; + TipoSeguro? nullable1; + if (critica != null && !this.IsLoading) + { + this.IsLoading = true; + base.Loading(true); + CriticaApolice criticaApolouse = critica; + Documento documento = await this.Servico.BuscarApoliceAsync(critica.get_Documento().get_Id(), false, false); + criticaApolouse.set_Documento(documento); + criticaApolouse = null; + base.SelectedDocumento = null; + base.Repasses = null; + base.Parcelas = null; + base.Pagamentos = null; + base.SelectedParcela = null; + base.SelectedPagamento = null; + this.SelectedCritica = critica; + await base.SelecionaDocumento(critica.get_Documento()); + CriticaApoliceViewModel criticaApoliceViewModel = this; + if (critica.get_Documento() == null || !critica.get_Documento().get_Emissao().HasValue) + { + networkTime = Funcoes.GetNetworkTime(); + nullable = new DateTime?(networkTime.Date); + } + else + { + nullable = critica.get_Documento().get_Emissao(); + } + criticaApoliceViewModel.EmissaoCritica = nullable; + CriticaApoliceViewModel criticaApoliceViewModel1 = this; + if (critica.get_Documento() == null || !critica.get_Documento().get_Remessa().HasValue) + { + networkTime = Funcoes.GetNetworkTime(); + remessa = new DateTime?(networkTime.Date); + } + else + { + remessa = critica.get_Documento().get_Remessa(); + } + criticaApoliceViewModel1.TransmissaoCritica = remessa; + CriticaApoliceViewModel criticaApoliceViewModel2 = this; + List configuracoes = Recursos.Configuracoes; + if (configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 3)) + { + nullable1 = new TipoSeguro?(base.SelectedDocumento.get_Situacao()); + } + else + { + nullable1 = null; + } + criticaApoliceViewModel2.StatusDocumento = nullable1; + if (base.SelectedDocumento != null) + { + TipoRecebimento? tipoRecebimento = base.SelectedDocumento.get_TipoRecebimento(); + this.IsParcela = tipoRecebimento.GetValueOrDefault() == 1; + await this.SelecionaCliente(base.SelectedDocumento.get_Controle().get_Cliente()); + await this.SelecionaItens(base.SelectedDocumento.get_Controle().get_Id()); + this.HasChange = false; + base.Loading(false); + this.IsLoading = false; + } + else + { + this.IsParcela = true; + this.HasChange = false; + base.Loading(false); + } + } + } + + public async Task SelecionaItens(long id) + { + this.Itens = await this._itemServico.BuscarItens(id, 0); + } + + public async Task SelecionaUsuario() + { + this.IsLoading = true; + List configuracoes = Recursos.Configuracoes; + if (configuracoes.Any((ConfiguracaoSistema x) => { + if (x.get_Configuracao() == 38) + { + return true; + } + return x.get_Configuracao() == 43; + }) && Recursos.Usuario.get_Id() != 0) + { + this.Vinculos = await base.VerificaVinculoVendedor(Recursos.Usuario); + } + this.IsLoading = false; + } + + private async Task>> Validate() + { + List clientes; + List> keyValuePairs = new List>(); + bool flag = !string.IsNullOrEmpty(this.SelectedCliente.get_Nome()); + TipoDocumento? documentoPrincipal = this.SelectedCliente.get_DocumentoPrincipal(); + if (documentoPrincipal.HasValue) + { + switch (documentoPrincipal.GetValueOrDefault()) + { + case 0: + { + if (ValidationHelper.ValidateDocument(this.SelectedCliente.get_Documento())) + { + break; + } + flag = false; + break; + } + case 1: + { + if (ValidationHelper.ValidateRne(this.SelectedCliente.get_Rne())) + { + break; + } + flag = false; + break; + } + case 2: + { + if (ValidationHelper.ValidateCei(this.SelectedCliente.get_Cei())) + { + break; + } + flag = false; + break; + } + } + } + if (!ValidationHelper.ValidateDocument(this.SelectedCliente.get_Documento())) + { + clientes = new List(); + } + else + { + clientes = await (new ClienteServico()).BuscarClientePorDocumento(this.SelectedCliente.get_Documento()); + } + List clientes1 = clientes; + string nome = ""; + if (clientes1.Count > 0) + { + clientes1.ForEach((Cliente x) => { + if (x.get_Id() == this.SelectedCliente.get_Id()) + { + return; + } + if (this.SelectedCliente.get_IdEmpresa() != x.get_IdEmpresa()) + { + return; + } + if (!string.IsNullOrEmpty(this.SelectedCliente.get_Documento()) && x.get_Documento() == this.SelectedCliente.get_Documento()) + { + flag = false; + nome = x.get_Nome(); + } + }); + } + if (!flag) + { + keyValuePairs.Add(new KeyValuePair("Documento", string.Concat("O DOCUMENTO JÁ ESTÁ CADASTRADO PARA O CLIENTE ", nome, "."))); + } + if (this.SelectedCliente.get_Telefones() == null || this.SelectedCliente.get_Telefones().Count == 0) + { + keyValuePairs.Add(new KeyValuePair("Telefones", "NECESSITA-SE AO MENOS UM TELEFONE VÁLIDO.")); + } + List configuracoes = Recursos.Configuracoes; + if (configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 29) && (this.SelectedCliente.get_Emails() == null || this.SelectedCliente.get_Emails().Count == 0)) + { + keyValuePairs.Add(new KeyValuePair("Emails", "NECESSITA-SE AO MENOS UM E-MAIL VÁLIDO.")); + } + List> keyValuePairs1 = keyValuePairs; + keyValuePairs = null; + return keyValuePairs1; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/AeronauticoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/AeronauticoViewModel.cs new file mode 100644 index 0000000..ded661f --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/AeronauticoViewModel.cs @@ -0,0 +1,554 @@ +using Gestor.Application.Actions; +using Gestor.Application.Componentes; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Seguros.Itens +{ + public class AeronauticoViewModel : ItemViewModel, IDisposable + { + private readonly ItemServico _itemServico; + + private readonly AeronauticoServico _servico; + + private bool _allowAlterarExcluir = true; + + private object _cobertura; + + private string _codigoItem; + + private Item _selectedItem = new Item(); + + private bool _aero = true; + + private string _serie = "REGISTRO"; + + private string _prefixo = "PREFIXO"; + + private string _marinaAero = "AERÓDROMO"; + + public bool Aero + { + get + { + return this._aero; + } + set + { + this._aero = value; + base.OnPropertyChanged("Aero"); + } + } + + public bool AllowAlterarExcluir + { + get + { + return this._allowAlterarExcluir; + } + set + { + this._allowAlterarExcluir = value; + base.OnPropertyChanged("AllowAlterarExcluir"); + } + } + + public object Cobertura + { + get + { + return this._cobertura; + } + set + { + this._cobertura = value; + base.OnPropertyChanged("Cobertura"); + } + } + + public string CodigoItem + { + get + { + return this._codigoItem; + } + set + { + this._codigoItem = value; + base.OnPropertyChanged("CodigoItem"); + } + } + + public bool Invoke + { + get; + set; + } + + private Item ItemSelecionado + { + get; + set; + } + + public string MarinaAero + { + get + { + return this._marinaAero; + } + set + { + this._marinaAero = value; + base.OnPropertyChanged("MarinaAero"); + } + } + + public string Prefixo + { + get + { + return this._prefixo; + } + set + { + this._prefixo = value; + base.OnPropertyChanged("Prefixo"); + } + } + + private Gestor.Model.Domain.Seguros.Ramo Ramo + { + get; + } + + public Item SelectedItem + { + get + { + return this._selectedItem; + } + set + { + long? nullable; + this._selectedItem = value; + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedItem"); + } + } + + public string Serie + { + get + { + return this._serie; + } + set + { + this._serie = value; + base.OnPropertyChanged("Serie"); + } + } + + public AeronauticoViewModel(bool substituir = false, ManutencaoItem manutencao = null, Item itemSelecionado = null, Gestor.Model.Domain.Seguros.Ramo ramo = null, bool endossoRenovacao = false) + { + this.Invoke = itemSelecionado == null; + this.ItemSelecionado = itemSelecionado ?? ConsultaViewModel.ItemSelecionado; + this.Ramo = ramo ?? ConsultaViewModel.DocumentoSelecionado.get_Controle().get_Ramo(); + if (this.Invoke) + { + this.ItemSelecionado = this.ItemSelecionado ?? new Item(); + this.ItemSelecionado.set_Documento(ConsultaViewModel.DocumentoSelecionado); + } + this._itemServico = new ItemServico(); + this._servico = new AeronauticoServico(); + this.Seleciona(this.ItemSelecionado); + if (substituir) + { + this.Substituir(this.ItemSelecionado); + } + if (manutencao != null) + { + this.Manter(this.ItemSelecionado, manutencao); + } + this.AllowAlterarExcluir = !endossoRenovacao; + this.CarregaCobertura(); + } + + public async void CancelarAlteracao() + { + base.Loading(true); + await this.SelecionaItem(this.ItemSelecionado, false); + await this.CoberturaViewModel.CancelarAlteracao(); + base.Alterar(false); + base.Loading(false); + } + + public void CarregaCobertura() + { + this.CoberturaViewModel.Item = this.ItemSelecionado; + this.CoberturaViewModel.Ramo = this.Ramo; + this.Cobertura = new CoberturaView(this.CoberturaViewModel); + } + + public void Descarregar() + { + this.Cobertura = null; + } + + public void Dispose() + { + Gestor.Application.Actions.Actions.UpdateItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.UpdateItem, new Action(this.Seleciona)); + Gestor.Application.Actions.Actions.SubstituirItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.SubstituirItem, new Action(this.Substituir)); + Gestor.Application.Actions.Actions.ManterItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.ManterItem, new Action(this.Manter)); + } + + public async Task Excluir() + { + bool flag; + if (this.SelectedItem == null || this.SelectedItem.get_Id() == 0) + { + flag = false; + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + base.Loading(true); + bool flag1 = await this._servico.Delete(this.SelectedItem); + base.Loading(false); + if (flag1) + { + string str = string.Concat("EXCLUIU ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + base.ToggleSnackBar(string.Concat(this.Ramo.get_Nome(), " EXCLUÍDO COM SUCESSO"), true); + flag = true; + } + else + { + await base.ShowMessage("NÃO POSSÍVEL EXCLUIR O ITEM", "OK", "", false); + flag = false; + } + } + else + { + flag = false; + } + return flag; + } + + public async Task Incluir(bool substituir = false) + { + int? ordem; + List coberturas; + long? nullable; + coberturas = (this.CoberturaViewModel.Coberturas == null ? this.CoberturaViewModel.CarregaCoberturaPadrao().ToList() : this.CoberturaViewModel.Coberturas.ToList()); + List coberturas1 = coberturas; + Item item = new Item(); + item.set_Documento(this.ItemSelecionado.get_Documento()); + Item item1 = item; + ordem = (substituir ? base.ItemSubstituido.get_Ordem() : new int?(await base.QuantidadeDeItens(this.ItemSelecionado.get_Documento().get_Controle().get_Id()))); + item1.set_Ordem(ordem); + Item item2 = item; + Aeronautico aeronautico = new Aeronautico(); + aeronautico.set_Tipo(1); + item2.set_Aeronautico(aeronautico); + Item item3 = item; + if (substituir) + { + nullable = new long?(base.ItemSubstituido.get_Id()); + } + else + { + nullable = null; + } + item3.set_Substituicao(nullable); + Item item4 = item; + item1 = null; + item = null; + ordem = item4.get_Ordem(); + if (ordem.GetValueOrDefault() == 2) + { + if (!await base.ShowMessage("ESTA APÓLICE SERÁ UMA FROTA, DESEJA CONTINUAR?", "SIM", "NÃO", false)) + { + coberturas1 = null; + item4 = null; + return; + } + } + bool valueOrDefault = substituir; + if (valueOrDefault) + { + valueOrDefault = await base.ShowMessage("DESEJA COPIAR OS DADOS DO ITEM?", "SIM", "NÃO", false); + } + if (!valueOrDefault) + { + this.SelectedItem = item4; + this.SelectedItem.get_Aeronautico().set_Item(item4); + } + else + { + this.SelectedItem.set_Id((long)0); + this.SelectedItem.set_Documento(this.ItemSelecionado.get_Documento()); + } + ordem = item4.get_Ordem(); + int num = 1; + valueOrDefault = ordem.GetValueOrDefault() > num & ordem.HasValue; + if (valueOrDefault) + { + valueOrDefault = await base.ShowMessage("DESEJA REPLICAR AS COBERTURAS DO ITEM SELECIONADO?", "SIM", "NÃO", false); + } + if (!valueOrDefault) + { + this.CoberturaViewModel.CarregaPadrao(); + } + else + { + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + coberturas1.ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + if (substituir) + { + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + coberturas1.ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + base.Alterar(true); + coberturas1 = null; + item4 = null; + } + + public void Manter(Item item, ManutencaoItem manutencao) + { + if (manutencao.get_Tipo() == 1) + { + base.ItemSubstituido = item; + } + this.Manter(manutencao); + base.Mantido = true; + } + + public void Manter(ManutencaoItem manutencao) + { + long? nullable; + object list; + ObservableCollection coberturas = this.CoberturaViewModel.Coberturas; + if (coberturas != null) + { + list = coberturas.ToList(); + } + else + { + list = null; + } + this.SelectedItem.set_Id((long)0); + this.SelectedItem.get_Aeronautico().set_Id((long)0); + Item selectedItem = this.SelectedItem; + Item itemSubstituido = base.ItemSubstituido; + if (itemSubstituido != null) + { + nullable = new long?(itemSubstituido.get_Id()); + } + else + { + nullable = null; + } + selectedItem.set_Substituicao(nullable); + this.SelectedItem.set_Documento(this.ItemSelecionado.get_Documento()); + if (manutencao.get_Tipo() == null) + { + this.SelectedItem.set_Sinistrado(false); + this.SelectedItem.set_Status(""); + this.SelectedItem.set_Sinistro(null); + this.SelectedItem.set_Sinistros(null); + } + this.CoberturaViewModel.CarregaPadrao(); + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + if (list != null) + { + ((List)list).ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + else + { + } + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + string str1; + string str2; + string str3; + this.SelectedItem.set_Descricao(string.Format("{0} - FABRICANTE: {1} - MODELO: {2}", this.SelectedItem.get_Aeronautico().get_Tipo(), this.SelectedItem.get_Aeronautico().get_Fabricante(), this.SelectedItem.get_Aeronautico().get_Modelo())); + List> keyValuePairs1 = this.SelectedItem.Validate(); + if (keyValuePairs1.Count <= 0) + { + Item selectedItem = this.SelectedItem; + selectedItem.set_Coberturas(await this.CoberturaViewModel.LimpaCoberturas()); + selectedItem = null; + if (this.SelectedItem.get_Documento().get_Ordem() <= 0) + { + str = ""; + } + else if (base.Mantido) + { + str = string.Format("ITEM ALTERADO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem()); + } + else + { + str = (base.ItemSubstituido != null ? string.Format("SUBSTITUIÇÃO DO ITEM {0} NO ENDOSSO ORDEM {1}", base.ItemSubstituido.get_Ordem(), this.SelectedItem.get_Documento().get_Ordem()) : string.Format("ITEM INCLUÍDO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem())); + } + string str4 = str; + if (this.SelectedItem.get_Id() == 0) + { + this.SelectedItem.set_Status(str4); + } + str1 = (this.SelectedItem.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str3 = str1; + this.SelectedItem = await this._itemServico.Save(this.SelectedItem); + if (this._itemServico.Sucesso) + { + if (base.ItemSubstituido != null) + { + str2 = (base.Mantido ? string.Format("ITEM ALTERADO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem()) : string.Format("ITEM SUBSTITUIDO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem())); + string str5 = str2; + await this._itemServico.Substituir(base.ItemSubstituido, this.SelectedItem.get_Id(), str5); + } + base.Mantido = false; + await this.SelecionaItem(this.SelectedItem, false); + this.ItemSelecionado = this.SelectedItem; + if (this.Invoke) + { + ConsultaViewModel.ItemSelecionado = this.SelectedItem; + } + base.ToggleSnackBar(string.Concat(this.Ramo.get_Nome(), " SALVO COM SUCESSO"), true); + string str6 = string.Concat(str3, " ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str6, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + base.Alterar(false); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str3 = null; + return keyValuePairs; + } + + private async void Seleciona(Item item) + { + base.Loading(true); + await base.PermissaoTela(3); + await this.SelecionaItem(item, true); + base.Loading(false); + } + + public async Task SelecionaItem(Item item, bool registrar = true) + { + if (item == null || this.LastAccessId != item.get_Id() || this.LastAccessTela != 9) + { + base.Mantido = false; + List nums = new List() + { + (long)13 + }; + if (nums.Contains(this.Ramo.get_Id())) + { + this.CoberturaViewModel.Ramo = this.Ramo; + if (this.CoberturaViewModel.CoberturasPadrao == null) + { + await this.CoberturaViewModel.SelectionaCoberturas(); + } + if (item == null || item.get_Id() == 0) + { + this.SelectedItem = null; + this.CoberturaViewModel.Coberturas = null; + base.IsVisible = Visibility.Visible; + } + else + { + base.Loading(true); + item = await this._itemServico.BuscarItemPorIdAsync(item.get_Id()); + Item item1 = item; + Aeronautico aeronautico = await this._itemServico.BuscaAeronautico(item.get_Id()); + item1.set_Aeronautico(aeronautico); + item1 = null; + this.SelectedItem = item; + this.SelectedItem.Initialize(); + this.Initialized = true; + this.CoberturaViewModel.Item = item; + await this.CoberturaViewModel.CancelarAlteracao(); + if (registrar) + { + string str = string.Concat("ACESSOU ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + } + this.LastAccessId = this.SelectedItem.get_Id(); + this.LastAccessTela = 3; + this.CodigoItem = this.SelectedItem.get_Id().ToString(); + base.Loading(false); + } + } + } + } + + public async void Substituir(Item item) + { + base.ItemSubstituido = item; + await this.Incluir(true); + } + + public void UpdateAero() + { + this.Aero = ValidationHelper.GetCategory(this.SelectedItem.get_Aeronautico().get_Tipo()) == "Aero"; + this.Serie = (this.Aero ? "REGISTRO" : "SÉRIE"); + this.Prefixo = (this.Aero ? "PREFIXO" : "NOME"); + this.MarinaAero = (this.Aero ? "AERÓDROMO" : "MARINA"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/AutoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/AutoViewModel.cs new file mode 100644 index 0000000..735d4a7 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/AutoViewModel.cs @@ -0,0 +1,3018 @@ +using ClosedXML.Excel; +using Gestor.Application.Actions; +using Gestor.Application.Componentes; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using Microsoft.CSharp.RuntimeBinder; +using Microsoft.Office.Interop.Excel; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Data; +using System.Diagnostics; +using System.Globalization; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Forms; + +namespace Gestor.Application.ViewModels.Seguros.Itens +{ + public class AutoViewModel : ItemViewModel, IDisposable + { + private readonly ItemServico _itemServico; + + private readonly AutoServico _servico; + + private bool _allowAlterarExcluir = true; + + private Visibility _isVisiblePorcentagemReferencia = Visibility.Collapsed; + + private Visibility _isVisibleValorDeterminado = Visibility.Collapsed; + + private object _cobertura; + + private List _combustivel = ((Gestor.Model.Common.Combustivel[])Enum.GetValues(typeof(Gestor.Model.Common.Combustivel))).OrderBy(new Func((Gestor.Model.Common.Combustivel x) => Gestor.Common.Validation.ValidationHelper.GetCategory(x))).ToList(); + + private Item _selectedItem = new Item(); + + private List _fabricantes; + + private Fabricante _selectedFabricante; + + private string _codigoItem; + + private Gestor.Model.Common.Categoria? _categocia; + + private Gestor.Model.Common.UsoVeiculo? _usoVeiculo; + + public bool AllowAlterarExcluir + { + get + { + return this._allowAlterarExcluir; + } + set + { + this._allowAlterarExcluir = value; + base.OnPropertyChanged("AllowAlterarExcluir"); + } + } + + public Gestor.Model.Common.Categoria? Categoria + { + get + { + return this._categocia; + } + set + { + bool auto; + this._categocia = value; + Item selectedItem = this.SelectedItem; + if (selectedItem != null) + { + auto = selectedItem.get_Auto(); + } + else + { + auto = false; + } + if (auto) + { + this.SelectedItem.get_Auto().set_Categoria(value); + } + base.OnPropertyChanged("Categoria"); + } + } + + public object Cobertura + { + get + { + return this._cobertura; + } + set + { + this._cobertura = value; + base.OnPropertyChanged("Cobertura"); + } + } + + public string CodigoItem + { + get + { + return this._codigoItem; + } + set + { + this._codigoItem = value; + base.OnPropertyChanged("CodigoItem"); + } + } + + public List Combustivel + { + get + { + return this._combustivel; + } + set + { + this._combustivel = value; + base.OnPropertyChanged("Combustivel"); + } + } + + public List Fabricantes + { + get + { + return this._fabricantes; + } + set + { + this._fabricantes = value; + base.OnPropertyChanged("Fabricantes"); + } + } + + public bool Invoke + { + get; + set; + } + + public Visibility IsVisiblePorcentagemReferencia + { + get + { + return this._isVisiblePorcentagemReferencia; + } + set + { + this._isVisiblePorcentagemReferencia = value; + base.OnPropertyChanged("IsVisiblePorcentagemReferencia"); + } + } + + public Visibility IsVisibleValorDeterminado + { + get + { + return this._isVisibleValorDeterminado; + } + set + { + this._isVisibleValorDeterminado = value; + base.OnPropertyChanged("IsVisibleValorDeterminado"); + } + } + + private Item ItemSelecionado + { + get; + set; + } + + private Gestor.Model.Domain.Seguros.Ramo Ramo + { + get; + } + + public Fabricante SelectedFabricante + { + get + { + return this._selectedFabricante; + } + set + { + this._selectedFabricante = value; + base.OnPropertyChanged("SelectedFabricante"); + } + } + + public Item SelectedItem + { + get + { + return this._selectedItem; + } + set + { + long? nullable; + this._selectedItem = value; + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedItem"); + } + } + + public Gestor.Model.Common.UsoVeiculo? UsoVeiculo + { + get + { + return this._usoVeiculo; + } + set + { + bool auto; + if (value.GetValueOrDefault() == 2 || value.GetValueOrDefault() == 3) + { + this.SelectedItem.get_Auto().set_Categoria(new Gestor.Model.Common.Categoria?(3)); + this.Categoria = new Gestor.Model.Common.Categoria?(3); + } + Item selectedItem = this.SelectedItem; + if (selectedItem != null) + { + auto = selectedItem.get_Auto(); + } + else + { + auto = false; + } + if (auto && value.HasValue) + { + this.SelectedItem.get_Auto().set_UsoVeiculo(value); + } + this._usoVeiculo = value; + base.OnPropertyChanged("UsoVeiculo"); + } + } + + public AutoViewModel(bool substituir = false, ManutencaoItem manutencao = null, Item itemSelecionado = null, Gestor.Model.Domain.Seguros.Ramo ramo = null, bool endossoRenovacao = false) + { + this.Invoke = itemSelecionado == null; + this.ItemSelecionado = itemSelecionado ?? ConsultaViewModel.ItemSelecionado; + this.Ramo = ramo ?? ConsultaViewModel.DocumentoSelecionado.get_Controle().get_Ramo(); + if (this.Invoke) + { + this.ItemSelecionado = this.ItemSelecionado ?? new Item(); + this.ItemSelecionado.set_Documento(ConsultaViewModel.DocumentoSelecionado); + } + this._itemServico = new ItemServico(); + this._servico = new AutoServico(); + this.Seleciona(this.ItemSelecionado); + if (substituir) + { + this.Substituir(this.ItemSelecionado); + } + if (manutencao != null) + { + this.Manter(this.ItemSelecionado, manutencao); + } + this.AllowAlterarExcluir = !endossoRenovacao; + this.CarregaCobertura(); + } + + public void Atualiza(string valorSelecionado) + { + if (valorSelecionado == "MERCADO") + { + this.IsVisiblePorcentagemReferencia = Visibility.Visible; + this.IsVisibleValorDeterminado = Visibility.Collapsed; + return; + } + this.IsVisiblePorcentagemReferencia = Visibility.Collapsed; + this.IsVisibleValorDeterminado = Visibility.Visible; + } + + public async void BaixarXls() + { + char chr; + object obj; + object obj1; + object obj2; + object obj3; + object obj4; + object obj5; + object obj6; + object obj7; + object obj8; + object obj9; + object obj10; + object obj11; + object obj12; + object obj13; + object obj14; + object obj15; + object obj16; + object obj17; + object obj18; + object obj19; + object obj20; + object obj21; + object obj22; + object obj23; + object obj24; + object obj25; + object obj26; + object obj27; + object obj28; + object obj29; + object obj30; + object obj31; + object obj32; + object obj33; + object obj34; + object obj35; + object obj36; + object obj37; + object obj38; + object obj39; + object obj40; + object obj41; + object obj42; + object obj43; + object obj44; + object obj45; + object obj46; + object obj47; + object obj48; + object obj49; + object obj50; + object obj51; + object obj52; + object obj53; + object obj54; + object obj55; + object obj56; + object obj57; + object obj58; + object obj59; + object obj60; + object obj61; + object obj62; + object obj63; + object obj64; + object obj65; + object obj66; + object obj67; + object obj68; + object obj69; + object obj70; + object obj71; + object obj72; + using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog()) + { + folderBrowserDialog.SelectedPath = Environment.SpecialFolder.Desktop.ToString(); + if (folderBrowserDialog.ShowDialog() == DialogResult.OK && !string.IsNullOrWhiteSpace(folderBrowserDialog.SelectedPath)) + { + XLWorkbook xLWorkbook = new XLWorkbook(); + DataTable dataTable = new DataTable(); + List strs = new List() + { + "placa", + "fabricante", + "modelo", + "fipe", + "chassi", + "anofabricacao", + "anomodelo", + "cor", + "categoria", + "combustivel", + "zerokm", + "renavam", + "capacidade", + "portas", + "bonus", + "ceppernoite", + "ci", + "financiado", + "correcao", + "isencao", + "pcd", + "cepcirculacao", + "tipocobertura", + "porcentagemreferencia", + "tabelareferencia", + "valordeterminado", + "observacao", + "pr casco", + "fr casco", + "lmi casco", + "obs casco", + "pr dm", + "fr dm", + "lmi dm", + "obs dm", + "pr dc", + "fr dc", + "lmi dc", + "obs dc", + "pr morte", + "fr morte", + "lmi morte", + "obs morte", + "pr invalidez", + "fr invalidez", + "lmi invalidez", + "obs invalidez", + "pr carro reserva", + "fr carro reserva", + "lmi carro reserva", + "obs carro reserva", + "pr vidros", + "fr vidros", + "lmi vidros", + "obs vidros", + "pr carroceria", + "fr carroceria", + "lmi carroceria", + "obs carroceria", + "pr Ass 24Horas", + "fr Ass 24Horas", + "lmi Ass 24Horas", + "obs Ass 24Horas", + "pr Danos Morais", + "fr Danos Morais", + "lmi Danos Morais", + "obs Danos Morais", + "pr app", + "fr app", + "lmi app", + "obs app", + "pr equipamentos", + "fr equipamentos", + "lmi equipamentos", + "obs equipamentos" + }; + List strs1 = strs; + List> lists = new List>(); + List strs2 = new List() + { + "XXX0X00", + "FORD", + "MODELO", + "000000-0", + "75F 8C33MP Y2 W12900", + "2000", + "2001", + "PRETO", + "PASSEIO", + "FLEX", + "SIM", + "00000000000", + "5", + "5", + "100", + "00.000-000", + "000000", + "NÃO", + "MERCADO", + "SEM", + "NÃO", + "00.000-000", + "COMPREENSIVA", + "100", + "FIPE", + "", + "OBSERVAÇÕES", + "1000", + "2000", + "3000", + "teste obs", + "", + "", + "", + "", + "2000", + "3000", + "4000", + "teste obs", + "100000", + "200000", + "300000", + "teste obs", + "2000", + "3000", + "4000", + "teste obs", + "", + "", + "", + "", + "1000", + "2000", + "3000", + "teste obs", + "2000", + "3000", + "4000", + "teste obs", + "", + "", + "", + "", + "1000", + "2000", + "3000", + "teste obs", + "", + "", + "", + "", + "2000", + "3000", + "4000", + "teste obs", + "1000", + "2000", + "3000", + "teste obs" + }; + lists.Add(strs2); + List strs3 = new List() + { + "XXX0X01", + "CHEVROLET", + "MODELO", + "000000-1", + "4EL ZBE75H B5 A65693", + "2000", + "2001", + "VERDE", + "PICKUP", + "GASOLINA/ÁLCOOL/GNV", + "NÃO", + "00000000000", + "5", + "2", + "100", + "00.000-000", + "000000", + "SIM", + "DETERMINADO", + "IPI E ICMS", + "NÃO", + "00.000-000", + "INCÊNDIO E ROUBO/FURTO", + "100", + "MOLICAR", + "19767,34", + "OBSERVAÇÕES", + "1000", + "2000", + "3000", + "teste obs", + "", + "", + "", + "", + "2000", + "3000", + "4000", + "teste obs", + "100000", + "200000", + "300000", + "teste obs", + "2000", + "3000", + "4000", + "teste obs", + "", + "", + "", + "", + "1000", + "2000", + "3000", + "teste obs", + "2000", + "3000", + "4000", + "teste obs", + "", + "", + "", + "", + "1000", + "2000", + "3000", + "teste obs", + "", + "", + "", + "", + "2000", + "3000", + "4000", + "teste obs", + "1000", + "2000", + "3000", + "teste obs" + }; + lists.Add(strs3); + List> lists1 = lists; + List strs4 = new List() + { + "BRANCO", + "CINZA", + "PRATA", + "VERMELHO", + "AMARELO", + "OURO", + "LARANJA", + "ROSA", + "VERDE", + "AZUL", + "VINHO", + "MARROM", + "BEGE", + "DOURADO", + "OUTROS" + }; + List strs5 = strs4; + List strs6 = new List() + { + "PICKUP", + "OUTROS", + "PASSEIO", + "CAMINHÃO", + "CAMINHONETE", + "ÔNIBUS", + "UTILITÁRIO", + "CARGA", + "MOTOCICLETA", + "TAXI", + "UBER", + "REBOCADOR", + "REBOQUE/SEMI REBOQUE" + }; + List strs7 = strs6; + List strs8 = new List() + { + "ÁLCOOL", + "GASOLINA", + "DIESEL", + "FLEX", + "GNV", + "OUTROS", + "GASOLINA/GNV", + "GASOLINA/ÁLCOOL/GNV", + "GASOLINA/ELÉTRICO", + "HÍBRIDO", + "ELÉTRICO", + "GASOLINA/ÁLCOOL/ELÉTRICO" + }; + List strs9 = strs8; + List strs10 = new List() + { + "MERCADO", + "DETERMINADO" + }; + List strs11 = new List() + { + "SEM ISENÇÃO", + "ICMS", + "IPI", + "IPI E ICMS" + }; + List strs12 = new List() + { + "COMPREENSIVA", + "INCÊNDIO E ROUBO/FURTO", + "DANOS A TERCEIROS", + "PASSAGEIROS", + "ROUBO/FURTO" + }; + List strs13 = new List() + { + "MOLICAR", + "FIPE" + }; + List strs14 = new List() + { + "SIM", + "NÃO" + }; + foreach (string str in strs1) + { + DataColumn dataColumn = new DataColumn() + { + DataType = Type.GetType("System.String"), + ColumnName = str + }; + dataTable.Columns.Add(dataColumn); + } + foreach (List strs15 in lists1) + { + DataRow item = dataTable.NewRow(); + foreach (string str1 in strs1) + { + item[str1] = strs15[strs1.IndexOf(str1)]; + } + dataTable.Rows.Add(item); + } + xLWorkbook.get_Worksheets().Add(dataTable, "EXEMPLO AUTO EXCEL"); + xLWorkbook.SaveAs(string.Concat(folderBrowserDialog.SelectedPath, "\\EXEMPLO AUTO EXCEL.xlsx")); + xLWorkbook = new XLWorkbook(); + dataTable = new DataTable(); + foreach (string str2 in strs1) + { + DataColumn dataColumn1 = new DataColumn() + { + DataType = Type.GetType("System.String"), + ColumnName = str2 + }; + dataTable.Columns.Add(dataColumn1); + } + foreach (string str3 in strs5) + { + DataRow dataRow = dataTable.NewRow(); + Label2: + foreach (string str4 in strs1) + { + int num = strs5.IndexOf(str3); + if (str4 == null) + { + continue; + } + switch (str4.Length) + { + case 2: + { + if (str4 == "ci") + { + DataRow dataRow1 = dataRow; + string str5 = str4; + obj = (num == 0 ? "000000" : ""); + dataRow1[str5] = obj; + continue; + } + else + { + continue; + } + } + case 3: + { + chr = str4[0]; + if (chr != 'c') + { + if (chr == 'p') + { + if (str4 == "pcd") + { + break; + } + continue; + } + else + { + continue; + } + } + else if (str4 == "cor") + { + DataRow dataRow2 = dataRow; + string str6 = str4; + obj1 = (strs5.Count >= num + 1 ? strs5[num] : ""); + dataRow2[str6] = obj1; + continue; + } + else + { + continue; + } + } + case 4: + { + if (str4 == "fipe") + { + DataRow dataRow3 = dataRow; + string str7 = str4; + obj3 = (num == 0 ? "000000-0" : ""); + dataRow3[str7] = obj3; + continue; + } + else + { + continue; + } + } + case 5: + { + chr = str4[4]; + if (chr > 'c') + { + if (chr != 'm') + { + if (chr != 's') + { + continue; + } + else if (str4 == "bonus") + { + DataRow dataRow4 = dataRow; + string str8 = str4; + obj6 = (num == 0 ? "0" : ""); + dataRow4[str8] = obj6; + continue; + } + else + { + continue; + } + } + else if (str4 == "pr dm") + { + DataRow dataRow5 = dataRow; + string str9 = str4; + obj4 = (num == 0 ? "0" : ""); + dataRow5[str9] = obj4; + continue; + } + else if (str4 == "fr dm") + { + DataRow dataRow6 = dataRow; + string str10 = str4; + obj5 = (num == 0 ? "0" : ""); + dataRow6[str10] = obj5; + continue; + } + else + { + continue; + } + } + else if (chr == 'a') + { + if (str4 == "placa") + { + DataRow dataRow7 = dataRow; + string str11 = str4; + obj7 = (num == 0 ? "XXX0X00" : ""); + dataRow7[str11] = obj7; + continue; + } + else + { + continue; + } + } + else if (chr != 'c') + { + continue; + } + else if (str4 == "pr dc") + { + DataRow dataRow8 = dataRow; + string str12 = str4; + obj8 = (num == 0 ? "0" : ""); + dataRow8[str12] = obj8; + continue; + } + else if (str4 == "fr dc") + { + DataRow dataRow9 = dataRow; + string str13 = str4; + obj9 = (num == 0 ? "0" : ""); + dataRow9[str13] = obj9; + continue; + } + else + { + continue; + } + } + case 6: + { + chr = str4[0]; + if (chr > 'f') + { + switch (chr) + { + case 'l': + { + if (str4 == "lmi dm") + { + DataRow dataRow10 = dataRow; + string str14 = str4; + obj10 = (num == 0 ? "0" : ""); + dataRow10[str14] = obj10; + continue; + } + else if (str4 == "lmi dc") + { + DataRow dataRow11 = dataRow; + string str15 = str4; + obj11 = (num == 0 ? "0" : ""); + dataRow11[str15] = obj11; + continue; + } + else + { + continue; + } + } + case 'm': + { + if (str4 == "modelo") + { + DataRow dataRow12 = dataRow; + string str16 = str4; + obj12 = (num == 0 ? "MODELO" : ""); + dataRow12[str16] = obj12; + continue; + } + else + { + continue; + } + } + case 'n': + { + continue; + } + case 'o': + { + if (str4 == "obs dm") + { + DataRow dataRow13 = dataRow; + string str17 = str4; + obj13 = (num == 0 ? "OBSERVAÇÃO" : ""); + dataRow13[str17] = obj13; + continue; + } + else if (str4 == "obs dc") + { + DataRow dataRow14 = dataRow; + string str18 = str4; + obj14 = (num == 0 ? "OBSERVAÇÃO" : ""); + dataRow14[str18] = obj14; + continue; + } + else + { + continue; + } + } + case 'p': + { + if (str4 == "portas") + { + DataRow dataRow15 = dataRow; + string str19 = str4; + obj15 = (num == 0 ? "00" : ""); + dataRow15[str19] = obj15; + continue; + } + else if (str4 == "pr app") + { + DataRow dataRow16 = dataRow; + string str20 = str4; + obj16 = (num == 0 ? "0" : ""); + dataRow16[str20] = obj16; + continue; + } + else + { + continue; + } + } + default: + { + if (chr == 'z') + { + if (str4 == "zerokm") + { + goto Label0; + } + continue; + } + else + { + continue; + } + } + } + } + else if (chr == 'c') + { + if (str4 == "chassi") + { + DataRow dataRow17 = dataRow; + string str21 = str4; + obj17 = (num == 0 ? "XXX XXXXXX XX XXXXXX" : ""); + dataRow17[str21] = obj17; + continue; + } + else + { + continue; + } + } + else if (chr != 'f') + { + continue; + } + else if (str4 == "fr app") + { + DataRow dataRow18 = dataRow; + string str22 = str4; + obj18 = (num == 0 ? "0" : ""); + dataRow18[str22] = obj18; + continue; + } + else + { + continue; + } + break; + } + case 7: + { + chr = str4[0]; + if (chr <= 'l') + { + if (chr == 'i') + { + if (str4 == "isencao") + { + DataRow dataRow19 = dataRow; + string str23 = str4; + obj21 = (strs11.Count >= num + 1 ? strs11[num] : ""); + dataRow19[str23] = obj21; + continue; + } + else + { + continue; + } + } + else if (chr != 'l') + { + continue; + } + else if (str4 == "lmi app") + { + DataRow dataRow20 = dataRow; + string str24 = str4; + obj22 = (num == 0 ? "0" : ""); + dataRow20[str24] = obj22; + continue; + } + else + { + continue; + } + } + else if (chr == 'o') + { + if (str4 == "obs app") + { + DataRow dataRow21 = dataRow; + string str25 = str4; + obj19 = (num == 0 ? "OBSERVAÇÃO" : ""); + dataRow21[str25] = obj19; + continue; + } + else + { + continue; + } + } + else if (chr != 'r') + { + continue; + } + else if (str4 == "renavam") + { + DataRow dataRow22 = dataRow; + string str26 = str4; + obj20 = (num == 0 ? "00000000000" : ""); + dataRow22[str26] = obj20; + continue; + } + else + { + continue; + } + } + case 8: + { + chr = str4[0]; + if (chr == 'c') + { + if (str4 == "correcao") + { + DataRow dataRow23 = dataRow; + string str27 = str4; + obj23 = (strs10.Count >= num + 1 ? strs10[num] : ""); + dataRow23[str27] = obj23; + continue; + } + else + { + continue; + } + } + else if (chr == 'f') + { + if (str4 == "fr casco") + { + DataRow dataRow24 = dataRow; + string str28 = str4; + obj24 = (num == 0 ? "0" : ""); + dataRow24[str28] = obj24; + continue; + } + else if (str4 == "fr morte") + { + DataRow dataRow25 = dataRow; + string str29 = str4; + obj25 = (num == 0 ? "0" : ""); + dataRow25[str29] = obj25; + continue; + } + else + { + continue; + } + } + else if (chr != 'p') + { + continue; + } + else if (str4 == "pr casco") + { + DataRow dataRow26 = dataRow; + string str30 = str4; + obj26 = (num == 0 ? "0" : ""); + dataRow26[str30] = obj26; + continue; + } + else if (str4 == "pr morte") + { + DataRow dataRow27 = dataRow; + string str31 = str4; + obj27 = (num == 0 ? "0" : ""); + dataRow27[str31] = obj27; + continue; + } + else + { + continue; + } + } + case 9: + { + chr = str4[0]; + if (chr > 'c') + { + if (chr != 'f') + { + switch (chr) + { + case 'l': + { + if (str4 == "lmi casco") + { + DataRow dataRow28 = dataRow; + string str32 = str4; + obj29 = (num == 0 ? "0" : ""); + dataRow28[str32] = obj29; + continue; + } + else if (str4 == "lmi morte") + { + DataRow dataRow29 = dataRow; + string str33 = str4; + obj30 = (num == 0 ? "0" : ""); + dataRow29[str33] = obj30; + continue; + } + else + { + continue; + } + } + case 'o': + { + if (str4 == "obs casco") + { + DataRow dataRow30 = dataRow; + string str34 = str4; + obj31 = (num == 0 ? "OBSERVAÇÃO" : ""); + dataRow30[str34] = obj31; + continue; + } + else if (str4 == "obs morte") + { + DataRow dataRow31 = dataRow; + string str35 = str4; + obj32 = (num == 0 ? "OBSERVAÇÃO" : ""); + dataRow31[str35] = obj32; + continue; + } + else + { + continue; + } + } + case 'p': + { + if (str4 == "pr vidros") + { + DataRow dataRow32 = dataRow; + string str36 = str4; + obj33 = (num == 0 ? "0" : ""); + dataRow32[str36] = obj33; + continue; + } + else + { + continue; + } + } + default: + { + continue; + } + } + } + else if (str4 == "fr vidros") + { + DataRow dataRow33 = dataRow; + string str37 = str4; + obj28 = (num == 0 ? "0" : ""); + dataRow33[str37] = obj28; + continue; + } + else + { + continue; + } + } + else if (chr == 'a') + { + if (str4 == "anomodelo") + { + DataRow dataRow34 = dataRow; + string str38 = str4; + obj34 = (num == 0 ? "0000" : ""); + dataRow34[str38] = obj34; + continue; + } + else + { + continue; + } + } + else if (chr != 'c') + { + continue; + } + else if (str4 == "categoria") + { + DataRow dataRow35 = dataRow; + string str39 = str4; + obj35 = (strs7.Count >= num + 1 ? strs7[num] : ""); + dataRow35[str39] = obj35; + continue; + } + else + { + continue; + } + break; + } + case 10: + { + chr = str4[2]; + if (chr <= 'i') + { + if (chr == 'b') + { + if (str4 == "fabricante") + { + DataRow dataRow36 = dataRow; + string str40 = str4; + obj39 = (num == 0 ? "FABRICANTE" : ""); + dataRow36[str40] = obj39; + continue; + } + else + { + continue; + } + } + else if (chr != 'i') + { + continue; + } + else if (str4 == "lmi vidros") + { + DataRow dataRow37 = dataRow; + string str41 = str4; + obj40 = (num == 0 ? "0" : ""); + dataRow37[str41] = obj40; + continue; + } + else + { + continue; + } + } + else if (chr == 'n') + { + if (str4 == "financiado") + { + break; + } + continue; + } + else if (chr == 'p') + { + if (str4 == "capacidade") + { + DataRow dataRow38 = dataRow; + string str42 = str4; + obj36 = (num == 0 ? "000" : ""); + dataRow38[str42] = obj36; + continue; + } + else + { + continue; + } + } + else if (chr != 's') + { + continue; + } + else if (str4 == "observacao") + { + DataRow dataRow39 = dataRow; + string str43 = str4; + obj37 = (num == 0 ? "OBSERVAÇÕES" : ""); + dataRow39[str43] = obj37; + continue; + } + else if (str4 == "obs vidros") + { + DataRow dataRow40 = dataRow; + string str44 = str4; + obj38 = (num == 0 ? "OBSERVAÇÃO" : ""); + dataRow40[str44] = obj38; + continue; + } + else + { + continue; + } + } + case 11: + { + chr = str4[1]; + if (chr == 'e') + { + if (str4 == "ceppernoite") + { + DataRow dataRow41 = dataRow; + string str45 = str4; + obj41 = (num == 0 ? "00.000-000" : ""); + dataRow41[str45] = obj41; + continue; + } + else + { + continue; + } + } + else if (chr != 'o') + { + continue; + } + else if (str4 == "combustivel") + { + DataRow dataRow42 = dataRow; + string str46 = str4; + obj42 = (strs9.Count >= num + 1 ? strs9[num] : ""); + dataRow42[str46] = obj42; + continue; + } + else + { + continue; + } + } + case 12: + { + chr = str4[0]; + if (chr == 'f') + { + if (str4 == "fr invalidez") + { + DataRow dataRow43 = dataRow; + string str47 = str4; + obj43 = (num == 0 ? "0" : ""); + dataRow43[str47] = obj43; + continue; + } + else + { + continue; + } + } + else if (chr != 'p') + { + continue; + } + else if (str4 == "pr invalidez") + { + DataRow dataRow44 = dataRow; + string str48 = str4; + obj44 = (num == 0 ? "0" : ""); + dataRow44[str48] = obj44; + continue; + } + else + { + continue; + } + } + case 13: + { + chr = str4[0]; + if (chr > 'c') + { + if (chr != 'f') + { + switch (chr) + { + case 'l': + { + if (str4 == "lmi invalidez") + { + DataRow dataRow45 = dataRow; + string str49 = str4; + obj46 = (num == 0 ? "0" : ""); + dataRow45[str49] = obj46; + continue; + } + else + { + continue; + } + } + case 'm': + case 'n': + { + continue; + } + case 'o': + { + if (str4 == "obs invalidez") + { + DataRow dataRow46 = dataRow; + string str50 = str4; + obj47 = (num == 0 ? "OBSERVAÇÃO" : ""); + dataRow46[str50] = obj47; + continue; + } + else + { + continue; + } + } + case 'p': + { + if (str4 == "pr carroceria") + { + DataRow dataRow47 = dataRow; + string str51 = str4; + obj48 = (num == 0 ? "0" : ""); + dataRow47[str51] = obj48; + continue; + } + else + { + continue; + } + } + default: + { + if (chr == 't') + { + break; + } + else + { + goto Label2; + } + } + } + if (str4 == "tipocobertura") + { + DataRow dataRow48 = dataRow; + string str52 = str4; + obj49 = (strs12.Count >= num + 1 ? strs12[num] : ""); + dataRow48[str52] = obj49; + continue; + } + else + { + continue; + } + } + else if (str4 == "fr carroceria") + { + DataRow dataRow49 = dataRow; + string str53 = str4; + obj45 = (num == 0 ? "0" : ""); + dataRow49[str53] = obj45; + continue; + } + else + { + continue; + } + } + else if (chr == 'a') + { + if (str4 == "anofabricacao") + { + DataRow dataRow50 = dataRow; + string str54 = str4; + obj50 = (num == 0 ? "0000" : ""); + dataRow50[str54] = obj50; + continue; + } + else + { + continue; + } + } + else if (chr != 'c') + { + continue; + } + else if (str4 == "cepcirculacao") + { + DataRow dataRow51 = dataRow; + string str55 = str4; + obj51 = (num == 0 ? "00.000-000" : ""); + dataRow51[str55] = obj51; + continue; + } + else + { + continue; + } + } + case 14: + { + chr = str4[0]; + if (chr != 'f') + { + switch (chr) + { + case 'l': + { + if (str4 == "lmi carroceria") + { + DataRow dataRow52 = dataRow; + string str56 = str4; + obj53 = (num == 0 ? "0" : ""); + dataRow52[str56] = obj53; + continue; + } + else + { + continue; + } + } + case 'o': + { + if (str4 == "obs carroceria") + { + DataRow dataRow53 = dataRow; + string str57 = str4; + obj54 = (num == 0 ? "OBSERVAÇÃO" : ""); + dataRow53[str57] = obj54; + continue; + } + else + { + continue; + } + } + case 'p': + { + if (str4 == "pr Ass 24Horas") + { + DataRow dataRow54 = dataRow; + string str58 = str4; + obj55 = (num == 0 ? "0" : ""); + dataRow54[str58] = obj55; + continue; + } + else + { + continue; + } + } + default: + { + continue; + } + } + } + else if (str4 == "fr Ass 24Horas") + { + DataRow dataRow55 = dataRow; + string str59 = str4; + obj52 = (num == 0 ? "0" : ""); + dataRow55[str59] = obj52; + continue; + } + else + { + continue; + } + break; + } + case 15: + { + chr = str4[0]; + if (chr != 'f') + { + switch (chr) + { + case 'l': + { + if (str4 == "lmi Ass 24Horas") + { + DataRow dataRow56 = dataRow; + string str60 = str4; + obj58 = (num == 0 ? "0" : ""); + dataRow56[str60] = obj58; + continue; + } + else + { + continue; + } + } + case 'o': + { + if (str4 == "obs Ass 24Horas") + { + DataRow dataRow57 = dataRow; + string str61 = str4; + obj59 = (num == 0 ? "OBSERVAÇÃO" : ""); + dataRow57[str61] = obj59; + continue; + } + else + { + continue; + } + } + case 'p': + { + if (str4 == "pr Danos Morais") + { + DataRow dataRow58 = dataRow; + string str62 = str4; + obj60 = (num == 0 ? "0" : ""); + dataRow58[str62] = obj60; + continue; + } + else if (str4 == "pr equipamentos") + { + DataRow dataRow59 = dataRow; + string str63 = str4; + obj61 = (num == 0 ? "0" : ""); + dataRow59[str63] = obj61; + continue; + } + else + { + continue; + } + } + default: + { + continue; + } + } + } + else if (str4 == "fr Danos Morais") + { + DataRow dataRow60 = dataRow; + string str64 = str4; + obj56 = (num == 0 ? "0" : ""); + dataRow60[str64] = obj56; + continue; + } + else if (str4 == "fr equipamentos") + { + DataRow dataRow61 = dataRow; + string str65 = str4; + obj57 = (num == 0 ? "0" : ""); + dataRow61[str65] = obj57; + continue; + } + else + { + continue; + } + break; + } + case 16: + { + chr = str4[0]; + if (chr <= 'p') + { + if (chr != 'f') + { + switch (chr) + { + case 'l': + { + if (str4 == "lmi Danos Morais") + { + DataRow dataRow62 = dataRow; + string str66 = str4; + obj65 = (num == 0 ? "0" : ""); + dataRow62[str66] = obj65; + continue; + } + else if (str4 == "lmi equipamentos") + { + DataRow dataRow63 = dataRow; + string str67 = str4; + obj66 = (num == 0 ? "0" : ""); + dataRow63[str67] = obj66; + continue; + } + else + { + continue; + } + } + case 'o': + { + if (str4 == "obs Danos Morais") + { + DataRow dataRow64 = dataRow; + string str68 = str4; + obj67 = (num == 0 ? "OBSERVAÇÃO" : ""); + dataRow64[str68] = obj67; + continue; + } + else if (str4 == "obs equipamentos") + { + DataRow dataRow65 = dataRow; + string str69 = str4; + obj68 = (num == 0 ? "OBSERVAÇÃO" : ""); + dataRow65[str69] = obj68; + continue; + } + else + { + continue; + } + } + case 'p': + { + if (str4 == "pr carro reserva") + { + DataRow dataRow66 = dataRow; + string str70 = str4; + obj69 = (num == 0 ? "0" : ""); + dataRow66[str70] = obj69; + continue; + } + else + { + continue; + } + } + default: + { + continue; + } + } + } + else if (str4 == "fr carro reserva") + { + DataRow dataRow67 = dataRow; + string str71 = str4; + obj64 = (num == 0 ? "0" : ""); + dataRow67[str71] = obj64; + continue; + } + else + { + continue; + } + } + else if (chr == 't') + { + if (str4 == "tabelareferencia") + { + DataRow dataRow68 = dataRow; + string str72 = str4; + obj62 = (strs13.Count >= num + 1 ? strs13[num] : ""); + dataRow68[str72] = obj62; + continue; + } + else + { + continue; + } + } + else if (chr != 'v') + { + continue; + } + else if (str4 == "valordeterminado") + { + DataRow dataRow69 = dataRow; + string str73 = str4; + obj63 = (num == 0 ? "000000" : ""); + dataRow69[str73] = obj63; + continue; + } + else + { + continue; + } + break; + } + case 17: + { + chr = str4[0]; + if (chr == 'l') + { + if (str4 == "lmi carro reserva") + { + DataRow dataRow70 = dataRow; + string str74 = str4; + obj70 = (num == 0 ? "0" : ""); + dataRow70[str74] = obj70; + continue; + } + else + { + continue; + } + } + else if (chr != 'o') + { + continue; + } + else if (str4 == "obs carro reserva") + { + DataRow dataRow71 = dataRow; + string str75 = str4; + obj71 = (num == 0 ? "OBSERVAÇÃO" : ""); + dataRow71[str75] = obj71; + continue; + } + else + { + continue; + } + } + case 21: + { + if (str4 == "porcentagemreferencia") + { + DataRow dataRow72 = dataRow; + string str76 = str4; + obj72 = (num == 0 ? "000" : ""); + dataRow72[str76] = obj72; + continue; + } + else + { + continue; + } + } + default: + { + continue; + } + } + Label0: + DataRow dataRow73 = dataRow; + string str77 = str4; + obj2 = (strs14.Count >= num + 1 ? strs14[num] : ""); + dataRow73[str77] = obj2; + } + dataTable.Rows.Add(dataRow); + } + xLWorkbook.get_Worksheets().Add(dataTable, "VALORES PERMITIDOS AUTO EXCEL"); + xLWorkbook.SaveAs(string.Concat(folderBrowserDialog.SelectedPath, "\\VALORES PERMITIDOS AUTO EXCEL.xlsx")); + } + await base.ShowMessage(string.Concat("\"EXEMPLO AUTO EXCEL.xlsx\" E \"VALORES PERMITIDOS AUTO EXCEL.xlsx\"\nFORAM SALVOS EM \"", folderBrowserDialog.SelectedPath, "\""), "OK", "", false); + } + folderBrowserDialog = null; + return; + goto Label2; + } + + public async Task BuscaModelo(string fipe) + { + return await this._itemServico.BuscarModelo(fipe); + } + + public async void CancelarAlteracao() + { + base.Loading(true); + await this.SelecionaItem(this.ItemSelecionado, false); + await this.CoberturaViewModel.CancelarAlteracao(); + base.Alterar(false); + base.Loading(false); + } + + public void CarregaCobertura() + { + this.CoberturaViewModel.Item = this.ItemSelecionado; + this.CoberturaViewModel.Ramo = this.Ramo; + this.Cobertura = new CoberturaView(this.CoberturaViewModel); + } + + public List Coberturas(DataRow row) + { + char chr; + List coberturas = new List(); + foreach (DataColumn column in row.Table.Columns) + { + if (!Regex.IsMatch(column.ColumnName, "pr .+")) + { + continue; + } + string value = Regex.Match(column.ColumnName, "pr (.+)").Groups[1].Value; + if (value != "casco" && value != "dm" && value != "dc" && value != "morte" && value != "invalidez" && value != "carro reserva" && value != "vidros" && value != "carroceria" && value != "ass 24horas" && value != "danos morais" && value != "app" && value != "equipamentos") + { + continue; + } + int num = 0; + string str = ""; + if (value != null) + { + switch (value.Length) + { + case 2: + { + chr = value[1]; + if (chr == 'c') + { + if (value == "dc") + { + num = 3; + str = "Danos Corporais"; + break; + } + else + { + break; + } + } + else if (chr != 'm') + { + break; + } + else if (value == "dm") + { + num = 2; + str = "Danos Materiais"; + break; + } + else + { + break; + } + } + case 3: + { + if (value == "app") + { + num = 53; + str = "Acidentes Pessoais"; + break; + } + else + { + break; + } + } + case 5: + { + chr = value[0]; + if (chr == 'c') + { + if (value == "casco") + { + num = 1; + str = "Veiculo (Casco)"; + break; + } + else + { + break; + } + } + else if (chr != 'm') + { + break; + } + else if (value == "morte") + { + num = 4; + str = "Morte"; + break; + } + else + { + break; + } + } + case 6: + { + if (value == "vidros") + { + num = 6; + str = "Vidros"; + break; + } + else + { + break; + } + } + case 9: + { + if (value == "invalidez") + { + num = 5; + str = "Invalidez"; + break; + } + else + { + break; + } + } + case 10: + { + if (value == "carroceria") + { + num = 25; + str = "Carroceria"; + break; + } + else + { + break; + } + } + case 11: + { + if (value == "ass 24horas") + { + num = 19; + str = "Assistência (Guincho)"; + break; + } + else + { + break; + } + } + case 12: + { + chr = value[0]; + if (chr == 'd') + { + if (value == "danos morais") + { + num = 17; + str = "Danos Morais"; + break; + } + else + { + break; + } + } + else if (chr != 'e') + { + break; + } + else if (value == "equipamentos") + { + num = 54; + str = "Equipamentos"; + break; + } + else + { + break; + } + } + case 13: + { + if (value == "carro reserva") + { + num = 7; + str = "Carro Reserva"; + break; + } + else + { + break; + } + } + } + } + decimal num1 = (string.IsNullOrWhiteSpace(row.Field(string.Concat("pr ", value)).ToString()) ? decimal.Zero : Gestor.Model.Helper.ValidationHelper.ToDecimal(row.Field(string.Concat("pr ", value)).ToString(), "pt-BR")); + decimal num2 = (string.IsNullOrWhiteSpace(row.Field(string.Concat("lmi ", value)).ToString()) ? decimal.Zero : Gestor.Model.Helper.ValidationHelper.ToDecimal(row.Field(string.Concat("lmi ", value)).ToString(), "pt-BR")); + decimal num3 = (string.IsNullOrWhiteSpace(row.Field(string.Concat("fr ", value)).ToString()) ? decimal.Zero : Gestor.Model.Helper.ValidationHelper.ToDecimal(row.Field(string.Concat("fr ", value)).ToString(), "pt-BR")); + string str1 = (string.IsNullOrWhiteSpace(row.Field(string.Concat("obs ", value)).ToString()) ? "" : row.Field(string.Concat("obs ", value)).ToString()); + if (!(num2 > decimal.Zero) && !(num3 > decimal.Zero) && !(num1 > decimal.Zero)) + { + continue; + } + Gestor.Model.Domain.Seguros.Cobertura cobertura = new Gestor.Model.Domain.Seguros.Cobertura(); + CoberturaPadrao coberturaPadrao = new CoberturaPadrao(); + coberturaPadrao.set_Id((long)num); + cobertura.set_CoberturaPadrao(coberturaPadrao); + cobertura.set_Observacao(string.Concat(str, " - ", str1)); + cobertura.set_Premio(num1); + cobertura.set_Lmi(num2); + cobertura.set_Franquia(num3); + coberturas.Add(cobertura); + } + return coberturas; + } + + public void Descarregar() + { + this.Cobertura = null; + } + + public void Dispose() + { + Gestor.Application.Actions.Actions.UpdateItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.UpdateItem, new Action(this.Seleciona)); + Gestor.Application.Actions.Actions.SubstituirItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.SubstituirItem, new Action(this.Substituir)); + Gestor.Application.Actions.Actions.ManterItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.ManterItem, new Action(this.Manter)); + } + + public async Task Excluir() + { + bool flag; + if (this.SelectedItem == null || this.SelectedItem.get_Id() == 0) + { + flag = false; + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + base.Loading(true); + bool flag1 = await this._servico.Delete(this.SelectedItem); + base.Loading(false); + if (flag1) + { + string str = string.Concat("EXCLUIU ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + base.ToggleSnackBar(string.Concat(this.Ramo.get_Nome(), " EXCLUÍDO COM SUCESSO"), true); + flag = true; + } + else + { + await base.ShowMessage("NÃO POSSÍVEL EXCLUIR O ITEM", "OK", "", false); + flag = false; + } + } + else + { + flag = false; + } + return flag; + } + + public async Task>> ImportarXls() + { + List> keyValuePairs; + string fileName; + List> keyValuePairs1 = new List>(); + using (OpenFileDialog openFileDialog = new OpenFileDialog()) + { + openFileDialog.Filter = "Excel|*.xls;*.xlsx"; + openFileDialog.InitialDirectory = Environment.SpecialFolder.Desktop.ToString(); + if (DialogResult.OK == openFileDialog.ShowDialog()) + { + fileName = openFileDialog.FileName; + } + else + { + keyValuePairs1.Add(new KeyValuePair("EXCEL", "ERRO AO SELECIONAR DOCUMENTO")); + keyValuePairs = keyValuePairs1; + keyValuePairs1 = null; + return keyValuePairs; + } + } + try + { + List> tasks1 = await Task.Run>>(() => { + string upper; + Microsoft.Office.Interop.Excel.Application variable = (Microsoft.Office.Interop.Excel.Application)Activator.CreateInstance(Marshal.GetTypeFromCLSID(new Guid("00024500-0000-0000-C000-000000000046"))); + Workbook variable1 = variable.Workbooks.Open(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); + List strs = new List() + { + "placa", + "fabricante", + "modelo", + "fipe", + "chassi", + "anofabricacao", + "anomodelo", + "cor", + "categoria", + "combustivel", + "zerokm", + "renavam", + "capacidade", + "portas", + "bonus", + "ceppernoite", + "ci", + "financiado", + "correcao", + "isencao", + "pcd", + "cepcirculacao", + "tipocobertura", + "porcentagemreferencia", + "tabelareferencia", + "valordeterminado", + "observacao", + "usoveiculos" + }; + List dataTables = new List(); + foreach (object worksheet in variable1.Worksheets) + { + DataTable dataTable = new DataTable(); + Microsoft.Office.Interop.Excel.Range usedRange = ((Worksheet)worksheet).UsedRange; + if (AutoViewModel.u003cu003eo__77.u003cu003ep__0 == null) + { + AutoViewModel.u003cu003eo__77.u003cu003ep__0 = CallSite>.Create(Binder.Convert(CSharpBinderFlags.None, typeof(object[,]), typeof(AutoViewModel))); + } + object[,] target = AutoViewModel.u003cu003eo__77.u003cu003ep__0.Target(AutoViewModel.u003cu003eo__77.u003cu003ep__0, usedRange.Value2); + int num1 = 0; + for (int i = 0; i <= usedRange.Columns.Count - 1; i++) + { + if (target[1, i + 1] != null) + { + DataColumn dataColumn = new DataColumn() + { + DataType = Type.GetType("System.String"), + ColumnName = Funcoes.RemoverAcentos(target[1, i + 1].ToString().ToLower()) + }; + dataTable.Columns.Add(dataColumn); + for (int j = 0; j <= usedRange.Rows.Count - 2; j++) + { + object obj = target[j + 2, i + 1]; + string str = obj as string; + if (str != null) + { + upper = Funcoes.RemoverAcentos(str).ToUpper(); + } + else if (!(obj is double)) + { + upper = (!(obj is bool) ? "" : ((bool)obj ? "1" : "0")); + } + else + { + double num2 = (double)obj; + upper = (!num2.ToString(CultureInfo.InvariantCulture).Contains("+") ? num2.ToString(CultureInfo.InvariantCulture) : "."); + } + if (i + num1 != 0) + { + dataTable.Rows[j][i + num1] = upper; + } + else + { + dataTable.Rows.Add(dataTable.NewRow()); + dataTable.Rows[j][i + num1] = upper; + } + } + } + else + { + num1--; + } + } + dataTables.Add(dataTable); + } + variable.Quit(); + List> tasks = new List>(); + foreach (DataTable dataTable1 in dataTables) + { + for (int k = dataTable1.Rows.Count - 1; k >= 0; k--) + { + object[] itemArray = dataTable1.Rows[k].ItemArray; + Func u003cu003e9_772 = AutoViewModel.u003cu003ec.u003cu003e9__77_2; + if (u003cu003e9_772 == null) + { + u003cu003e9_772 = (object item) => string.IsNullOrEmpty((item != null ? item.ToString() : null)); + AutoViewModel.u003cu003ec.u003cu003e9__77_2 = u003cu003e9_772; + } + if (((IEnumerable)itemArray).All(u003cu003e9_772)) + { + dataTable1.Rows.RemoveAt(k); + } + } + tasks.AddRange(dataTable1.AsEnumerable().ToList().Select>(async (DataRow x) => { + decimal num; + bool? nullable; + bool? nullable1; + bool? nullable2; + bool? nullable3; + bool? nullable4; + Item item2 = new Item(); + Item item1 = item2; + Auto auto = new Auto(); + auto.set_Placa((!dataTable1.Columns.Contains("placa") || string.IsNullOrWhiteSpace(x.Field("placa").ToString()) ? null : x.Field("placa").ToString().ToUpper())); + auto.set_AnoFabricacao((!dataTable1.Columns.Contains("anofabricacao") || string.IsNullOrWhiteSpace(x.Field("anofabricacao").ToString()) ? null : (new Regex("[^0-9]")).Replace(x.Field("anofabricacao").ToString(), ""))); + auto.set_AnoModelo((!dataTable1.Columns.Contains("anomodelo") || string.IsNullOrWhiteSpace(x.Field("anomodelo").ToString()) ? null : (new Regex("[^0-9]")).Replace(x.Field("anomodelo").ToString(), ""))); + auto.set_Bonus((!dataTable1.Columns.Contains("bonus") || string.IsNullOrWhiteSpace(x.Field("bonus").ToString()) ? null : new int?(int.Parse((new Regex("[^0-9]")).Replace(x.Field("bonus").ToString(), ""))))); + auto.set_Capacidade((!dataTable1.Columns.Contains("capacidade") || string.IsNullOrWhiteSpace(x.Field("capacidade").ToString()) ? null : (new Regex("[^0-9]")).Replace(x.Field("capacidade").ToString(), ""))); + auto.set_CepPernoite((!dataTable1.Columns.Contains("ceppernoite") || string.IsNullOrWhiteSpace(x.Field("ceppernoite").ToString()) ? Gestor.Common.Validation.ValidationHelper.FormatPostCode((new Regex("[^0-9]")).Replace(x.Field("cepcirculacao").ToString(), "")) : Gestor.Common.Validation.ValidationHelper.FormatPostCode((new Regex("[^0-9]")).Replace(x.Field("ceppernoite").ToString(), "")))); + auto.set_Chassi((!dataTable1.Columns.Contains("chassi") || string.IsNullOrWhiteSpace(x.Field("chassi").ToString()) ? null : x.Field("chassi").ToString())); + auto.set_Ci((!dataTable1.Columns.Contains("ci") || string.IsNullOrWhiteSpace(x.Field("ci").ToString()) ? null : (new Regex("[^0-9]")).Replace(x.Field("ci").ToString(), ""))); + auto.set_Observacao((!dataTable1.Columns.Contains("observacao") || string.IsNullOrWhiteSpace(x.Field("observacao").ToString()) ? null : x.Field("observacao").ToString())); + auto.set_Cor((!dataTable1.Columns.Contains("cor") || string.IsNullOrWhiteSpace(x.Field("cor").ToString()) ? null : Funcoes.GetCor(x.Field("cor").ToString().ToLower()))); + Auto auto1 = auto; + if (!dataTable1.Columns.Contains("financiado") || string.IsNullOrWhiteSpace(x.Field("financiado").ToString())) + { + nullable = null; + nullable1 = nullable; + } + else + { + nullable1 = new bool?(x.Field("financiado").ToString().ToLower() == "sim"); + } + auto1.set_Financiado(nullable1); + Auto auto2 = auto; + if (!dataTable1.Columns.Contains("zerokm") || string.IsNullOrWhiteSpace(x.Field("zerokm").ToString())) + { + nullable = null; + nullable2 = nullable; + } + else + { + nullable2 = new bool?(x.Field("zerokm").ToString().ToLower() == "sim"); + } + auto2.set_ZeroKm(nullable2); + auto.set_Combustivel((!dataTable1.Columns.Contains("combustivel") || string.IsNullOrWhiteSpace(x.Field("combustivel").ToString()) ? null : Funcoes.GetCombustivel(x.Field("combustivel").ToString().ToLower()))); + auto.set_Correcao((!dataTable1.Columns.Contains("correcao") || string.IsNullOrWhiteSpace(x.Field("correcao").ToString()) ? null : Funcoes.GetCorrecao(x.Field("correcao").ToString().ToLower()))); + auto.set_Fabricante((!dataTable1.Columns.Contains("fabricante") || string.IsNullOrWhiteSpace(x.Field("fabricante").ToString()) ? null : await Funcoes.GetFabricante(x.Field("fabricante").ToString().ToLower()))); + auto.set_Fipe((!dataTable1.Columns.Contains("fipe") || string.IsNullOrWhiteSpace(x.Field("fipe").ToString()) ? null : Gestor.Model.Helper.ValidationHelper.FormataFipe((new Regex("[^0-9]")).Replace(x.Field("fipe").ToString(), "")))); + auto.set_Isencao((!dataTable1.Columns.Contains("isencao") || string.IsNullOrWhiteSpace(x.Field("isencao").ToString()) ? null : Funcoes.GetIsencao(x.Field("isencao").ToString().ToLower()))); + auto.set_Modelo((!dataTable1.Columns.Contains("modelo") || string.IsNullOrWhiteSpace(x.Field("modelo").ToString()) ? null : x.Field("modelo").ToString())); + Auto auto3 = auto; + if (!dataTable1.Columns.Contains("pcd") || string.IsNullOrWhiteSpace(x.Field("pcd").ToString())) + { + nullable = null; + nullable3 = nullable; + } + else + { + nullable3 = new bool?(x.Field("pcd").ToString().ToLower() == "sim"); + } + auto3.set_Pcd(nullable3); + auto.set_PorcentagemReferencia((!dataTable1.Columns.Contains("porcentagemreferencia") || string.IsNullOrWhiteSpace(x.Field("porcentagemreferencia").ToString()) ? decimal.Zero : (decimal.TryParse(x.Field("porcentagemreferencia").ToString(), out num) ? decimal.Parse(x.Field("porcentagemreferencia").ToString()) : decimal.Zero))); + auto.set_Portas((!dataTable1.Columns.Contains("portas") || string.IsNullOrWhiteSpace(x.Field("portas").ToString()) ? null : (new Regex("[^0-9]")).Replace(x.Field("portas").ToString(), ""))); + auto.set_RegiaoCirculacao((!dataTable1.Columns.Contains("cepcirculacao") || string.IsNullOrWhiteSpace(x.Field("cepcirculacao").ToString()) ? null : Gestor.Common.Validation.ValidationHelper.FormatPostCode((new Regex("[^0-9]")).Replace(x.Field("cepcirculacao").ToString(), "")))); + auto.set_Renavam((!dataTable1.Columns.Contains("renavam") || string.IsNullOrWhiteSpace(x.Field("renavam").ToString()) ? null : (new Regex("[^0-9]")).Replace(x.Field("renavam").ToString(), ""))); + auto.set_TabelaReferencia((!dataTable1.Columns.Contains("tabelareferencia") || string.IsNullOrWhiteSpace(x.Field("tabelareferencia").ToString()) ? null : Funcoes.GetTabelaReferencia(x.Field("tabelareferencia").ToString().ToLower()))); + auto.set_TipoCobertura((!dataTable1.Columns.Contains("tipocobertura") || string.IsNullOrWhiteSpace(x.Field("tipocobertura").ToString()) ? null : Funcoes.GetTipoCobertura(x.Field("tipocobertura").ToString().ToLower()))); + auto.set_ValorDeterminado((!dataTable1.Columns.Contains("valordeterminado") || string.IsNullOrWhiteSpace(x.Field("valordeterminado").ToString()) || !Gestor.Common.Validation.ValidationHelper.ValidateValor(x.Field("valordeterminado").ToString()) ? decimal.Zero : decimal.Parse(x.Field("valordeterminado").ToString()))); + auto.set_Categoria((!dataTable1.Columns.Contains("categoria") || string.IsNullOrWhiteSpace(x.Field("categoria").ToString()) ? null : Funcoes.GetCategoria(x.Field("categoria").ToString().ToLower()))); + auto.set_UsoVeiculo((!dataTable1.Columns.Contains("usoveiculo") || string.IsNullOrWhiteSpace(x.Field("usoveiculo").ToString()) ? null : Funcoes.GetUsoveiculo(x.Field("usoveiculo").ToString().ToUpper()))); + Auto auto4 = auto; + if (!dataTable1.Columns.Contains("KitGas") || string.IsNullOrWhiteSpace(x.Field("KitGas").ToString())) + { + nullable = null; + nullable4 = nullable; + } + else + { + nullable4 = new bool?(x.Field("KitGas").ToString().ToLower() == "sim"); + } + auto4.set_KitGas(nullable4); + item1.set_Auto(auto); + item2.set_Coberturas(this.Coberturas(x)); + item2.set_Documento(this.ItemSelecionado.get_Documento()); + item2.set_Substituicao(null); + return item2; + }).ToList>()); + } + return tasks; + }); + if (tasks1.Count != 0) + { + Item[] itemArray1 = await Task.WhenAll(tasks1); + keyValuePairs1 = await this.SalvarRange(itemArray1); + } + else + { + keyValuePairs1.Add(new KeyValuePair("EXCEL", "NENHUMA COLUNA FOI ENCONTRADA")); + keyValuePairs = keyValuePairs1; + keyValuePairs1 = null; + return keyValuePairs; + } + } + catch (Exception exception) + { + keyValuePairs1.Add(new KeyValuePair("EXCEL", "FALHA AO IMPORTAR O EXCEL,\nVERIFIQUE SE O ARQUIVO POSSUI ALGUM ERRO")); + } + keyValuePairs = keyValuePairs1; + keyValuePairs1 = null; + return keyValuePairs; + } + + public async Task Incluir(bool substituir = false) + { + int? ordem; + long? nullable; + List coberturas; + long? nullable1; + long? nullable2; + coberturas = (this.CoberturaViewModel.Coberturas == null ? this.CoberturaViewModel.CarregaCoberturaPadrao().ToList() : this.CoberturaViewModel.Coberturas.ToList()); + List coberturas1 = coberturas; + Item item = new Item(); + item.set_Documento(this.ItemSelecionado.get_Documento()); + Item item1 = item; + ordem = (substituir ? base.ItemSubstituido.get_Ordem() : new int?(await base.QuantidadeDeItens(this.ItemSelecionado.get_Documento().get_Controle().get_Id()))); + item1.set_Ordem(ordem); + Item item2 = item; + Auto auto = new Auto(); + auto.set_Isencao(new Isencao?(0)); + auto.set_ZeroKm(new bool?(false)); + auto.set_Financiado(new bool?(false)); + auto.set_UsoVeiculo(new Gestor.Model.Common.UsoVeiculo?(0)); + auto.set_Categoria(new Gestor.Model.Common.Categoria?(3)); + item2.set_Auto(auto); + Item item3 = item; + if (substituir) + { + nullable1 = new long?(base.ItemSubstituido.get_Id()); + } + else + { + nullable = null; + nullable1 = nullable; + } + item3.set_Substituicao(nullable1); + Item item4 = item; + item1 = null; + item = null; + bool valueOrDefault = substituir; + if (valueOrDefault) + { + valueOrDefault = await base.ShowMessage("DESEJA COPIAR OS DADOS DO ITEM?", "SIM", "NÃO", false); + } + if (!valueOrDefault) + { + this.SelectedItem = item4; + this.SelectedItem.get_Auto().set_Item(item4); + this.UsoVeiculo = this.SelectedItem.get_Auto().get_UsoVeiculo(); + this.Categoria = this.SelectedItem.get_Auto().get_Categoria(); + } + else + { + this.SelectedItem.set_Id((long)0); + this.SelectedItem.get_Auto().set_Id((long)0); + Item selectedItem = this.SelectedItem; + Item itemSubstituido = base.ItemSubstituido; + if (itemSubstituido != null) + { + nullable2 = new long?(itemSubstituido.get_Id()); + } + else + { + nullable = null; + nullable2 = nullable; + } + selectedItem.set_Substituicao(nullable2); + this.SelectedItem.set_Documento(this.ItemSelecionado.get_Documento()); + } + ordem = item4.get_Ordem(); + if (ordem.GetValueOrDefault() == 2 && !substituir) + { + if (!await base.ShowMessage("ESTA APÓLICE SERÁ UMA FROTA, DESEJA CONTINUAR?", "SIM", "NÃO", false)) + { + coberturas1 = null; + item4 = null; + return; + } + } + ordem = item4.get_Ordem(); + int num = 1; + valueOrDefault = ordem.GetValueOrDefault() > num & ordem.HasValue; + if (valueOrDefault) + { + valueOrDefault = await base.ShowMessage("DESEJA REPLICAR AS COBERTURAS DO ITEM SELECIONADO?", "SIM", "NÃO", false); + } + if (!valueOrDefault) + { + this.CoberturaViewModel.CarregaPadrao(); + } + else + { + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + coberturas1.ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + if (substituir) + { + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + coberturas1.ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + base.Alterar(true); + coberturas1 = null; + item4 = null; + } + + public void Manter(Item item, ManutencaoItem manutencao) + { + if (manutencao.get_Tipo() == 1) + { + base.ItemSubstituido = item; + } + this.Manter(manutencao); + base.Mantido = true; + } + + public void Manter(ManutencaoItem manutencao) + { + long? nullable; + object list; + ObservableCollection coberturas = this.CoberturaViewModel.Coberturas; + if (coberturas != null) + { + list = coberturas.ToList(); + } + else + { + list = null; + } + this.SelectedItem.set_Id((long)0); + this.SelectedItem.get_Auto().set_Id((long)0); + Item selectedItem = this.SelectedItem; + Item itemSubstituido = base.ItemSubstituido; + if (itemSubstituido != null) + { + nullable = new long?(itemSubstituido.get_Id()); + } + else + { + nullable = null; + } + selectedItem.set_Substituicao(nullable); + this.SelectedItem.set_Documento(this.ItemSelecionado.get_Documento()); + if (manutencao.get_Tipo() == null) + { + this.SelectedItem.set_Sinistrado(false); + this.SelectedItem.set_Status(""); + this.SelectedItem.set_Sinistro(null); + this.SelectedItem.set_Sinistros(null); + } + this.CoberturaViewModel.CarregaPadrao(); + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + if (list != null) + { + ((List)list).ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + else + { + } + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + string descricao; + string str1; + string str2; + string str3; + string str4; + Auto auto = this.SelectedItem.get_Auto(); + str = (!string.IsNullOrEmpty(this.SelectedItem.get_Auto().get_Placa()) ? Gestor.Model.Helper.ValidationHelper.FormataPlaca(this.SelectedItem.get_Auto().get_Placa()) : string.Empty); + auto.set_Placa(str); + Item selectedItem = this.SelectedItem; + string[] modelo = new string[7]; + Fabricante fabricante = this.SelectedItem.get_Auto().get_Fabricante(); + if (fabricante != null) + { + descricao = fabricante.get_Descricao(); + } + else + { + descricao = null; + } + modelo[0] = descricao; + modelo[1] = " "; + modelo[2] = this.SelectedItem.get_Auto().get_Modelo(); + modelo[3] = " / "; + modelo[4] = this.SelectedItem.get_Auto().get_Chassi(); + modelo[5] = " / "; + modelo[6] = this.SelectedItem.get_Auto().get_Placa(); + selectedItem.set_Descricao(string.Concat(modelo)); + Item item = this.SelectedItem; + List configuracoes = Recursos.Configuracoes; + bool flag = configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 18); + List configuracaoSistemas = Recursos.Configuracoes; + List> keyValuePairs1 = item.Validate(flag, configuracaoSistemas.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 27)); + List> keyValuePairs2 = keyValuePairs1; + keyValuePairs2.AddRange(await this.Validate()); + keyValuePairs2 = null; + if (keyValuePairs1.Count <= 0) + { + Item selectedItem1 = this.SelectedItem; + selectedItem1.set_Coberturas(await this.CoberturaViewModel.LimpaCoberturas()); + selectedItem1 = null; + str1 = (this.SelectedItem.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str4 = str1; + if (this.SelectedItem.get_Documento().get_Ordem() <= 0) + { + str2 = ""; + } + else if (base.Mantido) + { + str2 = string.Format("ITEM ALTERADO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem()); + } + else + { + str2 = (base.ItemSubstituido != null ? string.Format("SUBSTITUIÇÃO DO ITEM {0} NO ENDOSSO ORDEM {1}", base.ItemSubstituido.get_Ordem(), this.SelectedItem.get_Documento().get_Ordem()) : string.Format("ITEM INCLUÍDO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem())); + } + string str5 = str2; + if (this.SelectedItem.get_Id() == 0) + { + this.SelectedItem.set_Status(str5); + } + this.SelectedItem = await this._itemServico.Save(this.SelectedItem); + if (this._itemServico.Sucesso) + { + if (base.ItemSubstituido != null) + { + str3 = (base.Mantido ? string.Format("ITEM ALTERADO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem()) : string.Format("ITEM SUBSTITUIDO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem())); + string str6 = str3; + await this._itemServico.Substituir(base.ItemSubstituido, this.SelectedItem.get_Id(), str6); + } + base.Mantido = false; + await this.SelecionaItem(this.SelectedItem, false); + this.ItemSelecionado = this.SelectedItem; + if (this.Invoke) + { + ConsultaViewModel.ItemSelecionado = this.SelectedItem; + } + base.ToggleSnackBar(string.Concat(this.Ramo.get_Nome(), " SALVO COM SUCESSO"), true); + string str7 = string.Concat(str4, " ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str7, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + base.Alterar(false); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + keyValuePairs1 = null; + str4 = null; + return keyValuePairs; + } + + public async Task>> SalvarRange(IEnumerable list) + { + List> keyValuePairs; + string str; + string descricao; + string str1; + string str2; + Item item = null; + Item item1 = new Item(); + List> keyValuePairs1 = new List>(); + int num = await base.QuantidadeDeItens(list.First().get_Documento().get_Controle().get_Id()); + foreach (Item item in list) + { + if (!item.get_Auto().get_Isencao().HasValue) + { + item.get_Auto().set_Isencao(new Isencao?(0)); + } + if (!item.get_Auto().get_ZeroKm().HasValue) + { + item.get_Auto().set_ZeroKm(new bool?(false)); + } + if (!item.get_Auto().get_Financiado().HasValue) + { + item.get_Auto().set_Financiado(new bool?(false)); + } + if (!item.get_Auto().get_UsoVeiculo().HasValue) + { + item.get_Auto().set_UsoVeiculo(new Gestor.Model.Common.UsoVeiculo?(0)); + } + item.set_Ordem(new int?(num)); + num++; + item.get_Auto().set_Item(item); + Auto auto = item.get_Auto(); + str = (!string.IsNullOrEmpty(item.get_Auto().get_Placa()) ? Gestor.Model.Helper.ValidationHelper.FormataPlaca(item.get_Auto().get_Placa()) : string.Empty); + auto.set_Placa(str); + Item item2 = item; + string[] modelo = new string[7]; + Fabricante fabricante = item.get_Auto().get_Fabricante(); + if (fabricante != null) + { + descricao = fabricante.get_Descricao(); + } + else + { + descricao = null; + } + modelo[0] = descricao; + modelo[1] = " "; + modelo[2] = item.get_Auto().get_Modelo(); + modelo[3] = " / "; + modelo[4] = item.get_Auto().get_Chassi(); + modelo[5] = " / "; + modelo[6] = item.get_Auto().get_Placa(); + item2.set_Descricao(string.Concat(modelo)); + Item item3 = item; + List configuracoes = Recursos.Configuracoes; + List> keyValuePairs2 = item3.Validate(configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 18), false); + List> keyValuePairs3 = keyValuePairs2; + keyValuePairs3.AddRange(await this.Validate(item)); + keyValuePairs3 = null; + Item item4 = item; + str1 = (item.get_Documento().get_Ordem() > 0 ? string.Format("ITEM INCLUÍDO NO ENDOSSO ORDEM {0}", item.get_Documento().get_Ordem()) : ""); + item4.set_Status(str1); + if (keyValuePairs2.Count <= 0) + { + continue; + } + keyValuePairs1.Add(new KeyValuePair("", item.get_Descricao())); + keyValuePairs1.AddRange(keyValuePairs2); + keyValuePairs2 = null; + } + if (keyValuePairs1.Count <= 0) + { + foreach (Item item5 in list) + { + str2 = (item5.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + string str3 = str2; + item1 = await this._itemServico.Save(item5); + string str4 = string.Concat(str3, " ITEM DE DESCRIÇÃO \"", item5.get_Descricao(), "\""); + long id = item5.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { item5.get_Id(), item5.get_Documento().get_Id(), item5.get_Documento().get_Controle().get_Ramo().get_Nome(), item5.get_Documento().get_Controle().get_Cliente().get_Nome(), item5.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str4, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + str3 = null; + } + this.SelectedItem = item1; + await this.SelecionaItem(this.SelectedItem, false); + this.ItemSelecionado = this.SelectedItem; + if (this.Invoke) + { + ConsultaViewModel.ItemSelecionado = this.SelectedItem; + } + base.ToggleSnackBar("ITENS SALVOS COM SUCESSO", true); + base.Alterar(false); + keyValuePairs = null; + } + else + { + keyValuePairs = keyValuePairs1; + } + item1 = null; + keyValuePairs1 = null; + return keyValuePairs; + } + + public async void Seleciona(Item item) + { + base.Loading(true); + await base.PermissaoTela(3); + await this.SelecionaItem(item, true); + base.Loading(false); + } + + public async Task SelecionaItem(Item item, bool registrar = true) + { + if (item == null || this.LastAccessId != item.get_Id() || this.LastAccessTela != 9) + { + base.Mantido = false; + this.Fabricantes = Recursos.Fabricantes; + List nums = new List() + { + (long)5, + (long)37 + }; + if (nums.Contains(this.Ramo.get_Id())) + { + this.CoberturaViewModel.Ramo = this.Ramo; + if (this.CoberturaViewModel.CoberturasPadrao == null) + { + await this.CoberturaViewModel.SelectionaCoberturas(); + } + if (item == null || item.get_Id() == 0) + { + this.SelectedItem = null; + this.CoberturaViewModel.Coberturas = null; + base.IsVisible = Visibility.Visible; + } + else + { + base.Loading(true); + item = await this._itemServico.BuscarItemPorIdAsync(item.get_Id()); + Item item1 = item; + Auto auto = await this._itemServico.BuscaAuto(item.get_Id()); + item1.set_Auto(auto); + item1 = null; + this.SelectedItem = item; + this.SelectedItem.Initialize(); + this.Initialized = true; + this.WorkOnSelectedAuto(this.SelectedItem.get_Auto()); + this.CoberturaViewModel.Item = item; + await this.CoberturaViewModel.CancelarAlteracao(); + if (registrar) + { + string str = string.Concat("ACESSOU ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + } + this.LastAccessId = this.SelectedItem.get_Id(); + this.LastAccessTela = 3; + this.CodigoItem = this.SelectedItem.get_Id().ToString(); + this.UsoVeiculo = this.SelectedItem.get_Auto().get_UsoVeiculo(); + this.Categoria = this.SelectedItem.get_Auto().get_Categoria(); + base.Loading(false); + } + } + } + } + + public async void Substituir(Item item) + { + base.ItemSubstituido = item; + await this.Incluir(true); + } + + public async Task>> Validate() + { + List> keyValuePairs; + List> keyValuePairs1 = new List>(); + if (!string.IsNullOrEmpty(this.SelectedItem.get_Auto().get_Chassi())) + { + List configuracoes = Recursos.Configuracoes; + if (!configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 26)) + { + Documento documento = await (new AutoServico()).BuscarAuto(this.SelectedItem.get_Auto().get_Chassi(), this.SelectedItem.get_Auto().get_Id(), this.SelectedItem.get_Documento().get_Vigencia1(), this.SelectedItem.get_Documento().get_Vigencia2(), this.SelectedItem.get_Documento().get_Controle().get_Seguradora().get_Id()); + if (documento == null) + { + keyValuePairs = keyValuePairs1; + } + else if (this.AllowAlterarExcluir || this.SelectedItem.get_Documento().get_Controle().get_Id() != documento.get_Controle().get_Id()) + { + List> keyValuePairs2 = keyValuePairs1; + string[] apolice = new string[] { "CHASSI JÁ CADASTRADO NA APÓLICE ", documento.get_Apolice(), " DO CLIENTE ", documento.get_Controle().get_Cliente().get_Nome(), "." }; + keyValuePairs2.Add(new KeyValuePair("Chassi", string.Concat(apolice))); + keyValuePairs = keyValuePairs1; + } + else + { + keyValuePairs = keyValuePairs1; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + keyValuePairs1 = null; + return keyValuePairs; + } + + public async Task>> Validate(Item item) + { + List> keyValuePairs; + List> keyValuePairs1 = new List>(); + if (!string.IsNullOrEmpty(item.get_Auto().get_Chassi())) + { + List configuracoes = Recursos.Configuracoes; + if (!configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 26)) + { + Documento documento = await (new AutoServico()).BuscarAuto(item.get_Auto().get_Chassi(), item.get_Auto().get_Id(), item.get_Documento().get_Vigencia1(), item.get_Documento().get_Vigencia2(), item.get_Documento().get_Controle().get_Seguradora().get_Id()); + if (documento == null) + { + keyValuePairs = keyValuePairs1; + } + else if (this.AllowAlterarExcluir || item.get_Documento().get_Controle().get_Id() != documento.get_Controle().get_Id()) + { + List> keyValuePairs2 = keyValuePairs1; + string[] apolice = new string[] { "CHASSI JÁ CADASTRADO NA APÓLICE ", documento.get_Apolice(), " DO CLIENTE ", documento.get_Controle().get_Cliente().get_Nome(), "." }; + keyValuePairs2.Add(new KeyValuePair("Chassi", string.Concat(apolice))); + keyValuePairs = keyValuePairs1; + } + else + { + keyValuePairs = keyValuePairs1; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + keyValuePairs1 = null; + return keyValuePairs; + } + + private void WorkOnSelectedAuto(Auto value) + { + if (value == null || value.get_Id() == 0) + { + return; + } + this.SelectedFabricante = this.Fabricantes.FirstOrDefault((Fabricante x) => { + int? nullable; + int id = x.get_Id(); + Fabricante fabricante = value.get_Fabricante(); + if (fabricante != null) + { + nullable = new int?(fabricante.get_Id()); + } + else + { + nullable = null; + } + int? nullable1 = nullable; + return id == nullable1.GetValueOrDefault() & nullable1.HasValue; + }); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/BuscarModeloViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/BuscarModeloViewModel.cs new file mode 100644 index 0000000..b97c9ea --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/BuscarModeloViewModel.cs @@ -0,0 +1,95 @@ +using CsQuery.ExtensionMethods.Internal; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Seguros.Itens +{ + public class BuscarModeloViewModel : BaseSegurosViewModel + { + private Auto _selectedBuscaModelo = new Auto(); + + private ObservableCollection _modelosAutos = new ObservableCollection(); + + private Fipe _resultado = new Fipe(); + + public ObservableCollection ModelosAutos + { + get + { + return this._modelosAutos; + } + set + { + this._modelosAutos = value; + base.OnPropertyChanged("ModelosAutos"); + } + } + + public Fipe Resultado + { + get + { + return this._resultado; + } + set + { + this._resultado = value; + base.OnPropertyChanged("Resultado"); + } + } + + public Auto SelectedBuscaModelo + { + get + { + return this._selectedBuscaModelo; + } + set + { + this._selectedBuscaModelo = value; + base.OnPropertyChanged("SelectedBuscaModelo"); + } + } + + public BuscarModeloViewModel(string modelo, string ano) + { + Auto auto = new Auto(); + auto.set_AnoModelo(ano); + auto.set_Modelo(modelo); + this.SelectedBuscaModelo = auto; + } + + public async void Pesquisar() + { + string modelo = this.SelectedBuscaModelo.get_Modelo(); + int num = ValidationHelper.ToInt(this.SelectedBuscaModelo.get_AnoModelo()); + List list = await (new ItemServico()).BuscarPorModelo(modelo); + if ((this.SelectedBuscaModelo.get_AnoModelo() != null || ExtensionMethods.IsNullOrEmpty(list)) && this.SelectedBuscaModelo.get_Id() != 0) + { + list = list.Where((Fipe x) => { + if (x.get_AnoMinimo() > num) + { + return false; + } + return x.get_AnoMaximo() >= num; + }).ToList(); + this.ModelosAutos = new ObservableCollection(list); + } + else + { + this.ModelosAutos = new ObservableCollection(list); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/ConsorcioViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/ConsorcioViewModel.cs new file mode 100644 index 0000000..0470058 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/ConsorcioViewModel.cs @@ -0,0 +1,520 @@ +using Gestor.Application.Actions; +using Gestor.Application.Componentes; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Seguros.Itens +{ + public class ConsorcioViewModel : ItemViewModel, IDisposable + { + private readonly ItemServico _itemServico; + + private readonly ConsorcioServico _servico; + + private bool _visibilityTitulares; + + private bool _allowAlterarExcluir = true; + + private object _cobertura; + + private object _sinistro; + + private string _codigoItem; + + private Item _selectedItem = new Item(); + + public bool AllowAlterarExcluir + { + get + { + return this._allowAlterarExcluir; + } + set + { + this._allowAlterarExcluir = value; + base.OnPropertyChanged("AllowAlterarExcluir"); + } + } + + public object Cobertura + { + get + { + return this._cobertura; + } + set + { + this._cobertura = value; + base.OnPropertyChanged("Cobertura"); + } + } + + public string CodigoItem + { + get + { + return this._codigoItem; + } + set + { + this._codigoItem = value; + base.OnPropertyChanged("CodigoItem"); + } + } + + public bool Invoke + { + get; + set; + } + + private Item ItemSelecionado + { + get; + set; + } + + private Gestor.Model.Domain.Seguros.Ramo Ramo + { + get; + } + + public Item SelectedItem + { + get + { + return this._selectedItem; + } + set + { + long? nullable; + this._selectedItem = value; + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedItem"); + } + } + + public object Sinistro + { + get + { + return this._sinistro; + } + set + { + this._sinistro = value; + base.OnPropertyChanged("Sinistro"); + } + } + + public bool VisibilityTitulares + { + get + { + return this._visibilityTitulares; + } + set + { + this._visibilityTitulares = value; + base.OnPropertyChanged("VisibilityTitulares"); + } + } + + public ConsorcioViewModel(bool substituir = false, ManutencaoItem manutencao = null, Item itemSelecionado = null, Gestor.Model.Domain.Seguros.Ramo ramo = null, bool endossoRenovacao = false) + { + this.Invoke = itemSelecionado == null; + this.ItemSelecionado = itemSelecionado ?? ConsultaViewModel.ItemSelecionado; + this.Ramo = ramo ?? ConsultaViewModel.DocumentoSelecionado.get_Controle().get_Ramo(); + if (this.Invoke) + { + this.ItemSelecionado = this.ItemSelecionado ?? new Item(); + this.ItemSelecionado.set_Documento(ConsultaViewModel.DocumentoSelecionado); + } + this._itemServico = new ItemServico(); + this._servico = new ConsorcioServico(); + this.Seleciona(this.ItemSelecionado); + if (substituir) + { + this.Substituir(this.ItemSelecionado); + } + if (manutencao != null) + { + this.Manter(this.ItemSelecionado, manutencao); + } + this.AllowAlterarExcluir = !endossoRenovacao; + this.CarregaCobertura(); + this.VisibilityTitulares = this.Ramo.get_Id() == (long)31; + } + + public async void CancelarAlteracao() + { + base.Loading(true); + await this.SelecionaItem(this.ItemSelecionado, false); + await this.CoberturaViewModel.CancelarAlteracao(); + base.Alterar(false); + base.Loading(false); + } + + public void CarregaCobertura() + { + this.CoberturaViewModel.Item = this.ItemSelecionado; + this.CoberturaViewModel.Ramo = this.Ramo; + this.Cobertura = new CoberturaView(this.CoberturaViewModel); + } + + public void Descarregar() + { + this.Cobertura = null; + this.Sinistro = null; + } + + public void Dispose() + { + Gestor.Application.Actions.Actions.UpdateItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.UpdateItem, new Action(this.Seleciona)); + Gestor.Application.Actions.Actions.SubstituirItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.SubstituirItem, new Action(this.Substituir)); + Gestor.Application.Actions.Actions.ManterItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.ManterItem, new Action(this.Manter)); + } + + public async Task Excluir() + { + bool flag; + if (this.SelectedItem == null || this.SelectedItem.get_Id() == 0) + { + flag = false; + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + base.Loading(true); + bool flag1 = await this._servico.Delete(this.SelectedItem); + base.Loading(false); + if (flag1) + { + string str = string.Concat("EXCLUIU ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + base.ToggleSnackBar(string.Concat(this.Ramo.get_Nome(), " EXCLUÍDO COM SUCESSO"), true); + flag = true; + } + else + { + await base.ShowMessage("NÃO POSSÍVEL EXCLUIR O ITEM", "OK", "", false); + flag = false; + } + } + else + { + flag = false; + } + return flag; + } + + public async Task Incluir(bool substituir = false) + { + int? ordem; + List coberturas; + long? nullable; + coberturas = (this.CoberturaViewModel.Coberturas == null ? this.CoberturaViewModel.CarregaCoberturaPadrao().ToList() : this.CoberturaViewModel.Coberturas.ToList()); + List coberturas1 = coberturas; + Item item = new Item(); + item.set_Documento(this.ItemSelecionado.get_Documento()); + Item item1 = item; + ordem = (substituir ? base.ItemSubstituido.get_Ordem() : new int?(await base.QuantidadeDeItens(this.ItemSelecionado.get_Documento().get_Controle().get_Id()))); + item1.set_Ordem(ordem); + item.set_Consorcio(new Consorcio()); + Item item2 = item; + if (substituir) + { + nullable = new long?(base.ItemSubstituido.get_Id()); + } + else + { + nullable = null; + } + item2.set_Substituicao(nullable); + Item item3 = item; + item1 = null; + item = null; + base.Titulares = new ObservableCollection(); + ordem = item3.get_Ordem(); + if (ordem.GetValueOrDefault() == 2) + { + if (!await base.ShowMessage("ESTA APÓLICE SERÁ UMA FROTA, DESEJA CONTINUAR?", "SIM", "NÃO", false)) + { + coberturas1 = null; + item3 = null; + return; + } + } + bool valueOrDefault = substituir; + if (valueOrDefault) + { + valueOrDefault = await base.ShowMessage("DESEJA COPIAR OS DADOS DO ITEM?", "SIM", "NÃO", false); + } + if (!valueOrDefault) + { + this.SelectedItem = item3; + this.SelectedItem.get_Consorcio().set_Item(item3); + } + else + { + this.SelectedItem.set_Id((long)0); + this.SelectedItem.set_Documento(this.ItemSelecionado.get_Documento()); + } + ordem = item3.get_Ordem(); + int num = 1; + valueOrDefault = ordem.GetValueOrDefault() > num & ordem.HasValue; + if (valueOrDefault) + { + valueOrDefault = await base.ShowMessage("DESEJA REPLICAR AS COBERTURAS DO ITEM SELECIONADO?", "SIM", "NÃO", false); + } + if (!valueOrDefault) + { + this.CoberturaViewModel.CarregaPadrao(); + } + else + { + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + coberturas1.ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + if (substituir) + { + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + coberturas1.ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + base.Alterar(true); + coberturas1 = null; + item3 = null; + } + + public void Manter(Item item, ManutencaoItem manutencao) + { + if (manutencao.get_Tipo() == 1) + { + base.ItemSubstituido = item; + } + this.Manter(manutencao); + base.Mantido = true; + } + + public void Manter(ManutencaoItem manutencao) + { + long? nullable; + object list; + ObservableCollection coberturas = this.CoberturaViewModel.Coberturas; + if (coberturas != null) + { + list = coberturas.ToList(); + } + else + { + list = null; + } + this.SelectedItem.set_Id((long)0); + this.SelectedItem.get_Consorcio().set_Id((long)0); + Item selectedItem = this.SelectedItem; + Item itemSubstituido = base.ItemSubstituido; + if (itemSubstituido != null) + { + nullable = new long?(itemSubstituido.get_Id()); + } + else + { + nullable = null; + } + selectedItem.set_Substituicao(nullable); + this.SelectedItem.set_Documento(this.ItemSelecionado.get_Documento()); + if (manutencao.get_Tipo() == null) + { + this.SelectedItem.set_Sinistrado(false); + this.SelectedItem.set_Status(""); + this.SelectedItem.set_Sinistro(null); + this.SelectedItem.set_Sinistros(null); + } + this.CoberturaViewModel.CarregaPadrao(); + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + if (list != null) + { + ((List)list).ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + else + { + } + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + string str1; + string str2; + string str3; + this.SelectedItem.set_Descricao(this.SelectedItem.get_Consorcio().get_BensConsorcio()); + List> keyValuePairs1 = this.SelectedItem.Validate(); + if (keyValuePairs1.Count <= 0) + { + Item selectedItem = this.SelectedItem; + selectedItem.set_Coberturas(await this.CoberturaViewModel.LimpaCoberturas()); + selectedItem = null; + if (this.SelectedItem.get_Documento().get_Ordem() <= 0) + { + str = ""; + } + else if (base.Mantido) + { + str = string.Format("ITEM ALTERADO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem()); + } + else + { + str = (base.ItemSubstituido != null ? string.Format("SUBSTITUIÇÃO DO ITEM {0} NO ENDOSSO ORDEM {1}", base.ItemSubstituido.get_Ordem(), this.SelectedItem.get_Documento().get_Ordem()) : string.Format("ITEM INCLUÍDO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem())); + } + string str4 = str; + if (this.SelectedItem.get_Id() == 0) + { + this.SelectedItem.set_Status(str4); + } + str1 = (this.SelectedItem.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str3 = str1; + this.SelectedItem = await this._itemServico.Save(this.SelectedItem); + if (this._itemServico.Sucesso) + { + if (base.ItemSubstituido != null) + { + str2 = (base.Mantido ? string.Format("ITEM ALTERADO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem()) : string.Format("ITEM SUBSTITUIDO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem())); + string str5 = str2; + await this._itemServico.Substituir(base.ItemSubstituido, this.SelectedItem.get_Id(), str5); + } + base.Mantido = false; + await this.SelecionaItem(this.SelectedItem, false); + this.ItemSelecionado = this.SelectedItem; + if (this.Invoke) + { + ConsultaViewModel.ItemSelecionado = this.SelectedItem; + } + base.ToggleSnackBar(string.Concat(this.Ramo.get_Nome(), " SALVO COM SUCESSO"), true); + string str6 = string.Concat(str3, " ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str6, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + base.Alterar(false); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str3 = null; + return keyValuePairs; + } + + private async void Seleciona(Item item) + { + base.Loading(true); + await base.PermissaoTela(3); + await this.SelecionaItem(item, true); + base.Loading(false); + } + + public async Task SelecionaItem(Item item, bool registrar = true) + { + if (item == null || this.LastAccessId != item.get_Id() || this.LastAccessTela != 9) + { + base.Mantido = false; + this.CoberturaViewModel.Ramo = this.Ramo; + if (this.CoberturaViewModel.CoberturasPadrao == null) + { + await this.CoberturaViewModel.SelectionaCoberturas(); + } + if (item == null || item.get_Id() == 0) + { + this.SelectedItem = null; + this.CoberturaViewModel.Coberturas = null; + base.IsVisible = Visibility.Visible; + base.Titulares = new ObservableCollection(); + } + else + { + base.Loading(true); + item = await this._itemServico.BuscarItemPorIdAsync(item.get_Id()); + Item item1 = item; + Consorcio consorcio = await this._itemServico.BuscaConsorcio(item.get_Id()); + Item item2 = item1; + Consorcio consorcio1 = consorcio; + if (consorcio1 == null) + { + consorcio1 = new Consorcio(); + consorcio1.set_Item(item); + } + item2.set_Consorcio(consorcio1); + item1 = null; + if (this.VisibilityTitulares) + { + await base.CarregarTitulares(item.get_Id()); + } + this.SelectedItem = item; + this.SelectedItem.Initialize(); + this.Initialized = true; + this.CoberturaViewModel.Item = item; + await this.CoberturaViewModel.CancelarAlteracao(); + if (registrar) + { + string str = string.Concat("ACESSOU ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + } + this.LastAccessId = this.SelectedItem.get_Id(); + this.LastAccessTela = 3; + this.CodigoItem = this.SelectedItem.get_Id().ToString(); + base.Loading(false); + } + } + } + + public async void Substituir(Item item) + { + base.ItemSubstituido = item; + await this.Incluir(true); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/GranizoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/GranizoViewModel.cs new file mode 100644 index 0000000..b40ea83 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/GranizoViewModel.cs @@ -0,0 +1,500 @@ +using Gestor.Application.Actions; +using Gestor.Application.Componentes; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Seguros.Itens +{ + public class GranizoViewModel : ItemViewModel, IDisposable + { + private readonly ItemServico _itemServico; + + private readonly GranizoServico _servico; + + private bool _allowAlterarExcluir = true; + + private object _cobertura; + + private string _codigoItem; + + private Item _selectedItem = new Item(); + + private Visibility _visibilityMaisInformacoes = Visibility.Collapsed; + + public bool AllowAlterarExcluir + { + get + { + return this._allowAlterarExcluir; + } + set + { + this._allowAlterarExcluir = value; + base.OnPropertyChanged("AllowAlterarExcluir"); + } + } + + public object Cobertura + { + get + { + return this._cobertura; + } + set + { + this._cobertura = value; + base.OnPropertyChanged("Cobertura"); + } + } + + public string CodigoItem + { + get + { + return this._codigoItem; + } + set + { + this._codigoItem = value; + base.OnPropertyChanged("CodigoItem"); + } + } + + public bool Invoke + { + get; + set; + } + + private Item ItemSelecionado + { + get; + } + + private Gestor.Model.Domain.Seguros.Ramo Ramo + { + get; + } + + public Item SelectedItem + { + get + { + return this._selectedItem; + } + set + { + long? nullable; + this._selectedItem = value; + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedItem"); + } + } + + public Visibility VisibilityMaisInformacoes + { + get + { + return this._visibilityMaisInformacoes; + } + set + { + this._visibilityMaisInformacoes = value; + base.OnPropertyChanged("VisibilityMaisInformacoes"); + } + } + + public GranizoViewModel(bool substituir = false, ManutencaoItem manutencao = null, Item itemSelecionado = null, Gestor.Model.Domain.Seguros.Ramo ramo = null, bool endossoRenovacao = false) + { + this.Invoke = itemSelecionado == null; + this.ItemSelecionado = itemSelecionado ?? ConsultaViewModel.ItemSelecionado; + this.Ramo = ramo ?? ConsultaViewModel.DocumentoSelecionado.get_Controle().get_Ramo(); + if (this.Invoke) + { + this.ItemSelecionado = this.ItemSelecionado ?? new Item(); + this.ItemSelecionado.set_Documento(ConsultaViewModel.DocumentoSelecionado); + } + this._itemServico = new ItemServico(); + this._servico = new GranizoServico(); + this.Seleciona(this.ItemSelecionado); + if (substituir) + { + this.Substituir(this.ItemSelecionado); + } + if (manutencao != null) + { + this.Manter(this.ItemSelecionado, manutencao); + } + this.AllowAlterarExcluir = !endossoRenovacao; + this.CarregaCobertura(); + } + + public async void CancelarAlteracao() + { + base.Loading(true); + await this.SelecionaItem(this.ItemSelecionado, false); + await this.CoberturaViewModel.CancelarAlteracao(); + base.Alterar(false); + base.Loading(false); + } + + public void CarregaCobertura() + { + this.CoberturaViewModel.Item = this.ItemSelecionado; + this.CoberturaViewModel.Ramo = this.Ramo; + this.Cobertura = new CoberturaView(this.CoberturaViewModel); + } + + public void Descarregar() + { + this.Cobertura = null; + } + + public void Dispose() + { + Gestor.Application.Actions.Actions.UpdateItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.UpdateItem, new Action(this.Seleciona)); + Gestor.Application.Actions.Actions.SubstituirItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.SubstituirItem, new Action(this.Substituir)); + Gestor.Application.Actions.Actions.ManterItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.ManterItem, new Action(this.Manter)); + } + + public async Task Excluir() + { + bool flag; + if (this.SelectedItem == null || this.SelectedItem.get_Id() == 0) + { + flag = false; + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + base.Loading(true); + bool flag1 = await this._servico.Delete(this.SelectedItem); + base.Loading(false); + if (flag1) + { + string str = string.Concat("EXCLUIU ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + base.ToggleSnackBar(string.Concat(this.Ramo.get_Nome(), " EXCLUÍDO COM SUCESSO"), true); + flag = true; + } + else + { + await base.ShowMessage("NÃO POSSÍVEL EXCLUIR O ITEM", "OK", "", false); + flag = false; + } + } + else + { + flag = false; + } + return flag; + } + + public async Task IncluirItem(bool substituir = false) + { + int? ordem; + List coberturas; + long? nullable; + coberturas = (this.CoberturaViewModel.Coberturas == null ? this.CoberturaViewModel.CarregaCoberturaPadrao().ToList() : this.CoberturaViewModel.Coberturas.ToList()); + List coberturas1 = coberturas; + Item item = new Item(); + item.set_Documento(this.ItemSelecionado.get_Documento()); + Item item1 = item; + ordem = (substituir ? base.ItemSubstituido.get_Ordem() : new int?(await base.QuantidadeDeItens(this.ItemSelecionado.get_Documento().get_Controle().get_Id()))); + item1.set_Ordem(ordem); + Item item2 = item; + Granizo granizo = new Granizo(); + granizo.set_Item(this.SelectedItem); + item2.set_Granizo(granizo); + Item item3 = item; + if (substituir) + { + nullable = new long?(base.ItemSubstituido.get_Id()); + } + else + { + nullable = null; + } + item3.set_Substituicao(nullable); + Item item4 = item; + item1 = null; + item = null; + ordem = item4.get_Ordem(); + if (ordem.GetValueOrDefault() == 2) + { + if (!await base.ShowMessage("ESTA APÓLICE SERÁ UMA FROTA, DESEJA CONTINUAR?", "SIM", "NÃO", false)) + { + coberturas1 = null; + item4 = null; + return; + } + } + bool valueOrDefault = substituir; + if (valueOrDefault) + { + valueOrDefault = await base.ShowMessage("DESEJA COPIAR OS DADOS DO ITEM?", "SIM", "NÃO", false); + } + if (!valueOrDefault) + { + this.SelectedItem = item4; + this.SelectedItem.get_Granizo().set_Item(item4); + } + else + { + this.SelectedItem.set_Id((long)0); + this.SelectedItem.set_Documento(this.ItemSelecionado.get_Documento()); + } + ordem = item4.get_Ordem(); + int num = 1; + valueOrDefault = ordem.GetValueOrDefault() > num & ordem.HasValue; + if (valueOrDefault) + { + valueOrDefault = await base.ShowMessage("DESEJA REPLICAR AS COBERTURAS DO ITEM SELECIONADO?", "SIM", "NÃO", false); + } + if (!valueOrDefault) + { + this.CoberturaViewModel.CarregaPadrao(); + } + else + { + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + coberturas1.ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + if (substituir) + { + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + coberturas1.ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + base.Alterar(true); + coberturas1 = null; + item4 = null; + } + + public void Manter(Item item, ManutencaoItem manutencao) + { + if (manutencao.get_Tipo() == 1) + { + base.ItemSubstituido = item; + } + this.Manter(manutencao); + base.Mantido = true; + } + + public void Manter(ManutencaoItem manutencao) + { + long? nullable; + object list; + ObservableCollection coberturas = this.CoberturaViewModel.Coberturas; + if (coberturas != null) + { + list = coberturas.ToList(); + } + else + { + list = null; + } + this.SelectedItem.set_Id((long)0); + this.SelectedItem.get_Granizo().set_Id((long)0); + Item selectedItem = this.SelectedItem; + Item itemSubstituido = base.ItemSubstituido; + if (itemSubstituido != null) + { + nullable = new long?(itemSubstituido.get_Id()); + } + else + { + nullable = null; + } + selectedItem.set_Substituicao(nullable); + this.SelectedItem.set_Documento(this.ItemSelecionado.get_Documento()); + if (manutencao.get_Tipo() == null) + { + this.SelectedItem.set_Sinistrado(false); + this.SelectedItem.set_Status(""); + this.SelectedItem.set_Sinistro(null); + this.SelectedItem.set_Sinistros(null); + } + this.CoberturaViewModel.CarregaPadrao(); + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + if (list != null) + { + ((List)list).ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + else + { + } + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + string str1; + string str2; + string str3; + string str4; + Item selectedItem = this.SelectedItem; + string cultura = this.SelectedItem.get_Granizo().get_Cultura(); + string sitio = this.SelectedItem.get_Granizo().get_Sitio(); + str = (ValidationHelper.IsNotNullOrEmpty(this.SelectedItem.get_Granizo().get_Area()) ? "" : string.Concat(" / ", this.SelectedItem.get_Granizo().get_Area())); + selectedItem.set_Descricao(string.Concat(cultura, " ", sitio, str)); + List> keyValuePairs1 = this.SelectedItem.get_Granizo().Validate(); + if (keyValuePairs1.Count <= 0) + { + Item item = this.SelectedItem; + item.set_Coberturas(await this.CoberturaViewModel.LimpaCoberturas()); + item = null; + if (this.SelectedItem.get_Documento().get_Ordem() <= 0) + { + str1 = ""; + } + else if (base.Mantido) + { + str1 = string.Format("ITEM ALTERADO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem()); + } + else + { + str1 = (base.ItemSubstituido != null ? string.Format("SUBSTITUIÇÃO DO ITEM {0} NO ENDOSSO ORDEM {1}", base.ItemSubstituido.get_Ordem(), this.SelectedItem.get_Documento().get_Ordem()) : string.Format("ITEM INCLUÍDO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem())); + } + string str5 = str1; + if (this.SelectedItem.get_Id() == 0) + { + this.SelectedItem.set_Status(str5); + } + str2 = (this.SelectedItem.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str4 = str2; + this.SelectedItem = await this._itemServico.Save(this.SelectedItem); + if (this._itemServico.Sucesso) + { + if (base.ItemSubstituido != null) + { + str3 = (base.Mantido ? string.Format("ITEM ALTERADO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem()) : string.Format("ITEM SUBSTITUIDO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem())); + string str6 = str3; + await this._itemServico.Substituir(base.ItemSubstituido, this.SelectedItem.get_Id(), str6); + } + base.Mantido = false; + await this.SelecionaItem(this.SelectedItem, false); + base.ToggleSnackBar(string.Concat(this.Ramo.get_Nome(), " SALVO COM SUCESSO"), true); + string str7 = string.Concat(str4, " ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str7, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + base.Alterar(false); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str4 = null; + return keyValuePairs; + } + + private async void Seleciona(Item item) + { + base.Loading(true); + await base.PermissaoTela(3); + await this.SelecionaItem(item, true); + base.Loading(false); + } + + public async Task SelecionaItem(Item item, bool registrar = true) + { + if (item == null || this.LastAccessId != item.get_Id() || this.LastAccessTela != 9) + { + base.Mantido = false; + List nums = new List() + { + (long)20 + }; + if (nums.Contains(this.Ramo.get_Id())) + { + this.CoberturaViewModel.Ramo = this.Ramo; + if (this.CoberturaViewModel.CoberturasPadrao == null) + { + await this.CoberturaViewModel.SelectionaCoberturas(); + } + if (item == null || item.get_Id() == 0) + { + this.SelectedItem = null; + this.CoberturaViewModel.Coberturas = null; + base.IsVisible = Visibility.Visible; + } + else + { + base.Loading(true); + item = await this._itemServico.BuscarItemPorIdAsync(item.get_Id()); + Item item1 = item; + Granizo granizo = await this._itemServico.BuscaGranizo(item.get_Id()); + item1.set_Granizo(granizo); + item1 = null; + this.SelectedItem = item; + this.SelectedItem.Initialize(); + this.Initialized = true; + this.CoberturaViewModel.Item = item; + await this.CoberturaViewModel.CancelarAlteracao(); + if (registrar) + { + string str = string.Concat("ACESSOU ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + } + this.LastAccessId = this.SelectedItem.get_Id(); + this.LastAccessTela = 3; + this.CodigoItem = this.SelectedItem.get_Id().ToString(); + base.Loading(false); + } + } + } + } + + public async void Substituir(Item item) + { + base.ItemSubstituido = item; + await this.IncluirItem(true); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/PatrimonialViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/PatrimonialViewModel.cs new file mode 100644 index 0000000..caf28fa --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/PatrimonialViewModel.cs @@ -0,0 +1,678 @@ +using Gestor.Application.Actions; +using Gestor.Application.Componentes; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Seguros.Itens +{ + public class PatrimonialViewModel : ItemViewModel, IDisposable + { + private readonly ItemServico _itemServico; + + private readonly PatrimonialServico _servico; + + private bool _allowAlterarExcluir = true; + + private object _cobertura; + + private string _codigoItem; + + private Item _selectedItem = new Item(); + + private Visibility _visibilityTipoMoradia = Visibility.Collapsed; + + private Visibility _visibilityFianca = Visibility.Collapsed; + + private Visibility _visibilityPatrimonial; + + private string _bensInformacoes = "BENS/INFORMAÇÕES"; + + private string _locatarioTomador1 = "LOCATÁRIO 1:"; + + private string _locatarioTomador2 = "LOCATÁRIO 2:"; + + private string _locatarioTomador3 = "LOCATÁRIO 3:"; + + private Visibility _visibilityDescricao = Visibility.Collapsed; + + public bool AllowAlterarExcluir + { + get + { + return this._allowAlterarExcluir; + } + set + { + this._allowAlterarExcluir = value; + base.OnPropertyChanged("AllowAlterarExcluir"); + } + } + + public string BensInformacoes + { + get + { + return this._bensInformacoes; + } + set + { + this._bensInformacoes = value; + base.OnPropertyChanged("BensInformacoes"); + } + } + + public object Cobertura + { + get + { + return this._cobertura; + } + set + { + this._cobertura = value; + base.OnPropertyChanged("Cobertura"); + } + } + + public string CodigoItem + { + get + { + return this._codigoItem; + } + set + { + this._codigoItem = value; + base.OnPropertyChanged("CodigoItem"); + } + } + + public bool Garantia + { + get; + set; + } + + public bool Invoke + { + get; + set; + } + + private Item ItemSelecionado + { + get; + set; + } + + public string LocatarioTomador1 + { + get + { + return this._locatarioTomador1; + } + set + { + this._locatarioTomador1 = value; + base.OnPropertyChanged("LocatarioTomador1"); + } + } + + public string LocatarioTomador2 + { + get + { + return this._locatarioTomador2; + } + set + { + this._locatarioTomador2 = value; + base.OnPropertyChanged("LocatarioTomador2"); + } + } + + public string LocatarioTomador3 + { + get + { + return this._locatarioTomador3; + } + set + { + this._locatarioTomador3 = value; + base.OnPropertyChanged("LocatarioTomador3"); + } + } + + private Gestor.Model.Domain.Seguros.Ramo Ramo + { + get; + } + + public Item SelectedItem + { + get + { + return this._selectedItem; + } + set + { + long? nullable; + this._selectedItem = value; + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedItem"); + } + } + + public Visibility VisibilityDescricao + { + get + { + return this._visibilityDescricao; + } + set + { + this._visibilityDescricao = value; + base.OnPropertyChanged("VisibilityDescricao"); + } + } + + public Visibility VisibilityFianca + { + get + { + return this._visibilityFianca; + } + set + { + this._visibilityFianca = value; + base.OnPropertyChanged("VisibilityFianca"); + } + } + + public Visibility VisibilityPatrimonial + { + get + { + return this._visibilityPatrimonial; + } + set + { + this._visibilityPatrimonial = value; + base.OnPropertyChanged("VisibilityPatrimonial"); + } + } + + public Visibility VisibilityTipoMoradia + { + get + { + return this._visibilityTipoMoradia; + } + set + { + this._visibilityTipoMoradia = value; + base.OnPropertyChanged("VisibilityTipoMoradia"); + } + } + + public PatrimonialViewModel(bool substituir = false, ManutencaoItem manutencao = null, Item itemSelecionado = null, Gestor.Model.Domain.Seguros.Ramo ramo = null, bool endossoRenovacao = false) + { + this.Invoke = itemSelecionado == null; + this.ItemSelecionado = itemSelecionado ?? ConsultaViewModel.ItemSelecionado; + this.Ramo = ramo ?? ConsultaViewModel.DocumentoSelecionado.get_Controle().get_Ramo(); + if (this.Invoke) + { + this.ItemSelecionado = this.ItemSelecionado ?? new Item(); + this.ItemSelecionado.set_Documento(ConsultaViewModel.DocumentoSelecionado); + } + this._itemServico = new ItemServico(); + this._servico = new PatrimonialServico(); + this.Seleciona(this.ItemSelecionado); + if (substituir) + { + this.Substituir(this.ItemSelecionado); + } + if (manutencao != null) + { + this.Manter(this.ItemSelecionado, manutencao); + } + this.AllowAlterarExcluir = !endossoRenovacao; + this.CarregaCobertura(); + } + + public async void CancelarAlteracao() + { + base.Loading(true); + await this.SelecionaItem(this.ItemSelecionado, false); + await this.CoberturaViewModel.CancelarAlteracao(); + base.Alterar(false); + base.Loading(false); + } + + public void CarregaCobertura() + { + this.CoberturaViewModel.Item = this.ItemSelecionado; + this.CoberturaViewModel.Ramo = this.Ramo; + this.Cobertura = new CoberturaView(this.CoberturaViewModel); + } + + public void Descarregar() + { + this.Cobertura = null; + } + + public void Dispose() + { + Gestor.Application.Actions.Actions.UpdateItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.UpdateItem, new Action(this.Seleciona)); + Gestor.Application.Actions.Actions.SubstituirItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.SubstituirItem, new Action(this.Substituir)); + Gestor.Application.Actions.Actions.ManterItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.ManterItem, new Action(this.Manter)); + } + + public async Task Excluir() + { + bool flag; + if (this.SelectedItem == null || this.SelectedItem.get_Id() == 0) + { + flag = false; + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + base.Loading(true); + bool flag1 = await this._servico.Delete(this.SelectedItem); + base.Loading(false); + if (flag1) + { + string str = string.Concat("EXCLUIU ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + base.ToggleSnackBar(string.Concat(this.Ramo.get_Nome(), " EXCLUÍDO COM SUCESSO"), true); + flag = true; + } + else + { + await base.ShowMessage("NÃO POSSÍVEL EXCLUIR O ITEM", "OK", "", false); + flag = false; + } + } + else + { + flag = false; + } + return flag; + } + + private void HabilitaCamposGarantia() + { + this.VisibilityPatrimonial = (this.Ramo.get_Id() == (long)38 ? Visibility.Collapsed : Visibility.Visible); + this.BensInformacoes = "OBSERVAÇÕES"; + this.LocatarioTomador1 = "TOMADOR 1:"; + this.LocatarioTomador2 = "TOMADOR 2:"; + this.LocatarioTomador3 = "TOMADOR 3:"; + this.VisibilityDescricao = Visibility.Visible; + this.Garantia = true; + } + + public async Task Incluir(bool substituir = false) + { + int? ordem; + List coberturas; + long? nullable; + Patrimonial patrimonial1; + coberturas = (this.CoberturaViewModel.Coberturas == null ? this.CoberturaViewModel.CarregaCoberturaPadrao().ToList() : this.CoberturaViewModel.Coberturas.ToList()); + List coberturas1 = coberturas; + Item item = new Item(); + item.set_Documento(this.ItemSelecionado.get_Documento()); + Item item1 = item; + ordem = (substituir ? base.ItemSubstituido.get_Ordem() : new int?(await base.QuantidadeDeItens(this.ItemSelecionado.get_Documento().get_Controle().get_Id()))); + item1.set_Ordem(ordem); + Item item2 = item; + Patrimonial patrimonial2 = new Patrimonial(); + patrimonial2.set_Item(this.SelectedItem); + item2.set_Patrimonial(patrimonial2); + Item item3 = item; + if (substituir) + { + nullable = new long?(base.ItemSubstituido.get_Id()); + } + else + { + nullable = null; + } + item3.set_Substituicao(nullable); + Item item4 = item; + item1 = null; + item = null; + bool garantia = !this.Garantia; + if (garantia) + { + garantia = await base.ShowMessage("COPIAR OS DADOS DE ENDEREÇO DO CLIENTE?", "SIM", "NÃO", false); + } + if (garantia) + { + ObservableCollection observableCollection = await (new ClienteServico()).BuscarEnderecosAsync(item4.get_Documento().get_Controle().get_Cliente().get_Id()); + if (observableCollection != null && observableCollection.Any()) + { + ObservableCollection observableCollection1 = observableCollection; + IOrderedEnumerable valueOrDefault = + from x in observableCollection1 + orderby x.get_Ordem().GetValueOrDefault() == 1 + select x; + List list = valueOrDefault.Select((ClienteEndereco e) => { + Patrimonial patrimonial = new Patrimonial(); + patrimonial.set_Endereco(e.get_Endereco()); + patrimonial.set_Numero(e.get_Numero()); + patrimonial.set_Complemento(e.get_Complemento()); + patrimonial.set_Bairro(e.get_Bairro()); + patrimonial.set_Cidade(e.get_Cidade()); + patrimonial.set_Estado(e.get_Estado()); + patrimonial.set_Cep(e.get_Cep()); + return patrimonial; + }).ToList(); + Item item5 = item4; + if (list.Any()) + { + patrimonial1 = list.Last(); + } + else + { + patrimonial1 = null; + } + item5.set_Patrimonial(patrimonial1); + } + } + ordem = item4.get_Ordem(); + if (ordem.GetValueOrDefault() == 2) + { + if (!await base.ShowMessage("ESTA APÓLICE SERÁ UMA FROTA, DESEJA CONTINUAR?", "SIM", "NÃO", false)) + { + coberturas1 = null; + item4 = null; + return; + } + } + this.SelectedItem = item4; + this.SelectedItem.get_Patrimonial().set_Item(item4); + ordem = item4.get_Ordem(); + int num = 1; + garantia = ordem.GetValueOrDefault() > num & ordem.HasValue; + if (garantia) + { + garantia = await base.ShowMessage("DESEJA REPLICAR AS COBERTURAS DO ITEM SELECIONADO?", "SIM", "NÃO", false); + } + if (!garantia) + { + this.CoberturaViewModel.CarregaPadrao(); + } + else + { + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + coberturas1.ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + if (substituir) + { + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + coberturas1.ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + base.Alterar(true); + coberturas1 = null; + item4 = null; + } + + public void Manter(Item item, ManutencaoItem manutencao) + { + if (manutencao.get_Tipo() == 1) + { + base.ItemSubstituido = item; + } + this.Manter(manutencao); + base.Mantido = true; + } + + public void Manter(ManutencaoItem manutencao) + { + long? nullable; + object list; + ObservableCollection coberturas = this.CoberturaViewModel.Coberturas; + if (coberturas != null) + { + list = coberturas.ToList(); + } + else + { + list = null; + } + this.SelectedItem.set_Id((long)0); + this.SelectedItem.get_Patrimonial().set_Id((long)0); + Item selectedItem = this.SelectedItem; + Item itemSubstituido = base.ItemSubstituido; + if (itemSubstituido != null) + { + nullable = new long?(itemSubstituido.get_Id()); + } + else + { + nullable = null; + } + selectedItem.set_Substituicao(nullable); + this.SelectedItem.set_Documento(this.ItemSelecionado.get_Documento()); + if (manutencao.get_Tipo() == null) + { + this.SelectedItem.set_Sinistrado(false); + this.SelectedItem.set_Status(""); + this.SelectedItem.set_Sinistro(null); + this.SelectedItem.set_Sinistros(null); + } + this.CoberturaViewModel.CarregaPadrao(); + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + if (list != null) + { + ((List)list).ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + else + { + } + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string descricao; + string str; + string str1; + string str2; + string str3; + Item selectedItem = this.SelectedItem; + if (this.VisibilityPatrimonial == Visibility.Visible) + { + string[] endereco = new string[] { this.SelectedItem.get_Patrimonial().get_Endereco(), ", ", this.SelectedItem.get_Patrimonial().get_Numero(), " - ", this.SelectedItem.get_Patrimonial().get_Complemento(), " - ", this.SelectedItem.get_Patrimonial().get_Bairro(), ", ", this.SelectedItem.get_Patrimonial().get_Cidade(), " / ", this.SelectedItem.get_Patrimonial().get_Estado() }; + descricao = string.Concat(endereco); + } + else + { + descricao = this.SelectedItem.get_Descricao(); + } + selectedItem.set_Descricao(descricao); + List> keyValuePairs1 = this.SelectedItem.Validate(); + if (keyValuePairs1.Count <= 0) + { + Item item = this.SelectedItem; + item.set_Coberturas(await this.CoberturaViewModel.LimpaCoberturas()); + item = null; + if (this.SelectedItem.get_Documento().get_Ordem() <= 0) + { + str = ""; + } + else if (base.Mantido) + { + str = string.Format("ITEM ALTERADO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem()); + } + else + { + str = (base.ItemSubstituido != null ? string.Format("SUBSTITUIÇÃO DO ITEM {0} NO ENDOSSO ORDEM {1}", base.ItemSubstituido.get_Ordem(), this.SelectedItem.get_Documento().get_Ordem()) : string.Format("ITEM INCLUÍDO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem())); + } + string str4 = str; + if (this.SelectedItem.get_Id() == 0) + { + this.SelectedItem.set_Status(str4); + } + str1 = (this.SelectedItem.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str3 = str1; + this.SelectedItem = await this._itemServico.Save(this.SelectedItem); + if (this._itemServico.Sucesso) + { + if (base.ItemSubstituido != null) + { + str2 = (base.Mantido ? string.Format("ITEM ALTERADO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem()) : string.Format("ITEM SUBSTITUIDO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem())); + string str5 = str2; + await this._itemServico.Substituir(base.ItemSubstituido, this.SelectedItem.get_Id(), str5); + } + base.Mantido = false; + await this.SelecionaItem(this.SelectedItem, false); + this.ItemSelecionado = this.SelectedItem; + if (this.Invoke) + { + ConsultaViewModel.ItemSelecionado = this.SelectedItem; + } + base.ToggleSnackBar(string.Concat(this.Ramo.get_Nome(), " SALVO COM SUCESSO"), true); + string str6 = string.Concat(str3, " ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str6, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + base.Alterar(false); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str3 = null; + return keyValuePairs; + } + + private async void Seleciona(Item item) + { + base.Loading(true); + await base.PermissaoTela(3); + await this.SelecionaItem(item, true); + base.Loading(false); + } + + public async Task SelecionaItem(Item item, bool registrar = true) + { + Visibility visibility; + Visibility visibility1; + if (item == null || this.LastAccessId != item.get_Id() || this.LastAccessTela != 9) + { + base.Mantido = false; + List nums = new List() + { + (long)1, + (long)2, + (long)3, + (long)15, + (long)18, + (long)30, + (long)38 + }; + if (nums.Contains(this.Ramo.get_Id())) + { + PatrimonialViewModel patrimonialViewModel = this; + visibility = (this.Ramo.get_Id() == (long)1 ? Visibility.Visible : Visibility.Collapsed); + patrimonialViewModel.VisibilityTipoMoradia = visibility; + this.CoberturaViewModel.Ramo = this.Ramo; + if (this.CoberturaViewModel.CoberturasPadrao == null) + { + await this.CoberturaViewModel.SelectionaCoberturas(); + } + PatrimonialViewModel patrimonialViewModel1 = this; + visibility1 = (this.Ramo.get_Id() == (long)15 || this.Ramo.get_Id() == (long)38 ? Visibility.Visible : Visibility.Collapsed); + patrimonialViewModel1.VisibilityFianca = visibility1; + if (this.Ramo.get_Id() == (long)38) + { + this.HabilitaCamposGarantia(); + } + if (item == null || item.get_Id() == 0) + { + this.SelectedItem = null; + this.CoberturaViewModel.Coberturas = null; + base.IsVisible = Visibility.Visible; + } + else + { + base.Loading(true); + item = await this._itemServico.BuscarItemPorIdAsync(item.get_Id()); + Item item1 = item; + Patrimonial patrimonial = await this._itemServico.BuscaPatrimonial(item.get_Id()); + item1.set_Patrimonial(patrimonial); + item1 = null; + this.SelectedItem = item; + this.SelectedItem.Initialize(); + this.Initialized = true; + this.CoberturaViewModel.Item = item; + await this.CoberturaViewModel.CancelarAlteracao(); + if (registrar) + { + string str = string.Concat("ACESSOU ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + } + this.LastAccessId = this.SelectedItem.get_Id(); + this.LastAccessTela = 3; + this.CodigoItem = this.SelectedItem.get_Id().ToString(); + base.Loading(false); + } + } + } + } + + public async void Substituir(Item item) + { + base.ItemSubstituido = item; + await this.Incluir(true); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/RiscosDiversosViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/RiscosDiversosViewModel.cs new file mode 100644 index 0000000..7469ac9 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/RiscosDiversosViewModel.cs @@ -0,0 +1,626 @@ +using Gestor.Application.Actions; +using Gestor.Application.Componentes; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Seguros.Itens +{ + public class RiscosDiversosViewModel : ItemViewModel, IDisposable + { + private readonly ItemServico _itemServico; + + private readonly RiscosDiversosServico _servico; + + private bool _visibilityTitulares; + + private bool _allowAlterarExcluir = true; + + private object _cobertura; + + private object _sinistro; + + private string _codigoItem; + + private Item _selectedItem = new Item(); + + public Visibility _visibilityMultRisco { get; set; } = Visibility.Collapsed; + + public bool AllowAlterarExcluir + { + get + { + return this._allowAlterarExcluir; + } + set + { + this._allowAlterarExcluir = value; + base.OnPropertyChanged("AllowAlterarExcluir"); + } + } + + public object Cobertura + { + get + { + return this._cobertura; + } + set + { + this._cobertura = value; + base.OnPropertyChanged("Cobertura"); + } + } + + public string CodigoItem + { + get + { + return this._codigoItem; + } + set + { + this._codigoItem = value; + base.OnPropertyChanged("CodigoItem"); + } + } + + public bool Invoke + { + get; + set; + } + + private Item ItemSelecionado + { + get; + set; + } + + private Gestor.Model.Domain.Seguros.Ramo Ramo + { + get; + } + + public Item SelectedItem + { + get + { + return this._selectedItem; + } + set + { + long? nullable; + this._selectedItem = value; + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedItem"); + } + } + + public object Sinistro + { + get + { + return this._sinistro; + } + set + { + this._sinistro = value; + base.OnPropertyChanged("Sinistro"); + } + } + + public Visibility VisibilityMultRisco + { + get + { + return this._visibilityMultRisco; + } + set + { + this._visibilityMultRisco = value; + base.OnPropertyChanged("VisibilityMultRisco"); + } + } + + public bool VisibilityTitulares + { + get + { + return this._visibilityTitulares; + } + set + { + this._visibilityTitulares = value; + base.OnPropertyChanged("VisibilityTitulares"); + } + } + + public RiscosDiversosViewModel(bool substituir = false, ManutencaoItem manutencao = null, Item itemSelecionado = null, Gestor.Model.Domain.Seguros.Ramo ramo = null, bool endossoRenovacao = false) + { + this.Invoke = itemSelecionado == null; + this.ItemSelecionado = itemSelecionado ?? ConsultaViewModel.ItemSelecionado; + this.Ramo = ramo ?? ConsultaViewModel.DocumentoSelecionado.get_Controle().get_Ramo(); + if (this.Invoke) + { + this.ItemSelecionado = this.ItemSelecionado ?? new Item(); + this.ItemSelecionado.set_Documento(ConsultaViewModel.DocumentoSelecionado); + } + this._itemServico = new ItemServico(); + this._servico = new RiscosDiversosServico(); + this.Seleciona(this.ItemSelecionado); + if (substituir) + { + this.Substituir(this.ItemSelecionado); + } + if (manutencao != null) + { + this.Manter(this.ItemSelecionado, manutencao); + } + this.AllowAlterarExcluir = !endossoRenovacao; + this.CarregaCobertura(); + this.VisibilityTitulares = this.Ramo.get_Id() == (long)31; + this.VisibilityMultRisco = (this.Ramo.get_Id() == (long)33 ? Visibility.Visible : Visibility.Collapsed); + } + + public async void CancelarAlteracao() + { + base.Loading(true); + await this.SelecionaItem(this.ItemSelecionado, false); + await this.CoberturaViewModel.CancelarAlteracao(); + base.Alterar(false); + base.Loading(false); + } + + public void CarregaCobertura() + { + this.CoberturaViewModel.Item = this.ItemSelecionado; + this.CoberturaViewModel.Ramo = this.Ramo; + this.Cobertura = new CoberturaView(this.CoberturaViewModel); + } + + public void Descarregar() + { + this.Cobertura = null; + this.Sinistro = null; + } + + public void Dispose() + { + Gestor.Application.Actions.Actions.UpdateItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.UpdateItem, new Action(this.Seleciona)); + Gestor.Application.Actions.Actions.SubstituirItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.SubstituirItem, new Action(this.Substituir)); + Gestor.Application.Actions.Actions.ManterItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.ManterItem, new Action(this.Manter)); + } + + public async Task Excluir() + { + bool flag; + if (this.SelectedItem == null || this.SelectedItem.get_Id() == 0) + { + flag = false; + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + base.Loading(true); + bool flag1 = await this._servico.Delete(this.SelectedItem); + base.Loading(false); + if (flag1) + { + string str = string.Concat("EXCLUIU ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + base.ToggleSnackBar(string.Concat(this.Ramo.get_Nome(), " EXCLUÍDO COM SUCESSO"), true); + flag = true; + } + else + { + await base.ShowMessage("NÃO POSSÍVEL EXCLUIR O ITEM", "OK", "", false); + flag = false; + } + } + else + { + flag = false; + } + return flag; + } + + public async Task Incluir(bool substituir = false) + { + int? ordem; + List coberturas; + long? nullable; + coberturas = (this.CoberturaViewModel.Coberturas == null ? this.CoberturaViewModel.CarregaCoberturaPadrao().ToList() : this.CoberturaViewModel.Coberturas.ToList()); + List coberturas1 = coberturas; + Item item = new Item(); + item.set_Documento(this.ItemSelecionado.get_Documento()); + Item item1 = item; + ordem = (substituir ? base.ItemSubstituido.get_Ordem() : new int?(await base.QuantidadeDeItens(this.ItemSelecionado.get_Documento().get_Controle().get_Id()))); + item1.set_Ordem(ordem); + item.set_RiscosDiversos(new RiscosDiversos()); + Item item2 = item; + if (substituir) + { + nullable = new long?(base.ItemSubstituido.get_Id()); + } + else + { + nullable = null; + } + item2.set_Substituicao(nullable); + Item item3 = item; + item1 = null; + item = null; + base.Titulares = new ObservableCollection(); + ordem = item3.get_Ordem(); + if (ordem.GetValueOrDefault() == 2) + { + if (!await base.ShowMessage("ESTA APÓLICE SERÁ UMA FROTA, DESEJA CONTINUAR?", "SIM", "NÃO", false)) + { + coberturas1 = null; + item3 = null; + return; + } + } + bool valueOrDefault = substituir; + if (valueOrDefault) + { + valueOrDefault = await base.ShowMessage("DESEJA COPIAR OS DADOS DO ITEM?", "SIM", "NÃO", false); + } + if (!valueOrDefault) + { + this.SelectedItem = item3; + this.SelectedItem.get_RiscosDiversos().set_Item(item3); + } + else + { + this.SelectedItem.set_Id((long)0); + this.SelectedItem.set_Documento(this.ItemSelecionado.get_Documento()); + } + ordem = item3.get_Ordem(); + int num = 1; + valueOrDefault = ordem.GetValueOrDefault() > num & ordem.HasValue; + if (valueOrDefault) + { + valueOrDefault = await base.ShowMessage("DESEJA REPLICAR AS COBERTURAS DO ITEM SELECIONADO?", "SIM", "NÃO", false); + } + if (!valueOrDefault) + { + this.CoberturaViewModel.CarregaPadrao(); + } + else + { + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + coberturas1.ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + if (substituir) + { + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + coberturas1.ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + base.Alterar(true); + coberturas1 = null; + item3 = null; + } + + public void Manter(Item item, ManutencaoItem manutencao) + { + if (manutencao.get_Tipo() == 1) + { + base.ItemSubstituido = item; + } + this.Manter(manutencao); + base.Mantido = true; + } + + public void Manter(ManutencaoItem manutencao) + { + long? nullable; + object list; + ObservableCollection coberturas = this.CoberturaViewModel.Coberturas; + if (coberturas != null) + { + list = coberturas.ToList(); + } + else + { + list = null; + } + this.SelectedItem.set_Id((long)0); + this.SelectedItem.get_RiscosDiversos().set_Id((long)0); + Item selectedItem = this.SelectedItem; + Item itemSubstituido = base.ItemSubstituido; + if (itemSubstituido != null) + { + nullable = new long?(itemSubstituido.get_Id()); + } + else + { + nullable = null; + } + selectedItem.set_Substituicao(nullable); + this.SelectedItem.set_Documento(this.ItemSelecionado.get_Documento()); + if (manutencao.get_Tipo() == null) + { + this.SelectedItem.set_Sinistrado(false); + this.SelectedItem.set_Status(""); + this.SelectedItem.set_Sinistro(null); + this.SelectedItem.set_Sinistros(null); + } + this.CoberturaViewModel.CarregaPadrao(); + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + if (list != null) + { + ((List)list).ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + else + { + } + base.Alterar(true); + } + + public async Task>> Salvar(List titularesGrid) + { + List> keyValuePairs; + string str; + string str1; + string str2; + bool flag; + bool flag1; + bool flag2; + string str3; + if (this.VisibilityTitulares) + { + this.SelectedItem.set_Titulares(titularesGrid); + } + List> keyValuePairs1 = this.SelectedItem.Validate(); + if (keyValuePairs1.Count <= 0) + { + Item selectedItem = this.SelectedItem; + selectedItem.set_Coberturas(await this.CoberturaViewModel.LimpaCoberturas()); + selectedItem = null; + if (this.SelectedItem.get_Documento().get_Ordem() <= 0) + { + str = ""; + } + else if (base.Mantido) + { + str = string.Format("ITEM ALTERADO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem()); + } + else + { + str = (base.ItemSubstituido != null ? string.Format("SUBSTITUIÇÃO DO ITEM {0} NO ENDOSSO ORDEM {1}", base.ItemSubstituido.get_Ordem(), this.SelectedItem.get_Documento().get_Ordem()) : string.Format("ITEM INCLUÍDO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem())); + } + string str4 = str; + if (this.SelectedItem.get_Id() == 0) + { + this.SelectedItem.set_Status(str4); + } + if (this.VisibilityTitulares) + { + await this._itemServico.DeleteTitulares(base.ExcluirTitulares); + base.ExcluirTitulares = new List(); + } + str1 = (this.SelectedItem.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str3 = str1; + this.SelectedItem = await this._itemServico.Save(this.SelectedItem); + if (this.VisibilityTitulares) + { + foreach (TitularesVida titularesVida in titularesGrid) + { + titularesVida.set_IdItem(this.SelectedItem.get_Id()); + } + List titularesVidas = new List(); + foreach (TitularesVida titularesVida1 in titularesGrid) + { + if (titularesVida1.get_Id() != 0) + { + TitularesVida titularesVida2 = base.OldTitulares.First((TitularesVida x) => x.get_Id() == titularesVida1.get_Id()); + if (titularesVida1.get_Codigo() == titularesVida2.get_Codigo()) + { + DateTime? inicio = titularesVida1.get_Inicio(); + DateTime? fim = titularesVida2.get_Inicio(); + if (inicio.HasValue == fim.HasValue) + { + flag = (inicio.HasValue ? inicio.GetValueOrDefault() != fim.GetValueOrDefault() : false); + } + else + { + flag = true; + } + if (!flag) + { + fim = titularesVida1.get_Fim(); + inicio = titularesVida2.get_Fim(); + if (fim.HasValue == inicio.HasValue) + { + flag1 = (fim.HasValue ? fim.GetValueOrDefault() != inicio.GetValueOrDefault() : false); + } + else + { + flag1 = true; + } + if (!flag1 && !(titularesVida1.get_Fatura() != titularesVida2.get_Fatura()) && !(titularesVida1.get_Nome() != titularesVida2.get_Nome()) && !(titularesVida1.get_Observacao() != titularesVida2.get_Observacao())) + { + inicio = titularesVida1.get_Nascimento(); + fim = titularesVida2.get_Nascimento(); + if (inicio.HasValue == fim.HasValue) + { + flag2 = (inicio.HasValue ? inicio.GetValueOrDefault() != fim.GetValueOrDefault() : false); + } + else + { + flag2 = true; + } + if (!flag2 && !(titularesVida1.get_Cpf() != titularesVida2.get_Cpf()) && !(titularesVida1.get_Matricula() != titularesVida2.get_Matricula())) + { + decimal? premio = titularesVida1.get_Premio(); + decimal? capital = titularesVida2.get_Premio(); + if ((premio.GetValueOrDefault() == capital.GetValueOrDefault()) & premio.HasValue == capital.HasValue) + { + capital = titularesVida1.get_Capital(); + premio = titularesVida2.get_Capital(); + if ((capital.GetValueOrDefault() == premio.GetValueOrDefault()) & capital.HasValue == premio.HasValue) + { + TipoTitular? tipo = titularesVida1.get_Tipo(); + TipoTitular? nullable = titularesVida2.get_Tipo(); + if (tipo.GetValueOrDefault() == nullable.GetValueOrDefault() & tipo.HasValue == nullable.HasValue && (object)titularesVida1.get_Dependente() == (object)titularesVida2.get_Dependente()) + { + continue; + } + } + } + } + } + } + } + titularesVidas.Add(titularesVida1); + } + else + { + titularesVidas.Add(titularesVida1); + } + } + base.Titulares = new ObservableCollection(await this._itemServico.SaveTitulares(titularesVidas)); + } + if (this._itemServico.Sucesso) + { + if (base.ItemSubstituido != null) + { + str2 = (base.Mantido ? string.Format("ITEM ALTERADO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem()) : string.Format("ITEM SUBSTITUIDO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem())); + string str5 = str2; + await this._itemServico.Substituir(base.ItemSubstituido, this.SelectedItem.get_Id(), str5); + } + base.Mantido = false; + await this.SelecionaItem(this.SelectedItem, false); + this.ItemSelecionado = this.SelectedItem; + if (this.Invoke) + { + ConsultaViewModel.ItemSelecionado = this.SelectedItem; + } + base.ToggleSnackBar(string.Concat(this.Ramo.get_Nome(), " SALVO COM SUCESSO"), true); + string str6 = string.Concat(str3, " ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable1 = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str6, id, nullable1, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + base.Alterar(false); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str3 = null; + return keyValuePairs; + } + + private async void Seleciona(Item item) + { + base.Loading(true); + await base.PermissaoTela(3); + await this.SelecionaItem(item, true); + base.Loading(false); + } + + public async Task SelecionaItem(Item item, bool registrar = true) + { + if (item == null || this.LastAccessId != item.get_Id() || this.LastAccessTela != 9) + { + base.Mantido = false; + this.CoberturaViewModel.Ramo = this.Ramo; + if (this.CoberturaViewModel.CoberturasPadrao == null) + { + await this.CoberturaViewModel.SelectionaCoberturas(); + } + if (item == null || item.get_Id() == 0) + { + this.SelectedItem = null; + this.CoberturaViewModel.Coberturas = null; + base.IsVisible = Visibility.Visible; + base.Titulares = new ObservableCollection(); + } + else + { + base.Loading(true); + item = await this._itemServico.BuscarItemPorIdAsync(item.get_Id()); + Item item1 = item; + RiscosDiversos riscosDiverso = await this._itemServico.BuscaRiscosDiversos(item.get_Id()); + Item item2 = item1; + RiscosDiversos riscosDiverso1 = riscosDiverso; + if (riscosDiverso1 == null) + { + riscosDiverso1 = new RiscosDiversos(); + riscosDiverso1.set_Item(item); + } + item2.set_RiscosDiversos(riscosDiverso1); + item1 = null; + if (this.VisibilityTitulares) + { + await base.CarregarTitulares(item.get_Id()); + } + this.SelectedItem = item; + this.SelectedItem.Initialize(); + this.Initialized = true; + this.CoberturaViewModel.Item = item; + await this.CoberturaViewModel.CancelarAlteracao(); + if (registrar) + { + string str = string.Concat("ACESSOU ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + } + this.LastAccessId = this.SelectedItem.get_Id(); + this.LastAccessTela = 3; + this.CodigoItem = this.SelectedItem.get_Id().ToString(); + base.Loading(false); + } + } + } + + public async void Substituir(Item item) + { + base.ItemSubstituido = item; + await this.Incluir(true); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/VidaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/VidaViewModel.cs new file mode 100644 index 0000000..e128b48 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/VidaViewModel.cs @@ -0,0 +1,661 @@ +using Gestor.Application.Actions; +using Gestor.Application.Componentes; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Seguros.Itens +{ + public class VidaViewModel : ItemViewModel, IDisposable + { + private readonly ItemServico _itemServico; + + private readonly VidaServico _servico; + + private bool _allowAlterarExcluir = true; + + private object _cobertura; + + private string _codigoItem; + + private Item _selectedItem = new Item(); + + private Visibility _atualizarCamposSaude; + + public bool AllowAlterarExcluir + { + get + { + return this._allowAlterarExcluir; + } + set + { + this._allowAlterarExcluir = value; + base.OnPropertyChanged("AllowAlterarExcluir"); + } + } + + public Visibility AtualizarCamposSaude + { + get + { + return this._atualizarCamposSaude; + } + set + { + this._atualizarCamposSaude = value; + base.OnPropertyChanged("AtualizarCamposSaude"); + } + } + + public object Cobertura + { + get + { + return this._cobertura; + } + set + { + this._cobertura = value; + base.OnPropertyChanged("Cobertura"); + } + } + + public string CodigoItem + { + get + { + return this._codigoItem; + } + set + { + this._codigoItem = value; + base.OnPropertyChanged("CodigoItem"); + } + } + + public bool Invoke + { + get; + set; + } + + private Item ItemSelecionado + { + get; + set; + } + + private Gestor.Model.Domain.Seguros.Ramo Ramo + { + get; + } + + public Item SelectedItem + { + get + { + return this._selectedItem; + } + set + { + long? nullable; + this._selectedItem = value; + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedItem"); + } + } + + public VidaViewModel(bool substituir = false, ManutencaoItem manutencao = null, Item itemSelecionado = null, Gestor.Model.Domain.Seguros.Ramo ramo = null, bool endossoRenovacao = false) + { + this.Invoke = itemSelecionado == null; + this.ItemSelecionado = itemSelecionado ?? ConsultaViewModel.ItemSelecionado; + this.Ramo = ramo ?? ConsultaViewModel.DocumentoSelecionado.get_Controle().get_Ramo(); + if (this.Invoke) + { + this.ItemSelecionado = this.ItemSelecionado ?? new Item(); + this.ItemSelecionado.set_Documento(ConsultaViewModel.DocumentoSelecionado); + } + this._itemServico = new ItemServico(); + this._servico = new VidaServico(); + Gestor.Application.Actions.Actions.UpdateItem = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.UpdateItem, new Action(this.Seleciona)); + Gestor.Application.Actions.Actions.SubstituirItem = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.SubstituirItem, new Action(this.Substituir)); + Gestor.Application.Actions.Actions.ManterItem = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.ManterItem, new Action(this.Manter)); + this.Seleciona(this.ItemSelecionado); + if (substituir) + { + this.Substituir(this.ItemSelecionado); + } + if (manutencao != null) + { + this.Manter(this.ItemSelecionado, manutencao); + } + this.AllowAlterarExcluir = !endossoRenovacao; + this.CarregaCobertura(); + } + + public async void CancelarAlteracao() + { + base.Loading(true); + base.AllSelected = new bool?(false); + await this.SelecionaItem(this.ItemSelecionado, false); + await this.CoberturaViewModel.CancelarAlteracao(); + base.Alterar(false); + base.Loading(false); + } + + public void CarregaCobertura() + { + this.CoberturaViewModel.Item = this.ItemSelecionado; + this.CoberturaViewModel.Ramo = this.Ramo; + this.Cobertura = new CoberturaView(this.CoberturaViewModel); + } + + public void Descarregar() + { + this.Cobertura = null; + } + + public void Dispose() + { + Gestor.Application.Actions.Actions.UpdateItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.UpdateItem, new Action(this.Seleciona)); + Gestor.Application.Actions.Actions.SubstituirItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.SubstituirItem, new Action(this.Substituir)); + Gestor.Application.Actions.Actions.ManterItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.ManterItem, new Action(this.Manter)); + } + + public async Task Excluir() + { + bool flag; + if (this.SelectedItem == null || this.SelectedItem.get_Id() == 0) + { + flag = false; + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + base.Loading(true); + bool flag1 = await this._servico.Delete(this.SelectedItem); + base.Loading(false); + if (flag1) + { + string str = string.Concat("EXCLUIU ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + base.ToggleSnackBar(string.Concat(this.Ramo.get_Nome(), " EXCLUÍDO COM SUCESSO"), true); + flag = true; + } + else + { + await base.ShowMessage("NÃO POSSÍVEL EXCLUIR O ITEM", "OK", "", false); + flag = false; + } + } + else + { + flag = false; + } + return flag; + } + + public async Task Incluir(bool substituir = false) + { + int? ordem; + List coberturas; + long? nullable; + coberturas = (this.CoberturaViewModel.Coberturas == null ? this.CoberturaViewModel.CarregaCoberturaPadrao().ToList() : this.CoberturaViewModel.Coberturas.ToList()); + List coberturas1 = coberturas; + Item item = new Item(); + item.set_Documento(this.ItemSelecionado.get_Documento()); + Item item1 = item; + ordem = (substituir ? base.ItemSubstituido.get_Ordem() : new int?(await base.QuantidadeDeItens(this.ItemSelecionado.get_Documento().get_Controle().get_Id()))); + item1.set_Ordem(ordem); + Item item2 = item; + Vida vida = new Vida(); + vida.set_Item(this.SelectedItem); + item2.set_Vida(vida); + Item item3 = item; + if (substituir) + { + nullable = new long?(base.ItemSubstituido.get_Id()); + } + else + { + nullable = null; + } + item3.set_Substituicao(nullable); + Item item4 = item; + item1 = null; + item = null; + base.Titulares = new ObservableCollection(); + ordem = item4.get_Ordem(); + if (ordem.GetValueOrDefault() == 2) + { + if (!await base.ShowMessage("ESTA APÓLICE SERÁ UMA FROTA, DESEJA CONTINUAR?", "SIM", "NÃO", false)) + { + coberturas1 = null; + item4 = null; + return; + } + } + bool valueOrDefault = substituir; + if (valueOrDefault) + { + valueOrDefault = await base.ShowMessage("DESEJA COPIAR OS DADOS DO ITEM?", "SIM", "NÃO", false); + } + if (!valueOrDefault) + { + this.SelectedItem = item4; + this.SelectedItem.get_Vida().set_Item(item4); + } + else + { + this.SelectedItem.set_Id((long)0); + this.SelectedItem.set_Documento(this.ItemSelecionado.get_Documento()); + } + ordem = item4.get_Ordem(); + int num = 1; + valueOrDefault = ordem.GetValueOrDefault() > num & ordem.HasValue; + if (valueOrDefault) + { + valueOrDefault = await base.ShowMessage("DESEJA REPLICAR AS COBERTURAS DO ITEM SELECIONADO?", "SIM", "NÃO", false); + } + if (!valueOrDefault) + { + this.CoberturaViewModel.CarregaPadrao(); + } + else + { + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + coberturas1.ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + if (substituir) + { + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + coberturas1.ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + base.Alterar(true); + coberturas1 = null; + item4 = null; + } + + public void Manter(Item item, ManutencaoItem manutencao) + { + if (manutencao.get_Tipo() == 1) + { + base.ItemSubstituido = item; + } + this.Manter(manutencao); + base.Mantido = true; + } + + public void Manter(ManutencaoItem manutencao) + { + long? nullable; + object list; + bool flag; + ObservableCollection coberturas = this.CoberturaViewModel.Coberturas; + if (coberturas != null) + { + list = coberturas.ToList(); + } + else + { + list = null; + } + List nums = new List() + { + (long)6, + (long)7, + (long)9, + (long)10, + (long)47, + (long)53, + (long)66 + }; + if (this.SelectedItem.get_Vida() == null) + { + this.SelectedItem.set_Vida(new Vida()); + } + if (this.ItemSelecionado.get_Documento().get_Controle().get_Id() != this.SelectedItem.get_Documento().get_Controle().get_Id()) + { + Item selectedItem = this.SelectedItem; + if (selectedItem != null) + { + flag = selectedItem.get_Sinistros().Count() > 0; + } + else + { + flag = false; + } + if (flag && manutencao.get_Tipo() == null) + { + goto Label1; + } + if (!nums.Contains(this.Ramo.get_Id())) + { + this.SelectedItem.set_Id((long)0); + goto Label0; + } + else + { + goto Label0; + } + } + Label1: + this.SelectedItem.set_Id((long)0); + this.SelectedItem.get_Vida().set_Id((long)0); + Label0: + Item item = this.SelectedItem; + Item itemSubstituido = base.ItemSubstituido; + if (itemSubstituido != null) + { + nullable = new long?(itemSubstituido.get_Id()); + } + else + { + nullable = null; + } + item.set_Substituicao(nullable); + this.SelectedItem.set_Documento(this.ItemSelecionado.get_Documento()); + if (manutencao.get_Tipo() == null) + { + this.SelectedItem.set_Sinistrado(false); + this.SelectedItem.set_Status(""); + this.SelectedItem.set_Sinistro(null); + this.SelectedItem.set_Sinistros(null); + } + this.CoberturaViewModel.CarregaPadrao(); + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + if (list != null) + { + ((List)list).ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + else + { + } + base.Alterar(true); + } + + public async Task>> Salvar(List titularesGrid) + { + List> keyValuePairs; + DateTime? inicio; + string plano; + string str; + string str1; + bool flag; + bool flag1; + bool flag2; + string str2; + string str3; + Item selectedItem = this.SelectedItem; + if (string.IsNullOrWhiteSpace(this.SelectedItem.get_Descricao())) + { + plano = this.SelectedItem.get_Vida().get_Plano(); + if (plano == null) + { + plano = ""; + } + } + else + { + plano = this.SelectedItem.get_Descricao(); + } + selectedItem.set_Descricao(plano); + this.SelectedItem.set_Titulares(titularesGrid); + List> keyValuePairs1 = this.SelectedItem.Validate(); + if (keyValuePairs1.Count <= 0) + { + Item item = this.SelectedItem; + item.set_Coberturas(await this.CoberturaViewModel.LimpaCoberturas()); + item = null; + if (this.SelectedItem.get_Documento().get_Ordem() <= 0) + { + str = ""; + } + else if (base.Mantido) + { + str = string.Format("ITEM ALTERADO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem()); + } + else + { + str = (base.ItemSubstituido != null ? string.Format("SUBSTITUIÇÃO DO ITEM {0} NO ENDOSSO ORDEM {1}", base.ItemSubstituido.get_Ordem(), this.SelectedItem.get_Documento().get_Ordem()) : string.Format("ITEM INCLUÍDO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem())); + } + string str4 = str; + if (this.SelectedItem.get_Id() == 0) + { + this.SelectedItem.set_Status(str4); + } + await this._itemServico.DeleteTitulares(base.ExcluirTitulares); + base.ExcluirTitulares = new List(); + str1 = (this.SelectedItem.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str3 = str1; + this.SelectedItem = await this._itemServico.Save(this.SelectedItem); + foreach (TitularesVida titularesVida in titularesGrid) + { + titularesVida.set_IdItem(this.SelectedItem.get_Id()); + } + List titularesVidas = new List(); + foreach (TitularesVida titularesVida1 in titularesGrid) + { + if (titularesVida1.get_Id() != 0) + { + TitularesVida titularesVida2 = base.OldTitulares.First((TitularesVida x) => x.get_Id() == titularesVida1.get_Id()); + if (titularesVida1.get_Codigo() == titularesVida2.get_Codigo()) + { + inicio = titularesVida1.get_Inicio(); + DateTime? fim = titularesVida2.get_Inicio(); + if (inicio.HasValue == fim.HasValue) + { + flag = (inicio.HasValue ? inicio.GetValueOrDefault() != fim.GetValueOrDefault() : false); + } + else + { + flag = true; + } + if (!flag) + { + fim = titularesVida1.get_Fim(); + inicio = titularesVida2.get_Fim(); + if (fim.HasValue == inicio.HasValue) + { + flag1 = (fim.HasValue ? fim.GetValueOrDefault() != inicio.GetValueOrDefault() : false); + } + else + { + flag1 = true; + } + if (!flag1 && !(titularesVida1.get_Fatura() != titularesVida2.get_Fatura()) && !(titularesVida1.get_Nome() != titularesVida2.get_Nome()) && !(titularesVida1.get_Observacao() != titularesVida2.get_Observacao())) + { + inicio = titularesVida1.get_Nascimento(); + fim = titularesVida2.get_Nascimento(); + if (inicio.HasValue == fim.HasValue) + { + flag2 = (inicio.HasValue ? inicio.GetValueOrDefault() != fim.GetValueOrDefault() : false); + } + else + { + flag2 = true; + } + if (!flag2 && !(titularesVida1.get_Cpf() != titularesVida2.get_Cpf()) && !(titularesVida1.get_Matricula() != titularesVida2.get_Matricula())) + { + decimal? premio = titularesVida1.get_Premio(); + decimal? capital = titularesVida2.get_Premio(); + if ((premio.GetValueOrDefault() == capital.GetValueOrDefault()) & premio.HasValue == capital.HasValue) + { + capital = titularesVida1.get_Capital(); + premio = titularesVida2.get_Capital(); + if ((capital.GetValueOrDefault() == premio.GetValueOrDefault()) & capital.HasValue == premio.HasValue) + { + TipoTitular? tipo = titularesVida1.get_Tipo(); + TipoTitular? nullable = titularesVida2.get_Tipo(); + if (tipo.GetValueOrDefault() == nullable.GetValueOrDefault() & tipo.HasValue == nullable.HasValue && (object)titularesVida1.get_Dependente() == (object)titularesVida2.get_Dependente()) + { + continue; + } + } + } + } + } + } + } + titularesVidas.Add(titularesVida1); + } + else + { + inicio = titularesVida1.get_Inicio(); + if (!inicio.HasValue) + { + continue; + } + titularesVidas.Add(titularesVida1); + } + } + base.Titulares = new ObservableCollection(await this._itemServico.SaveTitulares(titularesVidas)); + if (this._itemServico.Sucesso) + { + if (base.ItemSubstituido != null) + { + str2 = (base.Mantido ? string.Format("ITEM ALTERADO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem()) : string.Format("ITEM SUBSTITUIDO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem())); + string str5 = str2; + await this._itemServico.Substituir(base.ItemSubstituido, this.SelectedItem.get_Id(), str5); + } + base.Mantido = false; + await this.SelecionaItem(this.SelectedItem, false); + this.ItemSelecionado = this.SelectedItem; + if (this.Invoke) + { + ConsultaViewModel.ItemSelecionado = this.SelectedItem; + } + base.ToggleSnackBar(string.Concat(this.Ramo.get_Nome(), " SALVO COM SUCESSO"), true); + string str6 = string.Concat(str3, " ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable1 = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str6, id, nullable1, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + base.Alterar(false); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str3 = null; + return keyValuePairs; + } + + private async void Seleciona(Item item) + { + base.Loading(true); + await base.PermissaoTela(3); + await this.SelecionaItem(item, true); + base.Loading(false); + } + + public async Task SelecionaItem(Item item, bool registrar = true) + { + Visibility visibility; + if (item == null || this.LastAccessId != item.get_Id() || this.LastAccessTela != 9) + { + base.Mantido = false; + List nums = new List() + { + (long)6, + (long)7, + (long)9, + (long)10, + (long)47, + (long)53, + (long)66 + }; + if (nums.Contains(this.Ramo.get_Id())) + { + VidaViewModel vidaViewModel = this; + visibility = (this.Ramo.get_Id() == (long)9 ? Visibility.Collapsed : Visibility.Visible); + vidaViewModel.AtualizarCamposSaude = visibility; + this.CoberturaViewModel.Ramo = this.Ramo; + if (this.CoberturaViewModel.CoberturasPadrao == null) + { + await this.CoberturaViewModel.SelectionaCoberturas(); + } + if (item == null || item.get_Id() == 0) + { + this.SelectedItem = null; + this.CoberturaViewModel.Coberturas = null; + base.IsVisible = Visibility.Visible; + base.Titulares = new ObservableCollection(); + } + else + { + base.Loading(true); + item = await this._itemServico.BuscarItemPorIdAsync(item.get_Id()); + Item item1 = item; + Vida vida = await this._itemServico.BuscaVida(item.get_Id()); + item1.set_Vida(vida); + item1 = null; + await base.CarregarTitulares(item.get_Id()); + this.SelectedItem = item; + this.SelectedItem.Initialize(); + this.Initialized = true; + this.CoberturaViewModel.Item = item; + await this.CoberturaViewModel.CancelarAlteracao(); + if (registrar) + { + string str = string.Concat("ACESSOU ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + } + this.LastAccessId = this.SelectedItem.get_Id(); + this.LastAccessTela = 3; + this.CodigoItem = this.SelectedItem.get_Id().ToString(); + base.Loading(false); + } + } + } + } + + public async void Substituir(Item item) + { + base.ItemSubstituido = item; + await this.Incluir(true); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Seguros/PerfilEmpresaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Seguros/PerfilEmpresaViewModel.cs new file mode 100644 index 0000000..0c116ab --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Seguros/PerfilEmpresaViewModel.cs @@ -0,0 +1,274 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Seguros +{ + public class PerfilEmpresaViewModel : BaseViewModel + { + private readonly PerfilEmpresaServico _servico; + + private readonly Controle _controle; + + private Visibility _ativaCampos = Visibility.Collapsed; + + private string _equipamentoSeguranca = ""; + + private string _equipamentoIncendio = ""; + + private bool _enableIncluirPerfil; + + private string _dataConstrucao; + + public long CancelPerfil; + + private PerfilEmpresa _selectedPerfilEmpresa = new PerfilEmpresa(); + + public Visibility AtivaCampos + { + get + { + return this._ativaCampos; + } + set + { + this._ativaCampos = value; + base.OnPropertyChanged("AtivaCampos"); + } + } + + public string DataConstrucao + { + get + { + return this._dataConstrucao; + } + set + { + string str; + if (value != null) + { + str = value.Replace(" ", ""); + } + else + { + str = null; + } + this._dataConstrucao = str; + base.OnPropertyChanged("DataConstrucao"); + } + } + + public bool EnableIncluirPerfil + { + get + { + return this._enableIncluirPerfil; + } + set + { + this._enableIncluirPerfil = value; + base.OnPropertyChanged("EnableIncluirPerfil"); + } + } + + public string EquipamentoIncendio + { + get + { + return this._equipamentoIncendio; + } + set + { + this._equipamentoIncendio = value; + base.OnPropertyChanged("EquipamentoIncendio"); + } + } + + public string EquipamentoSeguranca + { + get + { + return this._equipamentoSeguranca; + } + set + { + this._equipamentoSeguranca = value; + base.OnPropertyChanged("EquipamentoSeguranca"); + } + } + + public PerfilEmpresa SelectedPerfilEmpresa + { + get + { + return this._selectedPerfilEmpresa; + } + set + { + long? nullable; + this._selectedPerfilEmpresa = value; + if (value != null && value.get_Id() > (long)0) + { + this.CancelPerfil = value.get_Id(); + } + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedPerfilEmpresa"); + } + } + + public PerfilEmpresaViewModel(Controle controle) + { + this._servico = new PerfilEmpresaServico(); + this._controle = controle; + this.Seleciona(controle.get_Id()); + } + + public void CancelarAlteracao() + { + base.Loading(true); + base.Alterar(false); + base.Loading(false); + } + + public async Task Excluir() + { + if (this.SelectedPerfilEmpresa != null && this.SelectedPerfilEmpresa.get_Id() != 0) + { + if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + base.Loading(true); + if (await this._servico.Delete(this.SelectedPerfilEmpresa)) + { + await this.SelecionaPerfil(this._controle.get_Id()); + base.Loading(false); + this.EnableIncluirPerfil = true; + this.AtivaCampos = Visibility.Collapsed; + this.DataConstrucao = null; + base.ToggleSnackBar("PERFIL EXCLUÍDO COM SUCESSO", true); + } + else + { + base.Loading(false); + } + } + } + } + + public void Incluir() + { + PerfilEmpresa perfilEmpresa = new PerfilEmpresa(); + perfilEmpresa.set_Controle(this._controle); + perfilEmpresa.set_Cliente(this._controle.get_Cliente()); + perfilEmpresa.set_ExclusivoDeposito(new bool?(false)); + perfilEmpresa.set_DivisaTerrenoBaldio(new bool?(false)); + perfilEmpresa.set_PatrimonioHistorio(new bool?(false)); + perfilEmpresa.set_PossuiTelhado(new bool?(false)); + perfilEmpresa.set_CaixasEletronicos(new bool?(false)); + perfilEmpresa.set_Isopainel(new bool?(false)); + perfilEmpresa.set_ConstrucaoReforma(new bool?(false)); + this.SelectedPerfilEmpresa = perfilEmpresa; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + List> keyValuePairs1 = this.SelectedPerfilEmpresa.Validate(); + keyValuePairs1 = this.ValidateCampos(keyValuePairs1); + if (keyValuePairs1.Count <= 0) + { + if (this.DataConstrucao != null && this.DataConstrucao != "") + { + this.SelectedPerfilEmpresa.set_AnoConstrucao(new DateTime?(DateTime.Parse(string.Concat("01/01/", this.DataConstrucao)))); + } + this.SelectedPerfilEmpresa = await this._servico.Save(this.SelectedPerfilEmpresa); + if (this._servico.Sucesso) + { + await this.SelecionaPerfil(this._controle.get_Id()); + base.ToggleSnackBar("PERFIL SALVO COM SUCESSO", true); + base.Alterar(false); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + return keyValuePairs; + } + + private async void Seleciona(long id) + { + base.Loading(true); + await base.PermissaoTela(32); + await this.SelecionaPerfil(id); + base.Loading(false); + } + + private async Task SelecionaPerfil(long id) + { + base.Loading(true); + this.SelectedPerfilEmpresa = await this._servico.BuscarPerfis(id); + if (this.SelectedPerfilEmpresa == null) + { + this.EnableIncluirPerfil = true; + this.EquipamentoSeguranca = ""; + this.EquipamentoIncendio = ""; + } + else + { + this.EquipamentoSeguranca = BindingEnumHelper.ConcatenarDescricoesEnum(this.SelectedPerfilEmpresa.get_EquipamentoSeguranca()); + this.EquipamentoIncendio = BindingEnumHelper.ConcatenarDescricoesEnum(this.SelectedPerfilEmpresa.get_EquipamentoIncendio()); + if (this.SelectedPerfilEmpresa.get_AnoConstrucao().HasValue) + { + DateTime? anoConstrucao = this.SelectedPerfilEmpresa.get_AnoConstrucao(); + this.DataConstrucao = anoConstrucao.Value.Year.ToString(); + } + } + base.Loading(false); + } + + private List> ValidateCampos(List> errorMessages) + { + int num; + int num1; + if (this.DataConstrucao == null) + { + ValidationHelper.AddValue(errorMessages, "ANO DA CONSTRUÇÃO", Messages.get_DataInvalida(), true); + } + if (!int.TryParse(this.DataConstrucao, out num)) + { + ValidationHelper.AddValue(errorMessages, "ANO DA CONSTRUÇÃO", Messages.get_DataInvalida(), true); + } + if (this.DataConstrucao != null && int.TryParse(this.DataConstrucao, out num1) && (int.Parse(this.DataConstrucao) <= 1755 || int.Parse(this.DataConstrucao) >= 9999)) + { + ValidationHelper.AddValue(errorMessages, "ANO DA CONSTRUÇÃO", Messages.get_DataInvalida(), true); + } + return errorMessages; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Seguros/PerfilViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Seguros/PerfilViewModel.cs new file mode 100644 index 0000000..dd3313a --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Seguros/PerfilViewModel.cs @@ -0,0 +1,183 @@ +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Seguros +{ + public class PerfilViewModel : BaseViewModel + { + private readonly PerfilServico _servico; + + private readonly Controle _controle; + + public long CancelPerfil; + + private Perfil _selectedPerfil = new Perfil(); + + private ObservableCollection _perfis; + + public ObservableCollection Perfis + { + get + { + return this._perfis; + } + set + { + this._perfis = value; + base.OnPropertyChanged("Perfis"); + } + } + + public Perfil SelectedPerfil + { + get + { + return this._selectedPerfil; + } + set + { + long? nullable; + this._selectedPerfil = value; + if (value != null && value.get_Id() > (long)0) + { + this.CancelPerfil = value.get_Id(); + } + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedPerfil"); + } + } + + public PerfilViewModel(Controle controle) + { + this._servico = new PerfilServico(); + this._controle = controle; + this.Seleciona(controle.get_Id()); + } + + public void CancelarAlteracao() + { + base.Loading(true); + if (this.CancelPerfil > (long)0) + { + this.SelectedPerfil = this.Perfis.FirstOrDefault((Perfil x) => x.get_Id() == this.CancelPerfil); + } + base.Alterar(false); + base.Loading(false); + } + + public async Task Excluir() + { + if (this.SelectedPerfil != null && this.SelectedPerfil.get_Id() != 0) + { + if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + base.Loading(true); + bool selectedPerfil = (object)this.SelectedPerfil == (object)this.Perfis.Last(); + if (await this._servico.Delete(this.SelectedPerfil)) + { + if (selectedPerfil) + { + int num = this.Perfis.IndexOf(this.SelectedPerfil); + if (num <= 0) + { + await this.SelecionaPerfis(this._controle.get_Id(), (long)0); + } + else + { + await this.SelecionaPerfis(this._controle.get_Id(), this.Perfis[num - 1].get_Id()); + } + } + else if (this.Perfis.Count > 0) + { + await this.SelecionaPerfis(this._controle.get_Id(), this.Perfis[this.Perfis.IndexOf(this.SelectedPerfil) + 1].get_Id()); + } + base.Loading(false); + base.ToggleSnackBar("PERFIL EXCLUÍDO COM SUCESSO", true); + } + else + { + base.Loading(false); + } + } + } + } + + public void Incluir() + { + Perfil perfil = new Perfil(); + perfil.set_Controle(this._controle); + perfil.set_Cliente(this._controle.get_Cliente()); + perfil.set_UsoProfissional(new bool?(false)); + perfil.set_AntiFurto(new Antifurto?(0)); + perfil.set_Isencao(new bool?(false)); + perfil.set_SeguroVida(new bool?(false)); + perfil.set_EstenderCobertura(new bool?(false)); + this.SelectedPerfil = perfil; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + List> keyValuePairs1 = this.SelectedPerfil.Validate(); + if (keyValuePairs1.Count <= 0) + { + this.SelectedPerfil = await this._servico.Save(this.SelectedPerfil); + if (this._servico.Sucesso) + { + await this.SelecionaPerfis(this._controle.get_Id(), this.SelectedPerfil.get_Id()); + base.ToggleSnackBar("PERFIL SALVO COM SUCESSO", true); + base.Alterar(false); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + return keyValuePairs; + } + + private async void Seleciona(long id) + { + base.Loading(true); + await base.PermissaoTela(32); + await this.SelecionaPerfis(id, (long)0); + base.Loading(false); + } + + private async Task SelecionaPerfis(long id, long perfilId = 0L) + { + Perfil perfil; + base.Loading(true); + this.Perfis = new ObservableCollection(await this._servico.BuscarPerfis(id)); + PerfilViewModel perfilViewModel = this; + perfil = (perfilId == 0 ? this.Perfis.FirstOrDefault() : this.Perfis.First((Perfil x) => x.get_Id() == perfilId)); + perfilViewModel.SelectedPerfil = perfil; + base.Loading(false); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Seguros/SinistroViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Seguros/SinistroViewModel.cs new file mode 100644 index 0000000..c7359e8 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Seguros/SinistroViewModel.cs @@ -0,0 +1,2104 @@ +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Ferramentas; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.MalaDireta; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Seguros +{ + public class SinistroViewModel : BaseSegurosViewModel + { + private readonly SinistroServico _servico; + + private readonly ItemServico _itemServico; + + private readonly Documento _documentoSelecionado; + + private readonly ClienteServico _clienteServico; + + private bool _editarObservacao = Recursos.Configuracoes.Any(new Func((ConfiguracaoSistema x) => x.get_Configuracao() == 49)); + + private bool _isAnotacoes = true; + + private List _tipoPerdaAuto = new List() + { + 1, + 2, + 4, + 3, + 8 + }; + + private List _tipoPerdaVida = new List() + { + 5, + 6, + 7, + 8 + }; + + private Credencial _selectedCredencial = new Credencial(); + + private List _credenciais = new List(); + + private ObservableCollection _itens = new ObservableCollection(); + + private ObservableCollection _itensFiltrados = new ObservableCollection(); + + private ObservableCollection _parceiros = new ObservableCollection(SinistroViewModel.GerarParceiros()); + + private bool _habilitarImprimirHistorico; + + private bool _habilitarEnviarHistorico; + + private Visibility _isVisibleImprimirHistorico; + + private Visibility _isVisibleIncluir; + + private Visibility _isVisibleTerceiro = Visibility.Collapsed; + + private Visibility _visibilityAuto = Visibility.Collapsed; + + private Visibility _visibilityVida = Visibility.Collapsed; + + private Visibility _liquidacaoVisibility; + + private bool _isReadOnlyItem = true; + + private bool _tipoSinistroEnabled; + + private Item _selectedItem = new Item(); + + private bool _mostrarLista; + + private bool _isExpandedItem = true; + + private bool _isExpandedSinistro = true; + + private List _controles = new List(); + + private ObservableCollection _controlesFiltrados = new ObservableCollection(); + + private ControleSinistro _selectedControle = new ControleSinistro(); + + private Sinistro _selectedSinistro; + + private string _codigoSinistro; + + private string _anotacoes; + + private string _anotacoesInternas; + + private string _telefonesMecanica; + + private string _telefonesFunileiro; + + public new string Anotacoes + { + get + { + return this._anotacoes; + } + set + { + this._anotacoes = value; + base.OnPropertyChanged("Anotacoes"); + } + } + + public string AnotacoesInternas + { + get + { + return this._anotacoesInternas; + } + set + { + this._anotacoesInternas = value; + base.OnPropertyChanged("AnotacoesInternas"); + } + } + + private bool Carregando + { + get; + set; + } + + public string CodigoSinistro + { + get + { + return this._codigoSinistro; + } + set + { + this._codigoSinistro = value; + base.OnPropertyChanged("CodigoSinistro"); + } + } + + public List Controles + { + get + { + return this._controles; + } + set + { + this._controles = value; + base.EnableIncluir = (value == null ? true : value.Count == 0); + base.OnPropertyChanged("Controles"); + } + } + + public ObservableCollection ControlesFiltrados + { + get + { + return this._controlesFiltrados; + } + set + { + this._controlesFiltrados = value; + this.IsExpandedSinistro = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("ControlesFiltrados"); + } + } + + public List Credenciais + { + get + { + return this._credenciais; + } + set + { + this._credenciais = value; + base.OnPropertyChanged("Credenciais"); + } + } + + public bool EditarObservacao + { + get + { + return this._editarObservacao; + } + set + { + this._editarObservacao = value; + base.OnPropertyChanged("EditarObservacao"); + } + } + + public int FiltroItens + { + get; + set; + } + + public bool HabilitarEnviarHistorico + { + get + { + return this._habilitarEnviarHistorico; + } + set + { + this._habilitarEnviarHistorico = value; + base.OnPropertyChanged("HabilitarEnviarHistorico"); + } + } + + public bool HabilitarImprimirHistorico + { + get + { + return this._habilitarImprimirHistorico; + } + set + { + this._habilitarImprimirHistorico = value; + base.OnPropertyChanged("HabilitarImprimirHistorico"); + } + } + + public bool IsAnotacoes + { + get + { + return this._isAnotacoes; + } + set + { + this._isAnotacoes = value; + base.OnPropertyChanged("IsAnotacoes"); + } + } + + public bool IsExpandedItem + { + get + { + return this._isExpandedItem; + } + set + { + this._isExpandedItem = value; + base.OnPropertyChanged("IsExpandedItem"); + } + } + + public bool IsExpandedSinistro + { + get + { + return this._isExpandedSinistro; + } + set + { + this._isExpandedSinistro = value; + base.OnPropertyChanged("IsExpandedSinistro"); + } + } + + public bool IsReadOnlyItem + { + get + { + return this._isReadOnlyItem; + } + set + { + this._isReadOnlyItem = value; + base.OnPropertyChanged("IsReadOnlyItem"); + } + } + + public Visibility IsVisibleImprimirHistorico + { + get + { + return this._isVisibleImprimirHistorico; + } + set + { + this._isVisibleImprimirHistorico = value; + base.OnPropertyChanged("IsVisibleImprimirHistorico"); + } + } + + public Visibility IsVisibleIncluir + { + get + { + return this._isVisibleIncluir; + } + set + { + this._isVisibleIncluir = value; + base.OnPropertyChanged("IsVisibleIncluir"); + } + } + + public Visibility IsVisibleTerceiro + { + get + { + return this._isVisibleTerceiro; + } + set + { + this._isVisibleTerceiro = value; + base.OnPropertyChanged("IsVisibleTerceiro"); + } + } + + public Item ItemSelecionado + { + get; + set; + } + + public ObservableCollection Itens + { + get + { + return this._itens; + } + set + { + this._itens = value; + base.OnPropertyChanged("Itens"); + } + } + + public ObservableCollection ItensFiltrados + { + get + { + return this._itensFiltrados; + } + set + { + this._itensFiltrados = value; + this.IsExpandedItem = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("ItensFiltrados"); + } + } + + public Visibility LiquidacaoVisibility + { + get + { + return this._liquidacaoVisibility; + } + set + { + this._liquidacaoVisibility = value; + base.OnPropertyChanged("LiquidacaoVisibility"); + } + } + + public bool MostrarLista + { + get + { + return this._mostrarLista; + } + set + { + this._mostrarLista = value; + base.OnPropertyChanged("MostrarLista"); + } + } + + public ObservableCollection Parceiros + { + get + { + return this._parceiros; + } + set + { + this._parceiros = value; + base.OnPropertyChanged("Parceiros"); + } + } + + public ControleSinistro SelectedControle + { + get + { + return this._selectedControle; + } + set + { + bool count; + this._selectedControle = value; + if (value != null) + { + base.EnableButtons = value.get_Id() > (long)0; + base.EnableIncluir = value.get_Id() > (long)0; + this.IsVisibleTerceiro = (value.get_Sinistros() == null || value.get_Sinistros() != null && value.get_Sinistros().Count < 2 ? Visibility.Collapsed : Visibility.Visible); + this.IsVisibleIncluir = (value.get_Sinistros() == null || !value.get_Sinistros().Any() ? Visibility.Visible : Visibility.Collapsed); + if (this.MostrarLista) + { + count = true; + } + else + { + List controles = this.Controles; + if (controles != null) + { + count = controles.Count > 1; + } + else + { + count = false; + } + } + this.MostrarLista = count; + } + base.OnPropertyChanged("SelectedControle"); + } + } + + public Credencial SelectedCredencial + { + get + { + return this._selectedCredencial; + } + set + { + this._selectedCredencial = value; + base.OnPropertyChanged("SelectedCredencial"); + } + } + + public Item SelectedItem + { + get + { + return this._selectedItem; + } + set + { + long? nullable; + this._selectedItem = value; + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedItem"); + } + } + + public Sinistro SelectedSinistro + { + get + { + return this._selectedSinistro; + } + set + { + long? nullable; + this._selectedSinistro = value; + this.Anotacoes = string.Empty; + this.AnotacoesInternas = string.Empty; + this.HabilitarImprimirHistorico = value != null; + this.HabilitarEnviarHistorico = value != null; + this.CodigoSinistro = (this.SelectedSinistro == null || this.SelectedSinistro.get_Id() == 0 ? "" : string.Format("CÓDIGO SINISTRO {0}", this.SelectedSinistro.get_Id())); + if (value != null && value.get_Id() != 0 && (this.LastAccessId != value.get_Id() || this.LastAccessTela != 7)) + { + base.RegistrarAcao(string.Format("ACESSOU SINISTRO DE ID \"{0}\"", value.get_Id()), value.get_Id(), new TipoTela?(7), string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}\nDESCRIÇÃO: \"{5}\"", new object[] { value.get_ControleSinistro().get_Item().get_Id(), value.get_ControleSinistro().get_Item().get_Documento().get_Id(), value.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Ramo().get_Nome(), value.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Cliente().get_Nome(), value.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Cliente().get_Id(), value.get_Descricao() })); + this.LastAccessId = value.get_Id(); + this.LastAccessTela = 7; + } + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedSinistro"); + } + } + + public string TelefonesFunileiro + { + get + { + return this._telefonesFunileiro; + } + set + { + this._telefonesFunileiro = value; + base.OnPropertyChanged("TelefonesFunileiro"); + } + } + + public string TelefonesMecanica + { + get + { + return this._telefonesMecanica; + } + set + { + this._telefonesMecanica = value; + base.OnPropertyChanged("TelefonesMecanica"); + } + } + + public List TipoPerdaAuto + { + get + { + return this._tipoPerdaAuto; + } + set + { + this._tipoPerdaAuto = value; + base.OnPropertyChanged("TipoPerdaAuto"); + } + } + + public List TipoPerdaVida + { + get + { + return this._tipoPerdaVida; + } + set + { + this._tipoPerdaVida = value; + base.OnPropertyChanged("TipoPerdaVida"); + } + } + + public bool TipoSinistroEnabled + { + get + { + return this._tipoSinistroEnabled; + } + set + { + this._tipoSinistroEnabled = value; + base.OnPropertyChanged("TipoSinistroEnabled"); + } + } + + public Visibility VisibilityAuto + { + get + { + return this._visibilityAuto; + } + set + { + this._visibilityAuto = value; + base.OnPropertyChanged("VisibilityAuto"); + } + } + + public Visibility VisibilityVida + { + get + { + return this._visibilityVida; + } + set + { + this._visibilityVida = value; + base.OnPropertyChanged("VisibilityVida"); + } + } + + public SinistroViewModel(Item item, bool attached) + { + bool documento; + bool vendedorPrincipal; + this._servico = new SinistroServico(); + this._itemServico = new ItemServico(); + this._clienteServico = new ClienteServico(); + this._documentoSelecionado = (attached ? ConsultaViewModel.DocumentoSelecionado : item.get_Documento()); + this.FiltroItens = ConsultaViewModel.FiltrarItens; + this.ItemSelecionado = ConsultaViewModel.ItemSelecionado; + if (!attached) + { + this.FiltroItens = 4; + this.ItemSelecionado = item; + } + if (item != null) + { + documento = item.get_Documento(); + } + else + { + documento = false; + } + if (documento) + { + Documento documentoSelecionado = ConsultaViewModel.DocumentoSelecionado; + if (documentoSelecionado != null) + { + vendedorPrincipal = documentoSelecionado.get_VendedorPrincipal(); + } + else + { + vendedorPrincipal = false; + } + if (vendedorPrincipal) + { + item.get_Documento().set_VendedorPrincipal(ConsultaViewModel.DocumentoSelecionado.get_VendedorPrincipal()); + } + } + this.Seleciona(item); + } + + public void AbrirInfo() + { + base.ShowDrawer(new InfoDrawer(this._documentoSelecionado, false), 0, false); + } + + public async Task BuscarClienteSinistro() + { + Cliente cliente = await this._itemServico.BuscarCliente(this.SelectedItem.get_Id()); + return cliente; + } + + public async void CancelarAlteracao() + { + // + // Current member / type: System.Void Gestor.Application.ViewModels.Seguros.SinistroViewModel::CancelarAlteracao() + // File path: C:\AggerSeguros\Gestor.Application.exe + // + // Product version: 0.0.0.0 + // Exception in: System.Void CancelarAlteracao() + // + // Object reference not set to an instance of an object. + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.FindLowestCommonAncestor(ICollection`1 typeNodes) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 515 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.MergeWithLowestCommonAncestor() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 459 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.ProcessSingleConstraints() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 378 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.InferTypes() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 331 + // at Telerik.JustDecompiler.Decompiler.ExpressionDecompilerStep.Process(DecompilationContext theContext, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\ExpressionDecompilerStep.cs:line 104 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.Extensions.DecompileStateMachine(MethodBody body, DecompilationContext enclosingContext, BaseStateMachineRemoverStep removeStateMachineStep, Func`2 stateMachineDataSelector, DecompilationContext& decompilationContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 112 + // at Telerik.JustDecompiler.Decompiler.Extensions.DecompileAsyncStateMachine(MethodBody body, DecompilationContext enclosingContext, AsyncData& asyncData) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 150 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.GetMoveNextStatements() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 161 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.Match() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 76 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.Process(DecompilationContext context, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 36 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61 + // at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 133 + // + // mailto: JustDecompilePublicFeedback@telerik.com + + } + + private async Task CarregarControles(Item item) + { + List controleSinistros = await this._servico.BuscarControles(item.get_Id()); + SinistroViewModel list = this; + List controleSinistros1 = controleSinistros; + list.Controles = ( + from x in controleSinistros1 + orderby x.get_DataSinistro() descending + select x).ToList(); + this.ControlesFiltrados = new ObservableCollection(this.Controles); + } + + public void CarregarParceiros() + { + List parceiros = new List(); + Parceiro parceiro = new Parceiro(); + parceiro.set_Nome("NENHUM"); + parceiros.Add(parceiro); + List parceiros1 = parceiros; + parceiros1.AddRange( + from x in Recursos.Parceiros + orderby x.get_Nome() + select x); + this.Parceiros = new ObservableCollection(parceiros1); + } + + public async void EnviarLogEmail() + { + int? nullable; + string nome; + string email; + int? ordem; + List credenciais = this.Credenciais; + if (credenciais == null) + { + credenciais = await (new BaseServico()).BuscarCredenciais(); + } + this.Credenciais = credenciais; + SinistroViewModel sinistroViewModel = this; + List credencials = this.Credenciais; + Credencial credencial = credencials.FirstOrDefault((Credencial x) => x.get_IdUsuario() == Recursos.Usuario.get_Id()); + if (credencial == null) + { + credencial = this.Credenciais.FirstOrDefault(); + } + sinistroViewModel.SelectedCredencial = credencial; + ObservableCollection observableCollection = await this._clienteServico.BuscarEmailsAsync(this.SelectedSinistro.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Cliente().get_Id()); + if (observableCollection.Count != 0) + { + Documento documento = await (new ApoliceServico()).BuscarApoliceAsync(this._documentoSelecionado.get_Id(), false, false); + SinistroViewModel sinistroViewModel1 = this; + Vendedor vendedorPrincipal = documento.get_VendedorPrincipal(); + if (vendedorPrincipal != null) + { + nome = vendedorPrincipal.get_Nome(); + } + else + { + nome = null; + } + string str = sinistroViewModel1.GerarHtmlSinistro(nome); + string str1 = (new Regex(".*<\\/title>")).Replace(str, " ").Trim(); + str1 = (new Regex("(<[^>]*>)|(p\\s?{[^}]*})|(\\r)|(\\n)")).Replace(str1, " ").Trim(); + str1 = str1.Replace("@page{ size: A4;} body; -webkit-print-color-adjust: exact; }", " "); + str1 = str1.Replace("NEW P { MARGIN-BOTTOM: 0; MARGIN-TOP: 0; }", " "); + MalaDireta malaDiretum = new MalaDireta(); + malaDiretum.set_Cliente(documento.get_Controle().get_Cliente()); + malaDiretum.set_ArquivoDigital(null); + malaDiretum.set_Sinistro(this.SelectedSinistro); + malaDiretum.set_Item(this.SelectedItem); + malaDiretum.set_Apolice(documento); + malaDiretum.set_Tela(7); + ClienteEmail clienteEmail = observableCollection.FirstOrDefault<ClienteEmail>(); + if (clienteEmail != null) + { + email = clienteEmail.get_Email(); + } + else + { + email = null; + } + malaDiretum.set_Email(email); + ClienteEmail clienteEmail1 = observableCollection.FirstOrDefault<ClienteEmail>(); + if (clienteEmail1 != null) + { + ordem = clienteEmail1.get_Ordem(); + } + else + { + nullable = null; + ordem = nullable; + } + nullable = ordem; + malaDiretum.set_Ordem(nullable.GetValueOrDefault()); + MalaDireta malaDiretum1 = malaDiretum; + if (Funcoes.IsWindowOpen<HosterWindow>("ENVIO DE E-MAIL")) + { + Funcoes.Destroy<HosterWindow>("ENVIO DE E-MAIL"); + } + List<MalaDireta> malaDiretas = new List<MalaDireta>() + { + malaDiretum1 + }; + (new HosterWindow(new MalaDiretaView(malaDiretas, string.Concat("HISTÓRICO DO SINISTRO DO ITEM ", this.SelectedItem.get_Descricao()), str, null), "ENVIO DE E-MAIL", new double?((double)1200), new double?((double)600), true)).ShowDialog(); + } + else + { + await base.ShowMessage("O CLIENTE NÃO POSSUI NENHUM E-MAIL CADASTRADO", "OK", "", false); + } + observableCollection = null; + } + + public async void Excluir() + { + Sinistro sinistro; + int? nullable; + bool valueOrDefault; + bool flag; + Sinistro sinistro1; + int num; + ControleSinistro controleSinistro; + if (this.SelectedSinistro != null && this.SelectedSinistro.get_Id() != 0) + { + if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + base.Loading(true); + string str = string.Format("EXCLUIU SINISTRO DE ID \"{0}\"", this.SelectedSinistro.get_Id()); + long id = this.SelectedSinistro.get_Id(); + TipoTela? nullable1 = new TipoTela?(7); + object[] objArray = new object[] { this.SelectedSinistro.get_ControleSinistro().get_Item().get_Id(), this.SelectedSinistro.get_ControleSinistro().get_Item().get_Documento().get_Id(), this.SelectedSinistro.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedSinistro.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedSinistro.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Cliente().get_Id(), this.SelectedSinistro.get_Id() }; + base.RegistrarAcao(str, id, nullable1, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}\nDESCRIÇÃO: {5}", objArray)); + if (this.SelectedControle.get_Sinistros().Count == 1) + { + List<ControleSinistro> controles = this.Controles; + controles.Remove(this.SelectedControle); + SinistroServico sinistroServico = this._servico; + ControleSinistro selectedControle = this.SelectedControle; + flag = (controles == null ? true : controles.Count == 0); + if (await sinistroServico.DeleteControle(selectedControle, flag)) + { + int num1 = this.ControlesFiltrados.IndexOf(this.SelectedControle); + this.Controles.Remove(this.SelectedControle); + this.ControlesFiltrados.Remove(this.SelectedControle); + this.ControlesFiltrados = new ObservableCollection<ControleSinistro>(this.ControlesFiltrados); + if (this.ControlesFiltrados.Count <= 0) + { + this.SelectedControle = new ControleSinistro(); + base.Alterar(false); + base.EnableMenu = false; + } + else + { + SinistroViewModel sinistroViewModel = this; + if (num1 < this.ControlesFiltrados.Count) + { + ObservableCollection<ControleSinistro> controlesFiltrados = this.ControlesFiltrados; + num = (num1 == 0 ? 1 : num1); + controleSinistro = controlesFiltrados.ElementAt<ControleSinistro>(num - 1); + } + else + { + controleSinistro = this.ControlesFiltrados.Last<ControleSinistro>(); + } + sinistroViewModel.SelectedControle = controleSinistro; + } + SinistroViewModel sinistroViewModel1 = this; + ControleSinistro selectedControle1 = this.SelectedControle; + if (selectedControle1 != null) + { + List<Sinistro> sinistros = selectedControle1.get_Sinistros(); + if (sinistros != null) + { + sinistro1 = sinistros.FirstOrDefault<Sinistro>(); + } + else + { + sinistro1 = null; + } + } + else + { + sinistro1 = null; + } + sinistroViewModel1.SelectedSinistro = sinistro1; + } + else + { + return; + } + } + else if (await this._servico.Delete(this.SelectedSinistro)) + { + int num2 = this.SelectedControle.get_Sinistros().IndexOf(this.SelectedSinistro); + this.SelectedControle.get_Sinistros().Remove(this.SelectedSinistro); + long id1 = this.SelectedControle.get_Id(); + this.SelectedControle = null; + this.SelectedControle = this.ControlesFiltrados.First<ControleSinistro>((ControleSinistro x) => x.get_Id() == id1); + SinistroViewModel sinistroViewModel2 = this; + sinistro = (num2 < this.SelectedControle.get_Sinistros().Count ? this.SelectedControle.get_Sinistros().ElementAt<Sinistro>(num2) : this.SelectedControle.get_Sinistros().Last<Sinistro>()); + sinistroViewModel2.SelectedSinistro = sinistro; + } + else + { + return; + } + if (this.Controles == null || this.Controles.Count == 0) + { + ItemServico itemServico = new ItemServico(); + Item item = await itemServico.BuscarItemPorIdAsync(this.SelectedItem.get_Id()); + item.set_Sinistrado(false); + await itemServico.Save(item); + itemServico = null; + } + if (this.ItensFiltrados.Count > 0 && this.ItensFiltrados != null) + { + Item item1 = this.ItensFiltrados.First<Item>((Item x) => x.get_Id() == this.SelectedItem.get_Id()); + ControleSinistro controleSinistro1 = this.SelectedControle; + if (controleSinistro1 != null) + { + List<Sinistro> sinistros1 = controleSinistro1.get_Sinistros(); + if (sinistros1 != null) + { + nullable = new int?(sinistros1.Count); + } + else + { + nullable = null; + } + int? nullable2 = nullable; + int num3 = 0; + valueOrDefault = nullable2.GetValueOrDefault() > num3 & nullable2.HasValue; + } + else + { + valueOrDefault = false; + } + item1.set_Sinistrado(valueOrDefault); + } + this.ItensFiltrados = new ObservableCollection<Item>(this.ItensFiltrados); + base.Loading(false); + base.ToggleSnackBar("SINISTRO EXCLUÍDO COM SUCESSO", true); + } + } + } + + public List<Item> FiltrarItem(string filter) + { + this.ItensFiltrados = (string.IsNullOrWhiteSpace(filter) ? this.Itens : new ObservableCollection<Item>( + from x in this.Itens + where ValidationHelper.RemoveDiacritics(x.get_Descricao().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby x.get_Ordem() + select x)); + return this.ItensFiltrados.ToList<Item>(); + } + + public List<ControleSinistro> FiltrarSinistro(string filter) + { + ControleSinistro controleSinistro; + this.ControlesFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection<ControleSinistro>(this.Controles) : new ObservableCollection<ControleSinistro>(this.Controles.Where<ControleSinistro>((ControleSinistro x) => { + if (ValidationHelper.RemoveDiacritics(x.get_DataSinistro().ToString().Trim()).Contains(filter)) + { + return true; + } + if (x.get_Sinistros() == null || x.get_Sinistros().Count <= 0) + { + return false; + } + return ValidationHelper.RemoveDiacritics(x.get_Sinistros()[0].get_Numero().Trim()).Contains(filter); + }).OrderBy<ControleSinistro, DateTime?>((ControleSinistro x) => x.get_DataSinistro()))); + if (this.ControlesFiltrados.Count > 0) + { + controleSinistro = this.ControlesFiltrados.First<ControleSinistro>(); + } + else + { + controleSinistro = null; + } + this.SelectedControle = controleSinistro; + return this.ControlesFiltrados.ToList<ControleSinistro>(); + } + + public string GerarHtmlSinistro(string vendedorPrincipal = "") + { + DateTime? vigencia2; + bool? culpado; + string shortDateString; + string shortTimeString; + string str; + string str1; + string str2; + bool valueOrDefault; + string shortDateString1; + string str3 = "<html><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><meta http-equiv='Content-Language' content='pt-br'><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1, shrink-to-fit=yes'><link rel='stylesheet' href='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css' integrity='sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T' crossorigin='anonymous'><style type='text/css' media='print'>@page{ size: A4;} body; -webkit-print-color-adjust: exact; }</style><title> HISTÓRICO DO SINISTRO
"; + string str4 = ""; + foreach (Sinistro sinistro in + from x in this.SelectedControle.get_Sinistros() + orderby x.get_TipoSinistro() + select x) + { + str3 = string.Concat(str3, "

"); + str4 = (string.IsNullOrEmpty(str4) ? "CLIENTE" : string.Concat("TERCEIRO Nº ", sinistro.get_Numero())); + str3 = string.Concat(str3, str4, "

"); + str3 = string.Concat(str3, "
"); + int num = 0; + if (str4 == "CLIENTE") + { + string[] nome = new string[] { str3, ""; + str3 = string.Concat(nome); + num = 1; + string[] documento = new string[] { str3, ""; + str3 = string.Concat(documento); + num = 0; + string[] apolice = new string[] { str3, ""; + str3 = string.Concat(apolice); + num = 1; + string[] strArrays = new string[] { str3, ""; + str3 = string.Concat(strArrays); + num = 0; + vigencia2 = sinistro.get_ControleSinistro().get_Item().get_Documento().get_Vigencia2(); + if (vigencia2.GetValueOrDefault().ToString(new CultureInfo("pt-BR")) != "01/01/0001 00:00:00") + { + vigencia2 = sinistro.get_ControleSinistro().get_Item().get_Documento().get_Vigencia2(); + if (vigencia2.HasValue) + { + shortDateString1 = vigencia2.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString1 = null; + } + } + else + { + shortDateString1 = "NÃO POSSUI"; + } + string str5 = shortDateString1; + string[] strArrays1 = new string[] { str3, ""; + str3 = string.Concat(strArrays1); + num = 1; + vendedorPrincipal = (sinistro.get_ControleSinistro().get_Item().get_Documento().get_VendedorPrincipal() == null ? vendedorPrincipal : sinistro.get_ControleSinistro().get_Item().get_Documento().get_VendedorPrincipal().get_Nome()); + string[] strArrays2 = new string[] { str3, ""; + str3 = string.Concat(strArrays2); + num = 0; + string[] nome1 = new string[] { str3, ""; + str3 = string.Concat(nome1); + } + num = 1; + string[] numero = new string[] { str3, ""; + str3 = string.Concat(numero); + num = 0; + string[] strArrays3 = new string[] { str3, ""; + str3 = string.Concat(strArrays3); + num = 1; + string[] strArrays4 = new string[] { str3, ""; + str3 = string.Concat(strArrays4); + num = 0; + string[] strArrays5 = new string[] { str3, ""; + str3 = string.Concat(strArrays5); + num = 1; + string[] str6 = new string[] { str3, ""; + str3 = string.Concat(str6); + num = 0; + string[] itemSinistrado = new string[] { str3, ""; + str3 = string.Concat(itemSinistrado); + num = 1; + string[] strArrays6 = new string[] { str3, ""; + str3 = string.Concat(strArrays6); + num = 0; + string[] str7 = new string[] { str3, ""; + str3 = string.Concat(str7); + num = 1; + string[] strArrays7 = new string[] { str3, ""; + str3 = string.Concat(strArrays7); + num = 0; + string[] str8 = new string[] { str3, ""; + str3 = string.Concat(str8); + num = 1; + string[] description = new string[] { str3, ""; + str3 = string.Concat(description); + str3 = string.Concat(str3, "
CLIENTE: "; + nome[4] = sinistro.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Cliente().get_Nome(); + nome[5] = "
DOCUMENTO DO SEGURADO: "; + documento[4] = sinistro.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Cliente().get_Documento(); + documento[5] = "
APÓLICE: "; + apolice[4] = sinistro.get_ControleSinistro().get_Item().get_Documento().get_Apolice(); + apolice[5] = "
VIGÊNCIA INICIAL: "; + DateTime vigencia1 = sinistro.get_ControleSinistro().get_Item().get_Documento().get_Vigencia1(); + strArrays[4] = vigencia1.ToShortDateString(); + strArrays[5] = "
VIGÊNCIA FINAL: "; + strArrays1[4] = str5; + strArrays1[5] = "
VENDEDOR PRINCIPAL: "; + strArrays2[4] = vendedorPrincipal; + strArrays2[5] = "
SEGURADORA: "; + nome1[4] = sinistro.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Seguradora().get_Nome(); + nome1[5] = "
NÚMERO SINISTRO: "; + numero[4] = sinistro.get_Numero(); + numero[5] = "
DATA DO SINISTRO: "; + vigencia2 = sinistro.get_ControleSinistro().get_DataSinistro(); + if (vigencia2.HasValue) + { + shortDateString = vigencia2.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString = null; + } + strArrays3[4] = shortDateString; + strArrays3[5] = "
HORA DO SINISTRO: "; + vigencia2 = sinistro.get_ControleSinistro().get_HoraSinistro(); + if (vigencia2.HasValue) + { + shortTimeString = vigencia2.GetValueOrDefault().ToShortTimeString(); + } + else + { + shortTimeString = null; + } + strArrays4[4] = shortTimeString; + strArrays4[5] = "
DATA/HORA ABERTURA: "; + vigencia2 = sinistro.get_DataReclamacao(); + strArrays5[4] = vigencia2.ToString(); + strArrays5[5] = "
DATA LIQUIDAÇÃO: "; + vigencia2 = sinistro.get_DataLiquidacao(); + str6[4] = vigencia2.ToString(); + str6[5] = "
DESCRIÇÃO DO BEM SINISTRADO: "; + itemSinistrado[4] = sinistro.get_ItemSinistrado(); + itemSinistrado[5] = "
VALOR ORÇADO: "; + decimal valorOrcado = sinistro.get_ValorOrcado(); + strArrays6[4] = valorOrcado.ToString("C", new CultureInfo("pt-BR", false)); + strArrays6[5] = "
VALOR LIBERADO: "; + valorOrcado = sinistro.get_ValorLiberado(); + str7[4] = valorOrcado.ToString("C", new CultureInfo("pt-BR", false)); + str7[5] = "
VALOR PAGO: "; + valorOrcado = sinistro.get_ValorPago(); + strArrays7[4] = valorOrcado.ToString("C", new CultureInfo("pt-BR", false)); + strArrays7[5] = "
VALOR FRANQUIA: "; + valorOrcado = sinistro.get_ValorFranquia(); + str8[4] = valorOrcado.ToString("C", new CultureInfo("pt-BR", false)); + str8[5] = "
SITUAÇÃO: "; + description[4] = ValidationHelper.GetDescription(sinistro.get_StatusSinistro()); + description[5] = "
"); + if (sinistro.get_SinistroAuto() != null) + { + str3 = string.Concat(str3, "
"); + num = 0; + string[] numeroBo = new string[] { str3, ""; + str3 = string.Concat(numeroBo); + num = 1; + string[] description1 = new string[] { str3, ""; + str3 = string.Concat(description1); + num = 0; + string str9 = str3; + str1 = (num % 2 == 0 ? "WhiteSmoke" : "White"); + culpado = sinistro.get_SinistroAuto().get_Culpado(); + if (string.Concat(""; + goto Label0; + } + Label1: + str2 = "NÃO"; + Label0: + str3 = string.Concat(str9, str2); + num = 1; + string[] strArrays8 = new string[] { str3, ""; + str3 = string.Concat(strArrays8); + num = 0; + string[] endereco = new string[] { str3, ""; + str3 = string.Concat(endereco); + num = 1; + string[] envolvido = new string[] { str3, ""; + str3 = string.Concat(envolvido); + num = 0; + string[] motorista = new string[] { str3, ""; + str3 = string.Concat(motorista); + num = 1; + string[] ddd = new string[] { str3, ""; + str3 = string.Concat(ddd); + num = 0; + string[] email = new string[] { str3, ""; + str3 = string.Concat(email); + str3 = string.Concat(str3, "
NÚMERO B.O.: "; + numeroBo[4] = sinistro.get_SinistroAuto().get_NumeroBo(); + numeroBo[5] = "
TIPO PERDA: "; + description1[4] = ValidationHelper.GetDescription(sinistro.get_SinistroAuto().get_TipoPerda()); + description1[5] = "
CONSIDERA-SE CULPADO? ", culpado.ToString()) != null) + { + SinistroAuto sinistroAuto = sinistro.get_SinistroAuto(); + if (sinistroAuto != null) + { + culpado = sinistroAuto.get_Culpado(); + bool flag = false; + valueOrDefault = culpado.GetValueOrDefault() == flag & culpado.HasValue; + } + else + { + valueOrDefault = false; + } + if (valueOrDefault) + { + goto Label1; + } + str2 = "SIM
ÚLTIMO DOC. ENVIADO: "; + strArrays8[4] = string.Format("{0:dd/MM/yyyy}", sinistro.get_SinistroAuto().get_UltimoDocEnviado()); + strArrays8[5] = "
ENDEREÇO: "; + endereco[4] = sinistro.get_SinistroAuto().get_Endereco(); + endereco[5] = "
ENVOLVIDO/PROPRIETÁRIO: "; + envolvido[4] = sinistro.get_SinistroAuto().get_Envolvido(); + envolvido[5] = "
MOTORISTA: "; + motorista[4] = sinistro.get_SinistroAuto().get_Motorista(); + motorista[5] = "
TELEFONE: ("; + ddd[4] = sinistro.get_SinistroAuto().get_Ddd(); + ddd[5] = ") "; + ddd[6] = sinistro.get_SinistroAuto().get_Telefone(); + ddd[7] = "
E-MAIL: "; + email[4] = sinistro.get_SinistroAuto().get_Email(); + email[5] = "
"); + str3 = string.Concat(str3, "
"); + num = 1; + string str10 = (sinistro.get_SinistroAuto().get_ParceiroMecanica() != null ? sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Nome() : ""); + string[] strArrays9 = new string[] { str3, ""; + str3 = string.Concat(strArrays9); + num = 0; + string str11 = (sinistro.get_SinistroAuto().get_ParceiroMecanica() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Ddd1()) && string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Telefone1()) ? "" : string.Concat("(", sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Ddd1(), ") ", sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Telefone1())); + string str12 = (sinistro.get_SinistroAuto().get_ParceiroMecanica() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Ddd2()) && string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Telefone2()) ? "" : string.Concat(" / (", sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Ddd2(), ") ", sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Telefone2())); + string str13 = (sinistro.get_SinistroAuto().get_ParceiroMecanica() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Ddd3()) && string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Telefone3()) ? "" : string.Concat(" / (", sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Ddd3(), ") ", sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Telefone3())); + string[] strArrays10 = new string[] { str3, ""; + str3 = string.Concat(strArrays10); + num = 1; + string str14 = (sinistro.get_SinistroAuto().get_ParceiroMecanica() == null ? "" : sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Email()); + string[] strArrays11 = new string[] { str3, ""; + str3 = string.Concat(strArrays11); + num = 0; + string str15 = (sinistro.get_SinistroAuto().get_ParceiroMecanica() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Endereco()) ? "" : sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Endereco() ?? ""); + string str16 = (sinistro.get_SinistroAuto().get_ParceiroMecanica() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Numero()) ? "" : string.Concat(", ", sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Numero())); + string str17 = (sinistro.get_SinistroAuto().get_ParceiroMecanica() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Complemento()) ? "" : string.Concat(", ", sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Complemento())); + string str18 = (sinistro.get_SinistroAuto().get_ParceiroMecanica() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Bairro()) ? "" : string.Concat(", ", sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Bairro())); + string str19 = (sinistro.get_SinistroAuto().get_ParceiroMecanica() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Cidade()) ? "" : string.Concat(" - ", sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Cidade())); + string str20 = (sinistro.get_SinistroAuto().get_ParceiroMecanica() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Uf()) ? "" : string.Concat(" - ", sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Uf())); + string str21 = (sinistro.get_SinistroAuto().get_ParceiroMecanica() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Cep()) ? "" : string.Concat(" - ", sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Cep())); + string[] strArrays12 = new string[] { str3, ""; + str3 = string.Concat(strArrays12); + str3 = string.Concat(str3, "
PARCEIRO MECÂNICA: "; + strArrays9[4] = str10; + strArrays9[5] = "
CONTATOS: "; + strArrays10[4] = str11; + strArrays10[5] = str12; + strArrays10[6] = str13; + strArrays10[7] = "
EMAIL: "; + strArrays11[4] = str14; + strArrays11[5] = "
ENDEREÇO: "; + strArrays12[4] = str15; + strArrays12[5] = str16; + strArrays12[6] = str17; + strArrays12[7] = str18; + strArrays12[8] = str19; + strArrays12[9] = str20; + strArrays12[10] = str21; + strArrays12[11] = "
"); + str3 = string.Concat(str3, "
"); + num = 1; + str10 = (sinistro.get_SinistroAuto().get_ParceiroFunilaria() != null ? sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Nome() : ""); + string[] strArrays13 = new string[] { str3, ""; + str3 = string.Concat(strArrays13); + num = 0; + str11 = (sinistro.get_SinistroAuto().get_ParceiroFunilaria() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Ddd1()) && string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Telefone1()) ? "" : string.Concat("(", sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Ddd1(), ") ", sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Telefone1())); + str12 = (sinistro.get_SinistroAuto().get_ParceiroFunilaria() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Ddd2()) && string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Telefone2()) ? "" : string.Concat(" / (", sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Ddd2(), ") ", sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Telefone2())); + str13 = (sinistro.get_SinistroAuto().get_ParceiroFunilaria() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Ddd3()) && string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Telefone3()) ? "" : string.Concat(" / (", sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Ddd3(), ") ", sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Telefone3())); + string[] strArrays14 = new string[] { str3, ""; + str3 = string.Concat(strArrays14); + num = 1; + str14 = (sinistro.get_SinistroAuto().get_ParceiroFunilaria() == null ? "" : sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Email()); + string[] strArrays15 = new string[] { str3, ""; + str3 = string.Concat(strArrays15); + num = 0; + str15 = (sinistro.get_SinistroAuto().get_ParceiroFunilaria() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Endereco()) ? "" : sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Endereco() ?? ""); + str16 = (sinistro.get_SinistroAuto().get_ParceiroFunilaria() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Numero()) ? "" : string.Concat(", ", sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Numero())); + str17 = (sinistro.get_SinistroAuto().get_ParceiroFunilaria() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Complemento()) ? "" : string.Concat(", ", sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Complemento())); + str18 = (sinistro.get_SinistroAuto().get_ParceiroFunilaria() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Bairro()) ? "" : string.Concat(", ", sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Bairro())); + str19 = (sinistro.get_SinistroAuto().get_ParceiroFunilaria() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Cidade()) ? "" : string.Concat(" - ", sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Cidade())); + str20 = (sinistro.get_SinistroAuto().get_ParceiroFunilaria() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Uf()) ? "" : string.Concat(" - ", sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Uf())); + str21 = (sinistro.get_SinistroAuto().get_ParceiroFunilaria() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Cep()) ? "" : string.Concat(" - ", sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Cep())); + string[] strArrays16 = new string[] { str3, ""; + str3 = string.Concat(strArrays16); + str3 = string.Concat(str3, "
PARCEIRO FUNILARIA: "; + strArrays13[4] = str10; + strArrays13[5] = "
CONTATOS: "; + strArrays14[4] = str11; + strArrays14[5] = str12; + strArrays14[6] = str13; + strArrays14[7] = "
EMAIL: "; + strArrays15[4] = str14; + strArrays15[5] = "
ENDEREÇO: "; + strArrays16[4] = str15; + strArrays16[5] = str16; + strArrays16[6] = str17; + strArrays16[7] = str18; + strArrays16[8] = str19; + strArrays16[9] = str20; + strArrays16[10] = str21; + strArrays16[11] = "
"); + } + if (sinistro.get_SinistroVida() != null) + { + str3 = string.Concat(str3, "
"); + num = 1; + string[] description2 = new string[] { str3, ""; + str3 = string.Concat(description2); + num = 0; + string[] strArrays17 = new string[] { str3, ""; + str3 = string.Concat(strArrays17); + num = 1; + string[] description3 = new string[] { str3, ""; + str3 = string.Concat(description3); + num = 0; + string[] certObito = new string[] { str3, ""; + str3 = string.Concat(certObito); + num = 1; + string[] beneficiario = new string[] { str3, ""; + str3 = string.Concat(beneficiario); + str3 = string.Concat(str3, "
TIPO PERDA: "; + description2[4] = ValidationHelper.GetDescription(sinistro.get_SinistroVida().get_TipoPerda()); + description2[5] = "
AUXÍLIO FUNERAL: "; + culpado = sinistro.get_SinistroVida().get_AuxFuneral(); + if (culpado.HasValue) + { + culpado = sinistro.get_SinistroVida().get_AuxFuneral(); + if (!culpado.Value) + { + goto Label3; + } + str = "SIM"; + goto Label2; + } + Label3: + str = "NÃO"; + Label2: + strArrays17[4] = str; + strArrays17[5] = "
ESTADO CIVIL: "; + description3[4] = ValidationHelper.GetDescription(sinistro.get_SinistroVida().get_EstadoCivil()); + description3[5] = "
CERTIDÃO DE ÓBITO: "; + certObito[4] = sinistro.get_SinistroVida().get_CertObito(); + certObito[5] = "
BENEFICIÁRIO: "; + beneficiario[4] = sinistro.get_SinistroVida().get_Beneficiario(); + beneficiario[5] = "
"); + } + if (!string.IsNullOrWhiteSpace(sinistro.get_Descricao())) + { + str3 = string.Concat(str3, "
"); + str3 = string.Concat(str3, "

DESCRIÇÃO

"); + str3 = string.Concat(str3, "
"); + str3 = string.Concat(str3, "
", sinistro.get_Descricao(), "
"); + } + if (string.IsNullOrWhiteSpace(sinistro.get_Observacao())) + { + continue; + } + str3 = string.Concat(str3, "
"); + str3 = string.Concat(str3, "

HISTÓRICO

"); + str3 = string.Concat(str3, "
"); + str3 = string.Concat(str3, "
", sinistro.get_Observacao().Replace("", "").Replace("", ""), "
"); + } + str3 = string.Concat(str3, "
"); + return str3; + } + + private static List GerarParceiros() + { + List parceiros = new List(); + Parceiro parceiro = new Parceiro(); + parceiro.set_Nome("NENHUM"); + parceiros.Add(parceiro); + parceiros.AddRange( + from x in Recursos.Parceiros + orderby x.get_Nome() + select x); + return parceiros; + } + + internal void ImprimirHistorico() + { + string nome; + Vendedor vendedorPrincipal = this._documentoSelecionado.get_VendedorPrincipal(); + if (vendedorPrincipal != null) + { + nome = vendedorPrincipal.get_Nome(); + } + else + { + nome = null; + } + string str = this.GerarHtmlSinistro(nome); + string tempPath = Path.GetTempPath(); + string str1 = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.html", tempPath, (TipoTela)7, Funcoes.GetNetworkTime()); + StreamWriter streamWriter = new StreamWriter(str1, true, Encoding.UTF8); + streamWriter.Write(str); + streamWriter.Close(); + Process.Start(str1); + } + + public async void IncluirEnvolvido() + { + Sinistro sinistro = new Sinistro(); + sinistro.set_ControleSinistro(this.SelectedControle); + sinistro.set_TipoSinistro(new TipoSinistro?(1)); + sinistro.set_Ativo(true); + sinistro.set_StatusSinistro(new StatusSinistro?(1)); + Sinistro sinistro1 = sinistro; + long id = this._documentoSelecionado.get_Controle().get_Ramo().get_Id(); + long num = id - (long)5; + if (num <= (long)5) + { + switch ((uint)num) + { + case 0: + { + sinistro1.set_SinistroAuto(new SinistroAuto()); + if (!await base.ShowMessage("VOCÊ DESEJA COPIAR OS DADOS DO SINISTRADO PARA O TERCEIRO?", "SIM", "NÃO", false)) + { + sinistro1.set_DataReclamacao(new DateTime?(Funcoes.GetNetworkTime())); + } + else + { + sinistro1.set_ItemSinistrado(this.SelectedItem.get_Descricao()); + sinistro1.set_Descricao(this.SelectedSinistro.get_Descricao()); + sinistro1.set_DataReclamacao(this.SelectedSinistro.get_DataReclamacao()); + if (sinistro1.get_SinistroAuto() != null) + { + if (this.SelectedSinistro.get_SinistroAuto() == null) + { + this.SelectedSinistro.set_SinistroAuto(new SinistroAuto()); + } + sinistro1.get_SinistroAuto().set_Endereco(this.SelectedSinistro.get_SinistroAuto().get_Endereco()); + } + } + this.IsReadOnlyItem = false; + this.SelectedSinistro = sinistro1; + base.Alterar(true); + sinistro1 = null; + return; + } + case 1: + case 2: + case 4: + case 5: + { + sinistro1.set_SinistroVida(new SinistroVida()); + if (!await base.ShowMessage("VOCÊ DESEJA COPIAR OS DADOS DO SINISTRADO PARA O TERCEIRO?", "SIM", "NÃO", false)) + { + sinistro1.set_DataReclamacao(new DateTime?(Funcoes.GetNetworkTime())); + } + else + { + sinistro1.set_ItemSinistrado(this.SelectedItem.get_Descricao()); + sinistro1.set_Descricao(this.SelectedSinistro.get_Descricao()); + sinistro1.set_DataReclamacao(this.SelectedSinistro.get_DataReclamacao()); + if (sinistro1.get_SinistroAuto() != null) + { + if (this.SelectedSinistro.get_SinistroAuto() == null) + { + this.SelectedSinistro.set_SinistroAuto(new SinistroAuto()); + } + sinistro1.get_SinistroAuto().set_Endereco(this.SelectedSinistro.get_SinistroAuto().get_Endereco()); + } + } + this.IsReadOnlyItem = false; + this.SelectedSinistro = sinistro1; + base.Alterar(true); + sinistro1 = null; + return; + } + case 3: + { + if (!await base.ShowMessage("VOCÊ DESEJA COPIAR OS DADOS DO SINISTRADO PARA O TERCEIRO?", "SIM", "NÃO", false)) + { + sinistro1.set_DataReclamacao(new DateTime?(Funcoes.GetNetworkTime())); + } + else + { + sinistro1.set_ItemSinistrado(this.SelectedItem.get_Descricao()); + sinistro1.set_Descricao(this.SelectedSinistro.get_Descricao()); + sinistro1.set_DataReclamacao(this.SelectedSinistro.get_DataReclamacao()); + if (sinistro1.get_SinistroAuto() != null) + { + if (this.SelectedSinistro.get_SinistroAuto() == null) + { + this.SelectedSinistro.set_SinistroAuto(new SinistroAuto()); + } + sinistro1.get_SinistroAuto().set_Endereco(this.SelectedSinistro.get_SinistroAuto().get_Endereco()); + } + } + this.IsReadOnlyItem = false; + this.SelectedSinistro = sinistro1; + base.Alterar(true); + sinistro1 = null; + return; + } + } + } + else + { + } + if (id != (long)37) + { + goto Label3; + } + sinistro1.set_SinistroAuto(new SinistroAuto()); + if (!await base.ShowMessage("VOCÊ DESEJA COPIAR OS DADOS DO SINISTRADO PARA O TERCEIRO?", "SIM", "NÃO", false)) + { + sinistro1.set_DataReclamacao(new DateTime?(Funcoes.GetNetworkTime())); + } + else + { + sinistro1.set_ItemSinistrado(this.SelectedItem.get_Descricao()); + sinistro1.set_Descricao(this.SelectedSinistro.get_Descricao()); + sinistro1.set_DataReclamacao(this.SelectedSinistro.get_DataReclamacao()); + if (sinistro1.get_SinistroAuto() != null) + { + if (this.SelectedSinistro.get_SinistroAuto() == null) + { + this.SelectedSinistro.set_SinistroAuto(new SinistroAuto()); + } + sinistro1.get_SinistroAuto().set_Endereco(this.SelectedSinistro.get_SinistroAuto().get_Endereco()); + } + } + this.IsReadOnlyItem = false; + this.SelectedSinistro = sinistro1; + base.Alterar(true); + sinistro1 = null; + return; + sinistro1.set_SinistroVida(new SinistroVida()); + if (!await base.ShowMessage("VOCÊ DESEJA COPIAR OS DADOS DO SINISTRADO PARA O TERCEIRO?", "SIM", "NÃO", false)) + { + sinistro1.set_DataReclamacao(new DateTime?(Funcoes.GetNetworkTime())); + } + else + { + sinistro1.set_ItemSinistrado(this.SelectedItem.get_Descricao()); + sinistro1.set_Descricao(this.SelectedSinistro.get_Descricao()); + sinistro1.set_DataReclamacao(this.SelectedSinistro.get_DataReclamacao()); + if (sinistro1.get_SinistroAuto() != null) + { + if (this.SelectedSinistro.get_SinistroAuto() == null) + { + this.SelectedSinistro.set_SinistroAuto(new SinistroAuto()); + } + sinistro1.get_SinistroAuto().set_Endereco(this.SelectedSinistro.get_SinistroAuto().get_Endereco()); + } + } + this.IsReadOnlyItem = false; + this.SelectedSinistro = sinistro1; + base.Alterar(true); + sinistro1 = null; + return; + Label3: + if (id != (long)53) + { + if (!await base.ShowMessage("VOCÊ DESEJA COPIAR OS DADOS DO SINISTRADO PARA O TERCEIRO?", "SIM", "NÃO", false)) + { + sinistro1.set_DataReclamacao(new DateTime?(Funcoes.GetNetworkTime())); + } + else + { + sinistro1.set_ItemSinistrado(this.SelectedItem.get_Descricao()); + sinistro1.set_Descricao(this.SelectedSinistro.get_Descricao()); + sinistro1.set_DataReclamacao(this.SelectedSinistro.get_DataReclamacao()); + if (sinistro1.get_SinistroAuto() != null) + { + if (this.SelectedSinistro.get_SinistroAuto() == null) + { + this.SelectedSinistro.set_SinistroAuto(new SinistroAuto()); + } + sinistro1.get_SinistroAuto().set_Endereco(this.SelectedSinistro.get_SinistroAuto().get_Endereco()); + } + } + this.IsReadOnlyItem = false; + this.SelectedSinistro = sinistro1; + base.Alterar(true); + sinistro1 = null; + return; + } + else + { + sinistro1.set_SinistroVida(new SinistroVida()); + if (!await base.ShowMessage("VOCÊ DESEJA COPIAR OS DADOS DO SINISTRADO PARA O TERCEIRO?", "SIM", "NÃO", false)) + { + sinistro1.set_DataReclamacao(new DateTime?(Funcoes.GetNetworkTime())); + } + else + { + sinistro1.set_ItemSinistrado(this.SelectedItem.get_Descricao()); + sinistro1.set_Descricao(this.SelectedSinistro.get_Descricao()); + sinistro1.set_DataReclamacao(this.SelectedSinistro.get_DataReclamacao()); + if (sinistro1.get_SinistroAuto() != null) + { + if (this.SelectedSinistro.get_SinistroAuto() == null) + { + this.SelectedSinistro.set_SinistroAuto(new SinistroAuto()); + } + sinistro1.get_SinistroAuto().set_Endereco(this.SelectedSinistro.get_SinistroAuto().get_Endereco()); + } + } + this.IsReadOnlyItem = false; + this.SelectedSinistro = sinistro1; + base.Alterar(true); + sinistro1 = null; + return; + } + if (!await base.ShowMessage("VOCÊ DESEJA COPIAR OS DADOS DO SINISTRADO PARA O TERCEIRO?", "SIM", "NÃO", false)) + { + sinistro1.set_DataReclamacao(new DateTime?(Funcoes.GetNetworkTime())); + } + else + { + sinistro1.set_ItemSinistrado(this.SelectedItem.get_Descricao()); + sinistro1.set_Descricao(this.SelectedSinistro.get_Descricao()); + sinistro1.set_DataReclamacao(this.SelectedSinistro.get_DataReclamacao()); + if (sinistro1.get_SinistroAuto() != null) + { + if (this.SelectedSinistro.get_SinistroAuto() == null) + { + this.SelectedSinistro.set_SinistroAuto(new SinistroAuto()); + } + sinistro1.get_SinistroAuto().set_Endereco(this.SelectedSinistro.get_SinistroAuto().get_Endereco()); + } + } + this.IsReadOnlyItem = false; + this.SelectedSinistro = sinistro1; + base.Alterar(true); + sinistro1 = null; + } + + public async Task IncluirSinistro() + { + Sinistro sinistro; + long id; + decimal num; + ControleSinistro controleSinistro; + if (this.SelectedItem != null) + { + DateTime networkTime = Funcoes.GetNetworkTime(); + ControleSinistro controleSinistro1 = new ControleSinistro(); + controleSinistro1.set_DataSinistro(new DateTime?(networkTime)); + controleSinistro1.set_Item(this.SelectedItem); + controleSinistro = controleSinistro1; + ObservableCollection observableCollection = await this._itemServico.BuscarCoberturasPorItemAsync(this.SelectedItem.get_Id()); + Cobertura cobertura = observableCollection.FirstOrDefault((Cobertura x) => { + if (x.get_CoberturaPadrao() == null) + { + return false; + } + return x.get_CoberturaPadrao().get_Id() == (long)1; + }); + Sinistro sinistro1 = new Sinistro(); + sinistro1.set_ControleSinistro(controleSinistro); + sinistro1.set_TipoSinistro(new TipoSinistro?(0)); + sinistro1.set_Ativo(true); + sinistro1.set_DataReclamacao(new DateTime?(networkTime)); + sinistro1.set_StatusSinistro(new StatusSinistro?(1)); + sinistro1.set_ItemSinistrado(this.SelectedItem.get_Descricao()); + num = (cobertura != null ? cobertura.get_Franquia() : decimal.Zero); + sinistro1.set_ValorFranquia(num); + sinistro = sinistro1; + id = this._documentoSelecionado.get_Controle().get_Ramo().get_Id(); + long num1 = id - (long)5; + if (num1 <= (long)5) + { + switch ((uint)num1) + { + case 0: + { + goto Label0; + } + case 1: + case 2: + case 4: + case 5: + { + goto Label1; + } + case 3: + { + goto Label2; + } + } + } + else + { + } + if (id != (long)37) + { + goto Label3; + } + Label0: + SinistroAuto sinistroAuto = new SinistroAuto(); + sinistroAuto.set_Culpado(new bool?(false)); + sinistro.set_SinistroAuto(sinistroAuto); + Label2: + this.IsReadOnlyItem = true; + this.SelectedControle = controleSinistro; + this.SelectedSinistro = sinistro; + base.Alterar(true); + } + else + { + await base.ShowMessage("NECESSÁRIO INCLUIR O ITEM ANTES DE INCLUIR UM SINISTRO.", "OK", "", false); + } + controleSinistro = null; + return; + Label1: + sinistro.set_SinistroVida(new SinistroVida()); + goto Label2; + Label3: + if (id != (long)53) + { + goto Label2; + } + else + { + goto Label1; + } + goto Label2; + } + + internal async Task> ItemFiltrar(string value) + { + List items = await Task.Run>(() => this.FiltrarItem(value)); + return items; + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + bool id; + bool flag; + string str1; + List> keyValuePairs1 = this.SelectedSinistro.Validate(); + if (keyValuePairs1.Count <= 0) + { + Sinistro selectedSinistro = this.SelectedSinistro; + if (selectedSinistro.get_SinistroAuto() != null) + { + Parceiro parceiroFunilaria = selectedSinistro.get_SinistroAuto().get_ParceiroFunilaria(); + if (parceiroFunilaria != null) + { + id = parceiroFunilaria.get_Id() == (long)0; + } + else + { + id = false; + } + if (id) + { + selectedSinistro.get_SinistroAuto().set_ParceiroFunilaria(null); + } + Parceiro parceiroMecanica = selectedSinistro.get_SinistroAuto().get_ParceiroMecanica(); + if (parceiroMecanica != null) + { + flag = parceiroMecanica.get_Id() == (long)0; + } + else + { + flag = false; + } + if (flag) + { + selectedSinistro.get_SinistroAuto().set_ParceiroMecanica(null); + } + } + DateTime networkTime = Funcoes.GetNetworkTime(); + if (!string.IsNullOrWhiteSpace(this.Anotacoes) && !this.Anotacoes.IsEmpty()) + { + Sinistro sinistro = selectedSinistro; + object[] nome = new object[] { Recursos.Usuario.get_Nome(), Recursos.Usuario.get_Id(), networkTime, this.Anotacoes, selectedSinistro.get_Observacao() }; + sinistro.set_Observacao(string.Format("

{0}, ID: {1}, {2:g}
{3}



{4}", nome)); + } + if (!string.IsNullOrWhiteSpace(this.AnotacoesInternas) && !this.AnotacoesInternas.IsEmpty()) + { + Sinistro sinistro1 = selectedSinistro; + object[] objArray = new object[] { Recursos.Usuario.get_Nome(), Recursos.Usuario.get_Id(), networkTime, this.AnotacoesInternas, selectedSinistro.get_ObservacaoInterna() }; + sinistro1.set_ObservacaoInterna(string.Format("

{0}, ID: {1}, {2:g}
{3}



{4}", objArray)); + } + if (selectedSinistro.get_Id() != 0) + { + selectedSinistro.set_DataAlteracao(new DateTime?(DateTime.Now)); + selectedSinistro.set_IdUsuarioAlteracao(Recursos.Usuario.get_Id()); + } + else + { + selectedSinistro.set_DataCriacao(new DateTime?(DateTime.Now)); + selectedSinistro.set_IdUsuarioCriacao(Recursos.Usuario.get_Id()); + } + str = (selectedSinistro.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str1 = str; + Sinistro sinistro2 = await this._servico.Save(selectedSinistro, this._documentoSelecionado.get_Controle().get_Ramo().get_Id()); + selectedSinistro = sinistro2; + if (this._servico.Sucesso) + { + await this.CarregarControles(selectedSinistro.get_ControleSinistro().get_Item()); + this.SelectedControle = this.ControlesFiltrados.First((ControleSinistro x) => x.get_Id() == selectedSinistro.get_ControleSinistro().get_Id()); + this.SelectedSinistro = this.SelectedControle.get_Sinistros().First((Sinistro x) => x.get_Id() == selectedSinistro.get_Id()); + Recursos.Parceiros = this.Parceiros.ToList(); + base.Alterar(false); + base.ToggleSnackBar("SINISTRO SALVO COM SUCESSO", true); + string str2 = string.Format("{0} SINISTRO DE ID \"{1}\"", str1, selectedSinistro.get_Id()); + long num = selectedSinistro.get_Id(); + TipoTela? nullable = new TipoTela?(7); + object[] id1 = new object[] { selectedSinistro.get_ControleSinistro().get_Item().get_Id(), selectedSinistro.get_ControleSinistro().get_Item().get_Documento().get_Id(), selectedSinistro.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Ramo().get_Nome(), selectedSinistro.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Cliente().get_Nome(), selectedSinistro.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Cliente().get_Id(), selectedSinistro.get_Descricao() }; + base.RegistrarAcao(str2, num, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}\nDESCRIÇÃO: \"{5}\"", id1)); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str1 = null; + return keyValuePairs; + } + + public async void Seleciona(Item item) + { + Visibility visibility; + Visibility visibility1; + base.Loading(true); + await base.PermissaoTela(7); + this.SelectedItem = this.ItemSelecionado; + SinistroViewModel sinistroViewModel = this; + visibility = (this._documentoSelecionado.get_Controle().get_Ramo().get_Id() == (long)5 ? Visibility.Visible : Visibility.Collapsed); + sinistroViewModel.VisibilityAuto = visibility; + SinistroViewModel sinistroViewModel1 = this; + visibility1 = (this._documentoSelecionado.get_Controle().get_Ramo().get_Id() == (long)6 ? Visibility.Visible : Visibility.Collapsed); + sinistroViewModel1.VisibilityVida = visibility1; + if (item != null) + { + await this.SelecionaControles(item); + base.Loading(false); + } + else + { + base.Loading(false); + } + } + + public void SelecionaControle(ControleSinistro controle) + { + List list; + bool sinistros; + if (this.Carregando) + { + return; + } + this.SelectedControle = controle; + ControleSinistro selectedControle = this.SelectedControle; + ControleSinistro controleSinistro = this.SelectedControle; + if (controleSinistro != null) + { + List sinistros1 = controleSinistro.get_Sinistros(); + if (sinistros1 != null) + { + list = ( + from x in sinistros1 + orderby x.get_Id() + select x).ToList(); + } + else + { + list = null; + } + } + else + { + list = null; + } + selectedControle.set_Sinistros(list); + if (this.Carregando) + { + return; + } + if (controle.get_Id() != this.SelectedControle.get_Id()) + { + this.SelectedControle = controle; + } + ControleSinistro selectedControle1 = this.SelectedControle; + if (selectedControle1 != null) + { + sinistros = selectedControle1.get_Sinistros(); + } + else + { + sinistros = false; + } + if (sinistros) + { + this.TipoSinistroEnabled = (!this.SelectedControle.get_Sinistros().Any((Sinistro x) => { + TipoSinistro? tipoSinistro = x.get_TipoSinistro(); + return tipoSinistro.GetValueOrDefault() == 0 & tipoSinistro.HasValue; + }) ? true : this.SelectedControle.get_Sinistros().Count <= 1); + } + } + + public async Task SelecionaControles(Item item) + { + Sinistro sinistro; + base.Loading(true); + await this.CarregarControles(item); + if (this.ControlesFiltrados.Count <= 0) + { + this.SelectedControle = new ControleSinistro(); + base.Alterar(false); + } + else + { + this.SelectedControle = this.ControlesFiltrados.FirstOrDefault(); + } + SinistroViewModel sinistroViewModel = this; + ControleSinistro selectedControle = this.SelectedControle; + if (selectedControle != null) + { + List sinistros = selectedControle.get_Sinistros(); + if (sinistros != null) + { + sinistro = sinistros.FirstOrDefault(); + } + else + { + sinistro = null; + } + } + else + { + sinistro = null; + } + sinistroViewModel.SelectedSinistro = sinistro; + base.Loading(false); + } + + public async void SelecionaItem(Item item) + { + if (!this.Carregando) + { + this.SelectedItem = item; + if (this.SelectedItem != null) + { + if (!this.Carregando) + { + if (item.get_Id() != this.SelectedItem.get_Id()) + { + this.SelectedItem = this.ItensFiltrados.FirstOrDefault((Item x) => x.get_Id() == item.get_Id()); + } + await this.SelecionaControles(item); + } + } + } + } + + public async Task SelecionaItens(int type, Item item = null) + { + bool count; + Item item1; + base.Loading(true); + this.Carregando = true; + switch (type) + { + case 1: + case 2: + { + this.Itens = await this._itemServico.BuscarItens(this._documentoSelecionado.get_Id(), 2); + break; + } + case 3: + { + this.Itens = await this._itemServico.BuscarItens(this._documentoSelecionado.get_Controle().get_Id(), 1); + break; + } + case 4: + { + this.Itens = await this._itemServico.BuscarItens(this._documentoSelecionado.get_Controle().get_Id(), 3); + break; + } + default: + { + this.Itens = await this._itemServico.BuscarItens(this._documentoSelecionado.get_Controle().get_Id(), 0); + break; + } + } + this.ItensFiltrados = this.Itens; + if (item != null && item.get_Id() > (long)0) + { + SinistroViewModel sinistroViewModel = this; + if (this.ItensFiltrados == null || this.ItensFiltrados.Count <= 0) + { + item1 = null; + } + else + { + item1 = this.ItensFiltrados.FirstOrDefault((Item x) => x.get_Id() == item.get_Id()); + } + sinistroViewModel.SelectedItem = item1; + } + SinistroViewModel sinistroViewModel1 = this; + if (this.MostrarLista) + { + count = true; + } + else + { + ObservableCollection itens = this.Itens; + if (itens != null) + { + count = itens.Count > 1; + } + else + { + count = false; + } + } + sinistroViewModel1.MostrarLista = count; + this.Carregando = false; + base.Loading(false); + } + + internal async Task> SinistroFiltrar(string value) + { + List controleSinistros = await Task.Run>(() => this.FiltrarSinistro(value)); + return controleSinistros; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Seguros/TrocarClienteViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Seguros/TrocarClienteViewModel.cs new file mode 100644 index 0000000..35881fd --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Seguros/TrocarClienteViewModel.cs @@ -0,0 +1,92 @@ +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Seguros +{ + public class TrocarClienteViewModel : BaseSegurosViewModel + { + private readonly ApoliceServico _apoliceServico; + + private readonly ClienteServico _clienteServico; + + private Documento _selectedDocumento; + + private Cliente _selectedCliente; + + public Cliente SelectedCliente + { + get + { + return this._selectedCliente; + } + set + { + base.OnPropertyChanged("SelectedCliente"); + this._selectedCliente = value; + } + } + + public Documento SelectedDocumento + { + get + { + return this._selectedDocumento; + } + set + { + base.OnPropertyChanged("SelectedDocumento"); + this._selectedDocumento = value; + } + } + + public TrocarClienteViewModel() + { + this._apoliceServico = new ApoliceServico(); + this._clienteServico = new ClienteServico(); + } + + public async Task Salvar() + { + bool flag; + Cliente cliente; + Documento selectedDocumento; + if (this.SelectedCliente == null) + { + flag = false; + } + else if (this.SelectedCliente.get_Id() != this.SelectedDocumento.get_Controle().get_Cliente().get_Id()) + { + cliente = await this._clienteServico.BuscarCliente(this.SelectedDocumento.get_Controle().get_Cliente().get_Id()); + selectedDocumento = this.SelectedDocumento; + this._apoliceServico.Sucesso = true; + await this._apoliceServico.Save(selectedDocumento.get_Controle(), this.SelectedCliente); + if (this._apoliceServico.Sucesso) + { + base.RegistrarAcao(string.Format("TROCOU O CLIENTE DO DOCUMENTO DE ID {0}", this.SelectedDocumento.get_Id()), this.SelectedDocumento.get_Id(), new TipoTela?(41), string.Format("CLIENTE ANTIGO: {0}\nNOVO CLIENTE: {1} ({2})", cliente.get_Nome(), this.SelectedCliente.get_Nome(), this.SelectedCliente.get_Id())); + this.SelectedCliente = selectedDocumento.get_Controle().get_Cliente(); + this.SelectedDocumento = selectedDocumento; + flag = true; + } + else + { + flag = false; + } + } + else + { + flag = false; + } + cliente = null; + selectedDocumento = null; + return flag; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/TrilhaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/TrilhaViewModel.cs new file mode 100644 index 0000000..a818704 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/TrilhaViewModel.cs @@ -0,0 +1,284 @@ +using Gestor.Application.Actions; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels +{ + public class TrilhaViewModel : BaseSegurosViewModel + { + private ObservableCollection _trilhas = new ObservableCollection(); + + private ObservableCollection _fases = new ObservableCollection(); + + private Trilha _selectedTrilha = new Trilha(); + + private Tarefa _selectedTarefa; + + private ObservableCollection _usuarios; + + private Usuario _selectedUsuario = new Usuario(); + + public ObservableCollection Fases + { + get + { + return this._fases; + } + set + { + this._fases = value; + base.OnPropertyChanged("Fases"); + } + } + + public Tarefa SelectedTarefa + { + get + { + return this._selectedTarefa; + } + set + { + this._selectedTarefa = value; + base.OnPropertyChanged("SelectedTarefa"); + } + } + + public Trilha SelectedTrilha + { + get + { + return this._selectedTrilha; + } + set + { + this._selectedTrilha = value; + base.OnPropertyChanged("SelectedTrilha"); + } + } + + public Usuario SelectedUsuario + { + get + { + return this._selectedUsuario; + } + set + { + this._selectedUsuario = value; + base.OnPropertyChanged("SelectedUsuario"); + } + } + + private TarefaServico Servico + { + get; + } + + public ObservableCollection Trilhas + { + get + { + return this._trilhas; + } + set + { + this._trilhas = value; + base.OnPropertyChanged("Trilhas"); + } + } + + public ObservableCollection Usuarios + { + get + { + return this._usuarios; + } + set + { + this._usuarios = value; + base.OnPropertyChanged("Usuarios"); + } + } + + public TrilhaViewModel() + { + this.Servico = new TarefaServico(); + List usuarios = new List(); + Usuario usuario = new Usuario(); + usuario.set_Id((long)0); + usuario.set_Nome("TODOS OS USUÁRIOS"); + usuarios.Add(usuario); + List usuarios1 = usuarios; + usuarios1.AddRange(Recursos.Usuarios.Where((Usuario x) => { + if (Recursos.Usuario.get_IdEmpresa() != (long)1 && x.get_IdEmpresa() != Recursos.Usuario.get_IdEmpresa()) + { + return false; + } + return !x.get_Excluido(); + }).OrderBy((Usuario x) => x.get_Nome()).ToList()); + this.Usuarios = new ObservableCollection(usuarios1); + this.SelectedUsuario = this.Usuarios.First(); + Gestor.Application.Actions.Actions.AtualizaTrilhas = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.AtualizaTrilhas, new Action(this.AtualizarTrilhas)); + this.CarregaTrilhas(); + } + + public void AtualizarTrilhas() + { + this.CarregaTrilhas(); + } + + public async Task Cancelar() + { + await this.CarregarTrilha(this.SelectedTrilha); + base.Alterar(false); + } + + public async Task CarregarTrilha(Trilha trilha) + { + if (trilha != null && trilha.get_Id() != 0) + { + this.SelectedTrilha = trilha; + List tarefas = await this.Servico.BuscarTarefas(trilha.get_Id()); + List tarefas1 = tarefas; + List fases = await this.Servico.BuscarFases(trilha.get_Id()); + this.Fases = new ObservableCollection(); + fases.ForEach((Fase x) => { + x.set_Tarefas(tarefas1.Where((Tarefa t) => { + if (this.SelectedUsuario != null && this.SelectedUsuario.get_Id() != 0 && this.SelectedUsuario.get_Id() != t.get_Usuario().get_Id() || t.get_Fase().get_Id() != x.get_Id()) + { + return false; + } + return t.get_Status() != 2; + }).ToList()); + this.Fases.Add(x); + }); + } + } + + public async Task CarregarTrilhas(Trilha trilha = null) + { + Trilha trilha1; + List trilhas = await this.Servico.BuscarTrilhas(); + this.Trilhas = new ObservableCollection(trilhas); + TrilhaViewModel trilhaViewModel = this; + trilha1 = (trilha != null ? this.Trilhas.FirstOrDefault((Trilha x) => x.get_Id() == trilha.get_Id()) : trilhas.FirstOrDefault()); + await trilhaViewModel.CarregarTrilha(trilha1); + } + + public async void CarregaTrilhas() + { + await this.CarregarTrilhas(null); + } + + public void Excluir(Fase origem, Tarefa data) + { + Tarefa tarefa = this.Fases.First((Fase x) => x.get_Id() == origem.get_Id()).get_Tarefas().First((Tarefa x) => x.get_Id() == data.get_Id()); + this.Fases.First((Fase x) => x.get_Id() == origem.get_Id()).get_Tarefas().Remove(tarefa); + } + + public async Task Excluir(Tarefa tarefa) + { + if (tarefa.get_Id() != 0) + { + string[] titulo = new string[] { "DESEJA REALMENTE EXCLUIR A TAREFA ", tarefa.get_Titulo(), "?", Environment.NewLine, "ESSE PROCEDIMENTO É IRREVERSÍVEL" }; + if (await base.ShowMessage(string.Concat(titulo), "SIM", "NÃO", false)) + { + if (await this.Servico.Excluir(tarefa.get_Id())) + { + await this.CarregarTrilha(this.SelectedTrilha); + base.Alterar(false); + } + else + { + base.Alterar(false); + } + } + } + } + + public void Inserir(Fase origem, Tarefa data, int index, bool aberto = false) + { + data.set_Aberto(aberto); + data.set_Fase(origem); + this.Fases.First((Fase x) => x.get_Id() == origem.get_Id()).get_Tarefas().Insert((index == -1 ? 0 : index), data); + this.TrocarFase(data); + } + + public async Task>> Salvar(Tarefa destino) + { + List> keyValuePairs; + Tarefa tarefa = destino; + List configuracoes = Recursos.Configuracoes; + tarefa.set_AgendamentoRetroativo(configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 45)); + List> keyValuePairs1 = destino.Validate(); + if (keyValuePairs1.Count <= 0) + { + await this.Servico.Salvar(destino); + if (this.Servico.Sucesso) + { + await this.CarregarTrilha(this.SelectedTrilha); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + return keyValuePairs; + } + + public async Task Salvar(Trilha destino) + { + TrilhaViewModel.u003cu003ec__DisplayClass37_0 variable; + this.SelectedTrilha = null; + this.Fases = null; + List fases = destino.get_Fases(); + Trilha trilha = await this.Servico.Salvar(destino); + if (this.Servico.Sucesso) + { + if (fases != null) + { + fases.ForEach((Fase x) => x.set_Trilha(trilha)); + await this.Servico.Salvar(fases); + if (!this.Servico.Sucesso) + { + variable = null; + fases = null; + return; + } + } + await this.CarregarTrilhas(trilha); + } + variable = null; + fases = null; + } + + private async void TrocarFase(Tarefa tarefa) + { + await this.Servico.Salvar(tarefa); + } + + public void Update() + { + this.Fases = new ObservableCollection(this.Fases); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/TutorialViewModel.cs b/Codemerx/Gestor.Application/ViewModels/TutorialViewModel.cs new file mode 100644 index 0000000..d027b83 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/TutorialViewModel.cs @@ -0,0 +1,612 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Ajuda; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Security; +using Gestor.Model.API; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.License; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text.RegularExpressions; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels +{ + public class TutorialViewModel : BaseViewModel + { + private bool _fase1; + + private bool _fase2; + + private bool _fase3; + + private string _mensagem = "ESTAMOS PREPARANDO TUDO PRA VOCÊ INICIAR"; + + private string _nome; + + private string _usuario; + + private string _senha; + + private string _confirmacaoSenha; + + private ObservableCollection _seguradoras = new ObservableCollection(); + + private ObservableCollection _ramos = new ObservableCollection(); + + private bool _loadingVisibility; + + private long _idUsuario { get; set; } = (long)-1; + + public string ConfirmacaoSenha + { + get + { + return this._confirmacaoSenha; + } + set + { + this._confirmacaoSenha = value; + base.OnPropertyChanged("ConfirmacaoSenha"); + } + } + + private Customer Empresa + { + get; + set; + } + + public bool Fase1 + { + get + { + return this._fase1; + } + set + { + this._fase1 = value; + base.OnPropertyChanged("Fase1"); + } + } + + public bool Fase2 + { + get + { + return this._fase2; + } + set + { + this._fase2 = value; + base.OnPropertyChanged("Fase2"); + } + } + + public bool Fase3 + { + get + { + return this._fase3; + } + set + { + this._fase3 = value; + base.OnPropertyChanged("Fase3"); + } + } + + public bool LoadingVisibility + { + get + { + return this._loadingVisibility; + } + set + { + this._loadingVisibility = value; + base.OnPropertyChanged("LoadingVisibility"); + } + } + + public string Mensagem + { + get + { + return this._mensagem; + } + set + { + this._mensagem = value; + base.OnPropertyChanged("Mensagem"); + } + } + + public string Nome + { + get + { + return this._nome; + } + set + { + this._nome = value; + base.OnPropertyChanged("Nome"); + } + } + + public ObservableCollection Ramos + { + get + { + return this._ramos; + } + set + { + this._ramos = value; + base.OnPropertyChanged("Ramos"); + } + } + + public ObservableCollection Seguradoras + { + get + { + return this._seguradoras; + } + set + { + this._seguradoras = value; + base.OnPropertyChanged("Seguradoras"); + } + } + + public string Senha + { + get + { + return this._senha; + } + set + { + this._senha = value; + base.OnPropertyChanged("Senha"); + } + } + + public string Usuario + { + get + { + return this._usuario; + } + set + { + this._usuario = value; + base.OnPropertyChanged("Usuario"); + } + } + + public TutorialViewModel() + { + base.EnableFields = true; + } + + public async Task Concluir() + { + bool flag; + SeguradoraServico seguradoraServico; + RamoServico ramoServico; + this.Fase3 = false; + ObservableCollection ramos = this.Ramos; + if (!ramos.All((Ramo x) => !x.get_Ativo())) + { + this.Mensagem = "ESTAMOS TERMINANDO AS CONFIGURAÇÕES INICIAIS E LOGO MAIS VOCÊ PODERÁ UTILIZAR."; + if (await this.UsuarioInicial()) + { + seguradoraServico = new SeguradoraServico(); + foreach (Seguradora seguradora in this.Seguradoras) + { + await seguradoraServico.Save(seguradora, null, true); + if (seguradoraServico.Sucesso) + { + continue; + } + flag = false; + seguradoraServico = null; + ramoServico = null; + return flag; + } + ramoServico = new RamoServico(); + foreach (Ramo ramo in this.Ramos) + { + await ramoServico.Save(ramo, null); + if (ramoServico.Sucesso) + { + continue; + } + flag = false; + seguradoraServico = null; + ramoServico = null; + return flag; + } + await (new BaseServico()).LoadInicialParameters(); + flag = true; + } + else + { + flag = false; + } + } + else + { + await base.ShowMessage("NECESSÁRIO AO MENOS UM RAMO ATIVO PARA PROSSEGUIR.", "OK", "", false); + this.Fase3 = true; + flag = false; + } + seguradoraServico = null; + ramoServico = null; + return flag; + } + + public async Task CriarBanco() + { + string str; + string str1 = await (new ConnectionHelper()).VerifyConnection(); + if (str1 != null) + { + str = str1; + } + else + { + Instancia.ExcluirCfg(); + str = await this.VerificaEmpresa(); + } + return str; + } + + public void DesativarRamos() + { + foreach (Ramo ramo in this.Ramos) + { + ramo.set_Ativo(false); + } + this.Ramos = new ObservableCollection(this.Ramos); + } + + public void DesativarSeguradoras() + { + foreach (Seguradora seguradora in this.Seguradoras) + { + seguradora.set_Ativo(false); + } + this.Seguradoras = new ObservableCollection(this.Seguradoras); + } + + public async Task IniciarConfiguracoes() + { + List seguradoras; + base.EnableButtons = false; + ConnectionHelper connectionHelper = new ConnectionHelper(); + EmpresaServico empresaServico = new EmpresaServico(); + Gestor.Model.Domain.Common.Empresa empresa = await empresaServico.BuscarEmpresaPorId((long)1); + this.Empresa = await Connection.Get(string.Format("Customer/{0}", ApplicationHelper.IdFornecedor), true, false); + if (empresa == null) + { + await empresaServico.Save(this.Empresa); + } + BaseServico baseServico = new BaseServico(); + ControleArquivoDigital controleArquivoDigital = await baseServico.BuscarControle(); + if (controleArquivoDigital == null) + { + controleArquivoDigital = new ControleArquivoDigital(); + controleArquivoDigital.set_Catalogo(Connection.Catalog); + controleArquivoDigital.set_Tabela("Arquivos"); + } + ControleArquivoDigital controleArquivoDigital1 = controleArquivoDigital; + if (controleArquivoDigital1.get_Id() == 0) + { + await baseServico.SalvarControle(controleArquivoDigital1); + } + VendedorServico vendedorServico = new VendedorServico(); + Vendedor vendedor = await vendedorServico.BuscarCorretora(); + if (vendedor == null) + { + vendedor = new Vendedor(); + vendedor.set_IdEmpresa((long)1); + vendedor.set_Nome(this.Empresa.get_Name()); + vendedor.set_Ativo(true); + vendedor.set_Corretora(true); + } + Vendedor vendedor1 = vendedor; + if (vendedor1.get_Id() == 0) + { + Repasse repasse = new Repasse(); + repasse.set_Forma(new FormaRepasse?(1)); + repasse.set_Incidencia(new TipoIncidencia?(1)); + repasse.set_Ativo(true); + repasse.set_Tipo(new TipoRepasse?(2)); + repasse.set_ValorNovo(decimal.Zero); + repasse.set_ValorRenovacao(decimal.Zero); + await vendedorServico.Save(vendedor1, repasse); + if (!vendedorServico.Sucesso) + { + connectionHelper = null; + empresaServico = null; + empresa = null; + baseServico = null; + vendedorServico = null; + seguradoras = null; + return; + } + } + await (new Gestor.Application.Servicos.ArquivoDigitalServico()).Criar(); + string str = await connectionHelper.AtualizarBanco(); + if (str == null) + { + seguradoras = await (new SeguradoraServico()).BuscarSeguradoras(); + List ramos = await (new RamoServico()).BuscarRamos(); + TutorialViewModel observableCollection = this; + List seguradoras1 = seguradoras; + observableCollection.Seguradoras = new ObservableCollection( + from x in seguradoras1 + orderby x.get_Nome() + select x); + TutorialViewModel tutorialViewModel = this; + List ramos1 = ramos; + tutorialViewModel.Ramos = new ObservableCollection( + from x in ramos1 + orderby x.get_Nome() + select x); + base.EnableButtons = true; + } + else + { + await base.ShowMessage(str, "OK", "", false); + } + connectionHelper = null; + empresaServico = null; + empresa = null; + baseServico = null; + vendedorServico = null; + seguradoras = null; + } + + private async Task SalvarUsuario(Gestor.Model.Domain.Seguros.Usuario verificaUsuario) + { + long id; + string ssoId; + TutorialViewModel tutorialViewModel = this; + Gestor.Model.Domain.Seguros.Usuario usuario = verificaUsuario; + if (usuario != null) + { + id = usuario.get_Id(); + } + else + { + id = (long)0; + } + tutorialViewModel._idUsuario = id; + Gestor.Model.Domain.Seguros.Usuario usuario1 = new Gestor.Model.Domain.Seguros.Usuario(); + usuario1.set_Id(this._idUsuario); + usuario1.set_Nome(this.Nome); + usuario1.set_Login(this.Usuario); + usuario1.set_Senha((new Token()).AggerEncrypt(this.Senha)); + usuario1.set_Administrador(true); + usuario1.set_Excluido(false); + usuario1.set_IdEmpresa((long)1); + usuario1.set_PermissaoAggilizador(new long?((long)1)); + Gestor.Model.Domain.Seguros.Usuario usuario2 = verificaUsuario; + if (usuario2 != null) + { + ssoId = usuario2.get_SsoId(); + } + else + { + ssoId = null; + } + usuario1.set_SsoId(ssoId); + Gestor.Model.Domain.Seguros.Usuario usuario3 = usuario1; + usuario3 = await (new UsuarioServico()).Save(usuario3); + this._idUsuario = usuario3.get_Id(); + Recursos.Usuario = usuario3; + } + + public async Task UsuarioInicial() + { + bool flag; + Gestor.Model.Domain.Seguros.Usuario usuario = await (new UsuarioServico()).BuscaUsuarioInicial(this.Usuario, this.Senha); + if (usuario != null) + { + await this.SalvarUsuario(usuario); + flag = true; + } + else + { + await base.ShowMessage("USUÁRIO JÁ EXISTE E A SENHA ESTÁ INCORRETA, REINICIE O SISTEMA!", "OK", "", false); + flag = false; + } + return flag; + } + + public async Task ValidarLogin() + { + bool flag; + this.Fase1 = false; + this.Mensagem = "ESTAMOS VALIDANDO AS INFORMAÇÕES"; + if (string.IsNullOrEmpty(this.Usuario) || string.IsNullOrEmpty(this.Senha) || string.IsNullOrEmpty(this.ConfirmacaoSenha) || string.IsNullOrEmpty(this.Nome)) + { + await base.ShowMessage("NECESSÁRIO PREENCHER O NOME COMPLETO, USUÁRIO, SENHA E CONFIRMAÇÃO DA SENHA PARA PROSSEGUIR.", "OK", "", false); + this.Fase1 = true; + flag = true; + } + else if (!string.IsNullOrEmpty(this.Usuario) && !Regex.IsMatch(this.Usuario, "^(?!.*(@.*@|@\\.|\\.@|--|\\.\\.|-\\.|\\.-|-@|@-))[a-zA-Z0-9](?:[a-zA-Z0-9@.-]*[a-zA-Z0-9])?(?: [a-zA-Z0-9](?:[a-zA-Z0-9@.-]*[a-zA-Z0-9])?)?$")) + { + string[] newLine = new string[] { "USUÁRIO DEVE CONTER APENAS LETRAS E NÚMEROS,", Environment.NewLine, "NÃO DEVE CONTER MAIS DE UM ESPAÇO,", Environment.NewLine, "NÃO DEVE TER ESPAÇO NO INICIO E NO FIM.", Environment.NewLine, "EXEMPLO VALIDO:", Environment.NewLine, "USUARIO01 OU USUARIO 02 OU USUARIO.03" }; + await base.ShowMessage(string.Concat(newLine), "OK", "", false); + this.Fase1 = true; + flag = true; + } + else if (this.Usuario.Length > 30) + { + await base.ShowMessage("USUÁRIO SOMENTE DEVE CONTER NO MÁXIMO 30 CARACTERES", "OK", "", false); + this.Fase1 = true; + flag = true; + } + else if (this.Senha != this.ConfirmacaoSenha) + { + await base.ShowMessage("A SENHA E A CONFIRMAÇÃO DA SENHA ESTÃO DIFERENTES, CORRIJA PARA PROSSEGUIR.", "OK", "", false); + this.Fase1 = true; + flag = true; + } + else if (await this.UsuarioInicial()) + { + while (this.Seguradoras.Count == 0) + { + await Task.Delay(25); + } + this.Fase1 = false; + this.Fase2 = true; + flag = true; + } + else + { + flag = false; + } + return flag; + } + + public async Task ValidarSeguradoras() + { + this.Fase2 = false; + ObservableCollection seguradoras = this.Seguradoras; + if (!seguradoras.All((Seguradora x) => !x.get_Ativo())) + { + this.Fase2 = false; + this.Fase3 = true; + } + else + { + await base.ShowMessage("NECESSÁRIO AO MENOS UMA SEGURADORA ATIVA PARA PROSSEGUIR.", "OK", "", false); + this.Fase2 = true; + } + } + + public async Task VerificaAcesso() + { + bool flag; + Instalacao instalacao; + LicenseHelper licenseHelper = new LicenseHelper(); + bool flag1 = false; + if (!await licenseHelper.VerificarMaquina()) + { + base.Loading(false); + while (!flag1) + { + List instalacoes = await licenseHelper.GetInstalacoes(); + if (instalacoes.Count != 0) + { + List instalacaos = instalacoes; + IOrderedEnumerable ultimoAcesso = + from x in instalacaos + orderby x.get_UltimoAcesso() descending + select x; + Instalacao instalacao1 = ultimoAcesso.FirstOrDefault((Instalacao x) => x.get_UsuarioId() == Recursos.Usuario.get_Id()); + bool flag2 = instalacao1 != null; + if (flag2) + { + flag2 = await base.ShowMessage(string.Concat("SEU ULTIMO ACESSO FOI NA MAQUINA ", instalacao1.get_NomeMaquina(), ". DESEJA SUBSTITUIR A LICENÇA PARA ESSA MAQUINA?"), "SIM", "NÃO", false); + } + if (!flag2) + { + instalacao = await base.ShowInstalacoes(instalacoes); + } + else + { + instalacao = instalacao1; + } + Instalacao instalacao2 = instalacao; + if (instalacao2 != null) + { + await (new AjudaServico()).ExcluirInstalacao(instalacao2.get_Id()); + flag2 = await licenseHelper.VerificarMaquina(); + flag1 = flag2; + instalacoes = null; + instalacao1 = null; + } + else + { + await base.ShowMessage("MÁQUINA NÃO REGISTRADA", "OK", "", false); + flag = false; + licenseHelper = null; + return flag; + } + } + else + { + await base.ShowMessage("ACESSO NEGADO, NÃO EXISTEM LICENÇAS VÁLIDAS.", "OK", "", false); + flag = false; + licenseHelper = null; + return flag; + } + } + } + flag = true; + licenseHelper = null; + return flag; + } + + public async Task VerificaEmpresa() + { + string str; + ConnectionHelper connectionHelper = new ConnectionHelper(); + this.Empresa = await Connection.Get(string.Format("Customer/{0}", ApplicationHelper.IdFornecedor), true, false); + EmpresaServico empresaServico = new EmpresaServico(); + if (!connectionHelper.ExisteEmpresa()) + { + await empresaServico.Save(this.Empresa); + if (!empresaServico.Sucesso) + { + str = "ERRO AO CRIAR BANCO DE DADOS"; + connectionHelper = null; + empresaServico = null; + return str; + } + } + else if (!connectionHelper.BDConvertido()) + { + str = "HOUVE UM ERRO NO ACESSO! REINICIE O SISTEMA!"; + connectionHelper = null; + empresaServico = null; + return str; + } + str = null; + connectionHelper = null; + empresaServico = null; + return str; + } + + public async Task VerificarUsuario() + { + Instancia.ExcluirCfg(); + Gestor.Model.Domain.Seguros.Usuario usuario = await (new UsuarioServico()).BuscarUsuarioPorId((long)1); + if (usuario != null) + { + this.Nome = usuario.get_Nome(); + this.Usuario = usuario.get_Login(); + this._idUsuario = usuario.get_Id(); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Ajuda/AtendimentosView.cs b/Codemerx/Gestor.Application/Views/Ajuda/AtendimentosView.cs new file mode 100644 index 0000000..9cf46c0 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Ajuda/AtendimentosView.cs @@ -0,0 +1,302 @@ +using Gestor.Application.Componentes; +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels.Drawer.Ajuda; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Ferramentas; +using Gestor.Application.Views.Generic; +using Gestor.Model.API; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Seguros; +using MaterialDesignThemes.Wpf; +using mshtml; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using Xceed.Wpf.AvalonDock.Controls; + +namespace Gestor.Application.Views.Ajuda +{ + public class AtendimentosView : BaseUserControl, IComponentConnector, IStyleConnector + { + internal AtendimentosViewModel ViewModel; + + internal ComboBox StatusCbo; + + internal DataGrid AtendimentosGrid; + + internal DataGridTextColumn SolucaoColumn; + + internal TextBox NomeBox; + + internal TextBox Ddd; + + internal TextBox TelefoneBox; + + internal TextBox ValorBox; + + internal TextBox AssuntoBox; + + internal TextBox IdAcessoBox; + + internal TextBox SenhaBox; + + internal Gestor.Application.Componentes.WebEditor WebEditor; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public AtendimentosView() + { + this.ViewModel = new AtendimentosViewModel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + this.ViewModel.Head = string.Concat(Recursos.Usuario.get_Nome(), " - ", Recursos.Empresa.get_Nome(), ", VOCÊ ESTÁ EM ATENDIMENTOS"); + this.StatusCbo.SelectedIndex = 0; + this.ViewModel.IsVisible = System.Windows.Visibility.Visible; + } + + private void AbrirAntendimento_OnClick(object sender, RoutedEventArgs e) + { + this.AtendimentosGrid.SelectedItem = null; + this.ViewModel.LimparComponentes(); + if (this.WebEditor.WebBrowserEditor.HtmlDocument.body != null) + { + this.WebEditor.WebBrowserEditor.HtmlDocument.body.innerHTML = string.Empty; + } + this.ViewModel.AtendimentoVisibility = System.Windows.Visibility.Collapsed; + this.ViewModel.EnvioEmailVisibility = System.Windows.Visibility.Visible; + this.ViewModel.IsEnabled = false; + } + + private void AcessoRemoto_OnClick(object sender, RoutedEventArgs e) + { + string str = "c:\\AggerSeguros\\Remoto.exe"; + if (File.Exists(str)) + { + Process.Start(str); + return; + } + Parameters parameter = new Parameters(); + parameter.set_Beta(false); + parameter.set_Type(99); + parameter.set_Application("Remoto.exe"); + parameter.set_Directory(""); + parameter.set_Run(true); + (new DownloadWindow(parameter)).Show(); + } + + private void AnexarArquivos_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Anexar(); + } + + private void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.IsEnabled = true; + this.ViewModel.SelecionaAtendimento(); + } + + private void DeleteArquivo_OnDeleteClick(object sender, RoutedEventArgs e) + { + Chip chip = sender as Chip; + if (chip == null) + { + return; + } + ListBox listBox = Extentions.FindVisualAncestor(chip); + Gestor.Model.Domain.Common.ArquivoDigital item = (Gestor.Model.Domain.Common.ArquivoDigital)listBox.Items[listBox.Items.IndexOf(chip.DataContext)]; + if (item == null) + { + return; + } + this.ViewModel.Delete(item); + } + + private async void Enviar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.Loading(true); + this.ViewModel.Corpo = this.WebEditor.GetHtml(); + List> keyValuePairs = await this.ViewModel.Enviar(); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + if (keyValuePairs != null) + { + List> keyValuePairs1 = keyValuePairs; + if (keyValuePairs1.Any>((KeyValuePair x) => x.Key == "fail")) + { + List> keyValuePairs2 = keyValuePairs; + List> keyValuePairs3 = keyValuePairs; + keyValuePairs2.Remove(keyValuePairs3.First>((KeyValuePair x) => x.Key == "fail")); + } + } + this.ValidateFields(keyValuePairs, true); + this.ViewModel.Loading(false); + if (flag) + { + await this.ViewModel.ShowMessage("SOLICITAÇÃO ENVIADA PARA AGGER, POR FAVOR AGUARDE NOSSO RETORNO!", "OK", "", false); + this.WebEditor.Body = ""; + } + else + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/ajuda/atendimentosview.xaml", UriKind.Relative)); + } + + private void SelectedStatus_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + if (this.StatusCbo.SelectedItem == null) + { + return; + } + this.ViewModel.WorkOnSelectedStatus(this.StatusCbo.SelectedItem.ToString()); + this.SolucaoColumn.Visibility = (this.StatusCbo.SelectedItem.ToString() == "PENDENTES" ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.StatusCbo = (ComboBox)target; + this.StatusCbo.SelectionChanged += new SelectionChangedEventHandler(this.SelectedStatus_OnSelectionChanged); + return; + } + case 2: + { + ((Button)target).Click += new RoutedEventHandler(this.AbrirAntendimento_OnClick); + return; + } + case 3: + { + this.AtendimentosGrid = (DataGrid)target; + return; + } + case 4: + { + this.SolucaoColumn = (DataGridTextColumn)target; + return; + } + case 5: + { + ((Button)target).Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 6: + { + ((Button)target).Click += new RoutedEventHandler(this.AnexarArquivos_OnClick); + return; + } + case 7: + { + ((Button)target).Click += new RoutedEventHandler(this.Enviar_OnClick); + return; + } + case 8: + { + this.NomeBox = (TextBox)target; + return; + } + case 9: + { + this.Ddd = (TextBox)target; + AtendimentosView atendimentosView = this; + this.Ddd.PreviewTextInput += new TextCompositionEventHandler(atendimentosView.SomenteNumeros); + return; + } + case 10: + { + this.TelefoneBox = (TextBox)target; + AtendimentosView atendimentosView1 = this; + this.TelefoneBox.LostFocus += new RoutedEventHandler(atendimentosView1.FormatarTelefone); + AtendimentosView atendimentosView2 = this; + this.TelefoneBox.PreviewTextInput += new TextCompositionEventHandler(atendimentosView2.SomenteNumeros); + return; + } + case 11: + { + this.ValorBox = (TextBox)target; + return; + } + case 12: + { + this.AssuntoBox = (TextBox)target; + return; + } + case 13: + { + this.IdAcessoBox = (TextBox)target; + return; + } + case 14: + { + this.SenhaBox = (TextBox)target; + return; + } + case 15: + { + ((Button)target).Click += new RoutedEventHandler(this.AcessoRemoto_OnClick); + return; + } + case 16: + { + this._contentLoaded = true; + return; + } + case 17: + { + this.WebEditor = (Gestor.Application.Componentes.WebEditor)target; + return; + } + default: + { + this._contentLoaded = true; + return; + } + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + if (connectionId == 16) + { + ((Chip)target).add_DeleteClick(new RoutedEventHandler(this.DeleteArquivo_OnDeleteClick)); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/BI/AcompanhamentoView.cs b/Codemerx/Gestor.Application/Views/BI/AcompanhamentoView.cs new file mode 100644 index 0000000..a509fdf --- /dev/null +++ b/Codemerx/Gestor.Application/Views/BI/AcompanhamentoView.cs @@ -0,0 +1,339 @@ +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Model.Domain.Ferramentas; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Media; + +namespace Gestor.Application.Views.BI +{ + public class AcompanhamentoView : BaseUserControl, IComponentConnector, IStyleConnector + { + private ListBox _dragSource; + + private object _data; + + internal ListBox FasesListBox; + + private bool _contentLoaded; + + public TrilhaViewModel ViewModel + { + get; + set; + } + + public AcompanhamentoView() + { + base.Tag = "CADASTRO DE TRILHAS"; + this.ViewModel = new TrilhaViewModel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + this.FasesListBox.DataContext = this.ViewModel; + } + + private async Task AbrirTarefa(Tarefa data) + { + while (true) + { + Tarefa tarefa = await this.ViewModel.ShowTarefaDialog(data, false, false); + if (tarefa == null) + { + return; + } + List> keyValuePairs = await this.ViewModel.Salvar(tarefa); + this.ViewModel.Loading(false); + if (keyValuePairs == null || keyValuePairs.Count == 0) + { + break; + } + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + this.ViewModel.ToggleSnackBar("TAREFA SALVA COM SUCESSO.", true); + this.ViewModel.Alterar(false); + return; + } + + private async void AdicionarTarefa_OnClick(object sender, RoutedEventArgs e) + { + Fase dataContext = ((Button)sender).DataContext as Fase; + Tarefa tarefa = new Tarefa(); + tarefa.set_Agendamento(Funcoes.GetNetworkTime()); + tarefa.set_Titulo("NOVA TAREFA"); + tarefa.set_Usuario(Recursos.Usuario); + tarefa.set_Trilha(this.ViewModel.SelectedTrilha); + tarefa.set_Status(0); + tarefa.set_Fase(dataContext); + Tarefa tarefa1 = tarefa; + this.ViewModel.Loading(true); + while (true) + { + Tarefa tarefa2 = await this.ViewModel.ShowTarefaDialog(tarefa1, false, false); + if (tarefa2 == null) + { + tarefa1 = null; + return; + } + List> keyValuePairs = await this.ViewModel.Salvar(tarefa2); + this.ViewModel.Loading(false); + if (keyValuePairs == null || keyValuePairs.Count == 0) + { + break; + } + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + this.ViewModel.ToggleSnackBar("TAREFA SALVA COM SUCESSO.", true); + this.ViewModel.Alterar(false); + tarefa1 = null; + return; + tarefa1 = null; + } + + private async void EditarTarefa_OnClick(object sender, RoutedEventArgs e) + { + await this.AbrirTarefa(((Button)sender).DataContext as Tarefa); + } + + private async void ExcluirTarefa_OnClick(object sender, RoutedEventArgs e) + { + Tarefa dataContext = ((Button)sender).DataContext as Tarefa; + await this.ViewModel.Excluir(dataContext); + } + + private void FasesListBox_OnDragOver(object sender, DragEventArgs e) + { + ListBox listBox = sender as ListBox; + ScrollViewer scrollViewer = AcompanhamentoView.FindVisualChild(this.FasesListBox); + if (listBox != null) + { + double x = e.GetPosition(listBox).X; + if (x < 100) + { + scrollViewer.ScrollToHorizontalOffset(scrollViewer.HorizontalOffset - 30); + return; + } + if (x > listBox.ActualWidth - 100) + { + scrollViewer.ScrollToHorizontalOffset(scrollViewer.HorizontalOffset + 30); + } + } + } + + public static TChildItem FindVisualChild(DependencyObject obj) + where TChildItem : DependencyObject + { + for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++) + { + DependencyObject child = VisualTreeHelper.GetChild(obj, i); + TChildItem tChildItem = (TChildItem)(child as TChildItem); + if (tChildItem != null) + { + return tChildItem; + } + TChildItem tChildItem1 = AcompanhamentoView.FindVisualChild(child); + if (tChildItem1 != null) + { + return tChildItem1; + } + } + return default(TChildItem); + } + + private static object GetDataFromListBox(ItemsControl source, Point point) + { + UIElement parent = source.InputHitTest(point) as UIElement; + if (parent != null) + { + object unsetValue = DependencyProperty.UnsetValue; + while (unsetValue == DependencyProperty.UnsetValue) + { + if (parent == null) + { + continue; + } + unsetValue = source.ItemContainerGenerator.ItemFromContainer(parent); + if (unsetValue == DependencyProperty.UnsetValue) + { + parent = VisualTreeHelper.GetParent(parent) as UIElement; + } + if (parent != source) + { + continue; + } + return null; + } + if (unsetValue != DependencyProperty.UnsetValue) + { + return unsetValue; + } + } + return null; + } + + private void Info_OnClick(object sender, RoutedEventArgs e) + { + Button button = (Button)sender; + bool isOpen = !((System.Windows.Controls.ToolTip)button.ToolTip).IsOpen; + ((System.Windows.Controls.ToolTip)button.ToolTip).IsOpen = isOpen; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/bi/acompanhamentoview.xaml", UriKind.Relative)); + } + + private static bool IsMouseOverTarget(Visual target, Point point) + { + return VisualTreeHelper.GetDescendantBounds(target).Contains(point); + } + + private void ListBox_Drop(object sender, DragEventArgs e) + { + ListBox listBox = (ListBox)sender; + object data = e.Data.GetData(this._data.GetType()); + int num = -1; + int num1 = 0; + while (num1 < listBox.Items.Count) + { + ListBoxItem listBoxItem = listBox.ItemContainerGenerator.ContainerFromIndex(num1) as ListBoxItem; + if (listBoxItem == null || !AcompanhamentoView.IsMouseOverTarget(listBoxItem, e.GetPosition(listBoxItem))) + { + num1++; + } + else + { + num = num1; + break; + } + } + Fase dataContext = this._dragSource.DataContext as Fase; + Fase fase = listBox.DataContext as Fase; + this.ViewModel.Excluir(dataContext, (Tarefa)data); + this.ViewModel.Inserir(fase, (Tarefa)data, num, false); + this.ViewModel.Update(); + } + + private async void ListBox_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e) + { + ListBox listBox = (ListBox)sender; + object dataFromListBox = AcompanhamentoView.GetDataFromListBox(listBox, e.GetPosition(listBox)); + if (dataFromListBox != null) + { + await this.AbrirTarefa((Tarefa)dataFromListBox); + } + } + + private void ListBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) + { + if (!(sender is Button)) + { + return; + } + Button button = (Button)sender; + this._dragSource = ViewHelper.FindAncestor(button).FirstOrDefault(); + this._data = AcompanhamentoView.GetDataFromListBox(this._dragSource, e.GetPosition(button)); + if (this._data == null) + { + return; + } + DragDrop.DoDragDrop(button, this._data, DragDropEffects.Move); + e.Handled = true; + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + if (connectionId != 1) + { + this._contentLoaded = true; + return; + } + this.FasesListBox = (ListBox)target; + this.FasesListBox.DragOver += new DragEventHandler(this.FasesListBox_OnDragOver); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 2: + { + ((Button)target).Click += new RoutedEventHandler(this.AdicionarTarefa_OnClick); + return; + } + case 3: + { + ((Button)target).Click += new RoutedEventHandler(this.Info_OnClick); + return; + } + case 4: + { + ((ListBox)target).PreviewMouseDoubleClick += new MouseButtonEventHandler(this.ListBox_OnPreviewMouseDoubleClick); + ((ListBox)target).MouseLeftButtonDown += new MouseButtonEventHandler(this.ListBox_PreviewMouseLeftButtonDown); + ((ListBox)target).Drop += new DragEventHandler(this.ListBox_Drop); + return; + } + case 5: + { + ((Button)target).Click += new RoutedEventHandler(this.ExcluirTarefa_OnClick); + return; + } + case 6: + { + ((Button)target).PreviewMouseLeftButtonDown += new MouseButtonEventHandler(this.ListBox_PreviewMouseLeftButtonDown); + return; + } + case 7: + { + ((Button)target).Click += new RoutedEventHandler(this.EditarTarefa_OnClick); + return; + } + case 8: + { + ((Button)target).Click += new RoutedEventHandler(this.TarefaConcluida_OnClick); + return; + } + default: + { + return; + } + } + } + + private async void TarefaConcluida_OnClick(object sender, RoutedEventArgs e) + { + Tarefa dataContext = ((Button)sender).DataContext as Tarefa; + if (dataContext != null) + { + dataContext.set_Conclusao(new DateTime?(Funcoes.GetNetworkTime())); + dataContext.set_Status(2); + await this.ViewModel.Salvar(dataContext); + await this.ViewModel.CarregarTrilha(this.ViewModel.SelectedTrilha); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/BI/AgendaBIView.cs b/Codemerx/Gestor.Application/Views/BI/AgendaBIView.cs new file mode 100644 index 0000000..33865eb --- /dev/null +++ b/Codemerx/Gestor.Application/Views/BI/AgendaBIView.cs @@ -0,0 +1,81 @@ +using System; +using System.CodeDom.Compiler; +using System.ComponentModel; +using System.Diagnostics; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Views.BI +{ + public class AgendaBIView : UserControl, IComponentConnector + { + internal ContentControl NotasControl; + + internal ContentControl TarefaControl; + + internal ContentControl BiControl; + + private bool _contentLoaded; + + public AgendaBIView() + { + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + + private void ContentLoad() + { + NotasView notasView = new NotasView(); + this.NotasControl.Content = notasView; + this.NotasControl.DataContext = notasView.DataContext; + TarefaView tarefaView = new TarefaView(); + this.TarefaControl.Content = tarefaView; + this.TarefaControl.DataContext = tarefaView.DataContext; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/bi/agendabiview.xaml", UriKind.Relative)); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.NotasControl = (ContentControl)target; + return; + } + case 2: + { + this.TarefaControl = (ContentControl)target; + return; + } + case 3: + { + this.BiControl = (ContentControl)target; + return; + } + } + this._contentLoaded = true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/BI/NotasView.cs b/Codemerx/Gestor.Application/Views/BI/NotasView.cs new file mode 100644 index 0000000..1386592 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/BI/NotasView.cs @@ -0,0 +1,298 @@ +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels.BI; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Media; + +namespace Gestor.Application.Views.BI +{ + public class NotasView : BaseUserControl, IComponentConnector, IStyleConnector + { + internal ProgressBar ProgressRing; + + private bool _contentLoaded; + + public NotasViewModel ViewModel + { + get; + set; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public NotasView() + { + this.ViewModel = new NotasViewModel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + } + + private async Task AbrirNota(Tarefa data, bool notaBool = false, bool agendamento = false) + { + while (true) + { + Tarefa tarefa = await this.ViewModel.ShowTarefaDialog(data, notaBool, agendamento); + Tarefa tarefa1 = tarefa; + if (tarefa1 == null) + { + return; + } + if (tarefa1.get_Usuario() == null) + { + tarefa1.set_Usuario(tarefa1.get_UsuariosVinculados().FirstOrDefault()); + } + List list = tarefa1.get_UsuariosVinculados().Select((Usuario x) => { + ResponsavelTarefa responsavelTarefa = new ResponsavelTarefa(); + responsavelTarefa.set_IdTarefa(tarefa1.get_Id()); + responsavelTarefa.set_Usuario(x); + return responsavelTarefa; + }).ToList(); + tarefa1.set_Responsaveis(list); + this.ViewModel.Loading(true); + List> keyValuePairs = await this.ViewModel.Salvar(tarefa1); + this.ViewModel.Loading(false); + if (keyValuePairs == null || keyValuePairs.Count == 0) + { + break; + } + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + this.ViewModel.ToggleSnackBar("NOTA SALVA COM SUCESSO.", true); + await this.ViewModel.CarregarNotas(); + return; + } + + private async void AdicionarNota_OnClick(object sender, RoutedEventArgs e) + { + await this.ViewModel.AdicionarNota(); + } + + private async void ExcluirNota_OnClick(object sender, RoutedEventArgs e) + { + Tarefa dataContext = ((Button)sender).DataContext as Tarefa; + if (dataContext != null) + { + await this.ViewModel.ExcluirNota(dataContext); + await this.ViewModel.CarregarNotas(); + } + } + + private static object GetDataFromListBox(ItemsControl source, Point point) + { + UIElement parent = source.InputHitTest(point) as UIElement; + if (parent == null) + { + return null; + } + object unsetValue = DependencyProperty.UnsetValue; + while (unsetValue == DependencyProperty.UnsetValue) + { + if (parent == null) + { + continue; + } + unsetValue = source.ItemContainerGenerator.ItemFromContainer(parent); + if (unsetValue == DependencyProperty.UnsetValue) + { + parent = VisualTreeHelper.GetParent(parent) as UIElement; + } + if (parent != source) + { + continue; + } + return null; + } + if (unsetValue == DependencyProperty.UnsetValue) + { + return null; + } + return unsetValue; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/bi/notasview.xaml", UriKind.Relative)); + } + + private async void ListBox_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e) + { + List list; + ListBox listBox = (ListBox)sender; + object dataFromListBox = NotasView.GetDataFromListBox(listBox, e.GetPosition(listBox)); + if (dataFromListBox != null) + { + Tarefa tarefa = new Tarefa(); + DomainBase.Copy(tarefa, (Tarefa)dataFromListBox); + Tarefa tarefa1 = tarefa; + List responsaveis = tarefa.get_Responsaveis(); + if (responsaveis != null) + { + list = ( + from x in responsaveis + select x.get_Usuario()).ToList(); + } + else + { + list = null; + } + tarefa1.set_UsuariosVinculados(list); + await this.AbrirNota(tarefa, tarefa.get_Entidade() == 1, tarefa.get_Entidade() == 1); + } + } + + private async void NotaConcluida_OnClick(object sender, RoutedEventArgs e) + { + Tarefa dataContext = ((Button)sender).DataContext as Tarefa; + if (dataContext != null) + { + dataContext.set_Conclusao(new DateTime?(Funcoes.GetNetworkTime())); + dataContext.set_Status(2); + await this.ViewModel.SalvarNota(dataContext); + await this.ViewModel.CarregarNotas(); + } + } + + private async void SarvarNota_OnClick(object sender, RoutedEventArgs e) + { + Tarefa dataContext = ((Button)sender).DataContext as Tarefa; + if (dataContext != null) + { + this.ViewModel.Loading(true); + List> keyValuePairs = await this.ViewModel.Salvar(dataContext); + this.ViewModel.Loading(false); + if (keyValuePairs == null || keyValuePairs.Count == 0) + { + this.ViewModel.ToggleSnackBar("NOTA SALVA COM SUCESSO.", true); + } + else + { + await this.ViewModel.CarregarNotas(); + } + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.ProgressRing = (ProgressBar)target; + return; + } + case 2: + { + ((ListBox)target).PreviewMouseDoubleClick += new MouseButtonEventHandler(this.ListBox_OnPreviewMouseDoubleClick); + return; + } + case 3: + case 4: + case 5: + { + this._contentLoaded = true; + return; + } + case 6: + { + ((Button)target).Click += new RoutedEventHandler(this.AdicionarNota_OnClick); + return; + } + case 7: + { + ((Button)target).Click += new RoutedEventHandler(this.ToggleNotasConcluidas_OnClick); + return; + } + case 8: + { + ((ListBox)target).PreviewMouseDoubleClick += new MouseButtonEventHandler(this.ListBox_OnPreviewMouseDoubleClick); + return; + } + default: + { + this._contentLoaded = true; + return; + } + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 3: + { + ((Button)target).Click += new RoutedEventHandler(this.ExcluirNota_OnClick); + return; + } + case 4: + { + ((Button)target).Click += new RoutedEventHandler(this.NotaConcluida_OnClick); + return; + } + case 5: + { + ((Button)target).Click += new RoutedEventHandler(this.SarvarNota_OnClick); + return; + } + case 6: + case 7: + case 8: + { + return; + } + case 9: + { + ((Button)target).Click += new RoutedEventHandler(this.ExcluirNota_OnClick); + return; + } + case 10: + { + ((Button)target).Click += new RoutedEventHandler(this.SarvarNota_OnClick); + return; + } + default: + { + return; + } + } + } + + private void ToggleNotasConcluidas_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.ToggleNotasConcluidas(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/BI/PainelBiView.cs b/Codemerx/Gestor.Application/Views/BI/PainelBiView.cs new file mode 100644 index 0000000..1886b4f --- /dev/null +++ b/Codemerx/Gestor.Application/Views/BI/PainelBiView.cs @@ -0,0 +1,502 @@ +using Gestor.Application.ViewModels.BI; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using LiveCharts.Wpf; +using System; +using System.CodeDom.Compiler; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Markup; + +namespace Gestor.Application.Views.BI +{ + public class PainelBiView : BaseUserControl, IComponentConnector + { + public PainelBiViewModel ViewModel; + + internal ProgressBar ProgressProducao; + + internal DatePicker InicioBox; + + internal DatePicker FimBox; + + internal Button Anterior; + + internal Button Gerada; + + internal Button Apolices; + + internal Button Endossos; + + internal Button NovosNegocios; + + internal Button Faturas; + + internal Button Renovacoes; + + internal Button Cancelamentos; + + internal ProgressBar ProgressClientes; + + internal DatePicker InicioClientesBox; + + internal DatePicker FimClientesBox; + + internal Button Aniversariantes; + + internal Button VencimentoCnh; + + internal ProgressBar ProgressPendencia; + + internal DatePicker InicioPendenciaBox; + + internal DatePicker FimPendenciaBox; + + internal Button VencimentoApolices; + + internal Button ParcelasAVencer; + + internal Button ApolicesPendentes; + + internal Button ParcelasPendentes; + + private bool _contentLoaded; + + public PainelBiView() + { + this.ViewModel = new PainelBiViewModel(); + base.DataContext = this.ViewModel; + base.Tag = "PAINEL B.I."; + this.InitializeComponent(); + } + + private async void Atualizar_Click(object sender, RoutedEventArgs e) + { + this.InicioBox.Text = ValidationHelper.FormatDate(this.InicioBox.Text); + this.FimBox.Text = ValidationHelper.FormatDate(this.FimBox.Text); + try + { + this.ViewModel.Inicio = Convert.ToDateTime(this.InicioBox.Text); + this.ViewModel.Fim = Convert.ToDateTime(this.FimBox.Text); + } + catch (Exception exception) + { + return; + } + await this.ViewModel.GerarProducao(); + } + + private async void AtualizarClientes_OnClick(object sender, RoutedEventArgs e) + { + this.InicioClientesBox.Text = ValidationHelper.FormatDate(this.InicioClientesBox.Text); + this.FimClientesBox.Text = ValidationHelper.FormatDate(this.FimClientesBox.Text); + try + { + this.ViewModel.Inicio = Convert.ToDateTime(this.InicioClientesBox.Text); + this.ViewModel.Fim = Convert.ToDateTime(this.FimClientesBox.Text); + } + catch (Exception exception) + { + return; + } + await this.ViewModel.GerarClientes(); + } + + private async void AtualizarPendencias_OnClick(object sender, RoutedEventArgs e) + { + this.InicioPendenciaBox.Text = ValidationHelper.FormatDate(this.InicioPendenciaBox.Text); + this.FimPendenciaBox.Text = ValidationHelper.FormatDate(this.FimPendenciaBox.Text); + try + { + this.ViewModel.Inicio = Convert.ToDateTime(this.InicioPendenciaBox.Text); + this.ViewModel.Fim = Convert.ToDateTime(this.FimPendenciaBox.Text); + } + catch (Exception exception) + { + return; + } + await this.ViewModel.GerarVencimento(); + } + + private void DetalharProducao_OnClick(object sender, RoutedEventArgs e) + { + char chr; + string name = ((Button)sender).Name; + if (name != null) + { + switch (name.Length) + { + case 7: + { + if (name == "Faturas") + { + this.ViewModel.Detalhar(12); + return; + } + break; + } + case 8: + { + chr = name[2]; + if (chr == 'd') + { + if (name == "Endossos") + { + this.ViewModel.Detalhar(11); + return; + } + break; + } + else if (chr == 'o') + { + if (name == "Apolices") + { + this.ViewModel.Detalhar(13); + return; + } + break; + } + else if (chr == 't') + { + if (name != "Anterior") + { + break; + } + this.ViewModel.Detalhar(14); + return; + } + else + { + break; + } + } + case 10: + { + if (name == "Renovacoes") + { + this.ViewModel.Detalhar(3); + return; + } + break; + } + case 13: + { + chr = name[0]; + if (chr == 'C') + { + if (name == "Cancelamentos") + { + this.ViewModel.Detalhar(4); + return; + } + break; + } + else if (chr == 'N') + { + if (name == "NovosNegocios") + { + this.ViewModel.Detalhar(2); + return; + } + break; + } + else if (chr == 'V') + { + if (name == "VencimentoCnh") + { + this.ViewModel.Detalhar(6); + return; + } + break; + } + else + { + break; + } + } + case 15: + { + chr = name[0]; + if (chr == 'A') + { + if (name == "Aniversariantes") + { + this.ViewModel.Detalhar(5); + return; + } + break; + } + else if (chr == 'P') + { + if (name == "ParcelasAVencer") + { + this.ViewModel.Detalhar(8); + return; + } + break; + } + else + { + break; + } + } + case 17: + { + chr = name[0]; + if (chr == 'A') + { + if (name == "ApolicesPendentes") + { + this.ViewModel.Detalhar(9); + return; + } + break; + } + else if (chr == 'P') + { + if (name == "ParcelasPendentes") + { + this.ViewModel.Detalhar(10); + return; + } + break; + } + else + { + break; + } + } + case 18: + { + if (name == "VencimentoApolices") + { + this.ViewModel.Detalhar(7); + return; + } + break; + } + } + } + this.ViewModel.Detalhar(0); + } + + private void Fechamento_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e) + { + this.ViewModel.Detalhar(1); + } + + private void Grafico_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e) + { + this.ViewModel.Detalhar(0); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/bi/painelbiview.xaml", UriKind.Relative)); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.ProgressProducao = (ProgressBar)target; + return; + } + case 2: + { + this.InicioBox = (DatePicker)target; + this.InicioBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.InicioBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 3: + { + this.FimBox = (DatePicker)target; + this.FimBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.FimBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 4: + { + ((CartesianChart)target).PreviewMouseDoubleClick += new MouseButtonEventHandler(this.Grafico_OnPreviewMouseDoubleClick); + return; + } + case 5: + { + ((Button)target).Click += new RoutedEventHandler(this.Atualizar_Click); + return; + } + case 6: + { + ((Button)target).Click += new RoutedEventHandler(this.DetalharProducao_OnClick); + return; + } + case 7: + { + this.Anterior = (Button)target; + this.Anterior.Click += new RoutedEventHandler(this.DetalharProducao_OnClick); + return; + } + case 8: + { + this.Gerada = (Button)target; + this.Gerada.Click += new RoutedEventHandler(this.DetalharProducao_OnClick); + return; + } + case 9: + { + this.Apolices = (Button)target; + this.Apolices.Click += new RoutedEventHandler(this.DetalharProducao_OnClick); + return; + } + case 10: + { + this.Endossos = (Button)target; + this.Endossos.Click += new RoutedEventHandler(this.DetalharProducao_OnClick); + return; + } + case 11: + { + this.NovosNegocios = (Button)target; + this.NovosNegocios.Click += new RoutedEventHandler(this.DetalharProducao_OnClick); + return; + } + case 12: + { + this.Faturas = (Button)target; + this.Faturas.Click += new RoutedEventHandler(this.DetalharProducao_OnClick); + return; + } + case 13: + { + this.Renovacoes = (Button)target; + this.Renovacoes.Click += new RoutedEventHandler(this.DetalharProducao_OnClick); + return; + } + case 14: + { + this.Cancelamentos = (Button)target; + this.Cancelamentos.Click += new RoutedEventHandler(this.DetalharProducao_OnClick); + return; + } + case 15: + { + ((PieChart)target).PreviewMouseDoubleClick += new MouseButtonEventHandler(this.Grafico_OnPreviewMouseDoubleClick); + return; + } + case 16: + { + ((PieChart)target).PreviewMouseDoubleClick += new MouseButtonEventHandler(this.Grafico_OnPreviewMouseDoubleClick); + return; + } + case 17: + { + ((CartesianChart)target).PreviewMouseDoubleClick += new MouseButtonEventHandler(this.Fechamento_OnPreviewMouseDoubleClick); + return; + } + case 18: + { + this.ProgressClientes = (ProgressBar)target; + return; + } + case 19: + { + this.InicioClientesBox = (DatePicker)target; + this.InicioClientesBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.InicioClientesBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 20: + { + this.FimClientesBox = (DatePicker)target; + this.FimClientesBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.FimClientesBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 21: + { + ((Button)target).Click += new RoutedEventHandler(this.AtualizarClientes_OnClick); + return; + } + case 22: + { + this.Aniversariantes = (Button)target; + this.Aniversariantes.Click += new RoutedEventHandler(this.DetalharProducao_OnClick); + return; + } + case 23: + { + this.VencimentoCnh = (Button)target; + this.VencimentoCnh.Click += new RoutedEventHandler(this.DetalharProducao_OnClick); + return; + } + case 24: + { + this.ProgressPendencia = (ProgressBar)target; + return; + } + case 25: + { + this.InicioPendenciaBox = (DatePicker)target; + this.InicioPendenciaBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.InicioPendenciaBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 26: + { + this.FimPendenciaBox = (DatePicker)target; + this.FimPendenciaBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.FimPendenciaBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 27: + { + ((Button)target).Click += new RoutedEventHandler(this.AtualizarPendencias_OnClick); + return; + } + case 28: + { + this.VencimentoApolices = (Button)target; + this.VencimentoApolices.Click += new RoutedEventHandler(this.DetalharProducao_OnClick); + return; + } + case 29: + { + this.ParcelasAVencer = (Button)target; + this.ParcelasAVencer.Click += new RoutedEventHandler(this.DetalharProducao_OnClick); + return; + } + case 30: + { + this.ApolicesPendentes = (Button)target; + this.ApolicesPendentes.Click += new RoutedEventHandler(this.DetalharProducao_OnClick); + return; + } + case 31: + { + this.ParcelasPendentes = (Button)target; + this.ParcelasPendentes.Click += new RoutedEventHandler(this.DetalharProducao_OnClick); + return; + } + } + this._contentLoaded = true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/BI/ProspeccaoView.cs b/Codemerx/Gestor.Application/Views/BI/ProspeccaoView.cs new file mode 100644 index 0000000..b625599 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/BI/ProspeccaoView.cs @@ -0,0 +1,422 @@ +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.ViewModels.BI; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Views.BI +{ + public class ProspeccaoView : BaseUserControl, IComponentConnector, IStyleConnector + { + private bool openProsceccao; + + internal DatePicker InicioBox; + + internal DatePicker FimBox; + + internal AutoCompleteBox AutoCompleteFornecedor; + + internal MenuItem MaisOpcoesButton; + + private bool _contentLoaded; + + public ProspeccaoViewModel ViewModel + { + get; + set; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public ProspeccaoView() + { + base.Tag = "PROSPECTAR"; + this.ViewModel = new ProspeccaoViewModel(); + base.DataContext = this.ViewModel; + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher != null) + { + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + else + { + } + this.InitializeComponent(); + } + + private async void AbrirAquivoDigital_Click(object sender, RoutedEventArgs e) + { + if (!await this.ViewModel.BuscaPermissao("Alterar")) + { + await this.ViewModel.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA ALTERAR PROSPECÇÃO. CONTATE O ADMINISTRADOR DO SISTEMA.", "OK", "", false); + } + else if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 11).get_Consultar()) + { + Prospeccao dataContext = (Prospeccao)((Button)sender).DataContext; + FiltroArquivoDigital filtroArquivoDigital = new FiltroArquivoDigital(); + filtroArquivoDigital.set_Id(dataContext.get_Id()); + filtroArquivoDigital.set_Tipo(11); + filtroArquivoDigital.set_Parente(dataContext); + this.ViewModel.ShowDrawer(new ArquivoDigitalDrawer(filtroArquivoDigital), 0, false); + } + else + { + await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", ValidationHelper.GetDescription((TipoArquivoDigital)11), "."), "OK", "", false); + } + } + + private void AbrirLog_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLog(33, this.ViewModel.SelectedProspeccao.get_Id()); + } + + private void AbrirLogEmail_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLogEmail(33, this.ViewModel.SelectedProspeccao.get_Id()); + } + + private async Task AbrirProspeccao(Prospeccao data) + { + bool flag; + string str; + ProspeccaoView.u003cu003ec__DisplayClass11_0 variable; + bool id; + Prospeccao prospeccao; + Func func = null; + if (await this.ViewModel.BuscaPermissao("Alterar")) + { + this.InicioBox.Text = ValidationHelper.FormatDate(this.InicioBox.Text); + this.FimBox.Text = ValidationHelper.FormatDate(this.FimBox.Text); + try + { + this.ViewModel.Inicio = Convert.ToDateTime(this.InicioBox.Text); + this.ViewModel.Fim = Convert.ToDateTime(this.FimBox.Text); + } + catch (Exception exception) + { + variable = null; + return; + } + while (true) + { + id = data.get_Id() == (long)0; + prospeccao = await this.ViewModel.ShowProspeccaoDialog(data); + if (prospeccao == null) + { + goto Label1; + } + List> keyValuePairs = await this.ViewModel.Salvar(data); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + if (flag) + { + break; + } + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + prospeccao = null; + } + str = (prospeccao.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + string str1 = str; + this.ViewModel.RegistrarAcao(string.Concat(str1, " PROSPECÇÃO \"", prospeccao.get_Nome(), "\""), prospeccao.get_Id(), new TipoTela?(33), string.Format("CLIENTE \"{0}\", ID: {1}", prospeccao.get_Nome(), prospeccao.get_Id())); + this.ViewModel.ToggleSnackBar("PROSPECÇÃO SALVA COM SUCESSO.", true); + await this.ViewModel.CarregarProspeccoes(); + } + else + { + await this.ViewModel.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA ALTERAR PROSPECÇÃO. CONTATE O ADMINISTRADOR DO SISTEMA.", "OK", "", false); + } + variable = null; + return; + Label1: + if (!id) + { + await this.ViewModel.CarregarProspeccoes(); + ProspeccaoViewModel viewModel = this.ViewModel; + ObservableCollection prospeccoesFiltradas = this.ViewModel.ProspeccoesFiltradas; + Func func1 = func; + if (func1 == null) + { + Func id1 = (Prospeccao x) => x.get_Id() == data.get_Id(); + Func func2 = id1; + func = id1; + func1 = func2; + } + viewModel.SelectedProspeccao = prospeccoesFiltradas.FirstOrDefault(func1); + variable = null; + return; + } + else + { + variable = null; + return; + } + } + + private void AutoCompleteBoxDetalhe_Populating(object sender, PopulatingEventArgs e) + { + e.set_Cancel(true); + this.ViewModel.FiltrarProspecao(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private async void ContentLoad() + { + await this.ViewModel.CarregaProspeccao(); + await this.ViewModel.CarregarPermissao(); + } + + private async void Control_OnMouseDoubleClick(object sender, MouseButtonEventArgs e) + { + object obj; + DataGrid dataGrid = (DataGrid)sender; + if (dataGrid == null || dataGrid.SelectedIndex >= 0) + { + obj = (dataGrid != null ? dataGrid.Items[dataGrid.SelectedIndex] : null); + Prospeccao prospeccao = (Prospeccao)obj; + this.ViewModel.Loading(true); + await this.AbrirProspeccao(prospeccao); + this.ViewModel.Loading(false); + } + } + + private async void CriarProspeccao_OnClick(object sender, RoutedEventArgs e) + { + if (!await this.ViewModel.BuscaPermissao("Incluir")) + { + await this.ViewModel.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA INCLUIR PROSPECÇÃO. CONTATE O ADMINISTRADOR DO SISTEMA.", "OK", "", false); + } + else if (!this.openProsceccao) + { + this.openProsceccao = true; + Prospeccao prospeccao = new Prospeccao(); + prospeccao.set_Status(new StatusProspeccao?(1)); + prospeccao.set_Renovacao(true); + Prospeccao prospeccao1 = prospeccao; + this.ViewModel.Loading(true); + await this.AbrirProspeccao(prospeccao1); + this.openProsceccao = false; + this.ViewModel.Loading(false); + } + } + + private async void EditarProspeccao_OnClick(object sender, RoutedEventArgs e) + { + Prospeccao dataContext = (Prospeccao)((Button)sender).DataContext; + this.ViewModel.Loading(true); + await this.AbrirProspeccao(dataContext); + this.ViewModel.Loading(false); + } + + private async void Excel_OnClick(object sender, RoutedEventArgs e) + { + this.InicioBox.Text = ValidationHelper.FormatDate(this.InicioBox.Text); + this.FimBox.Text = ValidationHelper.FormatDate(this.FimBox.Text); + try + { + this.ViewModel.Inicio = Convert.ToDateTime(this.InicioBox.Text); + this.ViewModel.Fim = Convert.ToDateTime(this.FimBox.Text); + } + catch (Exception exception) + { + return; + } + await this.ViewModel.GerarExcel(); + } + + private async void ExcluirProspeccao_OnClick(object sender, RoutedEventArgs e) + { + if (await this.ViewModel.BuscaPermissao("Excluir")) + { + Prospeccao dataContext = (Prospeccao)((Button)sender).DataContext; + this.ViewModel.Excluir(dataContext); + } + else + { + await this.ViewModel.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA EXCLUIR PROSPECÇÃO. CONTATE O ADMINISTRADOR DO SISTEMA.", "OK", "", false); + } + } + + private async void Imprimir_OnClick(object sender, RoutedEventArgs e) + { + this.InicioBox.Text = ValidationHelper.FormatDate(this.InicioBox.Text); + this.FimBox.Text = ValidationHelper.FormatDate(this.FimBox.Text); + try + { + this.ViewModel.Inicio = Convert.ToDateTime(this.InicioBox.Text); + this.ViewModel.Fim = Convert.ToDateTime(this.FimBox.Text); + } + catch (Exception exception) + { + return; + } + await this.ViewModel.Print(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/bi/prospeccaoview.xaml", UriKind.Relative)); + } + + private async void Periodo_OnSelectedDateChanged(object sender, SelectionChangedEventArgs e) + { + await this.ViewModel.CarregarProspeccoes(); + } + + private async void StatusProspeccao_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + await this.ViewModel.CarregarProspeccoes(); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((ComboBox)target).SelectionChanged += new SelectionChangedEventHandler(this.Vendedor_OnSelectionChanged); + return; + } + case 2: + { + ((ComboBox)target).SelectionChanged += new SelectionChangedEventHandler(this.StatusProspeccao_OnSelectionChanged); + return; + } + case 3: + { + this.InicioBox = (DatePicker)target; + this.InicioBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.InicioBox.PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + this.InicioBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + this.InicioBox.SelectedDateChanged += new EventHandler(this.Periodo_OnSelectedDateChanged); + return; + } + case 4: + { + this.FimBox = (DatePicker)target; + this.FimBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.FimBox.PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + this.FimBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + this.FimBox.SelectedDateChanged += new EventHandler(this.Periodo_OnSelectedDateChanged); + return; + } + case 5: + { + this.AutoCompleteFornecedor = (AutoCompleteBox)target; + this.AutoCompleteFornecedor.add_Populating(new PopulatingEventHandler(this, ProspeccaoView.AutoCompleteBoxDetalhe_Populating)); + return; + } + case 6: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Imprimir_OnClick); + return; + } + case 7: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Excel_OnClick); + return; + } + case 8: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.CriarProspeccao_OnClick); + return; + } + case 9: + { + this.MaisOpcoesButton = (MenuItem)target; + return; + } + case 10: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick); + return; + } + case 11: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLogEmail_OnClick); + return; + } + case 12: + { + ((DataGrid)target).MouseDoubleClick += new MouseButtonEventHandler(this.Control_OnMouseDoubleClick); + return; + } + } + this._contentLoaded = true; + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 13: + { + ((Button)target).Click += new RoutedEventHandler(this.ExcluirProspeccao_OnClick); + return; + } + case 14: + { + ((Button)target).Click += new RoutedEventHandler(this.AbrirAquivoDigital_Click); + return; + } + case 15: + { + ((Button)target).Click += new RoutedEventHandler(this.EditarProspeccao_OnClick); + return; + } + default: + { + return; + } + } + } + + private async void Vendedor_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + await this.ViewModel.CarregarProspeccoes(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/BI/TarefaView.cs b/Codemerx/Gestor.Application/Views/BI/TarefaView.cs new file mode 100644 index 0000000..7ca7f68 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/BI/TarefaView.cs @@ -0,0 +1,628 @@ +using Gestor.Application.Actions; +using Gestor.Application.Componentes; +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.ViewModels.BI; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Ferramentas; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.MalaDireta; +using Gestor.Model.Domain.Seguros; +using MaterialDesignThemes.Wpf; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; +using Xceed.Wpf.AvalonDock.Controls; + +namespace Gestor.Application.Views.BI +{ + public class TarefaView : BaseUserControl, IComponentConnector, IStyleConnector + { + internal ComboBox UsuarioBox; + + internal DatePicker InicioBox; + + internal DatePicker FimBox; + + internal TextBox TituloTarefaLabel; + + internal DatePicker AgendamentoBox; + + internal ComboBox ResponsavelBox; + + internal RadioButton AnotacoesButton; + + internal RadioButton AnotacoesInternasButton; + + internal WebEditor Anotacoes; + + internal WebEditor Historico; + + internal WebEditor AnotacoesInternas; + + internal WebEditor HistoricoInterno; + + private bool _contentLoaded; + + public TarefaBIViewModel ViewModel + { + get; + set; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public TarefaView() + { + this.ViewModel = new TarefaBIViewModel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + + private void AbrirLog_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLog(38, this.ViewModel.SelectedTarefa.get_Id()); + } + + private void AdicionarFiltro_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AdcionarFiltro(); + } + + private void AdicionarResponsavel_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AdcionarResponsavel(); + } + + private void Alterar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AlterarTarefa(); + this.Anotacoes.Initialize(null); + this.AnotacoesInternas.Initialize(null); + } + + private async void AnexoTarefa_OnClick(object sender, RoutedEventArgs e) + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 15).get_Consultar()) + { + FiltroArquivoDigital filtroArquivoDigital = new FiltroArquivoDigital(); + filtroArquivoDigital.set_Id(this.ViewModel.SelectedTarefa.get_Id()); + filtroArquivoDigital.set_Tipo(15); + filtroArquivoDigital.set_Parente(this.ViewModel.SelectedTarefa); + this.ViewModel.ShowDrawer(new ArquivoDigitalDrawer(filtroArquivoDigital), 0, false); + } + else + { + await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", ValidationHelper.GetDescription((TipoArquivoDigital)15), "."), "OK", "", false); + } + } + + private void Anotacoes_OnChecked(object sender, RoutedEventArgs e) + { + this.ViewModel.IsAnotacoes = true; + } + + private void AnotacoesInternas_OnChecked(object sender, RoutedEventArgs e) + { + this.ViewModel.IsAnotacoes = false; + } + + private void Apolice_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Abrir((this.ViewModel.SelectedTarefa.get_Entidade() == 3 ? 3 : 0)); + } + + private void ArquivoDigital_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirArquivoDigital(); + } + + private async void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + await this.ViewModel.Cancelar(); + } + + private void Cliente_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Abrir(2); + } + + private async void Concluida_OnClick(object sender, RoutedEventArgs e) + { + if (this.ViewModel.SelectedTarefa == null) + { + await this.ViewModel.ShowMessage("NECESSÁRIO SELECIONAR UMA TAREFA ANTES DE CONCLUIR.", "OK", "", false); + } + else if (await this.ViewModel.ValidaPermissaoParaEditarTarefa()) + { + this.ViewModel.SelectedTarefa.set_Conclusao(new DateTime?(Funcoes.GetNetworkTime())); + this.ViewModel.SelectedTarefa.set_Status(2); + await this.ViewModel.ConcluirTarefa(this.ViewModel.SelectedTarefa); + await this.ViewModel.CarregarTarefas(); + } + else + { + await this.ViewModel.ShowMessage(string.Format("APENAS O USUÁRIO {0} (ID: {1}) PODE CONCLUIR ESSA TAREFA.", this.ViewModel.SelectedTarefa.get_UsuarioCadastro().get_Nome(), this.ViewModel.SelectedTarefa.get_UsuarioCadastro().get_Id()), "OK", "", false); + } + } + + private void ContentLoad() + { + this.AnotacoesButton.IsChecked = new bool?(this.ViewModel.IsAnotacoes); + this.AnotacoesInternasButton.IsChecked = new bool?(!this.ViewModel.IsAnotacoes); + this.AnotacoesButton.Checked += new RoutedEventHandler(this.Anotacoes_OnChecked); + this.AnotacoesInternasButton.Checked += new RoutedEventHandler(this.AnotacoesInternas_OnChecked); + } + + private void CopyTelefoneToClipBoard_Click(object sender, RoutedEventArgs e) + { + Button button = (Button)sender; + if (button.DataContext != null) + { + TelefoneBase dataContext = button.DataContext as TelefoneBase; + if (dataContext != null) + { + string.Concat(dataContext.get_Prefixo(), ValidationHelper.OnlyNumber(dataContext.get_Numero())).CopyToClipboard(); + this.ViewModel.ToggleSnackBar(string.Concat("COPIADO - ", dataContext.get_Prefixo(), ValidationHelper.OnlyNumber(dataContext.get_Numero())), true); + return; + } + } + } + + private async void Email_OnClick(object sender, RoutedEventArgs e) + { + MalaDireta malaDiretum = await this.ViewModel.CriarMalaDireta(this.ViewModel.SelectedTarefa.get_Entidade()); + if (malaDiretum != null) + { + if (Funcoes.IsWindowOpen("ENVIO DE E-MAIL")) + { + Funcoes.Destroy("ENVIO DE E-MAIL"); + } + string str = string.Concat("Cliente: ", this.ViewModel.SelectedTarefa.get_Cliente(), "
"); + str = string.Concat(str, string.Format("Número do Atendimento: {0}
", this.ViewModel.SelectedTarefa.get_Id())); + str = string.Concat(str, string.Format("Data/Hora da Solicitação: {0}
", this.ViewModel.SelectedTarefa.get_Agendamento())); + if (this.ViewModel.SelectedTarefa.get_Conclusao().HasValue) + { + str = string.Concat(str, string.Format("Data/Hora da Conclusão: {0}
", this.ViewModel.SelectedTarefa.get_Conclusao())); + } + if (this.ViewModel.SelectedTarefa.get_Usuario() != null) + { + str = string.Concat(str, "Atendente: ", this.ViewModel.SelectedTarefa.get_Usuario().get_Nome(), "
"); + } + if (this.ViewModel.SelectedTarefa.get_TipoDeTarefa() != null) + { + str = string.Concat(str, "Tipo: ", this.ViewModel.SelectedTarefa.get_TipoDeTarefa().get_Nome(), "
"); + } + str = string.Concat(str, "Assunto: ", this.ViewModel.SelectedTarefa.get_Titulo(), "
"); + str = string.Concat(str, "Situação do Atendimento: ", ValidationHelper.GetDescription(this.ViewModel.SelectedTarefa.get_Status()), "

"); + str = string.Concat(str, "Prezado cliente,
"); + str = string.Concat(str, "Segue, abaixo, a descrição do seu atendimento prestado pela corretora.


"); + List malaDiretas = new List() + { + malaDiretum + }; + (new HosterWindow(new MalaDiretaView(malaDiretas, this.ViewModel.SelectedTarefa.get_Titulo(), string.Concat(str, this.ViewModel.Descricao), null), "ENVIO DE E-MAIL", new double?((double)1200), new double?((double)600), true)).Show(); + } + else + { + await this.ViewModel.ShowMessage("NECESSÁRIO SELECIONAR AO MENOS UM CLIENTE PARA PROSSEGUIR.", "OK", "", false); + } + } + + private async void Excluir_OnClick(object sender, RoutedEventArgs e) + { + if (!this.ViewModel.SelectedTarefa.get_Restrito().HasValue || !this.ViewModel.SelectedTarefa.get_Restrito().Value || this.ViewModel.SelectedTarefa.get_UsuarioCadastro().get_Id() == Recursos.Usuario.get_Id() || Recursos.Usuario.get_Administrador()) + { + await this.ViewModel.Excluir(); + } + else + { + await this.ViewModel.ShowMessage(string.Format("APENAS O USUÁRIO {0} (ID: {1}) PODE EXCLUIR ESSA TAREFA.", this.ViewModel.SelectedTarefa.get_UsuarioCadastro().get_Nome(), this.ViewModel.SelectedTarefa.get_UsuarioCadastro().get_Id()), "OK", "", false); + } + } + + private void ExcluirFiltro_onClick(object sender, RoutedEventArgs e) + { + Chip chip = sender as Chip; + if (chip == null) + { + return; + } + ListBox listBox = Extentions.FindVisualAncestor(chip); + string item = (string)listBox.Items[listBox.Items.IndexOf(chip.DataContext)]; + if (item == null) + { + return; + } + this.ViewModel.ExcluirFiltro(item); + } + + private void ExcluirResponsavel_OnClick(object sender, RoutedEventArgs e) + { + Chip chip = sender as Chip; + if (chip == null) + { + return; + } + ResponsavelTarefa dataContext = (ResponsavelTarefa)chip.DataContext; + if (dataContext == null) + { + return; + } + this.ViewModel.Responsaveis.Remove(dataContext); + this.ViewModel.Usuarios.Add(dataContext.get_Usuario()); + this.ViewModel.Usuarios = new ObservableCollection( + from x in this.ViewModel.Usuarios + orderby x.get_Nome() + select x); + } + + private async void ExcluirTarefa_OnClick(object sender, RoutedEventArgs e) + { + if (await this.ViewModel.ValidaPermissaoParaExcluirTarefa(null)) + { + await this.ViewModel.Excluir(); + } + else + { + await this.ViewModel.ShowMessage(string.Format("APENAS O USUÁRIO {0} (ID: {1}) PODE EXCLUIR ESSA TAREFA.", this.ViewModel.SelectedTarefa.get_UsuarioCadastro().get_Nome(), this.ViewModel.SelectedTarefa.get_UsuarioCadastro().get_Id()), "OK", "", false); + } + } + + private void Imprimir_OnClick(object sender, RoutedEventArgs e) + { + if (this.ViewModel.SelectedTarefa.get_Id() == 0) + { + return; + } + this.ViewModel.Print(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/bi/tarefaview.xaml", UriKind.Relative)); + } + + private async void NaoConcluida_OnClick(object sender, RoutedEventArgs e) + { + if (this.ViewModel.SelectedTarefa != null) + { + this.ViewModel.SelectedTarefa.set_Conclusao(null); + this.ViewModel.SelectedTarefa.set_Status(0); + await this.ViewModel.ConcluirTarefa(this.ViewModel.SelectedTarefa); + await this.ViewModel.CarregarTarefas(); + } + else + { + await this.ViewModel.ShowMessage("NECESSÁRIO SELECIONAR UMA TAREFA ANTES DE MARCAR COMO NÃO CONCLUÍDO.", "OK", "", false); + } + } + + private async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.SelectedTarefa.set_Anotacoes(this.Anotacoes.GetHtml()); + this.ViewModel.SelectedTarefa.set_AnotacoesInternas(this.AnotacoesInternas.GetHtml()); + this.ViewModel.SelectedTarefa.set_Usuario((Usuario)this.ResponsavelBox.SelectedItem); + List> keyValuePairs = await this.ViewModel.Salvar(this.TituloTarefaLabel.Text); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + else + { + this.ViewModel.ToggleSnackBar("TAREFA SALVA COM SUCESSO.", true); + this.ViewModel.Alterar(false); + } + } + + private void Sinistro_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Abrir(4); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.UsuarioBox = (ComboBox)target; + return; + } + case 2: + { + this.InicioBox = (DatePicker)target; + this.InicioBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.InicioBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 3: + { + this.FimBox = (DatePicker)target; + this.FimBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.FimBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 4: + { + ((Button)target).Click += new RoutedEventHandler(this.AdicionarFiltro_OnClick); + return; + } + case 5: + case 6: + case 7: + case 22: + case 23: + case 28: + { + this._contentLoaded = true; + return; + } + case 8: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Concluida_OnClick); + return; + } + case 9: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.NaoConcluida_OnClick); + return; + } + case 10: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 11: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 12: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 13: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Excluir_OnClick); + return; + } + case 14: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AnexoTarefa_OnClick); + return; + } + case 15: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Cliente_OnClick); + return; + } + case 16: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Apolice_OnClick); + return; + } + case 17: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.ArquivoDigital_OnClick); + return; + } + case 18: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Sinistro_OnClick); + return; + } + case 19: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Imprimir_OnClick); + return; + } + case 20: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Email_OnClick); + return; + } + case 21: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick); + return; + } + case 24: + { + this.TituloTarefaLabel = (TextBox)target; + return; + } + case 25: + { + this.AgendamentoBox = (DatePicker)target; + this.AgendamentoBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + return; + } + case 26: + { + this.ResponsavelBox = (ComboBox)target; + return; + } + case 27: + { + ((Button)target).Click += new RoutedEventHandler(this.AdicionarResponsavel_OnClick); + return; + } + case 29: + { + this.AnotacoesButton = (RadioButton)target; + return; + } + case 30: + { + this.AnotacoesInternasButton = (RadioButton)target; + return; + } + case 31: + { + this.Anotacoes = (WebEditor)target; + return; + } + case 32: + { + this.Historico = (WebEditor)target; + return; + } + case 33: + { + this.AnotacoesInternas = (WebEditor)target; + return; + } + case 34: + { + this.HistoricoInterno = (WebEditor)target; + return; + } + default: + { + this._contentLoaded = true; + return; + } + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + if (connectionId > 22) + { + if (connectionId == 23) + { + ((Button)target).Click += new RoutedEventHandler(this.WhatsAppMessage_Click); + return; + } + if (connectionId != 28) + { + return; + } + ((Chip)target).add_DeleteClick(new RoutedEventHandler(this.ExcluirResponsavel_OnClick)); + return; + } + switch (connectionId) + { + case 5: + { + ((Chip)target).add_DeleteClick(new RoutedEventHandler(this.ExcluirFiltro_onClick)); + return; + } + case 6: + { + ((Button)target).Click += new RoutedEventHandler(this.ExcluirTarefa_OnClick); + return; + } + case 7: + { + ((Button)target).Click += new RoutedEventHandler(this.TarefaConcluida_OnClick); + return; + } + default: + { + if (connectionId == 22) + { + break; + } + else + { + return; + } + } + } + ((Button)target).Click += new RoutedEventHandler(this.CopyTelefoneToClipBoard_Click); + } + + private async void TarefaConcluida_OnClick(object sender, RoutedEventArgs e) + { + Tarefa dataContext = ((Button)sender).DataContext as Tarefa; + if (dataContext != null) + { + if (await this.ViewModel.ValidaPermissaoParaEditarTarefa()) + { + dataContext.set_Conclusao(new DateTime?(Funcoes.GetNetworkTime())); + dataContext.set_Status(2); + await this.ViewModel.ConcluirTarefa(dataContext); + await this.ViewModel.CarregarTarefas(); + Action atualizaTrilhas = Gestor.Application.Actions.Actions.AtualizaTrilhas; + if (atualizaTrilhas != null) + { + atualizaTrilhas(); + } + else + { + } + } + else + { + await this.ViewModel.ShowMessage(string.Format("APENAS O USUÁRIO {0} (ID: {1}) PODE CONCLUIR ESSA TAREFA.", this.ViewModel.SelectedTarefa.get_UsuarioCadastro().get_Nome(), this.ViewModel.SelectedTarefa.get_UsuarioCadastro().get_Id()), "OK", "", false); + } + } + dataContext = null; + } + + private async void WhatsAppMessage_Click(object sender, RoutedEventArgs e) + { + string str; + Button button = (Button)sender; + if (button.DataContext != null) + { + TelefoneBase dataContext = button.DataContext as TelefoneBase; + if (dataContext != null) + { + str = (!dataContext.get_Tipo().HasValue || dataContext.get_Tipo().GetValueOrDefault() != 8 ? string.Concat("55", dataContext.get_Prefixo(), dataContext.get_Numero().Clear()) : string.Concat(dataContext.get_Prefixo(), dataContext.get_Numero()).Clear()); + if (!str.EnviarWhatsapp(null)) + { + await this.ViewModel.ShowMessage("HOUVE UM PROBLEMA AO ABRIR LINK DO WHATSAPP, O LINK FOI COPIADO EM SUA MAQUINA, BASTA ABRIR O NAVEGADOR DE INTERNET E COLAR NA BARRA DE ENDEREÇOS", "OK", "", false); + } + return; + } + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/ConnectionRetryView.cs b/Codemerx/Gestor.Application/Views/ConnectionRetryView.cs new file mode 100644 index 0000000..94d0947 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/ConnectionRetryView.cs @@ -0,0 +1,218 @@ +using Gestor.Application; +using Gestor.Application.Helpers; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using System; +using System.CodeDom.Compiler; +using System.ComponentModel; +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Media; +using System.Windows.Shapes; +using System.Windows.Shell; + +namespace Gestor.Application.Views +{ + public class ConnectionRetryView : Window, IComponentConnector + { + public TaskCompletionSource CloseTask = new TaskCompletionSource(); + + private bool _buttonClickable; + + internal System.Windows.Shell.WindowChrome WindowChrome; + + internal Grid MinimizeButton; + + internal Grid CloseButton; + + internal ProgressBar ProgressRing; + + internal ItemsControl Controls; + + private bool _contentLoaded; + + public UnitOfWork UnitOfWOrk + { + get; + set; + } + + public ConnectionRetryView() + { + this.InitializeComponent(); + this.MinimizeButton.MouseEnter += new MouseEventHandler(ConnectionRetryView.TopControls_OnMouseEnter); + this.MinimizeButton.MouseLeave += new MouseEventHandler(this.TopControls_OnMouseLeave); + this.CloseButton.MouseEnter += new MouseEventHandler(ConnectionRetryView.TopControls_OnMouseEnter); + this.CloseButton.MouseLeave += new MouseEventHandler(this.TopControls_OnMouseLeave); + base.Closed += new EventHandler((object s, EventArgs a) => this.CloseTask.SetResult(null)); + } + + private void btnRestart_OnClick(object sender, RoutedEventArgs e) + { + Instancia.App.Restart(); + } + + private async void btnRetry_Click(object sender, RoutedEventArgs e) + { + this.Loading(true); + UnitOfWork unitOfWork1 = await Task.Run(() => { + UnitOfWork unitOfWork; + try + { + Instancia.Conexao = Instancia.Conexao ?? Connection.GetConnection(true); + unitOfWork = new UnitOfWork(Instancia.Conexao, true); + } + catch (Exception exception) + { + unitOfWork = null; + } + return unitOfWork; + }); + this.Loading(false); + if (unitOfWork1 != null && unitOfWork1.get_HasSession()) + { + this.UnitOfWOrk = unitOfWork1; + base.Close(); + } + } + + public void CloseButton_Click() + { + base.Close(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/connectionretryview.xaml", UriKind.Relative)); + } + + private void Loading(bool isLoading) + { + this.Controls.Visibility = (!isLoading ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.ProgressRing.Visibility = (isLoading ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + base.IsEnabled = !isLoading; + } + + public void MinimizeButton_Click() + { + base.WindowState = System.Windows.WindowState.Minimized; + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.WindowChrome = (System.Windows.Shell.WindowChrome)target; + return; + } + case 2: + { + this.MinimizeButton = (Grid)target; + this.MinimizeButton.MouseLeftButtonDown += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonDown); + this.MinimizeButton.MouseLeftButtonUp += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonUp); + return; + } + case 3: + { + this.CloseButton = (Grid)target; + this.CloseButton.MouseLeftButtonDown += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonDown); + this.CloseButton.MouseLeftButtonUp += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonUp); + return; + } + case 4: + { + this.ProgressRing = (ProgressBar)target; + return; + } + case 5: + { + this.Controls = (ItemsControl)target; + return; + } + case 6: + { + ((RepeatButton)target).Click += new RoutedEventHandler(this.btnRetry_Click); + return; + } + case 7: + { + ((RepeatButton)target).Click += new RoutedEventHandler(this.btnRestart_OnClick); + return; + } + } + this._contentLoaded = true; + } + + private static void TopControls_OnMouseEnter(object sender, MouseEventArgs e) + { + ((Grid)sender).Background = (((Grid)sender).Name == "CloseButton" ? new SolidColorBrush(Color.FromRgb(232, 17, 35)) : new SolidColorBrush(Colors.Blue)); + Path child = VisualTreeHelper.GetChild((Grid)sender, 0) as Path; + if (child != null) + { + child.Stroke = new SolidColorBrush(Colors.White); + } + } + + private void TopControls_OnMouseLeave(object sender, MouseEventArgs e) + { + this._buttonClickable = false; + ((Grid)sender).Background = new SolidColorBrush(Colors.Transparent); + Path child = VisualTreeHelper.GetChild((Grid)sender, 0) as Path; + if (child != null) + { + child.Stroke = new SolidColorBrush(Colors.White); + } + } + + private void TopControls_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e) + { + this._buttonClickable = true; + if (((Grid)sender).Name != "CloseButton") + { + ((Grid)sender).Background = new SolidColorBrush(Colors.Blue); + } + else + { + ((Grid)sender).Background = new SolidColorBrush(Color.FromRgb(241, 112, 123)); + Path child = VisualTreeHelper.GetChild((Grid)sender, 0) as Path; + if (child != null) + { + child.Stroke = new SolidColorBrush(Colors.Black); + return; + } + } + } + + private void TopControls_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e) + { + if (this._buttonClickable) + { + MethodInfo method = base.GetType().GetMethod(string.Concat(((Grid)sender).Name, "_Click")); + if (method == null) + { + return; + } + method.Invoke(this, null); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Ferramentas/CadastroEmailView.cs b/Codemerx/Gestor.Application/Views/Ferramentas/CadastroEmailView.cs new file mode 100644 index 0000000..d4691ca --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Ferramentas/CadastroEmailView.cs @@ -0,0 +1,400 @@ +using Gestor.Application.Componentes; +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels.Ferramentas; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Views.Ferramentas +{ + public class CadastroEmailView : UserControl, IComponentConnector + { + internal DataGrid CredenciaisGrid; + + internal MenuItem SalvarApoliceButton; + + internal MenuItem CancelarApoliceButton; + + internal MenuItem MaisOpcoesButton; + + internal TextBox DescricaoBox; + + internal TextBox HeaderBox; + + internal ComboBox TipoBox; + + internal TextBox PortaBox; + + internal TextBox DominioBox; + + internal TextBox EmailBox; + + internal CustomPasswordBox SenhaBox; + + internal TextBox LoginBox; + + internal TextBlock CabecalhoTitulo; + + internal WebEditor Cabecalho; + + internal TextBlock AssinaturaTitulo; + + internal WebEditor Assinatura; + + private bool _contentLoaded; + + public CadastroEmailViewModel ViewModel + { + get; + set; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public CadastroEmailView() + { + base.Tag = "CADASTRO DE E-MAIL"; + this.ViewModel = new CadastroEmailViewModel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + + private void AbrirLog_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLog(17, this.ViewModel.SelectedCredencial.get_Id()); + } + + private void Alterar_OnClick(object sender, RoutedEventArgs e) + { + this.Assinatura.Visibility = System.Windows.Visibility.Visible; + this.AssinaturaTitulo.Visibility = System.Windows.Visibility.Visible; + this.Cabecalho.Visibility = System.Windows.Visibility.Visible; + this.CabecalhoTitulo.Visibility = System.Windows.Visibility.Visible; + this.ViewModel.Alterar(true); + this.ValidarTela(); + this.ViewModel.SelectedCredencial.Initialize(); + } + + private void AutoCompleteBox_OnTextChanged(object sender, RoutedEventArgs e) + { + if (!string.IsNullOrWhiteSpace(((AutoCompleteBox)sender).get_Text())) + { + return; + } + this.ViewModel.FiltrarCredenciais(""); + } + + private void AutoCompleteBox_Populating(object sender, PopulatingEventArgs e) + { + e.set_Cancel(true); + this.ViewModel.Filtrar(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private async void ButtonBase_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Loading(true); + bool flag = await this.ViewModel.EnviarTesteEmail(); + this.ViewModel.Loading(false); + if (flag) + { + this.ViewModel.ToggleSnackBar("E-MAIL ENVIADO COM SUCESSO.", true); + } + } + + private async void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Loading(true); + await this.ViewModel.CancelarAlteracao(); + this.Assinatura.Initialize(null); + this.Assinatura.Visibility = System.Windows.Visibility.Collapsed; + this.AssinaturaTitulo.Visibility = System.Windows.Visibility.Collapsed; + this.Cabecalho.Initialize(null); + this.Cabecalho.Visibility = System.Windows.Visibility.Collapsed; + this.CabecalhoTitulo.Visibility = System.Windows.Visibility.Collapsed; + this.ViewModel.Loading(false); + this.ScrollToItem(); + } + + private async void ContentLoad() + { + this.ViewModel.Loading(true); + await this.ViewModel.SelecionaCredenciais(); + this.ViewModel.Loading(false); + } + + private void EmailBox_OnLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) + { + if (((TextBox)sender).Text.Contains("@gmail.com")) + { + this.TipoBox.SelectedItem = (TipoEmail)1; + } + } + + private async void Excluir_OnClick(object sender, RoutedEventArgs e) + { + await this.ViewModel.Excluir(); + this.ScrollToItem(); + } + + private void Incluir_OnClick(object sender, RoutedEventArgs e) + { + this.Assinatura.Visibility = System.Windows.Visibility.Visible; + this.AssinaturaTitulo.Visibility = System.Windows.Visibility.Visible; + this.ViewModel.Incluir(); + this.ValidarTela(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/ferramentas/cadastroemailview.xaml", UriKind.Relative)); + } + + public string ReplaceLocalImages(string mailBody) + { + string[] array = ( + from Match m in Regex.Matches(mailBody, "", RegexOptions.IgnoreCase) + select m.Groups[0].Value).ToArray(); + for (int i = 0; i < (int)array.Length; i++) + { + string value = Regex.Match(array[i], "(?<=src=\")(.*?)(?=\")", RegexOptions.IgnoreCase).Value; + string str = Regex.Match(value, "file:(///).*\\.(.*)", RegexOptions.IgnoreCase).Groups[2].Value; + if (str == "jpg") + { + str = "jpeg"; + } + if (Uri.IsWellFormedUriString(value, UriKind.Absolute)) + { + Uri uri = new Uri(value); + if (File.Exists(uri.LocalPath)) + { + mailBody = mailBody.Replace(value, string.Concat("data:image/", str, ";base64,", Convert.ToBase64String(File.ReadAllBytes(uri.LocalPath)))); + } + } + } + return mailBody; + } + + private async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.Loading(true); + this.ViewModel.SelectedCredencial.set_Assinatura(this.ReplaceLocalImages(this.Assinatura.GetHtml())); + this.ViewModel.SelectedCredencial.set_Cabecalho(this.ReplaceLocalImages(this.Cabecalho.GetHtml())); + List> keyValuePairs = await this.ViewModel.Salvar(); + this.ValidateFields(keyValuePairs, true); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + else + { + this.Assinatura.Visibility = System.Windows.Visibility.Collapsed; + this.AssinaturaTitulo.Visibility = System.Windows.Visibility.Collapsed; + this.Cabecalho.Visibility = System.Windows.Visibility.Collapsed; + this.CabecalhoTitulo.Visibility = System.Windows.Visibility.Collapsed; + this.ScrollToItem(); + } + } + + private void ScrollToItem() + { + if (this.CredenciaisGrid.SelectedItem == null) + { + return; + } + this.CredenciaisGrid.UpdateLayout(); + this.CredenciaisGrid.ScrollIntoView(this.CredenciaisGrid.SelectedItem); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, CadastroEmailView.AutoCompleteBox_Populating)); + ((AutoCompleteBox)target).add_TextChanged(new RoutedEventHandler(this.AutoCompleteBox_OnTextChanged)); + return; + } + case 2: + { + this.CredenciaisGrid = (DataGrid)target; + return; + } + case 3: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + case 4: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 5: + { + this.SalvarApoliceButton = (MenuItem)target; + this.SalvarApoliceButton.Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 6: + { + this.CancelarApoliceButton = (MenuItem)target; + this.CancelarApoliceButton.Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 7: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Excluir_OnClick); + return; + } + case 8: + { + this.MaisOpcoesButton = (MenuItem)target; + return; + } + case 9: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.ButtonBase_OnClick); + return; + } + case 10: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick); + return; + } + case 11: + { + this.DescricaoBox = (TextBox)target; + return; + } + case 12: + { + this.HeaderBox = (TextBox)target; + return; + } + case 13: + { + this.TipoBox = (ComboBox)target; + this.TipoBox.SelectionChanged += new SelectionChangedEventHandler(this.Tipo_OnSelectionChanged); + return; + } + case 14: + { + this.PortaBox = (TextBox)target; + return; + } + case 15: + { + this.DominioBox = (TextBox)target; + return; + } + case 16: + { + this.EmailBox = (TextBox)target; + this.EmailBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.EmailBox_OnLostKeyboardFocus); + return; + } + case 17: + { + this.SenhaBox = (CustomPasswordBox)target; + return; + } + case 18: + { + this.LoginBox = (TextBox)target; + return; + } + case 19: + { + this.CabecalhoTitulo = (TextBlock)target; + return; + } + case 20: + { + this.Cabecalho = (WebEditor)target; + return; + } + case 21: + { + this.AssinaturaTitulo = (TextBlock)target; + return; + } + case 22: + { + this.Assinatura = (WebEditor)target; + return; + } + } + this._contentLoaded = true; + } + + private void Tipo_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + TipoEmail? selectedItem = (TipoEmail?)((ComboBox)sender).SelectedItem; + if (selectedItem.GetValueOrDefault() == 0 & selectedItem.HasValue && this.ViewModel.SelectedCredencial.get_Email() != null && this.ViewModel.SelectedCredencial.get_Email().Contains("@gmail.com")) + { + this.EmailBox.Text = ""; + } + } + + private void ValidarTela() + { + if (this.ViewModel.SelectedCredencial == null) + { + return; + } + List> keyValuePairs = this.ViewModel.SelectedCredencial.Validate(); + this.ValidateFields(keyValuePairs, false); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Ferramentas/CadastroParceiroView.cs b/Codemerx/Gestor.Application/Views/Ferramentas/CadastroParceiroView.cs new file mode 100644 index 0000000..ae3bfde --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Ferramentas/CadastroParceiroView.cs @@ -0,0 +1,387 @@ +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels.Ferramentas; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Views.Ferramentas +{ + public class CadastroParceiroView : BaseUserControl, IComponentConnector + { + internal DataGrid ParceiroGrid; + + internal MenuItem MaisOpcoesButton; + + internal TextBox NomeBox; + + internal TextBox DocumentoPrincipalBox; + + internal TextBox PrimeiroPrefixo; + + internal TextBox PrimeiroTelefone; + + internal TextBox SegundoPrefixo; + + internal TextBox SegundoTelefone; + + internal TextBox TerceiroPrefixo; + + internal TextBox TerceiroTelefone; + + internal TextBox EmailBox; + + internal TextBox CepBox; + + internal TextBox EnderecoBox; + + internal TextBox NumeroBox; + + internal TextBox BairroBox; + + internal TextBox CidadeBox; + + internal TextBox EstadoBox; + + private bool _contentLoaded; + + public CadastroParceiroViewModel ViewModel + { + get; + set; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public CadastroParceiroView(Parceiro parceiro = null) + { + CadastroParceiroView cadastroParceiroView = this; + base.Tag = "CADASTRO DE PARCEIROS"; + this.ViewModel = new CadastroParceiroViewModel(parceiro); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(() => cadastroParceiroView.ContentLoad(parceiro))); + } + + private void AbrirLog_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLog(22, this.ViewModel.SelectedParceiro.get_Id()); + } + + private void Alterar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelParceiro = (Parceiro)this.ViewModel.SelectedParceiro.Clone(); + this.ViewModel.Alterar(true); + this.ValidarTela(); + this.ViewModel.SelectedParceiro.Initialize(); + } + + private void AutoCompleteBox_OnTextChanged(object sender, RoutedEventArgs e) + { + if (!string.IsNullOrWhiteSpace(((AutoCompleteBox)sender).get_Text())) + { + return; + } + this.ViewModel.FiltrarParceiro(""); + } + + private void AutoCompleteBoxParceiro_Populating(object sender, PopulatingEventArgs e) + { + e.set_Cancel(true); + this.ViewModel.Filtrar(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelarAlteracao(); + } + + private void ContentLoad(Parceiro parceiro) + { + if (parceiro == null) + { + this.ParceiroGrid.SelectedIndex = -1; + } + this.ParceiroGrid.SelectionChanged += new SelectionChangedEventHandler(this.ParceiroGrid_OnSelectionChanged); + this.ParceiroGrid.MouseDoubleClick += new MouseButtonEventHandler((object sender, MouseButtonEventArgs args) => { + }); + } + + private void DocumentoPrincipalBox_LostFocus(object sender, RoutedEventArgs e) + { + if (((TextBox)sender).IsReadOnly) + { + return; + } + string str = ValidationHelper.Clear(this.DocumentoPrincipalBox.Text); + if (string.IsNullOrEmpty(str)) + { + return; + } + this.DocumentoPrincipalBox.Text = (str.Length == 11 ? ValidationHelper.FormatDocument(str.PadLeft(11, '0').Substring(0, 11)) : ValidationHelper.FormatDocument(str.PadLeft(14, '0').Substring(0, 14))); + } + + private void Excluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Excluir(); + } + + private void Incluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Incluir(); + this.ValidarTela(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/ferramentas/cadastroparceiroview.xaml", UriKind.Relative)); + } + + private void ParceiroGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + DataGrid dataGrid = (DataGrid)sender; + if (dataGrid != null && dataGrid.SelectedIndex < 0) + { + return; + } + this.ViewModel.SelecionarParceiro((Parceiro)((dataGrid != null ? dataGrid.Items[dataGrid.SelectedIndex] : null))); + } + + private async void PostcodeBox_OnLostFocus(object sender, RoutedEventArgs e) + { + string str = ValidationHelper.FormatPostCode(((TextBox)sender).Text); + this.CepBox.Text = str; + if (ValidationHelper.ValidatePostCode(str)) + { + EnderecoBase enderecoBase = await this.ViewModel.BuscaCep(str); + if (enderecoBase != null) + { + this.EnderecoBox.Text = enderecoBase.get_Endereco(); + this.CidadeBox.Text = enderecoBase.get_Cidade(); + this.EstadoBox.Text = enderecoBase.get_Estado(); + this.BairroBox.Text = enderecoBase.get_Bairro(); + } + } + } + + private async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.Loading(true); + this.NomeBox.Focus(); + List> keyValuePairs = await this.ViewModel.Salvar(); + this.ValidateFields(keyValuePairs, true); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, CadastroParceiroView.AutoCompleteBoxParceiro_Populating)); + ((AutoCompleteBox)target).add_TextChanged(new RoutedEventHandler(this.AutoCompleteBox_OnTextChanged)); + return; + } + case 2: + { + this.ParceiroGrid = (DataGrid)target; + return; + } + case 3: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + case 4: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 6: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 7: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Excluir_OnClick); + return; + } + case 8: + { + this.MaisOpcoesButton = (MenuItem)target; + return; + } + case 9: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick); + return; + } + case 10: + { + this.NomeBox = (TextBox)target; + return; + } + case 11: + { + this.DocumentoPrincipalBox = (TextBox)target; + this.DocumentoPrincipalBox.LostFocus += new RoutedEventHandler(this.DocumentoPrincipalBox_LostFocus); + CadastroParceiroView cadastroParceiroView = this; + this.DocumentoPrincipalBox.PreviewTextInput += new TextCompositionEventHandler(cadastroParceiroView.SomenteNumeros); + return; + } + case 12: + { + this.PrimeiroPrefixo = (TextBox)target; + CadastroParceiroView cadastroParceiroView1 = this; + this.PrimeiroPrefixo.PreviewTextInput += new TextCompositionEventHandler(cadastroParceiroView1.SomenteNumeros); + return; + } + case 13: + { + this.PrimeiroTelefone = (TextBox)target; + CadastroParceiroView cadastroParceiroView2 = this; + this.PrimeiroTelefone.LostFocus += new RoutedEventHandler(cadastroParceiroView2.FormatarTelefone); + CadastroParceiroView cadastroParceiroView3 = this; + this.PrimeiroTelefone.PreviewTextInput += new TextCompositionEventHandler(cadastroParceiroView3.SomenteNumeros); + return; + } + case 14: + { + this.SegundoPrefixo = (TextBox)target; + CadastroParceiroView cadastroParceiroView4 = this; + this.SegundoPrefixo.PreviewTextInput += new TextCompositionEventHandler(cadastroParceiroView4.SomenteNumeros); + return; + } + case 15: + { + this.SegundoTelefone = (TextBox)target; + CadastroParceiroView cadastroParceiroView5 = this; + this.SegundoTelefone.LostFocus += new RoutedEventHandler(cadastroParceiroView5.FormatarTelefone); + CadastroParceiroView cadastroParceiroView6 = this; + this.SegundoTelefone.PreviewTextInput += new TextCompositionEventHandler(cadastroParceiroView6.SomenteNumeros); + return; + } + case 16: + { + this.TerceiroPrefixo = (TextBox)target; + CadastroParceiroView cadastroParceiroView7 = this; + this.TerceiroPrefixo.PreviewTextInput += new TextCompositionEventHandler(cadastroParceiroView7.SomenteNumeros); + return; + } + case 17: + { + this.TerceiroTelefone = (TextBox)target; + CadastroParceiroView cadastroParceiroView8 = this; + this.TerceiroTelefone.LostFocus += new RoutedEventHandler(cadastroParceiroView8.FormatarTelefone); + CadastroParceiroView cadastroParceiroView9 = this; + this.TerceiroTelefone.PreviewTextInput += new TextCompositionEventHandler(cadastroParceiroView9.SomenteNumeros); + return; + } + case 18: + { + this.EmailBox = (TextBox)target; + return; + } + case 19: + { + this.CepBox = (TextBox)target; + this.CepBox.LostFocus += new RoutedEventHandler(this.PostcodeBox_OnLostFocus); + CadastroParceiroView cadastroParceiroView10 = this; + this.CepBox.PreviewTextInput += new TextCompositionEventHandler(cadastroParceiroView10.SomenteNumeros); + return; + } + case 20: + { + this.EnderecoBox = (TextBox)target; + return; + } + case 21: + { + this.NumeroBox = (TextBox)target; + return; + } + case 22: + { + this.BairroBox = (TextBox)target; + return; + } + case 23: + { + this.CidadeBox = (TextBox)target; + return; + } + case 24: + { + this.EstadoBox = (TextBox)target; + return; + } + } + this._contentLoaded = true; + } + + private void ValidarTela() + { + if (this.ViewModel.SelectedParceiro == null) + { + return; + } + List> keyValuePairs = this.ViewModel.SelectedParceiro.Validate(); + this.ValidateFields(keyValuePairs, false); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Ferramentas/DownloadWindow.cs b/Codemerx/Gestor.Application/Views/Ferramentas/DownloadWindow.cs new file mode 100644 index 0000000..1fd4776 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Ferramentas/DownloadWindow.cs @@ -0,0 +1,171 @@ +using Gestor.Application.ViewModels.Ferramentas; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.API; +using System; +using System.CodeDom.Compiler; +using System.ComponentModel; +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Media; +using System.Windows.Shapes; +using System.Windows.Shell; +using System.Windows.Threading; + +namespace Gestor.Application.Views.Ferramentas +{ + public class DownloadWindow : Window, IComponentConnector + { + internal DownloadViewModel ViewModel; + + private bool _buttonClickable; + + internal System.Windows.Shell.WindowChrome WindowChrome; + + internal Grid MinimizeButton; + + internal Grid MaximizeButton; + + internal Grid CloseButton; + + private bool _contentLoaded; + + public DownloadWindow(Parameters parameters) + { + this.ViewModel = new DownloadViewModel(parameters); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + + public void CloseButton_Click() + { + base.Close(); + } + + private void ContentLoad() + { + this.MinimizeButton.MouseEnter += new MouseEventHandler(DownloadWindow.TopControls_OnMouseEnter); + this.MinimizeButton.MouseLeave += new MouseEventHandler(this.TopControls_OnMouseLeave); + this.MaximizeButton.MouseEnter += new MouseEventHandler(DownloadWindow.TopControls_OnMouseEnter); + this.MaximizeButton.MouseLeave += new MouseEventHandler(this.TopControls_OnMouseLeave); + this.CloseButton.MouseEnter += new MouseEventHandler(DownloadWindow.TopControls_OnMouseEnter); + this.CloseButton.MouseLeave += new MouseEventHandler(this.TopControls_OnMouseLeave); + } + + private async void DownloadWindow_OnLoaded(object sender, RoutedEventArgs e) + { + this.ViewModel.IsEnabled = false; + await this.ViewModel.Atualizar(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/ferramentas/downloadwindow.xaml", UriKind.Relative)); + } + + public void MinimizeButton_Click() + { + base.WindowState = System.Windows.WindowState.Minimized; + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((DownloadWindow)target).Loaded += new RoutedEventHandler(this.DownloadWindow_OnLoaded); + return; + } + case 2: + { + this.WindowChrome = (System.Windows.Shell.WindowChrome)target; + return; + } + case 3: + { + this.MinimizeButton = (Grid)target; + this.MinimizeButton.MouseLeftButtonDown += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonDown); + this.MinimizeButton.MouseLeftButtonUp += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonUp); + return; + } + case 4: + { + this.MaximizeButton = (Grid)target; + this.MaximizeButton.MouseLeftButtonDown += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonDown); + this.MaximizeButton.MouseLeftButtonUp += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonUp); + return; + } + case 5: + { + this.CloseButton = (Grid)target; + this.CloseButton.MouseLeftButtonDown += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonDown); + this.CloseButton.MouseLeftButtonUp += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonUp); + return; + } + } + this._contentLoaded = true; + } + + private static void TopControls_OnMouseEnter(object sender, MouseEventArgs e) + { + ((Grid)sender).Background = (((Grid)sender).Name == "CloseButton" ? new SolidColorBrush(Colors.IndianRed) : new SolidColorBrush(Colors.Gray)); + Path child = VisualTreeHelper.GetChild((Grid)sender, 0) as Path; + if (child != null) + { + child.Stroke = new SolidColorBrush(Colors.White); + } + } + + private void TopControls_OnMouseLeave(object sender, MouseEventArgs e) + { + this._buttonClickable = false; + ((Grid)sender).Background = new SolidColorBrush(Colors.Transparent); + Path child = VisualTreeHelper.GetChild((Grid)sender, 0) as Path; + if (child != null) + { + child.Stroke = new SolidColorBrush(Colors.White); + } + } + + private void TopControls_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e) + { + this._buttonClickable = true; + ((Grid)sender).Background = (((Grid)sender).Name == "CloseButton" ? new SolidColorBrush(Colors.Red) : new SolidColorBrush(Colors.DimGray)); + } + + private void TopControls_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e) + { + if (this._buttonClickable) + { + MethodInfo method = base.GetType().GetMethod(string.Concat(((Grid)sender).Name, "_Click")); + if (method == null) + { + return; + } + method.Invoke(this, null); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Ferramentas/EmpresaView.cs b/Codemerx/Gestor.Application/Views/Ferramentas/EmpresaView.cs new file mode 100644 index 0000000..f431ae6 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Ferramentas/EmpresaView.cs @@ -0,0 +1,424 @@ +using Gestor.Application.Componentes; +using Gestor.Application.Drawers; +using Gestor.Application.Drawers.Configuracoes; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.ViewModels.Ferramentas; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Views.Ferramentas +{ + public class EmpresaView : BaseUserControl, IComponentConnector + { + internal DataGrid EmpresaGrid; + + internal MenuItem Alterar; + + internal TextBox DocumentoPrincipalBox; + + internal TextBox NomeBox; + + internal TextBox CepBox; + + internal TextBox EnderecoBox; + + internal TextBox BairroBox; + + internal TextBox CidadeBox; + + internal TextBox EstadoBox; + + internal CustomPasswordBox SenhaBox; + + private bool _contentLoaded; + + public EmpresaViewModel ViewModel + { + get; + set; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public EmpresaView() + { + base.Tag = "CADASTRO DE EMPRESA E FILIAIS"; + this.ViewModel = new EmpresaViewModel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + + private async void AbrirAquivoDigital_Click(object sender, RoutedEventArgs e) + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 13).get_Consultar()) + { + FiltroArquivoDigital filtroArquivoDigital = new FiltroArquivoDigital(); + filtroArquivoDigital.set_Id(this.ViewModel.SelectedEmpresa.get_Id()); + filtroArquivoDigital.set_Tipo(13); + filtroArquivoDigital.set_Parente(this.ViewModel.SelectedEmpresa); + this.ViewModel.ShowDrawer(new ArquivoDigitalDrawer(filtroArquivoDigital), 0, false); + } + else + { + await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", ValidationHelper.GetDescription((TipoArquivoDigital)13), "."), "OK", "", false); + } + } + + private void AbrirLog_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLog(18, this.ViewModel.SelectedEmpresa.get_Id()); + } + + private void AbrirLogEmail_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLogEmail(18, this.ViewModel.SelectedEmpresa.get_Id()); + } + + private void Alterar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelEmpresa = (Empresa)this.ViewModel.SelectedEmpresa.Clone(); + this.ViewModel.Alterar(true); + this.PermissaoAuteracao(); + this.ViewModel.PassWordReadOnly = this.ViewModel.EnableFields; + this.ViewModel.ConfirmacaoSenha = (this.ViewModel.SelectedEmpresa.get_Id() == (long)1 ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + } + + private async void AnexarLogo_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Loading(true); + await this.ViewModel.AnexarLogo(); + this.ViewModel.Loading(false); + } + + private void AutoCompleteBox_OnTextChanged(object sender, RoutedEventArgs e) + { + if (!string.IsNullOrWhiteSpace(((AutoCompleteBox)sender).get_Text())) + { + return; + } + this.ViewModel.FiltrarEmpresa(""); + } + + private void AutoCompleteBoxEmpresa_Populating(object sender, PopulatingEventArgs e) + { + e.set_Cancel(true); + this.ViewModel.Filtrar(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelarAlteracao(); + if (Recursos.Usuario.get_Id() == 0) + { + this.Alterar.IsEnabled = true; + } + this.NomeBox.IsReadOnly = true; + this.DocumentoPrincipalBox.IsReadOnly = true; + this.ViewModel.PassWordReadOnly = this.ViewModel.EnableFields; + this.ViewModel.ConfirmacaoSenha = System.Windows.Visibility.Collapsed; + } + + private async void Configuracoes_OnClick(object sender, RoutedEventArgs e) + { + if (await this.ViewModel.VerificarRestricao(64, false, true)) + { + this.ViewModel.ShowDrawer(new ConfiguracoesDrawer(), 0, false); + } + } + + private void ContentLoad() + { + this.EmpresaGrid.SelectedIndex = 0; + this.EmpresaGrid.SelectionChanged += new SelectionChangedEventHandler(this.EmpresaGrid_OnSelectionChanged); + this.EmpresaGrid.MouseDoubleClick += new MouseButtonEventHandler((object sender, MouseButtonEventArgs args) => { + }); + if (Recursos.Usuario.get_Id() == 0) + { + this.Alterar.IsEnabled = true; + } + } + + private void DocumentoPrincipalBox_LostFocus(object sender, RoutedEventArgs e) + { + if (((TextBox)sender).IsReadOnly) + { + return; + } + string str = this.DocumentoPrincipalBox.Text.Clear(); + if (string.IsNullOrEmpty(str)) + { + return; + } + this.DocumentoPrincipalBox.Text = (str.Length == 11 ? ValidationHelper.FormatDocument(str.PadLeft(11, '0').Substring(0, 11)) : ValidationHelper.FormatDocument(str.PadLeft(14, '0').Substring(0, 14))); + } + + private void EmpresaGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + DataGrid dataGrid = (DataGrid)sender; + if (dataGrid != null && dataGrid.SelectedIndex < 0) + { + return; + } + this.ViewModel.SelecionaEmpresa((Empresa)((dataGrid != null ? dataGrid.Items[dataGrid.SelectedIndex] : null))); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/ferramentas/empresaview.xaml", UriKind.Relative)); + } + + public void PermissaoAuteracao() + { + if (Recursos.Usuario.get_Id() != 0) + { + this.DocumentoPrincipalBox.IsReadOnly = true; + this.NomeBox.IsReadOnly = true; + return; + } + this.ViewModel.ConfirmacaoSenha = (this.ViewModel.SelectedEmpresa.get_Id() == (long)1 ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.ViewModel.PassWordReadOnly = true; + this.Alterar.IsEnabled = false; + this.DocumentoPrincipalBox.IsReadOnly = false; + this.NomeBox.IsReadOnly = false; + } + + private async void PostcodeBox_OnLostFocus(object sender, RoutedEventArgs e) + { + if (this.ViewModel.EnableFields) + { + string str = ValidationHelper.FormatPostCode(((TextBox)sender).Text); + this.CepBox.Text = str; + if (ValidationHelper.ValidatePostCode(str)) + { + EnderecoBase enderecoBase = await this.ViewModel.BuscaCep(str); + if (enderecoBase != null) + { + this.EnderecoBox.Text = enderecoBase.get_Endereco(); + this.CidadeBox.Text = enderecoBase.get_Cidade(); + this.EstadoBox.Text = enderecoBase.get_Estado(); + this.BairroBox.Text = enderecoBase.get_Bairro(); + } + } + } + } + + private async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + System.Windows.Visibility visibility; + bool flag; + this.ViewModel.Loading(true); + List> keyValuePairs = await this.ViewModel.Salvar(); + this.ValidateFields(keyValuePairs, true); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + this.ViewModel.PassWordReadOnly = this.ViewModel.EnableFields; + EmpresaViewModel viewModel = this.ViewModel; + visibility = (keyValuePairs == null || keyValuePairs.Count <= 0 ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible); + viewModel.ConfirmacaoSenha = visibility; + if (Recursos.Usuario.get_Id() == 0) + { + this.Alterar.IsEnabled = true; + this.NomeBox.IsReadOnly = true; + this.DocumentoPrincipalBox.IsReadOnly = true; + } + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, EmpresaView.AutoCompleteBoxEmpresa_Populating)); + ((AutoCompleteBox)target).add_TextChanged(new RoutedEventHandler(this.AutoCompleteBox_OnTextChanged)); + return; + } + case 2: + { + this.EmpresaGrid = (DataGrid)target; + return; + } + case 3: + { + this.Alterar = (MenuItem)target; + this.Alterar.Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 4: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 6: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirAquivoDigital_Click); + return; + } + case 7: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AnexarLogo_OnClick); + return; + } + case 8: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick); + return; + } + case 9: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLogEmail_OnClick); + return; + } + case 10: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Configuracoes_OnClick); + return; + } + case 11: + { + this.DocumentoPrincipalBox = (TextBox)target; + this.DocumentoPrincipalBox.LostFocus += new RoutedEventHandler(this.DocumentoPrincipalBox_LostFocus); + EmpresaView empresaView = this; + this.DocumentoPrincipalBox.PreviewTextInput += new TextCompositionEventHandler(empresaView.SomenteNumeros); + return; + } + case 12: + { + this.NomeBox = (TextBox)target; + return; + } + case 13: + { + this.CepBox = (TextBox)target; + this.CepBox.LostFocus += new RoutedEventHandler(this.PostcodeBox_OnLostFocus); + EmpresaView empresaView1 = this; + this.CepBox.PreviewTextInput += new TextCompositionEventHandler(empresaView1.SomenteNumeros); + return; + } + case 14: + { + this.EnderecoBox = (TextBox)target; + return; + } + case 15: + { + this.BairroBox = (TextBox)target; + return; + } + case 16: + { + this.CidadeBox = (TextBox)target; + return; + } + case 17: + { + this.EstadoBox = (TextBox)target; + return; + } + case 18: + { + this.SenhaBox = (CustomPasswordBox)target; + return; + } + case 19: + { + EmpresaView empresaView2 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(empresaView2.SomenteNumeros); + return; + } + case 20: + { + EmpresaView empresaView3 = this; + ((TextBox)target).LostFocus += new RoutedEventHandler(empresaView3.FormatarTelefone); + EmpresaView empresaView4 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(empresaView4.SomenteNumeros); + return; + } + case 21: + { + EmpresaView empresaView5 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(empresaView5.SomenteNumeros); + return; + } + case 22: + { + EmpresaView empresaView6 = this; + ((TextBox)target).LostFocus += new RoutedEventHandler(empresaView6.FormatarTelefone); + EmpresaView empresaView7 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(empresaView7.SomenteNumeros); + return; + } + case 23: + { + EmpresaView empresaView8 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(empresaView8.SomenteNumeros); + return; + } + case 24: + { + EmpresaView empresaView9 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(empresaView9.SomenteNumeros); + return; + } + } + this._contentLoaded = true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Ferramentas/EstipulanteView.cs b/Codemerx/Gestor.Application/Views/Ferramentas/EstipulanteView.cs new file mode 100644 index 0000000..b546879 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Ferramentas/EstipulanteView.cs @@ -0,0 +1,395 @@ +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.ViewModels.Ferramentas; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Views.Ferramentas +{ + public class EstipulanteView : BaseUserControl, IComponentConnector + { + public EstipulanteViewModel ViewModel; + + internal DataGrid EstipulanteGrid; + + internal MenuItem MaisOpcoesButton; + + internal TextBox EmpresaBox; + + internal TextBox NomeBox; + + internal TextBox DocumentoPrincipalBox; + + internal ToggleButton AtivoBox; + + internal TextBox PrimeiroPrefixo; + + internal TextBox PrimeiroTelefone; + + internal TextBox SegundoPrefixo; + + internal TextBox SegundoTelefone; + + internal TextBox EmailBox; + + internal TextBox CepBox; + + internal TextBox EnderecoBox; + + internal TextBox NumeroBox; + + internal TextBox BairroBox; + + internal TextBox CidadeBox; + + internal TextBox EstadoBox; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public EstipulanteView() + { + base.Tag = "CADASTRO DE ESTIPULANTE"; + this.ViewModel = new EstipulanteViewModel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + + private void AbrirLog_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLog(9, this.ViewModel.SelectedEstipulante.get_Id()); + } + + private void Alterar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelEstipulante = (Estipulante)this.ViewModel.SelectedEstipulante.Clone(); + this.ViewModel.Alterar(true); + this.ValidarTela(); + } + + private async void ArquivoDigital_OnClick(object sender, RoutedEventArgs e) + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 5).get_Consultar()) + { + FiltroArquivoDigital filtroArquivoDigital = new FiltroArquivoDigital(); + filtroArquivoDigital.set_Id(this.ViewModel.SelectedEstipulante.get_Id()); + filtroArquivoDigital.set_Tipo(17); + filtroArquivoDigital.set_Parente(this.ViewModel.SelectedEstipulante); + this.ViewModel.ShowDrawer(new ArquivoDigitalDrawer(filtroArquivoDigital), 0, false); + } + else + { + await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", ValidationHelper.GetDescription((TipoArquivoDigital)17), "."), "OK", "", false); + } + } + + private void AutoCompleteBox_OnTextChanged(object sender, RoutedEventArgs e) + { + if (!string.IsNullOrWhiteSpace(((AutoCompleteBox)sender).get_Text())) + { + return; + } + this.ViewModel.FiltrarEstipulante(""); + } + + private void AutoCompleteBoxEstipulante_Populating(object sender, PopulatingEventArgs e) + { + e.set_Cancel(true); + this.ViewModel.Filtrar(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelarAlteracao(); + } + + private void ContentLoad() + { + this.EstipulanteGrid.SelectedIndex = 0; + this.EstipulanteGrid.SelectionChanged += new SelectionChangedEventHandler(this.EstipulanteGrid_OnSelectionChanged); + this.EstipulanteGrid.MouseDoubleClick += new MouseButtonEventHandler((object sender, MouseButtonEventArgs args) => { + }); + } + + private void DocumentoPrincipalBox_LostFocus(object sender, RoutedEventArgs e) + { + if (((TextBox)sender).IsReadOnly) + { + return; + } + string str = ValidationHelper.Clear(this.DocumentoPrincipalBox.Text); + if (string.IsNullOrEmpty(str)) + { + return; + } + this.DocumentoPrincipalBox.Text = (str.Length == 11 ? ValidationHelper.FormatDocument(str.PadLeft(11, '0').Substring(0, 11)) : ValidationHelper.FormatDocument(str.PadLeft(14, '0').Substring(0, 14))); + } + + private void EstipulanteGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + DataGrid dataGrid = (DataGrid)sender; + if (dataGrid != null && dataGrid.SelectedIndex < 0) + { + return; + } + this.ViewModel.SelecionaEstipulante((Estipulante)((dataGrid != null ? dataGrid.Items[dataGrid.SelectedIndex] : null))); + } + + private void Excluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Excluir(); + } + + private void Incluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Incluir(); + this.ValidarTela(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/ferramentas/estipulanteview.xaml", UriKind.Relative)); + } + + private async void PostcodeBox_OnLostFocus(object sender, RoutedEventArgs e) + { + string str = ValidationHelper.FormatPostCode(((TextBox)sender).Text); + this.CepBox.Text = str; + if (ValidationHelper.ValidatePostCode(str)) + { + EnderecoBase enderecoBase = await this.ViewModel.BuscaCep(str); + if (enderecoBase != null) + { + this.EnderecoBox.Text = enderecoBase.get_Endereco(); + this.CidadeBox.Text = enderecoBase.get_Cidade(); + this.EstadoBox.Text = enderecoBase.get_Estado(); + this.BairroBox.Text = enderecoBase.get_Bairro(); + } + } + } + + private async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.Loading(true); + List> keyValuePairs = await this.ViewModel.Salvar(); + this.ValidateFields(keyValuePairs, true); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, EstipulanteView.AutoCompleteBoxEstipulante_Populating)); + ((AutoCompleteBox)target).add_TextChanged(new RoutedEventHandler(this.AutoCompleteBox_OnTextChanged)); + return; + } + case 2: + { + this.EstipulanteGrid = (DataGrid)target; + return; + } + case 3: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + case 4: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 6: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 7: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Excluir_OnClick); + return; + } + case 8: + { + this.MaisOpcoesButton = (MenuItem)target; + return; + } + case 9: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick); + return; + } + case 10: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.ArquivoDigital_OnClick); + return; + } + case 11: + { + this.EmpresaBox = (TextBox)target; + return; + } + case 12: + { + this.NomeBox = (TextBox)target; + return; + } + case 13: + { + this.DocumentoPrincipalBox = (TextBox)target; + EstipulanteView estipulanteView = this; + this.DocumentoPrincipalBox.PreviewTextInput += new TextCompositionEventHandler(estipulanteView.SomenteNumeros); + this.DocumentoPrincipalBox.LostFocus += new RoutedEventHandler(this.DocumentoPrincipalBox_LostFocus); + return; + } + case 14: + { + this.AtivoBox = (ToggleButton)target; + return; + } + case 15: + { + this.PrimeiroPrefixo = (TextBox)target; + EstipulanteView estipulanteView1 = this; + this.PrimeiroPrefixo.PreviewTextInput += new TextCompositionEventHandler(estipulanteView1.SomenteNumeros); + return; + } + case 16: + { + this.PrimeiroTelefone = (TextBox)target; + EstipulanteView estipulanteView2 = this; + this.PrimeiroTelefone.LostFocus += new RoutedEventHandler(estipulanteView2.FormatarTelefone); + EstipulanteView estipulanteView3 = this; + this.PrimeiroTelefone.PreviewTextInput += new TextCompositionEventHandler(estipulanteView3.SomenteNumeros); + return; + } + case 17: + { + this.SegundoPrefixo = (TextBox)target; + EstipulanteView estipulanteView4 = this; + this.SegundoPrefixo.PreviewTextInput += new TextCompositionEventHandler(estipulanteView4.SomenteNumeros); + return; + } + case 18: + { + this.SegundoTelefone = (TextBox)target; + EstipulanteView estipulanteView5 = this; + this.SegundoTelefone.LostFocus += new RoutedEventHandler(estipulanteView5.FormatarTelefone); + EstipulanteView estipulanteView6 = this; + this.SegundoTelefone.PreviewTextInput += new TextCompositionEventHandler(estipulanteView6.SomenteNumeros); + return; + } + case 19: + { + this.EmailBox = (TextBox)target; + return; + } + case 20: + { + this.CepBox = (TextBox)target; + this.CepBox.LostFocus += new RoutedEventHandler(this.PostcodeBox_OnLostFocus); + EstipulanteView estipulanteView7 = this; + this.CepBox.PreviewTextInput += new TextCompositionEventHandler(estipulanteView7.SomenteNumeros); + return; + } + case 21: + { + this.EnderecoBox = (TextBox)target; + return; + } + case 22: + { + this.NumeroBox = (TextBox)target; + return; + } + case 23: + { + this.BairroBox = (TextBox)target; + return; + } + case 24: + { + this.CidadeBox = (TextBox)target; + return; + } + case 25: + { + this.EstadoBox = (TextBox)target; + return; + } + } + this._contentLoaded = true; + } + + private void ValidarTela() + { + if (this.ViewModel.SelectedEstipulante == null) + { + return; + } + List> keyValuePairs = this.ViewModel.SelectedEstipulante.Validate(); + this.ValidateFields(keyValuePairs, false); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Ferramentas/EtiquetaView.cs b/Codemerx/Gestor.Application/Views/Ferramentas/EtiquetaView.cs new file mode 100644 index 0000000..985ed97 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Ferramentas/EtiquetaView.cs @@ -0,0 +1,157 @@ +using Gestor.Application.ViewModels.Ferramentas; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Markup; + +namespace Gestor.Application.Views.Ferramentas +{ + public class EtiquetaView : BaseUserControl, IComponentConnector + { + internal EtiquetaViewModel ViewModel; + + internal System.Windows.Controls.AutoCompleteBox AutoCompleteBox; + + internal ProgressBar ProgressRing; + + internal System.Windows.Controls.DataGrid DataGrid; + + internal Grid Botoes; + + internal ComboBox CboTipoEtiqueta; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public EtiquetaView(List list, bool apenasCliente) + { + this.ViewModel = new EtiquetaViewModel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + this.CboTipoEtiqueta.IsEnabled = !apenasCliente; + this.CarregarClientes(list, apenasCliente); + } + + private void AutoCompleteBox_OnTextChanged(object sender, RoutedEventArgs e) + { + if (!string.IsNullOrWhiteSpace(((System.Windows.Controls.AutoCompleteBox)sender).get_Text())) + { + return; + } + this.ViewModel.FiltrarApolice(""); + } + + private void AutoCompleteBox_Populating(object sender, PopulatingEventArgs e) + { + if (e.get_Parameter().Length < 3) + { + return; + } + e.set_Cancel(true); + this.ViewModel.Filtrar(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + System.Windows.Controls.AutoCompleteBox autoCompleteBox = (System.Windows.Controls.AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private async void CarregarClientes(List list, bool apenasCliente) + { + this.ProgressRing.Visibility = System.Windows.Visibility.Visible; + this.DataGrid.Visibility = System.Windows.Visibility.Collapsed; + this.Botoes.IsEnabled = false; + this.AutoCompleteBox.IsEnabled = false; + await this.ViewModel.CarregarDados(list, apenasCliente); + this.ProgressRing.Visibility = System.Windows.Visibility.Collapsed; + this.DataGrid.Visibility = System.Windows.Visibility.Visible; + this.Botoes.IsEnabled = true; + this.AutoCompleteBox.IsEnabled = true; + } + + private void Emitir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.EmitirEtiquetas(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/ferramentas/etiquetaview.xaml", UriKind.Relative)); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.AutoCompleteBox = (System.Windows.Controls.AutoCompleteBox)target; + this.AutoCompleteBox.add_Populating(new PopulatingEventHandler(this, EtiquetaView.AutoCompleteBox_Populating)); + this.AutoCompleteBox.add_TextChanged(new RoutedEventHandler(this.AutoCompleteBox_OnTextChanged)); + return; + } + case 2: + { + this.ProgressRing = (ProgressBar)target; + return; + } + case 3: + { + this.DataGrid = (System.Windows.Controls.DataGrid)target; + return; + } + case 4: + { + this.Botoes = (Grid)target; + return; + } + case 5: + { + EtiquetaView etiquetaView = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(etiquetaView.SomenteNumeros); + return; + } + case 6: + { + this.CboTipoEtiqueta = (ComboBox)target; + return; + } + case 7: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Emitir_OnClick); + return; + } + } + this._contentLoaded = true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Ferramentas/IncluirRamoView.cs b/Codemerx/Gestor.Application/Views/Ferramentas/IncluirRamoView.cs new file mode 100644 index 0000000..c9c8d4b --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Ferramentas/IncluirRamoView.cs @@ -0,0 +1,133 @@ +using Gestor.Application.Actions; +using Gestor.Application.ViewModels.Ferramentas; +using Gestor.Application.Views.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Views.Ferramentas +{ + public class IncluirRamoView : BaseUserControl, IComponentConnector + { + public IncluirRamoViewModel ViewModel; + + internal DataGrid RamoGrid; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public IncluirRamoView(List ramos) + { + this.ViewModel = new IncluirRamoViewModel(ramos); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + + private void ContentLoad() + { + this.RamoGrid.SelectionChanged += new SelectionChangedEventHandler(this.RamoGrid_OnSelectionChanged); + } + + private void Incluir_OnClick(object sender, RoutedEventArgs e) + { + if (this.ViewModel.SelectedRamo == null) + { + return; + } + this.ViewModel.AdicionarRamo = this.ViewModel.SelectedRamo; + Action closeHoster = Gestor.Application.Actions.Actions.CloseHoster; + if (closeHoster == null) + { + return; + } + closeHoster(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/ferramentas/incluirramoview.xaml", UriKind.Relative)); + } + + private void Pesquisar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Pesquisar(); + } + + private void Pesquisar_OnPreviewKeyDown(object sender, KeyEventArgs e) + { + if (e.Key == Key.Return) + { + this.ViewModel.Pesquisar(); + } + } + + private void RamoGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + DataGrid dataGrid = (DataGrid)sender; + if (dataGrid != null && dataGrid.SelectedIndex < 0) + { + return; + } + this.ViewModel.SelectedRamo = (Ramo)((dataGrid != null ? dataGrid.Items[dataGrid.SelectedIndex] : null)); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((TextBox)target).PreviewKeyDown += new KeyEventHandler(this.Pesquisar_OnPreviewKeyDown); + return; + } + case 2: + { + ((Button)target).Click += new RoutedEventHandler(this.Pesquisar_OnClick); + return; + } + case 3: + { + this.RamoGrid = (DataGrid)target; + return; + } + case 4: + { + ((Button)target).Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + } + this._contentLoaded = true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Ferramentas/IncluirSeguradoraView.cs b/Codemerx/Gestor.Application/Views/Ferramentas/IncluirSeguradoraView.cs new file mode 100644 index 0000000..e76969b --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Ferramentas/IncluirSeguradoraView.cs @@ -0,0 +1,133 @@ +using Gestor.Application.Actions; +using Gestor.Application.ViewModels.Ferramentas; +using Gestor.Application.Views.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Views.Ferramentas +{ + public class IncluirSeguradoraView : BaseUserControl, IComponentConnector + { + public IncluirSeguradoraViewModel ViewModel; + + internal DataGrid SeguradoraGrid; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public IncluirSeguradoraView(List seguradoras) + { + this.ViewModel = new IncluirSeguradoraViewModel(seguradoras); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + + private void ContentLoad() + { + this.SeguradoraGrid.SelectionChanged += new SelectionChangedEventHandler(this.SeguradoraGrid_OnSelectionChanged); + } + + private void Incluir_OnClick(object sender, RoutedEventArgs e) + { + if (this.ViewModel.SelectedSeguradora == null) + { + return; + } + this.ViewModel.AdicionarSeguradora = this.ViewModel.SelectedSeguradora; + Action closeHoster = Gestor.Application.Actions.Actions.CloseHoster; + if (closeHoster == null) + { + return; + } + closeHoster(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/ferramentas/incluirseguradoraview.xaml", UriKind.Relative)); + } + + private void Pesquisar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Pesquisar(); + } + + private void Pesquisar_OnPreviewKeyDown(object sender, KeyEventArgs e) + { + if (e.Key == Key.Return) + { + this.ViewModel.Pesquisar(); + } + } + + private void SeguradoraGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + DataGrid dataGrid = (DataGrid)sender; + if (dataGrid != null && dataGrid.SelectedIndex < 0) + { + return; + } + this.ViewModel.SelectedSeguradora = (Seguradora)((dataGrid != null ? dataGrid.Items[dataGrid.SelectedIndex] : null)); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((TextBox)target).PreviewKeyDown += new KeyEventHandler(this.Pesquisar_OnPreviewKeyDown); + return; + } + case 2: + { + ((Button)target).Click += new RoutedEventHandler(this.Pesquisar_OnClick); + return; + } + case 3: + { + this.SeguradoraGrid = (DataGrid)target; + return; + } + case 4: + { + ((Button)target).Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + } + this._contentLoaded = true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Ferramentas/MalaDiretaView.cs b/Codemerx/Gestor.Application/Views/Ferramentas/MalaDiretaView.cs new file mode 100644 index 0000000..1bb9312 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Ferramentas/MalaDiretaView.cs @@ -0,0 +1,301 @@ +using Gestor.Application.Componentes; +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels.Ferramentas; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.MalaDireta; +using MaterialDesignThemes.Wpf; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Markup; +using Xceed.Wpf.AvalonDock.Controls; + +namespace Gestor.Application.Views.Ferramentas +{ + public class MalaDiretaView : BaseUserControl, IComponentConnector, IStyleConnector + { + internal MalaDiretaViewModel ViewModel; + + internal DataGrid Grid; + + internal TextBox AssuntoBox; + + internal Gestor.Application.Componentes.WebEditor WebEditor; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public MalaDiretaView(List maladireta, string assunto = null, string corpo = null, FiltroArquivoDigital filtro = null) + { + this.ViewModel = new MalaDiretaViewModel(filtro); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + this.CarregarClientes(maladireta, assunto, corpo); + } + + private async void AdicionarCC_OnClick(object sender, RoutedEventArgs e) + { + Button button = (Button)sender; + if (button.DataContext != null) + { + this.WebEditor.Visibility = System.Windows.Visibility.Collapsed; + Copia copium = await this.ViewModel.ShowCopiaDialog(((MalaDireta)button.DataContext).get_Copia()); + this.WebEditor.Visibility = System.Windows.Visibility.Visible; + if (copium != null) + { + ((MalaDireta)button.DataContext).set_Copia(copium); + } + } + button = null; + } + + private void Alterar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Alterar(true); + } + + private void AnexarArquivos_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Anexar(); + } + + private void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelarAlteracao(); + } + + private async void CarregarClientes(List maladireta, string assunto = null, string corpo = null) + { + this.ViewModel.IsEnabled = false; + await this.ViewModel.CarregarEmails(maladireta, assunto, corpo); + this.ViewModel.IsEnabled = true; + } + + private void CheckBox_Checked(object sender, RoutedEventArgs e) + { + this.ViewModel.Selecionar(); + } + + private void DeleteArquivo_OnDeleteClick(object sender, RoutedEventArgs e) + { + Chip chip = sender as Chip; + if (chip == null) + { + return; + } + ListBox listBox = Extentions.FindVisualAncestor(chip); + Gestor.Model.Domain.Common.ArquivoDigital item = (Gestor.Model.Domain.Common.ArquivoDigital)listBox.Items[listBox.Items.IndexOf(chip.DataContext)]; + if (item == null) + { + return; + } + this.ViewModel.Delete(item); + } + + private async void Enviar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.IsEnabled = false; + this.ViewModel.Corpo = this.WebEditor.GetHtml(); + await this.ViewModel.Enviar(); + this.ViewModel.IsEnabled = true; + } + + private void Excluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Excluir(); + } + + private void Fechar_OnClick(object sender, RoutedEventArgs e) + { + Funcoes.Destroy("ENVIO DE E-MAIL"); + } + + private void Incluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Incluir(); + this.AssuntoBox.Focus(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/ferramentas/maladiretaview.xaml", UriKind.Relative)); + } + + private void ModelosBox_SelectionChanged(object sender, SelectionChangedEventArgs e) + { + ComboBox comboBox = (ComboBox)sender; + if (comboBox.SelectedItem == null) + { + return; + } + ModeloMalaDireta modeloMalaDireta = ((ComboModelo)comboBox.SelectedItem).ModeloMalaDireta; + if (modeloMalaDireta.get_Id() == 0) + { + return; + } + this.ViewModel.Corpo = modeloMalaDireta.get_Corpo(); + this.ViewModel.Assunto = modeloMalaDireta.get_Assunto(); + } + + private async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.Loading(true); + this.ViewModel.Corpo = this.WebEditor.GetHtml(); + List> keyValuePairs = await this.ViewModel.Salvar(); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.Grid = (DataGrid)target; + return; + } + case 2: + case 3: + case 12: + { + this._contentLoaded = true; + return; + } + case 4: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 6: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 7: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 8: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Excluir_OnClick); + return; + } + case 9: + { + ((ComboBox)target).SelectionChanged += new SelectionChangedEventHandler(this.ModelosBox_SelectionChanged); + return; + } + case 10: + { + this.AssuntoBox = (TextBox)target; + return; + } + case 11: + { + ((ComboBox)target).SelectionChanged += new SelectionChangedEventHandler(this.VariaveisBox_SelectionChanged); + return; + } + case 13: + { + this.WebEditor = (Gestor.Application.Componentes.WebEditor)target; + return; + } + case 14: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AnexarArquivos_OnClick); + return; + } + case 15: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Enviar_OnClick); + return; + } + case 16: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Fechar_OnClick); + return; + } + default: + { + this._contentLoaded = true; + return; + } + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + if (connectionId == 2) + { + ((CheckBox)target).Checked += new RoutedEventHandler(this.CheckBox_Checked); + ((CheckBox)target).Unchecked += new RoutedEventHandler(this.CheckBox_Checked); + return; + } + if (connectionId == 3) + { + ((Button)target).Click += new RoutedEventHandler(this.AdicionarCC_OnClick); + return; + } + if (connectionId != 12) + { + return; + } + ((Chip)target).add_DeleteClick(new RoutedEventHandler(this.DeleteArquivo_OnDeleteClick)); + } + + private void VariaveisBox_SelectionChanged(object sender, SelectionChangedEventArgs e) + { + ComboBox comboBox = (ComboBox)sender; + if (comboBox.SelectedItem == null) + { + return; + } + VariaveisMalaDireta variaveisMalaDireta = ((ComboVariavel)comboBox.SelectedItem).VariaveisMalaDireta; + this.WebEditor.InsertText(string.Concat(ValidationHelper.GetEntity(variaveisMalaDireta), " ")); + comboBox.SelectedItem = null; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Ferramentas/ManutencaoPagamentosView.cs b/Codemerx/Gestor.Application/Views/Ferramentas/ManutencaoPagamentosView.cs new file mode 100644 index 0000000..f57ac7c --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Ferramentas/ManutencaoPagamentosView.cs @@ -0,0 +1,252 @@ +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels.Ferramentas; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Application.Views.Seguros; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using MaterialDesignThemes.Wpf; +using System; +using System.CodeDom.Compiler; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Markup; +using Xceed.Wpf.AvalonDock.Controls; + +namespace Gestor.Application.Views.Ferramentas +{ + public class ManutencaoPagamentosView : BaseUserControl, IComponentConnector, IStyleConnector + { + private bool _contentLoaded; + + public ManutencaoPagamentosViewModel ViewModel + { + get; + set; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public ManutencaoPagamentosView() + { + base.Tag = "MANUTENÇÃO DE PAGAMENTOS"; + this.ViewModel = new ManutencaoPagamentosViewModel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + } + + private void AdicionarFiltro_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AdcionarFiltroPersonalizado(); + } + + private async void Apolice_OnClick(object sender, RoutedEventArgs e) + { + ManutencaoPagamentos dataContext = (ManutencaoPagamentos)((Button)sender).DataContext; + if (dataContext != null) + { + this.ViewModel.Loading(true); + long idDocumento = dataContext.get_IdDocumento(); + Documento documento = await (new ApoliceServico()).BuscarApoliceAsync(idDocumento, false, false); + if (documento != null) + { + double? nullable = null; + double? nullable1 = nullable; + nullable = null; + (new HosterWindow(new ApoliceView(documento, true, false, 1, dataContext.get_IdParcela(), false), string.Concat("CADASTRO DE APÓLICES - ", documento.get_Controle().get_Cliente().get_Nome()), nullable1, nullable, false)).Show(); + this.ViewModel.Loading(false); + } + else + { + this.ViewModel.Loading(false); + } + } + dataContext = null; + } + + private async void Buscar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Loading(true); + await this.ViewModel.Buscar(); + this.ViewModel.Loading(false); + } + + private void CheckBox_Checked(object sender, RoutedEventArgs e) + { + this.ViewModel.Selecionar(true); + } + + private async void Excluir_OnClick(object sender, RoutedEventArgs e) + { + if (this.ViewModel.Pagamentos != null) + { + ObservableCollection pagamentos = this.ViewModel.Pagamentos; + if (!pagamentos.All((ManutencaoPagamentos x) => !x.get_Selecionado())) + { + bool? nullable = await this.ViewModel.ShowSenha("DESEJA REALMENTE EXCLUIR OS PAGAMENTOS SELECIONADOS?\nESSE PROCEDIMENTO É IRREVERSÍVEL."); + if (!nullable.HasValue) + { + return; + } + else if (!nullable.GetValueOrDefault()) + { + await this.ViewModel.ShowMessage("SENHA INVÁLIDA", "OK", "", false); + return; + } + else + { + this.ViewModel.Loading(true); + await this.ViewModel.Excluir(); + this.ViewModel.Loading(false); + return; + } + } + } + await this.ViewModel.ShowMessage("NECESSÁRIO SELECIONAR OS PAGAMENTOS QUE DESEJA EXCLUIR ANTES DE PROSSEGUIR", "OK", "", false); + } + + private void ExcluirFiltro_OnClick(object sender, RoutedEventArgs e) + { + Chip chip = sender as Chip; + if (chip == null) + { + return; + } + ListBox listBox = Extentions.FindVisualAncestor(chip); + FiltroPersonalizado item = (FiltroPersonalizado)listBox.Items[listBox.Items.IndexOf(chip.DataContext)]; + if (item == null) + { + return; + } + this.ViewModel.FiltroPersonalizadoSelecionado.Remove(item); + this.ViewModel.PesquisaPersonalizada(); + } + + private void FecharFiltro_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.VisibilityFiltroPersonalizado = (this.ViewModel.VisibilityFiltroPersonalizado == System.Windows.Visibility.Collapsed ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/ferramentas/manutencaopagamentosview.xaml", UriKind.Relative)); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 2: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 3: + { + ((Button)target).Click += new RoutedEventHandler(this.Buscar_OnClick); + return; + } + case 4: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Excluir_OnClick); + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.FecharFiltro_OnClick); + return; + } + case 6: + { + ((Button)target).Click += new RoutedEventHandler(this.FecharFiltro_OnClick); + return; + } + case 7: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 8: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 9: + { + ((Button)target).Click += new RoutedEventHandler(this.AdicionarFiltro_OnClick); + return; + } + } + this._contentLoaded = true; + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 10: + { + ((Chip)target).add_DeleteClick(new RoutedEventHandler(this.ExcluirFiltro_OnClick)); + return; + } + case 11: + { + ((CheckBox)target).Checked += new RoutedEventHandler(this.CheckBox_Checked); + ((CheckBox)target).Unchecked += new RoutedEventHandler(this.UnCheckBox_Checked); + return; + } + case 12: + { + ((Button)target).Click += new RoutedEventHandler(this.Apolice_OnClick); + return; + } + default: + { + return; + } + } + } + + private void UnCheckBox_Checked(object sender, RoutedEventArgs e) + { + this.ViewModel.Selecionar(false); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Ferramentas/NotaFiscalView.cs b/Codemerx/Gestor.Application/Views/Ferramentas/NotaFiscalView.cs new file mode 100644 index 0000000..a4928ce --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Ferramentas/NotaFiscalView.cs @@ -0,0 +1,327 @@ +using CurrencyTextBoxControl; +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.ViewModels.Ferramentas; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Views.Ferramentas +{ + public class NotaFiscalView : BaseUserControl, IComponentConnector + { + public NotaFiscalViewModel ViewModel; + + internal DataGrid NotaFiscalGrid; + + internal DataGridTextColumn NomeField; + + internal DataGridTextColumn ApelidoField; + + internal MenuItem MaisOpcoesButton; + + internal DatePicker DataPicker; + + internal CurrencyTextBox ValorBrutoBox; + + internal CurrencyTextBox ValorIssBox; + + internal CurrencyTextBox ValorIrBox; + + internal CurrencyTextBox ValorLiquidoBox; + + internal TextBox ExtratoBox; + + internal ComboBox EstipulanteBox; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public NotaFiscalView() + { + base.Tag = "CADASTRO DE NOTA FISCAL"; + this.ViewModel = new NotaFiscalViewModel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + + private void AbrirLog_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLog(55, this.ViewModel.SelectedNotaFiscal.get_Id()); + } + + private void Alterar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelNotaFiscal = (NotaFiscal)this.ViewModel.SelectedNotaFiscal.Clone(); + this.ViewModel.Alterar(true); + this.ViewModel.SelectedNotaFiscal.Initialize(); + } + + private async void ArquivoDigital_OnClick(object sender, RoutedEventArgs e) + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 16).get_Consultar()) + { + FiltroArquivoDigital filtroArquivoDigital = new FiltroArquivoDigital(); + filtroArquivoDigital.set_Id(this.ViewModel.SelectedNotaFiscal.get_Id()); + filtroArquivoDigital.set_Tipo(16); + filtroArquivoDigital.set_Parente(this.ViewModel.SelectedNotaFiscal); + this.ViewModel.ShowDrawer(new ArquivoDigitalDrawer(filtroArquivoDigital), 0, false); + } + else + { + await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", ValidationHelper.GetDescription((TipoArquivoDigital)16), "."), "OK", "", false); + } + } + + private void AutoCompleteBox_OnTextChanged(object sender, RoutedEventArgs e) + { + if (!string.IsNullOrWhiteSpace(((AutoCompleteBox)sender).get_Text())) + { + return; + } + this.ViewModel.FiltrarNotaFiscal(""); + } + + private void AutoCompleteBoxNotaFiscal_Populating(object sender, PopulatingEventArgs e) + { + e.set_Cancel(true); + this.ViewModel.Filtrar(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelarAlteracao(); + } + + private void ContentLoad() + { + this.NomeField.Visibility = (this.ViewModel.Apelido ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible); + this.ApelidoField.Visibility = (!this.ViewModel.Apelido ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible); + } + + private void Excluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Excluir(); + } + + private async void Importar_Click(object sender, RoutedEventArgs e) + { + this.ViewModel.IsEnabled = false; + this.ViewModel.EnableMenu = false; + this.ViewModel.EnableMainMenu = false; + List notaFiscals = await this.ViewModel.ShowExtratoComissaoDialog(this.ViewModel.Seguradoras); + if (notaFiscals != null) + { + await this.ViewModel.SalvarLote(notaFiscals); + } + this.ViewModel.EnableMainMenu = true; + this.ViewModel.EnableMenu = true; + this.ViewModel.IsEnabled = true; + } + + private void Incluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Incluir(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/ferramentas/notafiscalview.xaml", UriKind.Relative)); + } + + private async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.Loading(true); + this.DataPicker.SelectedDate = new DateTime?(Convert.ToDateTime(this.DataPicker.Text)); + List> keyValuePairs = await this.ViewModel.Salvar(); + this.ValidateFields(keyValuePairs, true); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, NotaFiscalView.AutoCompleteBoxNotaFiscal_Populating)); + ((AutoCompleteBox)target).add_TextChanged(new RoutedEventHandler(this.AutoCompleteBox_OnTextChanged)); + return; + } + case 2: + { + this.NotaFiscalGrid = (DataGrid)target; + return; + } + case 3: + { + this.NomeField = (DataGridTextColumn)target; + return; + } + case 4: + { + this.ApelidoField = (DataGridTextColumn)target; + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + case 6: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Importar_Click); + return; + } + case 7: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 8: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 9: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 10: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Excluir_OnClick); + return; + } + case 11: + { + this.MaisOpcoesButton = (MenuItem)target; + return; + } + case 12: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick); + return; + } + case 13: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.ArquivoDigital_OnClick); + return; + } + case 14: + { + this.DataPicker = (DatePicker)target; + this.DataPicker.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.DataPicker.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + this.DataPicker.PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + return; + } + case 15: + { + this.ValorBrutoBox = (CurrencyTextBox)target; + this.ValorBrutoBox.LostFocus += new RoutedEventHandler(this.UIElement_OnLostFocus); + return; + } + case 16: + { + this.ValorIssBox = (CurrencyTextBox)target; + this.ValorIssBox.LostFocus += new RoutedEventHandler(this.UIElement_OnLostFocus); + return; + } + case 17: + { + this.ValorIrBox = (CurrencyTextBox)target; + this.ValorIrBox.LostFocus += new RoutedEventHandler(this.UIElement_OnLostFocus); + return; + } + case 18: + { + this.ValorLiquidoBox = (CurrencyTextBox)target; + this.ValorLiquidoBox.LostFocus += new RoutedEventHandler(this.UIElement_OnLostFocus); + return; + } + case 19: + { + this.ExtratoBox = (TextBox)target; + return; + } + case 20: + { + this.EstipulanteBox = (ComboBox)target; + return; + } + } + this._contentLoaded = true; + } + + private async void UIElement_OnLostFocus(object sender, RoutedEventArgs e) + { + if (this.ViewModel.SelectedNotaFiscal != null && this.ViewModel.EnableFields) + { + List configuracoes = Recursos.Configuracoes; + bool flag = configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 5); + if ((((CurrencyTextBox)sender).Name == "ValorBrutoBox") & flag && this.ValorIssBox.get_Number() == decimal.Zero) + { + decimal num = await this.ViewModel.BuscarImposto(); + this.ValorIssBox.set_Number(this.ValorBrutoBox.get_Number() * num); + } + this.ValorLiquidoBox.set_Number((this.ValorBrutoBox.get_Number() - this.ValorIssBox.get_Number()) - this.ValorIrBox.get_Number()); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Ferramentas/ProdutoView.cs b/Codemerx/Gestor.Application/Views/Ferramentas/ProdutoView.cs new file mode 100644 index 0000000..8c61f17 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Ferramentas/ProdutoView.cs @@ -0,0 +1,215 @@ +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels.Ferramentas; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Views.Ferramentas +{ + public class ProdutoView : BaseUserControl, IComponentConnector + { + public ProdutoViewModel ViewModel; + + internal DataGrid ProdutoGrid; + + internal MenuItem MaisOpcoesButton; + + internal ToggleButton AtivoBox; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public ProdutoView() + { + base.Tag = "CADASTRO DE PRODUTOS"; + this.ViewModel = new ProdutoViewModel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + + private void AbrirLog_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLog(10, this.ViewModel.SelectedProduto.get_Id()); + } + + private void Alterar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelProduto = (Produto)this.ViewModel.SelectedProduto.Clone(); + this.ViewModel.Alterar(true); + this.ValidarTela(); + this.ViewModel.SelectedProduto.Initialize(); + } + + private void AutoCompleteBox_OnTextChanged(object sender, RoutedEventArgs e) + { + if (!string.IsNullOrWhiteSpace(((AutoCompleteBox)sender).get_Text())) + { + return; + } + this.ViewModel.FiltrarProduto(""); + } + + private void AutoCompleteBoxProduto_Populating(object sender, PopulatingEventArgs e) + { + e.set_Cancel(true); + this.ViewModel.Filtrar(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelarAlteracao(); + } + + private void ContentLoad() + { + this.ProdutoGrid.SelectedIndex = 0; + this.ProdutoGrid.SelectionChanged += new SelectionChangedEventHandler(this.EstipulanteGrid_OnSelectionChanged); + this.ProdutoGrid.MouseDoubleClick += new MouseButtonEventHandler((object sender, MouseButtonEventArgs args) => { + }); + } + + private void EstipulanteGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + DataGrid dataGrid = (DataGrid)sender; + if (dataGrid != null && dataGrid.SelectedIndex < 0) + { + return; + } + this.ViewModel.SelecionaProduto((Produto)((dataGrid != null ? dataGrid.Items[dataGrid.SelectedIndex] : null))); + } + + private void Incluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Incluir(); + this.ValidarTela(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/ferramentas/produtoview.xaml", UriKind.Relative)); + } + + private async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.Loading(true); + List> keyValuePairs = await this.ViewModel.Salvar(); + this.ValidateFields(keyValuePairs, true); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, ProdutoView.AutoCompleteBoxProduto_Populating)); + ((AutoCompleteBox)target).add_TextChanged(new RoutedEventHandler(this.AutoCompleteBox_OnTextChanged)); + return; + } + case 2: + { + this.ProdutoGrid = (DataGrid)target; + return; + } + case 3: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + case 4: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 6: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 7: + { + this.MaisOpcoesButton = (MenuItem)target; + return; + } + case 8: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick); + return; + } + case 9: + { + this.AtivoBox = (ToggleButton)target; + return; + } + } + this._contentLoaded = true; + } + + private void ValidarTela() + { + if (this.ViewModel.SelectedProduto == null) + { + return; + } + List> keyValuePairs = this.ViewModel.SelectedProduto.Validate(); + this.ValidateFields(keyValuePairs, false); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Ferramentas/ProtocoloDocumentosView.cs b/Codemerx/Gestor.Application/Views/Ferramentas/ProtocoloDocumentosView.cs new file mode 100644 index 0000000..06943cf --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Ferramentas/ProtocoloDocumentosView.cs @@ -0,0 +1,209 @@ +using Gestor.Application.ViewModels.Ferramentas; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Markup; + +namespace Gestor.Application.Views.Ferramentas +{ + public class ProtocoloDocumentosView : UserControl, IComponentConnector, IStyleConnector + { + private bool _contentLoaded; + + public ProtocoloDocumentosViewModel ViewModel + { + get; + set; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public ProtocoloDocumentosView() + { + base.Tag = "PROTOCOLOS E ETIQUETAS"; + this.ViewModel = new ProtocoloDocumentosViewModel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + } + + private void AdicionarEtiqueta_OnClick(object sender, RoutedEventArgs e) + { + Button button = sender as Button; + if (button == null) + { + return; + } + if (button.DataContext == null) + { + return; + } + this.ViewModel.AdicionarEtiqueta((Documento)button.DataContext); + } + + private void AdicionarEtiquetaCliente_OnClick(object sender, RoutedEventArgs e) + { + MenuItem menuItem = sender as MenuItem; + if (menuItem == null) + { + return; + } + if (menuItem.DataContext == null) + { + return; + } + this.ViewModel.AdicionarEtiquetaCliente(); + } + + private void AdicionarEtiquetaCorretora_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AdicionarEtiquetaCorretora(); + } + + private void AdicionarProtocolo_OnClick(object sender, RoutedEventArgs e) + { + Button button = sender as Button; + if (button == null) + { + return; + } + if (button.DataContext == null) + { + return; + } + this.ViewModel.AdicionarProtocolo((Documento)button.DataContext); + } + + private void AutoCompleteClienteBox_Populating(object sender, PopulatingEventArgs e) + { + if (e.get_Parameter().Length < 3) + { + return; + } + e.set_Cancel(true); + this.ViewModel.BuscarCliente(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim()), null, 2).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void ImprimirEtiqueta_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Imprimir(1); + } + + private void ImprimirProtocolo_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Imprimir(0); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/ferramentas/protocolodocumentosview.xaml", UriKind.Relative)); + } + + private void Remover_OnClick(object sender, RoutedEventArgs e) + { + Button button = sender as Button; + if (button == null) + { + return; + } + if (button.DataContext == null) + { + return; + } + this.ViewModel.Remover((ProtocoloEtiqueta)button.DataContext); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, ProtocoloDocumentosView.AutoCompleteClienteBox_Populating)); + return; + } + case 2: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AdicionarEtiquetaCliente_OnClick); + return; + } + case 3: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AdicionarEtiquetaCorretora_OnClick); + return; + } + case 4: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.ImprimirProtocolo_OnClick); + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.ImprimirEtiqueta_OnClick); + return; + } + } + this._contentLoaded = true; + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 6: + { + ((Button)target).Click += new RoutedEventHandler(this.AdicionarProtocolo_OnClick); + return; + } + case 7: + { + ((Button)target).Click += new RoutedEventHandler(this.AdicionarEtiqueta_OnClick); + return; + } + case 8: + { + ((Button)target).Click += new RoutedEventHandler(this.Remover_OnClick); + return; + } + default: + { + return; + } + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Ferramentas/QualificacaoView.cs b/Codemerx/Gestor.Application/Views/Ferramentas/QualificacaoView.cs new file mode 100644 index 0000000..e3a334c --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Ferramentas/QualificacaoView.cs @@ -0,0 +1,197 @@ +using CurrencyTextBoxControl; +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels.Ferramentas; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Markup; + +namespace Gestor.Application.Views.Ferramentas +{ + public class QualificacaoView : BaseUserControl, IComponentConnector + { + public QualificacaoViewModel ViewModel; + + internal MenuItem MaisOpcoesButton; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public QualificacaoView() + { + base.Tag = "CADASTRO DE QUALIFICAÇÃO"; + this.ViewModel = new QualificacaoViewModel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + } + + private void AbrirLog_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLog(48, this.ViewModel.SelectedQualificacao.get_Id()); + } + + private void Alterar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelQualificacao = (Qualificacao)this.ViewModel.SelectedQualificacao.Clone(); + this.ViewModel.Alterar(true); + this.ViewModel.SelectedQualificacao.Initialize(); + } + + private void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelarAlteracao(); + } + + private void CurrencyTextBox_OnLostFocus(object sender, RoutedEventArgs e) + { + if (this.ViewModel.SelectedQualificacao.get_Liquido2() <= this.ViewModel.SelectedQualificacao.get_Liquido1()) + { + this.ViewModel.SelectedQualificacao.set_Liquido2(this.ViewModel.SelectedQualificacao.get_Liquido1() + new decimal(1, 0, 0, false, 2)); + } + if (this.ViewModel.SelectedQualificacao.get_Liquido3() <= this.ViewModel.SelectedQualificacao.get_Liquido2()) + { + this.ViewModel.SelectedQualificacao.set_Liquido3(this.ViewModel.SelectedQualificacao.get_Liquido2() + new decimal(1, 0, 0, false, 2)); + } + if (this.ViewModel.SelectedQualificacao.get_Comissao2() <= this.ViewModel.SelectedQualificacao.get_Comissao1()) + { + this.ViewModel.SelectedQualificacao.set_Comissao2(this.ViewModel.SelectedQualificacao.get_Comissao1() + new decimal(1, 0, 0, false, 2)); + } + if (this.ViewModel.SelectedQualificacao.get_Comissao3() <= this.ViewModel.SelectedQualificacao.get_Comissao2()) + { + this.ViewModel.SelectedQualificacao.set_Comissao3(this.ViewModel.SelectedQualificacao.get_Comissao2() + new decimal(1, 0, 0, false, 2)); + } + if (this.ViewModel.SelectedQualificacao.get_Resultado2() <= this.ViewModel.SelectedQualificacao.get_Resultado1()) + { + this.ViewModel.SelectedQualificacao.set_Resultado2(this.ViewModel.SelectedQualificacao.get_Resultado1() + new decimal(1, 0, 0, false, 2)); + } + if (this.ViewModel.SelectedQualificacao.get_Resultado3() <= this.ViewModel.SelectedQualificacao.get_Resultado2()) + { + this.ViewModel.SelectedQualificacao.set_Resultado3(this.ViewModel.SelectedQualificacao.get_Resultado2() + new decimal(1, 0, 0, false, 2)); + } + this.ViewModel.SelectedQualificacao = this.ViewModel.SelectedQualificacao; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/ferramentas/qualificacaoview.xaml", UriKind.Relative)); + } + + private async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.Loading(true); + List> keyValuePairs = await this.ViewModel.Salvar(); + this.ValidateFields(keyValuePairs, true); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 2: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 3: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 4: + { + this.MaisOpcoesButton = (MenuItem)target; + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick); + return; + } + case 6: + { + ((CurrencyTextBox)target).LostFocus += new RoutedEventHandler(this.CurrencyTextBox_OnLostFocus); + return; + } + case 7: + { + ((CurrencyTextBox)target).LostFocus += new RoutedEventHandler(this.CurrencyTextBox_OnLostFocus); + return; + } + case 8: + { + ((CurrencyTextBox)target).LostFocus += new RoutedEventHandler(this.CurrencyTextBox_OnLostFocus); + return; + } + case 9: + { + ((CurrencyTextBox)target).LostFocus += new RoutedEventHandler(this.CurrencyTextBox_OnLostFocus); + return; + } + case 10: + { + ((CurrencyTextBox)target).LostFocus += new RoutedEventHandler(this.CurrencyTextBox_OnLostFocus); + return; + } + case 11: + { + ((CurrencyTextBox)target).LostFocus += new RoutedEventHandler(this.CurrencyTextBox_OnLostFocus); + return; + } + case 12: + { + ((CurrencyTextBox)target).LostFocus += new RoutedEventHandler(this.CurrencyTextBox_OnLostFocus); + return; + } + case 13: + { + ((CurrencyTextBox)target).LostFocus += new RoutedEventHandler(this.CurrencyTextBox_OnLostFocus); + return; + } + case 14: + { + ((CurrencyTextBox)target).LostFocus += new RoutedEventHandler(this.CurrencyTextBox_OnLostFocus); + return; + } + } + this._contentLoaded = true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Ferramentas/RamoView.cs b/Codemerx/Gestor.Application/Views/Ferramentas/RamoView.cs new file mode 100644 index 0000000..ee06d21 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Ferramentas/RamoView.cs @@ -0,0 +1,282 @@ +using CurrencyTextBoxControl; +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels.Ferramentas; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Views.Ferramentas +{ + public class RamoView : BaseUserControl, IComponentConnector + { + internal DataGrid RamoGrid; + + internal MenuItem MaisOpcoesButton; + + internal TextBox ApoliceBox; + + internal CurrencyTextBox IofBox; + + internal DataGrid CoberturaGrid; + + private bool _contentLoaded; + + public RamoViewModel ViewModel + { + get; + set; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public RamoView() + { + base.Tag = "RAMOS"; + this.ViewModel = new RamoViewModel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher != null) + { + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + else + { + } + this.RamoGrid.DataContext = base.DataContext; + this.CoberturaGrid.DataContext = base.DataContext; + } + + private void AbrirLog_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLog(12, this.ViewModel.SelectedRamo.get_Id()); + } + + private void Alterar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelRamo = (Ramo)this.ViewModel.SelectedRamo.Clone(); + this.ViewModel.Alterar(true); + } + + private void AutoCompleteBox_OnTextChanged(object sender, RoutedEventArgs e) + { + if (!string.IsNullOrWhiteSpace(((AutoCompleteBox)sender).get_Text())) + { + return; + } + this.ViewModel.FiltrarRamo(""); + } + + private void AutoCompleteBoxCobertura_OnTextChanged(object sender, RoutedEventArgs e) + { + if (!string.IsNullOrWhiteSpace(((AutoCompleteBox)sender).get_Text())) + { + return; + } + this.ViewModel.FiltrarCoberturaRamo(""); + } + + private void AutoCompleteBoxCobertura_Populating(object sender, PopulatingEventArgs e) + { + e.set_Cancel(true); + this.ViewModel.FiltrarCobertura(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void AutoCompleteBoxRamo_Populating(object sender, PopulatingEventArgs e) + { + e.set_Cancel(true); + this.ViewModel.Filtrar(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelarAlteracao(); + } + + private void ContentLoad() + { + this.RamoGrid.SelectedIndex = 0; + this.RamoGrid.SelectionChanged += new SelectionChangedEventHandler(this.RamoGrid_OnSelectionChanged); + this.RamoGrid.MouseDoubleClick += new MouseButtonEventHandler((object sender, MouseButtonEventArgs args) => { + }); + this.CoberturaGrid.MouseDoubleClick += new MouseButtonEventHandler((object sender, MouseButtonEventArgs args) => { + }); + } + + private async void Impostos_OnClick(object sender, RoutedEventArgs e) + { + List configuracoes = Recursos.Configuracoes; + if (configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 5)) + { + await this.ViewModel.ShowMessage("RECURSO NÃO HABILITADO, ACESSE AS CONFIGURAÇÕES DENTRO DO CADASTRO DE EMPRESAS E FILIAIS PARA HABILITAR O RECURSO.", "OK", "", false); + } + else if (await this.ViewModel.VerificarPermissao(56, false)) + { + this.ViewModel.ShowDrawer(new ImpostoDrawer(1, this.ViewModel.SelectedRamo.get_Id()), 0, false); + } + } + + private void Incluir_OnClick(object sender, RoutedEventArgs e) + { + IncluirRamoView incluirRamoView = new IncluirRamoView(this.ViewModel.Ramos); + (new HosterWindow(incluirRamoView, "INCLUIR RAMO", new double?((double)500), new double?((double)600), false)).ShowDialog(); + if (incluirRamoView.ViewModel.AdicionarRamo != null) + { + this.ViewModel.Incluir(incluirRamoView.ViewModel.AdicionarRamo); + } + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/ferramentas/ramoview.xaml", UriKind.Relative)); + } + + private void RamoGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + DataGrid dataGrid = (DataGrid)sender; + if (dataGrid != null && dataGrid.SelectedIndex < 0) + { + return; + } + this.ViewModel.SelecionaRamo((Ramo)((dataGrid != null ? dataGrid.Items[dataGrid.SelectedIndex] : null))); + } + + private async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.Loading(true); + List> keyValuePairs = await this.ViewModel.Salvar(); + this.ValidateFields(keyValuePairs, true); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, RamoView.AutoCompleteBoxRamo_Populating)); + ((AutoCompleteBox)target).add_TextChanged(new RoutedEventHandler(this.AutoCompleteBox_OnTextChanged)); + return; + } + case 2: + { + this.RamoGrid = (DataGrid)target; + return; + } + case 3: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + case 4: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 6: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 7: + { + this.MaisOpcoesButton = (MenuItem)target; + return; + } + case 8: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick); + return; + } + case 9: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Impostos_OnClick); + return; + } + case 10: + { + this.ApoliceBox = (TextBox)target; + return; + } + case 11: + { + this.IofBox = (CurrencyTextBox)target; + return; + } + case 12: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, RamoView.AutoCompleteBoxCobertura_Populating)); + ((AutoCompleteBox)target).add_TextChanged(new RoutedEventHandler(this.AutoCompleteBoxCobertura_OnTextChanged)); + return; + } + case 13: + { + this.CoberturaGrid = (DataGrid)target; + return; + } + } + this._contentLoaded = true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Ferramentas/ReciboView.cs b/Codemerx/Gestor.Application/Views/Ferramentas/ReciboView.cs new file mode 100644 index 0000000..d807ef3 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Ferramentas/ReciboView.cs @@ -0,0 +1,280 @@ +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels.Ferramentas; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Views.Ferramentas +{ + public class ReciboView : BaseUserControl, IComponentConnector + { + public ReciboViewModel ViewModel; + + internal DataGrid ReciboGrid; + + internal MenuItem MaisOpcoesButton; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public ReciboView() + { + base.Tag = "CADASTRO DE RECIBOS"; + this.ViewModel = new ReciboViewModel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + + private void AbrirLog_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLog(42, this.ViewModel.SelectedRecibo.get_Id()); + } + + private void Alterar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelRecibo = (Recibo)this.ViewModel.SelectedRecibo.Clone(); + this.ViewModel.Alterar(true); + this.ValidarTela(); + this.ViewModel.SelectedRecibo.Initialize(); + } + + private void AutoCompleteBox_OnTextChanged(object sender, RoutedEventArgs e) + { + if (!string.IsNullOrWhiteSpace(((AutoCompleteBox)sender).get_Text())) + { + return; + } + this.ViewModel.FiltrarRecibo(""); + } + + private void AutoCompleteBox_Populating(object sender, PopulatingEventArgs e) + { + if (e.get_Parameter().Trim().Length < 3) + { + return; + } + e.set_Cancel(true); + this.ViewModel.BuscarClienteEmpresa(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void AutoCompleteBoxRecibo_Populating(object sender, PopulatingEventArgs e) + { + e.set_Cancel(true); + this.ViewModel.Filtrar(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelarAlteracao(); + } + + private void ContentLoad() + { + this.ReciboGrid.SelectedIndex = 0; + this.ReciboGrid.SelectionChanged += new SelectionChangedEventHandler(this.ReciboGrid_OnSelectionChanged); + this.ReciboGrid.MouseDoubleClick += new MouseButtonEventHandler((object sender, MouseButtonEventArgs args) => { + }); + } + + private void Excluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Excluir(); + } + + private void Imprimir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Print(); + } + + private void Incluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Incluir(); + this.ValidarTela(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/ferramentas/reciboview.xaml", UriKind.Relative)); + } + + private void ReciboGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + DataGrid dataGrid = (DataGrid)sender; + if (dataGrid != null && dataGrid.SelectedIndex < 0) + { + return; + } + this.ViewModel.SelectedRecibo = (Recibo)((dataGrid != null ? dataGrid.Items[dataGrid.SelectedIndex] : null)); + } + + private async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.Loading(true); + List> keyValuePairs = await this.ViewModel.Salvar(); + this.ValidateFields(keyValuePairs, true); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + else + { + this.ReciboGrid.ScrollIntoView(this.ReciboGrid.SelectedItem); + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, ReciboView.AutoCompleteBoxRecibo_Populating)); + ((AutoCompleteBox)target).add_TextChanged(new RoutedEventHandler(this.AutoCompleteBox_OnTextChanged)); + return; + } + case 2: + { + this.ReciboGrid = (DataGrid)target; + return; + } + case 3: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + case 4: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 6: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 7: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Excluir_OnClick); + return; + } + case 8: + { + this.MaisOpcoesButton = (MenuItem)target; + return; + } + case 9: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Imprimir_OnClick); + return; + } + case 10: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick); + return; + } + case 11: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 12: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, ReciboView.AutoCompleteBox_Populating)); + return; + } + case 13: + { + ReciboView reciboView = this; + ((TextBox)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(reciboView.FormatarDocumento); + return; + } + case 14: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, ReciboView.AutoCompleteBox_Populating)); + return; + } + case 15: + { + ReciboView reciboView1 = this; + ((TextBox)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(reciboView1.FormatarDocumento); + return; + } + } + this._contentLoaded = true; + } + + private void ValidarTela() + { + if (this.ViewModel.SelectedRecibo == null) + { + return; + } + List> keyValuePairs = this.ViewModel.SelectedRecibo.Validate(); + this.ValidateFields(keyValuePairs, false); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Ferramentas/SeguradoraView.cs b/Codemerx/Gestor.Application/Views/Ferramentas/SeguradoraView.cs new file mode 100644 index 0000000..68421cd --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Ferramentas/SeguradoraView.cs @@ -0,0 +1,643 @@ +using CurrencyTextBoxControl; +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.ViewModels.Ferramentas; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Common.Helpers; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; +using Xceed.Wpf.AvalonDock.Controls; + +namespace Gestor.Application.Views.Ferramentas +{ + public class SeguradoraView : BaseUserControl, IComponentConnector, IStyleConnector + { + public SeguradoraViewModel ViewModel; + + internal DataGrid SeguradoraGrid; + + internal DataGridTextColumn NomeField; + + internal DataGridTextColumn ApelidoField; + + internal MenuItem MaisOpcoesButton; + + internal ToggleButton AtivoBox; + + internal TextBox DocumentoPrincipalBox; + + internal TextBox AssistenciaBox; + + internal TextBox SusepBox; + + internal TextBox CodigoCiaBox; + + internal TextBox LinkAppAndroidBox; + + internal TextBox LinkAppIosBox; + + internal CurrencyTextBox ToleranciaComissaoBox; + + internal CurrencyTextBox ToleranciaPremioBox; + + internal TextBox ObservacaoBox; + + internal ListBox ContatosListBox; + + internal ListBox EnderecoSeguradoraBox; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public SeguradoraView() + { + base.Tag = "CADASTRO DE SEGURADORA"; + this.Tela = 13; + this.ViewModel = new SeguradoraViewModel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + + private async void AbrirAquivoDigital_Click(object sender, RoutedEventArgs e) + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 8).get_Consultar()) + { + FiltroArquivoDigital filtroArquivoDigital = new FiltroArquivoDigital(); + filtroArquivoDigital.set_Id(this.ViewModel.SelectedSeguradora.get_Id()); + filtroArquivoDigital.set_Tipo(8); + filtroArquivoDigital.set_Parente(this.ViewModel.SelectedSeguradora); + this.ViewModel.ShowDrawer(new ArquivoDigitalDrawer(filtroArquivoDigital), 0, false); + } + else + { + await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", EnumHelper.GetDescription(8), "."), "OK", "", false); + } + } + + private void AbrirLog_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLog(13, this.ViewModel.SelectedSeguradora.get_Id()); + } + + private void AbrirLogEmail_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLogEmail(13, this.ViewModel.SelectedSeguradora.get_Id()); + } + + private void Alterar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Clonar(); + this.ViewModel.Alterar(true); + this.ValidarTela(); + } + + private void AutoCompleteBox_OnTextChanged(object sender, RoutedEventArgs e) + { + if (!string.IsNullOrWhiteSpace(((AutoCompleteBox)sender).get_Text())) + { + return; + } + this.ViewModel.FiltrarSeguradora(""); + } + + private void AutoCompleteBoxDescricao_OnTextChanged(object sender, RoutedEventArgs e) + { + if (!string.IsNullOrWhiteSpace(((AutoCompleteBox)sender).get_Text())) + { + return; + } + this.ViewModel.FiltrarDescricao(""); + } + + private void AutoCompleteBoxDescricao_Populating(object sender, PopulatingEventArgs e) + { + e.set_Cancel(true); + this.ViewModel.FiltrarConfig(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void AutoCompleteBoxSeguradora_Populating(object sender, PopulatingEventArgs e) + { + e.set_Cancel(true); + this.ViewModel.Filtrar(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelarAlteracao(); + } + + private void ContentLoad() + { + this.SeguradoraGrid.SelectedIndex = 0; + this.SeguradoraGrid.SelectionChanged += new SelectionChangedEventHandler(this.SeguradoraGrid_OnSelectionChanged); + this.SeguradoraGrid.MouseDoubleClick += new MouseButtonEventHandler((object sender, MouseButtonEventArgs args) => { + }); + this.NomeField.Visibility = (this.ViewModel.Apelido ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible); + this.ApelidoField.Visibility = (!this.ViewModel.Apelido ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible); + } + + private void DocumentoPrincipalBox_LostFocus(object sender, RoutedEventArgs e) + { + if (((TextBox)sender).IsReadOnly) + { + return; + } + string str = ValidationHelper.Clear(this.DocumentoPrincipalBox.Text); + if (string.IsNullOrEmpty(str)) + { + return; + } + this.DocumentoPrincipalBox.Text = (str.Length == 11 ? ValidationHelper.FormatDocument(str.PadLeft(11, '0').Substring(0, 11)) : ValidationHelper.FormatDocument(str.PadLeft(14, '0').Substring(0, 14))); + } + + private void ExcluirEndereco_OnClick(object sender, RoutedEventArgs e) + { + Button button = sender as Button; + if (button == null) + { + return; + } + ListBox listBox = Extentions.FindVisualAncestor(button); + SeguradoraEndereco item = (SeguradoraEndereco)listBox.Items[listBox.Items.IndexOf(button.DataContext)]; + this.ViewModel.ExcluirEndereco(item); + } + + private void ExcluirTelefone_OnClick(object sender, RoutedEventArgs e) + { + Button button = sender as Button; + if (button == null) + { + return; + } + ListBox listBox = Extentions.FindVisualAncestor(button); + SeguradoraContato item = (SeguradoraContato)listBox.Items[listBox.Items.IndexOf(button.DataContext)]; + this.ViewModel.ExcluirTelefone(item); + } + + private async void Impostos_OnClick(object sender, RoutedEventArgs e) + { + List configuracoes = Recursos.Configuracoes; + if (configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 5)) + { + await this.ViewModel.ShowMessage("RECURSO NÃO HABILITADO, ACESSE AS CONFIGURAÇÕES DENTRO DO CADASTRO DE EMPRESAS E FILIAIS PARA HABILITAR O RECURSO.", "OK", "", false); + } + else if (await this.ViewModel.VerificarPermissao(56, false)) + { + this.ViewModel.ShowDrawer(new ImpostoDrawer(0, this.ViewModel.SelectedSeguradora.get_Id()), 0, false); + } + } + + private void Incluir_OnClick(object sender, RoutedEventArgs e) + { + IncluirSeguradoraView incluirSeguradoraView = new IncluirSeguradoraView(this.ViewModel.Seguradoras); + (new HosterWindow(incluirSeguradoraView, "INCLUIR SEGURADORA", new double?((double)500), new double?((double)600), false)).ShowDialog(); + if (incluirSeguradoraView.ViewModel.AdicionarSeguradora != null) + { + this.ViewModel.Incluir(incluirSeguradoraView.ViewModel.AdicionarSeguradora); + } + } + + private void IncluirEndereco_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.IncluirEndereco(); + this.ValidarTela(); + } + + private void IncluirTelefone_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.IncluirTelefone(); + this.ValidarTela(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/ferramentas/seguradoraview.xaml", UriKind.Relative)); + } + + public async void Metas_Click(object sender, RoutedEventArgs e) + { + this.ViewModel.Loading(true); + if (await this.ViewModel.VerificarPermissao(31, false)) + { + this.ViewModel.ShowDrawer(new MetaSeguradoraView(this.ViewModel.SelectedSeguradora), 0, false); + this.ViewModel.Loading(false); + } + } + + private async void PostcodeBox_OnLostFocus(object sender, RoutedEventArgs e) + { + ContentPresenter contentPresenter; + DataTemplate contentTemplate; + TextBox textBox = (TextBox)sender; + string str = ValidationHelper.FormatPostCode(textBox.Text); + if (ValidationHelper.ValidatePostCode(str)) + { + ListBox listBox = Extentions.FindVisualAncestor(textBox); + ListBoxItem listBoxItem = (ListBoxItem)listBox.ItemContainerGenerator.ContainerFromIndex(listBox.Items.IndexOf(textBox.DataContext)); + contentPresenter = FindVisualChild.Find(listBoxItem); + contentTemplate = contentPresenter.ContentTemplate; + ((TextBox)contentTemplate.FindName("CepBox", contentPresenter)).Text = str; + EnderecoBase enderecoBase = await this.ViewModel.BuscaCep(str); + if (enderecoBase != null) + { + TextBox endereco = (TextBox)contentTemplate.FindName("EnderecoBox", contentPresenter); + TextBox cidade = (TextBox)contentTemplate.FindName("CidadeBox", contentPresenter); + TextBox estado = (TextBox)contentTemplate.FindName("EstadoBox", contentPresenter); + TextBox bairro = (TextBox)contentTemplate.FindName("BairroBox", contentPresenter); + endereco.Text = enderecoBase.get_Endereco(); + cidade.Text = enderecoBase.get_Cidade(); + estado.Text = enderecoBase.get_Estado(); + bairro.Text = enderecoBase.get_Bairro(); + } + } + contentPresenter = null; + contentTemplate = null; + } + + private async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.Loading(true); + this.ViewModel.SelectedSeguradora.set_NomeSocial(this.ViewModel.SelectedSeguradora.get_NomeSocialBanco().Trim()); + if ((this.ToleranciaComissaoBox.get_Number() > new decimal(2) || this.ToleranciaPremioBox.get_Number() > new decimal(2)) && (this.ViewModel.Tolerancia != this.ToleranciaComissaoBox.get_Number() || this.ViewModel.Tolerancia != this.ToleranciaPremioBox.get_Number())) + { + bool? nullable = await this.ViewModel.ShowSenha("TOLERÂNCIA DE COMISSÃO, DIFERENÇA IMPORTAÇÃO OU REPASSE MAIOR QUE R$2,00, PREENCHA A SENHA ADM PARA PROSSEGUIR."); + if (!nullable.HasValue) + { + this.ViewModel.Loading(false); + return; + } + else if (!nullable.GetValueOrDefault()) + { + await this.ViewModel.ShowMessage("SENHA INVÁLIDA", "OK", "", false); + this.ViewModel.Loading(false); + return; + } + } + List> keyValuePairs = await this.ViewModel.Salvar(); + this.ValidateFields(keyValuePairs, true); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + } + + private void SeguradoraGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + DataGrid dataGrid = (DataGrid)sender; + if (dataGrid != null && dataGrid.SelectedIndex < 0) + { + return; + } + this.ViewModel.SelecionaSeguradora((Seguradora)((dataGrid != null ? dataGrid.Items[dataGrid.SelectedIndex] : null))); + } + + public void Selector_ContactChanged(object sender, SelectionChangedEventArgs e) + { + this.ViewModel.TipoTelefoneVisibility = System.Windows.Visibility.Visible; + this.ViewModel.TelefoneVisibility = System.Windows.Visibility.Visible; + this.ViewModel.PrefixoVisibility = System.Windows.Visibility.Visible; + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, SeguradoraView.AutoCompleteBoxSeguradora_Populating)); + ((AutoCompleteBox)target).add_TextChanged(new RoutedEventHandler(this.AutoCompleteBox_OnTextChanged)); + return; + } + case 2: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, SeguradoraView.AutoCompleteBoxSeguradora_Populating)); + ((AutoCompleteBox)target).add_TextChanged(new RoutedEventHandler(this.AutoCompleteBox_OnTextChanged)); + return; + } + case 3: + { + this.SeguradoraGrid = (DataGrid)target; + return; + } + case 4: + { + this.NomeField = (DataGridTextColumn)target; + return; + } + case 5: + { + this.ApelidoField = (DataGridTextColumn)target; + return; + } + case 6: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + case 7: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 8: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 9: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 10: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirAquivoDigital_Click); + return; + } + case 11: + { + this.MaisOpcoesButton = (MenuItem)target; + return; + } + case 12: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Metas_Click); + return; + } + case 13: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Impostos_OnClick); + return; + } + case 14: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick); + return; + } + case 15: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLogEmail_OnClick); + return; + } + case 16: + { + this.AtivoBox = (ToggleButton)target; + return; + } + case 17: + { + this.DocumentoPrincipalBox = (TextBox)target; + SeguradoraView seguradoraView = this; + this.DocumentoPrincipalBox.PreviewTextInput += new TextCompositionEventHandler(seguradoraView.SomenteNumeros); + this.DocumentoPrincipalBox.LostFocus += new RoutedEventHandler(this.DocumentoPrincipalBox_LostFocus); + return; + } + case 18: + { + this.AssistenciaBox = (TextBox)target; + return; + } + case 19: + { + this.SusepBox = (TextBox)target; + return; + } + case 20: + { + this.CodigoCiaBox = (TextBox)target; + return; + } + case 21: + { + this.LinkAppAndroidBox = (TextBox)target; + return; + } + case 22: + { + this.LinkAppIosBox = (TextBox)target; + return; + } + case 23: + { + this.ToleranciaComissaoBox = (CurrencyTextBox)target; + return; + } + case 24: + { + this.ToleranciaPremioBox = (CurrencyTextBox)target; + return; + } + case 25: + { + this.ObservacaoBox = (TextBox)target; + return; + } + case 26: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.IncluirTelefone_OnClick); + return; + } + case 27: + { + this.ContatosListBox = (ListBox)target; + return; + } + case 28: + case 29: + case 30: + case 31: + case 34: + case 35: + case 36: + { + this._contentLoaded = true; + return; + } + case 32: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.IncluirEndereco_OnClick); + return; + } + case 33: + { + this.EnderecoSeguradoraBox = (ListBox)target; + return; + } + case 37: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, SeguradoraView.AutoCompleteBoxDescricao_Populating)); + ((AutoCompleteBox)target).add_TextChanged(new RoutedEventHandler(this.AutoCompleteBoxDescricao_OnTextChanged)); + return; + } + default: + { + this._contentLoaded = true; + return; + } + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 28: + { + ((ComboBox)target).SelectionChanged += new SelectionChangedEventHandler(this.Selector_ContactChanged); + return; + } + case 29: + { + SeguradoraView seguradoraView = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(seguradoraView.SomenteNumeros); + return; + } + case 30: + { + SeguradoraView seguradoraView1 = this; + ((TextBox)target).LostFocus += new RoutedEventHandler(seguradoraView1.FormatarTelefone); + SeguradoraView seguradoraView2 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(seguradoraView2.SomenteNumeros); + return; + } + case 31: + { + ((Button)target).Click += new RoutedEventHandler(this.ExcluirTelefone_OnClick); + return; + } + case 32: + case 33: + { + return; + } + case 34: + { + ((TextBox)target).LostFocus += new RoutedEventHandler(this.PostcodeBox_OnLostFocus); + SeguradoraView seguradoraView3 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(seguradoraView3.SomenteNumeros); + return; + } + case 35: + { + SeguradoraView seguradoraView4 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(seguradoraView4.SomenteNumeros); + return; + } + case 36: + { + ((Button)target).Click += new RoutedEventHandler(this.ExcluirEndereco_OnClick); + return; + } + default: + { + return; + } + } + } + + private void ValidarTela() + { + object keyValuePairs; + object obj; + if (this.ViewModel.SelectedSeguradora == null) + { + return; + } + List> keyValuePairs1 = this.ViewModel.SelectedSeguradora.Validate(); + List> keyValuePairs2 = keyValuePairs1; + SeguradoraContato seguradoraContato = this.ViewModel.Contatos.FirstOrDefault(); + if (seguradoraContato != null) + { + keyValuePairs = seguradoraContato.Validate(); + } + else + { + keyValuePairs = null; + } + if (keyValuePairs == null) + { + keyValuePairs = new List>(); + } + keyValuePairs2.AddRange((IEnumerable)keyValuePairs); + List> keyValuePairs3 = keyValuePairs1; + SeguradoraEndereco seguradoraEndereco = this.ViewModel.Enderecos.FirstOrDefault(); + if (seguradoraEndereco != null) + { + obj = seguradoraEndereco.Validate(); + } + else + { + obj = null; + } + if (obj == null) + { + obj = new List>(); + } + keyValuePairs3.AddRange((IEnumerable)obj); + this.ValidateFields(keyValuePairs1, false); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Ferramentas/SocioView.cs b/Codemerx/Gestor.Application/Views/Ferramentas/SocioView.cs new file mode 100644 index 0000000..08f3460 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Ferramentas/SocioView.cs @@ -0,0 +1,266 @@ +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.ViewModels.Ferramentas; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Markup; + +namespace Gestor.Application.Views.Ferramentas +{ + public class SocioView : BaseUserControl, IComponentConnector + { + internal ComboBox EmpresaFilialBox; + + internal DataGrid SocioGrid; + + internal MenuItem MaisOpcoesButton; + + internal TextBox NomeBox; + + internal TextBox PrimeiroPrefixo; + + internal TextBox PrimeiroTelefone; + + internal TextBox EmailBox; + + private bool _contentLoaded; + + public SocioViewModel ViewModel + { + get; + set; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public SocioView() + { + base.Tag = "CADASTRO DE SÓCIOS"; + this.ViewModel = new SocioViewModel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + } + + private async void AbrirAquivoDigital_Click(object sender, RoutedEventArgs e) + { + if (!(new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 14).get_Consultar()) + { + await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", ValidationHelper.GetDescription((TipoArquivoDigital)14), "."), "OK", "", false); + } + else if (this.ViewModel.SelectedSocio != null) + { + FiltroArquivoDigital filtroArquivoDigital = new FiltroArquivoDigital(); + filtroArquivoDigital.set_Id(this.ViewModel.SelectedSocio.get_Id()); + filtroArquivoDigital.set_Tipo(14); + filtroArquivoDigital.set_Parente(this.ViewModel.SelectedSocio); + this.ViewModel.ShowDrawer(new ArquivoDigitalDrawer(filtroArquivoDigital), 0, false); + } + else + { + await this.ViewModel.ShowMessage("É NECESSÁRIO SELECIONAR UM SÓCIO PARA ABRIR SEU ARQUIVO DIGITAL", "OK", "", false); + } + } + + private void AbrirLog_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLog(19, this.ViewModel.SelectedSocio.get_Id()); + } + + private void Alterar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelSocio = (Socio)this.ViewModel.SelectedSocio.Clone(); + this.ViewModel.Alterar(true); + this.ValidarTela(); + this.ViewModel.SelectedSocio.Initialize(); + } + + private void AutoCompleteBox_OnTextChanged(object sender, RoutedEventArgs e) + { + if (!string.IsNullOrWhiteSpace(((AutoCompleteBox)sender).get_Text())) + { + return; + } + this.ViewModel.FiltrarSocio(""); + } + + private void AutoCompleteBoxSocio_Populating(object sender, PopulatingEventArgs e) + { + e.set_Cancel(true); + this.ViewModel.Filtrar(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelarAlteracao(); + } + + private void Excluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Excluir(); + } + + private void Incluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Incluir(); + this.ValidarTela(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/ferramentas/socioview.xaml", UriKind.Relative)); + } + + private async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.Loading(true); + List> keyValuePairs = await this.ViewModel.Salvar(); + this.ValidateFields(keyValuePairs, true); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.EmpresaFilialBox = (ComboBox)target; + return; + } + case 2: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, SocioView.AutoCompleteBoxSocio_Populating)); + ((AutoCompleteBox)target).add_TextChanged(new RoutedEventHandler(this.AutoCompleteBox_OnTextChanged)); + return; + } + case 3: + { + this.SocioGrid = (DataGrid)target; + return; + } + case 4: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 6: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 7: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 8: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Excluir_OnClick); + return; + } + case 9: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirAquivoDigital_Click); + return; + } + case 10: + { + this.MaisOpcoesButton = (MenuItem)target; + return; + } + case 11: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick); + return; + } + case 12: + { + this.NomeBox = (TextBox)target; + return; + } + case 13: + { + this.PrimeiroPrefixo = (TextBox)target; + SocioView socioView = this; + this.PrimeiroPrefixo.PreviewTextInput += new TextCompositionEventHandler(socioView.SomenteNumeros); + return; + } + case 14: + { + this.PrimeiroTelefone = (TextBox)target; + SocioView socioView1 = this; + this.PrimeiroTelefone.LostFocus += new RoutedEventHandler(socioView1.FormatarTelefone); + SocioView socioView2 = this; + this.PrimeiroTelefone.PreviewTextInput += new TextCompositionEventHandler(socioView2.SomenteNumeros); + return; + } + case 15: + { + this.EmailBox = (TextBox)target; + return; + } + } + this._contentLoaded = true; + } + + private void ValidarTela() + { + if (this.ViewModel.SelectedSocio == null) + { + return; + } + List> keyValuePairs = this.ViewModel.SelectedSocio.Validate(); + this.ValidateFields(keyValuePairs, false); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Ferramentas/StatusProspeccaoView.cs b/Codemerx/Gestor.Application/Views/Ferramentas/StatusProspeccaoView.cs new file mode 100644 index 0000000..5fee7d6 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Ferramentas/StatusProspeccaoView.cs @@ -0,0 +1,213 @@ +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels.Ferramentas; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Markup; + +namespace Gestor.Application.Views.Ferramentas +{ + public class StatusProspeccaoView : BaseUserControl, IComponentConnector + { + public StatusProspeccaoViewModel ViewModel; + + internal DataGrid StatusProspeccaoGrid; + + internal MenuItem MaisOpcoesButton; + + internal TextBox NomeBox; + + internal ToggleButton AtivoBox; + + internal TextBox ObsBox; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public StatusProspeccaoView() + { + base.Tag = "CADASTRO DE STATUS DE PROSPECÇÃO"; + this.ViewModel = new StatusProspeccaoViewModel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + } + + private void AbrirLog_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLog(57, this.ViewModel.SelectedStatusProspeccao.get_Id()); + } + + private void Alterar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelStatusProspeccao = (StatusDeProspeccao)this.ViewModel.SelectedStatusProspeccao.Clone(); + this.ViewModel.Alterar(true); + this.ValidarTela(); + this.ViewModel.SelectedStatusProspeccao.Initialize(); + } + + private void AutoCompleteBox_OnTextChanged(object sender, RoutedEventArgs e) + { + if (!string.IsNullOrWhiteSpace(((AutoCompleteBox)sender).get_Text())) + { + return; + } + this.ViewModel.FiltrarStatusProspeccao(""); + } + + private void AutoCompleteBoxStatusProspeccao_Populating(object sender, PopulatingEventArgs e) + { + e.set_Cancel(true); + this.ViewModel.Filtrar(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelarAlteracao(); + } + + private void Excluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Excluir(); + } + + private void Incluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Incluir(); + this.ValidarTela(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/ferramentas/statusprospeccaoview.xaml", UriKind.Relative)); + } + + private async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.Loading(true); + List> keyValuePairs = await this.ViewModel.Salvar(); + this.ValidateFields(keyValuePairs, true); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, StatusProspeccaoView.AutoCompleteBoxStatusProspeccao_Populating)); + ((AutoCompleteBox)target).add_TextChanged(new RoutedEventHandler(this.AutoCompleteBox_OnTextChanged)); + return; + } + case 2: + { + this.StatusProspeccaoGrid = (DataGrid)target; + return; + } + case 3: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + case 4: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 6: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 7: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Excluir_OnClick); + return; + } + case 8: + { + this.MaisOpcoesButton = (MenuItem)target; + return; + } + case 9: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick); + return; + } + case 10: + { + this.NomeBox = (TextBox)target; + return; + } + case 11: + { + this.AtivoBox = (ToggleButton)target; + return; + } + case 12: + { + this.ObsBox = (TextBox)target; + return; + } + } + this._contentLoaded = true; + } + + private void ValidarTela() + { + if (this.ViewModel.SelectedStatusProspeccao == null) + { + return; + } + List> keyValuePairs = this.ViewModel.SelectedStatusProspeccao.Validate(); + this.ValidateFields(keyValuePairs, false); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Ferramentas/StatusView.cs b/Codemerx/Gestor.Application/Views/Ferramentas/StatusView.cs new file mode 100644 index 0000000..0d1c8fe --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Ferramentas/StatusView.cs @@ -0,0 +1,232 @@ +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels.Ferramentas; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Views.Ferramentas +{ + public class StatusView : BaseUserControl, IComponentConnector + { + public StatusViewModel ViewModel; + + internal DataGrid StatusGrid; + + internal MenuItem MaisOpcoesButton; + + internal TextBox NomeBox; + + internal ToggleButton AtivoBox; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public StatusView() + { + base.Tag = "CADASTRO DE STATUS"; + this.ViewModel = new StatusViewModel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + + private void AbrirLog_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLog(11, this.ViewModel.SelectedStatus.get_Id()); + } + + private void Alterar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelStatus = (Status)this.ViewModel.SelectedStatus.Clone(); + this.ViewModel.Alterar(true); + this.ValidarTela(); + this.ViewModel.SelectedStatus.Initialize(); + } + + private void AutoCompleteBox_OnTextChanged(object sender, RoutedEventArgs e) + { + if (!string.IsNullOrWhiteSpace(((AutoCompleteBox)sender).get_Text())) + { + return; + } + this.ViewModel.FiltrarStatus(""); + } + + private void AutoCompleteBoxStatus_Populating(object sender, PopulatingEventArgs e) + { + e.set_Cancel(true); + this.ViewModel.Filtrar(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelarAlteracao(); + } + + private void ContentLoad() + { + this.StatusGrid.SelectedIndex = 0; + this.StatusGrid.SelectionChanged += new SelectionChangedEventHandler(this.EstipulanteGrid_OnSelectionChanged); + this.StatusGrid.MouseDoubleClick += new MouseButtonEventHandler((object sender, MouseButtonEventArgs args) => { + }); + } + + private void EstipulanteGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + DataGrid dataGrid = (DataGrid)sender; + if (dataGrid != null && dataGrid.SelectedIndex < 0) + { + return; + } + this.ViewModel.SelecionaStatus((Status)((dataGrid != null ? dataGrid.Items[dataGrid.SelectedIndex] : null))); + } + + private void Excluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Excluir(); + } + + private void Incluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Incluir(); + this.ValidarTela(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/ferramentas/statusview.xaml", UriKind.Relative)); + } + + private async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.Loading(true); + List> keyValuePairs = await this.ViewModel.Salvar(); + this.ValidateFields(keyValuePairs, true); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, StatusView.AutoCompleteBoxStatus_Populating)); + ((AutoCompleteBox)target).add_TextChanged(new RoutedEventHandler(this.AutoCompleteBox_OnTextChanged)); + return; + } + case 2: + { + this.StatusGrid = (DataGrid)target; + return; + } + case 3: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + case 4: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 6: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 7: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Excluir_OnClick); + return; + } + case 8: + { + this.MaisOpcoesButton = (MenuItem)target; + return; + } + case 9: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick); + return; + } + case 10: + { + this.NomeBox = (TextBox)target; + return; + } + case 11: + { + this.AtivoBox = (ToggleButton)target; + return; + } + } + this._contentLoaded = true; + } + + private void ValidarTela() + { + if (this.ViewModel.SelectedStatus == null) + { + return; + } + List> keyValuePairs = this.ViewModel.SelectedStatus.Validate(); + this.ValidateFields(keyValuePairs, false); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Ferramentas/TipoTarefaView.cs b/Codemerx/Gestor.Application/Views/Ferramentas/TipoTarefaView.cs new file mode 100644 index 0000000..8d97ee7 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Ferramentas/TipoTarefaView.cs @@ -0,0 +1,213 @@ +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels.Ferramentas; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Markup; + +namespace Gestor.Application.Views.Ferramentas +{ + public class TipoTarefaView : BaseUserControl, IComponentConnector + { + public TipoTarefaViewModel ViewModel; + + internal DataGrid TipoTarefaGrid; + + internal MenuItem MaisOpcoesButton; + + internal TextBox NomeBox; + + internal ToggleButton AtivoBox; + + internal TextBox ObsBox; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public TipoTarefaView() + { + base.Tag = "CADASTRO DO TIPO DE TAREFA"; + this.ViewModel = new TipoTarefaViewModel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + } + + private void AbrirLog_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLog(52, this.ViewModel.SelectedTipoTarefa.get_Id()); + } + + private void Alterar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelTipoTarefa = (TipoDeTarefa)this.ViewModel.SelectedTipoTarefa.Clone(); + this.ViewModel.Alterar(true); + this.ValidarTela(); + this.ViewModel.SelectedTipoTarefa.Initialize(); + } + + private void AutoCompleteBox_OnTextChanged(object sender, RoutedEventArgs e) + { + if (!string.IsNullOrWhiteSpace(((AutoCompleteBox)sender).get_Text())) + { + return; + } + this.ViewModel.FiltrarTipoTarefa(""); + } + + private void AutoCompleteBoxTipoTarefa_Populating(object sender, PopulatingEventArgs e) + { + e.set_Cancel(true); + this.ViewModel.Filtrar(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelarAlteracao(); + } + + private void Excluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Excluir(); + } + + private void Incluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Incluir(); + this.ValidarTela(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/ferramentas/tipotarefaview.xaml", UriKind.Relative)); + } + + private async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.Loading(true); + List> keyValuePairs = await this.ViewModel.Salvar(); + this.ValidateFields(keyValuePairs, true); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, TipoTarefaView.AutoCompleteBoxTipoTarefa_Populating)); + ((AutoCompleteBox)target).add_TextChanged(new RoutedEventHandler(this.AutoCompleteBox_OnTextChanged)); + return; + } + case 2: + { + this.TipoTarefaGrid = (DataGrid)target; + return; + } + case 3: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + case 4: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 6: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 7: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Excluir_OnClick); + return; + } + case 8: + { + this.MaisOpcoesButton = (MenuItem)target; + return; + } + case 9: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick); + return; + } + case 10: + { + this.NomeBox = (TextBox)target; + return; + } + case 11: + { + this.AtivoBox = (ToggleButton)target; + return; + } + case 12: + { + this.ObsBox = (TextBox)target; + return; + } + } + this._contentLoaded = true; + } + + private void ValidarTela() + { + if (this.ViewModel.SelectedTipoTarefa == null) + { + return; + } + List> keyValuePairs = this.ViewModel.SelectedTipoTarefa.Validate(); + this.ValidateFields(keyValuePairs, false); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Ferramentas/TipoVendedorView.cs b/Codemerx/Gestor.Application/Views/Ferramentas/TipoVendedorView.cs new file mode 100644 index 0000000..a8a150b --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Ferramentas/TipoVendedorView.cs @@ -0,0 +1,225 @@ +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels.Ferramentas; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Views.Ferramentas +{ + public class TipoVendedorView : BaseUserControl, IComponentConnector + { + public TipoVendedorViewModel ViewModel; + + internal DataGrid TipoVendedorGrid; + + internal MenuItem MaisOpcoesButton; + + internal ToggleButton AtivoBox; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public TipoVendedorView() + { + base.Tag = "CADASTRO DE TIPO DE VENDEDOR"; + this.ViewModel = new TipoVendedorViewModel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + + private void AbrirLog_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLog(14, this.ViewModel.SelectedTipoVendedor.get_Id()); + } + + private void Alterar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelTipoVendedor = (TipoVendedor)this.ViewModel.SelectedTipoVendedor.Clone(); + this.ViewModel.Alterar(true); + this.ValidarTela(); + this.ViewModel.SelectedTipoVendedor.Initialize(); + } + + private void AutoCompleteBox_OnTextChanged(object sender, RoutedEventArgs e) + { + if (!string.IsNullOrWhiteSpace(((AutoCompleteBox)sender).get_Text())) + { + return; + } + this.ViewModel.FiltrarTipoVendedor(""); + } + + private void AutoCompleteBoxTipoVendedor_Populating(object sender, PopulatingEventArgs e) + { + e.set_Cancel(true); + this.ViewModel.Filtrar(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelarAlteracao(); + } + + private void ContentLoad() + { + this.TipoVendedorGrid.SelectedIndex = 0; + this.TipoVendedorGrid.SelectionChanged += new SelectionChangedEventHandler(this.TipoVendedorGrid_OnSelectionChanged); + this.TipoVendedorGrid.MouseDoubleClick += new MouseButtonEventHandler((object sender, MouseButtonEventArgs args) => { + }); + } + + private void Excluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Excluir(); + } + + private void Incluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Incluir(); + this.ValidarTela(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/ferramentas/tipovendedorview.xaml", UriKind.Relative)); + } + + private async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.Loading(true); + List> keyValuePairs = await this.ViewModel.Salvar(); + this.ValidateFields(keyValuePairs, true); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, TipoVendedorView.AutoCompleteBoxTipoVendedor_Populating)); + ((AutoCompleteBox)target).add_TextChanged(new RoutedEventHandler(this.AutoCompleteBox_OnTextChanged)); + return; + } + case 2: + { + this.TipoVendedorGrid = (DataGrid)target; + return; + } + case 3: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + case 4: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 6: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 7: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Excluir_OnClick); + return; + } + case 8: + { + this.MaisOpcoesButton = (MenuItem)target; + return; + } + case 9: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick); + return; + } + case 10: + { + this.AtivoBox = (ToggleButton)target; + return; + } + } + this._contentLoaded = true; + } + + private void TipoVendedorGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + DataGrid dataGrid = (DataGrid)sender; + if (dataGrid != null && dataGrid.SelectedIndex < 0) + { + return; + } + this.ViewModel.SelecionaTipoVendedor((TipoVendedor)((dataGrid != null ? dataGrid.Items[dataGrid.SelectedIndex] : null))); + } + + private void ValidarTela() + { + if (this.ViewModel.SelectedTipoVendedor == null) + { + return; + } + List> keyValuePairs = this.ViewModel.SelectedTipoVendedor.Validate(); + this.ValidateFields(keyValuePairs, false); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Ferramentas/UsuarioView.cs b/Codemerx/Gestor.Application/Views/Ferramentas/UsuarioView.cs new file mode 100644 index 0000000..3946e16 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Ferramentas/UsuarioView.cs @@ -0,0 +1,545 @@ +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.ViewModels.Ferramentas; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.License; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Views.Ferramentas +{ + public class UsuarioView : BaseUserControl, IComponentConnector + { + private bool _abrindoPermissao; + + private bool _firstTime = true; + + private bool _setting; + + internal DataGrid UsuarioGrid; + + internal MenuItem CancelarApoliceButton; + + internal TextBox NomeBox; + + internal TextBox CepBox; + + internal TextBox EnderecoBox; + + internal TextBox NumeroBox; + + internal TextBox BairroBox; + + internal TextBox CidadeBox; + + internal TextBox EstadoBox; + + private bool _contentLoaded; + + public UsuarioViewModel ViewModel + { + get; + set; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public UsuarioView() + { + base.Tag = "CADASTRO DE USUÁRIOS"; + this.ViewModel = new UsuarioViewModel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + + private async void AbrirAquivoDigital_Click(object sender, RoutedEventArgs e) + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 12).get_Consultar()) + { + this.ViewModel.EnableAlterar = false; + FiltroArquivoDigital filtroArquivoDigital = new FiltroArquivoDigital(); + filtroArquivoDigital.set_Id(this.ViewModel.SelectedUsuario.get_Id()); + filtroArquivoDigital.set_Tipo(12); + filtroArquivoDigital.set_Parente(this.ViewModel.SelectedUsuario); + this.ViewModel.ShowDrawer(new ArquivoDigitalDrawer(filtroArquivoDigital), 0, false); + this.ViewModel.EnableAlterar = true; + } + else + { + await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", ValidationHelper.GetDescription((TipoArquivoDigital)12), "."), "OK", "", false); + } + } + + private void AbrirLog_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLog(16, this.ViewModel.SelectedUsuario.get_Id()); + } + + private async void AbrirLogAcesso_OnClick(object sender, RoutedEventArgs e) + { + await this.ViewModel.ShowLogAcessoDialog(49, this.ViewModel.SelectedUsuario); + } + + private async void Alterar_OnClick(object sender, RoutedEventArgs e) + { + List produtos = LicenseHelper.Produtos; + if (!produtos.Any((Licenca produto) => produto.get_Produto() == 91) || !this.ViewModel.SelectedUsuario.get_Login().Contains("@")) + { + await this.ViewModel.AlterarUsuario(); + this.ViewModel.SelectedUsuario.Initialize(); + this.ViewModel.CancelUsuario = (Usuario)this.ViewModel.SelectedUsuario.Clone(); + this.ViewModel.Alterar(true); + this.ViewModel.IsExpanded = false; + this.NomeBox.Focus(); + } + else + { + await this.ViewModel.ShowMessage("ALTERAÇÃO DESSE USUARIO TEM QUE SER FEITO NO PAINEL DO AGGILIZADOR.", "OK", "", false); + } + } + + private void AutoCompleteBancoBox_Populating(object sender, PopulatingEventArgs e) + { + if (e.get_Parameter().Length < 3) + { + return; + } + e.set_Cancel(true); + this.ViewModel.BuscarBanco(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void AutoCompleteBox_OnTextChanged(object sender, RoutedEventArgs e) + { + if (!string.IsNullOrWhiteSpace(((AutoCompleteBox)sender).get_Text())) + { + return; + } + this.ViewModel.FiltrarUsuario(""); + } + + private void AutoCompleteBoxUsuario_Populating(object sender, PopulatingEventArgs e) + { + e.set_Cancel(true); + this.ViewModel.Filtrar(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private async void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Loading(true); + await this.ViewModel.CancelarAlteracao(); + this.ViewModel.Loading(false); + this.ScrollToItem(); + } + + private async void Click_VerificaAdmCentralSegurado(object sender, RoutedEventArgs e) + { + await this.ViewModel.VerificaUsuarioAdmCentralSegurado(); + } + + private async void ContentLoad() + { + this.ViewModel.Loading(true); + await this.ViewModel.Seleciona(); + this.ViewModel.Loading(false); + } + + private void CpfBox_OnLostFocus(object sender, RoutedEventArgs e) + { + TextBox textBox = (TextBox)sender; + textBox.Text = ValidationHelper.FormatDocument(textBox.Text); + } + + private async void CriarCartao_OnClick(object sender, RoutedEventArgs e) + { + List configuracoes = Recursos.Configuracoes; + bool flag = configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 30); + await this.ViewModel.CriarCartao(flag); + } + + private async void Excluir_OnClick(object sender, RoutedEventArgs e) + { + List produtos = LicenseHelper.Produtos; + if (!produtos.Any((Licenca produto) => produto.get_Produto() == 91) || !this.ViewModel.SelectedUsuario.get_Login().Contains("@")) + { + await this.ViewModel.Excluir(); + this.ScrollToItem(); + } + else + { + await this.ViewModel.ShowMessage("EXCLUSÃO DESSE USUARIO TEM QUE SER FEITO NO PAINEL DO AGGILIZADOR.", "OK", "", false); + } + } + + private void Incluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Incluir(); + List> keyValuePairs = this.ViewModel.SelectedUsuario.Validate(); + this.ValidateFields(keyValuePairs, true); + this.ViewModel.IsExpanded = false; + this.NomeBox.Focus(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/ferramentas/usuarioview.xaml", UriKind.Relative)); + } + + private async void Permissoes_OnClick(object sender, RoutedEventArgs e) + { + bool consultar; + if (!this._abrindoPermissao) + { + List permissaoUsuario = this.ViewModel.PermissaoUsuario; + PermissaoUsuario permissaoUsuario1 = permissaoUsuario.FirstOrDefault((PermissaoUsuario permissao) => permissao.get_Tela() == 43); + if (Recursos.Usuario.get_Administrador() || Recursos.Usuario.get_Id() == 0 || Recursos.Usuario.get_Nome().Contains("ACESSO AGGER") || permissaoUsuario1 == null) + { + consultar = false; + } + else + { + permissaoUsuario1.get_Consultar(); + consultar = !permissaoUsuario1.get_Consultar(); + } + bool flag = consultar; + if (flag) + { + flag = await this.ViewModel.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR PERMISSÕES.", "OK", "", false); + } + if (!flag) + { + this._abrindoPermissao = true; + await this.ViewModel.OpenPermissao(); + await Task.Delay(1000); + this._abrindoPermissao = false; + } + } + } + + private async void PostcodeBox_OnLostFocus(object sender, RoutedEventArgs e) + { + string str = ValidationHelper.FormatPostCode(((TextBox)sender).Text); + this.CepBox.Text = str; + if (ValidationHelper.ValidatePostCode(str)) + { + EnderecoBase enderecoBase = await this.ViewModel.BuscaCep(str); + if (enderecoBase != null) + { + this.EnderecoBox.Text = enderecoBase.get_Endereco(); + this.CidadeBox.Text = enderecoBase.get_Cidade(); + this.EstadoBox.Text = enderecoBase.get_Estado(); + this.BairroBox.Text = enderecoBase.get_Bairro(); + } + } + } + + private async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.Loading(true); + List> keyValuePairs = await this.ViewModel.Salvar(); + this.ValidateFields(keyValuePairs, true); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + else + { + this.ScrollToItem(); + } + } + + private void ScrollToItem() + { + if (this.UsuarioGrid.SelectedItem == null) + { + return; + } + this.UsuarioGrid.UpdateLayout(); + this.UsuarioGrid.ScrollIntoView(this.UsuarioGrid.SelectedItem); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, UsuarioView.AutoCompleteBoxUsuario_Populating)); + ((AutoCompleteBox)target).add_TextChanged(new RoutedEventHandler(this.AutoCompleteBox_OnTextChanged)); + return; + } + case 2: + { + this.UsuarioGrid = (DataGrid)target; + return; + } + case 3: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + case 4: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 6: + { + this.CancelarApoliceButton = (MenuItem)target; + this.CancelarApoliceButton.Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 7: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Excluir_OnClick); + return; + } + case 8: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Permissoes_OnClick); + return; + } + case 9: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Vinculo_OnClick); + return; + } + case 10: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.CriarCartao_OnClick); + return; + } + case 11: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick); + return; + } + case 12: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirAquivoDigital_Click); + return; + } + case 13: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLogAcesso_OnClick); + return; + } + case 14: + { + this.NomeBox = (TextBox)target; + return; + } + case 15: + { + UsuarioView usuarioView = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(usuarioView.SomenteNumeros); + ((TextBox)target).LostFocus += new RoutedEventHandler(this.CpfBox_OnLostFocus); + return; + } + case 16: + { + ((ComboBox)target).SelectionChanged += new SelectionChangedEventHandler(this.TelaInicial_OnSelectionChanged); + return; + } + case 17: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + return; + } + case 18: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + return; + } + case 19: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, UsuarioView.AutoCompleteBancoBox_Populating)); + return; + } + case 20: + { + this.CepBox = (TextBox)target; + this.CepBox.LostFocus += new RoutedEventHandler(this.PostcodeBox_OnLostFocus); + UsuarioView usuarioView1 = this; + this.CepBox.PreviewTextInput += new TextCompositionEventHandler(usuarioView1.SomenteNumeros); + return; + } + case 21: + { + this.EnderecoBox = (TextBox)target; + return; + } + case 22: + { + this.NumeroBox = (TextBox)target; + return; + } + case 23: + { + this.BairroBox = (TextBox)target; + return; + } + case 24: + { + this.CidadeBox = (TextBox)target; + return; + } + case 25: + { + this.EstadoBox = (TextBox)target; + return; + } + case 26: + { + UsuarioView usuarioView2 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(usuarioView2.SomenteNumeros); + return; + } + case 27: + { + UsuarioView usuarioView3 = this; + ((TextBox)target).LostFocus += new RoutedEventHandler(usuarioView3.FormatarTelefone); + UsuarioView usuarioView4 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(usuarioView4.SomenteNumeros); + return; + } + case 28: + { + UsuarioView usuarioView5 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(usuarioView5.SomenteNumeros); + return; + } + case 29: + { + UsuarioView usuarioView6 = this; + ((TextBox)target).LostFocus += new RoutedEventHandler(usuarioView6.FormatarTelefone); + UsuarioView usuarioView7 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(usuarioView7.SomenteNumeros); + return; + } + case 30: + { + ((ToggleButton)target).Click += new RoutedEventHandler(this.Click_VerificaAdmCentralSegurado); + return; + } + } + this._contentLoaded = true; + } + + private async void TelaInicial_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + if (!this._setting) + { + if (((ComboBox)sender).SelectedItem != null) + { + if ((TipoTelaInicial)((ComboBox)sender).SelectedItem == 1 && this.ViewModel.Restricao(47)) + { + this._setting = true; + ((ComboBox)sender).SelectedItem = (TipoTelaInicial)0; + this._setting = false; + if (!this._firstTime) + { + await this.ViewModel.ShowMessage("FAVOR DESABILITAR A RESTRIÇÃO AO PAINEL B.I. ANTES.", "OK", "", false); + } + else + { + this._firstTime = false; + return; + } + } + this._firstTime = false; + } + } + } + + private async void UsuarioGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + object obj; + if (this.ViewModel.EnableGrid) + { + DataGrid dataGrid = (DataGrid)sender; + if (dataGrid == null || dataGrid.SelectedIndex >= 0) + { + this.ViewModel.EnableGrid = false; + UsuarioViewModel viewModel = this.ViewModel; + obj = (dataGrid != null ? dataGrid.Items[dataGrid.SelectedIndex] : null); + await viewModel.SelecionaUsuario((Usuario)obj); + this.ViewModel.EnableGrid = true; + } + } + } + + private async void Vinculo_OnClick(object sender, RoutedEventArgs e) + { + await this.ViewModel.OpenVinculo(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Ferramentas/VendedorView.cs b/Codemerx/Gestor.Application/Views/Ferramentas/VendedorView.cs new file mode 100644 index 0000000..1c2d4b4 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Ferramentas/VendedorView.cs @@ -0,0 +1,927 @@ +using CurrencyTextBoxControl; +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.ViewModels.Ferramentas; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Common.Helpers; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using Xceed.Wpf.AvalonDock.Controls; + +namespace Gestor.Application.Views.Ferramentas +{ + public class VendedorView : BaseUserControl, IComponentConnector, IStyleConnector + { + public VendedorViewModel ViewModel; + + internal DataGrid VendedorGrid; + + internal MenuItem IncluirButton; + + internal MenuItem AlterarButton; + + internal MenuItem SalvarButton; + + internal MenuItem CancelarButton; + + internal MenuItem MaisOpcoesButton; + + internal TextBox EmpresaBox; + + internal TextBox IdBox; + + internal TextBox NomeBox; + + internal TextBox DocumentoPrincipalBox; + + internal AutoCompleteBox AutoCompleteBanco; + + internal TextBox AgenciaBox; + + internal ComboBox TipoBox; + + internal TextBox ContaBox; + + internal TextBox TitularBox; + + internal TextBox TitularDocBox; + + internal ComboBox TipoIncidenciaDescontoBox; + + internal ToggleButton AtivoBox; + + internal Grid GridContatos; + + private bool _contentLoaded; + + public bool UpdatingScroll + { + get; + set; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public VendedorView() + { + base.Tag = "CADASTRO DE VENDEDOR"; + this.ViewModel = new VendedorViewModel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + } + + private async void AbrirAquivoDigital_Click(object sender, RoutedEventArgs e) + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 6).get_Consultar()) + { + FiltroArquivoDigital filtroArquivoDigital = new FiltroArquivoDigital(); + filtroArquivoDigital.set_Id(this.ViewModel.SelectedVendedor.get_Id()); + filtroArquivoDigital.set_Tipo(6); + filtroArquivoDigital.set_Parente(this.ViewModel.SelectedVendedor); + this.ViewModel.ShowDrawer(new ArquivoDigitalDrawer(filtroArquivoDigital), 0, false); + } + else + { + await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", EnumHelper.GetDescription(6), "."), "OK", "", false); + } + } + + private void AbrirLog_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLog(15, this.ViewModel.SelectedVendedor.get_Id()); + } + + private void AbrirLogEmail_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLogEmail(15, this.ViewModel.SelectedVendedor.get_Id()); + } + + private void AbrirLogRepasse_OnClick(object sender, RoutedEventArgs e) + { + Button button = (Button)sender; + if (button == null || button.DataContext == null) + { + return; + } + Repasse dataContext = (Repasse)button.DataContext; + this.ViewModel.AbrirLog(54, dataContext.get_Id()); + } + + private async void Adiantamento_Click(object sender, RoutedEventArgs e) + { + if (this.ViewModel.SelectedVendedor == null || !this.ViewModel.SelectedVendedor.get_Corretora()) + { + this.ViewModel.ShowDrawer(new AdiantamentoDrawerView(this.ViewModel.SelectedVendedor), 0, false); + } + else + { + await this.ViewModel.ShowMessage("NÃO É POSSÍVEL ADICIONAR ADIANTAMENTOS PARA O VENDEDOR PRÓPRIA CORRETORA.", "OK", "", false); + } + } + + private async void Alterar_OnClick(object sender, RoutedEventArgs e) + { + bool corretora; + object obj; + Vendedor selectedVendedor = this.ViewModel.SelectedVendedor; + if (selectedVendedor != null) + { + corretora = selectedVendedor.get_Corretora(); + } + else + { + corretora = false; + } + bool flag = corretora; + if (flag) + { + if (Recursos.Usuario.get_Id() == 0) + { + this.AlterarPropriaCorretora(true); + } + else + { + await this.ViewModel.ShowMessage("NÃO É POSSÍVEL ALTERAR O VENDEDOR PRÓPRIA CORRETORA.", "OK", "", false); + return; + } + } + this.ViewModel.IsExpanded = false; + VendedorViewModel viewModel = this.ViewModel; + Vendedor vendedor = this.ViewModel.SelectedVendedor; + if (vendedor != null) + { + obj = vendedor.Clone(); + } + else + { + obj = null; + } + viewModel.CancelVendedor = (Vendedor)obj; + if (!flag) + { + this.ViewModel.Alterar(true); + } + this.ValidarTela(); + } + + public void AlterarPropriaCorretora(bool habilitar = false) + { + if (habilitar) + { + this.NomeBox.IsReadOnly = false; + this.DocumentoPrincipalBox.IsReadOnly = false; + this.AlterarButton.IsEnabled = false; + this.SalvarButton.IsEnabled = true; + this.CancelarButton.IsEnabled = true; + this.IncluirButton.IsEnabled = false; + return; + } + this.NomeBox.IsReadOnly = true; + this.DocumentoPrincipalBox.IsReadOnly = true; + this.AlterarButton.IsEnabled = true; + this.SalvarButton.IsEnabled = false; + this.CancelarButton.IsEnabled = false; + this.IncluirButton.IsEnabled = false; + } + + private async void AtivarInativarRepasse_OnClick(object sender, RoutedEventArgs e) + { + if (!this.ViewModel.SelectedVendedor.get_Corretora()) + { + Repasse dataContext = (Repasse)((Button)sender).DataContext; + if (dataContext != null) + { + this.ViewModel.Loading(true); + await this.ViewModel.AtivarInativarRepasse(dataContext); + this.ScrollVendedor(); + this.ViewModel.Loading(false); + } + } + else + { + await this.ViewModel.ShowMessage("NÃO É POSSÍVEL ALTERAR O VENDEDOR PRÓPRIA CORRETORA.", "OK", "", false); + } + } + + private async void AtivarInativarVendedor_OnClick(object sender, RoutedEventArgs e) + { + if (this.ViewModel.SelectedVendedor != null) + { + if (this.ViewModel.SelectedVendedor.get_Corretora()) + { + await this.ViewModel.ShowMessage("NÃO É POSSÍVEL ALTERAR O VENDEDOR PRÓPRIA CORRETORA.", "OK", "", false); + } + else if (!await this.BuscaVinculo(this.ViewModel.SelectedVendedor)) + { + this.ViewModel.Loading(true); + await this.ViewModel.AtivarInativarVendedor(this.ViewModel.SelectedVendedor); + this.ScrollVendedor(); + this.ViewModel.Loading(false); + } + } + } + + private void AutoCompleteBanco_OnLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) + { + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + VendedorView.SetValid(autoCompleteBox, (string.IsNullOrWhiteSpace(autoCompleteBox.get_Text()) ? true : this.ViewModel.SelectedVendedor.get_Banco() != null)); + } + + private void AutoCompleteBancoBox_Populating(object sender, PopulatingEventArgs e) + { + if (e.get_Parameter().Length < 3) + { + return; + } + e.set_Cancel(true); + this.ViewModel.BuscarBanco(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void AutoCompleteBox_OnTextChanged(object sender, RoutedEventArgs e) + { + if (!string.IsNullOrWhiteSpace(((AutoCompleteBox)sender).get_Text())) + { + return; + } + this.ViewModel.FiltrarVendedor(""); + } + + private void AutoCompleteBoxVendedor_Populating(object sender, PopulatingEventArgs e) + { + e.set_Cancel(true); + this.ViewModel.Filtrar(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private async Task BuscaVinculo(Vendedor vendedor) + { + bool flag; + if (await (new VendedorUsuarioServico()).FindVinculo(vendedor)) + { + await this.ViewModel.ShowMessage("NÃO É POSSÍVEL INATIVAR VENDEDOR QUE POSSUI VINCULO DE USUÁRIO.", "OK", "", false); + this.ViewModel.Loading(false); + flag = true; + } + else + { + flag = false; + } + return flag; + } + + public async void Button_Click(object sender, RoutedEventArgs e) + { + if (this.ViewModel.SelectedVendedor == null || !this.ViewModel.SelectedVendedor.get_Corretora()) + { + this.ViewModel.Loading(true); + if (await this.ViewModel.VerificarPermissao(30, false)) + { + this.ViewModel.ShowDrawer(new MetaVendedorView(this.ViewModel.SelectedVendedor), 0, false); + this.ViewModel.Loading(false); + } + } + else + { + await this.ViewModel.ShowMessage("NÃO É POSSÍVEL CRIAR METAS DE VENDEDOR PARA O VENDEDOR PRÓPRIA CORRETORA.", "OK", "", false); + } + } + + private void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelarAlteracao(); + this.ViewModel.IsExpanded = true; + if (Recursos.Usuario.get_Id() == 0) + { + this.AlterarPropriaCorretora(false); + } + } + + private void DocumentoPrincipalBox_LostFocus(object sender, RoutedEventArgs e) + { + if (((TextBox)sender).IsReadOnly) + { + return; + } + string str = ValidationHelper.Clear(this.DocumentoPrincipalBox.Text); + if (string.IsNullOrEmpty(str)) + { + return; + } + this.DocumentoPrincipalBox.Text = (str.Length == 11 ? ValidationHelper.FormatDocument(str.PadLeft(11, '0').Substring(0, 11)) : ValidationHelper.FormatDocument(str.PadLeft(14, '0').Substring(0, 14))); + } + + private void ExcluirTelefone_OnClick(object sender, RoutedEventArgs e) + { + Button button = sender as Button; + if (button == null) + { + return; + } + ListBox listBox = Extentions.FindVisualAncestor(button); + VendedorTelefone item = (VendedorTelefone)listBox.Items[listBox.Items.IndexOf(button.DataContext)]; + this.ViewModel.ExcluirTelefone(item); + } + + private async void ExcluirVinculo_OnClick(object sender, RoutedEventArgs e) + { + Button button = (Button)sender; + if (button != null && button.DataContext != null) + { + VinculoRepasse dataContext = (VinculoRepasse)button.DataContext; + this.ViewModel.Loading(true); + await this.ViewModel.ExcluirVinculo(dataContext); + this.ViewModel.Loading(false); + } + } + + private void FormaPagtoBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + ComboBox comboBox = (ComboBox)sender; + if (comboBox.SelectedItem == null) + { + return; + } + Grid grid = ViewHelper.FindAncestor(comboBox).FirstOrDefault(); + if (grid == null) + { + return; + } + ComboBox comboBox1 = (ComboBox)FindVisualChild.Find(grid).FindName("BasePagtoBox"); + FormaRepasse selectedItem = (FormaRepasse)comboBox.SelectedItem; + if (comboBox1 == null) + { + return; + } + comboBox1.IsEnabled = true; + switch (selectedItem) + { + case 1: + { + comboBox1.SelectedItem = null; + return; + } + case 2: + { + comboBox1.SelectedItem = (BaseRepasse)1; + return; + } + case 3: + { + comboBox1.SelectedItem = (BaseRepasse)3; + comboBox1.IsEnabled = false; + return; + } + default: + { + return; + } + } + } + + private void Incluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Incluir(); + this.AutoCompleteBanco.set_Text(""); + this.ValidarTela(); + } + + private void IncluirRepasse_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.IncluirRepasse(); + this.ValidarTela(); + } + + private void IncluirTelefone_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.IncluirTelefone(); + this.ValidarTela(); + } + + private async void IncluirVinculo_OnClick(object sender, RoutedEventArgs e) + { + bool dataContext; + List repasses; + Repasse repasse; + VinculoRepasse vinculoRepasse; + Button button = (Button)sender; + Button button1 = button; + if (button1 != null) + { + dataContext = button1.DataContext; + } + else + { + dataContext = false; + } + if (dataContext) + { + this.ViewModel.Loading(true); + repasses = await (new VendedorServico()).BuscaRepasses(); + repasse = (Repasse)button.DataContext; + VinculoRepasse vinculoRepasse1 = new VinculoRepasse(); + vinculoRepasse1.set_IdRepasse(repasse.get_Id()); + VinculoRepasse vinculoRepasse2 = vinculoRepasse1; + if (repasse.get_Ativo()) + { + vinculoRepasse = await this.ViewModel.ShowVinculoDialog(vinculoRepasse2, repasses, repasse); + if (vinculoRepasse != null) + { + List> keyValuePairs = vinculoRepasse.Validate(repasse.get_Vinculo(), repasse); + while (keyValuePairs != null && keyValuePairs.Count > 0) + { + await this.ViewModel.ShowMessage(keyValuePairs, "OS CAMPOS ABAIXO ESTÃO INVÁLIDOS.", "OK", ""); + vinculoRepasse = await this.ViewModel.ShowVinculoDialog(vinculoRepasse, repasses, repasse); + if (vinculoRepasse != null) + { + keyValuePairs = vinculoRepasse.Validate(repasse.get_Vinculo(), repasse); + } + else + { + this.ViewModel.Loading(false); + button = null; + repasses = null; + repasse = null; + vinculoRepasse = null; + return; + } + } + await this.ViewModel.SalvarVinculo(vinculoRepasse); + this.ViewModel.Loading(false); + } + else + { + this.ViewModel.Loading(false); + } + } + else + { + await this.ViewModel.ShowMessage("POR FAVOR, ATIVE O REPASSE PARA VINCULÁ-LO", "OK", "", false); + this.ViewModel.Loading(false); + } + } + button = null; + repasses = null; + repasse = null; + vinculoRepasse = null; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/ferramentas/vendedorview.xaml", UriKind.Relative)); + } + + private async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.Loading(true); + this.ViewModel.IsExpanded = true; + if (!this.ViewModel.SelectedVendedor.get_Ativo()) + { + if (await this.BuscaVinculo(this.ViewModel.SelectedVendedor)) + { + return; + } + } + List> keyValuePairs = await this.ViewModel.Salvar(); + this.ValidateFields(keyValuePairs, true); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + else + { + if (Recursos.Usuario.get_Id() == 0) + { + this.AlterarPropriaCorretora(false); + } + this.ScrollVendedor(); + } + } + + private void ScrollVendedor() + { + if (!this.UpdatingScroll && this.VendedorGrid.SelectedItem != null) + { + this.VendedorGrid.ScrollIntoView(this.VendedorGrid.SelectedItem); + } + this.UpdatingScroll = false; + } + + private static void SetValid(AutoCompleteBox autocomplete, bool valid) + { + ViewHelper.SetInvalid(autocomplete, "BANCO INVÁLIDO", valid); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, VendedorView.AutoCompleteBoxVendedor_Populating)); + ((AutoCompleteBox)target).add_TextChanged(new RoutedEventHandler(this.AutoCompleteBox_OnTextChanged)); + return; + } + case 2: + { + this.VendedorGrid = (DataGrid)target; + return; + } + case 3: + { + this.IncluirButton = (MenuItem)target; + this.IncluirButton.Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + case 4: + { + this.AlterarButton = (MenuItem)target; + this.AlterarButton.Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 5: + { + this.SalvarButton = (MenuItem)target; + this.SalvarButton.Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 6: + { + this.CancelarButton = (MenuItem)target; + this.CancelarButton.Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 7: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Adiantamento_Click); + return; + } + case 8: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Button_Click); + return; + } + case 9: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirAquivoDigital_Click); + return; + } + case 10: + { + this.MaisOpcoesButton = (MenuItem)target; + return; + } + case 11: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick); + return; + } + case 12: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLogEmail_OnClick); + return; + } + case 13: + { + this.EmpresaBox = (TextBox)target; + return; + } + case 14: + { + this.IdBox = (TextBox)target; + return; + } + case 15: + { + this.NomeBox = (TextBox)target; + return; + } + case 16: + { + this.DocumentoPrincipalBox = (TextBox)target; + VendedorView vendedorView = this; + this.DocumentoPrincipalBox.PreviewTextInput += new TextCompositionEventHandler(vendedorView.SomenteNumeros); + this.DocumentoPrincipalBox.LostFocus += new RoutedEventHandler(this.DocumentoPrincipalBox_LostFocus); + return; + } + case 17: + { + this.AutoCompleteBanco = (AutoCompleteBox)target; + this.AutoCompleteBanco.add_Populating(new PopulatingEventHandler(this, VendedorView.AutoCompleteBancoBox_Populating)); + this.AutoCompleteBanco.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.AutoCompleteBanco_OnLostKeyboardFocus); + return; + } + case 18: + { + this.AgenciaBox = (TextBox)target; + return; + } + case 19: + { + this.TipoBox = (ComboBox)target; + return; + } + case 20: + { + this.ContaBox = (TextBox)target; + return; + } + case 21: + { + this.TitularBox = (TextBox)target; + return; + } + case 22: + { + this.TitularDocBox = (TextBox)target; + VendedorView vendedorView1 = this; + this.TitularDocBox.PreviewTextInput += new TextCompositionEventHandler(vendedorView1.SomenteNumeros); + return; + } + case 23: + { + this.TipoIncidenciaDescontoBox = (ComboBox)target; + return; + } + case 24: + { + this.AtivoBox = (ToggleButton)target; + return; + } + case 25: + { + ((Button)target).Click += new RoutedEventHandler(this.AtivarInativarVendedor_OnClick); + return; + } + case 26: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.IncluirRepasse_OnClick); + return; + } + case 27: + case 28: + case 29: + case 30: + case 31: + case 32: + { + this._contentLoaded = true; + return; + } + case 33: + { + this.GridContatos = (Grid)target; + return; + } + case 34: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.IncluirTelefone_OnClick); + return; + } + default: + { + this._contentLoaded = true; + return; + } + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 27: + { + ((Button)target).Click += new RoutedEventHandler(this.IncluirVinculo_OnClick); + return; + } + case 28: + { + ((Button)target).Click += new RoutedEventHandler(this.AbrirLogRepasse_OnClick); + return; + } + case 29: + { + ((ComboBox)target).SelectionChanged += new SelectionChangedEventHandler(this.TipoBox_OnSelectionChanged); + return; + } + case 30: + { + ((ComboBox)target).SelectionChanged += new SelectionChangedEventHandler(this.FormaPagtoBox_OnSelectionChanged); + return; + } + case 31: + { + ((Button)target).Click += new RoutedEventHandler(this.AtivarInativarRepasse_OnClick); + return; + } + case 32: + { + ((Button)target).Click += new RoutedEventHandler(this.ExcluirVinculo_OnClick); + return; + } + case 33: + case 34: + { + return; + } + case 35: + { + ((Button)target).Click += new RoutedEventHandler(this.ExcluirTelefone_OnClick); + return; + } + case 36: + { + VendedorView vendedorView = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(vendedorView.SomenteNumeros); + return; + } + case 37: + { + VendedorView vendedorView1 = this; + ((TextBox)target).LostFocus += new RoutedEventHandler(vendedorView1.FormatarTelefone); + VendedorView vendedorView2 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(vendedorView2.SomenteNumeros); + return; + } + default: + { + return; + } + } + } + + private void TipoBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + ComboBox comboBox = (ComboBox)sender; + if (comboBox.SelectedItem == null) + { + return; + } + ListBoxItem listBoxItem = ViewHelper.FindAncestor(comboBox).FirstOrDefault(); + if (listBoxItem == null) + { + return; + } + ComboBox comboBox1 = (ComboBox)FindVisualChild.Find(listBoxItem).FindName("FormaPagtoBox"); + if (comboBox1 == null) + { + return; + } + CurrencyTextBox currencyTextBox = (CurrencyTextBox)FindVisualChild.Find(listBoxItem).FindName("ValorBox"); + CurrencyTextBox currencyTextBox1 = (CurrencyTextBox)FindVisualChild.Find(listBoxItem).FindName("RenovacoesBox"); + TipoRepasse selectedItem = (TipoRepasse)comboBox.SelectedItem; + comboBox1.SelectedItem = (FormaRepasse)1; + if (selectedItem == 1) + { + if (currencyTextBox != null) + { + currencyTextBox.set_MaximumValue(new decimal(10000)); + } + if (currencyTextBox1 != null) + { + currencyTextBox1.set_MaximumValue(new decimal(10000)); + } + } + else if (selectedItem == 2) + { + if (currencyTextBox != null) + { + currencyTextBox.set_MaximumValue(new decimal(100)); + } + if (currencyTextBox1 != null) + { + currencyTextBox1.set_MaximumValue(new decimal(100)); + return; + } + } + } + + private void ValidarTela() + { + object keyValuePairs; + object obj; + if (this.ViewModel.SelectedVendedor == null) + { + return; + } + List> keyValuePairs1 = this.ViewModel.SelectedVendedor.Validate(); + List> keyValuePairs2 = keyValuePairs1; + List telefones = this.ViewModel.SelectedVendedor.get_Telefones(); + if (telefones != null) + { + VendedorTelefone vendedorTelefone = telefones.FirstOrDefault(); + if (vendedorTelefone != null) + { + keyValuePairs = vendedorTelefone.Validate(); + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = null; + } + if (keyValuePairs == null) + { + keyValuePairs = new List>(); + } + keyValuePairs2.AddRange((IEnumerable)keyValuePairs); + List> keyValuePairs3 = keyValuePairs1; + ObservableCollection repasses = this.ViewModel.Repasses; + if (repasses != null) + { + Repasse repasse = repasses.FirstOrDefault(); + if (repasse != null) + { + obj = repasse.Validate(); + } + else + { + obj = null; + } + } + else + { + obj = null; + } + if (obj == null) + { + obj = new List>(); + } + keyValuePairs3.AddRange((IEnumerable)obj); + this.ValidateFields(keyValuePairs1, false); + } + + private void VendedorView_SizeChanged(object sender, SizeChangedEventArgs e) + { + if (e.NewSize.Width > 1260) + { + this.ViewModel.GridHeight2 = new GridLength(0); + Grid.SetRow(this.GridContatos, 0); + Grid.SetColumn(this.GridContatos, 1); + return; + } + this.ViewModel.GridHeight2 = new GridLength(1, GridUnitType.Star); + Grid.SetRow(this.GridContatos, 1); + Grid.SetColumn(this.GridContatos, 0); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Financeiro/BancosContasView.cs b/Codemerx/Gestor.Application/Views/Financeiro/BancosContasView.cs new file mode 100644 index 0000000..fa40fe7 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Financeiro/BancosContasView.cs @@ -0,0 +1,371 @@ +using CurrencyTextBoxControl; +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels.Financeiro; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Views.Financeiro +{ + public class BancosContasView : BaseUserControl, IComponentConnector, IStyleConnector + { + internal DataGrid BancosContasGrid; + + internal AutoCompleteBox AutoCompleteBanco; + + internal CurrencyTextBox ValorSaldoBox; + + private bool _contentLoaded; + + public BancosContasViewModel ViewModel + { + get; + set; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public BancosContasView() + { + base.Tag = "BANCOS E CONTAS"; + this.ViewModel = new BancosContasViewModel(); + base.DataContext = this.ViewModel; + this.ViewModel.Alterar(false); + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + + private void AbrirLog_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLog(26, this.ViewModel.SelectedBancosContas.get_Id()); + } + + private void Alterar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelBancosContas = (BancosContas)this.ViewModel.SelectedBancosContas.Clone(); + this.ViewModel.Alterar(true); + this.ViewModel.SelectedBancosContas.Initialize(); + } + + private void AutoCompleteBancoBox_Populating(object sender, PopulatingEventArgs e) + { + if (e.get_Parameter().Length < 3) + { + return; + } + e.set_Cancel(true); + this.ViewModel.BuscarBanco(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void AutoCompleteBancosContasBox_Populating(object sender, PopulatingEventArgs e) + { + if (e.get_Parameter().Length < 3) + { + return; + } + e.set_Cancel(true); + this.ViewModel.Filtrar(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void AutoCompleteBox_OnTextChanged(object sender, RoutedEventArgs e) + { + if (!string.IsNullOrWhiteSpace(((AutoCompleteBox)sender).get_Text())) + { + return; + } + this.ViewModel.FiltrarBancosContas(""); + } + + private void BancosContasGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + DataGrid dataGrid = (DataGrid)sender; + if (dataGrid != null && dataGrid.SelectedIndex < 0) + { + return; + } + this.ViewModel.SelectedBancosContas = (BancosContas)((dataGrid != null ? dataGrid.Items[dataGrid.SelectedIndex] : null)); + } + + private void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelarAlteracao(); + } + + private void ContentLoad() + { + this.BancosContasGrid.SelectedIndex = 0; + this.BancosContasGrid.SelectionChanged += new SelectionChangedEventHandler(this.BancosContasGrid_OnSelectionChanged); + this.BancosContasGrid.MouseDoubleClick += new MouseButtonEventHandler((object sender, MouseButtonEventArgs args) => { + }); + } + + private void Excluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Excluir(); + } + + private void ExcluirSaldo_OnClick(object sender, RoutedEventArgs e) + { + ((MenuItem)sender).Click -= new RoutedEventHandler(this.ExcluirSaldo_OnClick); + this.ViewModel.ExcluirSaldo(); + ((MenuItem)sender).Click += new RoutedEventHandler(this.ExcluirSaldo_OnClick); + } + + private async void FechamentoBox_OnLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) + { + DateTime dateTime; + DatePicker datePicker = (DatePicker)sender; + datePicker.Text = ValidationHelper.FormatDate(datePicker.Text); + if (DateTime.TryParse(datePicker.Text, out dateTime)) + { + CurrencyTextBox valorSaldoBox = this.ValorSaldoBox; + valorSaldoBox.set_Number(await this.ViewModel.CalcularValor()); + valorSaldoBox = null; + } + } + + private async void FecharSaldo_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + TimeSpan? nullable; + bool flag1; + DateTime? dataFinal = this.ViewModel.SelectedSaldo.get_DataFinal(); + if (dataFinal.HasValue) + { + dataFinal = this.ViewModel.SelectedSaldo.get_DataInicio(); + DateTime? dataFinal1 = this.ViewModel.SelectedSaldo.get_DataFinal(); + DateTime value = dataFinal1.Value; + flag = (dataFinal.HasValue ? dataFinal.GetValueOrDefault() >= value : false); + if (!flag) + { + dataFinal1 = this.ViewModel.SelectedSaldo.get_DataFinal(); + value = dataFinal1.Value; + dataFinal = this.ViewModel.SelectedSaldo.get_DataInicio(); + if (dataFinal.HasValue) + { + nullable = new TimeSpan?(value - dataFinal.GetValueOrDefault()); + } + else + { + nullable = null; + } + TimeSpan? nullable1 = nullable; + if (!nullable1.HasValue) + { + flag1 = false; + } + else + { + flag1 = (nullable1.Value.TotalDays < 28 ? true : nullable1.Value.TotalDays > 31); + } + bool flag2 = flag1; + if (flag2) + { + flag2 = !await this.ViewModel.ShowMessage("O INTERVALO DE FECHAMENTO É RECOMENDADO 1 MÊS. DESEJA CONTINUAR?", "SIM", "NÃO", false); + } + if (!flag2) + { + this.ViewModel.Loading(true); + await this.ViewModel.FecharSaldo(); + this.ViewModel.Loading(false); + } + } + else + { + await this.ViewModel.ShowMessage("A DATA DE FECHAMENTO DEVE SER MAIOR QUE A DATA DE ABERTURA DO SALDO.", "OK", "", false); + } + } + else + { + await this.ViewModel.ShowMessage("NECESSÁRIO PREENCHER A DATA DE FECHAMENTO.", "OK", "", false); + } + } + + private void Incluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Incluir(); + this.AutoCompleteBanco.set_Text(""); + List> keyValuePairs = this.ViewModel.SelectedBancosContas.Validate(); + this.ValidateFields(keyValuePairs, true); + } + + private void InfoExtrato_OnClick(object sender, RoutedEventArgs e) + { + Button button = (Button)sender; + if (button == null || button.DataContext == null) + { + return; + } + (new HosterWindow(new InfoExtratoView((Saldo)button.DataContext, true), "INFORMAÇÕES DO EXTRATO", new double?((double)800), new double?((double)450), false)).ShowDialog(); + this.ViewModel.Loading(true); + this.ViewModel.CarregarSaldos(this.ViewModel.SelectedBancosContas); + this.ViewModel.Loading(false); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/financeiro/bancoscontasview.xaml", UriKind.Relative)); + } + + private async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.Loading(true); + List> keyValuePairs = await this.ViewModel.Salvar(); + this.ValidateFields(keyValuePairs, true); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, BancosContasView.AutoCompleteBancosContasBox_Populating)); + ((AutoCompleteBox)target).add_TextChanged(new RoutedEventHandler(this.AutoCompleteBox_OnTextChanged)); + return; + } + case 2: + { + this.BancosContasGrid = (DataGrid)target; + return; + } + case 3: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + case 4: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 6: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 7: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Excluir_OnClick); + return; + } + case 8: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick); + return; + } + case 9: + { + this.AutoCompleteBanco = (AutoCompleteBox)target; + this.AutoCompleteBanco.add_Populating(new PopulatingEventHandler(this, BancosContasView.AutoCompleteBancoBox_Populating)); + return; + } + case 10: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + return; + } + case 11: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.FechamentoBox_OnLostKeyboardFocus); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + return; + } + case 12: + { + this.ValorSaldoBox = (CurrencyTextBox)target; + return; + } + case 13: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.FecharSaldo_OnClick); + return; + } + case 14: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.ExcluirSaldo_OnClick); + return; + } + } + this._contentLoaded = true; + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + if (connectionId == 15) + { + ((Button)target).Click += new RoutedEventHandler(this.InfoExtrato_OnClick); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Financeiro/CentroDeCustoView.cs b/Codemerx/Gestor.Application/Views/Financeiro/CentroDeCustoView.cs new file mode 100644 index 0000000..02dd796 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Financeiro/CentroDeCustoView.cs @@ -0,0 +1,199 @@ +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels.Financeiro; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Views.Financeiro +{ + public class CentroDeCustoView : UserControl, IComponentConnector + { + private bool _seleciona = true; + + internal DataGrid CentroDeCustoGrid; + + private bool _contentLoaded; + + private CentroDeCustoViewmodel ViewModel + { + get; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public CentroDeCustoView() + { + base.Tag = "CENTRO DE CUSTO"; + this.ViewModel = new CentroDeCustoViewmodel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + + private void AbrirLog_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLog(29, this.ViewModel.SelectedCentro.get_Id()); + } + + private void Alterar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelCentro = (Centro)this.ViewModel.SelectedCentro.Clone(); + this.ViewModel.Alterar(true); + this.ViewModel.SelectedCentro.Initialize(); + } + + private void AutoCompleteBox_OnTextChanged(object sender, RoutedEventArgs e) + { + if (!string.IsNullOrWhiteSpace(((AutoCompleteBox)sender).get_Text())) + { + return; + } + this.ViewModel.FiltrarCentro(""); + } + + private void AutoCompleteBoxCentro_Populating(object sender, PopulatingEventArgs e) + { + e.set_Cancel(true); + this.ViewModel.Filtrar(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelarAlteracao(); + } + + private void CentroDeCustoGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + if (!this._seleciona) + { + return; + } + DataGrid dataGrid = (DataGrid)sender; + if (dataGrid != null && dataGrid.SelectedIndex < 0) + { + return; + } + this.ViewModel.SelecionaCentroDeCusto((Centro)((dataGrid != null ? dataGrid.Items[dataGrid.SelectedIndex] : null))); + } + + private void ContentLoad() + { + this.CentroDeCustoGrid.SelectedIndex = 0; + this.CentroDeCustoGrid.SelectionChanged += new SelectionChangedEventHandler(this.CentroDeCustoGrid_OnSelectionChanged); + this.CentroDeCustoGrid.MouseDoubleClick += new MouseButtonEventHandler((object sender, MouseButtonEventArgs args) => { + }); + } + + private void Incluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Incluir(); + List> keyValuePairs = this.ViewModel.SelectedCentro.Validate(); + this.ValidateFields(keyValuePairs, true); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/financeiro/centrodecustoview.xaml", UriKind.Relative)); + } + + private async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.Loading(true); + List> keyValuePairs = await this.ViewModel.Salvar(); + this.ValidateFields(keyValuePairs, true); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, CentroDeCustoView.AutoCompleteBoxCentro_Populating)); + ((AutoCompleteBox)target).add_TextChanged(new RoutedEventHandler(this.AutoCompleteBox_OnTextChanged)); + return; + } + case 2: + { + this.CentroDeCustoGrid = (DataGrid)target; + return; + } + case 3: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + case 4: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 6: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 7: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick); + return; + } + } + this._contentLoaded = true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Financeiro/ExtratoWindow.cs b/Codemerx/Gestor.Application/Views/Financeiro/ExtratoWindow.cs new file mode 100644 index 0000000..9f75243 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Financeiro/ExtratoWindow.cs @@ -0,0 +1,511 @@ +using Gestor.Application; +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels.Financeiro; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Seguros; +using MaterialDesignThemes.Wpf; +using System; +using System.CodeDom.Compiler; +using System.ComponentModel; +using System.Diagnostics; +using System.Drawing; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Forms; +using System.Windows.Input; +using System.Windows.Interop; +using System.Windows.Markup; +using System.Windows.Media; +using System.Windows.Shapes; +using System.Windows.Shell; +using System.Windows.Threading; + +namespace Gestor.Application.Views.Financeiro +{ + public class ExtratoWindow : Window, IComponentConnector + { + private bool _buttonClickable; + + public ExtratoContaViewModel ViewModel; + + internal System.Windows.Shell.WindowChrome WindowChrome; + + internal Grid MinimizeButton; + + internal Grid MaximizeButton; + + internal Grid CloseButton; + + internal System.Windows.Controls.ProgressBar ProgressRing; + + internal System.Windows.Controls.ComboBox ContaBox; + + internal DatePicker InicioBox; + + internal DatePicker FimBox; + + internal System.Windows.Controls.DataGrid LancamentoGrid; + + internal TextBlock NaoHaDados; + + internal MaterialDesignThemes.Wpf.Snackbar Snackbar; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public ExtratoWindow(long id = 0L) + { + this.ViewModel = new ExtratoContaViewModel(id); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher != null) + { + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + else + { + } + string str = ApplicationHelper.Versao.ToString(); + this.ViewModel.Head = string.Concat(new string[] { Recursos.Usuario.get_Nome(), " - ", Recursos.Empresa.get_Nome(), ", VOCÊ ESTÁ EM RELATÓRIOS DE CONTA CORRENTE | VERSÃO GESTOR ", str }); + } + + public void CloseButton_Click() + { + base.Close(); + } + + private void CloseSlackBar() + { + Thread.Sleep(3000); + System.Windows.Threading.Dispatcher dispatcher = App.ProgressRing.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => this.ToggleSnackBar("", false))); + } + + private void ContentLoad() + { + this.MinimizeButton.MouseEnter += new System.Windows.Input.MouseEventHandler(ExtratoWindow.TopControls_OnMouseEnter); + this.MinimizeButton.MouseLeave += new System.Windows.Input.MouseEventHandler(this.TopControls_OnMouseLeave); + this.MaximizeButton.MouseEnter += new System.Windows.Input.MouseEventHandler(ExtratoWindow.TopControls_OnMouseEnter); + this.MaximizeButton.MouseLeave += new System.Windows.Input.MouseEventHandler(this.TopControls_OnMouseLeave); + this.CloseButton.MouseEnter += new System.Windows.Input.MouseEventHandler(ExtratoWindow.TopControls_OnMouseEnter); + this.CloseButton.MouseLeave += new System.Windows.Input.MouseEventHandler(this.TopControls_OnMouseLeave); + this.InicioBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.InicioBox.PreviewKeyDown += new System.Windows.Input.KeyEventHandler(this.DatePicker_PreviewKeyDown); + this.InicioBox.SelectedDateChanged += new EventHandler(this.Periodo_OnSelectedDateChanged); + this.FimBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.FimBox.PreviewKeyDown += new System.Windows.Input.KeyEventHandler(this.DatePicker_PreviewKeyDown); + this.FimBox.SelectedDateChanged += new EventHandler(this.Periodo_OnSelectedDateChanged); + } + + private void DataAtual_OnDoubleClick(object sender, RoutedEventArgs e) + { + ((DatePicker)sender).SelectedDate = new DateTime?(Funcoes.GetNetworkTime().Date); + } + + private void DatePicker_OnLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) + { + DatePicker datePicker = (DatePicker)sender; + datePicker.Text = ValidationHelper.FormatDate(datePicker.Text); + } + + private void DatePicker_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e) + { + if (e.Key != Key.Return) + { + return; + } + DatePicker str = (DatePicker)sender; + DateTime date = Funcoes.GetNetworkTime().Date; + str.Text = date.ToString("dd/MM/yyyy"); + } + + private async void ExportarExcel_OnClick(object sender, RoutedEventArgs e) + { + await this.ViewModel.GerarExcel(); + } + + private async void GerarResultados_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + if (ValidationHelper.ValidateDate(ValidationHelper.FormatDate(this.InicioBox.Text))) + { + this.InicioBox.SelectedDate = new DateTime?(DateTime.Parse(ValidationHelper.FormatDate(this.InicioBox.Text))); + } + if (ValidationHelper.ValidateDate(ValidationHelper.FormatDate(this.FimBox.Text))) + { + this.FimBox.SelectedDate = new DateTime?(DateTime.Parse(ValidationHelper.FormatDate(this.FimBox.Text))); + } + DateTime? selectedDate = this.InicioBox.SelectedDate; + if (selectedDate.HasValue) + { + selectedDate = this.FimBox.SelectedDate; + if (selectedDate.HasValue) + { + selectedDate = this.InicioBox.SelectedDate; + DateTime? nullable = this.FimBox.SelectedDate; + flag = (selectedDate.HasValue & nullable.HasValue ? selectedDate.GetValueOrDefault() > nullable.GetValueOrDefault() : false); + if (!flag) + { + this.ProgressRing.Visibility = System.Windows.Visibility.Visible; + this.ViewModel.IsEnabled = false; + await this.ViewModel.GerarRelatorio(); + this.ViewModel.IsEnabled = true; + this.ProgressRing.Visibility = System.Windows.Visibility.Collapsed; + return; + } + else + { + await this.ViewModel.ShowMessage("A DATA FINAL NÃO PODE SER MENOR QUE A DATA INICIAL DO FILTRO.", "OK", "", false); + return; + } + } + } + await this.ViewModel.ShowMessage("NECESSÁRIO PREENCHER O PERIODO INICIAL E FINAL PARA O FILTRO.", "OK", "", false); + } + + [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false)] + private static extern bool GetCursorPos(out MainWindow.Point lpPoint); + + [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false)] + private static extern bool GetMonitorInfo(IntPtr hMonitor, ExtratoWindow.Monitorinfo lpmi); + + private async void Imprimir_OnClick(object sender, RoutedEventArgs e) + { + await this.ViewModel.Print(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/financeiro/extratowindow.xaml", UriKind.Relative)); + } + + public void MaximizeButton_Click() + { + base.WindowState = (base.WindowState == System.Windows.WindowState.Normal ? System.Windows.WindowState.Maximized : System.Windows.WindowState.Normal); + } + + public void MinimizeButton_Click() + { + base.WindowState = System.Windows.WindowState.Minimized; + } + + [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false, SetLastError=true)] + private static extern IntPtr MonitorFromPoint(MainWindow.Point pt, ExtratoWindow.MonitorOptions dwFlags); + + protected sealed override void OnStateChanged(EventArgs e) + { + object obj; + base.BorderThickness = new Thickness((double)(base.WindowState != System.Windows.WindowState.Maximized)); + System.Windows.Shell.WindowChrome windowChrome = this.WindowChrome; + if (base.WindowState == System.Windows.WindowState.Maximized) + { + obj = null; + } + else + { + obj = 4; + } + windowChrome.ResizeBorderThickness = new Thickness((double)obj); + this.WindowChrome.CaptionHeight = (double)((base.WindowState == System.Windows.WindowState.Maximized ? 33 : 30)); + this.ViewModel.MaximizeRestore = (base.WindowState == System.Windows.WindowState.Maximized ? Geometry.Parse((string)System.Windows.Application.Current.Resources["Restore"]) : Geometry.Parse((string)System.Windows.Application.Current.Resources["Maximize"])); + base.OnStateChanged(e); + } + + private void Periodo_OnSelectedDateChanged(object sender, SelectionChangedEventArgs e) + { + this.ViewModel.LimparRelatorio(); + } + + private void SnackbarMessage_ActionClick(object sender, RoutedEventArgs e) + { + this.Snackbar.set_IsActive(false); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((ExtratoWindow)target).Initialized += new EventHandler(this.Window_OnInitialized); + return; + } + case 2: + { + this.WindowChrome = (System.Windows.Shell.WindowChrome)target; + return; + } + case 3: + { + this.MinimizeButton = (Grid)target; + this.MinimizeButton.MouseLeftButtonDown += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonDown); + this.MinimizeButton.MouseLeftButtonUp += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonUp); + return; + } + case 4: + { + this.MaximizeButton = (Grid)target; + this.MaximizeButton.MouseLeftButtonDown += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonDown); + this.MaximizeButton.MouseLeftButtonUp += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonUp); + return; + } + case 5: + { + this.CloseButton = (Grid)target; + this.CloseButton.MouseLeftButtonDown += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonDown); + this.CloseButton.MouseLeftButtonUp += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonUp); + return; + } + case 6: + { + this.ProgressRing = (System.Windows.Controls.ProgressBar)target; + return; + } + case 7: + { + this.ContaBox = (System.Windows.Controls.ComboBox)target; + return; + } + case 8: + { + this.InicioBox = (DatePicker)target; + this.InicioBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.InicioBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 9: + { + this.FimBox = (DatePicker)target; + this.FimBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.FimBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 10: + { + ((System.Windows.Controls.MenuItem)target).Click += new RoutedEventHandler(this.GerarResultados_OnClick); + return; + } + case 11: + { + ((System.Windows.Controls.MenuItem)target).Click += new RoutedEventHandler(this.Imprimir_OnClick); + return; + } + case 12: + { + ((System.Windows.Controls.MenuItem)target).Click += new RoutedEventHandler(this.ExportarExcel_OnClick); + return; + } + case 13: + { + this.LancamentoGrid = (System.Windows.Controls.DataGrid)target; + return; + } + case 14: + { + this.NaoHaDados = (TextBlock)target; + return; + } + case 15: + { + this.Snackbar = (MaterialDesignThemes.Wpf.Snackbar)target; + return; + } + case 16: + { + ((SnackbarMessage)target).add_ActionClick(new RoutedEventHandler(this.SnackbarMessage_ActionClick)); + return; + } + } + this._contentLoaded = true; + } + + public void ToggleSnackBar(string message, bool active = true) + { + this.Snackbar.get_Message().Content = message; + this.Snackbar.set_IsActive(active); + if (!active) + { + return; + } + Task.Factory.StartNew(new Action(this.CloseSlackBar)); + } + + private static void TopControls_OnMouseEnter(object sender, System.Windows.Input.MouseEventArgs e) + { + ((Grid)sender).Background = (((Grid)sender).Name == "CloseButton" ? new SolidColorBrush(Colors.IndianRed) : new SolidColorBrush(Colors.Gray)); + Path child = VisualTreeHelper.GetChild((Grid)sender, 0) as Path; + if (child != null) + { + child.Stroke = new SolidColorBrush(Colors.White); + } + } + + private void TopControls_OnMouseLeave(object sender, System.Windows.Input.MouseEventArgs e) + { + this._buttonClickable = false; + ((Grid)sender).Background = new SolidColorBrush(Colors.Transparent); + Path child = VisualTreeHelper.GetChild((Grid)sender, 0) as Path; + if (child != null) + { + child.Stroke = new SolidColorBrush(Colors.White); + } + } + + private void TopControls_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e) + { + this._buttonClickable = true; + ((Grid)sender).Background = (((Grid)sender).Name == "CloseButton" ? new SolidColorBrush(Colors.Red) : new SolidColorBrush(Colors.DimGray)); + } + + private void TopControls_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e) + { + if (this._buttonClickable) + { + MethodInfo method = base.GetType().GetMethod(string.Concat(((Grid)sender).Name, "_Click")); + if (method == null) + { + return; + } + method.Invoke(this, null); + } + } + + private void Window_OnInitialized(object sender, EventArgs e) + { + WindowInteropHelper windowInteropHelper = new WindowInteropHelper(this); + windowInteropHelper.EnsureHandle(); + HwndSource hwndSource = HwndSource.FromHwnd(windowInteropHelper.Handle); + if (hwndSource == null) + { + return; + } + hwndSource.AddHook(new HwndSourceHook(this.WindowProc)); + } + + private IntPtr WindowProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) + { + if (msg == 36) + { + this.WmGetMinMaxInfo(lParam); + } + return IntPtr.Zero; + } + + private void WmGetMinMaxInfo(IntPtr lParam) + { + MainWindow.Point point; + System.Drawing.Rectangle workingArea = Screen.FromHandle((new WindowInteropHelper(this)).Handle).WorkingArea; + base.MaxHeight = (double)workingArea.Height; + ExtratoWindow.GetCursorPos(out point); + IntPtr intPtr = ExtratoWindow.MonitorFromPoint(new MainWindow.Point(0, 0), ExtratoWindow.MonitorOptions.MonitorDefaulttoprimary); + ExtratoWindow.Monitorinfo monitorinfo = new ExtratoWindow.Monitorinfo(); + if (!ExtratoWindow.GetMonitorInfo(intPtr, monitorinfo)) + { + return; + } + IntPtr intPtr1 = ExtratoWindow.MonitorFromPoint(point, ExtratoWindow.MonitorOptions.MonitorDefaulttonearest); + ExtratoWindow.Minmaxinfo structure = (ExtratoWindow.Minmaxinfo)Marshal.PtrToStructure(lParam, typeof(ExtratoWindow.Minmaxinfo)); + if (!intPtr.Equals(intPtr1)) + { + structure.ptMaxPosition.X = monitorinfo.rcMonitor.Left; + structure.ptMaxPosition.Y = monitorinfo.rcMonitor.Top; + structure.ptMaxSize.X = monitorinfo.rcMonitor.Right - monitorinfo.rcMonitor.Left; + structure.ptMaxSize.Y = monitorinfo.rcMonitor.Bottom - monitorinfo.rcMonitor.Top; + } + else + { + structure.ptMaxPosition.X = monitorinfo.rcWork.Left; + structure.ptMaxPosition.Y = monitorinfo.rcWork.Top; + structure.ptMaxSize.X = monitorinfo.rcWork.Right - monitorinfo.rcWork.Left; + structure.ptMaxSize.Y = monitorinfo.rcWork.Bottom - monitorinfo.rcWork.Top; + } + Marshal.StructureToPtr(structure, lParam, true); + } + + private struct Minmaxinfo + { + private readonly MainWindow.Point ptReserved; + + public ExtratoWindow.Point ptMaxSize; + + public ExtratoWindow.Point ptMaxPosition; + + private readonly MainWindow.Point ptMinTrackSize; + + private readonly MainWindow.Point ptMaxTrackSize; + } + + private class Monitorinfo + { + private readonly int cbSize; + + public readonly ExtratoWindow.Rect rcMonitor; + + public readonly ExtratoWindow.Rect rcWork; + + private readonly int dwFlags; + + public Monitorinfo() + { + } + } + + private enum MonitorOptions : uint + { + MonitorDefaulttoprimary = 1, + MonitorDefaulttonearest = 2 + } + + public struct Point + { + public int X; + + public int Y; + + public Point(int x, int y) + { + this.X = x; + this.Y = y; + } + } + + public struct Rect + { + public int Left; + + public int Top; + + public int Right; + + public int Bottom; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Financeiro/FinanceiroView.cs b/Codemerx/Gestor.Application/Views/Financeiro/FinanceiroView.cs new file mode 100644 index 0000000..431e1d1 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Financeiro/FinanceiroView.cs @@ -0,0 +1,1560 @@ +using Gestor.Application.Actions; +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.ViewModels.Financeiro; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using MaterialDesignThemes.Wpf; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Data; +using System.Windows.Input; +using System.Windows.Markup; +using Xceed.Wpf.AvalonDock.Controls; + +namespace Gestor.Application.Views.Financeiro +{ + public class FinanceiroView : BaseUserControl, IComponentConnector, IStyleConnector + { + private bool _selecionando; + + private List _sortDirections; + + private List _sortDescriptions; + + internal AutoCompleteBox AutoCompleteFornecedor; + + internal MenuItem MenuFiltros; + + internal Grid GridFiltros; + + internal DataGrid LancamentoGrid; + + internal AutoCompleteBox AutoCompleteFornecedorInclusao; + + private bool _contentLoaded; + + private string OriginalValue + { + get; + set; + } + + private TipoPagamento? tipoPagamento + { + get; + set; + } + + public FinanceiroViewModel ViewModel + { + get; + set; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public FinanceiroView() + { + base.Tag = "CONSULTA DE FINANÇAS"; + this.ViewModel = new FinanceiroViewModel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + Gestor.Application.Actions.Actions.SortLancamentos = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.SortLancamentos, new Action(this.SortLancamentos)); + Gestor.Application.Actions.Actions.SaveSortLancamentos = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.SaveSortLancamentos, new Action(this.SaveSortLancamentos)); + } + + private async void AbrirLancamento(Lancamento lancamento) + { + if (this.ViewModel.SelectedLancamento == null) + { + await this.ViewModel.ShowMessage("SELECIONE UM LANCAMENTO ANTES DE PROSSEGUIR", "OK", "", false); + } + else if (lancamento.get_Id() <= (long)0 || lancamento.get_Controle().get_Plano() != null) + { + this.ViewModel.SelectedLancamento = lancamento; + this.ViewModel.VencimentoAlterado = false; + this.ViewModel.VencimentoAnt = this.ViewModel.SelectedLancamento.get_Vencimento(); + if (lancamento.get_Id() <= (long)0) + { + this.ViewModel.FiltrarLancamento(lancamento); + } + else + { + this.ViewModel.FiltrarLancamento(lancamento.get_Id()); + } + this.ViewModel.Alterando = System.Windows.Visibility.Visible; + this.ViewModel.BuscaHabilitada = false; + this.ValidarLancamento(); + } + } + + private void AbrirLog_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLog(25, this.ViewModel.SelectedLancamento.get_Id()); + } + + private void AbrirLogEmail_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLogEmail(25, this.ViewModel.SelectedLancamento.get_Id()); + } + + private async Task AbrirVinculo() + { + Lancamento lancamento; + if (this.ViewModel.LancamentosVinculo.Count != 0) + { + lancamento = await this.ViewModel.ShowVinculo(this.ViewModel); + if (lancamento != null) + { + if (!await this.ViewModel.ShowMessage(string.Format("DESEJA VINCULAR O LANÇAMENTO {0} A MOVIMENTAÇÃO SELECIONADA?", this.ViewModel.LancamentoVinculo.get_Id()), "SIM", "NÃO", false)) + { + await this.AbrirVinculo(); + } + this.ViewModel.FeedImportando(lancamento); + this.ViewModel.BindImportando(); + } + } + else + { + await this.ViewModel.ShowMessage("NÃO HÁ LANÇAMENTOS CRIADOS PARA O FORNECEDOR SELECIONADO.", "OK", "", false); + } + lancamento = null; + } + + private void AdicionarFiltro_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AdcionarFiltroPersonalizado(); + } + + private void AdicionarFiltros_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.LimparFiltros(); + this.ViewModel.AdicionarFiltros(); + this.ViewModel.IsExpanded = !this.ViewModel.IsExpanded; + } + + private void Alterar_OnClick(object sender, RoutedEventArgs e) + { + Lancamento dataContext = (Lancamento)((Button)sender).DataContext; + this.ViewModel.VisibilityFornecedor = (this.ViewModel.Importando ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.ViewModel.BotaoSalvarVisibility = (this.ViewModel.Importando ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible); + this.AbrirLancamento(dataContext); + this.ViewModel.Loading(false); + } + + private async void ArquivoDigital_OnClick(object sender, RoutedEventArgs e) + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 9).get_Consultar()) + { + FiltroArquivoDigital filtroArquivoDigital = new FiltroArquivoDigital(); + filtroArquivoDigital.set_Id(this.ViewModel.SelectedLancamento.get_Id()); + filtroArquivoDigital.set_Tipo(9); + filtroArquivoDigital.set_Parente(this.ViewModel.SelectedLancamento); + this.ViewModel.ShowDrawer(new ArquivoDigitalDrawer(filtroArquivoDigital), 0, false); + } + else + { + await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", ValidationHelper.GetDescription((TipoArquivoDigital)9), "."), "OK", "", false); + } + } + + private void AutoCompleteBoxDetalhe_Populating(object sender, PopulatingEventArgs e) + { + if (e.get_Parameter().Length < 3) + { + return; + } + e.set_Cancel(true); + this.ViewModel.FiltroPersonalizadoTask(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void AutoCompleteFornecedor_OnPopulating(object sender, PopulatingEventArgs e) + { + if (e.get_Parameter().Length < 3) + { + return; + } + e.set_Cancel(true); + this.ViewModel.BuscarFornecedor(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void AutoCompleteFornecedorAtivo_OnPopulating(object sender, PopulatingEventArgs e) + { + if (e.get_Parameter().Length < 3) + { + return; + } + e.set_Cancel(true); + this.ViewModel.BuscarFornecedorAtivo(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void AutoCompleteLancamento_OnPopulating(object sender, PopulatingEventArgs e) + { + if (e.get_Parameter().Length < 3) + { + return; + } + e.set_Cancel(true); + this.ViewModel.FiltrarLancamento(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void AutoCompleteLancamento_OnTextChanged(object sender, RoutedEventArgs e) + { + if (!string.IsNullOrWhiteSpace(((AutoCompleteBox)sender).get_Text())) + { + return; + } + this.ViewModel.Filtrar(""); + } + + private void Baixados_Click(object sender, RoutedEventArgs e) + { + this.ViewModel.SelectedStatusImportacao = 1; + this.ViewModel.FiltroImportacao(); + } + + private async void Buscar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Loading(true); + await this.ViewModel.Buscar(); + this.ViewModel.Loading(false); + } + + private async void BuscarLancamentos_Click(object sender, RoutedEventArgs e) + { + if (this.ViewModel.FornecedorInclusao == null || this.ViewModel.FornecedorInclusao.get_Id() == 0) + { + await this.ViewModel.ShowMessage("É NECESSÁRIO PESQUISAR O FORNECEDOR AO LADO PARA VINCULAR UM LANÇAMENTO A ESSA MOVIMENTAÇÃO.", "OK", "", false); + } + else + { + this.ViewModel.Loading(true); + await this.ViewModel.BuscarLancamentosVinculo(); + this.ViewModel.Loading(false); + await this.AbrirVinculo(); + } + } + + private void CancelarAlteracao_OnClick(object sender, RoutedEventArgs e) + { + this.AutoCompleteFornecedorInclusao.set_Text(string.Empty); + this.ViewModel.Alterando = System.Windows.Visibility.Collapsed; + this.ViewModel.BuscaHabilitada = true; + this.ViewModel.CancelarAlteracao(); + this.ViewModel.EnableIncluirNovo = false; + } + + private async void CancelarImportacao_Click(object sender, RoutedEventArgs e) + { + this.ViewModel.Loading(true); + this.ViewModel.Importando = false; + await this.ViewModel.Buscar(); + this.ViewModel.Loading(false); + } + + private void CheckBox_Checked(object sender, RoutedEventArgs e) + { + if (this._selecionando) + { + return; + } + this._selecionando = true; + ((CheckBox)sender).IsChecked = new bool?(false); + this.ViewModel.SelecionarTodos(); + this._selecionando = false; + } + + private void CheckBoxFiltros_Checked(object sender, RoutedEventArgs e) + { + string name = ((CheckBox)sender).Name; + if (name == "GridPlanos") + { + this.ViewModel.PlanosFiltro.ForEach((Planos x) => x.set_Selecionado(!x.get_Selecionado())); + this.ViewModel.PlanosFiltro = new List(this.ViewModel.PlanosFiltro); + return; + } + if (name == "GridCentro") + { + this.ViewModel.CentroFiltro.ForEach((Centro x) => x.set_Selecionado(!x.get_Selecionado())); + this.ViewModel.CentroFiltro = new List(this.ViewModel.CentroFiltro); + return; + } + if (name != "GridConta") + { + return; + } + this.ViewModel.ContaFiltro.ForEach((BancosContas x) => x.set_Selecionado(!x.get_Selecionado())); + this.ViewModel.ContaFiltro = new List(this.ViewModel.ContaFiltro); + } + + private async void DataGrid_OnCellEditEnding(object sender, DataGridCellEditEndingEventArgs e) + { + string sortMemberPath; + DateTime vencimento; + DateTime? nullable; + string str; + DateTime? nullable1; + DateTime? nullable2; + string shortDateString; + string text; + TextBox editingElement; + if (e.EditingElement is TextBox) + { + editingElement = e.EditingElement as TextBox; + bool flag = true; + string stringFormat = e.Column.ClipboardContentBinding.StringFormat; + if (stringFormat == "d") + { + if (editingElement != null) + { + TextBox textBox = editingElement; + if (string.IsNullOrEmpty(editingElement.Text)) + { + str = null; + } + else + { + str = ValidationHelper.FormatDate(editingElement.Text); + } + textBox.Text = str; + if (e.Column.SortMemberPath == "Vencimento" && string.IsNullOrWhiteSpace(editingElement.Text)) + { + TextBox shortDateString1 = editingElement; + vencimento = this.ViewModel.SelectedLancamento.get_Vencimento(); + shortDateString1.Text = vencimento.ToShortDateString(); + await this.ViewModel.ShowMessage("VENCIMENTO NÃO PODE SER EM BRANCO", "OK", "", false); + editingElement = null; + return; + } + else if (string.IsNullOrWhiteSpace(editingElement.Text) || ValidationHelper.ValidateDate(editingElement.Text)) + { + sortMemberPath = e.Column.SortMemberPath; + if (sortMemberPath != "Baixa") + { + if (sortMemberPath == "Pagamento") + { + if (this.OriginalValue != editingElement.Text) + { + if (!await this.ViewModel.ShowMessage("DESEJA REPLICAR PARA OS DEMAIS LANÇAMENTOS FILTRADOS?", "SIM", "NÃO", false)) + { + flag = false; + } + foreach (Lancamento lancamento in this.LancamentoGrid.Items.Cast()) + { + if (!(lancamento.get_Id() == ((Lancamento)this.LancamentoGrid.SelectedItem).get_Id() | flag)) + { + continue; + } + Lancamento lancamento1 = lancamento; + if (string.IsNullOrEmpty(editingElement.Text)) + { + nullable = null; + nullable2 = nullable; + } + else + { + nullable2 = new DateTime?(DateTime.Parse(editingElement.Text)); + } + lancamento1.set_Pagamento(nullable2); + } + this.LancamentoGrid.Items.Refresh(); + } + else + { + editingElement = null; + return; + } + } + } + else if (this.OriginalValue != editingElement.Text) + { + if (!await this.ViewModel.ShowMessage("DESEJA REPLICAR PARA OS DEMAIS LANÇAMENTOS FILTRADOS?", "SIM", "NÃO", false)) + { + flag = false; + } + foreach (Lancamento lancamento2 in this.LancamentoGrid.Items.Cast()) + { + if (!(lancamento2.get_Id() == ((Lancamento)this.LancamentoGrid.SelectedItem).get_Id() | flag)) + { + continue; + } + Lancamento lancamento3 = lancamento2; + if (string.IsNullOrEmpty(editingElement.Text)) + { + nullable = null; + nullable1 = nullable; + } + else + { + nullable1 = new DateTime?(DateTime.Parse(editingElement.Text)); + } + lancamento3.set_Baixa(nullable1); + } + this.LancamentoGrid.Items.Refresh(); + } + else + { + editingElement = null; + return; + } + } + else + { + TextBox textBox1 = editingElement; + if (e.Column.SortMemberPath == "Vencimento") + { + vencimento = this.ViewModel.SelectedLancamento.get_Vencimento(); + shortDateString = vencimento.ToShortDateString(); + } + else + { + shortDateString = null; + } + textBox1.Text = shortDateString; + await this.ViewModel.ShowMessage("DATA INVÁLIDA", "OK", "", false); + editingElement = null; + return; + } + } + else + { + editingElement = null; + return; + } + } + else if (stringFormat != "c") + { + TextBox textBox2 = editingElement; + if (textBox2 != null) + { + text = textBox2.Text; + } + else + { + text = null; + } + if (!string.IsNullOrEmpty(text)) + { + sortMemberPath = e.Column.SortMemberPath; + if (sortMemberPath != "Documento") + { + if (sortMemberPath != "Competencia") + { + if (sortMemberPath == "Complemento") + { + if (editingElement.Text.Length > 15) + { + editingElement.Text = ""; + await this.ViewModel.ShowMessage("LIMITE DE CARACTERES: 15", "OK", "", false); + } + else + { + editingElement = null; + return; + } + } + } + else if (editingElement.Text.Length > 7) + { + editingElement.Text = ""; + await this.ViewModel.ShowMessage("LIMITE DE CARACTERES: 7", "OK", "", false); + } + else + { + editingElement.Text = ValidationHelper.FormatCompetencia(editingElement.Text); + editingElement = null; + return; + } + } + else if (editingElement.Text.Length > 50) + { + editingElement.Text = string.Empty; + await this.ViewModel.ShowMessage("LIMITE DE CARACTERES: 50", "OK", "", false); + } + else if (this.OriginalValue != editingElement.Text) + { + if (!await this.ViewModel.ShowMessage("DESEJA REPLICAR PARA OS DEMAIS LANÇAMENTOS FILTRADOS?", "SIM", "NÃO", false)) + { + flag = false; + } + foreach (Lancamento lancamento4 in this.LancamentoGrid.Items.Cast()) + { + if (!(lancamento4.get_Id() == ((Lancamento)this.LancamentoGrid.SelectedItem).get_Id() | flag)) + { + continue; + } + lancamento4.set_Documento(editingElement.Text); + } + this.LancamentoGrid.Items.Refresh(); + editingElement = null; + return; + } + else + { + editingElement = null; + return; + } + } + } + else if (editingElement != null) + { + editingElement.Text = ValidationHelper.FormatCurrency(editingElement.Text); + } + } + editingElement = null; + } + + public new void DatePicker_OnLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) + { + DatePicker datePicker = (DatePicker)sender; + datePicker.Text = ValidationHelper.FormatDate(datePicker.Text); + } + + private new void DatePicker_PreviewKeyDown(object sender, KeyEventArgs e) + { + if (e.Key != Key.Return) + { + return; + } + DatePicker str = (DatePicker)sender; + DateTime date = Funcoes.GetNetworkTime().Date; + str.Text = date.ToString("dd/MM/yyyy"); + } + + private void EsconderFiltros_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.VisibleFiltros = System.Windows.Visibility.Collapsed; + this.ViewModel.VisibleOlho = System.Windows.Visibility.Visible; + } + + private async void Excluir_OnClick(object sender, RoutedEventArgs e) + { + await this.ViewModel.Excluir(); + this.ViewModel.Alterando = System.Windows.Visibility.Collapsed; + this.ViewModel.BuscaHabilitada = true; + this.ViewModel.CancelarAlteracao(); + } + + private async void ExcluirBaixa_OnClick(object sender, RoutedEventArgs e) + { + await this.ViewModel.ExcluirBaixa(); + } + + private async void ExcluirBaixaRange_OnClick(object sender, RoutedEventArgs e) + { + await this.ViewModel.ExcluirBaixaRange(); + } + + private void ExcluirFiltro_OnClick(object sender, RoutedEventArgs e) + { + Chip chip = sender as Chip; + if (chip == null) + { + return; + } + ListBox listBox = Extentions.FindVisualAncestor(chip); + Gestor.Model.Domain.Relatorios.FiltroPersonalizado item = (Gestor.Model.Domain.Relatorios.FiltroPersonalizado)listBox.Items[listBox.Items.IndexOf(chip.DataContext)]; + if (item == null) + { + return; + } + this.ViewModel.PersonalizadoSelecionado.Remove(item); + this.ViewModel.PesquisaPersonalizada(); + } + + private void ExcluirFiltro_onDeleteClick(object sender, RoutedEventArgs e) + { + Chip chip = sender as Chip; + if (chip == null) + { + return; + } + ListBox listBox = Extentions.FindVisualAncestor(chip); + Gestor.Model.Domain.Financeiro.FiltroPersonalizado item = (Gestor.Model.Domain.Financeiro.FiltroPersonalizado)listBox.Items[listBox.Items.IndexOf(chip.DataContext)]; + if (item == null) + { + return; + } + this.ViewModel.ExcluirFiltro(item); + } + + private async void ExcluirRange_OnClick(object sender, RoutedEventArgs e) + { + await this.ViewModel.ExcluirRange(); + } + + private async void ExportarExcel_OnClick(object sender, RoutedEventArgs e) + { + List list = this.LancamentoGrid.Items.Cast().ToList(); + await this.ViewModel.GerarExcel(list); + } + + private void ExtratoConta_OnClick(object sender, RoutedEventArgs e) + { + Button button = (Button)sender; + if (button == null || button.DataContext == null) + { + return; + } + (new ExtratoWindow(((Saldo)button.DataContext).get_Conta().get_Id())).Show(); + } + + private void Fechar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.IsExpanded = !this.ViewModel.IsExpanded; + } + + private void Filtrar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.IsExpanded = !this.ViewModel.IsExpanded; + } + + private void FiltroDetalhes_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + if (autoCompleteBox == null || autoCompleteBox.get_SelectedItem() == null) + { + return; + } + if (!autoCompleteBox.get_IsDropDownOpen()) + { + return; + } + this.ViewModel.AdicionarFiltro((Gestor.Model.Domain.Financeiro.FiltroPersonalizado)autoCompleteBox.get_SelectedItem()); + autoCompleteBox.set_Text(string.Empty); + } + + private async Task ImportarOfx() + { + BancosContas bancosConta; + if (this.ViewModel.ContasFiltradas == null || this.ViewModel.ContasFiltradas.Count == 0) + { + await this.ViewModel.ShowMessage("NÃO HÁ CONTAS CADASTRADAS PARA REALIZAR A IMPORTAÇÃO.", "OK", "", false); + } + else + { + if (this.ViewModel.ContasFiltradas.Count <= 1) + { + bancosConta = this.ViewModel.ContasFiltradas.First(); + } + else + { + bancosConta = await this.ViewModel.ShowContas(this.ViewModel.ContasFiltradas.ToList()); + } + BancosContas bancosConta1 = bancosConta; + if (bancosConta1 != null) + { + this.ViewModel.Loading(true); + await this.ViewModel.ParseOfx(bancosConta1); + this.ViewModel.Loading(false); + } + } + } + + private async void ImportarOfx_Click(object sender, RoutedEventArgs e) + { + await this.ImportarOfx(); + } + + private async void Imprimir_OnClick(object sender, RoutedEventArgs e) + { + List list = this.LancamentoGrid.Items.Cast().ToList(); + if (await this.ViewModel.ShowMessage("DESEJA CONTINUAR COM A IMPRESSÃO?", "SIM", "NÃO", false)) + { + bool flag = await this.ViewModel.ShowMessage("EM QUAL POSIÇÂO DESEJA IMPRIMIR?", "PAISAGEM (horizontal)", "RETRATO (vertical)", false); + await this.ViewModel.Print(list, flag); + } + list = null; + } + + private void Incluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.IncluirLancamento(); + this.ViewModel.IdLancamento = (long)0; + this.ValidarLancamento(); + } + + private void IncluirParcela_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.IncluirParcela(); + this.ValidarLancamento(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/financeiro/financeiroview.xaml", UriKind.Relative)); + } + + private void LancamentoGrid_OnPreparingCellForEdit(object sender, DataGridPreparingCellForEditEventArgs e) + { + if (e.Column.GetType().Name != "DataGridTextColumn") + { + this.LancamentoGrid.CancelEdit(); + this.LancamentoGrid.CancelEdit(); + } + TextBox editingElement = e.EditingElement as TextBox; + if (editingElement != null) + { + this.OriginalValue = editingElement.Text; + } + } + + private void LimparFiltros_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.LimparFiltros(); + this.ViewModel.FiltrarPersonalizado(); + } + + private void MostrarFiltros_Click(object sender, RoutedEventArgs e) + { + MenuItem menuItem = (MenuItem)sender; + this.GridFiltros.Visibility = (this.GridFiltros.Visibility == System.Windows.Visibility.Collapsed ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + menuItem.Header = (this.GridFiltros.Visibility == System.Windows.Visibility.Collapsed ? "MOSTRAR FILTROS" : "ESCONDER FILTROS"); + } + + private void MostrarFiltros_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.VisibleFiltros = System.Windows.Visibility.Visible; + this.ViewModel.VisibleOlho = System.Windows.Visibility.Collapsed; + } + + private void OnChecked_OnHandler(object sender, RoutedEventArgs e) + { + DataGridCell dataGridCell = (DataGridCell)sender; + if (this.LancamentoGrid.SelectedItem == null) + { + return; + } + Lancamento dataContext = dataGridCell.DataContext as Lancamento; + if (dataContext != null) + { + if (dataContext.get_Selecionado()) + { + return; + } + this.ViewModel.SelecionarLancamento(dataContext); + this.LancamentoGrid.CommitEdit(); + this.LancamentoGrid.CommitEdit(); + CollectionViewSource.GetDefaultView(this.LancamentoGrid.ItemsSource).Refresh(); + } + } + + private void Pendentes_Click(object sender, RoutedEventArgs e) + { + this.ViewModel.SelectedStatusImportacao = 0; + this.ViewModel.FiltroImportacao(); + } + + private void Saldos_OnMouseDoubleClick(object sender, MouseButtonEventArgs e) + { + if (this.ViewModel.SelectedSaldo == null) + { + return; + } + string str = string.Concat("INFORMAÇÕES DO EXTRATO - ", this.ViewModel.SelectedSaldo.get_Conta().get_Descricao()); + Window window = Funcoes.IsHosterOpen(str); + if (window == null) + { + (new HosterWindow(new InfoExtratoView(this.ViewModel.SelectedSaldo, false), str, new double?((double)800), new double?((double)450), true)).Show(); + return; + } + window.WindowState = (window.WindowState == WindowState.Minimized ? WindowState.Maximized : window.WindowState); + window.Activate(); + } + + private async Task Salvar(bool fechar) + { + bool flag; + bool flag1; + DatePickerTextBox focusedElement = Keyboard.FocusedElement as DatePickerTextBox; + if (focusedElement != null) + { + ((DatePicker)focusedElement.TemplatedParent).SelectedDate = new DateTime?(ValidationHelper.ToDateTime(ValidationHelper.FormatDate(focusedElement.Text))); + DateTime? selectedDate = ((DatePicker)focusedElement.TemplatedParent).SelectedDate; + if (selectedDate.ToString() == "01/01/0001 00:00:00") + { + selectedDate = null; + ((DatePicker)focusedElement.TemplatedParent).SelectedDate = selectedDate; + } + } + flag = (!this.ViewModel.Importando ? false : this.ViewModel.Parcelas > 1); + bool flag2 = flag; + if (flag2) + { + flag2 = !await this.ViewModel.ShowMessage(string.Format("SERÁ CRIADO COM {0} PARCELAS, INICIADO POR ESSE LANÇAMENTO, DESEJA PROSSEGUIR?", this.ViewModel.Parcelas), "SIM", "NÃO", false); + } + if (!flag2) + { + this.ViewModel.Loading(true); + if (!this.ViewModel.Importando) + { + this.ViewModel.Bind(); + List> keyValuePairs = await this.ViewModel.Salvar(); + flag1 = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (!flag1) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + else if (!fechar) + { + Fornecedor fornecedorInclusao = this.ViewModel.FornecedorInclusao; + string historico = this.ViewModel.Historico; + string documento = this.ViewModel.Documento; + string competencia = this.ViewModel.Competencia; + string complemento = this.ViewModel.Complemento; + Planos plano = this.ViewModel.Plano; + Centro centro = this.ViewModel.Centro; + BancosContas conta = this.ViewModel.Conta; + Sinal sinal = this.ViewModel.Sinal; + int parcelas = this.ViewModel.Parcelas; + int parcela = this.ViewModel.Parcela; + DateTime vencimento = this.ViewModel.Vencimento; + decimal valor = this.ViewModel.Valor; + DateTime? baixa = this.ViewModel.Baixa; + decimal? valorPago = this.ViewModel.ValorPago; + DateTime? pagamento = this.ViewModel.Pagamento; + TipoPagamento tipoPagamento = this.ViewModel.TipoPagamento; + string observacao = this.ViewModel.Observacao; + this.ViewModel.FornecedorInclusao = fornecedorInclusao; + this.ViewModel.Historico = historico; + this.ViewModel.Documento = documento; + this.ViewModel.Competencia = competencia; + this.ViewModel.Complemento = complemento; + this.ViewModel.Plano = plano; + this.ViewModel.Centro = centro; + this.ViewModel.Conta = conta; + this.ViewModel.Sinal = sinal; + this.ViewModel.Parcelas = parcelas; + this.ViewModel.Parcela = parcela; + this.ViewModel.Vencimento = vencimento; + this.ViewModel.Valor = valor; + this.ViewModel.Baixa = baixa; + this.ViewModel.ValorPago = valorPago; + this.ViewModel.Pagamento = pagamento; + this.ViewModel.TipoPagamento = tipoPagamento; + this.ViewModel.Observacao = observacao; + this.ViewModel.EnableIncluirNovo = true; + } + else + { + this.AutoCompleteFornecedorInclusao.set_Text(string.Empty); + this.ViewModel.Alterando = System.Windows.Visibility.Collapsed; + this.ViewModel.BuscaHabilitada = true; + await this.ViewModel.Buscar(); + } + } + else + { + this.ViewModel.BindImportando(); + List> keyValuePairs1 = this.ViewModel.SelectedLancamento.Validate(); + if (keyValuePairs1 == null) + { + keyValuePairs1 = new List>(); + } + List> keyValuePairs2 = keyValuePairs1; + if (keyValuePairs2.Count <= 0) + { + this.ViewModel.LancamentosFiltrados = this.ViewModel.Lancamentos; + this.AutoCompleteFornecedorInclusao.set_Text(string.Empty); + this.ViewModel.Alterando = System.Windows.Visibility.Collapsed; + this.ViewModel.BuscaHabilitada = true; + this.ViewModel.Loading(false); + } + else + { + this.ViewModel.Loading(false); + await this.ViewModel.ShowMessage(keyValuePairs2, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + } + } + } + + private async void SalvarImportacao_Click(object sender, RoutedEventArgs e) + { + if (await this.ViewModel.ShowMessage(string.Concat("DESEJA PROSSEGUIR COM A IMPORTAÇÃO?", Environment.NewLine, Environment.NewLine, "SOMENTE OS LANÇAMENTOS VÁLIDOS SERÃO ALTERADOS OU INCLUÍDOS"), "SIM", "NÃO", false)) + { + this.ViewModel.Loading(true); + ObservableCollection lancamentos = this.ViewModel.Lancamentos; + List list = ( + from x in lancamentos + where x.Validate().Count == 0 + select x).ToList(); + if (await this.ViewModel.SalvarImportacao(list)) + { + this.ViewModel.Importando = false; + } + this.ViewModel.Loading(false); + } + } + + private async void SalvarInclusao_Click(object sender, RoutedEventArgs e) + { + await this.Salvar(false); + } + + private async void SalvarLancamento_OnClick(object sender, RoutedEventArgs e) + { + await this.Salvar(true); + } + + private async void SalvarRange_OnClick(object sender, RoutedEventArgs e) + { + await this.ViewModel.Atualizar(this.LancamentoGrid.Items.Cast().ToList()); + this.LancamentoGrid.CommitEdit(); + this.LancamentoGrid.CommitEdit(); + CollectionViewSource.GetDefaultView(this.LancamentoGrid.ItemsSource).Refresh(); + } + + public void SaveSortLancamentos() + { + this._sortDirections = new List(); + this._sortDescriptions = new List(); + foreach (DataGridColumn column in this.LancamentoGrid.Columns) + { + this._sortDirections.Add(column.SortDirection); + } + foreach (SortDescription sortDescription in this.LancamentoGrid.Items.SortDescriptions) + { + this._sortDescriptions.Add(sortDescription); + } + } + + private void Sintetizar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Sintetizar(); + } + + public void SortLancamentos() + { + if (this._sortDirections == null || this._sortDirections.Count != this.LancamentoGrid.Columns.Count) + { + return; + } + foreach (DataGridColumn column in this.LancamentoGrid.Columns) + { + column.SortDirection = this._sortDirections[this.LancamentoGrid.Columns.IndexOf(column)]; + } + this.LancamentoGrid.Items.SortDescriptions.Clear(); + foreach (SortDescription _sortDescription in this._sortDescriptions) + { + this.LancamentoGrid.Items.SortDescriptions.Add(_sortDescription); + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((ComboBox)target).SelectionChanged += new SelectionChangedEventHandler(this.TipoFiltrosBox_OnSelectionChanged); + return; + } + case 2: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 3: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 4: + { + this.AutoCompleteFornecedor = (AutoCompleteBox)target; + this.AutoCompleteFornecedor.add_Populating(new PopulatingEventHandler(this, FinanceiroView.AutoCompleteFornecedor_OnPopulating)); + return; + } + case 5: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, FinanceiroView.AutoCompleteBoxDetalhe_Populating)); + ((AutoCompleteBox)target).add_SelectionChanged(new SelectionChangedEventHandler(this.FiltroDetalhes_OnSelectionChanged)); + return; + } + case 6: + { + ((Button)target).Click += new RoutedEventHandler(this.MostrarFiltros_OnClick); + return; + } + case 7: + { + this.MenuFiltros = (MenuItem)target; + this.MenuFiltros.Click += new RoutedEventHandler(this.MostrarFiltros_Click); + return; + } + case 8: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Pendentes_Click); + return; + } + case 9: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Baixados_Click); + return; + } + case 10: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Todos_Click); + return; + } + case 11: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.SalvarImportacao_Click); + return; + } + case 12: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.CancelarImportacao_Click); + return; + } + case 13: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Buscar_OnClick); + return; + } + case 14: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Imprimir_OnClick); + return; + } + case 15: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.ExportarExcel_OnClick); + return; + } + case 16: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Sintetizar_OnClick); + return; + } + case 17: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.TrocarFornecedor_OnClick); + return; + } + case 18: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.SalvarRange_OnClick); + return; + } + case 19: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + case 20: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.IncluirParcela_OnClick); + return; + } + case 21: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.ExcluirBaixaRange_OnClick); + return; + } + case 22: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.ExcluirRange_OnClick); + return; + } + case 23: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Transferir_OnClick); + return; + } + case 24: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick); + return; + } + case 25: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLogEmail_OnClick); + return; + } + case 26: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.ImportarOfx_Click); + return; + } + case 27: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Filtrar_OnClick); + return; + } + case 28: + { + this.GridFiltros = (Grid)target; + return; + } + case 29: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 30: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 31: + { + ((Button)target).Click += new RoutedEventHandler(this.AdicionarFiltro_OnClick); + return; + } + case 32: + case 33: + case 37: + case 38: + case 39: + case 40: + case 41: + case 44: + case 45: + case 46: + case 60: + { + this._contentLoaded = true; + return; + } + case 34: + { + ((Button)target).Click += new RoutedEventHandler(this.LimparFiltros_OnClick); + return; + } + case 35: + { + ((Button)target).Click += new RoutedEventHandler(this.EsconderFiltros_OnClick); + return; + } + case 36: + { + this.LancamentoGrid = (DataGrid)target; + this.LancamentoGrid.CellEditEnding += new EventHandler(this.DataGrid_OnCellEditEnding); + this.LancamentoGrid.PreparingCellForEdit += new EventHandler(this.LancamentoGrid_OnPreparingCellForEdit); + return; + } + case 42: + { + ((Button)target).Click += new RoutedEventHandler(this.AdicionarFiltros_OnClick); + return; + } + case 43: + { + ((Button)target).Click += new RoutedEventHandler(this.Fechar_OnClick); + return; + } + case 47: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + case 48: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.SalvarInclusao_Click); + return; + } + case 49: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.SalvarLancamento_OnClick); + return; + } + case 50: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.CancelarAlteracao_OnClick); + return; + } + case 51: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.ExcluirBaixa_OnClick); + return; + } + case 52: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Excluir_OnClick); + return; + } + case 53: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.ArquivoDigital_OnClick); + return; + } + case 54: + { + this.AutoCompleteFornecedorInclusao = (AutoCompleteBox)target; + this.AutoCompleteFornecedorInclusao.add_Populating(new PopulatingEventHandler(this, FinanceiroView.AutoCompleteFornecedorAtivo_OnPopulating)); + return; + } + case 55: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.BuscarLancamentos_Click); + return; + } + case 56: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 57: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 58: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 59: + { + ((DataGrid)target).MouseDoubleClick += new MouseButtonEventHandler(this.Saldos_OnMouseDoubleClick); + return; + } + case 61: + { + ((DataGrid)target).CellEditEnding += new EventHandler(this.DataGrid_OnCellEditEnding); + return; + } + default: + { + this._contentLoaded = true; + return; + } + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 32: + { + ((Chip)target).add_DeleteClick(new RoutedEventHandler(this.ExcluirFiltro_OnClick)); + return; + } + case 33: + { + ((Chip)target).add_DeleteClick(new RoutedEventHandler(this.ExcluirFiltro_onDeleteClick)); + return; + } + case 34: + case 35: + case 36: + case 42: + case 43: + { + return; + } + case 37: + { + ((CheckBox)target).Checked += new RoutedEventHandler(this.CheckBox_Checked); + ((CheckBox)target).Unchecked += new RoutedEventHandler(this.CheckBox_Checked); + return; + } + case 38: + { + EventSetter eventSetter = new EventSetter() + { + Event = ToggleButton.CheckedEvent, + Handler = new RoutedEventHandler(this.OnChecked_OnHandler) + }; + ((System.Windows.Style)target).Setters.Add(eventSetter); + eventSetter = new EventSetter() + { + Event = ToggleButton.UncheckedEvent, + Handler = new RoutedEventHandler(this.Unchecked_OnHandler) + }; + ((System.Windows.Style)target).Setters.Add(eventSetter); + return; + } + case 39: + { + ((Button)target).Click += new RoutedEventHandler(this.ArquivoDigital_OnClick); + return; + } + case 40: + { + ((Button)target).Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 41: + { + ((ComboBox)target).DropDownOpened += new EventHandler(this.TipoPagamento_DropDownOpened); + ((ComboBox)target).DropDownClosed += new EventHandler(this.TipoPagamento_OnDropDownClosed); + return; + } + case 44: + { + ((CheckBox)target).Checked += new RoutedEventHandler(this.CheckBoxFiltros_Checked); + ((CheckBox)target).Unchecked += new RoutedEventHandler(this.CheckBoxFiltros_Checked); + return; + } + case 45: + { + ((CheckBox)target).Checked += new RoutedEventHandler(this.CheckBoxFiltros_Checked); + ((CheckBox)target).Unchecked += new RoutedEventHandler(this.CheckBoxFiltros_Checked); + return; + } + case 46: + { + ((CheckBox)target).Checked += new RoutedEventHandler(this.CheckBoxFiltros_Checked); + ((CheckBox)target).Unchecked += new RoutedEventHandler(this.CheckBoxFiltros_Checked); + return; + } + default: + { + if (connectionId != 60) + { + return; + } + ((Button)target).Click += new RoutedEventHandler(this.ExtratoConta_OnClick); + return; + } + } + } + + private void TipoFiltrosBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + ComboBox comboBox = (ComboBox)sender; + if (comboBox == null || comboBox.SelectedItem == null) + { + return; + } + this.ViewModel.IsvisibleStatus = System.Windows.Visibility.Visible; + this.ViewModel.IsVisibleData = System.Windows.Visibility.Collapsed; + this.ViewModel.IsVisibleFornecedor = System.Windows.Visibility.Collapsed; + this.ViewModel.IsVisiblePersonalizado = System.Windows.Visibility.Collapsed; + this.ViewModel.IsVisibleFiltros = System.Windows.Visibility.Visible; + this.ViewModel.LimparFiltros(); + this.ViewModel.SelectedFornecedor = null; + if (this.AutoCompleteFornecedor != null) + { + this.AutoCompleteFornecedor.set_Text(string.Empty); + } + this.ViewModel.DropDownHeight = 0; + switch ((FiltroLancamento)comboBox.SelectedItem) + { + case 1: + case 2: + { + this.ViewModel.IsvisibleStatus = System.Windows.Visibility.Collapsed; + this.ViewModel.IsVisibleData = System.Windows.Visibility.Visible; + return; + } + case 3: + { + this.ViewModel.IsVisibleFornecedor = System.Windows.Visibility.Visible; + return; + } + case 5: + { + this.ViewModel.IsVisiblePersonalizado = System.Windows.Visibility.Visible; + this.ViewModel.IsVisibleFiltros = System.Windows.Visibility.Collapsed; + this.GridFiltros.Visibility = System.Windows.Visibility.Collapsed; + this.MenuFiltros.Header = "MOSTRAR FILTROS"; + this.ViewModel.IsVisibleData = System.Windows.Visibility.Visible; + this.ViewModel.DropDownHeight = 200; + return; + } + default: + { + this.ViewModel.IsVisibleData = System.Windows.Visibility.Visible; + return; + } + } + } + + private void TipoPagamento_DropDownOpened(object sender, EventArgs e) + { + if (((ComboBox)sender).SelectedItem == null) + { + this.tipoPagamento = null; + return; + } + this.tipoPagamento = new TipoPagamento?((TipoPagamento)((ComboBox)sender).SelectedItem); + } + + private async void TipoPagamento_OnDropDownClosed(object sender, EventArgs e) + { + TipoPagamento? nullable = this.tipoPagamento; + TipoPagamento selectedItem = (TipoPagamento)((ComboBox)sender).SelectedItem; + if (nullable.GetValueOrDefault() == selectedItem & nullable.HasValue) + { + nullable = null; + this.tipoPagamento = nullable; + } + else if (await this.ViewModel.ShowMessage("DESEJA REPLICAR PARA OS DEMAIS LANÇAMENTOS FILTRADOS?", "SIM", "NÃO", false)) + { + nullable = null; + this.tipoPagamento = nullable; + foreach (Lancamento lancamento in this.LancamentoGrid.Items.Cast()) + { + lancamento.set_TipoPagamento((TipoPagamento)((ComboBox)sender).SelectedItem); + } + this.LancamentoGrid.CommitEdit(); + this.LancamentoGrid.CommitEdit(); + this.LancamentoGrid.Items.Refresh(); + } + } + + private void Todos_Click(object sender, RoutedEventArgs e) + { + this.ViewModel.SelectedStatusImportacao = 2; + this.ViewModel.FiltroImportacao(); + } + + private async void Transferir_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + Transferencia transferencium = new Transferencia(); + transferencium.set_Data(Funcoes.GetNetworkTime().Date); + Transferencia transferencium1 = transferencium; + while (true) + { + transferencium1 = await this.ViewModel.ShowTransferencia(transferencium1); + if (transferencium1 == null) + { + transferencium1 = null; + return; + } + List> keyValuePairs = await this.ViewModel.Salvar(transferencium1); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (flag) + { + break; + } + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + this.ViewModel.ToggleSnackBar("TRANSFERÊNCIA SALVA COM SUCESSO.", true); + this.ViewModel.Alterar(false); + transferencium1 = null; + return; + transferencium1 = null; + } + + private void TrocarFornecedor_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Loading(true); + this.AbrirLancamento(this.ViewModel.SelectedLancamento); + this.ViewModel.VisibilityFornecedor = System.Windows.Visibility.Visible; + this.ViewModel.Loading(false); + } + + private void Unchecked_OnHandler(object sender, RoutedEventArgs e) + { + DataGridCell dataGridCell = (DataGridCell)sender; + if (this.LancamentoGrid.SelectedItem == null) + { + return; + } + Lancamento dataContext = dataGridCell.DataContext as Lancamento; + if (dataContext != null) + { + if (!dataContext.get_Selecionado()) + { + return; + } + this.ViewModel.DeSelecionarLancamento(dataContext); + this.LancamentoGrid.CommitEdit(); + this.LancamentoGrid.CommitEdit(); + CollectionViewSource.GetDefaultView(this.LancamentoGrid.ItemsSource).Refresh(); + } + } + + private void ValidarLancamento() + { + if (this.ViewModel.SelectedLancamento == null) + { + return; + } + List> keyValuePairs = this.ViewModel.SelectedLancamento.Validate(); + this.ValidateFields(keyValuePairs, false); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Financeiro/FornecedorView.cs b/Codemerx/Gestor.Application/Views/Financeiro/FornecedorView.cs new file mode 100644 index 0000000..6825a38 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Financeiro/FornecedorView.cs @@ -0,0 +1,419 @@ +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels.Financeiro; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; + +namespace Gestor.Application.Views.Financeiro +{ + public class FornecedorView : BaseUserControl, IComponentConnector + { + internal DataGrid FornecedorGrid; + + internal TextBox NomeBox; + + internal TextBox DocumentoPrincipalBox; + + internal ToggleButton AtivoBox; + + internal TextBox CepBox; + + internal ProgressBar ProgressCep; + + internal TextBox EnderecoBox; + + internal TextBox BairroBox; + + internal TextBox CidadeBox; + + internal TextBox EstadoBox; + + internal ComboBox PlanoBox; + + internal ComboBox CentroBox; + + internal ComboBox ContaBox; + + internal ComboBox TipoPagamentoBox; + + private bool _contentLoaded; + + public FornecedorViewModel ViewModel + { + get; + set; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public FornecedorView() + { + base.Tag = "CADASTRO DE FORNECEDORES"; + this.ViewModel = new FornecedorViewModel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + } + + private async void AbrirAquivoDigital_Click(object sender, RoutedEventArgs e) + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 10).get_Consultar()) + { + FiltroArquivoDigital filtroArquivoDigital = new FiltroArquivoDigital(); + filtroArquivoDigital.set_Id(this.ViewModel.SelectedFornecedor.get_Id()); + filtroArquivoDigital.set_Tipo(10); + filtroArquivoDigital.set_Parente(this.ViewModel.SelectedFornecedor); + this.ViewModel.ShowDrawer(new ArquivoDigitalDrawer(filtroArquivoDigital), 0, false); + } + else + { + await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", ValidationHelper.GetDescription((TipoArquivoDigital)10), "."), "OK", "", false); + } + } + + private void AbrirLog_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLog(24, this.ViewModel.SelectedFornecedor.get_Id()); + } + + private void AbrirLogEmail_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLogEmail(24, this.ViewModel.SelectedFornecedor.get_Id()); + } + + private void Alterar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Alterar(true); + this.ViewModel.SelectedFornecedor.Initialize(); + } + + private void AutoCompleteBox_OnTextChanged(object sender, RoutedEventArgs e) + { + if (!string.IsNullOrWhiteSpace(((AutoCompleteBox)sender).get_Text())) + { + return; + } + this.ViewModel.FiltrarFornecedor(""); + } + + private void AutoCompleteFornecedor_OnPopulating(object sender, PopulatingEventArgs e) + { + if (e.get_Parameter().Length < 3) + { + return; + } + e.set_Cancel(true); + this.ViewModel.Filtrar(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelProduto = (Fornecedor)this.ViewModel.SelectedFornecedor.Clone(); + this.ViewModel.CancelarAlteracao(); + this.ScrollToItem(); + } + + private async void CopiarDados_OnClick(object sender, RoutedEventArgs e) + { + Cliente cliente = await this.ViewModel.ShowCopiarCliente(); + if (cliente != null) + { + this.ViewModel.Incluir(); + Cliente cliente1 = cliente; + ObservableCollection observableCollection = await (new ClienteServico()).BuscarEnderecosAsync(cliente.get_Id()); + cliente1.set_Enderecos(observableCollection); + cliente1 = null; + cliente1 = cliente; + ObservableCollection observableCollection1 = await (new ClienteServico()).BuscarTelefonesAsync(cliente.get_Id()); + cliente1.set_Telefones(observableCollection1); + cliente1 = null; + cliente1 = cliente; + ObservableCollection observableCollection2 = await (new ClienteServico()).BuscarEmailsAsync(cliente.get_Id()); + cliente1.set_Emails(observableCollection2); + cliente1 = null; + this.ViewModel.Copiar(cliente); + } + cliente = null; + } + + private void DocumentoPrincipalBox_OnLostFocus(object sender, RoutedEventArgs e) + { + TextBox textBox = (TextBox)sender; + textBox.Text = ValidationHelper.FormatDocument(textBox.Text); + } + + private void Excel_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Excel(); + } + + private async void Excluir_OnClick(object sender, RoutedEventArgs e) + { + await this.ViewModel.Delete(); + this.ScrollToItem(); + } + + private void Imprimir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Imprimir(); + } + + private void Incluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Incluir(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/financeiro/fornecedorview.xaml", UriKind.Relative)); + } + + private async void PostcodeBox_OnLostFocus(object sender, RoutedEventArgs e) + { + TextBox textBox = (TextBox)sender; + if (!string.IsNullOrWhiteSpace(textBox.Text)) + { + string str = ValidationHelper.FormatPostCode(textBox.Text); + if (ValidationHelper.ValidatePostCode(str)) + { + this.CepBox.Text = str; + EnderecoBase enderecoBase = await this.ViewModel.BuscaCep(str); + if (enderecoBase != null) + { + this.EnderecoBox.Text = enderecoBase.get_Endereco(); + this.CidadeBox.Text = enderecoBase.get_Cidade(); + this.EstadoBox.Text = enderecoBase.get_Estado(); + this.BairroBox.Text = enderecoBase.get_Bairro(); + } + } + } + } + + private async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.Loading(true); + List> keyValuePairs = await this.ViewModel.Salvar(); + this.ValidateFields(keyValuePairs, true); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + else + { + this.ScrollToItem(); + } + } + + private void ScrollToItem() + { + if (this.FornecedorGrid.SelectedItem == null) + { + return; + } + this.FornecedorGrid.UpdateLayout(); + this.FornecedorGrid.ScrollIntoView(this.FornecedorGrid.SelectedItem); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, FornecedorView.AutoCompleteFornecedor_OnPopulating)); + ((AutoCompleteBox)target).add_TextChanged(new RoutedEventHandler(this.AutoCompleteBox_OnTextChanged)); + return; + } + case 2: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Imprimir_OnClick); + return; + } + case 3: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Excel_OnClick); + return; + } + case 4: + { + this.FornecedorGrid = (DataGrid)target; + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + case 6: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.CopiarDados_OnClick); + return; + } + case 7: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 8: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 9: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 10: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Excluir_OnClick); + return; + } + case 11: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirAquivoDigital_Click); + return; + } + case 12: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick); + return; + } + case 13: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLogEmail_OnClick); + return; + } + case 14: + { + this.NomeBox = (TextBox)target; + return; + } + case 15: + { + this.DocumentoPrincipalBox = (TextBox)target; + FornecedorView fornecedorView = this; + this.DocumentoPrincipalBox.PreviewTextInput += new TextCompositionEventHandler(fornecedorView.SomenteNumeros); + this.DocumentoPrincipalBox.LostFocus += new RoutedEventHandler(this.DocumentoPrincipalBox_OnLostFocus); + return; + } + case 16: + { + this.AtivoBox = (ToggleButton)target; + return; + } + case 17: + { + this.CepBox = (TextBox)target; + this.CepBox.LostFocus += new RoutedEventHandler(this.PostcodeBox_OnLostFocus); + FornecedorView fornecedorView1 = this; + this.CepBox.PreviewTextInput += new TextCompositionEventHandler(fornecedorView1.SomenteNumeros); + return; + } + case 18: + { + this.ProgressCep = (ProgressBar)target; + return; + } + case 19: + { + this.EnderecoBox = (TextBox)target; + return; + } + case 20: + { + this.BairroBox = (TextBox)target; + return; + } + case 21: + { + this.CidadeBox = (TextBox)target; + return; + } + case 22: + { + this.EstadoBox = (TextBox)target; + return; + } + case 23: + { + FornecedorView fornecedorView2 = this; + ((TextBox)target).LostFocus += new RoutedEventHandler(fornecedorView2.FormatarTelefone); + return; + } + case 24: + { + FornecedorView fornecedorView3 = this; + ((TextBox)target).LostFocus += new RoutedEventHandler(fornecedorView3.FormatarTelefone); + return; + } + case 25: + { + this.PlanoBox = (ComboBox)target; + return; + } + case 26: + { + this.CentroBox = (ComboBox)target; + return; + } + case 27: + { + this.ContaBox = (ComboBox)target; + return; + } + case 28: + { + this.TipoPagamentoBox = (ComboBox)target; + return; + } + } + this._contentLoaded = true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Financeiro/InfoExtratoView.cs b/Codemerx/Gestor.Application/Views/Financeiro/InfoExtratoView.cs new file mode 100644 index 0000000..a666da9 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Financeiro/InfoExtratoView.cs @@ -0,0 +1,127 @@ +using Gestor.Application.ViewModels.Financeiro; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Model.Domain.Financeiro; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Media; +using System.Windows.Shapes; + +namespace Gestor.Application.Views.Financeiro +{ + public class InfoExtratoView : BaseUserControl, IComponentConnector + { + private bool _buttonClickable; + + private bool _contentLoaded; + + public InfoExtratoViewModel ViewModel + { + get; + set; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public InfoExtratoView(Saldo saldo, bool telaBancos = false) + { + this.ViewModel = new InfoExtratoViewModel(telaBancos); + base.DataContext = this.ViewModel; + this.ViewModel.SelectedSaldo = saldo; + this.InitializeComponent(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/financeiro/infoextratoview.xaml", UriKind.Relative)); + } + + private async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.Loading(true); + List> keyValuePairs = await this.ViewModel.Salvar(); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + if (connectionId != 1) + { + this._contentLoaded = true; + return; + } + ((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick); + } + + private static void TopControls_OnMouseEnter(object sender, MouseEventArgs e) + { + ((Grid)sender).Background = (((Grid)sender).Name == "CloseButton" ? new SolidColorBrush(Colors.IndianRed) : new SolidColorBrush(Colors.Gray)); + Path child = VisualTreeHelper.GetChild((Grid)sender, 0) as Path; + if (child != null) + { + child.Stroke = new SolidColorBrush(Colors.White); + } + } + + private void TopControls_OnMouseLeave(object sender, MouseEventArgs e) + { + this._buttonClickable = false; + ((Grid)sender).Background = new SolidColorBrush(Colors.Transparent); + Path child = VisualTreeHelper.GetChild((Grid)sender, 0) as Path; + if (child != null) + { + child.Stroke = new SolidColorBrush(Colors.White); + } + } + + private void TopControls_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e) + { + this._buttonClickable = true; + ((Grid)sender).Background = (((Grid)sender).Name == "CloseButton" ? new SolidColorBrush(Colors.Red) : new SolidColorBrush(Colors.DimGray)); + } + + private void TopControls_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e) + { + if (this._buttonClickable) + { + MethodInfo method = base.GetType().GetMethod(string.Concat(((Grid)sender).Name, "_Click")); + if (method == null) + { + return; + } + method.Invoke(this, null); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Financeiro/PlanoView.cs b/Codemerx/Gestor.Application/Views/Financeiro/PlanoView.cs new file mode 100644 index 0000000..5d4bff5 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Financeiro/PlanoView.cs @@ -0,0 +1,117 @@ +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels.Financeiro; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Markup; + +namespace Gestor.Application.Views.Financeiro +{ + public class PlanoView : BaseUserControl, IComponentConnector + { + private bool _contentLoaded; + + public PlanoViewModel ViewModel + { + get; + set; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public PlanoView(Plano plano) + { + this.ViewModel = new PlanoViewModel(plano); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + } + + private void Alterar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Cancel = (Plano)this.ViewModel.SelectedPlano.Clone(); + this.ViewModel.Alterar(true); + } + + private void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Cancelar(); + } + + private void Incluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Incluir(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/financeiro/planoview.xaml", UriKind.Relative)); + } + + private async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.Loading(true); + List> keyValuePairs = await this.ViewModel.Salvar(); + this.ValidateFields(keyValuePairs, true); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + case 2: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 3: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 4: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + } + this._contentLoaded = true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Financeiro/PlanosView.cs b/Codemerx/Gestor.Application/Views/Financeiro/PlanosView.cs new file mode 100644 index 0000000..e9b9fef --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Financeiro/PlanosView.cs @@ -0,0 +1,262 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Financeiro; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Views.Financeiro +{ + public class PlanosView : BaseUserControl, IComponentConnector + { + private bool _seleciona = true; + + public PlanosViewModel ViewModel; + + internal DataGrid PlanosGrid; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public PlanosView() + { + base.Tag = "PLANO DE CONTAS"; + this.ViewModel = new PlanosViewModel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + + private void AbrirLog_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLog(28, this.ViewModel.SelectedPlanos.get_Id()); + } + + private void AlterarPlanos_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Alterar(true); + this.ViewModel.SelectedPlanos.Initialize(); + } + + private void AutoCompleteBoxPlanos_OnTextChanged(object sender, RoutedEventArgs e) + { + if (!string.IsNullOrWhiteSpace(((AutoCompleteBox)sender).get_Text())) + { + return; + } + this.ViewModel.FiltrarPlanos(""); + } + + private void AutoCompleteBoxPlanos_Populating(object sender, PopulatingEventArgs e) + { + e.set_Cancel(true); + this.ViewModel.Filtrar(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void CancelarPlanos_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelarAlteracao(); + } + + private async void ContentLoad() + { + this.PlanosGrid.SelectedIndex = 0; + this.PlanosGrid.SelectionChanged += new SelectionChangedEventHandler(this.PlanosGrid_OnSelectionChanged); + this.PlanosGrid.MouseDoubleClick += new MouseButtonEventHandler((object sender, MouseButtonEventArgs args) => { + }); + PlanosViewModel viewModel = this.ViewModel; + List planos = await (new BaseServico()).BuscarPlanoAsync(); + PlanosViewModel observableCollection = viewModel; + List planos1 = planos; + IOrderedEnumerable ativo = + from x in planos1 + orderby x.get_Ativo() descending + select x; + observableCollection.Plano = new ObservableCollection(ativo.ThenBy((Plano x) => x.get_Descricao()).ToList()); + viewModel = null; + } + + private void IncluirPlanos_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Incluir(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/financeiro/planosview.xaml", UriKind.Relative)); + } + + private async void PlanoButton_OnClick(object sender, RoutedEventArgs e) + { + PlanoView planoView = new PlanoView(this.ViewModel.SelectedPlanos.get_Plano()); + (new HosterWindow(planoView, "PLANO", new double?((double)500), new double?((double)200), false)).ShowDialog(); + this.ViewModel.Loading(true); + if (planoView.ViewModel.SelectedPlano.get_Id() != 0) + { + PlanosViewModel viewModel = this.ViewModel; + List planos = await (new BaseServico()).BuscarPlanoAsync(); + PlanosViewModel observableCollection = viewModel; + List planos1 = planos; + IOrderedEnumerable ativo = + from x in planos1 + orderby x.get_Ativo() descending + select x; + observableCollection.Plano = new ObservableCollection(ativo.ThenBy((Plano x) => x.get_Descricao()).ToList()); + viewModel = null; + List planos2 = await (new BaseServico()).BuscarPlanosAsync(); + PlanosViewModel list = this.ViewModel; + List planos3 = planos2; + IOrderedEnumerable ativo1 = + from x in planos3 + orderby x.get_Ativo() descending + select x; + IOrderedEnumerable planos4 = ativo1.ThenBy((Planos x) => { + Plano plano = x.get_Plano(); + if (plano != null) + { + return plano.get_Descricao(); + } + return null; + }); + list.Planos = planos4.ThenBy((Planos x) => x.get_Descricao()).ToList(); + ObservableCollection planosFiltrados = this.ViewModel.PlanosFiltrados; + List nums = ( + from p in planosFiltrados + select p.get_Id()).ToList(); + this.ViewModel.PlanosFiltrados = new ObservableCollection( + from x in this.ViewModel.Planos + where nums.Contains(x.get_Id()) + select x); + this._seleciona = false; + this.PlanosGrid.SelectedItem = this.ViewModel.SelectedPlanos; + this.ViewModel.SelectedPlano = this.ViewModel.Plano.First((Plano x) => x.get_Id() == planoView.ViewModel.SelectedPlano.get_Id()); + this._seleciona = true; + } + this.ViewModel.Loading(false); + } + + private async void PlanosGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + object obj; + if (this._seleciona) + { + DataGrid dataGrid = (DataGrid)sender; + if (dataGrid == null || dataGrid.SelectedIndex >= 0) + { + PlanosViewModel viewModel = this.ViewModel; + obj = (dataGrid != null ? dataGrid.Items[dataGrid.SelectedIndex] : null); + await viewModel.SelecionaPlanos((Planos)obj); + } + } + } + + private async void SalvarPlanos_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.Loading(true); + List> keyValuePairs = await this.ViewModel.Salvar(); + this.ValidateFields(keyValuePairs, true); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, PlanosView.AutoCompleteBoxPlanos_Populating)); + ((AutoCompleteBox)target).add_TextChanged(new RoutedEventHandler(this.AutoCompleteBoxPlanos_OnTextChanged)); + return; + } + case 2: + { + this.PlanosGrid = (DataGrid)target; + return; + } + case 3: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.IncluirPlanos_OnClick); + return; + } + case 4: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AlterarPlanos_OnClick); + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.SalvarPlanos_OnClick); + return; + } + case 6: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.CancelarPlanos_OnClick); + return; + } + case 7: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick); + return; + } + case 8: + { + ((Button)target).Click += new RoutedEventHandler(this.PlanoButton_OnClick); + return; + } + } + this._contentLoaded = true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Financeiro/Relatorios/FechamentoFinanceiroView.cs b/Codemerx/Gestor.Application/Views/Financeiro/Relatorios/FechamentoFinanceiroView.cs new file mode 100644 index 0000000..3c04339 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Financeiro/Relatorios/FechamentoFinanceiroView.cs @@ -0,0 +1,285 @@ +using Gestor.Application.Componentes; +using Gestor.Application.ViewModels.Financeiro.Relatorios; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Financeiro.Relatorios; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Views.Financeiro.Relatorios +{ + public class FechamentoFinanceiroView : BaseUserControl, IComponentConnector, IStyleConnector + { + public FechamentoFinanceiroViewModel ViewModel; + + internal ProgressBar ProgressRing; + + internal DatePicker InicioBox; + + internal DatePicker FimBox; + + internal Gestor.Application.Componentes.WebEditor WebEditor; + + internal TextBlock NaoHaDados; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public FechamentoFinanceiroView() + { + this.ViewModel = new FechamentoFinanceiroViewModel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + + private void CheckBox_Checked(object sender, RoutedEventArgs e) + { + string name = ((CheckBox)sender).Name; + if (name == "GridPlanos") + { + this.ViewModel.Planos.ForEach((Planos x) => x.set_Selecionado(!x.get_Selecionado())); + this.ViewModel.Planos = new List(this.ViewModel.Planos); + return; + } + if (name == "GridCentro") + { + this.ViewModel.Centro.ForEach((Centro x) => x.set_Selecionado(!x.get_Selecionado())); + this.ViewModel.Centro = new List(this.ViewModel.Centro); + return; + } + if (name != "GridConta") + { + this.ViewModel.Plano.ForEach((Plano x) => x.set_Selecionado(!x.get_Selecionado())); + this.ViewModel.Plano = new List(this.ViewModel.Plano); + return; + } + this.ViewModel.Conta.ForEach((BancosContas x) => x.set_Selecionado(!x.get_Selecionado())); + this.ViewModel.Conta = new List(this.ViewModel.Conta); + } + + private void ContentLoad() + { + this.InicioBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.InicioBox.PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + this.InicioBox.SelectedDateChanged += new EventHandler(this.Periodo_OnSelectedDateChanged); + this.FimBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.FimBox.PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + this.FimBox.SelectedDateChanged += new EventHandler(this.Periodo_OnSelectedDateChanged); + } + + private async void ExportarExcel_OnClick(object sender, RoutedEventArgs e) + { + this.ProgressRing.Visibility = System.Windows.Visibility.Visible; + this.ViewModel.IsEnabled = false; + await this.ViewModel.GerarExcel(); + this.ProgressRing.Visibility = System.Windows.Visibility.Collapsed; + this.ViewModel.IsEnabled = true; + } + + private void Fechar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.IsExpanded = !this.ViewModel.IsExpanded; + } + + private void Filtros_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.IsExpanded = !this.ViewModel.IsExpanded; + } + + private async void GerarResultados_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.InicioBox.Text = ValidationHelper.FormatDate(this.InicioBox.Text); + this.FimBox.Text = ValidationHelper.FormatDate(this.FimBox.Text); + try + { + this.ViewModel.Inicio = new DateTime?(Convert.ToDateTime(this.InicioBox.Text)); + this.ViewModel.Fim = new DateTime?(Convert.ToDateTime(this.FimBox.Text)); + } + catch (Exception exception) + { + return; + } + DateTime? inicio = this.ViewModel.Inicio; + DateTime? fim = this.ViewModel.Fim; + flag = (inicio.HasValue & fim.HasValue ? inicio.GetValueOrDefault() > fim.GetValueOrDefault() : false); + if (!flag) + { + this.ProgressRing.Visibility = System.Windows.Visibility.Visible; + this.ViewModel.IsEnabled = false; + this.ViewModel.HtmlContent = string.Empty; + this.ViewModel.Fechamento = new List(); + await this.ViewModel.GerarRelatorio(); + if (this.ViewModel.HtmlContent == string.Empty) + { + this.NaoHaDados.Visibility = System.Windows.Visibility.Visible; + this.ViewModel.IsEnabled = true; + this.ProgressRing.Visibility = System.Windows.Visibility.Collapsed; + } + this.WebEditor.Initialize(this.ViewModel.HtmlContent); + this.NaoHaDados.Visibility = System.Windows.Visibility.Collapsed; + this.ViewModel.IsEnabled = true; + this.ProgressRing.Visibility = System.Windows.Visibility.Collapsed; + } + else + { + await this.ViewModel.ShowMessage("A DATA FINAL NÃO PODE SER MENOR QUE A DATA INICIAL DO FILTRO.", "OK", "", false); + } + } + + private async void Imprimir_OnClick(object sender, RoutedEventArgs e) + { + this.ProgressRing.Visibility = System.Windows.Visibility.Visible; + this.ViewModel.IsEnabled = false; + await this.ViewModel.Print(); + this.ProgressRing.Visibility = System.Windows.Visibility.Collapsed; + this.ViewModel.IsEnabled = true; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/financeiro/relatorios/fechamentofinanceiroview.xaml", UriKind.Relative)); + } + + private void Periodo_OnSelectedDateChanged(object sender, SelectionChangedEventArgs e) + { + this.ViewModel.Fechamento = new List(); + this.ViewModel.HtmlContent = string.Empty; + this.WebEditor.Initialize(""); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.ProgressRing = (ProgressBar)target; + return; + } + case 2: + { + this.InicioBox = (DatePicker)target; + this.InicioBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.InicioBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 3: + { + this.FimBox = (DatePicker)target; + this.FimBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.FimBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 4: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.GerarResultados_OnClick); + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Filtros_OnClick); + return; + } + case 6: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Imprimir_OnClick); + return; + } + case 7: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.ExportarExcel_OnClick); + return; + } + case 8: + { + this.WebEditor = (Gestor.Application.Componentes.WebEditor)target; + return; + } + case 9: + { + this.NaoHaDados = (TextBlock)target; + return; + } + case 10: + { + ((Button)target).Click += new RoutedEventHandler(this.Fechar_OnClick); + return; + } + } + this._contentLoaded = true; + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 11: + { + ((CheckBox)target).Checked += new RoutedEventHandler(this.CheckBox_Checked); + ((CheckBox)target).Unchecked += new RoutedEventHandler(this.CheckBox_Checked); + return; + } + case 12: + { + ((CheckBox)target).Checked += new RoutedEventHandler(this.CheckBox_Checked); + ((CheckBox)target).Unchecked += new RoutedEventHandler(this.CheckBox_Checked); + return; + } + case 13: + { + ((CheckBox)target).Checked += new RoutedEventHandler(this.CheckBox_Checked); + ((CheckBox)target).Unchecked += new RoutedEventHandler(this.CheckBox_Checked); + return; + } + case 14: + { + ((CheckBox)target).Checked += new RoutedEventHandler(this.CheckBox_Checked); + ((CheckBox)target).Unchecked += new RoutedEventHandler(this.CheckBox_Checked); + return; + } + default: + { + return; + } + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Generic/BaseUserControl.cs b/Codemerx/Gestor.Application/Views/Generic/BaseUserControl.cs new file mode 100644 index 0000000..a389f17 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Generic/BaseUserControl.cs @@ -0,0 +1,104 @@ +using Gestor.Application.Helpers; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; +using System.Text.RegularExpressions; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; + +namespace Gestor.Application.Views.Generic +{ + public class BaseUserControl : UserControl + { + public virtual TipoTela Tela + { + get; + set; + } + + public BaseUserControl() + { + } + + public void DataAtual_OnDoubleClick(object sender, RoutedEventArgs e) + { + ((DatePicker)sender).SelectedDate = new DateTime?(Funcoes.GetNetworkTime().Date); + } + + public void DatePicker_OnLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) + { + DatePicker today = (DatePicker)sender; + today.Text = ValidationHelper.FormatDate(today.Text); + if (string.IsNullOrEmpty(today.Text)) + { + today.DisplayDate = DateTime.Today; + } + } + + public void DatePicker_PreviewKeyDown(object sender, KeyEventArgs e) + { + if (e.Key != Key.Return) + { + return; + } + DatePicker str = (DatePicker)sender; + DateTime date = Funcoes.GetNetworkTime().Date; + str.Text = date.ToString("dd/MM/yyyy"); + } + + public virtual void FormatarDocumento(object sender, RoutedEventArgs e) + { + TextBox textBox = (TextBox)sender; + textBox.Text = ValidationHelper.FormatDocument(textBox.Text); + } + + public virtual void FormatarTelefone(object sender, RoutedEventArgs e) + { + TextBox textBox = (TextBox)sender; + if (string.IsNullOrWhiteSpace(textBox.Text)) + { + return; + } + textBox.Text = ValidationHelper.FormatarTelefone(textBox.Text); + } + + public virtual void LetrasHabilitacao(object sender, TextCompositionEventArgs e) + { + Regex regex = new Regex("[^a-eA-E]+"); + e.Handled = regex.IsMatch(e.Text); + } + + public virtual void Placa(object sender, TextCompositionEventArgs e) + { + Regex regex = new Regex("[^a-zA-Z0-9]+"); + e.Handled = regex.IsMatch(e.Text); + } + + public void ScrollViewer_PreviewMouseWheel(object sender, MouseWheelEventArgs e) + { + ScrollViewer scrollViewer = (ScrollViewer)sender; + scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset - (double)e.Delta); + e.Handled = true; + } + + public void SomenteCaracteres(object sender, TextCompositionEventArgs e) + { + Regex regex = new Regex("[^a-zA-Z]+$"); + e.Handled = regex.IsMatch(e.Text); + } + + public void SomenteData(object sender, TextCompositionEventArgs e) + { + Regex regex = new Regex("[^0-9/-]+"); + e.Handled = regex.IsMatch(e.Text); + } + + public virtual void SomenteNumeros(object sender, TextCompositionEventArgs e) + { + Regex regex = new Regex("[^0-9]+"); + e.Handled = regex.IsMatch(e.Text); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Generic/DragOverPopup.cs b/Codemerx/Gestor.Application/Views/Generic/DragOverPopup.cs new file mode 100644 index 0000000..234ab52 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Generic/DragOverPopup.cs @@ -0,0 +1,57 @@ +using Gestor.Model.Domain.Ferramentas; +using System; +using System.CodeDom.Compiler; +using System.ComponentModel; +using System.Diagnostics; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Markup; + +namespace Gestor.Application.Views.Generic +{ + public class DragOverPopup : UserControl, IComponentConnector + { + internal TextBlock Titulo; + + internal TextBlock Descricao; + + private bool _contentLoaded; + + public DragOverPopup(Tarefa tarefa) + { + this.InitializeComponent(); + this.Titulo.Text = tarefa.get_Titulo(); + this.Descricao.Text = tarefa.get_Descricao(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/generic/dragoverpopup.xaml", UriKind.Relative)); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + if (connectionId == 1) + { + this.Titulo = (TextBlock)target; + return; + } + if (connectionId != 2) + { + this._contentLoaded = true; + return; + } + this.Descricao = (TextBlock)target; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Generic/ErrorWindow.cs b/Codemerx/Gestor.Application/Views/Generic/ErrorWindow.cs new file mode 100644 index 0000000..e1b7df0 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Generic/ErrorWindow.cs @@ -0,0 +1,101 @@ +using Gestor.Application.Helpers; +using Gestor.Common.Validation; +using Gestor.Model.API; +using System; +using System.CodeDom.Compiler; +using System.ComponentModel; +using System.Diagnostics; +using System.Reflection; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Markup; + +namespace Gestor.Application.Views.Generic +{ + public class ErrorWindow : Window, IComponentConnector + { + internal TextBlock DescricaoErro; + + internal RepeatButton ContinuarButton; + + private bool _contentLoaded; + + public ErrorWindow(TipoErro tipo, bool fecharSistema = false) + { + this.InitializeComponent(); + this.HanddleErro(tipo); + if (fecharSistema) + { + this.ContinuarButton.Visibility = System.Windows.Visibility.Collapsed; + } + } + + private void ContinuarButton_OnClick(object sender, RoutedEventArgs e) + { + base.Close(); + } + + private void HanddleErro(TipoErro tipo) + { + this.DescricaoErro.Text = ValidationHelper.GetCategory(tipo); + if (tipo != 3) + { + this.ContinuarButton.Visibility = System.Windows.Visibility.Visible; + return; + } + this.ContinuarButton.Visibility = System.Windows.Visibility.Collapsed; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/generic/errorwindow.xaml", UriKind.Relative)); + } + + private void Reiniciar_OnClick(object sender, RoutedEventArgs e) + { + this.Shutdown(); + } + + private void Shutdown() + { + Instancia.ExcluirCfg(); + Process.Start(System.Windows.Application.ResourceAssembly.Location, (ApplicationHelper.Conectado ? "INICIAR CONECTADO" : "INICIAR")); + System.Windows.Application.Current.Shutdown(); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.DescricaoErro = (TextBlock)target; + return; + } + case 2: + { + this.ContinuarButton = (RepeatButton)target; + this.ContinuarButton.Click += new RoutedEventHandler(this.ContinuarButton_OnClick); + return; + } + case 3: + { + ((RepeatButton)target).Click += new RoutedEventHandler(this.Reiniciar_OnClick); + return; + } + } + this._contentLoaded = true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Generic/HosterWindow.cs b/Codemerx/Gestor.Application/Views/Generic/HosterWindow.cs new file mode 100644 index 0000000..01fa146 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Generic/HosterWindow.cs @@ -0,0 +1,460 @@ +using Gestor.Application.Actions; +using MaterialDesignThemes.Wpf; +using System; +using System.CodeDom.Compiler; +using System.ComponentModel; +using System.Diagnostics; +using System.Drawing; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Forms; +using System.Windows.Input; +using System.Windows.Interop; +using System.Windows.Markup; +using System.Windows.Media; +using System.Windows.Shapes; +using System.Windows.Shell; +using System.Windows.Threading; + +namespace Gestor.Application.Views.Generic +{ + public class HosterWindow : Window, IComponentConnector + { + private bool _buttonClickable; + + internal System.Windows.Shell.WindowChrome WindowChrome; + + internal Grid Menu; + + internal Grid MinimizeButton; + + internal Path MinimizeButtonPath; + + internal Grid MaximizeButton; + + internal Path MaximizeButtonPath; + + internal Grid CloseButton; + + internal System.Windows.Controls.ContentControl ContentControl; + + internal DialogHost HosterDialog; + + internal MaterialDesignThemes.Wpf.DrawerHost DrawerHost; + + internal MaterialDesignThemes.Wpf.Snackbar Snackbar; + + private bool _contentLoaded; + + public string Tela + { + get; + set; + } + + public HosterWindow(System.Windows.Controls.ContentControl control, string titulo, double? x = null, double? y = null, bool canMaximize = false) + { + this.InitializeComponent(); + Gestor.Application.Actions.Actions.EnableMainMenu = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.EnableMainMenu, new Action(this.HabilitarMenu)); + Gestor.Application.Actions.Actions.CloseHoster = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.CloseHoster, new Action(this.Close)); + this.MinimizeButton.MouseEnter += new System.Windows.Input.MouseEventHandler(HosterWindow.TopControls_OnMouseEnter); + this.MinimizeButton.MouseLeave += new System.Windows.Input.MouseEventHandler(this.TopControls_OnMouseLeave); + this.MaximizeButton.MouseEnter += new System.Windows.Input.MouseEventHandler(HosterWindow.TopControls_OnMouseEnter); + this.MaximizeButton.MouseLeave += new System.Windows.Input.MouseEventHandler(this.TopControls_OnMouseLeave); + this.CloseButton.MouseEnter += new System.Windows.Input.MouseEventHandler(HosterWindow.TopControls_OnMouseEnter); + this.CloseButton.MouseLeave += new System.Windows.Input.MouseEventHandler(this.TopControls_OnMouseLeave); + this.ContentControl.Content = control.Content; + this.ContentControl.DataContext = control.DataContext; + this.ContentControl.Tag = titulo; + this.MaximizeButtonPath.Data = Geometry.Parse((string)System.Windows.Application.Current.Resources["Restore"]); + if ((x.HasValue || y.HasValue) && !canMaximize) + { + base.WindowState = System.Windows.WindowState.Normal; + base.BorderThickness = new Thickness(1); + this.WindowChrome.ResizeBorderThickness = new Thickness(4); + this.WindowChrome.CaptionHeight = 30; + this.MaximizeButtonPath.Data = Geometry.Parse((string)System.Windows.Application.Current.Resources["Maximize"]); + } + if (x.HasValue) + { + if (x.Value >= base.Width) + { + if (!canMaximize) + { + base.MaxWidth = x.Value; + base.Width = x.Value; + } + base.MinWidth = x.Value; + } + else + { + base.MinWidth = x.Value; + if (!canMaximize) + { + base.Width = x.Value; + base.MaxWidth = x.Value; + } + } + } + if (y.HasValue) + { + if (y.Value >= base.Height) + { + if (!canMaximize) + { + base.MaxHeight = y.Value; + base.Height = y.Value; + } + base.MinHeight = y.Value; + } + else + { + base.MinHeight = y.Value; + if (!canMaximize) + { + base.Height = y.Value; + base.MaxHeight = y.Value; + } + } + } + if (!x.HasValue || !y.HasValue || canMaximize) + { + base.ResizeMode = System.Windows.ResizeMode.CanResize; + } + else + { + this.MaximizeButton.IsEnabled = false; + this.MinimizeButton.IsEnabled = false; + this.MaximizeButtonPath.Stroke = new SolidColorBrush(Colors.Gray); + this.MinimizeButtonPath.Stroke = new SolidColorBrush(Colors.Gray); + } + base.Title = titulo; + this.Tela = control.GetType().Name; + this.HosterDialog.set_Identifier(string.Format("Dialog{0}{1}", this.Tela, Guid.NewGuid())); + } + + public void CloseButton_Click() + { + base.Close(); + } + + [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false)] + private static extern bool GetCursorPos(out HosterWindow.Point lpPoint); + + [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false)] + private static extern bool GetMonitorInfo(IntPtr hMonitor, HosterWindow.Monitorinfo lpmi); + + private void HabilitarMenu(bool enable) + { + this.Menu.IsEnabled = enable; + } + + private void HosterWindow_OnLoaded(object sender, RoutedEventArgs e) + { + Task.Run(() => { + Thread.Sleep(500); + System.Windows.Application.Current.Dispatcher.Invoke(() => base.Topmost = false); + }); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/generic/hosterwindow.xaml", UriKind.Relative)); + } + + public void MaximizeButton_Click() + { + base.WindowState = (base.WindowState == System.Windows.WindowState.Normal ? System.Windows.WindowState.Maximized : System.Windows.WindowState.Normal); + } + + public void MinimizeButton_Click() + { + base.WindowState = System.Windows.WindowState.Minimized; + } + + [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false, SetLastError=true)] + private static extern IntPtr MonitorFromPoint(HosterWindow.Point pt, HosterWindow.MonitorOptions dwFlags); + + protected sealed override void OnStateChanged(EventArgs e) + { + object obj; + base.BorderThickness = new Thickness((double)(base.WindowState != System.Windows.WindowState.Maximized)); + System.Windows.Shell.WindowChrome windowChrome = this.WindowChrome; + if (base.WindowState == System.Windows.WindowState.Maximized) + { + obj = null; + } + else + { + obj = 4; + } + windowChrome.ResizeBorderThickness = new Thickness((double)obj); + this.WindowChrome.CaptionHeight = (double)((base.WindowState == System.Windows.WindowState.Maximized ? 32 : 29)); + this.MaximizeButtonPath.Data = (base.WindowState == System.Windows.WindowState.Maximized ? Geometry.Parse((string)System.Windows.Application.Current.Resources["Restore"]) : Geometry.Parse((string)System.Windows.Application.Current.Resources["Maximize"])); + base.OnStateChanged(e); + } + + private void SnackbarMessage_ActionClick(object sender, RoutedEventArgs e) + { + this.Snackbar.set_IsActive(false); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((HosterWindow)target).Initialized += new EventHandler(this.Window_OnInitialized); + ((HosterWindow)target).Loaded += new RoutedEventHandler(this.HosterWindow_OnLoaded); + return; + } + case 2: + { + this.WindowChrome = (System.Windows.Shell.WindowChrome)target; + return; + } + case 3: + { + this.Menu = (Grid)target; + return; + } + case 4: + { + this.MinimizeButton = (Grid)target; + this.MinimizeButton.MouseLeftButtonDown += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonDown); + this.MinimizeButton.MouseLeftButtonUp += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonUp); + return; + } + case 5: + { + this.MinimizeButtonPath = (Path)target; + return; + } + case 6: + { + this.MaximizeButton = (Grid)target; + this.MaximizeButton.MouseLeftButtonDown += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonDown); + this.MaximizeButton.MouseLeftButtonUp += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonUp); + return; + } + case 7: + { + this.MaximizeButtonPath = (Path)target; + return; + } + case 8: + { + this.CloseButton = (Grid)target; + this.CloseButton.MouseLeftButtonDown += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonDown); + this.CloseButton.MouseLeftButtonUp += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonUp); + return; + } + case 9: + { + this.ContentControl = (System.Windows.Controls.ContentControl)target; + return; + } + case 10: + { + this.HosterDialog = (DialogHost)target; + return; + } + case 11: + { + this.DrawerHost = (MaterialDesignThemes.Wpf.DrawerHost)target; + return; + } + case 12: + { + this.Snackbar = (MaterialDesignThemes.Wpf.Snackbar)target; + return; + } + case 13: + { + ((SnackbarMessage)target).add_ActionClick(new RoutedEventHandler(this.SnackbarMessage_ActionClick)); + return; + } + } + this._contentLoaded = true; + } + + private static void TopControls_OnMouseEnter(object sender, System.Windows.Input.MouseEventArgs e) + { + ((Grid)sender).Background = (((Grid)sender).Name == "CloseButton" ? new SolidColorBrush(Colors.IndianRed) : new SolidColorBrush(Colors.Gray)); + Path child = VisualTreeHelper.GetChild((Grid)sender, 0) as Path; + if (child != null) + { + child.Stroke = new SolidColorBrush(Colors.White); + } + } + + private void TopControls_OnMouseLeave(object sender, System.Windows.Input.MouseEventArgs e) + { + this._buttonClickable = false; + ((Grid)sender).Background = new SolidColorBrush(Colors.Transparent); + Path child = VisualTreeHelper.GetChild((Grid)sender, 0) as Path; + if (child != null) + { + child.Stroke = new SolidColorBrush(Colors.White); + } + } + + private void TopControls_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e) + { + this._buttonClickable = true; + if (((Grid)sender).Name != "CloseButton") + { + ((Grid)sender).Background = new SolidColorBrush(Colors.DimGray); + } + else + { + ((Grid)sender).Background = new SolidColorBrush(Colors.Red); + Path child = VisualTreeHelper.GetChild((Grid)sender, 0) as Path; + if (child != null) + { + child.Stroke = new SolidColorBrush(Colors.Black); + return; + } + } + } + + private void TopControls_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e) + { + if (this._buttonClickable) + { + MethodInfo method = base.GetType().GetMethod(string.Concat(((Grid)sender).Name, "_Click")); + if (method == null) + { + return; + } + method.Invoke(this, null); + } + } + + private void Window_OnInitialized(object sender, EventArgs e) + { + WindowInteropHelper windowInteropHelper = new WindowInteropHelper(this); + windowInteropHelper.EnsureHandle(); + HwndSource hwndSource = HwndSource.FromHwnd(windowInteropHelper.Handle); + if (hwndSource == null) + { + return; + } + hwndSource.AddHook(new HwndSourceHook(this.WindowProc)); + } + + private IntPtr WindowProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) + { + if (msg == 36) + { + this.WmGetMinMaxInfo(lParam); + } + return IntPtr.Zero; + } + + private void WmGetMinMaxInfo(IntPtr lParam) + { + HosterWindow.Point point; + System.Drawing.Rectangle workingArea = Screen.FromHandle((new WindowInteropHelper(this)).Handle).WorkingArea; + base.MaxHeight = (double)workingArea.Height; + HosterWindow.GetCursorPos(out point); + IntPtr intPtr = HosterWindow.MonitorFromPoint(new HosterWindow.Point(0, 0), HosterWindow.MonitorOptions.MonitorDefaulttoprimary); + HosterWindow.Monitorinfo monitorinfo = new HosterWindow.Monitorinfo(); + if (!HosterWindow.GetMonitorInfo(intPtr, monitorinfo)) + { + return; + } + IntPtr intPtr1 = HosterWindow.MonitorFromPoint(point, HosterWindow.MonitorOptions.MonitorDefaulttonearest); + HosterWindow.Minmaxinfo structure = (HosterWindow.Minmaxinfo)Marshal.PtrToStructure(lParam, typeof(HosterWindow.Minmaxinfo)); + if (!intPtr.Equals(intPtr1)) + { + structure.ptMaxPosition.X = monitorinfo.rcMonitor.Left; + structure.ptMaxPosition.Y = monitorinfo.rcMonitor.Top; + structure.ptMaxSize.X = monitorinfo.rcMonitor.Right - monitorinfo.rcMonitor.Left; + structure.ptMaxSize.Y = monitorinfo.rcMonitor.Bottom - monitorinfo.rcMonitor.Top; + } + else + { + structure.ptMaxPosition.X = monitorinfo.rcWork.Left; + structure.ptMaxPosition.Y = monitorinfo.rcWork.Top; + structure.ptMaxSize.X = monitorinfo.rcWork.Right - monitorinfo.rcWork.Left; + structure.ptMaxSize.Y = monitorinfo.rcWork.Bottom - monitorinfo.rcWork.Top; + } + Marshal.StructureToPtr(structure, lParam, true); + } + + private struct Minmaxinfo + { + private readonly HosterWindow.Point ptReserved; + + public HosterWindow.Point ptMaxSize; + + public HosterWindow.Point ptMaxPosition; + + private readonly HosterWindow.Point ptMinTrackSize; + + private readonly HosterWindow.Point ptMaxTrackSize; + } + + private class Monitorinfo + { + private readonly int cbSize; + + public readonly HosterWindow.Rect rcMonitor; + + public readonly HosterWindow.Rect rcWork; + + private readonly int dwFlags; + + public Monitorinfo() + { + } + } + + private enum MonitorOptions : uint + { + MonitorDefaulttoprimary = 1, + MonitorDefaulttonearest = 2 + } + + public struct Point + { + public int X; + + public int Y; + + public Point(int x, int y) + { + this.X = x; + this.Y = y; + } + } + + public struct Rect + { + public int Left; + + public int Top; + + public int Right; + + public int Bottom; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/ImportView.cs b/Codemerx/Gestor.Application/Views/ImportView.cs new file mode 100644 index 0000000..f7411e2 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/ImportView.cs @@ -0,0 +1,69 @@ +using Gestor.Application.ViewModels; +using System; +using System.CodeDom.Compiler; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Markup; + +namespace Gestor.Application.Views +{ + public class ImportView : UserControl, IComponentConnector + { + private bool _contentLoaded; + + private ImportViewModel ViewModel + { + get; + } + + public ImportView() + { + this.ViewModel = new ImportViewModel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + } + + private void ButtonBase_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Importar(); + } + + private void ButtonBase2_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CarregarArquivos(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/importview.xaml", UriKind.Relative)); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + if (connectionId == 1) + { + ((Button)target).Click += new RoutedEventHandler(this.ButtonBase2_OnClick); + return; + } + if (connectionId != 2) + { + this._contentLoaded = true; + return; + } + ((Button)target).Click += new RoutedEventHandler(this.ButtonBase_OnClick); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/LoginWindow.cs b/Codemerx/Gestor.Application/Views/LoginWindow.cs new file mode 100644 index 0000000..96cac36 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/LoginWindow.cs @@ -0,0 +1,825 @@ +using Agger.Registro; +using Gestor.Application; +using Gestor.Application.Componentes; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Ajuda; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Ferramentas; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.API; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.License; +using Newtonsoft.Json.Linq; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Sockets; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Media; +using System.Windows.Shapes; +using System.Windows.Threading; + +namespace Gestor.Application.Views +{ + public class LoginWindow : Window, IComponentConnector + { + internal LoginViewModel ViewModel; + + private bool _buttonClickable; + + private DispatcherTimer _carouselTimer; + + internal Image ProgressRing; + + internal TextBox UserBox; + + internal CustomSenhaLoginBox PasswordBox; + + internal TextBlock TrocaSenha; + + internal CustomSenhaLoginBox SenhaBox; + + internal CustomSenhaLoginBox ConfirmacaoBox; + + internal TextBox ChaveBox; + + internal Grid MinimizeButton; + + internal Grid CloseButton; + + private bool _contentLoaded; + + public bool Bloquear + { + get; + set; + } + + private JArray LoginSettings + { + get; + set; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public LoginWindow() + { + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + this.ViewModel = new LoginViewModel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + this.MinimizeButton.MouseEnter += new MouseEventHandler(LoginWindow.TopControls_OnMouseEnter); + this.MinimizeButton.MouseLeave += new MouseEventHandler(this.TopControls_OnMouseLeave); + this.CloseButton.MouseEnter += new MouseEventHandler(LoginWindow.TopControls_OnMouseEnter); + this.CloseButton.MouseLeave += new MouseEventHandler(this.TopControls_OnMouseLeave); + this.ViewModel.Head = string.Concat("AGGER GESTOR ", this.ViewModel.Version, " - AGUARDE ESTAMOS INICIALIZANDO"); + } + + private async Task Access(bool error = true) + { + string str; + if (string.IsNullOrEmpty(this.ViewModel.Login) || string.IsNullOrEmpty(this.ViewModel.Senha)) + { + if (error) + { + this.ViewModel.ErrorLoginVisibility = System.Windows.Visibility.Visible; + } + this.UserBox.Focus(); + } + else + { + this.Loading(true); + if (await this.ViewModel.Validate(this.ViewModel.Login, this.ViewModel.Senha)) + { + bool bloquear = this.Bloquear; + if (!bloquear) + { + bloquear = await this.VerificarAcesso(); + } + this.Bloquear = bloquear; + if (!this.Bloquear) + { + DateTime networkTime = Funcoes.GetNetworkTime(); + if (Recursos.Usuario.get_Id() > (long)0) + { + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(0); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(networkTime); + registroLog.set_Descricao(string.Format("O USUÁRIO {0} LOGOU NO SISTEMA, EM {1}.", Recursos.Usuario.get_Nome(), networkTime)); + registroLog.set_EntidadeId(Recursos.Usuario.get_Id()); + registroLog.set_Tela(49); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList; + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + RegistroLog registroLog1 = registroLog; + using (UnitOfWork commited = Instancia.Commited) + { + (new BaseServico()).SaveLog(registroLog1, commited); + commited.Commit(); + } + } + Parameters parameter = new Parameters(); + parameter.set_Beta(ApplicationHelper.Beta); + parameter.set_Type(7); + parameter.set_Application("Agger.Gestor.exe"); + parameter.set_Directory(""); + parameter.set_Run(false); + (new DownloadWindow(parameter)).Show(); + (new MainWindow()).Show(); + base.Close(); + } + } + else + { + this.Loading(false); + this.UserBox.Focus(); + } + } + } + + private async void Acessar_Click(object sender, RoutedEventArgs e) + { + ((RepeatButton)sender).Click -= new RoutedEventHandler(this.Acessar_Click); + await this.Access(true); + ((RepeatButton)sender).Click += new RoutedEventHandler(this.Acessar_Click); + } + + private void CancelarRegistro(object sender, RoutedEventArgs e) + { + this.ViewModel.FecharRegistro(); + } + + private void CancelarTrocaSenha_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.TrocaSenhaVisibility = System.Windows.Visibility.Collapsed; + this.ViewModel.LoginVisibility = System.Windows.Visibility.Visible; + } + + private void CentralAtendimento_OnPreviewMouseDown(object sender, MouseButtonEventArgs e) + { + Process.Start(new ProcessStartInfo() + { + FileName = this.ViewModel.CentralAtendimento, + UseShellExecute = true + }); + } + + public void CloseButton_Click() + { + base.Close(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/loginwindow.xaml", UriKind.Relative)); + } + + private void LinkImage_MouseDown(object sender, MouseButtonEventArgs e) + { + Process.Start(new ProcessStartInfo() + { + FileName = this.ViewModel.ImagemLink, + UseShellExecute = true + }); + } + + private void Loading(bool isLoading) + { + this.ViewModel.EnableFields = !isLoading; + this.ViewModel.LoadingVisibility = isLoading; + this.ViewModel.FieldsVisibility = !isLoading; + base.IsEnabled = !isLoading; + } + + private async void LoginWindow_OnLoaded(object sender, RoutedEventArgs e) + { + this.Loading(true); + await this.ViewModel.GetCfgJson(); + await this.SearchImage(); + this.ViewModel.EnableButtons = false; + LicenseHelper licenseHelper = new LicenseHelper(); + bool flag = await licenseHelper.VerificarRegistro(); + if (!flag) + { + string str = await licenseHelper.FindKey(); + bool flag1 = false; + if (str != null) + { + await licenseHelper.Registrar(str); + flag1 = true; + } + if (str == null && !string.IsNullOrWhiteSpace(Recursos.Registrar)) + { + await licenseHelper.Registrar(Recursos.Registrar); + flag1 = true; + } + if (flag1) + { + flag = await licenseHelper.VerificarRegistro(); + } + str = null; + } + if (!flag) + { + this.Loading(false); + this.ViewModel.AbrirRegistro(); + this.ViewModel.EnableButtons = true; + } + else + { + Tuple tuple = await licenseHelper.VerificarAcesso(); + if (tuple.Item1) + { + ConnectionHelper connectionHelper = new ConnectionHelper(); + Tuple tuple1 = await connectionHelper.PrimeiroAcesso(); + if (Gestor.Application.Helpers.Connection.ConnectionAddress == null || Gestor.Application.Helpers.Connection.ConnectionAddress.get_Type() == 4) + { + this.Loading(false); + this.ViewModel.AcessoNegado("Erro de conexão com Banco Gestor.\nEntre em contato com Suporte!"); + } + else if (!tuple1.Item1 || !tuple1.Item2) + { + (new TutorialView(tuple1)).Show(); + base.Close(); + } + else + { + Tuple tuple2 = await licenseHelper.VerificarVersao(); + if (tuple2.Item1) + { + Task.Run(() => { + try + { + if (!connectionHelper.BDConvertido()) + { + (new BaseServico()).BuscarEmpresa((long)1); + } + } + catch + { + } + }); + this.Loading(false); + if (!string.IsNullOrWhiteSpace(this.UserBox.Text)) + { + this.PasswordBox.PasswordBox.Focus(); + } + else + { + this.UserBox.Focus(); + } + this.ViewModel.EnableButtons = true; + string result = Gestor.Application.Helpers.Connection.Get(string.Concat("Customer/Name/", ApplicationHelper.NumeroSerial), true, false).Result; + this.ViewModel.Head = result; + } + else + { + this.Loading(false); + this.ViewModel.AcessoNegado(tuple2.Item2); + } + } + } + else + { + this.Loading(false); + this.ViewModel.AcessoNegado(tuple.Item2); + } + } + licenseHelper = null; + } + + public void MinimizeButton_Click() + { + base.WindowState = System.Windows.WindowState.Minimized; + } + + private void NovoPerfil_OnPreviewMouseDown(object sender, MouseButtonEventArgs e) + { + this.ViewModel.AbrirRegistro(); + this.ViewModel.EnableButtons = true; + } + + protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) + { + Size newSize; + base.OnRenderSizeChanged(sizeInfo); + if (sizeInfo.HeightChanged) + { + double top = base.Top; + double height = sizeInfo.PreviousSize.Height; + newSize = sizeInfo.NewSize; + base.Top = top + (height - newSize.Height) / 2; + } + if (sizeInfo.WidthChanged) + { + double left = base.Left; + double width = sizeInfo.PreviousSize.Width; + newSize = sizeInfo.NewSize; + base.Left = left + (width - newSize.Width) / 2; + } + } + + private async void PasswordBox_OnKeyDown(object sender, KeyEventArgs e) + { + if (e.Key == Key.Return) + { + await this.Access(true); + } + } + + private async void Registrar_OnClick(object sender, RoutedEventArgs e) + { + this.Loading(true); + LicenseHelper licenseHelper = new LicenseHelper(); + string str = await licenseHelper.Registrar(this.ViewModel.Chave); + if (str != "false") + { + if (str == "root") + { + await this.ViewModel.ShowMessage("CHAVE JÁ REGISTRADA ANTERIORMENTE.", "OK", "", false); + } + this.ViewModel.FecharRegistro(); + string result = Gestor.Application.Helpers.Connection.Get(string.Concat("Customer/Name/", ApplicationHelper.NumeroSerial), true, false).Result; + this.ViewModel.Head = result; + Tuple tuple = await licenseHelper.VerificarAcesso(); + if (tuple.Item1) + { + Tuple tuple1 = await (new ConnectionHelper()).PrimeiroAcesso(); + if (!tuple1.Item1 || !tuple1.Item2) + { + (new TutorialView(tuple1)).Show(); + base.Close(); + } + else + { + this.Loading(false); + await this.Access(false); + } + } + else + { + this.Loading(false); + this.ViewModel.AcessoNegado(tuple.Item2); + } + } + else + { + await this.ViewModel.ShowMessage("CHAVE INVÁLIDA", "OK", "", false); + this.Loading(false); + this.ViewModel.AbrirRegistro(); + } + licenseHelper = null; + } + + private async Task SearchImage() + { + string str2; + string str3; + try + { + using (HttpClient httpClient = new HttpClient()) + { + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + httpClient.set_Timeout(TimeSpan.FromSeconds(30)); + string stringAsync = await httpClient.GetStringAsync(Address.get_LoginJsonV2()); + this.LoginSettings = JArray.Parse(stringAsync); + DateTime now = DateTime.Now; + foreach (JToken jToken2 in this.LoginSettings.Where((JToken x) => { + DateTime dateTime; + DateTime dateTime1; + bool flag; + List list; + string str; + string str1; + JToken item = x.get_Item("Ativo"); + flag = (item != null ? Extensions.Value(item) : false); + if (!flag) + { + return false; + } + JToken jToken = x.get_Item("Produto"); + if (jToken != null) + { + list = jToken.Values().ToList(); + } + else + { + list = null; + } + List nums = list; + if (nums != null) + { + List nums1 = nums; + Func u003cu003e9_201 = LoginWindow.u003cu003ec.u003cu003e9__20_1; + if (u003cu003e9_201 == null) + { + u003cu003e9_201 = (int p) => { + if (p == 0) + { + return true; + } + return p == 3; + }; + LoginWindow.u003cu003ec.u003cu003e9__20_1 = u003cu003e9_201; + } + if (nums1.Any(u003cu003e9_201)) + { + JToken item1 = x.get_Item("Inicio"); + if (item1 != null) + { + str = item1.ToString(); + } + else + { + str = null; + } + bool flag1 = DateTime.TryParse(str, out dateTime); + JToken jToken1 = x.get_Item("Fim"); + if (jToken1 != null) + { + str1 = jToken1.ToString(); + } + else + { + str1 = null; + } + bool flag2 = DateTime.TryParse(str1, out dateTime1); + if (flag1 & flag2) + { + if (now < dateTime) + { + return false; + } + return now <= dateTime1; + } + if (flag1) + { + return now >= dateTime; + } + if (!flag2) + { + return true; + } + return now <= dateTime1; + } + } + return false; + })) + { + ObservableCollection loginImages = this.ViewModel.LoginImages; + LoginImageModel loginImageModel = new LoginImageModel(); + JToken jToken3 = jToken2.get_Item("Imagem"); + if (jToken3 != null) + { + str2 = jToken3.ToString(); + } + else + { + str2 = null; + } + loginImageModel.Imagem = str2; + JToken jToken4 = jToken2.get_Item("UrlFixa"); + if (jToken4 != null) + { + str3 = jToken4.ToString(); + } + else + { + str3 = null; + } + loginImageModel.UrlFixa = str3; + loginImages.Add(loginImageModel); + } + this.ViewModel.SelectedImage = this.ViewModel.LoginImages.FirstOrDefault(); + base.Dispatcher.Invoke(new Action(this.StartCarousel)); + } + httpClient = null; + } + catch + { + } + } + + private void StartCarousel() + { + if (this.ViewModel.LoginImages.Count <= 1) + { + return; + } + this._carouselTimer = new DispatcherTimer() + { + Interval = TimeSpan.FromSeconds(10) + }; + this._carouselTimer.Tick += new EventHandler((object s, EventArgs e) => { + int num = (this.ViewModel.LoginImages.IndexOf(this.ViewModel.SelectedImage) + 1) % this.ViewModel.LoginImages.Count; + this.ViewModel.SelectedImage = this.ViewModel.LoginImages[num]; + }); + this._carouselTimer.Start(); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((LoginWindow)target).Loaded += new RoutedEventHandler(this.LoginWindow_OnLoaded); + return; + } + case 2: + { + this.ProgressRing = (Image)target; + return; + } + case 3: + { + this.UserBox = (TextBox)target; + return; + } + case 4: + { + this.PasswordBox = (CustomSenhaLoginBox)target; + return; + } + case 5: + { + this.TrocaSenha = (TextBlock)target; + this.TrocaSenha.PreviewMouseDown += new MouseButtonEventHandler(this.TrocarSenha_OnPreviewMouseDown); + return; + } + case 6: + { + ((RepeatButton)target).Click += new RoutedEventHandler(this.Acessar_Click); + return; + } + case 7: + { + ((TextBlock)target).PreviewMouseDown += new MouseButtonEventHandler(this.NovoPerfil_OnPreviewMouseDown); + return; + } + case 8: + { + this.SenhaBox = (CustomSenhaLoginBox)target; + return; + } + case 9: + { + this.ConfirmacaoBox = (CustomSenhaLoginBox)target; + return; + } + case 10: + { + ((RepeatButton)target).Click += new RoutedEventHandler(this.CancelarTrocaSenha_OnClick); + return; + } + case 11: + { + ((RepeatButton)target).Click += new RoutedEventHandler(this.TrocarSenha_OnClick); + return; + } + case 12: + { + ((TextBlock)target).PreviewMouseDown += new MouseButtonEventHandler(this.CentralAtendimento_OnPreviewMouseDown); + return; + } + case 13: + { + this.ChaveBox = (TextBox)target; + return; + } + case 14: + { + ((RepeatButton)target).Click += new RoutedEventHandler(this.CancelarRegistro); + return; + } + case 15: + { + ((RepeatButton)target).Click += new RoutedEventHandler(this.Registrar_OnClick); + return; + } + case 16: + { + this.MinimizeButton = (Grid)target; + this.MinimizeButton.MouseLeftButtonDown += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonDown); + this.MinimizeButton.MouseLeftButtonUp += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonUp); + return; + } + case 17: + { + this.CloseButton = (Grid)target; + this.CloseButton.MouseLeftButtonDown += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonDown); + this.CloseButton.MouseLeftButtonUp += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonUp); + return; + } + } + this._contentLoaded = true; + } + + private static void TopControls_OnMouseEnter(object sender, MouseEventArgs e) + { + ((Grid)sender).Background = (((Grid)sender).Name == "CloseButton" ? new SolidColorBrush((Color)System.Windows.Application.Current.Resources["AggerYellow100"]) : new SolidColorBrush(Colors.Gray)); + Path child = VisualTreeHelper.GetChild((Grid)sender, 0) as Path; + if (child != null) + { + child.Stroke = new SolidColorBrush(Colors.White); + } + } + + private void TopControls_OnMouseLeave(object sender, MouseEventArgs e) + { + this._buttonClickable = false; + ((Grid)sender).Background = new SolidColorBrush(Colors.Transparent); + Path child = VisualTreeHelper.GetChild((Grid)sender, 0) as Path; + if (child != null) + { + child.Stroke = (((Grid)sender).Name == "CloseButton" ? new SolidColorBrush((Color)System.Windows.Application.Current.Resources["AggerYellow100"]) : new SolidColorBrush(Colors.DimGray)); + } + } + + private void TopControls_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e) + { + this._buttonClickable = true; + ((Grid)sender).Background = (((Grid)sender).Name == "CloseButton" ? new SolidColorBrush(Colors.DarkGoldenrod) : new SolidColorBrush(Colors.DimGray)); + } + + private void TopControls_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e) + { + if (this._buttonClickable) + { + MethodInfo method = base.GetType().GetMethod(string.Concat(((Grid)sender).Name, "_Click")); + if (method == null) + { + return; + } + method.Invoke(this, null); + } + } + + private async void TrocarSenha_OnClick(object sender, RoutedEventArgs e) + { + this.Loading(true); + bool flag = await this.ViewModel.TrocaSenha(); + this.Loading(false); + if (flag) + { + await this.Access(true); + } + } + + private async void TrocarSenha_OnPreviewMouseDown(object sender, MouseButtonEventArgs e) + { + this.Loading(true); + await this.ViewModel.AbrirTrocaSenha(); + this.Loading(false); + } + + private async Task VerificarAcesso() + { + bool flag; + Instalacao instalacao; + LicenseHelper licenseHelper = new LicenseHelper(); + Tuple tuple = await licenseHelper.VerificarAcesso(); + if (tuple.Item1) + { + if (!this.ViewModel.Login.Contains("AGGER@")) + { + bool flag1 = false; + if (!await licenseHelper.VerificarMaquina()) + { + this.Loading(false); + while (!flag1) + { + List instalacoes = await licenseHelper.GetInstalacoes(); + if (instalacoes.Count != 0) + { + List instalacaos = instalacoes; + IOrderedEnumerable ultimoAcesso = + from x in instalacaos + orderby x.get_UltimoAcesso() descending + select x; + Instalacao instalacao1 = ultimoAcesso.FirstOrDefault((Instalacao x) => x.get_UsuarioId() == Recursos.Usuario.get_Id()); + bool flag2 = instalacao1 != null; + if (flag2) + { + flag2 = await this.ViewModel.ShowMessage(string.Concat("SEU ULTIMO ACESSO FOI NA MAQUINA ", instalacao1.get_NomeMaquina(), ". DESEJA SUBSTITUIR A LICENÇA PARA ESSA MAQUINA?"), "SIM", "NÃO", false); + } + if (!flag2) + { + instalacao = await this.ViewModel.ShowInstalacoes(instalacoes); + } + else + { + instalacao = instalacao1; + } + Instalacao instalacao2 = instalacao; + if (instalacao2 != null) + { + this.Loading(true); + await (new AjudaServico()).ExcluirInstalacao(instalacao2.get_Id()); + await Task.Delay(15000); + flag2 = await licenseHelper.VerificarMaquina(); + flag1 = flag2; + this.Loading(false); + instalacoes = null; + instalacao1 = null; + } + else + { + this.ViewModel.AcessoNegado("MÁQUINA NÃO REGISTRADA"); + flag = true; + licenseHelper = null; + return flag; + } + } + else + { + this.ViewModel.AcessoNegado("ACESSO NEGADO, NÃO EXISTEM LICENÇAS VÁLIDAS."); + flag = true; + licenseHelper = null; + return flag; + } + } + } + } + Tuple tuple1 = await licenseHelper.VerificarVersao(); + if (tuple1.Item1) + { + string str = await (new ConnectionHelper()).AtualizarBanco(); + if (str == null) + { + if (!await this.ViewModel.Load()) + { + base.Close(); + } + flag = false; + } + else + { + await this.ViewModel.ShowMessage(str, "OK", "", false); + flag = false; + } + } + else + { + this.Loading(false); + this.ViewModel.AcessoNegado(tuple1.Item2); + flag = true; + } + } + else + { + this.Loading(false); + this.ViewModel.AcessoNegado(tuple.Item2); + flag = true; + } + licenseHelper = null; + return flag; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Menus/DashboardView.cs b/Codemerx/Gestor.Application/Views/Menus/DashboardView.cs new file mode 100644 index 0000000..1b130e6 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Menus/DashboardView.cs @@ -0,0 +1,1002 @@ +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Application.Views.Seguros; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios.ClientesAtivosInativos; +using Gestor.Model.Domain.Relatorios.Dashboard; +using Gestor.Model.Domain.Relatorios.Renovacao; +using Gestor.Model.Domain.Seguros; +using MaterialDesignThemes.Wpf; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Views.Menus +{ + public class DashboardView : BaseUserControl, IComponentConnector, IStyleConnector + { + internal Chip UsuarioChip; + + internal Button TileRenovacao; + + internal Button TileAniversariantes; + + internal Button TileTarefas; + + internal Button TileSinistro; + + internal Button TileProspeccao; + + internal TextBox TituloBox; + + internal TextBox DescricaoBox; + + internal Grid RenovacaoGrid; + + internal Grid AniversariantesGrid; + + internal Grid TarefasGrid; + + internal Grid ProspeccaoGrid; + + internal DatePicker InicioBox; + + internal DatePicker FimBox; + + internal ComboBox FiltroDocumento; + + internal Grid SinistroGrid; + + internal DatePicker InicioBox2; + + internal DatePicker FimBox2; + + private bool _contentLoaded; + + public DashboardViewModel ViewModel + { + get; + set; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public DashboardView(DashboardViewModel viewModel) + { + base.Tag = "DASHBOARD"; + this.ViewModel = viewModel; + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + + private async void AbrirAniversariante_OnClick(object sender, RoutedEventArgs e) + { + ClientesAtivosInativos dataContext = (ClientesAtivosInativos)((Button)sender).DataContext; + Cliente cliente = await (new ClienteServico()).BuscarClienteAsync(dataContext.get_EntidadeCliente().get_Id()); + double? nullable = null; + double? nullable1 = nullable; + nullable = null; + (new HosterWindow(new ClienteView(cliente, true, null), string.Concat("CADASTRO DE CLIENTES - ", cliente.get_Nome()), nullable1, nullable, false)).ShowDialog(); + } + + private async Task AbrirProspeccao(Prospeccao data) + { + bool flag; + this.InicioBox.Text = ValidationHelper.FormatDate(this.InicioBox.Text); + this.FimBox.Text = ValidationHelper.FormatDate(this.FimBox.Text); + while (true) + { + data = await this.ViewModel.ShowProspeccaoDialog(data); + if (data == null) + { + return; + } + List> keyValuePairs = await this.ViewModel.SalvarProspeccao(data); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + if (flag) + { + break; + } + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + this.ViewModel.ToggleSnackBar("PROSPECÇÃO SALVA COM SUCESSO.", true); + await this.CarregarForce(); + return; + } + + private async void AbrirRenovacao_OnClick(object sender, RoutedEventArgs e) + { + Renovacao dataContext = (Renovacao)((Button)sender).DataContext; + if (dataContext.get_Documento() != null) + { + Documento documento = await (new ApoliceServico()).BuscarApoliceAsync(dataContext.get_Documento().get_Id(), false, false); + double? nullable = null; + double? nullable1 = nullable; + nullable = null; + (new HosterWindow(new ApoliceView(documento, true, false, 0, (long)0, false), string.Concat("CADASTRO DE APÓLICES - ", documento.get_Controle().get_Cliente().get_Nome()), nullable1, nullable, false)).Show(); + } + else + { + this.ViewModel.Loading(true); + await this.AbrirProspeccao(dataContext.get_Prospeccao()); + this.ViewModel.Loading(false); + } + } + + private async void AbrirSinistro_OnClick(object sender, RoutedEventArgs e) + { + Button button = (Button)sender; + if (button.DataContext != null) + { + Sinistro dataContext = (Sinistro)button.DataContext; + if (dataContext != null) + { + dataContext = await this.ViewModel.CarregaSinistroApolice(dataContext.get_Id()); + Item item = dataContext.get_ControleSinistro().get_Item(); + SinistroView sinistroView = new SinistroView(item, false); + string[] nome = new string[] { "CADASTRO DE SINISTROS - ", item.get_Documento().get_Controle().get_Cliente().get_Nome(), " - ", item.get_Documento().get_Apolice(), " ", item.get_Documento().get_Endosso() }; + double? nullable = null; + double? nullable1 = nullable; + nullable = null; + (new HosterWindow(sinistroView, string.Concat(nome), nullable1, nullable, false)).Show(); + } + } + } + + private void AbrirTarefa_OnClick(object sender, RoutedEventArgs e) + { + Tarefa dataContext = (Tarefa)((Button)sender).DataContext; + this.ViewModel.ShowDrawer(new TarefaDrawer(dataContext, true), 0, false); + } + + private void AdicionarNota_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.EnableFields = true; + this.TituloBox.Text = string.Empty; + this.DescricaoBox.Text = string.Empty; + this.ViewModel.Publica = false; + } + + private void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.EnableFields = false; + } + + private async Task Carregar() + { + this.ViewModel.Loading(true); + this.RenovacaoGrid.Visibility = System.Windows.Visibility.Collapsed; + this.AniversariantesGrid.Visibility = System.Windows.Visibility.Collapsed; + this.TarefasGrid.Visibility = System.Windows.Visibility.Collapsed; + this.ProspeccaoGrid.Visibility = System.Windows.Visibility.Collapsed; + this.SinistroGrid.Visibility = System.Windows.Visibility.Collapsed; + if (this.ViewModel.Filtros == null) + { + await this.ViewModel.CarregarFiltros(); + } + await this.ViewModel.CarregarNotas(); + switch (this.ViewModel.SelectedTile) + { + case 1: + { + await this.ViewModel.CarregarRenovacoes(false); + this.RenovacaoGrid.Visibility = System.Windows.Visibility.Visible; + break; + } + case 2: + { + await this.ViewModel.CarregarAniversariantes(false); + this.AniversariantesGrid.Visibility = System.Windows.Visibility.Visible; + break; + } + case 3: + { + await this.ViewModel.CarregarTarefas(false); + this.TarefasGrid.Visibility = System.Windows.Visibility.Visible; + break; + } + case 4: + { + DashboardViewModel viewModel = this.ViewModel; + DateTime value = this.InicioBox.SelectedDate.Value; + await viewModel.CarregarProspect(value, this.FimBox.SelectedDate.Value); + this.ProspeccaoGrid.Visibility = System.Windows.Visibility.Visible; + break; + } + case 5: + { + await this.ViewModel.CarregarSinistros(false); + this.SinistroGrid.Visibility = System.Windows.Visibility.Visible; + break; + } + } + this.ViewModel.Loading(false); + } + + private async Task CarregarForce() + { + this.ViewModel.Loading(true); + this.RenovacaoGrid.Visibility = System.Windows.Visibility.Collapsed; + this.AniversariantesGrid.Visibility = System.Windows.Visibility.Collapsed; + this.TarefasGrid.Visibility = System.Windows.Visibility.Collapsed; + this.ProspeccaoGrid.Visibility = System.Windows.Visibility.Collapsed; + this.SinistroGrid.Visibility = System.Windows.Visibility.Collapsed; + await this.ViewModel.CarregarFiltros(); + List restricoes = this.ViewModel.Restricoes; + bool flag = restricoes.Any((RestricaoUsuario x) => { + if (x.get_Tipo() != 24) + { + return false; + } + return x.get_Restricao(); + }); + List restricaoUsuarios = this.ViewModel.Restricoes; + bool flag1 = restricaoUsuarios.Any((RestricaoUsuario x) => { + if (x.get_Tipo() != 49) + { + return false; + } + return x.get_Restricao(); + }); + List restricoes1 = this.ViewModel.Restricoes; + bool flag2 = restricoes1.Any((RestricaoUsuario x) => { + if (x.get_Tipo() != 19) + { + return false; + } + return x.get_Restricao(); + }); + List restricaoUsuarios1 = this.ViewModel.Restricoes; + bool flag3 = restricaoUsuarios1.Any((RestricaoUsuario x) => { + if (x.get_Tipo() != 25) + { + return false; + } + return x.get_Restricao(); + }); + if (!flag) + { + await this.ViewModel.CarregarRenovacoes(true); + } + if (!flag1) + { + await this.ViewModel.CarregarAniversariantes(true); + } + if (!flag2) + { + await this.ViewModel.CarregarTarefas(true); + } + if (!flag3) + { + await this.ViewModel.CarregarSinistros(true); + } + await this.ViewModel.CarregarNotas(); + switch (this.ViewModel.SelectedTile) + { + case 1: + { + this.RenovacaoGrid.Visibility = System.Windows.Visibility.Visible; + break; + } + case 2: + { + this.AniversariantesGrid.Visibility = System.Windows.Visibility.Visible; + break; + } + case 3: + { + this.TarefasGrid.Visibility = System.Windows.Visibility.Visible; + break; + } + case 4: + { + this.ProspeccaoGrid.Visibility = System.Windows.Visibility.Visible; + break; + } + case 5: + { + this.SinistroGrid.Visibility = System.Windows.Visibility.Visible; + break; + } + } + this.ViewModel.Loading(false); + } + + private async void ContentLoad() + { + DateTime? selectedDate; + this.UsuarioChip.Content = Recursos.Usuario.get_Nome(); + await this.ViewModel.BuscarRestricoes(); + await this.ViewModel.CarregarNotas(); + await this.ViewModel.CarregarFiltros(); + List restricoes = this.ViewModel.Restricoes; + bool flag = restricoes.Any((RestricaoUsuario x) => { + if (x.get_Tipo() != 24) + { + return false; + } + return x.get_Restricao(); + }); + List restricaoUsuarios = this.ViewModel.Restricoes; + bool flag1 = restricaoUsuarios.Any((RestricaoUsuario x) => { + if (x.get_Tipo() != 49) + { + return false; + } + return x.get_Restricao(); + }); + List permissoes = this.ViewModel.Permissoes; + bool flag2 = permissoes.Any((PermissaoUsuario x) => { + if (x.get_Tela() != 38) + { + return false; + } + return !x.get_Consultar(); + }); + bool hasValue = !Recursos.Usuario.get_PermissaoAggilizador().HasValue; + List restricoes1 = this.ViewModel.Restricoes; + bool flag3 = restricoes1.Any((RestricaoUsuario x) => { + if (x.get_Tipo() != 25) + { + return false; + } + return x.get_Restricao(); + }); + this.FiltroDocumento.SelectedIndex = 0; + List tasks = new List(); + if (hasValue) + { + this.TileProspeccao.Visibility = System.Windows.Visibility.Collapsed; + } + else + { + this.ViewModel.CarregarRamos(); + this.TileProspeccao.Visibility = System.Windows.Visibility.Visible; + if (!this.InicioBox.SelectedDate.HasValue) + { + this.InicioBox.SelectedDate = new DateTime?(DateTime.Today); + } + if (!this.FimBox.SelectedDate.HasValue) + { + DatePicker fimBox = this.FimBox; + selectedDate = this.InicioBox.SelectedDate; + fimBox.SelectedDate = new DateTime?(selectedDate.Value); + } + DashboardViewModel viewModel = this.ViewModel; + DateTime value = this.InicioBox.SelectedDate.Value; + selectedDate = this.FimBox.SelectedDate; + tasks.Add(viewModel.CarregarProspect(value, selectedDate.Value)); + } + if (flag2) + { + this.TileTarefas.Visibility = System.Windows.Visibility.Collapsed; + } + else + { + this.TileTarefas.Visibility = System.Windows.Visibility.Visible; + this.ViewModel.SelectedTile = 3; + tasks.Add(this.ViewModel.CarregarTarefas(false)); + } + if (flag1) + { + this.TileAniversariantes.Visibility = System.Windows.Visibility.Collapsed; + } + else + { + this.TileAniversariantes.Visibility = System.Windows.Visibility.Visible; + this.ViewModel.SelectedTile = 2; + tasks.Add(this.ViewModel.CarregarAniversariantes(false)); + } + if (flag3) + { + this.TileSinistro.Visibility = System.Windows.Visibility.Collapsed; + } + else + { + this.TileSinistro.Visibility = System.Windows.Visibility.Visible; + this.ViewModel.SelectedTile = 5; + tasks.Add(this.ViewModel.CarregarSinistros(false)); + } + if (flag) + { + this.TileRenovacao.Visibility = System.Windows.Visibility.Collapsed; + } + else + { + this.TileRenovacao.Visibility = System.Windows.Visibility.Visible; + this.ViewModel.SelectedTile = 1; + tasks.Add(this.ViewModel.CarregarRenovacoes(false)); + } + await Task.WhenAll(tasks); + this.ViewModel.Load = false; + } + + private void DatePicker_OnSelectedDateChanged(object sender, SelectionChangedEventArgs e) + { + this.ViewModel.LimparProspeccao(); + } + + private async void EnviarPorWhatsApp_OnClick(object sender, RoutedEventArgs e) + { + string str; + if (!this.ViewModel.Restricao(32)) + { + Button button = (Button)sender; + if (button.DataContext != null) + { + ClienteTelefone dataContext = button.DataContext as ClienteTelefone; + if (dataContext != null) + { + str = (!dataContext.get_Tipo().HasValue || dataContext.get_Tipo().GetValueOrDefault() != 8 ? string.Concat("55", dataContext.get_Prefixo(), dataContext.get_Numero().Clear()) : string.Concat(dataContext.get_Prefixo(), dataContext.get_Numero()).Clear()); + if (!str.EnviarWhatsapp(this.ViewModel.Anotacoes)) + { + await this.ViewModel.ShowMessage("HOUVE UM PROBLEMA AO ABRIR LINK DO WHATSAPP, O LINK FOI COPIADO EM SUA MAQUINA, BASTA ABRIR O NAVEGADOR DE INTERNET E COLAR NA BARRA DE ENDEREÇOS", "OK", "", false); + } + return; + } + } + } + else + { + await this.ViewModel.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR O WHATSAPP", "OK", "", false); + } + } + + private async void ExcluirNota_OnClick(object sender, RoutedEventArgs e) + { + Tarefa dataContext = ((Button)sender).DataContext as Tarefa; + if (dataContext != null) + { + await this.ViewModel.ExcluirNota(dataContext); + await this.ViewModel.CarregarNotas(); + } + } + + private void FiltroCliente_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + this.ViewModel.LimparProspeccao(); + } + + private async void GerarCsv_OnClick(object sender, RoutedEventArgs e) + { + DateTime date = DateTime.Now.Date; + string.Concat("NovosNegocios", date.ToString("d").Replace("/", ""), ".csv"); + if (this.ViewModel.Prospeccoes.Count != 0) + { + this.ViewModel.Loading(true); + await this.ViewModel.GerarCsv(); + this.ViewModel.Loading(false); + } + else + { + await this.ViewModel.ShowMessage("NÃO HÁ DADOS A SEREM EXPORTADOS NO .CSV", "OK", "", false); + } + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/menus/dashboardview.xaml", UriKind.Relative)); + } + + private async void NotaConcluida_OnClick(object sender, RoutedEventArgs e) + { + Tarefa dataContext = ((Button)sender).DataContext as Tarefa; + if (dataContext != null) + { + dataContext.set_Conclusao(new DateTime?(Funcoes.GetNetworkTime())); + dataContext.set_Status(2); + await this.ViewModel.SalvarNota(dataContext); + await this.ViewModel.CarregarNotas(); + } + } + + private void PopupBox_OnClosed(object sender, RoutedEventArgs e) + { + this.ViewModel.Anotacoes = ""; + } + + private void PopupBoxAniversariante_OnOpened(object sender, RoutedEventArgs e) + { + ClientesAtivosInativos dataContext = (ClientesAtivosInativos)((PopupBox)sender).DataContext; + this.ViewModel.Telefones = dataContext.get_EntidadeCliente().get_Telefones(); + } + + private void PopupBoxProspeccao_OnOpened(object sender, RoutedEventArgs e) + { + Prospectar dataContext = (Prospectar)((PopupBox)sender).DataContext; + this.ViewModel.Telefones = dataContext.get_EntidadeCliente().get_Telefones(); + } + + private void PopupBoxRenovacao_OnOpened(object sender, RoutedEventArgs e) + { + PopupBox popupBox = (PopupBox)sender; + ObservableCollection observableCollection = new ObservableCollection(); + Renovacao dataContext = (Renovacao)popupBox.DataContext; + if (dataContext.get_Documento() == null) + { + if (!string.IsNullOrEmpty(dataContext.get_Prospeccao().get_Telefone1())) + { + ClienteTelefone clienteTelefone = new ClienteTelefone(); + clienteTelefone.set_Prefixo(dataContext.get_Prospeccao().get_Prefixo1()); + clienteTelefone.set_Numero(dataContext.get_Prospeccao().get_Telefone1()); + observableCollection.Add(clienteTelefone); + } + if (!string.IsNullOrEmpty(dataContext.get_Prospeccao().get_Telefone2())) + { + ClienteTelefone clienteTelefone1 = new ClienteTelefone(); + clienteTelefone1.set_Prefixo(dataContext.get_Prospeccao().get_Prefixo2()); + clienteTelefone1.set_Numero(dataContext.get_Prospeccao().get_Telefone2()); + observableCollection.Add(clienteTelefone1); + } + } + else + { + observableCollection = dataContext.get_Documento().get_Controle().get_Cliente().get_Telefones(); + } + this.ViewModel.Telefones = observableCollection; + } + + private void Ramo_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + this.ViewModel.LimparProspeccao(); + } + + private void Referencia_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + this.ViewModel.LimparProspeccao(); + } + + private async void Refresh_OnClick(object sender, RoutedEventArgs e) + { + await this.CarregarForce(); + } + + private async void RefreshProspectar_OnClick(object sender, RoutedEventArgs e) + { + if (!this.InicioBox.SelectedDate.HasValue || !this.FimBox.SelectedDate.HasValue) + { + await this.ViewModel.ShowMessage("INÍCIO E FIM DEVEM ESTAR PREENCHIDOS.", "OK", "", false); + } + else if (this.InicioBox.SelectedDate.Value > this.FimBox.SelectedDate.Value) + { + await this.ViewModel.ShowMessage("INÍCIO NÃO DEVE SER MAIOR QUE O FIM.", "OK", "", false); + } + else if ((this.FimBox.SelectedDate.Value - this.InicioBox.SelectedDate.Value).TotalDays <= 31) + { + this.ViewModel.Loading(true); + DashboardViewModel viewModel = this.ViewModel; + DateTime value = this.InicioBox.SelectedDate.Value; + await viewModel.CarregarProspect(value, this.FimBox.SelectedDate.Value); + this.ProspeccaoGrid.Visibility = System.Windows.Visibility.Visible; + this.ViewModel.Loading(false); + } + else + { + await this.ViewModel.ShowMessage("O PERIODO TOTAL DO RELATÓRIO NÃO PODE SER MAIOR QUE 30 DIAS.", "OK", "", false); + } + } + + private async void RefreshSinsitro_OnClick(object sender, RoutedEventArgs e) + { + if (!this.InicioBox2.SelectedDate.HasValue || !this.FimBox2.SelectedDate.HasValue) + { + await this.ViewModel.ShowMessage("INÍCIO E FIM DEVEM ESTAR PREENCHIDOS.", "OK", "", false); + } + else if (this.InicioBox2.SelectedDate.Value > this.FimBox2.SelectedDate.Value) + { + await this.ViewModel.ShowMessage("INÍCIO NÃO DEVE SER MAIOR QUE O FIM.", "OK", "", false); + } + else if ((this.FimBox2.SelectedDate.Value - this.InicioBox2.SelectedDate.Value).TotalDays <= 31) + { + this.ViewModel.Loading(true); + DashboardViewModel viewModel = this.ViewModel; + DateTime value = this.InicioBox2.SelectedDate.Value; + await viewModel.CarregarSinistros(value, this.FimBox2.SelectedDate.Value); + this.SinistroGrid.Visibility = System.Windows.Visibility.Visible; + this.ViewModel.Loading(false); + } + else + { + await this.ViewModel.ShowMessage("O PERIODO TOTAL DO RELATÓRIO NÃO PODE SER MAIOR QUE 30 DIAS.", "OK", "", false); + } + } + + private async void SalvarNota_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + Tarefa tarefa = new Tarefa(); + tarefa.set_Agendamento(Funcoes.GetNetworkTime()); + tarefa.set_Titulo(this.TituloBox.Text); + tarefa.set_Anotacoes(this.DescricaoBox.Text); + tarefa.set_Usuario(Recursos.Usuario); + tarefa.set_UsuarioCadastro(Recursos.Usuario); + tarefa.set_Entidade(1); + tarefa.set_Status(0); + List> keyValuePairs = await this.ViewModel.Salvar(tarefa); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + else + { + this.ViewModel.ToggleSnackBar("NOTA SALVA COM SUCESSO.", true); + this.ViewModel.EnableFields = false; + await this.ViewModel.CarregarNotas(); + } + } + + private async void SarvarNota_OnClick(object sender, RoutedEventArgs e) + { + Tarefa dataContext = ((Button)sender).DataContext as Tarefa; + if (dataContext != null) + { + List> keyValuePairs = await this.ViewModel.Salvar(dataContext); + if (keyValuePairs != null && keyValuePairs.Count != 0) + { + await this.ViewModel.CarregarNotas(); + } + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.UsuarioChip = (Chip)target; + return; + } + case 2: + { + ((Button)target).Click += new RoutedEventHandler(this.Refresh_OnClick); + return; + } + case 3: + { + this.TileRenovacao = (Button)target; + this.TileRenovacao.Click += new RoutedEventHandler(this.TileRenovacao_OnClick); + return; + } + case 4: + { + this.TileAniversariantes = (Button)target; + this.TileAniversariantes.Click += new RoutedEventHandler(this.TileAniversariantes_OnClick); + return; + } + case 5: + { + this.TileTarefas = (Button)target; + this.TileTarefas.Click += new RoutedEventHandler(this.TileTarefas_OnClick); + return; + } + case 6: + { + this.TileSinistro = (Button)target; + this.TileSinistro.Click += new RoutedEventHandler(this.TileSinistro_OnClick); + return; + } + case 7: + { + this.TileProspeccao = (Button)target; + this.TileProspeccao.Click += new RoutedEventHandler(this.TileProspeccao_OnClick); + return; + } + case 8: + { + ((Button)target).Click += new RoutedEventHandler(this.AdicionarNota_OnClick); + return; + } + case 9: + { + ((Button)target).Click += new RoutedEventHandler(this.SalvarNota_OnClick); + return; + } + case 10: + { + ((Button)target).Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 11: + { + this.TituloBox = (TextBox)target; + return; + } + case 12: + { + this.DescricaoBox = (TextBox)target; + return; + } + case 13: + case 14: + case 16: + case 17: + case 18: + case 20: + case 21: + case 22: + case 24: + case 33: + case 34: + { + this._contentLoaded = true; + return; + } + case 15: + { + this.RenovacaoGrid = (Grid)target; + return; + } + case 19: + { + this.AniversariantesGrid = (Grid)target; + return; + } + case 23: + { + this.TarefasGrid = (Grid)target; + return; + } + case 25: + { + this.ProspeccaoGrid = (Grid)target; + return; + } + case 26: + { + ((ComboBox)target).SelectionChanged += new SelectionChangedEventHandler(this.Ramo_OnSelectionChanged); + return; + } + case 27: + { + ((ComboBox)target).SelectionChanged += new SelectionChangedEventHandler(this.Referencia_OnSelectionChanged); + return; + } + case 28: + { + this.InicioBox = (DatePicker)target; + this.InicioBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.InicioBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + this.InicioBox.SelectedDateChanged += new EventHandler(this.DatePicker_OnSelectedDateChanged); + return; + } + case 29: + { + this.FimBox = (DatePicker)target; + this.FimBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.FimBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + this.FimBox.SelectedDateChanged += new EventHandler(this.DatePicker_OnSelectedDateChanged); + return; + } + case 30: + { + this.FiltroDocumento = (ComboBox)target; + this.FiltroDocumento.SelectionChanged += new SelectionChangedEventHandler(this.FiltroCliente_OnSelectionChanged); + return; + } + case 31: + { + ((Button)target).Click += new RoutedEventHandler(this.RefreshProspectar_OnClick); + return; + } + case 32: + { + ((Button)target).Click += new RoutedEventHandler(this.GerarCsv_OnClick); + return; + } + case 35: + { + this.SinistroGrid = (Grid)target; + return; + } + case 36: + { + this.InicioBox2 = (DatePicker)target; + this.InicioBox2.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.InicioBox2.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + this.InicioBox2.SelectedDateChanged += new EventHandler(this.DatePicker_OnSelectedDateChanged); + return; + } + case 37: + { + this.FimBox2 = (DatePicker)target; + this.FimBox2.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.FimBox2.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + this.FimBox2.SelectedDateChanged += new EventHandler(this.DatePicker_OnSelectedDateChanged); + return; + } + case 38: + { + ((Button)target).Click += new RoutedEventHandler(this.RefreshSinsitro_OnClick); + return; + } + default: + { + this._contentLoaded = true; + return; + } + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + if (connectionId > 33) + { + if (connectionId == 34) + { + ((Button)target).Click += new RoutedEventHandler(this.EnviarPorWhatsApp_OnClick); + return; + } + if (connectionId != 39) + { + return; + } + ((Button)target).Click += new RoutedEventHandler(this.AbrirSinistro_OnClick); + } + else + { + switch (connectionId) + { + case 13: + { + ((Button)target).Click += new RoutedEventHandler(this.ExcluirNota_OnClick); + return; + } + case 14: + { + ((Button)target).Click += new RoutedEventHandler(this.NotaConcluida_OnClick); + return; + } + case 15: + case 19: + case 23: + { + return; + } + case 16: + { + ((Button)target).Click += new RoutedEventHandler(this.AbrirRenovacao_OnClick); + return; + } + case 17: + { + ((PopupBox)target).add_Opened(new RoutedEventHandler(this.PopupBoxRenovacao_OnOpened)); + ((PopupBox)target).add_Closed(new RoutedEventHandler(this.PopupBox_OnClosed)); + return; + } + case 18: + { + ((Button)target).Click += new RoutedEventHandler(this.EnviarPorWhatsApp_OnClick); + return; + } + case 20: + { + ((Button)target).Click += new RoutedEventHandler(this.AbrirAniversariante_OnClick); + return; + } + case 21: + { + ((PopupBox)target).add_Opened(new RoutedEventHandler(this.PopupBoxAniversariante_OnOpened)); + ((PopupBox)target).add_Closed(new RoutedEventHandler(this.PopupBox_OnClosed)); + return; + } + case 22: + { + ((Button)target).Click += new RoutedEventHandler(this.EnviarPorWhatsApp_OnClick); + return; + } + case 24: + { + ((Button)target).Click += new RoutedEventHandler(this.AbrirTarefa_OnClick); + return; + } + default: + { + if (connectionId == 33) + { + break; + } + else + { + return; + } + } + } + ((PopupBox)target).add_Opened(new RoutedEventHandler(this.PopupBoxProspeccao_OnOpened)); + ((PopupBox)target).add_Closed(new RoutedEventHandler(this.PopupBox_OnClosed)); + return; + } + } + + private async void TileAniversariantes_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.SelectedTile = 2; + await this.Carregar(); + } + + private async void TileProspeccao_OnClick(object sender, RoutedEventArgs e) + { + if (!this.InicioBox.SelectedDate.HasValue) + { + this.InicioBox.SelectedDate = new DateTime?(DateTime.Today); + } + if (!this.FimBox.SelectedDate.HasValue) + { + DatePicker fimBox = this.FimBox; + fimBox.SelectedDate = new DateTime?(this.InicioBox.SelectedDate.Value); + } + this.ViewModel.SelectedTile = 4; + await this.Carregar(); + } + + private async void TileRenovacao_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.SelectedTile = 1; + await this.Carregar(); + } + + private async void TileSinistro_OnClick(object sender, RoutedEventArgs e) + { + if (!this.InicioBox2.SelectedDate.HasValue) + { + this.InicioBox2.SelectedDate = new DateTime?(DateTime.Today); + } + if (!this.FimBox2.SelectedDate.HasValue) + { + this.FimBox2.SelectedDate = new DateTime?(DateTime.Today); + } + this.ViewModel.SelectedTile = 5; + await this.Carregar(); + } + + private async void TileTarefas_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.SelectedTile = 3; + await this.Carregar(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Menus/MenuItensView.cs b/Codemerx/Gestor.Application/Views/Menus/MenuItensView.cs new file mode 100644 index 0000000..b47ecd5 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Menus/MenuItensView.cs @@ -0,0 +1,375 @@ +using Gestor.Application.Actions; +using Gestor.Application.ViewModels; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Media; +using System.Windows.Threading; + +namespace Gestor.Application.Views.Menus +{ + public class MenuItensView : BaseUserControl, IComponentConnector, IStyleConnector + { + internal MenuItem ManterTodosButton; + + internal DataGrid ItemGrid; + + internal DataGridCheckBoxColumn CheckBoxColumn; + + internal DataGridTemplateColumn RenovarColumn; + + internal DataGridTemplateColumn CancelarColumn; + + internal DataGridTemplateColumn SubstituirColumn; + + internal DataGridTemplateColumn ReativarColumn; + + private bool _contentLoaded; + + public MenuItemViewModel ViewModel + { + get; + set; + } + + public MenuItensView(long ramo, ManutencaoItem manutencao = null) + { + base.Tag = "CADASTRO DE ITEM"; + this.ViewModel = new MenuItemViewModel(ramo, manutencao); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher != null) + { + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + else + { + } + this.ItemGrid.DataContext = base.DataContext; + this.HabilitarManutencao(manutencao); + Gestor.Application.Actions.Actions.ScrollToItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.ScrollToItem, new Action(this.ScrollToIndex)); + Gestor.Application.Actions.Actions.ScrollToItem = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.ScrollToItem, new Action(this.ScrollToIndex)); + } + + private void AutoCompleteBox_OnTextChanged(object sender, RoutedEventArgs e) + { + if (!string.IsNullOrWhiteSpace(((AutoCompleteBox)sender).get_Text())) + { + return; + } + this.ViewModel.FiltrarItem(""); + } + + private void AutoCompleteBox_Populating(object sender, PopulatingEventArgs e) + { + e.set_Cancel(true); + this.ViewModel.Filtrar(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void CancelarItem_OnClick(object sender, RoutedEventArgs e) + { + Button button = sender as Button; + if (button == null) + { + return; + } + if (button.DataContext == null) + { + return; + } + this.ViewModel.CancelarItem((Item)button.DataContext); + } + + private void ContentLoad() + { + this.ItemGrid.SelectionChanged += new SelectionChangedEventHandler(this.ItemGrid_OnSelectionChanged); + this.ItemGrid.MouseDoubleClick += new MouseButtonEventHandler((object sender, MouseButtonEventArgs args) => { + }); + } + + public Visual GetDescendantByType(Visual element, Type type) + { + if (element == null) + { + return null; + } + if (element.GetType() == type) + { + return element; + } + Visual descendantByType = null; + FrameworkElement frameworkElement = element as FrameworkElement; + if (frameworkElement != null) + { + frameworkElement.ApplyTemplate(); + } + for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++) + { + Visual child = VisualTreeHelper.GetChild(element, i) as Visual; + descendantByType = this.GetDescendantByType(child, type); + if (descendantByType != null) + { + break; + } + } + return descendantByType; + } + + private void HabilitarManutencao(ManutencaoItem manutencao) + { + this.RenovarColumn.Visibility = System.Windows.Visibility.Collapsed; + this.CancelarColumn.Visibility = System.Windows.Visibility.Collapsed; + this.SubstituirColumn.Visibility = System.Windows.Visibility.Collapsed; + this.ReativarColumn.Visibility = System.Windows.Visibility.Collapsed; + this.CheckBoxColumn.Visibility = System.Windows.Visibility.Collapsed; + this.ManterTodosButton.Visibility = System.Windows.Visibility.Collapsed; + if (manutencao == null) + { + return; + } + switch (manutencao.get_Tipo()) + { + case 0: + { + this.RenovarColumn.Visibility = System.Windows.Visibility.Visible; + this.CheckBoxColumn.Visibility = System.Windows.Visibility.Visible; + this.ManterTodosButton.Visibility = System.Windows.Visibility.Visible; + this.ViewModel.EndossoRenovacao = true; + return; + } + case 1: + { + this.RenovarColumn.Visibility = System.Windows.Visibility.Visible; + this.CancelarColumn.Visibility = System.Windows.Visibility.Visible; + this.SubstituirColumn.Visibility = System.Windows.Visibility.Visible; + this.ViewModel.EndossoRenovacao = true; + return; + } + case 2: + { + this.CancelarColumn.Visibility = System.Windows.Visibility.Visible; + this.ReativarColumn.Visibility = System.Windows.Visibility.Visible; + return; + } + default: + { + return; + } + } + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/menus/menuitensview.xaml", UriKind.Relative)); + } + + private void ItemGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + DataGrid dataGrid = (DataGrid)sender; + if (dataGrid != null && dataGrid.SelectedIndex < 0) + { + return; + } + if (!this.ViewModel.AlterandoSelectedItem) + { + this.ViewModel.SelecionaItem((Item)((dataGrid != null ? dataGrid.Items[dataGrid.SelectedIndex] : null))); + } + } + + private void ManterItem_OnClick(object sender, RoutedEventArgs e) + { + Button button = sender as Button; + if (button == null) + { + return; + } + if (button.DataContext == null) + { + return; + } + this.ViewModel.Manter((Item)button.DataContext); + } + + private void ManterItens_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.ManterItens(); + } + + private void ReativarItem_OnClick(object sender, RoutedEventArgs e) + { + Button button = sender as Button; + if (button == null) + { + return; + } + if (button.DataContext == null) + { + return; + } + this.ViewModel.Reativar((Item)button.DataContext); + } + + public void ScrollToIndex() + { + this.ScrollToIndex(this.ItemGrid, this.ItemGrid.SelectedIndex); + } + + public void ScrollToIndex(DataGrid grid, int index) + { + ScrollViewer descendantByType = this.GetDescendantByType(grid, typeof(ScrollViewer)) as ScrollViewer; + int num = (index - 5 > 0 ? index - 5 : 0); + if (descendantByType == null) + { + return; + } + descendantByType.ScrollToVerticalOffset((double)num); + } + + private void SubstituirItem_OnClick(object sender, RoutedEventArgs e) + { + Button button = sender as Button; + if (button == null) + { + return; + } + if (button.DataContext == null) + { + return; + } + this.ViewModel.Substituir((Item)button.DataContext); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, MenuItensView.AutoCompleteBox_Populating)); + ((AutoCompleteBox)target).add_TextChanged(new RoutedEventHandler(this.AutoCompleteBox_OnTextChanged)); + return; + } + case 2: + { + this.ManterTodosButton = (MenuItem)target; + this.ManterTodosButton.Click += new RoutedEventHandler(this.ManterItens_OnClick); + return; + } + case 3: + { + this.ItemGrid = (DataGrid)target; + return; + } + case 4: + { + this.CheckBoxColumn = (DataGridCheckBoxColumn)target; + return; + } + case 5: + { + this.RenovarColumn = (DataGridTemplateColumn)target; + return; + } + case 6: + case 8: + case 10: + { + this._contentLoaded = true; + return; + } + case 7: + { + this.CancelarColumn = (DataGridTemplateColumn)target; + return; + } + case 9: + { + this.SubstituirColumn = (DataGridTemplateColumn)target; + return; + } + case 11: + { + this.ReativarColumn = (DataGridTemplateColumn)target; + return; + } + default: + { + this._contentLoaded = true; + return; + } + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 6: + { + ((Button)target).Click += new RoutedEventHandler(this.ManterItem_OnClick); + return; + } + case 7: + case 9: + case 11: + { + return; + } + case 8: + { + ((Button)target).Click += new RoutedEventHandler(this.CancelarItem_OnClick); + return; + } + case 10: + { + ((Button)target).Click += new RoutedEventHandler(this.SubstituirItem_OnClick); + return; + } + case 12: + { + ((Button)target).Click += new RoutedEventHandler(this.ReativarItem_OnClick); + return; + } + default: + { + return; + } + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Relatorios/RelatorioView.cs b/Codemerx/Gestor.Application/Views/Relatorios/RelatorioView.cs new file mode 100644 index 0000000..69fdf01 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Relatorios/RelatorioView.cs @@ -0,0 +1,1167 @@ +using CurrencyTextBoxControl; +using Gestor.Application.Actions; +using Gestor.Application.Componentes; +using Gestor.Application.Drawers.Relatorios; +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Relatorios; +using Gestor.Application.Views.Ferramentas; +using Gestor.Application.Views.Generic; +using Gestor.Common.Helpers; +using Gestor.Common.Validation; +using Gestor.Model.API; +using Gestor.Model.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.MalaDireta; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using MaterialDesignThemes.Wpf; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; +using Xceed.Wpf.AvalonDock.Controls; + +namespace Gestor.Application.Views.Relatorios +{ + public class RelatorioView : BaseUserControl, IComponentConnector, IStyleConnector + { + internal RelatorioViewModel ViewModel; + + internal Image ProgressRing; + + internal ComboBox RelatorioBox; + + internal CurrencyTextBox ValorInicioBox; + + internal CurrencyTextBox ValorFimBox; + + internal DatePicker InicioBox; + + internal DatePicker FimBox; + + internal ToggleButton VisualizarRamosVendedoresTooltip; + + internal MenuItem GerarRelatorioButton; + + internal ComboBox RamoBox; + + internal ContentControl ReportControl; + + internal Gestor.Application.Componentes.WebEditor WebEditor; + + internal PopupBox HelpPopup; + + internal TextBlock NaoHaDados; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public RelatorioView(string opcao) + { + this.ViewModel = new RelatorioViewModel(opcao); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher != null) + { + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + else + { + } + this.ViewModel.Head = string.Concat(Recursos.Usuario.get_Nome(), ", VOCÊ ESTÁ EM RELATÓRIOS"); + Gestor.Application.Actions.Actions.RecarregarRelatorios = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.RecarregarRelatorios, new Action(this.Recarregar)); + } + + private void AbrirInfo_Click(object sender, RoutedEventArgs e) + { + this.ViewModel.InfoVisibility = (this.ViewModel.InfoVisibility == System.Windows.Visibility.Collapsed ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + } + + private async Task AbrirTarefa(Tarefa data) + { + Tarefa tarefa; + this.ViewModel.IsEnabled = false; + this.ViewModel.Carregando = true; + while (true) + { + Tarefa tarefa1 = await this.ViewModel.ShowTarefaDialog(data, true, false); + tarefa = tarefa1; + if (tarefa == null) + { + this.ViewModel.IsEnabled = true; + this.ViewModel.Carregando = false; + return; + } + if (tarefa.get_Usuario() == null) + { + tarefa.set_Usuario(tarefa.get_UsuariosVinculados().FirstOrDefault()); + } + List list = tarefa.get_UsuariosVinculados().Select((Usuario x) => { + ResponsavelTarefa responsavelTarefa = new ResponsavelTarefa(); + responsavelTarefa.set_IdTarefa(tarefa.get_Id()); + responsavelTarefa.set_Usuario(x); + return responsavelTarefa; + }).ToList(); + tarefa.set_Responsaveis(list); + tarefa.set_Anotacoes(string.Concat("

", tarefa.get_Anotacoes(), "

")); + Tarefa tarefa2 = tarefa; + List configuracoes = Recursos.Configuracoes; + tarefa2.set_AgendamentoRetroativo(configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 45)); + List> keyValuePairs = tarefa.Validate(); + if (string.IsNullOrWhiteSpace(tarefa.get_Anotacoes())) + { + keyValuePairs.Add(new KeyValuePair("ANOTAÇÕES", "OBRIGATÓRIO")); + } + if (keyValuePairs == null || keyValuePairs.Count == 0) + { + break; + } + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + List tarefas = this.ViewModel.GerarTarefas(tarefa); + if (tarefas == null || tarefas.Count == 0) + { + this.ViewModel.IsEnabled = true; + this.ViewModel.Carregando = false; + await this.ViewModel.ShowMessage("FALHA AO CRIAR TAREFA.", "OK", "", false); + } + else + { + await this.ViewModel.SalvarTarefas(tarefas); + this.ViewModel.ToggleSnackBar("TAREFA SALVA COM SUCESSO.", true); + this.ViewModel.Alterar(false); + this.ViewModel.IsEnabled = true; + this.ViewModel.Carregando = false; + } + return; + this.ViewModel.IsEnabled = true; + this.ViewModel.Carregando = false; + } + + private async void Acompanhamento_OnClick(object sender, RoutedEventArgs e) + { + await this.ViewModel.Acompanhamento(); + } + + private void AdicionarFiltro_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AdcionarFiltroPersonalizado(); + } + + private void AdicionarRamo_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AdicionarRamo(); + } + + private async void Apolice_OnClick(object sender, RoutedEventArgs e) + { + List malaDiretas; + this.ViewModel.Loading(true); + List malaDiretas1 = await this.ViewModel.CriarLista(); + if (malaDiretas1 == null) + { + malaDiretas = new List(); + } + else + { + List malaDiretas2 = malaDiretas1; + malaDiretas = malaDiretas2.Where((MalaDireta x) => { + if (x.get_Apolice().get_Tipo() == 0 && !string.IsNullOrWhiteSpace(x.get_Apolice().get_Apolice())) + { + return true; + } + if (x.get_Apolice().get_Tipo() != 1) + { + return false; + } + return !string.IsNullOrWhiteSpace(x.get_Apolice().get_Endosso()); + }).ToList(); + } + malaDiretas1 = malaDiretas; + if (malaDiretas1.Count != 0) + { + if (Funcoes.IsWindowOpen("ENVIO DE E-MAIL")) + { + Funcoes.Destroy("ENVIO DE E-MAIL"); + } + this.ViewModel.Loading(false); + (new HosterWindow(new MalaDiretaView(malaDiretas1, null, null, null), "ENVIO DE E-MAIL", new double?((double)1200), new double?((double)600), true)).Show(); + } + else + { + await this.ViewModel.ShowMessage("NECESSÁRIO SELECIONAR AO MENOS UM CLIENTE PARA PROSSEGUIR.", "OK", "", false); + this.ViewModel.Loading(false); + } + } + + private void AutoCompleteBox_OnTextChanged(object sender, RoutedEventArgs e) + { + if (!string.IsNullOrWhiteSpace(((AutoCompleteBox)sender).get_Text())) + { + return; + } + this.ViewModel.FiltrarUsuario(""); + } + + private void AutoCompleteBoxUsuario_Populating(object sender, PopulatingEventArgs e) + { + e.set_Cancel(true); + this.ViewModel.Filtrar(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void ConfigurarRelatorio_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.ShowDrawer(new ConfiguracaoRelatorio(this.ViewModel), 0, false); + } + + private void ContentLoad() + { + this.InicioBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.InicioBox.PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + this.InicioBox.SelectedDateChanged += new EventHandler(this.Periodo_OnSelectedDateChanged); + this.FimBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.FimBox.PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + this.FimBox.SelectedDateChanged += new EventHandler(this.Periodo_OnSelectedDateChanged); + this.RelatorioBox.SelectionChanged += new SelectionChangedEventHandler(this.TipoRelatorio_OnSelectionChanged); + } + + private void CopyLink_OnClick(object sender, RoutedEventArgs e) + { + Button button = (Button)sender; + if (button == null || button.DataContext == null) + { + return; + } + AjudaTela dataContext = (AjudaTela)button.DataContext; + string str = ""; + if (dataContext.get_Minuto() > 0 || dataContext.get_Segundo() > 0) + { + str = string.Format("&start={0}", dataContext.get_Minuto() * 60 + dataContext.get_Segundo()); + } + string.Concat(dataContext.get_Link(), str).CopyToClipboard(); + this.ViewModel.ToggleSnackBar("LINK COPIADO", true); + } + + private async void Email_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Loading(true); + List malaDiretas = await this.ViewModel.CriarLista(); + if (malaDiretas == null || malaDiretas.Count == 0) + { + await this.ViewModel.ShowMessage("NECESSÁRIO SELECIONAR AO MENOS UM CLIENTE PARA PROSSEGUIR.", "OK", "", false); + this.ViewModel.Loading(false); + } + else + { + if (Funcoes.IsWindowOpen("ENVIO DE E-MAIL")) + { + Funcoes.Destroy("ENVIO DE E-MAIL"); + } + this.ViewModel.Loading(false); + (new HosterWindow(new MalaDiretaView(malaDiretas, null, null, null), "ENVIO DE E-MAIL", new double?((double)1200), new double?((double)600), true)).Show(); + } + } + + private async void Etiquetas_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.Loading(true); + List documentos = await this.ViewModel.CriarListaEtiqueta(); + if (documentos == null || documentos.Count == 0) + { + await this.ViewModel.ShowMessage("NECESSÁRIO SELECIONAR AO MENOS UM CLIENTE PARA PROSSEGUIR.", "OK", "", false); + this.ViewModel.Loading(false); + } + else if (!Funcoes.IsWindowOpen("ETIQUETAS")) + { + flag = (this.ViewModel.Relatorio == null ? true : this.ViewModel.Relatorio == 1); + bool flag1 = flag; + this.ViewModel.Loading(false); + (new HosterWindow(new EtiquetaView(documentos, flag1), "ETIQUETAS", new double?((double)900), new double?((double)600), false)).Show(); + } + } + + private void ExcluirFiltro_OnClick(object sender, RoutedEventArgs e) + { + Chip chip = sender as Chip; + if (chip == null) + { + return; + } + ListBox listBox = Extentions.FindVisualAncestor(chip); + FiltroPersonalizado item = (FiltroPersonalizado)listBox.Items[listBox.Items.IndexOf(chip.DataContext)]; + if (item == null) + { + return; + } + this.ViewModel.FiltroPersonalizadoSelecionado.Remove(item); + this.ViewModel.PesquisaPersonalizada(); + } + + private void ExcluirRamo_onClick(object sender, RoutedEventArgs e) + { + Chip chip = sender as Chip; + if (chip == null) + { + return; + } + Ramo dataContext = (Ramo)chip.DataContext; + if (dataContext == null) + { + return; + } + this.ViewModel.RemoverRamo(dataContext); + } + + private async void ExportarExcel_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Carregando = true; + this.ViewModel.IsEnabled = false; + await this.ViewModel.GerarExcel(); + this.ViewModel.IsEnabled = true; + this.ViewModel.Carregando = false; + } + + private void Extrato_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.ExibirExtratoDrawer(); + } + + private void Fechar_OnClick(object sender, RoutedEventArgs e) + { + this.HelpPopup.set_IsPopupOpen(!this.HelpPopup.get_IsPopupOpen()); + } + + private void FecharFiltro_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.VisibilityFiltroPersonalizado = (this.ViewModel.VisibilityFiltroPersonalizado == System.Windows.Visibility.Collapsed ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + } + + private void FecharFiltroUsuario_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.VisibilityUsuarios = false; + } + + private void FecharInfo_Click(object sender, RoutedEventArgs e) + { + this.ViewModel.InfoVisibility = (this.ViewModel.InfoVisibility == System.Windows.Visibility.Collapsed ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + } + + private async void GerarResultados_OnClick(object sender, RoutedEventArgs e) + { + object obj; + bool flag; + GridRelatorio gridRelatorio; + this.InicioBox.Text = ValidationHelper.FormatDate(this.InicioBox.Text); + this.FimBox.Text = ValidationHelper.FormatDate(this.FimBox.Text); + try + { + this.ViewModel.Inicio = Convert.ToDateTime(this.InicioBox.Text); + this.ViewModel.Fim = Convert.ToDateTime(this.FimBox.Text); + } + catch (Exception exception) + { + gridRelatorio = null; + return; + } + if (this.ViewModel.Inicio > this.ViewModel.Fim) + { + await this.ViewModel.ShowMessage("A DATA FINAL NÃO PODE SER MENOR QUE A DATA INICIAL DO FILTRO.", "OK", "", false); + } + else if (this.RelatorioBox.Items.Count == 0) + { + await this.ViewModel.ShowMessage("NÃO HÁ RELATÓRIOS QUE VOCÊ POSSA GERAR.", "OK", "", false); + } + else if (this.ViewModel.InicioValor <= this.ViewModel.FimValor) + { + this.ViewModel.Carregando = true; + this.ViewModel.IsEnabled = false; + this.ViewModel.VisibilityHtml = false; + if (this.ViewModel.Report != null) + { + this.ViewModel.Report = null; + } + this.ViewModel.LimparRelatorio(); + if (await this.ViewModel.GerarRelatorio(new DateTime?(this.ViewModel.Inicio), new DateTime?(this.ViewModel.Fim))) + { + this.ReportControl.DataContext = this.ViewModel; + Relatorio relatorio = this.ViewModel.Relatorio; + gridRelatorio = new GridRelatorio(this.ViewModel); + switch (relatorio) + { + case 0: + case 1: + { + this.ViewModel.NovosNegocios = relatorio == 0; + await Funcoes.ContruirLista(gridRelatorio.DataGrid, this.ViewModel.Relatorio); + gridRelatorio.DataGrid.ItemsSource = this.ViewModel.ClientesAtivosInativosFiltrado; + goto case 22; + } + case 2: + { + await Funcoes.ContruirLista(gridRelatorio.DataGrid, this.ViewModel.Relatorio); + gridRelatorio.DataGrid.ItemsSource = this.ViewModel.ProducaoFiltrado; + goto case 22; + } + case 3: + { + await Funcoes.ContruirLista(gridRelatorio.DataGrid, this.ViewModel.Relatorio); + gridRelatorio.DataGrid.ItemsSource = this.ViewModel.ApolicePendenteFiltrado; + goto case 22; + } + case 4: + { + await Funcoes.ContruirLista(gridRelatorio.DataGrid, this.ViewModel.Relatorio); + gridRelatorio.DataGrid.ItemsSource = this.ViewModel.RenovacaoFiltrado; + goto case 22; + } + case 5: + { + await Funcoes.ContruirLista(gridRelatorio.DataGrid, this.ViewModel.Relatorio); + gridRelatorio.DataGrid.ItemsSource = this.ViewModel.ComissaoFiltrado; + goto case 22; + } + case 6: + case 16: + { + await Funcoes.ContruirLista(gridRelatorio.DataGrid, this.ViewModel.Relatorio); + gridRelatorio.DataGrid.ItemsSource = this.ViewModel.PendenteFiltrado; + goto case 22; + } + case 7: + case 11: + case 20: + { + this.WebEditor.Initialize(this.ViewModel.HtmlContent); + goto case 22; + } + case 8: + { + await Funcoes.ContruirLista(gridRelatorio.DataGrid, this.ViewModel.Relatorio); + gridRelatorio.DataGrid.ItemsSource = this.ViewModel.AuditoriaFiltrado; + goto case 22; + } + case 9: + case 10: + { + await Funcoes.ContruirLista(gridRelatorio.DataGrid, this.ViewModel.Relatorio); + gridRelatorio.DataGrid.ItemsSource = this.ViewModel.SinistroFiltrado; + goto case 22; + } + case 12: + { + await Funcoes.ContruirLista(gridRelatorio.DataGrid, this.ViewModel.Relatorio); + gridRelatorio.DataGrid.ItemsSource = this.ViewModel.FaturaPendenteFiltrado; + goto case 22; + } + case 13: + { + await Funcoes.ContruirLista(gridRelatorio.DataGrid, this.ViewModel.Relatorio); + gridRelatorio.DataGrid.ItemsSource = this.ViewModel.ExtratosFiltrado; + goto case 22; + } + case 14: + { + await Funcoes.ContruirLista(gridRelatorio.DataGrid, this.ViewModel.Relatorio); + gridRelatorio.DataGrid.ItemsSource = this.ViewModel.MetaSeguradoraFiltrado; + goto case 22; + } + case 15: + { + await Funcoes.ContruirLista(gridRelatorio.DataGrid, this.ViewModel.Relatorio); + gridRelatorio.DataGrid.ItemsSource = this.ViewModel.MetaVendedorFiltrado; + goto case 22; + } + case 17: + { + await Funcoes.ContruirLista(gridRelatorio.DataGrid, this.ViewModel.Relatorio); + gridRelatorio.DataGrid.ItemsSource = this.ViewModel.LicenciamentoFiltrado; + goto case 22; + } + case 18: + { + await Funcoes.ContruirLista(gridRelatorio.DataGrid, this.ViewModel.Relatorio); + gridRelatorio.DataGrid.ItemsSource = this.ViewModel.TarefaFiltrado; + goto case 22; + } + case 19: + { + await Funcoes.ContruirLista(gridRelatorio.DataGrid, this.ViewModel.Relatorio); + gridRelatorio.DataGrid.ItemsSource = this.ViewModel.NotaFiscalFiltrado; + goto case 22; + } + case 21: + case 22: + { + gridRelatorio.SinteticoGrid.ItemsSource = this.ViewModel.Sintetic; + RelatorioViewModel viewModel = this.ViewModel; + if (relatorio == 11 || relatorio == 7 || relatorio == 20) + { + obj = null; + } + else + { + obj = gridRelatorio; + } + viewModel.Report = obj; + RelatorioViewModel relatorioViewModel = this.ViewModel; + flag = (relatorio == 11 || relatorio == 7 ? true : relatorio == 20); + relatorioViewModel.VisibilityHtml = flag; + this.NaoHaDados.Visibility = System.Windows.Visibility.Collapsed; + this.ReportControl.Visibility = System.Windows.Visibility.Visible; + this.ViewModel.RelatorioVisibility = true; + this.ViewModel.IsEnabled = true; + this.ViewModel.ExtratosEnabled = true; + this.ViewModel.Carregando = false; + break; + } + case 23: + { + gridRelatorio.Totalizacao.Visibility = System.Windows.Visibility.Collapsed; + await Funcoes.ContruirLista(gridRelatorio.DataGrid, this.ViewModel.Relatorio); + gridRelatorio.DataGrid.ItemsSource = this.ViewModel.LogsEnvioFiltrado; + goto case 22; + } + case 24: + case 25: + { + await Funcoes.ContruirLista(gridRelatorio.DataGrid, this.ViewModel.Relatorio); + gridRelatorio.DataGrid.ItemsSource = this.ViewModel.LogUtilizacaoFiltrado; + goto case 22; + } + case 26: + { + await Funcoes.ContruirLista(gridRelatorio.DataGrid, this.ViewModel.Relatorio); + gridRelatorio.DataGrid.ItemsSource = this.ViewModel.ApoliceCriticaFiltrado; + goto case 22; + } + case 27: + { + await Funcoes.ContruirLista(gridRelatorio.DataGrid, this.ViewModel.Relatorio); + gridRelatorio.DataGrid.ItemsSource = this.ViewModel.PlacaFiltrado; + goto case 22; + } + case 28: + { + await Funcoes.ContruirLista(gridRelatorio.DataGrid, this.ViewModel.Relatorio); + gridRelatorio.DataGrid.ItemsSource = this.ViewModel.EndossoFiltrado; + goto case 22; + } + case 29: + { + await Funcoes.ContruirLista(gridRelatorio.DataGrid, this.ViewModel.Relatorio); + gridRelatorio.DataGrid.ItemsSource = this.ViewModel.Classificacao; + goto case 22; + } + default: + { + goto case 22; + } + } + } + else + { + this.NaoHaDados.Visibility = System.Windows.Visibility.Visible; + this.ReportControl.Visibility = System.Windows.Visibility.Collapsed; + this.ViewModel.IsEnabled = true; + this.ViewModel.ExtratosEnabled = false; + this.ViewModel.Carregando = false; + this.ViewModel.VisibilityHtml = false; + } + } + else + { + await this.ViewModel.ShowMessage("O VALOR FINAL NÃO PODE SER MENOR QUE O VALOR INICIAL DO FILTRO.", "OK", "", false); + } + gridRelatorio = null; + } + + private async void HelpPopup_Opened(object sender, RoutedEventArgs e) + { + await this.ViewModel.CarregarAjuda(); + } + + private async void Imprimir_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + flag = (this.ViewModel.VisibilityAgrupamento != System.Windows.Visibility.Visible || this.ViewModel.Agrupamento == null ? this.ViewModel.NotaFiscalPorSeguradora : true); + bool flag1 = flag; + if (flag1) + { + flag1 = await this.ViewModel.ShowMessage("DESEJA SEPARAR GRUPOS POR PÁGINA?", "SIM", "NÃO", false); + } + bool flag2 = flag1; + this.ViewModel.Carregando = true; + this.ViewModel.IsEnabled = false; + bool visibilityHtml = this.ViewModel.VisibilityHtml; + if (visibilityHtml) + { + this.ViewModel.VisibilityHtml = false; + } + await this.ViewModel.Print(flag2); + if (visibilityHtml) + { + this.ViewModel.VisibilityHtml = true; + } + this.ViewModel.Carregando = false; + this.ViewModel.IsEnabled = true; + if (this.ViewModel.Relatorio == 7 || this.ViewModel.Relatorio == 20) + { + this.WebEditor.Visibility = System.Windows.Visibility.Visible; + } + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/relatorios/relatorioview.xaml", UriKind.Relative)); + } + + private void LimparRelatorio() + { + this.ViewModel.LimparRelatorio(); + if (this.ReportControl == null) + { + return; + } + this.ReportControl.Content = null; + this.ReportControl.DataContext = null; + } + + private void MaisFiltros_OnClick(object sender, RoutedEventArgs e) + { + if (this.ViewModel.Relatorio == 24 || this.ViewModel.Relatorio == 25) + { + this.ViewModel.VisibilityUsuarios = true; + return; + } + this.ViewModel.Seguradoras = new List(this.ViewModel.Seguradoras); + this.ViewModel.Ramos = new List(this.ViewModel.Ramos); + this.ViewModel.Vendedores = new List(this.ViewModel.Vendedores); + this.ViewModel.Produtos = new List(this.ViewModel.Produtos); + this.ViewModel.Estipulantes = new List(this.ViewModel.Estipulantes); + this.ViewModel.TipoSeguros = new List(this.ViewModel.TipoSeguros); + this.ViewModel.RecheckAllLists(); + this.ViewModel.ShowDrawer(new Gestor.Application.Drawers.Relatorios.FiltroRelatorio(this.ViewModel, this.ViewModel.Relatorio), 0, false); + } + + private void OcultarAjuda_OnClick(object sender, RoutedEventArgs e) + { + this.HelpPopup.Visibility = System.Windows.Visibility.Collapsed; + } + + private void Periodo_OnSelectedDateChanged(object sender, SelectionChangedEventArgs e) + { + this.LimparRelatorio(); + } + + private async void PlanilhaCompleta_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Carregando = true; + await this.ViewModel.GerarPlanilhaCompleta(); + this.ViewModel.Carregando = false; + } + + private void Play_Click(object sender, RoutedEventArgs e) + { + Button button = (Button)sender; + if (button == null || button.DataContext == null) + { + return; + } + AjudaTela dataContext = (AjudaTela)button.DataContext; + string str = ""; + if (dataContext.get_Minuto() > 0 || dataContext.get_Segundo() > 0) + { + str = string.Format("&start={0}", dataContext.get_Minuto() * 60 + dataContext.get_Segundo()); + } + Process.Start(string.Concat(dataContext.get_Link(), str)); + } + + private void Protocolo_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.MostrarProtocolo(); + } + + private void Recarregar(string sessao) + { + if (this.ViewModel.Sessao != sessao) + { + return; + } + this.GerarResultados_OnClick(this.GerarRelatorioButton, new RoutedEventArgs()); + } + + private void ReloadWindow_Click(object sender, RoutedEventArgs e) + { + this.LimparRelatorio(); + } + + private async void ShowHelp(Relatorio relatorio) + { + if (await this.ViewModel.VerificarRestricao(61, true, false)) + { + bool flag = true; + if (this.HelpPopup != null) + { + this.HelpPopup.Visibility = (flag ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + } + } + else + { + this.HelpPopup.Visibility = System.Windows.Visibility.Collapsed; + } + } + + private async void Sincronizar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Carregando = true; + this.ViewModel.IsEnabled = false; + await this.ViewModel.Sincronizar(); + this.ViewModel.IsEnabled = true; + this.ViewModel.Carregando = false; + } + + private async void Sintetico_OnClick(object sender, RoutedEventArgs e) + { + if (this.ViewModel.Relatorio == 7 || this.ViewModel.Agrupamento != null || this.ViewModel.Relatorio == 11) + { + await this.ViewModel.Sintetico(); + } + else + { + await this.ViewModel.ShowMessage("NECESSÁRIO SELECIONAR UM AGRUPAMENTO PARA SINTETIZAR OS RESULTADOS.", "OK", "", false); + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.ProgressRing = (Image)target; + return; + } + case 2: + { + this.RelatorioBox = (ComboBox)target; + this.RelatorioBox.SelectionChanged += new SelectionChangedEventHandler(this.TipoRelatorio_OnSelectionChanged); + return; + } + case 3: + { + ((Button)target).Click += new RoutedEventHandler(this.AbrirInfo_Click); + return; + } + case 4: + { + this.ValorInicioBox = (CurrencyTextBox)target; + return; + } + case 5: + { + this.ValorFimBox = (CurrencyTextBox)target; + return; + } + case 6: + { + this.InicioBox = (DatePicker)target; + this.InicioBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.InicioBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 7: + { + this.FimBox = (DatePicker)target; + this.FimBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.FimBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 8: + { + this.VisualizarRamosVendedoresTooltip = (ToggleButton)target; + this.VisualizarRamosVendedoresTooltip.Click += new RoutedEventHandler(this.ReloadWindow_Click); + return; + } + case 9: + { + this.GerarRelatorioButton = (MenuItem)target; + this.GerarRelatorioButton.Click += new RoutedEventHandler(this.GerarResultados_OnClick); + return; + } + case 10: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Imprimir_OnClick); + return; + } + case 11: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.ExportarExcel_OnClick); + return; + } + case 12: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.PlanilhaCompleta_OnClick); + return; + } + case 13: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Extrato_OnClick); + return; + } + case 14: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.MaisFiltros_OnClick); + return; + } + case 15: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.ConfigurarRelatorio_OnClick); + return; + } + case 16: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Sintetico_OnClick); + return; + } + case 17: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Tarefas_OnClick); + return; + } + case 18: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Etiquetas_OnClick); + return; + } + case 19: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Acompanhamento_OnClick); + return; + } + case 20: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Email_OnClick); + return; + } + case 21: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Apolice_OnClick); + return; + } + case 22: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Protocolo_OnClick); + return; + } + case 23: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Sincronizar_OnClick); + return; + } + case 24: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.FecharFiltro_OnClick); + return; + } + case 25: + { + ((Button)target).Click += new RoutedEventHandler(this.FecharFiltro_OnClick); + return; + } + case 26: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 27: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 28: + { + ((Button)target).Click += new RoutedEventHandler(this.AdicionarFiltro_OnClick); + return; + } + case 29: + case 32: + case 38: + case 39: + { + this._contentLoaded = true; + return; + } + case 30: + { + this.RamoBox = (ComboBox)target; + return; + } + case 31: + { + ((Button)target).Click += new RoutedEventHandler(this.AdicionarRamo_OnClick); + return; + } + case 33: + { + this.ReportControl = (ContentControl)target; + return; + } + case 34: + { + this.WebEditor = (Gestor.Application.Componentes.WebEditor)target; + return; + } + case 35: + { + this.HelpPopup = (PopupBox)target; + this.HelpPopup.add_Opened(new RoutedEventHandler(this.HelpPopup_Opened)); + return; + } + case 36: + { + ((Button)target).Click += new RoutedEventHandler(this.OcultarAjuda_OnClick); + return; + } + case 37: + { + ((Button)target).Click += new RoutedEventHandler(this.Fechar_OnClick); + return; + } + case 40: + { + ((Button)target).Click += new RoutedEventHandler(this.FecharFiltroUsuario_OnClick); + return; + } + case 41: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, RelatorioView.AutoCompleteBoxUsuario_Populating)); + ((AutoCompleteBox)target).add_TextChanged(new RoutedEventHandler(this.AutoCompleteBox_OnTextChanged)); + return; + } + case 42: + { + ((Button)target).Click += new RoutedEventHandler(this.FecharInfo_Click); + return; + } + case 43: + { + this.NaoHaDados = (TextBlock)target; + return; + } + default: + { + this._contentLoaded = true; + return; + } + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + if (connectionId <= 32) + { + if (connectionId == 29) + { + ((Chip)target).add_DeleteClick(new RoutedEventHandler(this.ExcluirFiltro_OnClick)); + return; + } + if (connectionId != 32) + { + return; + } + ((Chip)target).add_DeleteClick(new RoutedEventHandler(this.ExcluirRamo_onClick)); + return; + } + if (connectionId == 38) + { + ((Button)target).Click += new RoutedEventHandler(this.CopyLink_OnClick); + return; + } + if (connectionId != 39) + { + return; + } + ((Button)target).Click += new RoutedEventHandler(this.Play_Click); + } + + private async void Tarefas_OnClick(object sender, RoutedEventArgs e) + { + if (!await this.ViewModel.ValidateTarefa()) + { + Tarefa tarefa = new Tarefa(); + tarefa.set_Entidade(1); + tarefa.set_Titulo(EnumHelper.GetDescription(this.ViewModel.Relatorio)); + tarefa.set_Usuario(Recursos.Usuario); + tarefa.set_Agendamento(Funcoes.GetNetworkTime()); + await this.AbrirTarefa(tarefa); + } + } + + private void TipoRelatorio_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + this.LimparRelatorio(); + this.VisualizarRamosVendedoresTooltip.IsChecked = new bool?(false); + Relatorio relatorio = this.ViewModel.Relatorio; + if (this.NaoHaDados != null) + { + this.NaoHaDados.Visibility = System.Windows.Visibility.Collapsed; + } + this.ShowHelp(relatorio); + switch (relatorio) + { + case 0: + { + this.ViewModel.PlanilhaVisibility = System.Windows.Visibility.Collapsed; + return; + } + case 1: + { + this.ViewModel.PlanilhaVisibility = System.Windows.Visibility.Collapsed; + return; + } + case 2: + { + this.ViewModel.PlanilhaVisibility = System.Windows.Visibility.Visible; + return; + } + case 3: + { + this.ViewModel.PlanilhaVisibility = System.Windows.Visibility.Collapsed; + return; + } + case 4: + { + this.ViewModel.PlanilhaVisibility = System.Windows.Visibility.Visible; + return; + } + case 5: + { + this.ViewModel.PlanilhaVisibility = System.Windows.Visibility.Collapsed; + return; + } + case 6: + { + this.ViewModel.PlanilhaVisibility = System.Windows.Visibility.Collapsed; + return; + } + case 7: + { + this.ViewModel.PlanilhaVisibility = System.Windows.Visibility.Collapsed; + return; + } + case 8: + { + this.ViewModel.PlanilhaVisibility = System.Windows.Visibility.Collapsed; + return; + } + case 9: + { + this.ViewModel.PlanilhaVisibility = System.Windows.Visibility.Collapsed; + return; + } + case 10: + { + this.ViewModel.PlanilhaVisibility = System.Windows.Visibility.Collapsed; + return; + } + case 11: + { + this.ViewModel.PlanilhaVisibility = System.Windows.Visibility.Collapsed; + this.ViewModel.Info = ""; + this.ViewModel.InfoVisibility = System.Windows.Visibility.Collapsed; + return; + } + case 12: + case 14: + case 15: + case 16: + case 17: + case 18: + case 19: + case 20: + case 21: + case 22: + { + return; + } + case 13: + { + this.ViewModel.VisibilityAgrupamento = System.Windows.Visibility.Collapsed; + this.ViewModel.PlanilhaVisibility = System.Windows.Visibility.Collapsed; + return; + } + case 23: + { + this.ViewModel.VisibilityAgrupamento = System.Windows.Visibility.Collapsed; + this.ViewModel.PlanilhaVisibility = System.Windows.Visibility.Collapsed; + return; + } + default: + { + return; + } + } + } + + private async void ToggleComparativo_OnChecked(object sender, RoutedEventArgs e) + { + if (this.ViewModel.Relatorio == 11) + { + this.ViewModel.Carregando = true; + this.ViewModel.IsEnabled = false; + RelatorioViewModel viewModel = this.ViewModel; + string str = await this.ViewModel.GerarHtml(true, false, null, false); + viewModel.HtmlContent = str; + viewModel = null; + this.WebEditor.Initialize(this.ViewModel.HtmlContent); + this.ViewModel.IsEnabled = true; + this.ViewModel.Carregando = false; + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Relatorios/SinteticoView.cs b/Codemerx/Gestor.Application/Views/Relatorios/SinteticoView.cs new file mode 100644 index 0000000..9ae559f --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Relatorios/SinteticoView.cs @@ -0,0 +1,509 @@ +using Gestor.Application; +using Gestor.Application.Helpers; +using Gestor.Application.Model; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Relatorios; +using Gestor.Model.Domain.Relatorios; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Drawing; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Forms; +using System.Windows.Input; +using System.Windows.Interop; +using System.Windows.Markup; +using System.Windows.Media; +using System.Windows.Shapes; +using System.Windows.Shell; + +namespace Gestor.Application.Views.Relatorios +{ + public class SinteticoView : Window, IComponentConnector, IStyleConnector + { + internal SinteticoViewModel ViewModel; + + private bool _buttonClickable; + + private ListSortDirection _ascending; + + private string _member; + + internal System.Windows.Shell.WindowChrome WindowChrome; + + internal TextBlock SubTitulo; + + internal Grid MinimizeButton; + + internal Grid MaximizeButton; + + internal Grid CloseButton; + + internal System.Windows.Controls.TabControl Tab; + + private bool _contentLoaded; + + public DateTime? DateFinal + { + get; + set; + } + + public DateTime? DateStart + { + get; + set; + } + + public SinteticoView(List sintetico, string relatorio, DateTime? inicio, DateTime? fim) + { + DateTime valueOrDefault; + string str; + string str1; + this.ViewModel = new SinteticoViewModel(sintetico, relatorio); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + TextBlock subTitulo = this.SubTitulo; + if (inicio.HasValue) + { + valueOrDefault = inicio.GetValueOrDefault(); + str = valueOrDefault.ToString("dd/MM/yyyy"); + } + else + { + str = null; + } + if (fim.HasValue) + { + valueOrDefault = fim.GetValueOrDefault(); + str1 = valueOrDefault.ToString("dd/MM/yyyy"); + } + else + { + str1 = null; + } + subTitulo.Text = string.Concat("VALORES BASEADOS NA RELAÇÃO EMITIDA ANTERIORMENTE - INICIO: ", str, " FIM: ", str1); + DateTime? nullable = inicio; + this.DateStart = new DateTime?((nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue)); + nullable = fim; + this.DateFinal = new DateTime?((nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue)); + this.MinimizeButton.MouseEnter += new System.Windows.Input.MouseEventHandler(SinteticoView.TopControls_OnMouseEnter); + this.MinimizeButton.MouseLeave += new System.Windows.Input.MouseEventHandler(this.TopControls_OnMouseLeave); + this.MaximizeButton.MouseEnter += new System.Windows.Input.MouseEventHandler(SinteticoView.TopControls_OnMouseEnter); + this.MaximizeButton.MouseLeave += new System.Windows.Input.MouseEventHandler(this.TopControls_OnMouseLeave); + this.CloseButton.MouseEnter += new System.Windows.Input.MouseEventHandler(SinteticoView.TopControls_OnMouseEnter); + this.CloseButton.MouseLeave += new System.Windows.Input.MouseEventHandler(this.TopControls_OnMouseLeave); + } + + private void AjustaNome(SinteticoSource source) + { + foreach (ValorSintetico listum in source.Lista) + { + if (string.IsNullOrEmpty(listum.get_Porcentagem()) || listum.get_Indice().Contains(listum.get_Porcentagem())) + { + continue; + } + ValorSintetico valorSintetico = listum; + valorSintetico.set_Indice(string.Concat(valorSintetico.get_Indice(), " - ", listum.get_Porcentagem(), "%")); + } + } + + public void CloseButton_Click() + { + base.Close(); + } + + private void DataGrid_Sorting(object sender, DataGridSortingEventArgs e) + { + System.Windows.Controls.DataGrid dataGrid = (System.Windows.Controls.DataGrid)sender; + if (dataGrid == null || dataGrid.DataContext == null) + { + return; + } + if (this._member != e.Column.SortMemberPath) + { + this._ascending = ListSortDirection.Ascending; + } + else + { + this._ascending = (this._ascending == ListSortDirection.Ascending ? ListSortDirection.Descending : ListSortDirection.Ascending); + } + ObservableCollection itemsSource = dataGrid.ItemsSource as ObservableCollection; + if (itemsSource == null) + { + return; + } + IQueryable valorSinteticos = itemsSource.AsQueryable(); + List list = ( + from x in (this._ascending == ListSortDirection.Ascending ? valorSinteticos.OrderBy(e.Column.SortMemberPath).ToList() : valorSinteticos.OrderByDescending(e.Column.SortMemberPath).ToList()) + orderby x.get_Indice() == "TOTAL" + select x).ToList(); + itemsSource.Clear(); + foreach (ValorSintetico valorSintetico in list) + { + itemsSource.Add(valorSintetico); + } + this.ViewModel.OnPropertyChanged("DataGrid_Sorting"); + this._member = e.Column.SortMemberPath; + e.Handled = true; + } + + private async void ExportarExcel_OnClick(object sender, RoutedEventArgs e) + { + System.Windows.Controls.MenuItem menuItem = (System.Windows.Controls.MenuItem)sender; + if (menuItem != null && menuItem.DataContext != null) + { + SinteticoSource dataContext = (SinteticoSource)menuItem.DataContext; + await this.ViewModel.GerarExcel(dataContext); + } + } + + private async void ExportarPdf_OnClick(object sender, RoutedEventArgs e) + { + System.Windows.Controls.MenuItem menuItem = (System.Windows.Controls.MenuItem)sender; + if (menuItem != null && menuItem.DataContext != null) + { + SinteticoSource dataContext = (SinteticoSource)menuItem.DataContext; + await this.ViewModel.GerarPdf(dataContext); + } + } + + [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false)] + private static extern bool GetCursorPos(out MainWindow.Point lpPoint); + + [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false)] + private static extern bool GetMonitorInfo(IntPtr hMonitor, SinteticoView.Monitorinfo lpmi); + + private async void Imprimir_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + System.Windows.Controls.MenuItem menuItem = (System.Windows.Controls.MenuItem)sender; + if (menuItem != null && menuItem.DataContext != null) + { + SinteticoSource dataContext = (SinteticoSource)menuItem.DataContext; + DateTime? dateStart = this.DateStart; + DateTime minValue = DateTime.MinValue; + flag = (dateStart.HasValue ? dateStart.GetValueOrDefault() != minValue : true); + if (flag) + { + dataContext.DateStart = this.DateStart; + dataContext.DateFinal = this.DateFinal; + } + await this.ViewModel.Print(dataContext); + } + } + + private async void ImprimirUnicaPagina_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + System.Windows.Controls.MenuItem menuItem = (System.Windows.Controls.MenuItem)sender; + if (menuItem != null && menuItem.DataContext != null) + { + SinteticoSource dataContext = (SinteticoSource)menuItem.DataContext; + DateTime? dateStart = this.DateStart; + DateTime minValue = DateTime.MinValue; + flag = (dateStart.HasValue ? dateStart.GetValueOrDefault() != minValue : true); + if (flag) + { + dataContext.DateStart = this.DateStart; + dataContext.DateFinal = this.DateFinal; + } + await this.ViewModel.PrintUnica(dataContext); + } + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/relatorios/sinteticoview.xaml", UriKind.Relative)); + } + + public void MaximizeButton_Click() + { + base.WindowState = (base.WindowState == System.Windows.WindowState.Normal ? System.Windows.WindowState.Maximized : System.Windows.WindowState.Normal); + } + + public void MinimizeButton_Click() + { + base.WindowState = System.Windows.WindowState.Minimized; + } + + [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false, SetLastError=true)] + private static extern IntPtr MonitorFromPoint(MainWindow.Point pt, SinteticoView.MonitorOptions dwFlags); + + protected sealed override void OnStateChanged(EventArgs e) + { + object obj; + base.BorderThickness = new Thickness((double)(base.WindowState != System.Windows.WindowState.Maximized)); + System.Windows.Shell.WindowChrome windowChrome = this.WindowChrome; + if (base.WindowState == System.Windows.WindowState.Maximized) + { + obj = null; + } + else + { + obj = 4; + } + windowChrome.ResizeBorderThickness = new Thickness((double)obj); + this.WindowChrome.CaptionHeight = (double)((base.WindowState == System.Windows.WindowState.Maximized ? 33 : 30)); + this.ViewModel.MaximizeRestore = (base.WindowState == System.Windows.WindowState.Maximized ? Geometry.Parse((string)System.Windows.Application.Current.Resources["Restore"]) : Geometry.Parse((string)System.Windows.Application.Current.Resources["Maximize"])); + base.OnStateChanged(e); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((SinteticoView)target).Initialized += new EventHandler(this.Window_OnInitialized); + return; + } + case 2: + { + this.WindowChrome = (System.Windows.Shell.WindowChrome)target; + return; + } + case 3: + { + this.SubTitulo = (TextBlock)target; + return; + } + case 4: + { + this.MinimizeButton = (Grid)target; + this.MinimizeButton.MouseLeftButtonDown += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonDown); + this.MinimizeButton.MouseLeftButtonUp += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonUp); + return; + } + case 5: + { + this.MaximizeButton = (Grid)target; + this.MaximizeButton.MouseLeftButtonDown += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonDown); + this.MaximizeButton.MouseLeftButtonUp += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonUp); + return; + } + case 6: + { + this.CloseButton = (Grid)target; + this.CloseButton.MouseLeftButtonDown += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonDown); + this.CloseButton.MouseLeftButtonUp += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonUp); + return; + } + case 7: + { + this.Tab = (System.Windows.Controls.TabControl)target; + return; + } + } + this._contentLoaded = true; + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 8: + { + ((System.Windows.Controls.MenuItem)target).Click += new RoutedEventHandler(this.Imprimir_OnClick); + return; + } + case 9: + { + ((System.Windows.Controls.MenuItem)target).Click += new RoutedEventHandler(this.ExportarPdf_OnClick); + return; + } + case 10: + { + ((System.Windows.Controls.MenuItem)target).Click += new RoutedEventHandler(this.ExportarExcel_OnClick); + return; + } + case 11: + { + ((System.Windows.Controls.MenuItem)target).Click += new RoutedEventHandler(this.ImprimirUnicaPagina_OnClick); + return; + } + case 12: + { + ((System.Windows.Controls.DataGrid)target).Sorting += new DataGridSortingEventHandler(this.DataGrid_Sorting); + return; + } + default: + { + return; + } + } + } + + private static void TopControls_OnMouseEnter(object sender, System.Windows.Input.MouseEventArgs e) + { + ((Grid)sender).Background = (((Grid)sender).Name == "CloseButton" ? new SolidColorBrush(Colors.IndianRed) : new SolidColorBrush(Colors.Gray)); + Path child = VisualTreeHelper.GetChild((Grid)sender, 0) as Path; + if (child != null) + { + child.Stroke = new SolidColorBrush(Colors.White); + } + } + + private void TopControls_OnMouseLeave(object sender, System.Windows.Input.MouseEventArgs e) + { + this._buttonClickable = false; + ((Grid)sender).Background = new SolidColorBrush(Colors.Transparent); + Path child = VisualTreeHelper.GetChild((Grid)sender, 0) as Path; + if (child != null) + { + child.Stroke = new SolidColorBrush(Colors.White); + } + } + + private void TopControls_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e) + { + this._buttonClickable = true; + ((Grid)sender).Background = (((Grid)sender).Name == "CloseButton" ? new SolidColorBrush(Colors.Red) : new SolidColorBrush(Colors.DimGray)); + } + + private void TopControls_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e) + { + if (this._buttonClickable) + { + MethodInfo method = base.GetType().GetMethod(string.Concat(((Grid)sender).Name, "_Click")); + if (method == null) + { + return; + } + method.Invoke(this, null); + } + } + + private void Window_OnInitialized(object sender, EventArgs e) + { + WindowInteropHelper windowInteropHelper = new WindowInteropHelper(this); + windowInteropHelper.EnsureHandle(); + HwndSource hwndSource = HwndSource.FromHwnd(windowInteropHelper.Handle); + if (hwndSource == null) + { + return; + } + hwndSource.AddHook(new HwndSourceHook(this.WindowProc)); + } + + private IntPtr WindowProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) + { + if (msg == 36) + { + this.WmGetMinMaxInfo(lParam); + } + return IntPtr.Zero; + } + + private void WmGetMinMaxInfo(IntPtr lParam) + { + MainWindow.Point point; + System.Drawing.Rectangle workingArea = Screen.FromHandle((new WindowInteropHelper(this)).Handle).WorkingArea; + base.MaxHeight = (double)workingArea.Height; + SinteticoView.GetCursorPos(out point); + IntPtr intPtr = SinteticoView.MonitorFromPoint(new MainWindow.Point(0, 0), SinteticoView.MonitorOptions.MonitorDefaulttoprimary); + SinteticoView.Monitorinfo monitorinfo = new SinteticoView.Monitorinfo(); + if (!SinteticoView.GetMonitorInfo(intPtr, monitorinfo)) + { + return; + } + IntPtr intPtr1 = SinteticoView.MonitorFromPoint(point, SinteticoView.MonitorOptions.MonitorDefaulttonearest); + SinteticoView.Minmaxinfo structure = (SinteticoView.Minmaxinfo)Marshal.PtrToStructure(lParam, typeof(SinteticoView.Minmaxinfo)); + if (!intPtr.Equals(intPtr1)) + { + structure.ptMaxPosition.X = monitorinfo.rcMonitor.Left; + structure.ptMaxPosition.Y = monitorinfo.rcMonitor.Top; + structure.ptMaxSize.X = monitorinfo.rcMonitor.Right - monitorinfo.rcMonitor.Left; + structure.ptMaxSize.Y = monitorinfo.rcMonitor.Bottom - monitorinfo.rcMonitor.Top; + } + else + { + structure.ptMaxPosition.X = monitorinfo.rcWork.Left; + structure.ptMaxPosition.Y = monitorinfo.rcWork.Top; + structure.ptMaxSize.X = monitorinfo.rcWork.Right - monitorinfo.rcWork.Left; + structure.ptMaxSize.Y = monitorinfo.rcWork.Bottom - monitorinfo.rcWork.Top; + } + Marshal.StructureToPtr(structure, lParam, true); + } + + private struct Minmaxinfo + { + private readonly MainWindow.Point ptReserved; + + public SinteticoView.Point ptMaxSize; + + public SinteticoView.Point ptMaxPosition; + + private readonly MainWindow.Point ptMinTrackSize; + + private readonly MainWindow.Point ptMaxTrackSize; + } + + private class Monitorinfo + { + private readonly int cbSize; + + public readonly SinteticoView.Rect rcMonitor; + + public readonly SinteticoView.Rect rcWork; + + private readonly int dwFlags; + + public Monitorinfo() + { + } + } + + private enum MonitorOptions : uint + { + MonitorDefaulttoprimary = 1, + MonitorDefaulttonearest = 2 + } + + public struct Point + { + public int X; + + public int Y; + + public Point(int x, int y) + { + this.X = x; + this.Y = y; + } + } + + public struct Rect + { + public int Left; + + public int Top; + + public int Right; + + public int Bottom; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Seguros/ApoliceView.cs b/Codemerx/Gestor.Application/Views/Seguros/ApoliceView.cs new file mode 100644 index 0000000..60dd854 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Seguros/ApoliceView.cs @@ -0,0 +1,3609 @@ +using CurrencyTextBoxControl; +using Gestor.Application.Actions; +using Gestor.Application.Componentes; +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Views.Seguros +{ + public class ApoliceView : BaseUserControl, IComponentConnector, IStyleConnector + { + private string _vencimentoCartaoOld = ""; + + private bool _calculando; + + internal DockPanel MenuApolice; + + internal MenuItem IncluirpoliceButton; + + internal MenuItem AlterarApoliceButton; + + internal MenuItem SalvarApoliceButton; + + internal MenuItem CancelarApoliceButton; + + internal MenuItem ExcluirpoliceButton; + + internal Button ButtonImportado; + + internal MenuItem ArquivoDigitalButton; + + internal MenuItem MaisOpcoesButton; + + internal MenuItem EditarParcelasButton; + + internal WrapPanel ApoliceControl1; + + internal ComboBox ProdutoBox; + + internal ComboBox SituacaoBox; + + internal ComboBox NegocioCorretoraBox; + + internal ComboBox TipoRecebimentoBox; + + internal ComboBox TipoEndossoBox; + + internal TextBox ApoliceBox; + + internal TextBox EndossoBox; + + internal DatePicker Vigencia2Box; + + internal DatePicker TransmissaoBox; + + internal DatePicker EmissaoBox; + + internal ComboBox FormaPagamentoBox; + + internal Grid PremiosBox; + + internal ToggleButton AdicionalBox; + + internal CustomIsReadOnlyControl Comissao; + + internal CurrencyTextBox ComissaoBox; + + internal CurrencyTextBox PremioLiquidoBox; + + internal CurrencyTextBox PremioAdicionalBox; + + internal CurrencyTextBox IofBox; + + internal CurrencyTextBox DiferencaBox; + + internal CurrencyTextBox PremioTotalBox; + + internal CurrencyTextBox ParcelasBox; + + internal CustomIsReadOnlyControl ComissaoOriginal; + + internal CustomIsReadOnlyControl Gerada; + + internal CustomIsReadOnlyControl Recebida; + + internal CustomIsReadOnlyControl Pendente; + + internal CustomIsReadOnlyControl Repasse; + + internal Menu BaixarParcelaButton; + + internal Menu SalvarParcelaButton; + + internal StackPanel EditarParcelasFields; + + internal CustomItemValidation TipoParcelaField; + + internal ComboBox TipoParcelaBox; + + internal CustomItemControl QuantidadeFaturaField; + + internal CurrencyTextBox QuantidadeFaturaBox; + + internal CustomItemValidation FaturaField; + + internal TextBox FaturaBox; + + internal CustomItemValidation VigenciaInicialField; + + internal CustomItemValidation VigenciaFinalField; + + internal DatePicker VigenciaFinalParcelaBox; + + internal CustomItemValidation VencimentoField; + + internal CustomItemControl EmissaoField; + + internal DatePicker EmissaoParcelaBox; + + internal CustomItemValidation PercentualComissaoField; + + internal CurrencyTextBox ComissaoParcelaBox; + + internal TextBlock ComissaoIcon; + + internal CustomItemControl ValorLiquidoField; + + internal CurrencyTextBox ValorLiquidoParcelaBox; + + internal CustomItemControl ValorField; + + internal CurrencyTextBox ValorParcelaBox; + + internal CustomItemValidation RecebimentoField; + + internal DatePicker RecebimentoParcelaBox; + + internal CustomItemControl QuitacaoField; + + internal CustomItemControl DataControleParcelaField; + + internal CustomItemValidation CreditoField; + + internal DatePicker CreditoParcelaBox; + + internal CustomItemValidation ValorRealizadoField; + + internal CurrencyTextBox ValorRealizadoParcelaBox; + + internal CustomItemValidation ValorComissaoField; + + internal CurrencyTextBox ValorComissaoParcelaBox; + + internal WrapPanel ImpostosField; + + internal CustomItemControl PorcentagemIrField; + + internal CurrencyTextBox PorcentagemIrBox; + + internal CustomItemControl ValorIrField; + + internal CurrencyTextBox ValorIrBox; + + internal CustomItemControl PorcentagemIssField; + + internal CurrencyTextBox PorcentagemIssBox; + + internal CustomItemControl ValorIssField; + + internal CurrencyTextBox ValorIssBox; + + internal CustomItemControl ValorOutrosField; + + internal CurrencyTextBox ValorOutrosBox; + + internal CustomItemControl ValorDescontoField; + + internal CurrencyTextBox ValorDescontoBox; + + internal CustomItemControl ValorComDescField; + + internal CurrencyTextBox ValorComDescBox; + + internal DataGrid ParcelaGrid; + + internal DataGridTextColumn ParcelaColumn; + + internal DataGridTextColumn FaturaColumn; + + internal DataGridTextColumn VigenciaInicialColumn; + + internal DataGridTextColumn VigenciaFinalColumn; + + internal DataGridTextColumn ParcelasComissaoColumn; + + internal DataGridTextColumn ParcelasValorComissaoColumn; + + internal DataGridTextColumn ParcelasValorComissaoDescColumn; + + internal DataGridTemplateColumn MaisInformacoesColumn; + + internal MenuItem EditarVendedorButton; + + internal MenuItem SalvarVendedorButton; + + internal MenuItem CancelarVendedorButton; + + internal WrapPanel EditarVendedorFields; + + internal ToggleButton CoCorretagemToogle; + + internal ComboBox TipoVendedorBox; + + internal ComboBox VendedorBox; + + internal CustomItemValidation ComissaoNovoBox; + + internal ComboBox ComissaoNovoComboBox; + + internal CustomItemValidation ComissaoRenovacaoBox; + + internal ComboBox ComissaoRenovacaoComboBox; + + internal CurrencyTextBox ValorRepasseBox; + + internal TextBox FormaRecebidaBox; + + internal TextBox FormaIncidenciaBox; + + internal DataGrid VendedorGrid; + + internal DataGridTextColumn VendedorGridColumn; + + internal DataGridTextColumn PagamentosPorcentagemRepasseColumn; + + internal DataGridTextColumn PagamentosValorRepasseColumn; + + internal TextBox ProponenteBox; + + internal AutoCompleteBox AutoCompleteBanco; + + internal TextBox AgenciaBox; + + internal TextBox ContaBox; + + internal TextBox CartaoBox; + + internal ComboBox BandeiraBox; + + internal TextBox VencimentoCartaoBox; + + internal DatePicker DataBox; + + internal TextBox PastaBox; + + private bool _contentLoaded; + + private Gestor.Model.Common.AcessoApolice AcessoApolice + { + get; + } + + private int EditarParcelaTipo + { + get; + set; + } + + public ApoliceViewModel ViewModel + { + get; + set; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public ApoliceView(Documento documentoSelecionado, bool lockInsert = false, bool invoke = true, Gestor.Model.Common.AcessoApolice acesso = 0, long idparcela = 0L, bool consultaTela = false) + { + string str; + base.Tag = "CADASTRO DE APÓLICE"; + this.AcessoApolice = acesso; + Gestor.Application.Actions.Actions.Redimencionar = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.Redimencionar, new Action(this.Redimencionar)); + this.ViewModel = new ApoliceViewModel(acesso, documentoSelecionado, invoke, idparcela); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher != null) + { + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + else + { + } + this.ParcelaGrid.DataContext = this.ViewModel; + if (consultaTela) + { + this.ExcluirpoliceButton.IsEnabled = false; + } + this.Restricao(false); + if (lockInsert) + { + this.IncluirpoliceButton.IsEnabled = false; + } + if (documentoSelecionado != null) + { + if (documentoSelecionado.get_Tipo() == 0 && string.IsNullOrEmpty(documentoSelecionado.get_Apolice())) + { + str = string.Concat("PROPOSTA \"", documentoSelecionado.get_Proposta(), "\""); + } + else if (documentoSelecionado.get_Tipo() != 0 || string.IsNullOrEmpty(documentoSelecionado.get_Apolice())) + { + str = (string.IsNullOrEmpty(documentoSelecionado.get_Endosso()) ? string.Concat("PROPOSTA DE ENDOSSO \"", documentoSelecionado.get_PropostaEndosso(), "\"") : string.Concat("ENDOSSO \"", documentoSelecionado.get_Endosso(), "\"")); + } + else + { + str = string.Concat("APÓLICE \"", documentoSelecionado.get_Apolice(), "\""); + } + string str1 = str; + this.ViewModel.RegistrarAcao(string.Concat("ACESSOU ", str1), documentoSelecionado.get_Id(), new TipoTela?(2), this.ViewModel.GerarObs(documentoSelecionado)); + } + } + + private async void AbrirAquivoDigital_Click(object sender, RoutedEventArgs e) + { + FiltroArquivoDigital filtroArquivoDigital = null; + string name = ""; + Button button = sender as Button; + if (button != null) + { + name = button.Name; + } + else + { + MenuItem menuItem = sender as MenuItem; + if (menuItem != null) + { + name = menuItem.Name; + } + } + if (name != "ArquivoDigitalButton") + { + if (name == "Parcela") + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 3).get_Consultar()) + { + FiltroArquivoDigital filtroArquivoDigital1 = new FiltroArquivoDigital(); + filtroArquivoDigital1.set_Id(this.ViewModel.SelectedParcela.get_Id()); + filtroArquivoDigital1.set_IdApolice(this.ViewModel.SelectedParcela.get_Documento().get_Id()); + filtroArquivoDigital1.set_Tipo(3); + filtroArquivoDigital1.set_Parente(this.ViewModel.SelectedParcela); + filtroArquivoDigital = filtroArquivoDigital1; + } + else + { + await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", ValidationHelper.GetDescription((TipoArquivoDigital)3), "."), "OK", "", false); + return; + } + } + } + else if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 2).get_Consultar()) + { + FiltroArquivoDigital filtroArquivoDigital2 = new FiltroArquivoDigital(); + filtroArquivoDigital2.set_Id(this.ViewModel.SelectedDocumento.get_Id()); + filtroArquivoDigital2.set_Tipo(2); + filtroArquivoDigital2.set_Parente(this.ViewModel.SelectedDocumento); + filtroArquivoDigital = filtroArquivoDigital2; + } + else + { + await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", ValidationHelper.GetDescription((TipoArquivoDigital)2), "."), "OK", "", false); + return; + } + this.ViewModel.ShowDrawer(new ArquivoDigitalDrawer(filtroArquivoDigital), 0, false); + } + + private async void AbrirImportacao() + { + await this.ViewModel.Importacao(); + ((System.Windows.Controls.ToolTip)this.ButtonImportado.ToolTip).PlacementTarget = this.ButtonImportado; + ((System.Windows.Controls.ToolTip)this.ButtonImportado.ToolTip).Placement = PlacementMode.Center; + ((System.Windows.Controls.ToolTip)this.ButtonImportado.ToolTip).IsOpen = true; + await Task.Run(async () => await Task.Delay(5000)); + ((System.Windows.Controls.ToolTip)this.ButtonImportado.ToolTip).IsOpen = false; + } + + private void AbrirInfo_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirInfo(); + } + + private void AbrirLog_OnClick(object sender, RoutedEventArgs e) + { + if (this.ViewModel.SelectedDocumento != null && this.ViewModel.SelectedDocumento.get_Id() != 0) + { + this.ViewModel.AbrirLog(2, this.ViewModel.SelectedDocumento.get_Id()); + } + } + + private void AbrirLogEmail_OnClick(object sender, RoutedEventArgs e) + { + if (this.ViewModel.SelectedDocumento != null && this.ViewModel.SelectedDocumento.get_Id() != 0) + { + this.ViewModel.AbrirLogEmail(2, this.ViewModel.SelectedDocumento.get_Id()); + } + } + + private void AbrirLogEmailPF_OnClick(object sender, RoutedEventArgs e) + { + if (this.ViewModel.SelectedParcela != null && this.ViewModel.SelectedParcela.get_Id() != 0) + { + this.ViewModel.AbrirLogEmail(5, this.ViewModel.SelectedParcela.get_Id()); + } + } + + private void AbrirLogParcelaAntigo_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLogAntigoParcela(); + } + + private async void AbrirLogParcelas_OnClick(object sender, RoutedEventArgs e) + { + bool count; + ApoliceView apoliceView = this; + if (apoliceView.ViewModel.SelectedDocumento != null) + { + ApoliceViewModel viewModel = apoliceView.ViewModel; + if (viewModel != null) + { + count = viewModel.Parcelas.Count > 0; + } + else + { + count = false; + } + if (count) + { + List nums = new List(); + apoliceView.ViewModel.Parcelas.ToList().ForEach((Parcela x) => nums.Add(x.get_Id())); + apoliceView.ViewModel.AbrirLogParcela(nums, apoliceView.ViewModel.SelectedDocumento.get_Id(), 0); + } + } + } + + private void AbrirLogParcelaSelecionada_OnClick(object sender, RoutedEventArgs e) + { + if (this.ViewModel.SelectedParcela != null && this.ViewModel.SelectedParcela.get_Id() != 0) + { + List nums = new List() + { + this.ViewModel.SelectedParcela.get_Id() + }; + if (this.ViewModel.SelectedDocumento != null && this.ViewModel.SelectedDocumento.get_Id() != 0) + { + this.ViewModel.AbrirLogParcela(nums, this.ViewModel.SelectedDocumento.get_Id(), this.ViewModel.SelectedParcela.get_NumeroParcela()); + } + } + } + + private void AbrirLogTrocaCliente_OnClick(object sender, RoutedEventArgs e) + { + if (this.ViewModel.SelectedDocumento != null && this.ViewModel.SelectedDocumento.get_Id() != 0) + { + this.ViewModel.AbrirLog(41, this.ViewModel.SelectedDocumento.get_Id()); + } + } + + private void AbrirLogVendedor_OnClick(object sender, RoutedEventArgs e) + { + if (this.ViewModel.SelectedParcela != null && this.ViewModel.SelectedParcela.get_Id() != 0) + { + this.ViewModel.AbrirLog(37, this.ViewModel.SelectedParcela.get_Id()); + } + } + + private async void AbrirPerfil_OnClick(object sender, RoutedEventArgs e) + { + if (await this.ViewModel.VerificarPermissao(32, false)) + { + if (this.ViewModel.SelectedDocumento.get_Controle().get_Ramo().get_Id() != (long)5) + { + (new HosterWindow(new PerfilEmpresaView(this.ViewModel.SelectedDocumento.get_Controle()), "QUESTIONÁRIO EMPRESA", new double?((double)900), new double?((double)500), false)).ShowDialog(); + } + else + { + (new HosterWindow(new PerfilView(this.ViewModel.SelectedDocumento.get_Controle()), "PERFIL", new double?((double)900), new double?((double)500), false)).ShowDialog(); + } + this.ViewModel.Alterar(false); + } + } + + private async Task AbrirProspeccao(Prospeccao data) + { + do + { + Label1: + if (await this.ViewModel.ShowProspeccaoDialog(data) != null) + { + List> keyValuePairs = await this.ViewModel.SalvarProspeccao(data); + if (keyValuePairs == null || keyValuePairs.Count == 0) + { + this.ViewModel.ToggleSnackBar("PROSPECÇÃO SALVA COM SUCESSO.", true); + return; + } + else + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + goto Label1; + } + } + else + { + } + } + while (!await this.ViewModel.ShowMessage("DESEJA REALMENTE NÃO CADASTRAR UMA PROSPECÇÃO PARA ESSE DOCUMENTO?", "SIM", "NÃO", false)); + } + + private void AcessarApolice(Gestor.Model.Common.AcessoApolice acesso) + { + if (acesso == 2) + { + this.Endossar_OnClick(this, new RoutedEventArgs()); + this.Restricao(true); + return; + } + if (acesso != 3) + { + return; + } + this.Renovar_OnClick(this, new RoutedEventArgs()); + this.Restricao(true); + } + + private void AdicionalBox_OnChecked(object sender, RoutedEventArgs e) + { + if (this.ViewModel.SelectedDocumento == null) + { + return; + } + this.AlteracaoDePremio_LostFocus(this.PremioAdicionalBox, new RoutedEventArgs()); + } + + private void AdicionarCoCorretagem_OnClick(object sender, RoutedEventArgs e) + { + bool valueOrDefault; + bool selectedItem; + bool flag; + ToggleButton toggleButton = (ToggleButton)sender; + if (toggleButton != null) + { + valueOrDefault = toggleButton.IsChecked.GetValueOrDefault(); + } + else + { + valueOrDefault = false; + } + bool flag1 = valueOrDefault; + ComboBox comissaoNovoComboBox = this.ComissaoNovoComboBox; + if (comissaoNovoComboBox != null) + { + selectedItem = comissaoNovoComboBox.SelectedItem; + } + else + { + selectedItem = false; + } + if (selectedItem) + { + this.ComissaoNovoComboBox.SelectedItem = null; + } + if (flag1) + { + this.TipoVendedorBox.SelectedIndex = 0; + } + else if (this.TipoVendedorBox.SelectedItem != null) + { + this.TipoVendedorBox.SelectedItem = null; + } + ComboBox vendedorBox = this.VendedorBox; + if (vendedorBox != null) + { + flag = vendedorBox.SelectedItem; + } + else + { + flag = false; + } + if (flag) + { + this.VendedorBox.SelectedItem = null; + } + if (ValidationHelper.IsNotNullOrEmpty(this.ValorRepasseBox.Text)) + { + this.ValorRepasseBox.Text = ""; + } + this.ViewModel.VendedorCoCorretagem(flag1); + } + + private void AlteracaoDePremio_LostFocus(object sender, RoutedEventArgs e) + { + decimal iof; + if (!this.ViewModel.AllowEditApolice) + { + return; + } + if (this.ViewModel.SelectedDocumento == null) + { + return; + } + CurrencyTextBox currencyTextBox = (CurrencyTextBox)sender; + if (currencyTextBox == null) + { + return; + } + string name = currencyTextBox.Name; + if ((name == "PremioLiquidoBox" || name == "PremioAdicionalBox") && this.IofBox.get_Number() == decimal.Zero) + { + decimal number = this.PremioLiquidoBox.get_Number() + this.PremioAdicionalBox.get_Number(); + Ramo ramo = this.ViewModel.SelectedDocumento.get_Controle().get_Ramo(); + if (ramo != null) + { + iof = ramo.get_Iof(); + } + else + { + iof = decimal.Zero; + } + decimal num = number * iof; + this.IofBox.set_Number(num); + CurrencyTextBox premioTotalBox = this.PremioTotalBox; + premioTotalBox.set_Number(premioTotalBox.get_Number() + num); + } + this.PremioTotalBox.set_Number(((this.PremioLiquidoBox.get_Number() + this.PremioAdicionalBox.get_Number()) + this.IofBox.get_Number()) + this.DiferencaBox.get_Number()); + name = currencyTextBox.Name; + if ((name == "PremioLiquidoBox" || name == "PremioAdicionalBox" || name == "ComissaoBox") && this.ViewModel.HabilitarVendedor(0).Count == 0) + { + this.ViewModel.RecalculaRepasses(); + } + this.ValidarDocumento(); + } + + private void AlteracaoParcela_LostFocus(object sender, RoutedEventArgs e) + { + this.ValidarDocumento(); + } + + public void AlterandoDocumento(bool alterando) + { + PermissaoUsuario permissaoUsuario = this.ViewModel.ServicoPermissUsuario.BuscarPermissao(Recursos.Usuario, 2); + this.EditarVendedorButton.IsEnabled = ((permissaoUsuario != null ? permissaoUsuario.get_Incluir() : true) ? !alterando : false); + } + + private async void Alterar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.UpdatePremio = false; + this.Restricao(false); + ApoliceViewModel viewModel = this.ViewModel; + List configuracoes = Recursos.Configuracoes; + if (configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 34)) + { + flag = true; + } + else + { + List repasses = this.ViewModel.Repasses; + flag = repasses.All((VendedorParcela x) => !x.get_DataPagamento().HasValue); + } + viewModel.EnableControle = flag; + ApoliceViewModel apoliceViewModel = this.ViewModel; + List vendedorParcelas = this.ViewModel.Repasses; + apoliceViewModel.CoCorretagem = vendedorParcelas.Any((VendedorParcela x) => { + Gestor.Model.Domain.Seguros.Repasse repasse = x.get_Repasse(); + if (repasse == null) + { + return false; + } + return repasse.get_Tipo().GetValueOrDefault() == 3; + }); + this.ViewModel.VerificaCoCorretagem(); + await this.ViewModel.Alteracao(true); + this.ViewModel.Alterar(true); + this.ValidarTela(); + this.AlterandoDocumento(true); + this.ExcluirpoliceButton.IsEnabled = false; + this.IncluirpoliceButton.IsEnabled = false; + this.AlterarApoliceButton.IsEnabled = false; + this.ViewModel.Inclusao = false; + } + + private void AlterarParcela() + { + this.FaturaField.Visibility = (this.ViewModel.IsFatura ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.QuantidadeFaturaField.Visibility = (this.ViewModel.IsFatura ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.VigenciaInicialField.Visibility = (this.ViewModel.IsFatura ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.VigenciaFinalField.Visibility = (this.ViewModel.IsFatura ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.ValorLiquidoField.Visibility = (this.ViewModel.IsFatura ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.PercentualComissaoField.Visibility = (this.ViewModel.IsFatura ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.ComissaoIcon.Visibility = (this.ViewModel.IsFatura ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.EmissaoField.Visibility = (this.ViewModel.IsFatura ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.RecebimentoField.Visibility = System.Windows.Visibility.Collapsed; + this.QuitacaoField.Visibility = System.Windows.Visibility.Visible; + this.DataControleParcelaField.Visibility = System.Windows.Visibility.Visible; + this.ValorRealizadoField.Visibility = System.Windows.Visibility.Collapsed; + this.CreditoField.Visibility = System.Windows.Visibility.Collapsed; + this.ValorComissaoField.Visibility = System.Windows.Visibility.Collapsed; + this.VencimentoField.Visibility = System.Windows.Visibility.Visible; + this.ValorField.Visibility = System.Windows.Visibility.Visible; + this.TipoParcelaField.Visibility = System.Windows.Visibility.Collapsed; + this.VencimentoField.Visibility = System.Windows.Visibility.Visible; + this.ValorField.Visibility = System.Windows.Visibility.Visible; + this.EditarParcelasFields.Visibility = System.Windows.Visibility.Visible; + this.ValidarParcela(); + } + + private void AlterarParcela_Click(object sender, RoutedEventArgs e) + { + this.ViewModel.QuantidadeFaturas = 1; + if (this.ViewModel.Parcelas.Count == 0) + { + return; + } + this.ToggleBotoesParcela(true); + this.EditarParcelaTipo = 1; + this.ViewModel.SelecionaPrimeiraParcela(); + this.AlterarParcela(); + Action enableMainMenu = Gestor.Application.Actions.Actions.EnableMainMenu; + if (enableMainMenu != null) + { + enableMainMenu(false); + } + else + { + } + Action enableMenu = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu != null) + { + enableMenu(false); + } + else + { + } + this.ViewModel.AllowEditVendedor = this.ViewModel.IsFatura; + } + + private void ApoliceControl_SizeChanged(object sender, SizeChangedEventArgs e) + { + bool flag; + if (e != null) + { + Size newSize = e.NewSize; + flag = false; + } + else + { + flag = true; + } + if (flag) + { + return; + } + this.Redimencionar(e.NewSize.Width); + } + + private async void ApoliceView_OnLoaded(object sender, RoutedEventArgs e) + { + while (!this.ViewModel.Loaded) + { + await Task.Delay(100); + } + this.AcessarApolice(this.AcessoApolice); + } + + private void AutoCompleteBanco_OnLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) + { + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + ApoliceView.SetValid(autoCompleteBox, (string.IsNullOrWhiteSpace(autoCompleteBox.get_Text()) ? true : this.ViewModel.SelectedDocumento.get_Banco() != null)); + } + + private void AutoCompleteBancoBox_Populating(object sender, PopulatingEventArgs e) + { + if (e.get_Parameter().Length < 3) + { + return; + } + e.set_Cancel(true); + this.ViewModel.BuscarBanco(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void BaixarParcelas() + { + this.FaturaField.Visibility = (this.ViewModel.IsFatura ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.VigenciaInicialField.Visibility = (this.ViewModel.IsFatura ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.VigenciaFinalField.Visibility = (this.ViewModel.IsFatura ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.PercentualComissaoField.Visibility = (this.ViewModel.IsFatura ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.ComissaoIcon.Visibility = (this.ViewModel.IsFatura ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.QuantidadeFaturaField.Visibility = System.Windows.Visibility.Collapsed; + this.QuitacaoField.Visibility = System.Windows.Visibility.Collapsed; + this.DataControleParcelaField.Visibility = System.Windows.Visibility.Collapsed; + this.EmissaoField.Visibility = System.Windows.Visibility.Collapsed; + this.ValorLiquidoField.Visibility = System.Windows.Visibility.Visible; + this.VencimentoField.Visibility = System.Windows.Visibility.Collapsed; + this.ValorField.Visibility = System.Windows.Visibility.Collapsed; + this.TipoParcelaField.Visibility = System.Windows.Visibility.Collapsed; + this.RecebimentoField.Visibility = System.Windows.Visibility.Visible; + this.CreditoField.Visibility = System.Windows.Visibility.Visible; + this.ValorRealizadoField.Visibility = System.Windows.Visibility.Visible; + this.ValorComissaoField.Visibility = System.Windows.Visibility.Visible; + this.EditarParcelasFields.Visibility = System.Windows.Visibility.Visible; + if (Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 5)) + { + this.ImpostosField.Visibility = System.Windows.Visibility.Visible; + } + this.ParcelaGrid.IsEnabled = false; + this.ValidarParcela(); + this.RecebimentoParcelaBox.Focus(); + } + + private async void BaixarParcelas_Click(object sender, RoutedEventArgs e) + { + this.ParcelaGrid.IsEnabled = false; + ((MenuItem)sender).Click -= new RoutedEventHandler(this.BaixarParcelas_Click); + this.ViewModel.QuantidadeFaturas = 1; + if (await this.ViewModel.SelecionarParcelaBaixa()) + { + this.ToggleBotoesParcela(true); + this.ViewModel.BaixarParcelas = true; + await this.ViewModel.CarregarImposto(); + this.EditarParcelaTipo = 2; + this.BaixarParcelas(); + Action enableMainMenu = Gestor.Application.Actions.Actions.EnableMainMenu; + if (enableMainMenu != null) + { + enableMainMenu(false); + } + else + { + } + Action enableMenu = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu != null) + { + enableMenu(false); + } + else + { + } + ((MenuItem)sender).Click += new RoutedEventHandler(this.BaixarParcelas_Click); + this.ViewModel.AllowEditVendedor = false; + } + } + + private async void Button_Click(object sender, RoutedEventArgs e) + { + bool flag = this.ViewModel.Restricao(97); + if (!flag) + { + Documento documento = this.ViewModel.AbrirDetalhes(); + this.ViewModel.ShowDrawer(new ValoresApoliceDrawer(documento), 0, true); + } + if (flag) + { + await this.ViewModel.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR MAIS INFORMAÇÕES.", "OK", "", false); + } + } + + private void CalculoComissao_OnNumberChanged(object sender, EventArgs e) + { + bool id; + bool flag; + bool id1; + bool flag1; + bool id2; + bool flag2; + if (!this.ViewModel.BaixarParcelas || this._calculando) + { + return; + } + this._calculando = true; + decimal number = this.ValorComissaoParcelaBox.get_Number(); + this.PorcentagemIrBox.remove_NumberChanged(new EventHandler(this.PorcentagemIrBox_OnNumberChanged)); + this.PorcentagemIssBox.remove_NumberChanged(new EventHandler(this.PorcentagemIssBox_OnNumberChanged)); + Imposto imposto = this.ViewModel.Imposto; + if (imposto != null) + { + id = imposto.get_Id() > (long)0; + } + else + { + id = false; + } + if (id) + { + this.PorcentagemIrBox.set_Number(this.ViewModel.Imposto.get_Ir() * new decimal(100)); + } + Imposto imposto1 = this.ViewModel.Imposto; + if (imposto1 != null) + { + flag = imposto1.get_Id() > (long)0; + } + else + { + flag = false; + } + if (flag) + { + this.PorcentagemIssBox.set_Number(this.ViewModel.Imposto.get_Iss() * new decimal(100)); + } + this.PorcentagemIrBox.add_NumberChanged(new EventHandler(this.PorcentagemIrBox_OnNumberChanged)); + this.PorcentagemIssBox.add_NumberChanged(new EventHandler(this.PorcentagemIssBox_OnNumberChanged)); + Imposto imposto2 = this.ViewModel.Imposto; + if (imposto2 != null) + { + id1 = imposto2.get_Id() > (long)0; + } + else + { + id1 = false; + } + decimal num = (id1 ? number * this.ViewModel.Imposto.get_Ir() : this.ValorIrBox.get_Number()); + if (this.ValorIrBox.get_Number() != num) + { + this.ViewModel.SelectedParcela.set_Irr(num); + } + Imposto imposto3 = this.ViewModel.Imposto; + if (imposto3 != null) + { + flag1 = imposto3.get_Id() > (long)0; + } + else + { + flag1 = false; + } + decimal num1 = (flag1 ? number * this.ViewModel.Imposto.get_Iss() : this.ValorIssBox.get_Number()); + if (this.ValorIssBox.get_Number() != num1) + { + this.ViewModel.SelectedParcela.set_Iss(num1); + } + Imposto imposto4 = this.ViewModel.Imposto; + if (imposto4 != null) + { + id2 = imposto4.get_Id() > (long)0; + } + else + { + id2 = false; + } + decimal num2 = (id2 ? number * this.ViewModel.Imposto.get_Outros() : this.ValorOutrosBox.get_Number()); + if (this.ValorOutrosBox.get_Number() != num2) + { + this.ViewModel.SelectedParcela.set_Outros(num2); + } + Imposto imposto5 = this.ViewModel.Imposto; + if (imposto5 != null) + { + flag2 = imposto5.get_Id() > (long)0; + } + else + { + flag2 = false; + } + decimal num3 = (flag2 ? number * this.ViewModel.Imposto.get_Desconto() : this.ValorDescontoBox.get_Number()); + if (this.ValorDescontoBox.get_Number() != num3) + { + this.ViewModel.SelectedParcela.set_Desconto(num3); + } + this.ValorComDescBox.set_Number((((number - num) - num1) - num2) - num3); + this.ViewModel.OnPropertyChanged("SelectedParcela"); + this._calculando = false; + } + + private void CancelarAlteracao() + { + ApoliceView.SetValid(this.AutoCompleteBanco, true); + this.AutoCompleteBanco.set_Text(string.Empty); + this.ViewModel.BotoesParcelaEnabled = true; + this.ViewModel.AlteracaoEnabled = true; + this.EditarVendedor(false); + this.ValidarDocumento(); + } + + private async void CancelarApolice_OnClick(object sender, RoutedEventArgs e) + { + this.CancelarAlteracao(); + await this.ViewModel.CancelarAlteracao(); + this.AlterandoDocumento(false); + this.EditandoVendedor(false); + this.Restricao(false); + } + + private void CancelarParcela_Click(object sender, RoutedEventArgs e) + { + this.ToggleBotoesParcela(false); + this.ViewModel.BaixarParcelas = false; + this.ViewModel.CancelPagamento(); + this.ValidarDocumento(); + this.EditarVendedor(false); + Action enableMainMenu = Gestor.Application.Actions.Actions.EnableMainMenu; + if (enableMainMenu != null) + { + enableMainMenu(true); + } + else + { + } + Action enableMenu = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu != null) + { + enableMenu(true); + } + else + { + } + this.EditandoParcela(false); + } + + private void CancelarVendedor_Click(object sender, RoutedEventArgs e) + { + this.EditarVendedor(false); + this.ViewModel.SelectedPagamento = null; + this.ViewModel.AllowEditParcela = true; + this.EditandoVendedor(false); + } + + private void ComissaoVendedorBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + decimal? valorRepasse; + bool valueOrDefault; + ComboBox comboBox = (ComboBox)sender; + if (comboBox.SelectedItem == null) + { + return; + } + Gestor.Model.Domain.Seguros.Repasse selectedItem = (Gestor.Model.Domain.Seguros.Repasse)comboBox.SelectedItem; + if (selectedItem != null && selectedItem.get_Tipo().GetValueOrDefault() == 3) + { + this.ViewModel.SelectedPagamento.set_ValorRepasse(new decimal?(new decimal(0, 0, 0, false, 2))); + CurrencyTextBox valorRepasseBox = this.ValorRepasseBox; + valorRepasse = this.ViewModel.SelectedPagamento.get_ValorRepasse(); + valorRepasseBox.set_Number(valorRepasse.Value); + return; + } + if (this.ViewModel.SelectedDocumento.get_NegocioCorretora().HasValue) + { + NegocioCorretora? negocioCorretora = this.ViewModel.SelectedDocumento.get_NegocioCorretora(); + valueOrDefault = negocioCorretora.GetValueOrDefault() == 1; + } + else if (this.ViewModel.SelectedDocumento.get_Situacao() != 2 || !this.ViewModel.SelectedDocumento.get_Negocio().HasValue) + { + valueOrDefault = false; + } + else + { + Negocio? negocio = this.ViewModel.SelectedDocumento.get_Negocio(); + valueOrDefault = negocio.GetValueOrDefault() == 1; + } + bool flag = valueOrDefault; + this.ViewModel.SelectedPagamento.set_Repasse(selectedItem); + this.ViewModel.SelectedPagamento.set_PorcentagemRepasse(new decimal?((flag ? selectedItem.get_ValorRenovacao() : selectedItem.get_ValorNovo()))); + if (this.ViewModel.SelectedParcela == null) + { + ApoliceViewModel viewModel = this.ViewModel; + Parcela parcela = new Parcela(); + parcela.set_SubTipo(1); + viewModel.SelectedParcela = parcela; + } + this.ViewModel.SelectedParcela.set_Documento(this.ViewModel.SelectedDocumento); + this.ViewModel.SelectedPagamento.set_ValorRepasse(new decimal?(Funcoes.CalculaRepasse(selectedItem, this.ViewModel.SelectedParcela, (this.ViewModel.SelectedParcela == null ? true : this.ViewModel.SelectedParcela.get_SubTipo() == 1)))); + this.ViewModel.SelectedPagamento.set_ValorTotal(this.ViewModel.SelectedPagamento.get_ValorRepasse()); + CurrencyTextBox currencyTextBox = this.ValorRepasseBox; + valorRepasse = this.ViewModel.SelectedPagamento.get_ValorRepasse(); + currencyTextBox.set_Number(valorRepasse.Value); + this.FormaRecebidaBox.Text = ValidationHelper.GetDescription(selectedItem.get_Forma()); + this.FormaIncidenciaBox.Text = ValidationHelper.GetDescription(selectedItem.get_Incidencia()); + } + + private void ContentLoad() + { + string nome; + this.ParcelaGrid.SelectionChanged += new SelectionChangedEventHandler(this.ParcelaGrid_OnSelectionChanged); + this.ApoliceBox.LostFocus += new RoutedEventHandler(this.ValidacaoDocumento); + this.EndossoBox.LostFocus += new RoutedEventHandler(this.ValidacaoDocumento); + this.TipoEndossoBox.SelectionChanged += new SelectionChangedEventHandler(this.TipoEndossoBox_OnSelectionChanged); + this.TipoRecebimentoBox.SelectionChanged += new SelectionChangedEventHandler(this.TipoRecebimentoBox_OnSelectionChanged); + this.SituacaoBox.SelectionChanged += new SelectionChangedEventHandler(this.SituacaoBox_OnSelectionChanged); + this.PremioLiquidoBox.LostFocus += new RoutedEventHandler(this.AlteracaoDePremio_LostFocus); + this.PremioAdicionalBox.LostFocus += new RoutedEventHandler(this.AlteracaoDePremio_LostFocus); + this.IofBox.LostFocus += new RoutedEventHandler(this.AlteracaoDePremio_LostFocus); + this.DiferencaBox.LostFocus += new RoutedEventHandler(this.AlteracaoDePremio_LostFocus); + this.AdicionalBox.Unchecked += new RoutedEventHandler(this.AdicionalBox_OnChecked); + this.AdicionalBox.Checked += new RoutedEventHandler(this.AdicionalBox_OnChecked); + this.ParcelasBox.LostFocus += new RoutedEventHandler(this.AlteracaoParcela_LostFocus); + this.NegocioCorretoraBox.SelectionChanged += new SelectionChangedEventHandler(this.NegocioCorretoraBox_OnSelectionChanged); + this.ComissaoBox.LostFocus += new RoutedEventHandler(this.AlteracaoDePremio_LostFocus); + this.DataBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.DataBox.PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + this.VendedorBox.SelectionChanged += new SelectionChangedEventHandler(this.VendedorBox_OnSelectionChanged); + this.TipoVendedorBox.SelectionChanged += new SelectionChangedEventHandler(this.TipoVendedorBox_OnSelectionChanged); + this.ValorLiquidoParcelaBox.LostFocus += new RoutedEventHandler(this.ValorParcelaBox_OnLostFocus); + this.ComissaoParcelaBox.LostFocus += new RoutedEventHandler(this.Recalcula); + this.ValorLiquidoParcelaBox.LostFocus += new RoutedEventHandler(this.Recalcula); + this.ValorComissaoParcelaBox.LostFocus += new RoutedEventHandler(this.Recalcula); + this.ValorRealizadoParcelaBox.LostFocus += new RoutedEventHandler(this.Recalcula); + this.ValorParcelaBox.LostFocus += new RoutedEventHandler(this.Recalcula); + bool flag = Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 5); + this.ValorDescontoField.Visibility = (flag ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + base.SizeChanged += new SizeChangedEventHandler(this.ApoliceControl_SizeChanged); + if (this.ViewModel.SelectedDocumento == null) + { + return; + } + AutoCompleteBox autoCompleteBanco = this.AutoCompleteBanco; + Banco banco = this.ViewModel.SelectedDocumento.get_Banco(); + if (banco != null) + { + nome = banco.get_Nome(); + } + else + { + nome = null; + } + autoCompleteBanco.set_Text(nome); + ApoliceViewModel viewModel = this.ViewModel; + TipoRecebimento? tipoRecebimento = this.ViewModel.SelectedDocumento.get_TipoRecebimento(); + viewModel.IsFatura = tipoRecebimento.GetValueOrDefault(1) == 2; + this.Parcelas(!this.ViewModel.IsFatura); + } + + public void EditandoParcela(bool enable) + { + PermissaoUsuario permissaoUsuario = this.ViewModel.ServicoPermissUsuario.BuscarPermissao(Recursos.Usuario, 2); + this.ViewModel.AllowEditVendedor = ((permissaoUsuario != null ? permissaoUsuario.get_Incluir() : true) ? !enable : false); + } + + public void EditandoVendedor(bool enable) + { + PermissaoUsuario permissaoUsuario = this.ViewModel.ServicoPermissUsuario.BuscarPermissao(Recursos.Usuario, 2); + this.IncluirpoliceButton.IsEnabled = ((permissaoUsuario != null ? permissaoUsuario.get_Incluir() : true) ? !enable : false); + this.AlterarApoliceButton.IsEnabled = ((permissaoUsuario != null ? permissaoUsuario.get_Alterar() : true) ? !enable : false); + this.ExcluirpoliceButton.IsEnabled = ((permissaoUsuario != null ? permissaoUsuario.get_Excluir() : true) ? !enable : false); + } + + private async void EditarParcelas_OnClick(object sender, RoutedEventArgs e) + { + await this.ViewModel.EditarParcelas(); + } + + private void EditarVendedor(bool editar) + { + bool valueOrDefault; + bool flag; + this.SalvarVendedorButton.Visibility = (editar ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.CancelarVendedorButton.Visibility = (editar ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.EditarVendedorButton.Visibility = (editar ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible); + this.EditarVendedorFields.Visibility = (editar ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.VendedorGrid.IsEnabled = !editar; + if (editar) + { + if (Recursos.Configuracoes.Any((ConfiguracaoSistema config) => config.get_Configuracao() == 56)) + { + if (this.ViewModel.Pagamentos.Count == 1) + { + if (!this.ViewModel.Pagamentos.Any((VendedorParcela vendedor) => vendedor.get_Repasse() == null)) + { + goto Label1; + } + flag = !this.IsFatura(); + goto Label0; + } + Label1: + flag = false; + Label0: + this.CoCorretagemToogle.IsEnabled = flag; + } + } + if (this.ViewModel.SelectedDocumento.get_NegocioCorretora().HasValue) + { + NegocioCorretora? negocioCorretora = this.ViewModel.SelectedDocumento.get_NegocioCorretora(); + valueOrDefault = negocioCorretora.GetValueOrDefault() == 1; + } + else if (this.ViewModel.SelectedDocumento.get_Situacao() != 2 || !this.ViewModel.SelectedDocumento.get_Negocio().HasValue) + { + valueOrDefault = false; + } + else + { + Negocio? negocio = this.ViewModel.SelectedDocumento.get_Negocio(); + valueOrDefault = negocio.GetValueOrDefault() == 1; + } + bool flag1 = valueOrDefault; + this.ComissaoNovoBox.Visibility = (!editar || flag1 ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible); + this.ComissaoRenovacaoBox.Visibility = (editar & flag1 ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.CoCorretagemToogle.IsChecked = new bool?(false); + } + + private void Endossar() + { + this.ViewModel.AlteracaoEnabled = false; + this.ViewModel.Situacao.Add(3); + this.ValidarDocumento(); + } + + private async void Endossar_OnClick(object sender, RoutedEventArgs e) + { + if (this.ViewModel.Restricao(33)) + { + await this.ViewModel.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA ENDOSSAR. PROCURE O ADMINSTRADOR DO SISTEMA.", "OK", "", false); + } + else if (!this.ViewModel.EnableEndossar) + { + List> keyValuePairs = this.ViewModel.SelectedDocumento.ValidateEndossar(); + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + else if (await this.ViewModel.IncluirEndosso()) + { + this.ViewModel.BotoesParcelaEnabled = false; + this.Endossar(); + this.Restricao(true); + } + } + + private async void ExcluirDocumento_OnClick(object sender, RoutedEventArgs e) + { + await this.ViewModel.ExcluirApolice(); + } + + private async void ExcluirParcela_Click(object sender, RoutedEventArgs e) + { + if (await this.ViewModel.PagamentoVendedor(this.ViewModel.SelectedParcela)) + { + bool? nullable = await this.ViewModel.ShowSenha("HÁ PAGAMENTOS DE VENDEDORES REALIZADOS PARA ESSA PARCELA. DESEJA PROSSEGUIR COM A EXCLUSÃO?"); + if (!nullable.HasValue) + { + return; + } + else if (!nullable.GetValueOrDefault()) + { + await this.ViewModel.ShowMessage("SENHA INVÁLIDA", "OK", "", false); + return; + } + } + if (!this.ViewModel.SelectedParcela.get_DataRecebimento().HasValue) + { + await this.ViewModel.ExcluirParcela(); + } + else + { + await this.ViewModel.ExcluirBaixa(); + } + this.EditandoParcela(true); + } + + private async void ExcluirVendedor_Click(object sender, RoutedEventArgs e) + { + TipoRepasse? nullable; + TipoRepasse? tipo; + bool flag; + System.Windows.Visibility visibility; + bool flag1; + VendedorParcela dataContext; + ((Button)sender).Click -= new RoutedEventHandler(this.ExcluirVendedor_Click); + Button button = (Button)sender; + if (button != null && button.DataContext != null) + { + dataContext = (VendedorParcela)button.DataContext; + VendedorParcela vendedorParcela = dataContext; + if (vendedorParcela != null) + { + Gestor.Model.Domain.Seguros.Repasse repasse1 = vendedorParcela.get_Repasse(); + if (repasse1 != null) + { + tipo = repasse1.get_Tipo(); + } + else + { + nullable = null; + tipo = nullable; + } + nullable = tipo; + flag = nullable.GetValueOrDefault() == 3; + } + else + { + flag = false; + } + bool flag2 = flag; + if (this.AlterarApoliceButton.IsEnabled || !this.SalvarApoliceButton.IsEnabled) + { + if (dataContext != null && !dataContext.get_DataPagamento().HasValue) + { + if (this.ViewModel._excluirPermissEnabled) + { + if (dataContext.get_CoCorretagem()) + { + ObservableCollection pagamentos = this.ViewModel.Pagamentos; + IEnumerable vendedorParcelas = pagamentos.Where((VendedorParcela pgt) => { + bool valueOrDefault; + Gestor.Model.Domain.Seguros.Repasse repasse = pgt.get_Repasse(); + valueOrDefault = (repasse != null ? repasse.get_Tipo().GetValueOrDefault() != 3 : true); + if (!valueOrDefault) + { + return false; + } + return !pgt.get_Vendedor().get_Corretora(); + }); + if (vendedorParcelas != null) + { + flag1 = vendedorParcelas.Count() >= 1; + } + else + { + flag1 = false; + } + if (flag1) + { + await this.ViewModel.ShowMessage("NÃO É POSSÍVEL EXCLUIR O VENDEDOR CO-CORRETAGEM. HÁ VENDEDORES CADASTRADOS NO DOCUMENTO", "OK", "", false); + dataContext = null; + return; + } + } + await this.ViewModel.ExcluirVendedor(dataContext, true); + } + else + { + await this.ViewModel.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA EXCLUIR VENDEDORES. ENTRE EM CONTATO COM O ADMINISTRADOR DO SISTEMA.", "OK", "", false); + dataContext = null; + return; + } + } + else if (await this.ViewModel.ShowSenha(string.Format("DESEJA REALMENTE EXCLUIR O PAGAMENTO DO VENDEDOR {0} {1:d}?\nESSE PROCEDIMENTO É IRREVERSÍVEL.", dataContext.get_Vendedor().get_Nome(), dataContext.get_DataPagamento())).GetValueOrDefault()) + { + await this.ViewModel.ExcluirPagamento(dataContext); + } + this.ComissaoBox.IsReadOnly = this.ViewModel.VerificaCoCorretagem(); + ApoliceViewModel viewModel = this.ViewModel; + visibility = (this.ComissaoBox.IsReadOnly ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + viewModel.ComissOriginalVisibility = visibility; + if (flag2) + { + await this.ViewModel.AjusteComissãoCoCorretagem(true); + } + ((Button)sender).Click += new RoutedEventHandler(this.ExcluirVendedor_Click); + } + else + { + await this.ViewModel.ShowMessage("NÃO É POSSÍVEL EXCLUIR VENDEDOR DURANTE ALTERAÇÃO DE DOCUMENTO.", "OK", "", false); + } + } + dataContext = null; + } + + private void ExecutarValidacaoDataApolice() + { + DateTime dateTime; + DateTime? nullable; + DateTime? nullable1; + DateTime? nullable2; + DateTime? nullable3; + DateTime? nullable4; + Documento selectedDocumento = this.ViewModel.SelectedDocumento; + if (DateTime.TryParse(ValidationHelper.FormatDate(this.Vigencia2Box.Text), out dateTime)) + { + nullable1 = new DateTime?(dateTime); + } + else + { + nullable = null; + nullable1 = nullable; + } + selectedDocumento.set_Vigencia2(nullable1); + Documento documento = this.ViewModel.SelectedDocumento; + if (DateTime.TryParse(ValidationHelper.FormatDate(this.TransmissaoBox.Text), out dateTime)) + { + nullable2 = new DateTime?(dateTime); + } + else + { + nullable = null; + nullable2 = nullable; + } + documento.set_Remessa(nullable2); + Documento selectedDocumento1 = this.ViewModel.SelectedDocumento; + if (DateTime.TryParse(ValidationHelper.FormatDate(this.EmissaoBox.Text), out dateTime)) + { + nullable3 = new DateTime?(dateTime); + } + else + { + nullable = null; + nullable3 = nullable; + } + selectedDocumento1.set_Emissao(nullable3); + Documento documento1 = this.ViewModel.SelectedDocumento; + if (DateTime.TryParse(ValidationHelper.FormatDate(this.DataBox.Text), out dateTime)) + { + nullable4 = new DateTime?(dateTime); + } + else + { + nullable = null; + nullable4 = nullable; + } + documento1.set_DataControle(nullable4); + } + + private void FocusPremios(object sender, RoutedEventArgs e) + { + this.ViewModel.UpdatePremio = true; + } + + private void Importacao_OnClick(object sender, RoutedEventArgs e) + { + if (this.ViewModel.SelectedDocumento != null && this.ViewModel.SelectedDocumento.get_Id() != 0) + { + this.AbrirImportacao(); + } + } + + private async void IncluirApolice_OnClick(object sender, RoutedEventArgs e) + { + await this.ViewModel.IncluirApolice(false); + this.ViewModel.BotoesParcelaEnabled = false; + this.ViewModel.AllowEditEmissao = true; + this.ValidarDocumento(); + this.Restricao(true); + this.ValidarTela(); + this.IncluirpoliceButton.IsEnabled = false; + this.AlterarApoliceButton.IsEnabled = false; + this.ExcluirpoliceButton.IsEnabled = false; + this.AlterandoDocumento(true); + } + + private async void IncluirNovaFatura_Click(object sender, RoutedEventArgs e) + { + this.ViewModel.QuantidadeFaturas = 1; + bool flag = this.IsFatura(); + if (!flag || this.ViewModel.SelectedDocumento.get_Ordem() <= 0) + { + this.ToggleBotoesParcela(true); + this.EditarParcelaTipo = 3; + this.ViewModel.QuantidadeFaturas = 1; + this.NovaFatura(); + this.ViewModel.AllowEditVendedor = flag; + this.ViewModel.BaixarParcelas = true; + this.ViewModel.VisibilityAlterarVencimento = System.Windows.Visibility.Visible; + Action enableMainMenu = Gestor.Application.Actions.Actions.EnableMainMenu; + if (enableMainMenu != null) + { + enableMainMenu(false); + } + else + { + } + Action enableMenu = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu != null) + { + enableMenu(false); + } + else + { + } + } + else + { + await this.ViewModel.ShowMessage("NÃO É POSSÍVEL ADICIONAR FATURAS AO ENDOSSO, TODAS AS FATURAS DEVEM SER ADICIONADAS SOBRE A APÓLICE.", "OK", "", false); + } + } + + private void IncluirParcelaEspecial_Click(object sender, RoutedEventArgs e) + { + ((MenuItem)sender).Click -= new RoutedEventHandler(this.IncluirParcelaEspecial_Click); + this.ViewModel.QuantidadeFaturas = 1; + this.ToggleBotoesParcela(true); + this.EditarParcelaTipo = 4; + this.NovaParcelaEspecial(); + this.ViewModel.EditarParcelaEspecial(); + this.ViewModel.BaixarParcelas = true; + Action enableMainMenu = Gestor.Application.Actions.Actions.EnableMainMenu; + if (enableMainMenu != null) + { + enableMainMenu(false); + } + else + { + } + Action enableMenu = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu != null) + { + enableMenu(false); + } + else + { + } + ((MenuItem)sender).Click += new RoutedEventHandler(this.IncluirParcelaEspecial_Click); + this.EditandoParcela(true); + } + + private async void IncluirVendedor_Click(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.AllowEditParcela = false; + List> keyValuePairs = this.ViewModel.HabilitarVendedor(this.EditarParcelaTipo); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + if (flag) + { + this.ViewModel.IncluirVendedor(); + this.EditarVendedor(true); + this.ValidarVendedor(); + this.EditandoVendedor(true); + this.ViewModel.VendedorCoCorretagem(false); + } + else + { + this.ValidateFields(keyValuePairs, true); + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + } + + private void Initial_DatePicker_OnLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) + { + DateTime now; + bool flag; + base.DatePicker_OnLostKeyboardFocus(sender, e); + if (string.IsNullOrEmpty(((DatePicker)sender).Text)) + { + ((DatePicker)sender).SelectedDate = new DateTime?(DateTime.MinValue); + this.ViewModel.SelectedDocumento.set_Vigencia1(DateTime.MinValue); + Documento selectedDocumento = this.ViewModel.SelectedDocumento; + if (selectedDocumento != null) + { + selectedDocumento.get_Vigencia1(); + flag = true; + } + else + { + flag = false; + } + if (flag && this.ViewModel.SelectedDocumento.get_Vigencia1() == DateTime.MinValue) + { + DatePicker nullable = (DatePicker)sender; + now = DateTime.Now; + nullable.SelectedDate = new DateTime?(now.Date); + this.ViewModel.SelectedDocumento.set_Vigencia1(DateTime.Now.Date); + } + } + if (string.IsNullOrWhiteSpace(this.Vigencia2Box.Text)) + { + DatePicker vigencia2Box = this.Vigencia2Box; + now = ValidationHelper.ToDateTime(((DatePicker)sender).Text); + vigencia2Box.DisplayDate = now.AddYears(1); + DatePicker shortDateString = this.Vigencia2Box; + now = this.Vigencia2Box.DisplayDate; + shortDateString.Text = now.ToShortDateString(); + } + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/seguros/apoliceview.xaml", UriKind.Relative)); + } + + private bool IsFatura() + { + TipoRecebimento? tipoRecebimento = this.ViewModel.SelectedDocumento.get_TipoRecebimento(); + return tipoRecebimento.GetValueOrDefault() == 2; + } + + private void LostFocusValorRealizado() + { + if (this.ValorRealizadoParcelaBox.get_Number() == decimal.Zero || this.ViewModel.SelectedParcela == null || !this.ValorRealizadoParcelaBox.IsFocused) + { + return; + } + decimal number = this.ValorRealizadoParcelaBox.get_Number(); + decimal comissao = this.ViewModel.SelectedParcela.get_Comissao() * new decimal(1, 0, 0, false, 2); + this.ValorComissaoParcelaBox.set_Number(number * comissao); + } + + private void ManutecaoItens_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.ManutecaoItens(); + } + + private void MenuItem_Click(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLogAntigo(); + } + + private void MenuItem_OnClick(object sender, RoutedEventArgs e) + { + Tarefa tarefa = new Tarefa(); + tarefa.set_IdCliente(this.ViewModel.SelectedDocumento.get_Controle().get_Cliente().get_Id()); + tarefa.set_Cliente(this.ViewModel.SelectedDocumento.get_Controle().get_Cliente().get_Nome()); + tarefa.set_Entidade(0); + tarefa.set_IdEntidade(this.ViewModel.SelectedDocumento.get_Id()); + tarefa.set_Titulo(string.Concat(this.ViewModel.SelectedDocumento.get_Controle().get_Cliente().get_Nome(), " APÓLICE ", this.ViewModel.SelectedDocumento.get_Apolice())); + Tarefa tarefa1 = tarefa; + this.ViewModel.ShowDrawer(new TarefaDrawer(tarefa1, true), 0, false); + } + + private void NegocioCorretoraBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + bool selectedItem; + if (!this.ViewModel.EnableFields) + { + return; + } + ComboBox comboBox = (ComboBox)sender; + if (comboBox != null) + { + selectedItem = comboBox.SelectedItem; + } + else + { + selectedItem = false; + } + if (!selectedItem) + { + return; + } + this.AlteracaoDePremio_LostFocus(this.PremioLiquidoBox, new RoutedEventArgs()); + if (this.SalvarVendedorButton.Visibility != System.Windows.Visibility.Visible) + { + return; + } + this.EditarVendedor(true); + this.ComissaoVendedorBox_OnSelectionChanged((this.ComissaoNovoBox.Visibility == System.Windows.Visibility.Visible ? this.ComissaoNovoComboBox : this.ComissaoRenovacaoComboBox), e); + } + + private void NovaFatura() + { + this.VigenciaInicialField.Visibility = System.Windows.Visibility.Visible; + this.VigenciaFinalField.Visibility = System.Windows.Visibility.Visible; + this.EmissaoField.Visibility = System.Windows.Visibility.Visible; + this.ValorLiquidoField.Visibility = System.Windows.Visibility.Visible; + this.QuantidadeFaturaField.Visibility = System.Windows.Visibility.Visible; + this.RecebimentoField.Visibility = System.Windows.Visibility.Visible; + this.QuitacaoField.Visibility = System.Windows.Visibility.Visible; + this.DataControleParcelaField.Visibility = System.Windows.Visibility.Visible; + this.CreditoField.Visibility = System.Windows.Visibility.Visible; + this.ValorRealizadoField.Visibility = System.Windows.Visibility.Visible; + this.ValorComissaoField.Visibility = System.Windows.Visibility.Visible; + this.VencimentoField.Visibility = System.Windows.Visibility.Visible; + this.ValorField.Visibility = System.Windows.Visibility.Visible; + this.TipoParcelaField.Visibility = System.Windows.Visibility.Collapsed; + this.PercentualComissaoField.Visibility = System.Windows.Visibility.Visible; + this.ComissaoIcon.Visibility = System.Windows.Visibility.Visible; + this.FaturaField.Visibility = System.Windows.Visibility.Visible; + this.EditarParcelasFields.Visibility = System.Windows.Visibility.Visible; + this.ParcelaGrid.IsEnabled = false; + if (this.ViewModel.Restricao(15)) + { + this.RecebimentoField.Visibility = System.Windows.Visibility.Collapsed; + this.QuitacaoField.Visibility = System.Windows.Visibility.Collapsed; + this.CreditoField.Visibility = System.Windows.Visibility.Collapsed; + this.ValorRealizadoField.Visibility = System.Windows.Visibility.Collapsed; + this.ValorComissaoField.Visibility = System.Windows.Visibility.Collapsed; + } + this.ViewModel.IncluirFatura(); + this.ValidarParcela(); + this.QuantidadeFaturaBox.Focus(); + this.EditandoParcela(true); + } + + private void NovaParcelaEspecial() + { + this.FaturaField.Visibility = System.Windows.Visibility.Collapsed; + this.VigenciaInicialField.Visibility = System.Windows.Visibility.Collapsed; + this.VigenciaFinalField.Visibility = System.Windows.Visibility.Collapsed; + this.EmissaoField.Visibility = System.Windows.Visibility.Collapsed; + this.ValorLiquidoField.Visibility = System.Windows.Visibility.Collapsed; + this.QuantidadeFaturaField.Visibility = (this.ViewModel.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 2 ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.TipoParcelaField.Visibility = System.Windows.Visibility.Visible; + this.VencimentoField.Visibility = System.Windows.Visibility.Visible; + this.ValorField.Visibility = System.Windows.Visibility.Visible; + this.RecebimentoField.Visibility = System.Windows.Visibility.Visible; + this.QuitacaoField.Visibility = System.Windows.Visibility.Visible; + this.CreditoField.Visibility = System.Windows.Visibility.Visible; + this.ValorRealizadoField.Visibility = System.Windows.Visibility.Visible; + this.ValorComissaoField.Visibility = System.Windows.Visibility.Visible; + this.PercentualComissaoField.Visibility = System.Windows.Visibility.Visible; + this.ComissaoIcon.Visibility = System.Windows.Visibility.Visible; + this.EditarParcelasFields.Visibility = System.Windows.Visibility.Visible; + this.ParcelaGrid.IsEnabled = false; + if (Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 5)) + { + this.ImpostosField.Visibility = System.Windows.Visibility.Visible; + } + this.ViewModel.IncluirParcelaEspecial(); + this.ValidarParcela(); + this.ValorParcelaBox.Focus(); + } + + private async void ParcelaGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + object obj; + DataGrid dataGrid = (DataGrid)sender; + if (dataGrid == null || dataGrid.SelectedIndex >= 0) + { + ApoliceViewModel viewModel = this.ViewModel; + obj = (dataGrid != null ? dataGrid.Items[dataGrid.SelectedIndex] : null); + await viewModel.SelecionaParcela((Parcela)obj); + } + } + + private void Parcelas(bool premios) + { + DateTime? selectedDate; + this.ViewModel.AllowEditVendedor = this.ViewModel.SelectedDocumento.get_Id() == (long)0; + this.PremiosBox.Visibility = (premios ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.FaturaColumn.Visibility = (this.ViewModel.IsFatura ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.VigenciaInicialColumn.Visibility = (this.ViewModel.IsFatura ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.VigenciaFinalColumn.Visibility = (this.ViewModel.IsFatura ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.ValidarDocumento(); + if (premios) + { + return; + } + this.ParcelasBox.set_Number(decimal.Zero); + this.ComissaoBox.set_Number(decimal.Zero); + this.PremioLiquidoBox.set_Number(decimal.Zero); + this.PremioTotalBox.set_Number(decimal.Zero); + this.IofBox.set_Number(decimal.Zero); + this.DiferencaBox.set_Number(decimal.Zero); + this.PremioAdicionalBox.set_Number(decimal.Zero); + this.FormaPagamentoBox.SelectedItem = (FormaPagamento)4; + DatePicker vigencia2Box = this.Vigencia2Box; + if (this.ViewModel.SelectedDocumento.get_Id() != 0 || this.ViewModel.SelectedDocumento.get_Tipo() != 0) + { + selectedDate = this.Vigencia2Box.SelectedDate; + } + else + { + selectedDate = null; + } + vigencia2Box.SelectedDate = selectedDate; + this.ViewModel.AllowEditVendedor = this.ViewModel.SelectedDocumento.get_Id() != (long)0; + } + + private async void Perdido_OnClick(object sender, RoutedEventArgs e) + { + object prefixo; + object numero; + string str; + string numero1; + object email; + DateTime dateTime; + string descricao; + bool count; + Cliente cliente; + ObservableCollection observableCollection; + if (this.ViewModel.SelectedDocumento.get_Situacao() == 7) + { + await this.ViewModel.ShowMessage("NÃO É POSSÍVEL ALTERAR O STATUS PARA PERDIDO DE UM DOCUMENTO RECUSADO.", "OK", "", false); + } + else if (await this.ViewModel.ShowMessage("DESEJA REALMENTE ALTERAR O STATUS DO SEGURO PARA PERDIDO?", "SIM", "NÃO", false)) + { + this.ViewModel.Loading(true); + cliente = await (new ClienteServico()).BuscarCliente(this.ViewModel.SelectedDocumento.get_Controle().get_Cliente().get_Id()); + Cliente cliente1 = cliente; + ObservableCollection observableCollection1 = await (new ClienteServico()).BuscarTelefonesAsync(this.ViewModel.SelectedDocumento.get_Controle().get_Cliente().get_Id()); + cliente1.set_Telefones(observableCollection1); + cliente1 = null; + cliente1 = cliente; + ObservableCollection observableCollection2 = await (new ClienteServico()).BuscarEmailsAsync(this.ViewModel.SelectedDocumento.get_Controle().get_Cliente().get_Id()); + cliente1.set_Emails(observableCollection2); + cliente1 = null; + observableCollection = await (new ItemServico()).BuscarItems(this.ViewModel.SelectedDocumento.get_Controle().get_Id(), 0, false); + if (await (new ApoliceServico()).Perdido(this.ViewModel.SelectedDocumento.get_Controle().get_Id())) + { + Prospeccao prospeccao = new Prospeccao(); + prospeccao.set_Nome(cliente.get_Nome()); + prospeccao.set_Documento(cliente.get_Documento()); + prospeccao.set_Nascimento(cliente.get_Nascimento()); + ObservableCollection telefones = cliente.get_Telefones(); + if (telefones != null) + { + ClienteTelefone clienteTelefone = telefones.FirstOrDefault(); + if (clienteTelefone != null) + { + prefixo = clienteTelefone.get_Prefixo(); + } + else + { + prefixo = null; + } + } + else + { + prefixo = null; + } + if (prefixo == null) + { + prefixo = ""; + } + prospeccao.set_Prefixo1((string)prefixo); + ObservableCollection telefones1 = cliente.get_Telefones(); + if (telefones1 != null) + { + ClienteTelefone clienteTelefone1 = telefones1.FirstOrDefault(); + if (clienteTelefone1 != null) + { + numero = clienteTelefone1.get_Numero(); + } + else + { + numero = null; + } + } + else + { + numero = null; + } + if (numero == null) + { + numero = ""; + } + prospeccao.set_Telefone1((string)numero); + str = (cliente.get_Telefones() == null || cliente.get_Telefones().Count <= 1 ? "" : cliente.get_Telefones()[1].get_Prefixo()); + prospeccao.set_Prefixo2(str); + if (cliente.get_Telefones() != null) + { + ObservableCollection telefones2 = cliente.get_Telefones(); + if (telefones2 != null) + { + count = telefones2.Count > 1; + } + else + { + count = false; + } + if (!count) + { + goto Label1; + } + numero1 = cliente.get_Telefones()[1].get_Numero(); + goto Label0; + } + Label1: + numero1 = ""; + Label0: + prospeccao.set_Telefone2(numero1); + ObservableCollection emails = cliente.get_Emails(); + if (emails != null) + { + ClienteEmail clienteEmail = emails.FirstOrDefault(); + if (clienteEmail != null) + { + email = clienteEmail.get_Email(); + } + else + { + email = null; + } + } + else + { + email = null; + } + if (email == null) + { + email = ""; + } + prospeccao.set_Email((string)email); + DateTime? vigencia2 = this.ViewModel.SelectedDocumento.get_Vigencia2(); + dateTime = (vigencia2.HasValue ? vigencia2.GetValueOrDefault() : Funcoes.GetNetworkTime().Date); + prospeccao.set_VigenciaFinal(new DateTime?(dateTime.AddYears(1))); + prospeccao.set_Vendedor(this.ViewModel.SelectedDocumento.get_VendedorPrincipal()); + Item item = observableCollection.FirstOrDefault(); + if (item != null) + { + descricao = item.get_Descricao(); + } + else + { + descricao = null; + } + prospeccao.set_Item(descricao); + prospeccao.set_Tipo("SEGURO PERDIDO"); + prospeccao.set_Observacao(string.Concat("SEGURO PERDIDO: PROPOSTA: ", this.ViewModel.SelectedDocumento.get_Proposta(), ", APÓLICE: ", this.ViewModel.SelectedDocumento.get_Apolice())); + prospeccao.set_Status(new StatusProspeccao?(1)); + prospeccao.set_Renovacao(true); + await this.AbrirProspeccao(prospeccao); + await this.ViewModel.SelecionaDocumento(this.ViewModel.SelectedDocumento); + this.ViewModel.Loading(false); + } + else + { + this.ViewModel.Loading(false); + } + } + cliente = null; + observableCollection = null; + } + + private void PorcentagemIrBox_OnNumberChanged(object sender, EventArgs e) + { + if (!this.ViewModel.BaixarParcelas || this._calculando) + { + return; + } + this._calculando = true; + this.ValorIrBox.set_Number(this.ValorComissaoParcelaBox.get_Number() * (this.PorcentagemIrBox.get_Number() / new decimal(100))); + this._calculando = false; + this.ValorImposto_OnNumberChanged(this.ValorIrBox, new EventArgs()); + } + + private void PorcentagemIssBox_OnNumberChanged(object sender, EventArgs e) + { + if (!this.ViewModel.BaixarParcelas || this._calculando) + { + return; + } + this._calculando = true; + this.ValorIssBox.set_Number(this.ValorComissaoParcelaBox.get_Number() * (this.PorcentagemIssBox.get_Number() / new decimal(100))); + this._calculando = false; + this.ValorImposto_OnNumberChanged(this.ValorIssBox, new EventArgs()); + } + + private async void Ramo_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + List configuracoes = Recursos.Configuracoes; + if (!configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 20) && this.ViewModel.SelectedDocumento != null) + { + this.EditarVendedor(false); + this.ViewModel.SelectedPagamento = null; + await this.ViewModel.BuscarVendedores(true); + await this.ViewModel.LimparRepasses(); + } + } + + private void Recalcula(object sender, RoutedEventArgs e) + { + this.ViewModel.RecalculaRepasse(); + } + + private async void RecusarDocumento_OnClick(object sender, RoutedEventArgs e) + { + if (!this.ViewModel.Restricao(18)) + { + await this.ViewModel.RecusarApolice(); + } + else + { + await this.ViewModel.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA RECUSAR. PROCURE O ADMINSTRADOR DO SISTEMA.", "OK", "", false); + } + } + + private void Redimencionar(bool invoke) + { + double actualWidth; + object obj; + Window window = System.Windows.Application.Current.Windows.OfType().SingleOrDefault((Window x) => x.IsActive); + if (window != null) + { + actualWidth = window.ActualWidth; + } + else + { + actualWidth = 1366; + } + double num = actualWidth; + if (invoke) + { + obj = 40; + } + else + { + obj = null; + } + this.Redimencionar(num - (double)obj); + Gestor.Application.Actions.Actions.Redimencionar = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.Redimencionar, new Action(this.Redimencionar)); + } + + private void Redimencionar(double width) + { + this.ViewModel.TamanhoGrid = (width - 17) / 2; + if (this.ViewModel.TamanhoGrid < (double)((this.ViewModel.IsFatura ? 620 : 450))) + { + this.ViewModel.TamanhoGrid = width; + } + } + + private async void Renovar_OnClick(object sender, RoutedEventArgs e) + { + if (!this.ViewModel.Restricao(17)) + { + if (!this.ViewModel.EnableRenovar) + { + await this.ViewModel.ShowMessage("NÃO É POSSÍVEL RENOVAR UM DOCUMENTO SEM EMISSÃO OU SEM FINAL DE VIGÊNCIA.", "OK", "", false); + } + if (await this.ViewModel.IncluirApolice(true)) + { + this.ViewModel.BotoesParcelaEnabled = false; + this.ViewModel.AllowEditEmissao = true; + this.Restricao(true); + } + } + else + { + await this.ViewModel.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA RENOVAR. PROCURE O ADMINSTRADOR DO SISTEMA.", "OK", "", false); + } + } + + private void ReplicarFatura() + { + this.VigenciaInicialField.Visibility = System.Windows.Visibility.Visible; + this.VigenciaFinalField.Visibility = System.Windows.Visibility.Visible; + this.EmissaoField.Visibility = System.Windows.Visibility.Visible; + this.ValorLiquidoField.Visibility = System.Windows.Visibility.Visible; + this.QuantidadeFaturaField.Visibility = System.Windows.Visibility.Visible; + this.RecebimentoField.Visibility = System.Windows.Visibility.Visible; + this.QuitacaoField.Visibility = System.Windows.Visibility.Visible; + this.DataControleParcelaField.Visibility = System.Windows.Visibility.Visible; + this.CreditoField.Visibility = System.Windows.Visibility.Visible; + this.ValorRealizadoField.Visibility = System.Windows.Visibility.Visible; + this.ValorComissaoField.Visibility = System.Windows.Visibility.Visible; + this.VencimentoField.Visibility = System.Windows.Visibility.Visible; + this.ValorField.Visibility = System.Windows.Visibility.Visible; + this.TipoParcelaField.Visibility = System.Windows.Visibility.Collapsed; + this.PercentualComissaoField.Visibility = System.Windows.Visibility.Visible; + this.ComissaoIcon.Visibility = System.Windows.Visibility.Visible; + this.FaturaField.Visibility = System.Windows.Visibility.Visible; + if (!this.ViewModel.Restricao(15)) + { + this.ViewModel.BaixarParcelas = true; + if (Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 5)) + { + this.ImpostosField.Visibility = System.Windows.Visibility.Visible; + } + } + if (( + from x in this.ViewModel.Parcelas + orderby x.get_NumeroParcela() + select x).LastOrDefault((Parcela x) => x.get_SubTipo() == 1).get_NumeroParcela() != 999) + { + this.EditarParcelasFields.Visibility = System.Windows.Visibility.Visible; + this.ParcelaGrid.IsEnabled = false; + } + this.ViewModel.ReplicarFatura(); + this.ValidarParcela(); + this.QuantidadeFaturaBox.Focus(); + } + + private void ReplicarFatura_Click(object sender, RoutedEventArgs e) + { + this.ViewModel.QuantidadeFaturas = 1; + this.ToggleBotoesParcela(true); + this.EditarParcelaTipo = 3; + this.ReplicarFatura(); + this.ViewModel.QuantidadeFaturas = 1; + Action enableMainMenu = Gestor.Application.Actions.Actions.EnableMainMenu; + if (enableMainMenu != null) + { + enableMainMenu(false); + } + else + { + } + Action enableMenu = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu == null) + { + return; + } + enableMenu(false); + } + + private void Restricao(bool insert = false) + { + bool flag = Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 5); + if (insert) + { + this.Comissao.Visibility = System.Windows.Visibility.Visible; + this.Gerada.Visibility = System.Windows.Visibility.Visible; + this.Recebida.Visibility = System.Windows.Visibility.Visible; + this.Pendente.Visibility = System.Windows.Visibility.Visible; + this.Repasse.Visibility = System.Windows.Visibility.Visible; + this.ParcelasComissaoColumn.Visibility = System.Windows.Visibility.Visible; + this.ParcelasValorComissaoColumn.Visibility = (flag ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible); + this.ParcelasValorComissaoDescColumn.Visibility = (flag ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.PagamentosPorcentagemRepasseColumn.Visibility = System.Windows.Visibility.Visible; + this.PagamentosValorRepasseColumn.Visibility = System.Windows.Visibility.Visible; + return; + } + System.Windows.Visibility visibility = (this.ViewModel.Restricao(14) ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible); + bool flag1 = this.ViewModel.Restricao(95); + this.Comissao.Visibility = (flag1 ? System.Windows.Visibility.Visible : visibility); + this.Gerada.Visibility = (flag1 ? System.Windows.Visibility.Collapsed : visibility); + this.Recebida.Visibility = (flag1 ? System.Windows.Visibility.Collapsed : visibility); + this.Pendente.Visibility = (flag1 ? System.Windows.Visibility.Collapsed : visibility); + this.Repasse.Visibility = (flag1 ? System.Windows.Visibility.Collapsed : visibility); + this.ParcelasComissaoColumn.Visibility = (flag1 ? System.Windows.Visibility.Visible : visibility); + this.ParcelasValorComissaoColumn.Visibility = (flag | flag1 ? System.Windows.Visibility.Collapsed : visibility); + this.ParcelasValorComissaoDescColumn.Visibility = (flag ? visibility : System.Windows.Visibility.Collapsed); + this.MaisInformacoesColumn.Visibility = visibility; + this.PagamentosPorcentagemRepasseColumn.Visibility = visibility; + this.PagamentosValorRepasseColumn.Visibility = (flag1 ? System.Windows.Visibility.Collapsed : visibility); + } + + private async void SalvarApolice_OnClick(object sender, RoutedEventArgs e) + { + this.SalvarApoliceButton.Click -= new RoutedEventHandler(this.SalvarApolice_OnClick); + if (this.ViewModel.CompararValores()) + { + this.PremioTotalBox.set_Number(((this.PremioLiquidoBox.get_Number() + this.PremioAdicionalBox.get_Number()) + this.IofBox.get_Number()) + this.DiferencaBox.get_Number()); + } + this.ExecutarValidacaoDataApolice(); + if (await this.SalvarDocumento()) + { + try + { + await this.ViewModel.CreateLinkAssistencia(this.ViewModel.SelectedDocumento, null, false); + } + catch (Exception exception) + { + } + this.AlterandoDocumento(false); + this.EditandoVendedor(false); + this.ViewModel.BotoesParcelaEnabled = true; + this.Restricao(false); + this.SalvarApoliceButton.Click += new RoutedEventHandler(this.SalvarApolice_OnClick); + } + else + { + this.SalvarApoliceButton.Click += new RoutedEventHandler(this.SalvarApolice_OnClick); + } + } + + private async Task SalvarDocumento() + { + bool flag; + bool flag1; + this.ViewModel.Loading(true); + List> keyValuePairs = await this.ViewModel.Salvar(false); + flag1 = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (!flag1) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + flag = false; + } + else + { + this.EditarVendedor(false); + ApoliceView.SetValid(this.AutoCompleteBanco, true); + flag = true; + } + return flag; + } + + private async Task SalvarParcela() + { + bool flag; + bool flag1; + flag = (this.EditarParcelaTipo != 3 ? false : this.ViewModel.QuantidadeFaturas > 1); + bool flag2 = flag; + if (flag2) + { + flag2 = !await this.ViewModel.ShowMessage(string.Format("O SISTEMA IRÁ INCLUIR/REPLICAR A FATURA {0} VEZES. DESEJA PROSSEGUIR?", this.ViewModel.QuantidadeFaturas), "SIM", "NÃO", false); + } + if (!flag2) + { + List> keyValuePairs = await this.ViewModel.SalvarParcelas(this.EditarParcelaTipo); + this.ValidateFields(keyValuePairs, true); + flag1 = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + if (flag1) + { + this.EditarVendedor(false); + this.SalvarParcelaButton.Visibility = System.Windows.Visibility.Collapsed; + this.ViewModel.EditandoParcela = false; + this.BaixarParcelaButton.Visibility = System.Windows.Visibility.Visible; + this.ViewModel.BaixarParcelas = false; + this.EditarParcelaTipo = 0; + Action enableMainMenu = Gestor.Application.Actions.Actions.EnableMainMenu; + if (enableMainMenu != null) + { + enableMainMenu(true); + } + else + { + } + Action enableMenu = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu != null) + { + enableMenu(true); + } + else + { + } + this.ToggleBotoesParcela(false); + if (this.ViewModel.UltimaFatura) + { + this.ViewModel.UltimaFatura = false; + this.ToggleBotoesParcela(true); + this.EditarParcelaTipo = 3; + this.ReplicarFatura(); + this.ViewModel.QuantidadeFaturas = 0; + Action action = Gestor.Application.Actions.Actions.EnableMainMenu; + if (action != null) + { + action(false); + } + else + { + } + Action enableMenu1 = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu1 != null) + { + enableMenu1(false); + } + else + { + } + this.EditandoParcela(!this.ViewModel.UltimaFatura); + } + } + else + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + } + } + + private async void SalvarParcela_Click(object sender, RoutedEventArgs e) + { + ((MenuItem)this.SalvarParcelaButton.Items[0]).Click -= new RoutedEventHandler(this.SalvarParcela_Click); + this.LostFocusValorRealizado(); + this.ViewModel.Loading(true); + if (!this.ViewModel.CriandoParcelaEspecial) + { + await this.SalvarParcela(); + } + this.ViewModel.Loading(false); + this.SalvarParcelaButton.IsEnabled = true; + ((MenuItem)this.SalvarParcelaButton.Items[0]).Click += new RoutedEventHandler(this.SalvarParcela_Click); + } + + private async void SalvarVendedor_Click(object sender, RoutedEventArgs e) + { + bool? isChecked; + List> keyValuePairs; + bool valueOrDefault; + bool flag; + bool valueOrDefault1; + bool? nullable; + this.ViewModel.Loading(true); + if (this.ViewModel.SelectedParcela == null) + { + valueOrDefault = true; + } + else if (this.ViewModel.SelectedParcela.get_SubTipo() != 1) + { + valueOrDefault = false; + } + else + { + TipoRecebimento? tipoRecebimento = this.ViewModel.SelectedDocumento.get_TipoRecebimento(); + valueOrDefault = tipoRecebimento.GetValueOrDefault() == 1; + } + List configuracoes = Recursos.Configuracoes; + if (configuracoes.Any((ConfiguracaoSistema config) => config.get_Configuracao() == 56)) + { + ToggleButton coCorretagemToogle = this.CoCorretagemToogle; + if (coCorretagemToogle != null) + { + isChecked = coCorretagemToogle.IsChecked; + valueOrDefault1 = isChecked.GetValueOrDefault(); + } + else + { + valueOrDefault1 = false; + } + if (valueOrDefault1) + { + VendedorParcela selectedPagamento = this.ViewModel.SelectedPagamento; + ToggleButton toggleButton = this.CoCorretagemToogle; + if (toggleButton != null) + { + nullable = toggleButton.IsChecked; + } + else + { + isChecked = null; + nullable = isChecked; + } + isChecked = nullable; + selectedPagamento.set_CoCorretagem(isChecked.GetValueOrDefault(true)); + } + } + keyValuePairs = (!valueOrDefault ? await this.ViewModel.AdicionarVendedorParcelaEspecial() : await this.ViewModel.AdicionarVendedor()); + List> keyValuePairs1 = keyValuePairs; + flag = (keyValuePairs1 == null ? true : keyValuePairs1.Count == 0); + bool flag1 = flag; + this.ViewModel.Loading(false); + if (!flag1) + { + this.ViewModel.AllowEditParcela = flag1; + await this.ViewModel.ShowMessage(keyValuePairs1, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + else + { + this.EditarVendedor(false); + this.EditandoVendedor(false); + if (this.ViewModel.VerificaCoCorretagem()) + { + this.ComissaoBox.IsReadOnly = true; + this.ViewModel.ComissOriginalVisibility = System.Windows.Visibility.Visible; + } + this.ViewModel.AllowEditParcela = flag1; + } + } + + private static void SetValid(AutoCompleteBox autocomplete, bool valid) + { + ViewHelper.SetInvalid(autocomplete, "BANCO INVÁLIDO", valid); + } + + private void SituacaoBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + ComboBox comboBox = (ComboBox)sender; + if (comboBox.SelectedItem == null) + { + return; + } + TipoSeguro selectedItem = (TipoSeguro)comboBox.SelectedItem; + this.ViewModel.ToggleSeguradoraAnterior(selectedItem); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.MenuApolice = (DockPanel)target; + return; + } + case 2: + { + this.IncluirpoliceButton = (MenuItem)target; + this.IncluirpoliceButton.Click += new RoutedEventHandler(this.IncluirApolice_OnClick); + return; + } + case 3: + { + this.AlterarApoliceButton = (MenuItem)target; + this.AlterarApoliceButton.Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 4: + { + this.SalvarApoliceButton = (MenuItem)target; + this.SalvarApoliceButton.Click += new RoutedEventHandler(this.SalvarApolice_OnClick); + return; + } + case 5: + { + this.CancelarApoliceButton = (MenuItem)target; + this.CancelarApoliceButton.Click += new RoutedEventHandler(this.CancelarApolice_OnClick); + return; + } + case 6: + { + this.ExcluirpoliceButton = (MenuItem)target; + this.ExcluirpoliceButton.Click += new RoutedEventHandler(this.ExcluirDocumento_OnClick); + return; + } + case 7: + { + this.ButtonImportado = (Button)target; + this.ButtonImportado.Click += new RoutedEventHandler(this.Importacao_OnClick); + return; + } + case 8: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirPerfil_OnClick); + return; + } + case 9: + { + this.ArquivoDigitalButton = (MenuItem)target; + this.ArquivoDigitalButton.Click += new RoutedEventHandler(this.AbrirAquivoDigital_Click); + return; + } + case 10: + { + this.MaisOpcoesButton = (MenuItem)target; + return; + } + case 11: + { + this.EditarParcelasButton = (MenuItem)target; + this.EditarParcelasButton.Click += new RoutedEventHandler(this.EditarParcelas_OnClick); + return; + } + case 12: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Renovar_OnClick); + return; + } + case 13: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Perdido_OnClick); + return; + } + case 14: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Endossar_OnClick); + return; + } + case 15: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.RecusarDocumento_OnClick); + return; + } + case 16: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.ManutecaoItens_OnClick); + return; + } + case 17: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.MenuItem_OnClick); + return; + } + case 18: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick); + return; + } + case 19: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLogEmail_OnClick); + return; + } + case 20: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLogEmailPF_OnClick); + return; + } + case 21: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLogTrocaCliente_OnClick); + return; + } + case 22: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.MenuItem_Click); + return; + } + case 23: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirInfo_OnClick); + return; + } + case 24: + { + this.ApoliceControl1 = (WrapPanel)target; + return; + } + case 25: + { + ((ComboBox)target).SelectionChanged += new SelectionChangedEventHandler(this.Ramo_OnSelectionChanged); + return; + } + case 26: + { + this.ProdutoBox = (ComboBox)target; + return; + } + case 27: + { + this.SituacaoBox = (ComboBox)target; + return; + } + case 28: + { + this.NegocioCorretoraBox = (ComboBox)target; + return; + } + case 29: + { + this.TipoRecebimentoBox = (ComboBox)target; + return; + } + case 30: + { + this.TipoEndossoBox = (ComboBox)target; + return; + } + case 31: + { + this.ApoliceBox = (TextBox)target; + return; + } + case 32: + { + this.EndossoBox = (TextBox)target; + return; + } + case 33: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.Initial_DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + ((DatePicker)target).SelectedDateChanged += new EventHandler(this.ValidacaoDocumento); + return; + } + case 34: + { + this.Vigencia2Box = (DatePicker)target; + this.Vigencia2Box.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.Vigencia2Box.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + this.Vigencia2Box.SelectedDateChanged += new EventHandler(this.ValidacaoDocumento); + return; + } + case 35: + { + this.TransmissaoBox = (DatePicker)target; + this.TransmissaoBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.TransmissaoBox.PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + this.TransmissaoBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 36: + { + this.EmissaoBox = (DatePicker)target; + this.EmissaoBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.EmissaoBox.PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + this.EmissaoBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + this.EmissaoBox.SelectedDateChanged += new EventHandler(this.ValidacaoDocumento); + return; + } + case 37: + { + this.FormaPagamentoBox = (ComboBox)target; + return; + } + case 38: + { + this.PremiosBox = (Grid)target; + return; + } + case 39: + { + this.AdicionalBox = (ToggleButton)target; + return; + } + case 40: + { + this.Comissao = (CustomIsReadOnlyControl)target; + return; + } + case 41: + { + this.ComissaoBox = (CurrencyTextBox)target; + return; + } + case 42: + { + this.PremioLiquidoBox = (CurrencyTextBox)target; + return; + } + case 43: + { + this.PremioAdicionalBox = (CurrencyTextBox)target; + this.PremioAdicionalBox.GotFocus += new RoutedEventHandler(this.FocusPremios); + return; + } + case 44: + { + this.IofBox = (CurrencyTextBox)target; + return; + } + case 45: + { + this.DiferencaBox = (CurrencyTextBox)target; + return; + } + case 46: + { + this.PremioTotalBox = (CurrencyTextBox)target; + return; + } + case 47: + { + this.ParcelasBox = (CurrencyTextBox)target; + return; + } + case 48: + { + this.ComissaoOriginal = (CustomIsReadOnlyControl)target; + return; + } + case 49: + { + this.Gerada = (CustomIsReadOnlyControl)target; + return; + } + case 50: + { + this.Recebida = (CustomIsReadOnlyControl)target; + return; + } + case 51: + { + this.Pendente = (CustomIsReadOnlyControl)target; + return; + } + case 52: + { + this.Repasse = (CustomIsReadOnlyControl)target; + return; + } + case 53: + { + ((Button)target).Click += new RoutedEventHandler(this.Button_Click); + return; + } + case 54: + { + this.BaixarParcelaButton = (Menu)target; + return; + } + case 55: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.BaixarParcelas_Click); + return; + } + case 56: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AlterarParcela_Click); + return; + } + case 57: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.IncluirNovaFatura_Click); + return; + } + case 58: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.ReplicarFatura_Click); + return; + } + case 59: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.IncluirParcelaEspecial_Click); + return; + } + case 60: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.ExcluirParcela_Click); + return; + } + case 61: + { + this.SalvarParcelaButton = (Menu)target; + return; + } + case 62: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.SalvarParcela_Click); + return; + } + case 63: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.CancelarParcela_Click); + return; + } + case 64: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLogParcelas_OnClick); + return; + } + case 65: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLogParcelaSelecionada_OnClick); + return; + } + case 66: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLogParcelaAntigo_OnClick); + return; + } + case 67: + { + this.EditarParcelasFields = (StackPanel)target; + return; + } + case 68: + { + this.TipoParcelaField = (CustomItemValidation)target; + return; + } + case 69: + { + this.TipoParcelaBox = (ComboBox)target; + return; + } + case 70: + { + this.QuantidadeFaturaField = (CustomItemControl)target; + return; + } + case 71: + { + this.QuantidadeFaturaBox = (CurrencyTextBox)target; + return; + } + case 72: + { + this.FaturaField = (CustomItemValidation)target; + return; + } + case 73: + { + this.FaturaBox = (TextBox)target; + return; + } + case 74: + { + this.VigenciaInicialField = (CustomItemValidation)target; + return; + } + case 75: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.Vigencia_DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 76: + { + this.VigenciaFinalField = (CustomItemValidation)target; + return; + } + case 77: + { + this.VigenciaFinalParcelaBox = (DatePicker)target; + this.VigenciaFinalParcelaBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.VigenciaFinalParcelaBox.PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + this.VigenciaFinalParcelaBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 78: + { + this.VencimentoField = (CustomItemValidation)target; + return; + } + case 79: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.Vencimento_DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 80: + { + this.EmissaoField = (CustomItemControl)target; + return; + } + case 81: + { + this.EmissaoParcelaBox = (DatePicker)target; + this.EmissaoParcelaBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.EmissaoParcelaBox.PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + this.EmissaoParcelaBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 82: + { + this.PercentualComissaoField = (CustomItemValidation)target; + return; + } + case 83: + { + this.ComissaoParcelaBox = (CurrencyTextBox)target; + return; + } + case 84: + { + this.ComissaoIcon = (TextBlock)target; + return; + } + case 85: + { + this.ValorLiquidoField = (CustomItemControl)target; + return; + } + case 86: + { + this.ValorLiquidoParcelaBox = (CurrencyTextBox)target; + return; + } + case 87: + { + this.ValorField = (CustomItemControl)target; + return; + } + case 88: + { + this.ValorParcelaBox = (CurrencyTextBox)target; + return; + } + case 89: + { + this.RecebimentoField = (CustomItemValidation)target; + return; + } + case 90: + { + this.RecebimentoParcelaBox = (DatePicker)target; + this.RecebimentoParcelaBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.Vencimento_OnLostKeyboardFocus); + this.RecebimentoParcelaBox.PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + this.RecebimentoParcelaBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + this.RecebimentoParcelaBox.SelectedDateChanged += new EventHandler(this.ValidacaoParcela); + return; + } + case 91: + { + this.QuitacaoField = (CustomItemControl)target; + return; + } + case 92: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + ((DatePicker)target).SelectedDateChanged += new EventHandler(this.ValidacaoParcela); + return; + } + case 93: + { + this.DataControleParcelaField = (CustomItemControl)target; + return; + } + case 94: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + ((DatePicker)target).SelectedDateChanged += new EventHandler(this.ValidacaoParcela); + return; + } + case 95: + { + this.CreditoField = (CustomItemValidation)target; + return; + } + case 96: + { + this.CreditoParcelaBox = (DatePicker)target; + this.CreditoParcelaBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.CreditoParcelaBox.PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + this.CreditoParcelaBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + this.CreditoParcelaBox.SelectedDateChanged += new EventHandler(this.ValidacaoParcela); + return; + } + case 97: + { + this.ValorRealizadoField = (CustomItemValidation)target; + return; + } + case 98: + { + this.ValorRealizadoParcelaBox = (CurrencyTextBox)target; + this.ValorRealizadoParcelaBox.LostFocus += new RoutedEventHandler(this.ValorRealizadoParcelaBox_OnLostFocus); + return; + } + case 99: + { + this.ValorComissaoField = (CustomItemValidation)target; + return; + } + case 100: + { + this.ValorComissaoParcelaBox = (CurrencyTextBox)target; + this.ValorComissaoParcelaBox.add_NumberChanged(new EventHandler(this.CalculoComissao_OnNumberChanged)); + return; + } + case 101: + { + this.ImpostosField = (WrapPanel)target; + return; + } + case 102: + { + this.PorcentagemIrField = (CustomItemControl)target; + return; + } + case 103: + { + this.PorcentagemIrBox = (CurrencyTextBox)target; + this.PorcentagemIrBox.add_NumberChanged(new EventHandler(this.PorcentagemIrBox_OnNumberChanged)); + return; + } + case 104: + { + this.ValorIrField = (CustomItemControl)target; + return; + } + case 105: + { + this.ValorIrBox = (CurrencyTextBox)target; + this.ValorIrBox.add_NumberChanged(new EventHandler(this.ValorImposto_OnNumberChanged)); + return; + } + case 106: + { + this.PorcentagemIssField = (CustomItemControl)target; + return; + } + case 107: + { + this.PorcentagemIssBox = (CurrencyTextBox)target; + this.PorcentagemIssBox.add_NumberChanged(new EventHandler(this.PorcentagemIssBox_OnNumberChanged)); + return; + } + case 108: + { + this.ValorIssField = (CustomItemControl)target; + return; + } + case 109: + { + this.ValorIssBox = (CurrencyTextBox)target; + this.ValorIssBox.add_NumberChanged(new EventHandler(this.ValorImposto_OnNumberChanged)); + return; + } + case 110: + { + this.ValorOutrosField = (CustomItemControl)target; + return; + } + case 111: + { + this.ValorOutrosBox = (CurrencyTextBox)target; + this.ValorOutrosBox.add_NumberChanged(new EventHandler(this.ValorImposto_OnNumberChanged)); + return; + } + case 112: + { + this.ValorDescontoField = (CustomItemControl)target; + return; + } + case 113: + { + this.ValorDescontoBox = (CurrencyTextBox)target; + this.ValorDescontoBox.add_NumberChanged(new EventHandler(this.ValorImposto_OnNumberChanged)); + return; + } + case 114: + { + this.ValorComDescField = (CustomItemControl)target; + return; + } + case 115: + { + this.ValorComDescBox = (CurrencyTextBox)target; + this.ValorComDescBox.add_NumberChanged(new EventHandler(this.ValorImposto_OnNumberChanged)); + return; + } + case 116: + { + this.ParcelaGrid = (DataGrid)target; + return; + } + case 117: + { + this.ParcelaColumn = (DataGridTextColumn)target; + return; + } + case 118: + { + this.FaturaColumn = (DataGridTextColumn)target; + return; + } + case 119: + { + this.VigenciaInicialColumn = (DataGridTextColumn)target; + return; + } + case 120: + { + this.VigenciaFinalColumn = (DataGridTextColumn)target; + return; + } + case 121: + { + this.ParcelasComissaoColumn = (DataGridTextColumn)target; + return; + } + case 122: + { + this.ParcelasValorComissaoColumn = (DataGridTextColumn)target; + return; + } + case 123: + { + this.ParcelasValorComissaoDescColumn = (DataGridTextColumn)target; + return; + } + case 124: + { + this.MaisInformacoesColumn = (DataGridTemplateColumn)target; + return; + } + case 125: + case 126: + case 146: + { + this._contentLoaded = true; + return; + } + case 127: + { + this.EditarVendedorButton = (MenuItem)target; + this.EditarVendedorButton.Click += new RoutedEventHandler(this.IncluirVendedor_Click); + return; + } + case 128: + { + this.SalvarVendedorButton = (MenuItem)target; + this.SalvarVendedorButton.Click += new RoutedEventHandler(this.SalvarVendedor_Click); + return; + } + case 129: + { + this.CancelarVendedorButton = (MenuItem)target; + this.CancelarVendedorButton.Click += new RoutedEventHandler(this.CancelarVendedor_Click); + return; + } + case 130: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLogVendedor_OnClick); + return; + } + case 131: + { + this.EditarVendedorFields = (WrapPanel)target; + return; + } + case 132: + { + this.CoCorretagemToogle = (ToggleButton)target; + this.CoCorretagemToogle.Click += new RoutedEventHandler(this.AdicionarCoCorretagem_OnClick); + return; + } + case 133: + { + this.TipoVendedorBox = (ComboBox)target; + return; + } + case 134: + { + this.VendedorBox = (ComboBox)target; + return; + } + case 135: + { + this.ComissaoNovoBox = (CustomItemValidation)target; + return; + } + case 136: + { + this.ComissaoNovoComboBox = (ComboBox)target; + this.ComissaoNovoComboBox.SelectionChanged += new SelectionChangedEventHandler(this.ComissaoVendedorBox_OnSelectionChanged); + return; + } + case 137: + { + this.ComissaoRenovacaoBox = (CustomItemValidation)target; + return; + } + case 138: + { + this.ComissaoRenovacaoComboBox = (ComboBox)target; + this.ComissaoRenovacaoComboBox.SelectionChanged += new SelectionChangedEventHandler(this.ComissaoVendedorBox_OnSelectionChanged); + return; + } + case 139: + { + this.ValorRepasseBox = (CurrencyTextBox)target; + this.ValorRepasseBox.add_NumberChanged(new EventHandler(this.CalculoComissao_OnNumberChanged)); + return; + } + case 140: + { + this.FormaRecebidaBox = (TextBox)target; + return; + } + case 141: + { + this.FormaIncidenciaBox = (TextBox)target; + return; + } + case 142: + { + this.VendedorGrid = (DataGrid)target; + return; + } + case 143: + { + this.VendedorGridColumn = (DataGridTextColumn)target; + return; + } + case 144: + { + this.PagamentosPorcentagemRepasseColumn = (DataGridTextColumn)target; + return; + } + case 145: + { + this.PagamentosValorRepasseColumn = (DataGridTextColumn)target; + return; + } + case 147: + { + this.ProponenteBox = (TextBox)target; + return; + } + case 148: + { + this.AutoCompleteBanco = (AutoCompleteBox)target; + this.AutoCompleteBanco.add_Populating(new PopulatingEventHandler(this, ApoliceView.AutoCompleteBancoBox_Populating)); + this.AutoCompleteBanco.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.AutoCompleteBanco_OnLostKeyboardFocus); + return; + } + case 149: + { + this.AgenciaBox = (TextBox)target; + return; + } + case 150: + { + this.ContaBox = (TextBox)target; + return; + } + case 151: + { + this.CartaoBox = (TextBox)target; + return; + } + case 152: + { + this.BandeiraBox = (ComboBox)target; + return; + } + case 153: + { + this.VencimentoCartaoBox = (TextBox)target; + ApoliceView apoliceView = this; + this.VencimentoCartaoBox.PreviewTextInput += new TextCompositionEventHandler(apoliceView.SomenteNumeros); + this.VencimentoCartaoBox.TextChanged += new TextChangedEventHandler(this.VencimentoCartaoBox_OnTextChanged); + this.VencimentoCartaoBox.GotFocus += new RoutedEventHandler(this.VencimentoCartaoBox_OnGotFocus); + return; + } + case 154: + { + this.DataBox = (DatePicker)target; + this.DataBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 155: + { + this.PastaBox = (TextBox)target; + return; + } + default: + { + this._contentLoaded = true; + return; + } + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + if (connectionId == 125) + { + ((Button)target).Click += new RoutedEventHandler(this.ValoresParcelaInfo_OnClick); + return; + } + if (connectionId == 126) + { + ((Button)target).Click += new RoutedEventHandler(this.AbrirAquivoDigital_Click); + return; + } + if (connectionId != 146) + { + return; + } + ((Button)target).Click += new RoutedEventHandler(this.ExcluirVendedor_Click); + } + + private void TipoEndossoBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + decimal comissao; + if (this.ViewModel.SelectedDocumento != null && this.ViewModel.SelectedDocumento.get_Tipo() == 0) + { + return; + } + ComboBox comboBox = (ComboBox)sender; + if (comboBox.SelectedItem == null) + { + return; + } + bool flag = (this.ViewModel.IsFatura ? false : (TipoEndosso)comboBox.SelectedItem != 1); + if (this.ViewModel.EnableFields) + { + if ((TipoEndosso)comboBox.SelectedItem != null && (TipoEndosso)comboBox.SelectedItem != 4) + { + if (this.ViewModel.SelectedDocumento != null) + { + this.ViewModel.SelectedDocumento.set_Comissao(decimal.Zero); + } + } + else if (this.ViewModel.SelectedDocumento != null) + { + Documento selectedDocumento = this.ViewModel.SelectedDocumento; + Documento cancelDocumento = this.ViewModel.CancelDocumento; + if (cancelDocumento != null) + { + comissao = cancelDocumento.get_Comissao(); + } + else + { + comissao = decimal.Zero; + } + selectedDocumento.set_Comissao(comissao); + } + this.ViewModel.OnPropertyChanged("SelectedDocumento"); + } + this.Parcelas(flag); + } + + private void TipoRecebimentoBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + ComboBox comboBox = (ComboBox)sender; + if (comboBox.SelectedItem == null) + { + return; + } + this.ViewModel.IsFatura = (TipoRecebimento)comboBox.SelectedItem == 2; + this.Parcelas(!this.ViewModel.IsFatura); + if (!this.ViewModel.EnableFields) + { + return; + } + this.FormaPagamentoBox.SelectedItem = (this.ViewModel.IsFatura ? new FormaPagamento?(5) : this.ViewModel.SelectedDocumento.get_FormaPagamento()); + } + + private void TipoVendedorBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + ComboBox comboBox = (ComboBox)sender; + if (comboBox.SelectedItem == null) + { + return; + } + if (this.ViewModel.SelectedPagamento == null) + { + this.ViewModel.SelectedPagamento = new VendedorParcela(); + } + this.ViewModel.SelectedPagamento.set_TipoVendedor((TipoVendedor)comboBox.SelectedItem); + } + + private void ToggleBotoesParcela(bool habilitar) + { + this.SalvarParcelaButton.Visibility = (habilitar ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.ViewModel.EditandoParcela = habilitar; + this.BaixarParcelaButton.Visibility = (habilitar ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible); + this.MenuApolice.IsEnabled = !habilitar; + this.ViewModel.IsEnabled = !habilitar; + this.PremiosBox.IsEnabled = !habilitar; + this.DataControleParcelaField.Visibility = System.Windows.Visibility.Collapsed; + if (habilitar) + { + return; + } + this.QuantidadeFaturaField.Visibility = System.Windows.Visibility.Collapsed; + this.TipoParcelaField.Visibility = System.Windows.Visibility.Collapsed; + this.VencimentoField.Visibility = System.Windows.Visibility.Collapsed; + this.ValorField.Visibility = System.Windows.Visibility.Collapsed; + this.RecebimentoField.Visibility = System.Windows.Visibility.Collapsed; + this.QuitacaoField.Visibility = System.Windows.Visibility.Collapsed; + this.CreditoField.Visibility = System.Windows.Visibility.Collapsed; + this.ValorRealizadoField.Visibility = System.Windows.Visibility.Collapsed; + this.ValorComissaoField.Visibility = System.Windows.Visibility.Collapsed; + this.PercentualComissaoField.Visibility = System.Windows.Visibility.Collapsed; + this.ComissaoIcon.Visibility = System.Windows.Visibility.Collapsed; + this.EmissaoField.Visibility = System.Windows.Visibility.Collapsed; + this.ValorLiquidoField.Visibility = System.Windows.Visibility.Collapsed; + this.FaturaField.Visibility = System.Windows.Visibility.Collapsed; + this.VigenciaInicialField.Visibility = System.Windows.Visibility.Collapsed; + this.VigenciaFinalField.Visibility = System.Windows.Visibility.Collapsed; + this.EditarParcelasFields.Visibility = System.Windows.Visibility.Collapsed; + this.ImpostosField.Visibility = System.Windows.Visibility.Collapsed; + this.ParcelaGrid.IsEnabled = true; + } + + private void ValidacaoDocumento(object sender, RoutedEventArgs e) + { + this.ValidarDocumento(); + } + + private void ValidacaoParcela(object sender, RoutedEventArgs e) + { + this.ValidarParcela(); + } + + private void ValidarDocumento() + { + if (this.ViewModel.SelectedDocumento == null) + { + return; + } + List> keyValuePairs = this.ViewModel.SelectedDocumento.Validate(this.ViewModel.IsEndosso, Recursos.Configuracoes.Any((ConfiguracaoSistema c) => c.get_Configuracao() == 11)); + this.ValidateFields(keyValuePairs, false); + } + + private void ValidarParcela() + { + if (this.ViewModel.SelectedParcela == null) + { + return; + } + if (this.ViewModel.SelectedParcela.get_Documento() == null) + { + this.ViewModel.SelectedParcela.set_Documento(this.ViewModel.SelectedDocumento); + } + this.ViewModel.SelectedParcela.get_Documento().set_Parcelas(this.ViewModel.Parcelas); + List> keyValuePairs = this.ViewModel.SelectedParcela.Validate(Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 9), Recursos.Configuracoes.Any((ConfiguracaoSistema y) => y.get_Configuracao() == 11), this.ViewModel.EditandoParcela, Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 16)); + this.ValidateFields(keyValuePairs, false); + } + + private void ValidarTela() + { + if (this.ViewModel.SelectedDocumento == null) + { + return; + } + List> keyValuePairs = this.ViewModel.SelectedDocumento.Validate(); + this.ValidateFields(keyValuePairs, false); + } + + private void ValidarVendedor() + { + if (this.ViewModel.SelectedPagamento == null) + { + return; + } + List> keyValuePairs = this.ViewModel.SelectedPagamento.Validate(); + this.ValidateFields(keyValuePairs, false); + } + + private void ValoresParcelaInfo_OnClick(object sender, RoutedEventArgs e) + { + Parcela parcela = this.ViewModel.AbrirDetalhesParcela(); + this.ViewModel.ShowDrawer(new ValoresParcelaDrawer(parcela, this.ViewModel.SelectedDocumento), 0, true); + } + + private void ValorImposto_OnNumberChanged(object sender, EventArgs e) + { + if (!this.ViewModel.BaixarParcelas || this._calculando) + { + return; + } + this._calculando = true; + CurrencyTextBox currencyTextBox = (CurrencyTextBox)sender; + decimal num = (this.ValorComissaoParcelaBox.get_Number() == decimal.Zero ? decimal.One : this.ValorComissaoParcelaBox.get_Number()); + decimal number = this.ValorComissaoParcelaBox.get_Number(); + string name = currencyTextBox.Name; + if (name == "ValorIrBox") + { + this.PorcentagemIrBox.set_Number((this.ValorIrBox.get_Number() * new decimal(100)) / num); + number = (((num - currencyTextBox.get_Number()) - this.ValorIssBox.get_Number()) - this.ValorOutrosBox.get_Number()) - this.ValorDescontoBox.get_Number(); + } + else if (name == "ValorIssBox") + { + this.PorcentagemIssBox.set_Number((this.ValorIssBox.get_Number() * new decimal(100)) / num); + number = (((num - currencyTextBox.get_Number()) - this.ValorIrBox.get_Number()) - this.ValorOutrosBox.get_Number()) - this.ValorDescontoBox.get_Number(); + } + else if (name == "ValorOutrosBox") + { + number = (((num - currencyTextBox.get_Number()) - this.ValorIrBox.get_Number()) - this.ValorIrBox.get_Number()) - this.ValorDescontoBox.get_Number(); + } + else if (name == "ValorDescontoBox") + { + number = (((num - currencyTextBox.get_Number()) - this.ValorIrBox.get_Number()) - this.ValorIrBox.get_Number()) - this.ValorOutrosBox.get_Number(); + } + this.ValorComDescBox.set_Number(number); + this._calculando = false; + } + + private void ValorParcelaBox_OnLostFocus(object sender, RoutedEventArgs e) + { + decimal iof; + if (!this.ViewModel.IsFatura) + { + return; + } + CurrencyTextBox currencyTextBox = (CurrencyTextBox)sender; + if (this.ValorParcelaBox.get_Number() > decimal.Zero) + { + return; + } + if (Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 46)) + { + Ramo ramo = this.ViewModel.SelectedDocumento.get_Controle().get_Ramo(); + if (ramo != null) + { + iof = ramo.get_Iof(); + } + else + { + iof = decimal.Zero; + } + } + else + { + iof = decimal.Zero; + } + decimal one = iof + decimal.One; + this.ValorParcelaBox.set_Number(currencyTextBox.get_Number() * one); + this.ValorParcelaBox.Focus(); + } + + private void ValorRealizadoParcelaBox_OnLostFocus(object sender, RoutedEventArgs e) + { + CurrencyTextBox currencyTextBox = (CurrencyTextBox)sender; + if (currencyTextBox != null && currencyTextBox.get_Number() != decimal.Zero && this.ViewModel.SelectedParcela != null) + { + decimal number = currencyTextBox.get_Number(); + decimal comissao = this.ViewModel.SelectedParcela.get_Comissao() * new decimal(1, 0, 0, false, 2); + this.ValorComissaoParcelaBox.set_Number(number * comissao); + } + } + + private void Vencimento_DatePicker_OnLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) + { + base.DatePicker_OnLostKeyboardFocus(sender, e); + if (this.ViewModel.SelectedDocumento == null) + { + return; + } + if (string.IsNullOrEmpty(((DatePicker)sender).Text)) + { + ((DatePicker)sender).SelectedDate = new DateTime?(this.ViewModel.SelectedDocumento.get_Vigencia1()); + DatePicker str = (DatePicker)sender; + DateTime vigencia1 = this.ViewModel.SelectedDocumento.get_Vigencia1(); + str.Text = vigencia1.ToString("dd/MM/yyyy"); + } + base.DatePicker_OnLostKeyboardFocus(sender, e); + } + + private void Vencimento_OnLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) + { + DateTime dateTime; + base.DatePicker_OnLostKeyboardFocus(sender, e); + DatePicker datePicker = (DatePicker)sender; + if (string.IsNullOrEmpty(datePicker.Text)) + { + return; + } + if (!DateTime.TryParse(ValidationHelper.FormatDate(datePicker.Text), out dateTime)) + { + return; + } + this.CreditoParcelaBox.SelectedDate = new DateTime?(dateTime); + } + + private void VencimentoCartaoBox_OnGotFocus(object sender, RoutedEventArgs e) + { + string str = ((TextBox)sender).Text.Replace("/", ""); + this._vencimentoCartaoOld = str.Substring(0, (str.Length > 4 ? 4 : str.Length)); + } + + private void VencimentoCartaoBox_OnTextChanged(object sender, TextChangedEventArgs e) + { + int caretIndex = ((TextBox)sender).CaretIndex; + TextBox textBox = (TextBox)sender; + if (textBox.Text.Contains("/") && (new Regex("/")).Match(textBox.Text).Index < caretIndex) + { + caretIndex--; + } + string str = textBox.Text.Replace("/", ""); + string str1 = str.Substring(0, (str.Length > 4 ? 4 : str.Length)); + if ((new Regex("^0")).IsMatch(str1)) + { + if ((new Regex("^00")).IsMatch(str1)) + { + textBox.Text = this._vencimentoCartaoOld; + textBox.CaretIndex = caretIndex; + return; + } + } + else if ((new Regex("^1")).IsMatch(str1)) + { + if ((new Regex("^1[^0-2]")).IsMatch(str1)) + { + textBox.Text = this._vencimentoCartaoOld; + textBox.CaretIndex = caretIndex; + return; + } + } + else if ((new Regex("^[^01]")).IsMatch(str1)) + { + textBox.Text = this._vencimentoCartaoOld; + textBox.CaretIndex = caretIndex; + return; + } + if (str1.Length > 2) + { + textBox.Text = str1.Insert(2, "/"); + caretIndex++; + } + else if (textBox.Text.Contains("/")) + { + textBox.Text = str1; + } + textBox.CaretIndex = caretIndex; + this._vencimentoCartaoOld = str1; + } + + private void VendedorBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + ComboBox comboBox = (ComboBox)sender; + if (comboBox.SelectedItem == null) + { + return; + } + this.ViewModel.FiltrarRepasse((Vendedor)comboBox.SelectedItem); + if (this.ViewModel.CoCorretagem) + { + this.ComissaoNovoBox.Visibility = System.Windows.Visibility.Visible; + this.ComissaoRenovacaoBox.Visibility = System.Windows.Visibility.Collapsed; + } + } + + private void Vigencia_DatePicker_OnLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) + { + DateTime dateTime; + base.DatePicker_OnLostKeyboardFocus(sender, e); + DatePicker datePicker = (DatePicker)sender; + if (string.IsNullOrEmpty(datePicker.Text)) + { + return; + } + if (!DateTime.TryParse(ValidationHelper.FormatDate(datePicker.Text), out dateTime)) + { + return; + } + this.VigenciaFinalParcelaBox.SelectedDate = new DateTime?(dateTime.AddMonths(1)); + this.EmissaoParcelaBox.SelectedDate = new DateTime?(dateTime); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Seguros/ClienteView.cs b/Codemerx/Gestor.Application/Views/Seguros/ClienteView.cs new file mode 100644 index 0000000..5426996 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Seguros/ClienteView.cs @@ -0,0 +1,1307 @@ +using CurrencyTextBoxControl; +using Gestor.Application.Componentes; +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Application.Views.Generic; +using Gestor.Common.Helpers; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; +using Xceed.Wpf.AvalonDock.Controls; + +namespace Gestor.Application.Views.Seguros +{ + public class ClienteView : BaseUserControl, IComponentConnector, IStyleConnector + { + public ClienteViewModel ViewModel; + + internal Grid MainGrid; + + internal MenuItem IncluirClienteButton; + + internal ComboBox TipoDocumentoPrincipalBox; + + internal TextBox DocumentoPrincipalBox; + + internal TextBox NomeBox; + + internal TextBox NomeSocialBox; + + internal TextBox CaepfBox; + + internal TextBox RneBox; + + internal TextBox CeiBox; + + internal TextBox IdentidadeBox; + + internal TextBox EmissorBox; + + internal TextBox EstadoEmissorBox; + + internal TextBox HabilitacaoBox; + + internal TextBox CategoriaHabilitacaooBox; + + internal ComboBox SexoBox; + + internal ComboBox EstadoCivilBox; + + internal AutoCompleteBox AutoCompleteProfissao; + + internal AutoCompleteBox AutoCompleteAtividade; + + internal TextBox ResponsavelBox; + + internal TextBox DocumentoResponsavel; + + internal TextBox EmailBox; + + internal TextBox PastaBox; + + internal AutoCompleteBox AutoCompleteBanco; + + internal TextBox AgenciaBox; + + internal TextBox TipoContaBox; + + internal TextBox ContaBox; + + internal CurrencyTextBox RendaMensalBox; + + internal ListBox TelefoneListBox; + + internal ListBox EmailListBox; + + internal ListBox EnderecoListBox; + + internal AutoCompleteBox VinculoBox; + + internal TextBox NomeOrigemBox; + + internal ListBox ContatosListBox; + + private bool _contentLoaded; + + private static int Ordem + { + get; + set; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public ClienteView(Cliente cliente = null, bool lockInsert = false, ClienteViewModel viewModel = null) + { + base.Tag = "CADASTRO DE CLIENTES"; + this.ViewModel = viewModel ?? new ClienteViewModel(cliente, !lockInsert); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher != null) + { + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + else + { + } + if (lockInsert) + { + this.IncluirClienteButton.IsEnabled = false; + } + if (cliente != null) + { + this.ViewModel.RegistrarAcao(string.Concat("ACESSOU CLIENTE \"", cliente.get_Nome(), "\""), cliente.get_Id(), new TipoTela?(1), string.Format("ID CLIENTE: {0}", cliente.get_Id())); + } + } + + private async void AbrirAquivoDigital_Click(object sender, RoutedEventArgs e) + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 1).get_Consultar()) + { + FiltroArquivoDigital filtroArquivoDigital = new FiltroArquivoDigital(); + filtroArquivoDigital.set_Id(this.ViewModel.SelectedCliente.get_Id()); + filtroArquivoDigital.set_Tipo(1); + filtroArquivoDigital.set_Parente(this.ViewModel.SelectedCliente); + this.ViewModel.ShowDrawer(new ArquivoDigitalDrawer(filtroArquivoDigital), 0, false); + } + else + { + await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", EnumHelper.GetDescription(1), "."), "OK", "", false); + } + } + + private void AbrirLog_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLog(1, this.ViewModel.SelectedCliente.get_Id()); + } + + private void AbrirLogEmail_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLogEmail(1, this.ViewModel.SelectedCliente.get_Id()); + } + + private void Alterar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Alterar(true); + this.ClearInputFields(); + this.ValidarTela(); + this.ViewModel.SelectedCliente.Initialize(); + this.InitializeResponsavelAssinatura(); + this.ViewModel.Salvando = false; + } + + private void AutoCompleteAtividadeBox_Populating(object sender, PopulatingEventArgs e) + { + if (e.get_Parameter().Length < 1) + { + return; + } + e.set_Cancel(true); + this.ViewModel.BuscarAtividade(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void AutoCompleteBanco_OnLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) + { + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + ClienteView.SetValid(autoCompleteBox, (string.IsNullOrWhiteSpace(autoCompleteBox.get_Text()) ? true : this.ViewModel.SelectedCliente.get_Banco() != null)); + } + + private void AutoCompleteBancoBox_Populating(object sender, PopulatingEventArgs e) + { + if (e.get_Parameter().Length < 3) + { + return; + } + e.set_Cancel(true); + this.ViewModel.BuscarBanco(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void AutoCompleteParentescoBox_Populating(object sender, PopulatingEventArgs e) + { + if (e.get_Parameter().Length < 3) + { + return; + } + e.set_Cancel(true); + this.ViewModel.BuscarClienteVinculo(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim()), this.ViewModel.SelectedCliente.get_Id()).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void AutoCompleteProfissaoBox_Populating(object sender, PopulatingEventArgs e) + { + if (e.get_Parameter().Length < 1) + { + return; + } + e.set_Cancel(true); + this.ViewModel.BuscarProfissao(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + this.ClearInputFields(); + ClienteView.SetValid(this.AutoCompleteBanco, true); + this.ViewModel.CancelarAlteracao(); + } + + private void ClearInputFields() + { + object nome; + object empty; + object obj; + object nome1; + AutoCompleteBox autoCompleteBanco = this.AutoCompleteBanco; + Banco banco = this.ViewModel.SelectedCliente.get_Banco(); + if (banco != null) + { + nome = banco.get_Nome(); + } + else + { + nome = null; + } + if (nome == null) + { + nome = string.Empty; + } + autoCompleteBanco.set_Text((string)nome); + AutoCompleteBox autoCompleteProfissao = this.AutoCompleteProfissao; + Profissao profissao = this.ViewModel.SelectedCliente.get_Profissao(); + if (profissao != null) + { + empty = profissao.get_Nome(); + } + else + { + empty = null; + } + if (empty == null) + { + empty = string.Empty; + } + autoCompleteProfissao.set_Text((string)empty); + AutoCompleteBox autoCompleteBox = this.AutoCompleteProfissao; + Profissao profissao1 = this.ViewModel.SelectedCliente.get_Profissao(); + if (profissao1 != null) + { + obj = profissao1.get_Nome(); + } + else + { + obj = null; + } + if (obj == null) + { + obj = string.Empty; + } + autoCompleteBox.set_Text((string)obj); + AutoCompleteBox autoCompleteAtividade = this.AutoCompleteAtividade; + Atividade atividade = this.ViewModel.SelectedCliente.get_Atividade(); + if (atividade != null) + { + nome1 = atividade.get_Nome(); + } + else + { + nome1 = null; + } + if (nome1 == null) + { + nome1 = string.Empty; + } + autoCompleteAtividade.set_Text((string)nome1); + } + + private void ContentLoad() + { + string nome; + string str; + string nome1; + this.TelefoneListBox.DataContext = this.ViewModel; + this.EmailListBox.DataContext = this.ViewModel; + this.EnderecoListBox.DataContext = this.ViewModel; + this.ContatosListBox.DataContext = this.ViewModel; + this.DocumentoResponsavel.LostFocus += new RoutedEventHandler(this.Validar_LostFocus); + if (this.ViewModel.SelectedCliente == null) + { + return; + } + AutoCompleteBox autoCompleteBanco = this.AutoCompleteBanco; + Banco banco = this.ViewModel.SelectedCliente.get_Banco(); + if (banco != null) + { + nome = banco.get_Nome(); + } + else + { + nome = null; + } + autoCompleteBanco.set_Text(nome); + AutoCompleteBox autoCompleteAtividade = this.AutoCompleteAtividade; + Atividade atividade = this.ViewModel.SelectedCliente.get_Atividade(); + if (atividade != null) + { + str = atividade.get_Nome(); + } + else + { + str = null; + } + autoCompleteAtividade.set_Text(str); + AutoCompleteBox autoCompleteProfissao = this.AutoCompleteProfissao; + Profissao profissao = this.ViewModel.SelectedCliente.get_Profissao(); + if (profissao != null) + { + nome1 = profissao.get_Nome(); + } + else + { + nome1 = null; + } + autoCompleteProfissao.set_Text(nome1); + } + + private void DocumentoPrincipalBox_LostFocus(object sender, RoutedEventArgs e) + { + if (((TextBox)sender).IsReadOnly) + { + return; + } + TextBox textBox = (TextBox)sender; + string str = ValidationHelper.Clear(textBox.Text); + if (string.IsNullOrEmpty(str)) + { + return; + } + textBox.Text = (str.Length == 11 ? ValidationHelper.FormatDocument(str.PadLeft(11, '0').Substring(0, 11)) : ValidationHelper.FormatDocument(str.PadLeft(14, '0').Substring(0, 14))); + if (textBox.Name == "DocumentoPrincipalBox") + { + this.ViewModel.JuridicaouFisica(this.DocumentoPrincipalBox.Text); + if (this.ViewModel.VisibilityFisica == System.Windows.Visibility.Visible) + { + this.ResponsavelBox.Text = string.Empty; + this.DocumentoResponsavel.Text = string.Empty; + this.EmailBox.Text = string.Empty; + } + } + } + + private void Excluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Excluir(); + } + + private void ExcluirEmail_OnClick(object sender, RoutedEventArgs e) + { + Button button = sender as Button; + if (button == null) + { + return; + } + ListBox listBox = Extentions.FindVisualAncestor(button); + ClienteEmail item = (ClienteEmail)listBox.Items[listBox.Items.IndexOf(button.DataContext)]; + this.ViewModel.ExcluirEmail(item); + } + + private void ExcluirEndereco_OnClick(object sender, RoutedEventArgs e) + { + Grid grid = Extentions.FindVisualAncestor((Button)sender); + ListBox listBox = Extentions.FindVisualAncestor(grid); + ClienteEndereco item = (ClienteEndereco)listBox.Items[listBox.Items.IndexOf(grid.DataContext)]; + this.ViewModel.ExcluirEndereco(item); + } + + private void ExcluirMaisContatos_OnClick(object sender, RoutedEventArgs e) + { + Button button = (Button)sender; + if (button == null || button.DataContext == null) + { + return; + } + MaisContato dataContext = (MaisContato)button.DataContext; + this.ViewModel.ExcluirContato(dataContext); + } + + private async void ExcluirOrigem_OnClick(object sender, RoutedEventArgs e) + { + Button button = (Button)sender; + if (button.DataContext != null) + { + this.ViewModel.Loading(true); + await this.ViewModel.ExcluirOrigem((OrigemCliente)button.DataContext); + this.ViewModel.Loading(false); + } + } + + private void ExcluirTelefone_OnClick(object sender, RoutedEventArgs e) + { + Button button = sender as Button; + if (button == null) + { + return; + } + ListBox listBox = Extentions.FindVisualAncestor(button); + ClienteTelefone item = (ClienteTelefone)listBox.Items[listBox.Items.IndexOf(button.DataContext)]; + this.ViewModel.ExcluirTelefone(item); + } + + private void ExcluirVinculo_OnClick(object sender, RoutedEventArgs e) + { + Button button = (Button)sender; + if (button == null || button.DataContext == null) + { + return; + } + ClienteVinculo dataContext = (ClienteVinculo)button.DataContext; + this.ViewModel.ExcluirVinculo(dataContext); + } + + public override void FormatarDocumento(object sender, RoutedEventArgs e) + { + TextBox textBox = (TextBox)sender; + textBox.Text = ValidationHelper.FormatDocument(textBox.Text); + this.ViewModel.JuridicaouFisica(textBox.Text); + } + + private void Incluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.IncluirCliente(); + this.DocumentoPrincipalBox.Text = ""; + this.AutoCompleteBanco.set_Text(""); + this.AutoCompleteProfissao.set_Text(""); + this.AutoCompleteAtividade.set_Text(""); + this.DocumentoPrincipalBox.Focus(); + this.ValidarTela(); + } + + private void IncluirEmail_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.IncluirEmail(); + this.ValidarTela(); + } + + private void IncluirEndereco_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.IncluirEndereco(); + this.ValidarTela(); + } + + private void IncluirMaisContatos_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.IncluirContato(); + } + + private async void IncluirOrigem_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Loading(true); + await this.ViewModel.IncluirOrigem(this.NomeOrigemBox.Text.Trim()); + this.NomeOrigemBox.Text = string.Empty; + this.ViewModel.Loading(false); + } + + private void IncluirTelefone_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.IncluirTelefone(); + } + + private void IncluirVinculo_OnClick(object sender, RoutedEventArgs e) + { + if (this.ViewModel.IncluirVinculo()) + { + this.VinculoBox.set_Text(""); + } + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/seguros/clienteview.xaml", UriKind.Relative)); + } + + private void InitializeResponsavelAssinatura() + { + object nomeResponsavel; + object documentoResponsavel; + object emailResponsavel; + TextBox responsavelBox = this.ResponsavelBox; + ResponsavelAssinatura responsavelAssinatura = this.ViewModel.SelectedCliente.get_ResponsavelAssinatura(); + if (responsavelAssinatura != null) + { + nomeResponsavel = responsavelAssinatura.get_NomeResponsavel(); + } + else + { + nomeResponsavel = null; + } + if (nomeResponsavel == null) + { + nomeResponsavel = string.Empty; + } + responsavelBox.Text = (string)nomeResponsavel; + TextBox textBox = this.DocumentoResponsavel; + ResponsavelAssinatura responsavelAssinatura1 = this.ViewModel.SelectedCliente.get_ResponsavelAssinatura(); + if (responsavelAssinatura1 != null) + { + documentoResponsavel = responsavelAssinatura1.get_DocumentoResponsavel(); + } + else + { + documentoResponsavel = null; + } + if (documentoResponsavel == null) + { + documentoResponsavel = string.Empty; + } + textBox.Text = (string)documentoResponsavel; + TextBox emailBox = this.EmailBox; + ResponsavelAssinatura responsavelAssinatura2 = this.ViewModel.SelectedCliente.get_ResponsavelAssinatura(); + if (responsavelAssinatura2 != null) + { + emailResponsavel = responsavelAssinatura2.get_EmailResponsavel(); + } + else + { + emailResponsavel = null; + } + if (emailResponsavel == null) + { + emailResponsavel = string.Empty; + } + emailBox.Text = (string)emailResponsavel; + } + + private void MenuItem_Click(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLogAntigo(); + } + + private void OrdemBox_OnLostFocus(object sender, RoutedEventArgs e) + { + int num; + int num1; + TextBox textBox = sender as TextBox; + if (textBox == null) + { + return; + } + if (textBox.IsReadOnly) + { + return; + } + if (!int.TryParse(textBox.Text, out num)) + { + return; + } + WrapPanel wrapPanel = Extentions.FindVisualAncestor(Extentions.FindVisualAncestor(textBox)); + ListBox listBox = Extentions.FindVisualAncestor(wrapPanel); + if (listBox != null) + { + for (int i = 0; i < listBox.Items.Count; i++) + { + if (i != listBox.Items.IndexOf(wrapPanel.DataContext)) + { + ContentPresenter contentPresenter = FindVisualChild.Find((ListBoxItem)listBox.ItemContainerGenerator.ContainerFromIndex(i)); + TextBox str = (TextBox)contentPresenter.ContentTemplate.FindName("OrdemBox", contentPresenter); + if (int.TryParse(str.Text, out num1) && num1 == num) + { + str.Text = ClienteView.Ordem.ToString(); + } + } + } + } + } + + private void OrdemBox_OnPreviewGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) + { + int num; + TextBox textBox = sender as TextBox; + if (textBox == null) + { + return; + } + if (!int.TryParse(textBox.Text, out num)) + { + return; + } + ClienteView.Ordem = num; + } + + private async void PostcodeBox_OnLostFocus(object sender, RoutedEventArgs e) + { + ContentPresenter contentPresenter; + DataTemplate contentTemplate; + ProgressBar progressBar; + TextBox textBox = (TextBox)sender; + if (!textBox.IsReadOnly) + { + if (!string.IsNullOrWhiteSpace(textBox.Text)) + { + string str = ValidationHelper.FormatPostCode(textBox.Text); + WrapPanel wrapPanel = Extentions.FindVisualAncestor(textBox); + ListBox listBox = Extentions.FindVisualAncestor(wrapPanel); + ListBoxItem listBoxItem = (ListBoxItem)listBox.ItemContainerGenerator.ContainerFromIndex(listBox.Items.IndexOf(wrapPanel.DataContext)); + contentPresenter = FindVisualChild.Find(listBoxItem); + contentTemplate = contentPresenter.ContentTemplate; + TextBox textBox1 = (TextBox)contentTemplate.FindName("CepBox", contentPresenter); + progressBar = (ProgressBar)contentTemplate.FindName("ProgressCep", contentPresenter); + progressBar.Visibility = System.Windows.Visibility.Visible; + textBox1.Text = str; + if (ValidationHelper.ValidatePostCode(str)) + { + EnderecoBase enderecoBase = await this.ViewModel.BuscaCep(str); + if (enderecoBase != null) + { + TextBox endereco = (TextBox)contentTemplate.FindName("EnderecoBox", contentPresenter); + TextBox cidade = (TextBox)contentTemplate.FindName("CidadeBox", contentPresenter); + TextBox estado = (TextBox)contentTemplate.FindName("EstadoBox", contentPresenter); + TextBox bairro = (TextBox)contentTemplate.FindName("BairroBox", contentPresenter); + endereco.Text = enderecoBase.get_Endereco(); + cidade.Text = enderecoBase.get_Cidade(); + estado.Text = enderecoBase.get_Estado(); + bairro.Text = enderecoBase.get_Bairro(); + progressBar.Visibility = System.Windows.Visibility.Collapsed; + } + else + { + progressBar.Visibility = System.Windows.Visibility.Collapsed; + } + } + else + { + progressBar.Visibility = System.Windows.Visibility.Collapsed; + } + } + } + contentPresenter = null; + contentTemplate = null; + progressBar = null; + } + + private async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.Loading(true); + this.ViewModel.ProfissaoText = this.AutoCompleteProfissao.get_Text(); + this.ViewModel.AtividadeText = this.AutoCompleteAtividade.get_Text(); + List> keyValuePairs = await this.ViewModel.Salvar(); + this.ValidateFields(keyValuePairs, true); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs.Distinct>().ToList>(), this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + else + { + ClienteView.SetValid(this.AutoCompleteBanco, true); + } + } + + private static void SetValid(AutoCompleteBox autocomplete, bool valid) + { + ViewHelper.SetInvalid(autocomplete, "BANCO INVÁLIDO", valid); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.MainGrid = (Grid)target; + return; + } + case 2: + { + this.IncluirClienteButton = (MenuItem)target; + this.IncluirClienteButton.Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + case 3: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 4: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 6: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Excluir_OnClick); + return; + } + case 7: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirAquivoDigital_Click); + return; + } + case 8: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Tarefa_Click); + return; + } + case 9: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick); + return; + } + case 10: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLogEmail_OnClick); + return; + } + case 11: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.MenuItem_Click); + return; + } + case 12: + { + this.TipoDocumentoPrincipalBox = (ComboBox)target; + return; + } + case 13: + { + this.DocumentoPrincipalBox = (TextBox)target; + ClienteView clienteView = this; + this.DocumentoPrincipalBox.PreviewTextInput += new TextCompositionEventHandler(clienteView.SomenteNumeros); + this.DocumentoPrincipalBox.LostFocus += new RoutedEventHandler(this.DocumentoPrincipalBox_LostFocus); + return; + } + case 14: + { + this.NomeBox = (TextBox)target; + return; + } + case 15: + { + this.NomeSocialBox = (TextBox)target; + return; + } + case 16: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + ((DatePicker)target).PreviewTextInput += new TextCompositionEventHandler(this.SomenteData); + return; + } + case 17: + { + this.CaepfBox = (TextBox)target; + return; + } + case 18: + { + this.RneBox = (TextBox)target; + return; + } + case 19: + { + this.CeiBox = (TextBox)target; + return; + } + case 20: + { + this.IdentidadeBox = (TextBox)target; + return; + } + case 21: + { + this.EmissorBox = (TextBox)target; + this.EmissorBox.PreviewTextInput += new TextCompositionEventHandler(this.SomenteCaracteres); + return; + } + case 22: + { + this.EstadoEmissorBox = (TextBox)target; + this.EstadoEmissorBox.PreviewTextInput += new TextCompositionEventHandler(this.SomenteCaracteres); + return; + } + case 23: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + ((DatePicker)target).PreviewTextInput += new TextCompositionEventHandler(this.SomenteData); + return; + } + case 24: + { + this.HabilitacaoBox = (TextBox)target; + ClienteView clienteView1 = this; + this.HabilitacaoBox.PreviewTextInput += new TextCompositionEventHandler(clienteView1.SomenteNumeros); + return; + } + case 25: + { + this.CategoriaHabilitacaooBox = (TextBox)target; + ClienteView clienteView2 = this; + this.CategoriaHabilitacaooBox.PreviewTextInput += new TextCompositionEventHandler(clienteView2.LetrasHabilitacao); + return; + } + case 26: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + return; + } + case 27: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + return; + } + case 28: + { + this.SexoBox = (ComboBox)target; + return; + } + case 29: + { + this.EstadoCivilBox = (ComboBox)target; + return; + } + case 30: + { + this.AutoCompleteProfissao = (AutoCompleteBox)target; + this.AutoCompleteProfissao.add_Populating(new PopulatingEventHandler(this, ClienteView.AutoCompleteProfissaoBox_Populating)); + return; + } + case 31: + { + this.AutoCompleteAtividade = (AutoCompleteBox)target; + this.AutoCompleteAtividade.add_Populating(new PopulatingEventHandler(this, ClienteView.AutoCompleteAtividadeBox_Populating)); + return; + } + case 32: + { + this.ResponsavelBox = (TextBox)target; + this.ResponsavelBox.LostFocus += new RoutedEventHandler(this.Validar_LostFocus); + return; + } + case 33: + { + this.DocumentoResponsavel = (TextBox)target; + ClienteView clienteView3 = this; + this.DocumentoResponsavel.PreviewTextInput += new TextCompositionEventHandler(clienteView3.SomenteNumeros); + this.DocumentoResponsavel.LostFocus += new RoutedEventHandler(this.DocumentoPrincipalBox_LostFocus); + return; + } + case 34: + { + this.EmailBox = (TextBox)target; + this.EmailBox.LostFocus += new RoutedEventHandler(this.Validar_LostFocus); + return; + } + case 35: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + return; + } + case 36: + { + this.PastaBox = (TextBox)target; + return; + } + case 37: + { + this.AutoCompleteBanco = (AutoCompleteBox)target; + this.AutoCompleteBanco.add_Populating(new PopulatingEventHandler(this, ClienteView.AutoCompleteBancoBox_Populating)); + this.AutoCompleteBanco.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.AutoCompleteBanco_OnLostKeyboardFocus); + return; + } + case 38: + { + this.AgenciaBox = (TextBox)target; + return; + } + case 39: + { + this.TipoContaBox = (TextBox)target; + return; + } + case 40: + { + this.ContaBox = (TextBox)target; + return; + } + case 41: + { + this.RendaMensalBox = (CurrencyTextBox)target; + return; + } + case 42: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.IncluirTelefone_OnClick); + return; + } + case 43: + { + this.TelefoneListBox = (ListBox)target; + return; + } + case 44: + case 45: + case 46: + case 47: + case 48: + case 51: + case 52: + case 55: + case 56: + case 57: + case 60: + case 63: + { + this._contentLoaded = true; + return; + } + case 49: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.IncluirEmail_OnClick); + return; + } + case 50: + { + this.EmailListBox = (ListBox)target; + return; + } + case 53: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.IncluirEndereco_OnClick); + return; + } + case 54: + { + this.EnderecoListBox = (ListBox)target; + return; + } + case 58: + { + this.VinculoBox = (AutoCompleteBox)target; + this.VinculoBox.add_Populating(new PopulatingEventHandler(this, ClienteView.AutoCompleteParentescoBox_Populating)); + return; + } + case 59: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.IncluirVinculo_OnClick); + return; + } + case 61: + { + this.NomeOrigemBox = (TextBox)target; + return; + } + case 62: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.IncluirOrigem_OnClick); + return; + } + case 64: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.IncluirMaisContatos_OnClick); + return; + } + case 65: + { + this.ContatosListBox = (ListBox)target; + return; + } + default: + { + this._contentLoaded = true; + return; + } + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 44: + { + ((ComboBox)target).SelectionChanged += new SelectionChangedEventHandler(this.TipoComboBox_OnSelectionChanged); + return; + } + case 45: + { + ClienteView clienteView = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(clienteView.SomenteNumeros); + return; + } + case 46: + { + ClienteView clienteView1 = this; + ((TextBox)target).LostFocus += new RoutedEventHandler(clienteView1.FormatarTelefone); + ClienteView clienteView2 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(clienteView2.SomenteNumeros); + return; + } + case 47: + { + ((TextBox)target).PreviewGotKeyboardFocus += new KeyboardFocusChangedEventHandler(this.OrdemBox_OnPreviewGotKeyboardFocus); + ((TextBox)target).LostFocus += new RoutedEventHandler(this.OrdemBox_OnLostFocus); + ClienteView clienteView3 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(clienteView3.SomenteNumeros); + return; + } + case 48: + { + ((Button)target).Click += new RoutedEventHandler(this.ExcluirTelefone_OnClick); + return; + } + case 49: + case 50: + case 53: + case 54: + case 58: + case 59: + case 61: + case 62: + case 64: + case 65: + { + return; + } + case 51: + { + ((TextBox)target).PreviewGotKeyboardFocus += new KeyboardFocusChangedEventHandler(this.OrdemBox_OnPreviewGotKeyboardFocus); + ((TextBox)target).LostFocus += new RoutedEventHandler(this.OrdemBox_OnLostFocus); + ClienteView clienteView4 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(clienteView4.SomenteNumeros); + return; + } + case 52: + { + ((Button)target).Click += new RoutedEventHandler(this.ExcluirEmail_OnClick); + return; + } + case 55: + { + ((TextBox)target).LostFocus += new RoutedEventHandler(this.PostcodeBox_OnLostFocus); + ClienteView clienteView5 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(clienteView5.SomenteNumeros); + return; + } + case 56: + { + ((TextBox)target).PreviewGotKeyboardFocus += new KeyboardFocusChangedEventHandler(this.OrdemBox_OnPreviewGotKeyboardFocus); + ((TextBox)target).LostFocus += new RoutedEventHandler(this.OrdemBox_OnLostFocus); + ClienteView clienteView6 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(clienteView6.SomenteNumeros); + return; + } + case 57: + { + ((Button)target).Click += new RoutedEventHandler(this.ExcluirEndereco_OnClick); + return; + } + case 60: + { + ((Button)target).Click += new RoutedEventHandler(this.ExcluirVinculo_OnClick); + return; + } + case 63: + { + ((Button)target).Click += new RoutedEventHandler(this.ExcluirOrigem_OnClick); + return; + } + case 66: + { + ClienteView clienteView7 = this; + ((TextBox)target).LostFocus += new RoutedEventHandler(clienteView7.FormatarDocumento); + return; + } + case 67: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + ((DatePicker)target).PreviewTextInput += new TextCompositionEventHandler(this.SomenteData); + return; + } + case 68: + { + ((ComboBox)target).SelectionChanged += new SelectionChangedEventHandler(this.TipoComboBox_OnSelectionChanged); + return; + } + case 69: + { + ClienteView clienteView8 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(clienteView8.SomenteNumeros); + return; + } + case 70: + { + ClienteView clienteView9 = this; + ((TextBox)target).LostFocus += new RoutedEventHandler(clienteView9.FormatarTelefone); + ClienteView clienteView10 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(clienteView10.SomenteNumeros); + return; + } + case 71: + { + ((Button)target).Click += new RoutedEventHandler(this.ExcluirMaisContatos_OnClick); + return; + } + default: + { + return; + } + } + } + + private void Tarefa_Click(object sender, RoutedEventArgs e) + { + Tarefa tarefa = new Tarefa(); + tarefa.set_IdCliente(this.ViewModel.SelectedCliente.get_Id()); + tarefa.set_Cliente(this.ViewModel.SelectedCliente.get_Nome()); + tarefa.set_Entidade(2); + tarefa.set_IdEntidade(this.ViewModel.SelectedCliente.get_Id()); + tarefa.set_Titulo(this.ViewModel.SelectedCliente.get_Nome()); + this.ViewModel.ShowDrawer(new TarefaDrawer(tarefa, true), 0, false); + } + + private void TipoComboBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + int num; + ComboBox comboBox = (ComboBox)sender; + CustomIsReadOnlyControl customIsReadOnlyControl = Extentions.FindVisualAncestor(comboBox); + if (customIsReadOnlyControl == null) + { + return; + } + WrapPanel wrapPanel = Extentions.FindVisualAncestor(customIsReadOnlyControl); + ListBox listBox = Extentions.FindVisualAncestor(wrapPanel); + ContentPresenter contentPresenter = FindVisualChild.Find((ListBoxItem)listBox.ItemContainerGenerator.ContainerFromIndex(listBox.Items.IndexOf(wrapPanel.DataContext))); + DataTemplate contentTemplate = contentPresenter.ContentTemplate; + CustomItemValidation customItemValidation = (CustomItemValidation)contentTemplate.FindName("Prefixo", contentPresenter); + CustomItemValidation customItemValidation1 = (CustomItemValidation)contentTemplate.FindName("Telefone", contentPresenter); + TextBox textBox = ViewHelper.FindChildren(customItemValidation).FirstOrDefault(); + TextBox textBox1 = ViewHelper.FindChildren(customItemValidation1).FirstOrDefault(); + if (textBox == null || textBox1 == null) + { + return; + } + if ((TipoTelefone)comboBox.SelectedValue == 8) + { + customItemValidation.Visibility = System.Windows.Visibility.Collapsed; + textBox1.MaxLength = 20; + return; + } + customItemValidation.Visibility = System.Windows.Visibility.Visible; + textBox1.MaxLength = 10; + num = (textBox1.Text.Length >= 10 ? 10 : textBox1.Text.Length); + textBox1.Text = textBox1.Text.Substring(0, num); + } + + private void Validar_LostFocus(object sender, RoutedEventArgs e) + { + this.ValidarTela(); + } + + private void ValidarTela() + { + object keyValuePairs; + object obj; + object keyValuePairs1; + if (this.ViewModel.SelectedCliente == null) + { + return; + } + List> keyValuePairs2 = this.ViewModel.SelectedCliente.Validate(); + if (Recursos.Configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 29)) + { + List> keyValuePairs3 = keyValuePairs2; + ClienteEmail clienteEmail = this.ViewModel.Emails.FirstOrDefault(); + if (clienteEmail != null) + { + keyValuePairs1 = clienteEmail.Validate(); + } + else + { + keyValuePairs1 = null; + } + if (keyValuePairs1 == null) + { + keyValuePairs1 = new List>(); + } + keyValuePairs3.AddRange((IEnumerable)keyValuePairs1); + } + List> keyValuePairs4 = keyValuePairs2; + ClienteTelefone clienteTelefone = this.ViewModel.Telefones.FirstOrDefault(); + if (clienteTelefone != null) + { + keyValuePairs = clienteTelefone.Validate(); + } + else + { + keyValuePairs = null; + } + if (keyValuePairs == null) + { + keyValuePairs = new List>(); + } + keyValuePairs4.AddRange((IEnumerable)keyValuePairs); + List> keyValuePairs5 = keyValuePairs2; + ClienteEndereco clienteEndereco = this.ViewModel.Enderecos.FirstOrDefault(); + if (clienteEndereco != null) + { + obj = clienteEndereco.Validate(); + } + else + { + obj = null; + } + if (obj == null) + { + obj = new List>(); + } + keyValuePairs5.AddRange((IEnumerable)obj); + this.ValidateFields(keyValuePairs2, false); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Seguros/ComissaoView.cs b/Codemerx/Gestor.Application/Views/Seguros/ComissaoView.cs new file mode 100644 index 0000000..7bbf613 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Seguros/ComissaoView.cs @@ -0,0 +1,1336 @@ +using Gestor.Application.Actions; +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.ViewModels.Comissao; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using MaterialDesignThemes.Wpf; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; +using Xceed.Wpf.AvalonDock.Controls; + +namespace Gestor.Application.Views.Seguros +{ + public class ComissaoView : BaseUserControl, IComponentConnector, IStyleConnector + { + internal ComboBox UsuarioBox; + + internal ComboBox StatusBox; + + internal ComboBox SeguradoraBox; + + internal ComboBox Seguradora2Box; + + internal DatePicker InicioBox; + + internal DatePicker FimBox; + + internal DataGrid ExtratoGrid; + + internal Card ProgressBar2; + + internal Card ProgressBar; + + internal MenuItem DesfazerExtratoButton; + + internal DatePicker DataBaixaBox; + + internal TextBox FiltroDetalhes; + + internal DataGrid DetalhesGrid; + + internal Grid PainelCritica; + + internal AutoCompleteBox AutoCompleteCliente; + + internal TextBox TipoDocumentoPrincipalBox; + + internal TextBox DocumentoPrincipalBox; + + internal TextBox FiltroApoliceBox; + + internal DataGrid ApoliceGrid; + + internal DataGrid ParcelaGrid; + + internal DataGridTextColumn ParcelaColumn; + + internal DataGrid FaturaGrid; + + private bool _contentLoaded; + + public SubTipo _previousSubTipo { get; set; } = 2; + + public ComissaoViewModel ViewModel + { + get; + set; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public ComissaoView() + { + base.Tag = "COMISSÃO AUTOMÁTICA"; + this.ViewModel = new ComissaoViewModel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher != null) + { + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + else + { + } + this.ExtratoGrid.DataContext = base.DataContext; + } + + private async void AbrirAquivoDigital_Click(object sender, RoutedEventArgs e) + { + if (!(new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 7).get_Consultar()) + { + await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", ValidationHelper.GetDescription((TipoArquivoDigital)7), "."), "OK", "", false); + } + else if (this.ViewModel.SelectedExtrato != null) + { + List indiceArquivoDigitals = await (new ArquivoDigitalServico()).BuscarPorTipo(7, this.ViewModel.SelectedExtrato.get_Id()); + if (indiceArquivoDigitals.Count != 1) + { + FiltroArquivoDigital filtroArquivoDigital = new FiltroArquivoDigital(); + filtroArquivoDigital.set_Id(this.ViewModel.SelectedExtrato.get_Id()); + filtroArquivoDigital.set_Tipo(7); + filtroArquivoDigital.set_Parente(this.ViewModel.SelectedExtrato); + this.ViewModel.ShowDrawer(new ArquivoDigitalDrawer(filtroArquivoDigital), 0, false); + } + else + { + this.ViewModel.Download(indiceArquivoDigitals.First(), true); + } + } + else + { + await this.ViewModel.ShowMessage("SELECIONE ALGUM EXTRATO PARA VISUALIZAR O ARQUIVO DIGITAL", "OK", "", false); + } + } + + private async Task AbrirCritica(DetalheExtrato detalhe) + { + List statusParcelas = new List() + { + 1, + 10, + 12, + 13 + }; + if (!detalhe.get_Status().HasValue || !statusParcelas.Contains(detalhe.get_Status().Value)) + { + this.ViewModel.FiltrarDetalheExtrato(detalhe.get_Id()); + await this.ViewModel.BuscarCriticado(detalhe); + if (!detalhe.get_Parcela().HasValue && !detalhe.get_Documento().HasValue) + { + this.AutoCompleteCliente.set_Text(detalhe.get_Cliente().Trim()); + } + this.ViewModel.Criticando = true; + this.PainelCritica.Visibility = System.Windows.Visibility.Visible; + this.FiltroDetalhes.Visibility = System.Windows.Visibility.Collapsed; + this.DetalhesGrid.Visibility = System.Windows.Visibility.Collapsed; + Action enableMainMenu = Gestor.Application.Actions.Actions.EnableMainMenu; + if (enableMainMenu != null) + { + enableMainMenu(false); + } + else + { + } + Action enableMenu = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu != null) + { + enableMenu(false); + } + else + { + } + this.ViewModel.FiltroApolice = string.Empty; + } + else + { + await this.ViewModel.ShowMessage("NÃO É POSSÍVEL CRITICAR UMA PARCELA JÁ BAIXADA", "OK", "", false); + } + } + + private async void AbrirCritica_OnClick(object sender, RoutedEventArgs e) + { + object item; + if (this.DetalhesGrid.SelectedIndex >= 0) + { + DataGrid detalhesGrid = this.DetalhesGrid; + if (detalhesGrid != null) + { + item = detalhesGrid.Items[this.DetalhesGrid.SelectedIndex]; + } + else + { + item = null; + } + DetalheExtrato detalheExtrato = (DetalheExtrato)item; + if (detalheExtrato != null) + { + this.ViewModel.Loading(true); + this.ViewModel.IsVisibleDetalhes = System.Windows.Visibility.Collapsed; + await this.AbrirCritica(detalheExtrato); + this.ViewModel.IsVisibleDetalhes = System.Windows.Visibility.Visible; + this.ViewModel.Loading(false); + } + } + else + { + await this.ViewModel.ShowMessage("PARA CRITICAR O DOCUMENTO É NECESSÁRIO SELECIONAR UMA PARCELA", "OK", "", false); + } + } + + private async void AcessarApolice_OnClick(object sender, RoutedEventArgs e) + { + long? parcela; + Documento documento; + Documento documento1; + bool flag; + bool flag1; + Button button = (Button)sender; + if (button.DataContext != null && button.DataContext.GetType().Name.Equals("DetalheExtrato")) + { + DetalheExtrato dataContext = (DetalheExtrato)button.DataContext; + flag = (dataContext != null ? !dataContext.get_Documento().HasValue : true); + if (flag) + { + flag1 = (dataContext != null ? !dataContext.get_Parcela().HasValue : true); + if (flag1) + { + return; + } + } + if (!dataContext.get_Documento().HasValue) + { + if (!dataContext.get_Parcela().HasValue) + { + documento1 = null; + } + else + { + ComissaoViewModel viewModel = this.ViewModel; + parcela = dataContext.get_Parcela(); + documento1 = await viewModel.CarregaApoliceParcela(parcela.Value); + } + documento = documento1; + } + else + { + ComissaoViewModel comissaoViewModel = this.ViewModel; + parcela = dataContext.get_Documento(); + documento = await comissaoViewModel.CarregaApolice(parcela.Value); + } + Documento documento2 = documento; + if (documento2 != null) + { + if (!documento2.get_Excluido()) + { + double? nullable = null; + double? nullable1 = nullable; + nullable = null; + (new HosterWindow(new ApoliceView(documento2, true, false, 0, (long)0, true), string.Concat("CADASTRO DE APÓLICE - ", documento2.get_Controle().get_Cliente().get_Nome(), " - ", documento2.get_Apolice()), nullable1, nullable, false)).Show(); + } + else + { + await this.ViewModel.ShowMessage("NÃO É POSSIVE VISUALIZAR UM DOCUMENTO EXCLUIDO.", "OK", "", false); + } + } + } + } + + private async void AcessarApoliceCritica_OnClick(object sender, RoutedEventArgs e) + { + double? nullable = null; + double? nullable1 = nullable; + nullable = null; + (new HosterWindow(new ApoliceView(await this.ViewModel.CarregaApolice(this.ViewModel.SelectedDocumento.get_Id()), true, false, 0, (long)0, false), string.Concat("CADASTRO DE APÓLICE - ", this.ViewModel.SelectedCliente.get_Nome(), " - ", this.ViewModel.SelectedDocumento.get_Apolice()), nullable1, nullable, false)).Show(); + } + + private void AdicionarFiltro_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AdcionarFiltro(); + } + + private async void ApoliceGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + object obj; + DataGrid dataGrid = (DataGrid)sender; + if (dataGrid == null || dataGrid.SelectedIndex >= 0) + { + ComissaoViewModel viewModel = this.ViewModel; + obj = (dataGrid != null ? dataGrid.Items[dataGrid.SelectedIndex] : null); + await viewModel.SelecionaDocumento((Documento)obj); + } + } + + private async void ArquivoDigitalButton_OnClick(object sender, RoutedEventArgs e) + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 2).get_Consultar()) + { + this.ViewModel.SelectedDocumento.get_Controle().set_Cliente(this.ViewModel.SelectedCliente); + FiltroArquivoDigital filtroArquivoDigital = new FiltroArquivoDigital(); + filtroArquivoDigital.set_Id(this.ViewModel.SelectedDocumento.get_Id()); + filtroArquivoDigital.set_Tipo(2); + filtroArquivoDigital.set_Parente(this.ViewModel.SelectedDocumento); + this.ViewModel.ShowDrawer(new ArquivoDigitalDrawer(filtroArquivoDigital), 0, false); + } + else + { + await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", ValidationHelper.GetDescription((TipoArquivoDigital)2), "."), "OK", "", false); + } + } + + private void Atualizar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.SelecionaSeguradora(this.ViewModel.SelectedSeguradora, this.ViewModel.SelectedStatusExtrato, this.ViewModel.SelectedExtrato); + } + + private async void AtualizarExtrato_OnClick(object sender, RoutedEventArgs e) + { + Action enableMainMenu = Gestor.Application.Actions.Actions.EnableMainMenu; + if (enableMainMenu != null) + { + enableMainMenu(false); + } + else + { + } + Action enableMenu = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu != null) + { + enableMenu(false); + } + else + { + } + this.ViewModel.EnableButtons = false; + await this.ViewModel.AtualizarExtrato(); + await this.ViewModel.SelecionaExtrato(this.ViewModel.SelectedExtrato); + this.ViewModel.EnableButtons = true; + Action action = Gestor.Application.Actions.Actions.EnableMenu; + if (action != null) + { + action(true); + } + else + { + } + Action enableMainMenu1 = Gestor.Application.Actions.Actions.EnableMainMenu; + if (enableMainMenu1 != null) + { + enableMainMenu1(true); + } + else + { + } + } + + private void AutoCompleteBox_Populating(object sender, PopulatingEventArgs e) + { + if (e.get_Parameter().Length < 3) + { + return; + } + e.set_Cancel(true); + this.ViewModel.BuscarCliente(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim()), null, 2).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private async void AutoCompleteBoxDetalhe_OnTextChanged(object sender, RoutedEventArgs e) + { + object text; + TextBox textBox = (TextBox)sender; + ComissaoViewModel viewModel = this.ViewModel; + if (textBox != null) + { + text = textBox.Text; + } + else + { + text = null; + } + if (text == null) + { + text = ""; + } + await viewModel.FiltrarDetalhe((string)text); + } + + private async void AutoCompleteBoxDocumento_OnTextChanged(object sender, RoutedEventArgs e) + { + object text; + TextBox textBox = (TextBox)sender; + ComissaoViewModel viewModel = this.ViewModel; + if (textBox != null) + { + text = textBox.Text; + } + else + { + text = null; + } + if (text == null) + { + text = ""; + } + await viewModel.FiltrarApolices((string)text); + } + + private async void BaixarParcelasSelecionadas_OnClick(object sender, RoutedEventArgs e) + { + ((MenuItem)sender).Click -= new RoutedEventHandler(this.BaixarParcelasSelecionadas_OnClick); + if (this.ViewModel.SelectedExtrato == null) + { + ((MenuItem)sender).Click += new RoutedEventHandler(this.BaixarParcelasSelecionadas_OnClick); + } + else if (await this.ViewModel.ShowMessage(string.Concat("DESEJA BAIXAR TODAS AS PARCELAS SELECIONADAS DO EXTRATO ", this.ViewModel.SelectedExtrato.get_Numero(), "?"), "SIM", "NÃO", false)) + { + this.ViewModel.IsVisible = System.Windows.Visibility.Collapsed; + this.ViewModel.IsVisibleDetalhes = System.Windows.Visibility.Collapsed; + this.ProgressBar.Visibility = System.Windows.Visibility.Visible; + this.ViewModel.EnableButtons = false; + Action enableMainMenu = Gestor.Application.Actions.Actions.EnableMainMenu; + if (enableMainMenu != null) + { + enableMainMenu(false); + } + else + { + } + Action enableMenu = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu != null) + { + enableMenu(false); + } + else + { + } + this.ViewModel.EnableButtons = false; + await this.ViewModel.BaixarExtrato(true); + this.ViewModel.EnableButtons = true; + Action action = Gestor.Application.Actions.Actions.EnableMainMenu; + if (action != null) + { + action(true); + } + else + { + } + Action enableMenu1 = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu1 != null) + { + enableMenu1(true); + } + else + { + } + this.ViewModel.EnableButtons = true; + this.ProgressBar.Visibility = System.Windows.Visibility.Collapsed; + this.ViewModel.IsVisibleDetalhes = System.Windows.Visibility.Visible; + this.ViewModel.IsVisible = System.Windows.Visibility.Visible; + this.ViewModel.WorkOnSelectedStatus(); + ((MenuItem)sender).Click += new RoutedEventHandler(this.BaixarParcelasSelecionadas_OnClick); + } + else + { + ((MenuItem)sender).Click += new RoutedEventHandler(this.BaixarParcelasSelecionadas_OnClick); + } + } + + private async void BaixarSelecionado_OnClick(object sender, RoutedEventArgs e) + { + ((MenuItem)sender).Click -= new RoutedEventHandler(this.BaixarSelecionado_OnClick); + if (this.ViewModel.SelectedExtrato == null) + { + ((MenuItem)sender).Click += new RoutedEventHandler(this.BaixarSelecionado_OnClick); + } + else if (await this.ViewModel.ShowMessage(string.Concat("DESEJA BAIXAR TODAS AS PARCELAS PENDENTES DO EXTRATO ", this.ViewModel.SelectedExtrato.get_Numero(), "?"), "SIM", "NÃO", false)) + { + this.ViewModel.IsVisible = System.Windows.Visibility.Collapsed; + this.ViewModel.IsVisibleDetalhes = System.Windows.Visibility.Collapsed; + this.ProgressBar.Visibility = System.Windows.Visibility.Visible; + this.ViewModel.EnableButtons = false; + Action enableMainMenu = Gestor.Application.Actions.Actions.EnableMainMenu; + if (enableMainMenu != null) + { + enableMainMenu(false); + } + else + { + } + Action enableMenu = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu != null) + { + enableMenu(false); + } + else + { + } + this.ViewModel.EnableButtons = false; + await this.ViewModel.BaixarExtrato(false); + this.ViewModel.EnableButtons = true; + Action action = Gestor.Application.Actions.Actions.EnableMainMenu; + if (action != null) + { + action(true); + } + else + { + } + Action enableMenu1 = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu1 != null) + { + enableMenu1(true); + } + else + { + } + this.ViewModel.EnableButtons = true; + this.ProgressBar.Visibility = System.Windows.Visibility.Collapsed; + this.ViewModel.IsVisibleDetalhes = System.Windows.Visibility.Visible; + this.ViewModel.IsVisible = System.Windows.Visibility.Visible; + ((MenuItem)sender).Click += new RoutedEventHandler(this.BaixarSelecionado_OnClick); + } + else + { + ((MenuItem)sender).Click += new RoutedEventHandler(this.BaixarSelecionado_OnClick); + } + } + + private void CancelarCritica_OnClick(object sender, RoutedEventArgs e) + { + if (this.ViewModel.SelectedDetalhe != null) + { + this.ViewModel.SelectedDetalhe.set_Corrigir(false); + } + this.LimparFiltros(); + } + + private void ContentLoad() + { + this.DataBaixaBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.DataBaixaBox.PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + this.InicioBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.InicioBox.PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + this.InicioBox.SelectedDateChanged += new EventHandler(this.FiltroDataBox_OnSelectedDateChanged); + this.FimBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.FimBox.PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + this.FimBox.SelectedDateChanged += new EventHandler(this.FiltroDataBox_OnSelectedDateChanged); + this.ExtratoGrid.SelectionChanged += new SelectionChangedEventHandler(this.Grid_OnSelectionChanged); + this.ExtratoGrid.MouseDoubleClick += new MouseButtonEventHandler((object sender, MouseButtonEventArgs args) => { + }); + this.DetalhesGrid.MouseDoubleClick += new MouseButtonEventHandler(this.DetalhesGrid_OnMouseDoubleClick); + this.ApoliceGrid.SelectionChanged += new SelectionChangedEventHandler(this.ApoliceGrid_OnSelectionChanged); + } + + private async void CriticarDocumento_OnClick(object sender, RoutedEventArgs e) + { + DetalheExtrato selectedDetalhe; + int? nullable; + object item; + if (this.DetalhesGrid.SelectedIndex >= 0) + { + SubTipo? subTipo = this.ViewModel.SelectedDetalhe.get_SubTipo(); + if (subTipo.HasValue && subTipo.GetValueOrDefault() == 1) + { + if (this.ViewModel.SelectedParcela == null || this.ViewModel.SelectedParcela.get_Id() == 0) + { + await this.ViewModel.ShowMessage("PARA CRITICAR ESSE DOCUMENTO É NECESSÁRIO SELECIONAR UMA PARCELA", "OK", "", false); + return; + } + } + else if (this.ViewModel.SelectedDocumento == null || this.ViewModel.SelectedDocumento.get_Id() == 0) + { + await this.ViewModel.ShowMessage("PARA CRITICAR ESSE DOCUMENTO É NECESSÁRIO SELECIONAR UM DOCUMENTO", "OK", "", false); + return; + } + if (this.DetalhesGrid.SelectedIndex < 0) + { + DataGrid detalhesGrid = this.DetalhesGrid; + if (detalhesGrid != null) + { + nullable = new int?(detalhesGrid.Items.Count); + } + else + { + nullable = null; + } + int? nullable1 = nullable; + int selectedIndex = this.DetalhesGrid.SelectedIndex; + if (nullable1.GetValueOrDefault() < selectedIndex | !nullable1.HasValue) + { + goto Label2; + } + DataGrid dataGrid = this.DetalhesGrid; + if (dataGrid != null) + { + item = dataGrid.Items[this.DetalhesGrid.SelectedIndex]; + } + else + { + item = null; + } + selectedDetalhe = (DetalheExtrato)item; + goto Label1; + } + Label2: + selectedDetalhe = this.ViewModel.SelectedDetalhe; + Label1: + DetalheExtrato detalheExtrato = selectedDetalhe; + if (detalheExtrato != null) + { + await this.ViewModel.Criticar(detalheExtrato, true); + this.LimparFiltros(); + } + } + else + { + await this.ViewModel.ShowMessage("NECESSÁRIO SELECIONAR UMA PARCELA PARA CRITICAR.", "OK", "", false); + } + } + + private async void Desconsiderar_OnClick(object sender, RoutedEventArgs e) + { + object item; + if (this.DetalhesGrid.SelectedIndex >= 0) + { + DataGrid detalhesGrid = this.DetalhesGrid; + if (detalhesGrid != null) + { + item = detalhesGrid.Items[this.DetalhesGrid.SelectedIndex]; + } + else + { + item = null; + } + DetalheExtrato detalheExtrato = (DetalheExtrato)item; + if (detalheExtrato != null) + { + await this.ViewModel.Criticar(detalheExtrato, false); + this.LimparFiltros(); + } + } + else + { + await this.ViewModel.ShowMessage("PARA DESCONSIDERAR O DOCUMENTO É NECESSÁRIO SELECIONAR UMA PARCELA", "OK", "", false); + } + } + + private async void DesconsiderarSelacionadas_Click(object sender, RoutedEventArgs e) + { + if (await this.ViewModel.ShowMessage(string.Concat("ESSA OPÇÃO DESCONSIDERA TODAS AS PARCELAS QUE FORAM SELECIONADAS, COLOCANDO STATUS DE DESCONSIDERADA PELO USUÁRIO", Environment.NewLine, "DESEJA CONTINUAR?"), "SIM", "NÃO", false)) + { + await this.ViewModel.DesconsiderarSelecionadas(); + } + } + + private async void DesconsiderarTodas_Click(object sender, RoutedEventArgs e) + { + if (await this.ViewModel.ShowMessage(string.Concat("ESSA OPÇÃO DESCONSIDERA TODAS AS PARCELAS COM O STATUS DE DOCUMENTO NÃO ENCONTRADO OU PARCELA NÃO ENCONTRADA DO EXTRATO.", Environment.NewLine, "DESEJA CONTINUAR?"), "SIM", "NÃO", false)) + { + await this.ViewModel.CriticarTodos(this.ViewModel.SelectedExtrato.get_Id()); + this.LimparFiltros(); + } + } + + private async void DesfazerExtrato_OnClick(object sender, RoutedEventArgs e) + { + if (this.ViewModel.SelectedExtrato != null) + { + if (await this.ViewModel.ShowMessage(string.Concat("DESEJA DESFAZER A BAIXA DO EXTRATO ", this.ViewModel.SelectedExtrato.get_Numero(), "?"), "SIM", "NÃO", false)) + { + this.ViewModel.IsVisible = System.Windows.Visibility.Collapsed; + this.ViewModel.IsVisibleDetalhes = System.Windows.Visibility.Collapsed; + this.ProgressBar.Visibility = System.Windows.Visibility.Visible; + this.ViewModel.EnableButtons = false; + Action enableMainMenu = Gestor.Application.Actions.Actions.EnableMainMenu; + if (enableMainMenu != null) + { + enableMainMenu(false); + } + else + { + } + Action enableMenu = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu != null) + { + enableMenu(false); + } + else + { + } + await this.ViewModel.DesfazerExtrato(); + this.ViewModel.EnableButtons = true; + this.ProgressBar.Visibility = System.Windows.Visibility.Collapsed; + Action action = Gestor.Application.Actions.Actions.EnableMainMenu; + if (action != null) + { + action(true); + } + else + { + } + Action enableMenu1 = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu1 != null) + { + enableMenu1(true); + } + else + { + } + this.ViewModel.IsVisibleDetalhes = System.Windows.Visibility.Visible; + this.ViewModel.IsVisible = System.Windows.Visibility.Visible; + } + } + } + + private async void DesfazerParcela_OnClick(object sender, RoutedEventArgs e) + { + object item; + DataGrid detalhesGrid = this.DetalhesGrid; + if (detalhesGrid != null) + { + item = detalhesGrid.Items[this.DetalhesGrid.SelectedIndex]; + } + else + { + item = null; + } + DetalheExtrato detalheExtrato = (DetalheExtrato)item; + if (detalheExtrato != null) + { + if (await this.ViewModel.ShowMessage(string.Concat("DESEJA DESFAZER A BAIXA DA PARCELA DO CLIENTE ", detalheExtrato.get_Cliente(), "?"), "SIM", "NÃO", false)) + { + this.ViewModel.Loading(true); + this.ViewModel.IsVisibleDetalhes = System.Windows.Visibility.Collapsed; + Action enableMainMenu = Gestor.Application.Actions.Actions.EnableMainMenu; + if (enableMainMenu != null) + { + enableMainMenu(false); + } + else + { + } + Action enableMenu = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu != null) + { + enableMenu(false); + } + else + { + } + this.ViewModel.EnableButtons = false; + bool flag = await this.ViewModel.DesfazerParcela(detalheExtrato); + await this.ViewModel.CarregaDetalhes(this.ViewModel.SelectedExtrato); + ComissaoViewModel viewModel = this.ViewModel; + viewModel.ToggleSnackBar((flag ? "PARCELA DESFEITA COM SUCESSO" : "NÃO FOI POSSÍVEL DESFAZER A BAIXA DA PARCELA"), true); + if (flag && detalheExtrato.get_Parcela().HasValue) + { + ComissaoViewModel comissaoViewModel = this.ViewModel; + string str = string.Format("DESFEZ PARCELA DE ID \"{0}\"", detalheExtrato.get_Parcela()); + long? parcela = detalheExtrato.get_Parcela(); + comissaoViewModel.RegistrarAcao(str, parcela.Value, new TipoTela?(35), null); + } + Action action = Gestor.Application.Actions.Actions.EnableMainMenu; + if (action != null) + { + action(true); + } + else + { + } + Action enableMenu1 = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu1 != null) + { + enableMenu1(true); + } + else + { + } + this.ViewModel.EnableButtons = true; + this.ViewModel.IsVisibleDetalhes = System.Windows.Visibility.Visible; + this.ViewModel.Loading(false); + } + } + detalheExtrato = null; + } + + private async void DetalhesGrid_OnMouseDoubleClick(object sender, MouseButtonEventArgs e) + { + object obj; + DataGrid dataGrid = (DataGrid)sender; + if (dataGrid == null || dataGrid.SelectedIndex >= 0) + { + this.ViewModel.Loading(true); + this.ViewModel.IsVisibleDetalhes = System.Windows.Visibility.Collapsed; + obj = (dataGrid != null ? dataGrid.Items[dataGrid.SelectedIndex] : null); + DetalheExtrato detalheExtrato = (DetalheExtrato)obj; + if (detalheExtrato != null) + { + await this.AbrirCritica(detalheExtrato); + this.ViewModel.IsVisibleDetalhes = System.Windows.Visibility.Visible; + this.ViewModel.Loading(false); + } + } + } + + private async void ExcluirExtrato_OnClick(object sender, RoutedEventArgs e) + { + if (this.ViewModel.SelectedExtrato != null) + { + if (await this.ViewModel.ShowMessage(string.Concat("DESEJA EXCLUIR O EXTRATO ", this.ViewModel.SelectedExtrato.get_Numero(), "?"), "SIM", "NÃO", false)) + { + this.ViewModel.IsVisible = System.Windows.Visibility.Collapsed; + this.ViewModel.IsVisibleDetalhes = System.Windows.Visibility.Collapsed; + this.ProgressBar.Visibility = System.Windows.Visibility.Visible; + this.ViewModel.EnableButtons = false; + Action enableMainMenu = Gestor.Application.Actions.Actions.EnableMainMenu; + if (enableMainMenu != null) + { + enableMainMenu(false); + } + else + { + } + Action enableMenu = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu != null) + { + enableMenu(false); + } + else + { + } + await this.ViewModel.ExcluirExtrato(); + Action action = Gestor.Application.Actions.Actions.EnableMainMenu; + if (action != null) + { + action(true); + } + else + { + } + Action enableMenu1 = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu1 != null) + { + enableMenu1(true); + } + else + { + } + this.ViewModel.EnableButtons = true; + this.ProgressBar.Visibility = System.Windows.Visibility.Collapsed; + this.ViewModel.IsVisibleDetalhes = System.Windows.Visibility.Visible; + this.ViewModel.IsVisible = System.Windows.Visibility.Visible; + } + } + } + + private void ExcluirFiltro_onClick(object sender, RoutedEventArgs e) + { + Chip chip = sender as Chip; + if (chip == null) + { + return; + } + ListBox listBox = Extentions.FindVisualAncestor(chip); + string item = (string)listBox.Items[listBox.Items.IndexOf(chip.DataContext)]; + if (item == null) + { + return; + } + this.ViewModel.ExcluirFiltro(item); + } + + private void FiltroDataBox_OnSelectedDateChanged(object sender, SelectionChangedEventArgs e) + { + bool hasValue; + DatePicker datePicker = (DatePicker)sender; + if (datePicker != null) + { + hasValue = !datePicker.SelectedDate.HasValue; + } + else + { + hasValue = true; + } + if (hasValue) + { + return; + } + this.ViewModel.SelecionaSeguradora(this.ViewModel.SelectedSeguradora, this.ViewModel.SelectedStatusExtrato, null); + } + + private async void FinalizarSelecionado_OnClick(object sender, RoutedEventArgs e) + { + ((MenuItem)sender).Click -= new RoutedEventHandler(this.FinalizarSelecionado_OnClick); + if (this.ViewModel.SelectedExtrato != null) + { + ComissaoViewModel viewModel = this.ViewModel; + string[] numero = new string[] { "DESEJA FINALIZAR O EXTRATO ", this.ViewModel.SelectedExtrato.get_Numero(), "?", Environment.NewLine, "O EXTRATO SERÁ MARCADO COMO BAIXADO." }; + if (await viewModel.ShowMessage(string.Concat(numero), "SIM", "NÃO", false)) + { + this.ViewModel.IsVisible = System.Windows.Visibility.Collapsed; + this.ViewModel.IsVisibleDetalhes = System.Windows.Visibility.Collapsed; + this.ProgressBar.Visibility = System.Windows.Visibility.Visible; + Action enableMainMenu = Gestor.Application.Actions.Actions.EnableMainMenu; + if (enableMainMenu != null) + { + enableMainMenu(false); + } + else + { + } + Action enableMenu = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu != null) + { + enableMenu(false); + } + else + { + } + this.ViewModel.EnableButtons = false; + await this.ViewModel.FinalizarExtrato(); + this.ViewModel.EnableButtons = true; + Action action = Gestor.Application.Actions.Actions.EnableMainMenu; + if (action != null) + { + action(true); + } + else + { + } + Action enableMenu1 = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu1 != null) + { + enableMenu1(true); + } + else + { + } + this.ProgressBar.Visibility = System.Windows.Visibility.Collapsed; + this.ViewModel.IsVisibleDetalhes = System.Windows.Visibility.Visible; + this.ViewModel.IsVisible = System.Windows.Visibility.Visible; + ((MenuItem)sender).Click += new RoutedEventHandler(this.FinalizarSelecionado_OnClick); + } + else + { + ((MenuItem)sender).Click += new RoutedEventHandler(this.FinalizarSelecionado_OnClick); + } + } + else + { + ((MenuItem)sender).Click += new RoutedEventHandler(this.FinalizarSelecionado_OnClick); + } + } + + private async void Grid_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + DataGrid dataGrid = (DataGrid)sender; + if (dataGrid != null) + { + if (dataGrid.SelectedIndex >= 0) + { + await this.ViewModel.SelecionaExtrato((Extrato)dataGrid.Items[dataGrid.SelectedIndex]); + } + } + } + + private async void Imprimir_OnClick(object sender, RoutedEventArgs e) + { + if (this.ViewModel.SelectedExtrato != null) + { + string str = await this.ViewModel.GerarHtml(); + if (!string.IsNullOrEmpty(str)) + { + string tempPath = Path.GetTempPath(); + string str1 = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.html", tempPath, (new Regex(string.Concat("[", Regex.Escape(string.Concat(new string(Path.GetInvalidFileNameChars()), new string(Path.GetInvalidPathChars()))), "]"))).Replace("EXTRATO COMISSÃO", ""), Funcoes.GetNetworkTime()); + StreamWriter streamWriter = new StreamWriter(str1, true, Encoding.UTF8); + streamWriter.Write(str); + streamWriter.Close(); + Process.Start(str1); + this.ViewModel.RegistrarAcao(string.Format("IMPRIMIU EXTRATO DE ID \"{0}\"", this.ViewModel.SelectedExtrato.get_Id()), this.ViewModel.SelectedExtrato.get_Id(), new TipoTela?(35), null); + } + } + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/seguros/comissaoview.xaml", UriKind.Relative)); + } + + private void LimparFiltros() + { + this.ViewModel.Criticando = false; + this.ViewModel.FiltrarDetalheExtrato(""); + this.PainelCritica.Visibility = System.Windows.Visibility.Collapsed; + this.FiltroDetalhes.Visibility = System.Windows.Visibility.Visible; + this.AutoCompleteCliente.set_Text(string.Empty); + this.DetalhesGrid.Visibility = System.Windows.Visibility.Visible; + Action enableMainMenu = Gestor.Application.Actions.Actions.EnableMainMenu; + if (enableMainMenu != null) + { + enableMainMenu(true); + } + else + { + } + Action enableMenu = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu == null) + { + return; + } + enableMenu(true); + } + + private void Subtipo_OnDropDownOpened(object sender, EventArgs e) + { + this._previousSubTipo = (SubTipo)((ComboBox)sender).SelectedItem; + } + + private void Subtipo_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + if (!this.ViewModel.IsEnabled) + { + return; + } + ComboBox comboBox = (ComboBox)sender; + if ((SubTipo)comboBox.SelectedItem != 1) + { + return; + } + DetalheExtrato dataContext = (DetalheExtrato)comboBox.DataContext; + if ((SubTipo)comboBox.SelectedItem == 1 && dataContext.get_NumeroParcela() == "999" || !dataContext.IsNormal && dataContext.get_SubTipo().GetValueOrDefault() == 1) + { + comboBox.SelectedItem = this._previousSubTipo; + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.UsuarioBox = (ComboBox)target; + return; + } + case 2: + { + this.StatusBox = (ComboBox)target; + return; + } + case 3: + { + this.SeguradoraBox = (ComboBox)target; + return; + } + case 4: + { + this.Seguradora2Box = (ComboBox)target; + return; + } + case 5: + { + this.InicioBox = (DatePicker)target; + this.InicioBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + return; + } + case 6: + { + this.FimBox = (DatePicker)target; + this.FimBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + return; + } + case 7: + { + ((Button)target).Click += new RoutedEventHandler(this.Atualizar_OnClick); + return; + } + case 8: + { + ((Button)target).Click += new RoutedEventHandler(this.AdicionarFiltro_OnClick); + return; + } + case 9: + case 29: + case 30: + case 31: + case 32: + case 33: + case 40: + case 41: + { + this._contentLoaded = true; + return; + } + case 10: + { + this.ExtratoGrid = (DataGrid)target; + return; + } + case 11: + { + this.ProgressBar2 = (Card)target; + return; + } + case 12: + { + this.ProgressBar = (Card)target; + return; + } + case 13: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AtualizarExtrato_OnClick); + return; + } + case 14: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.FinalizarSelecionado_OnClick); + return; + } + case 15: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.BaixarParcelasSelecionadas_OnClick); + return; + } + case 16: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.BaixarSelecionado_OnClick); + return; + } + case 17: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.DesconsiderarTodas_Click); + return; + } + case 18: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.DesconsiderarSelacionadas_Click); + return; + } + case 19: + { + this.DesfazerExtratoButton = (MenuItem)target; + this.DesfazerExtratoButton.Click += new RoutedEventHandler(this.DesfazerExtrato_OnClick); + return; + } + case 20: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.ExcluirExtrato_OnClick); + return; + } + case 21: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.CriticarDocumento_OnClick); + return; + } + case 22: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Desconsiderar_OnClick); + return; + } + case 23: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.CancelarCritica_OnClick); + return; + } + case 24: + { + this.DataBaixaBox = (DatePicker)target; + this.DataBaixaBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + return; + } + case 25: + { + this.FiltroDetalhes = (TextBox)target; + this.FiltroDetalhes.TextChanged += new TextChangedEventHandler(this.AutoCompleteBoxDetalhe_OnTextChanged); + return; + } + case 26: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Imprimir_OnClick); + return; + } + case 27: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirAquivoDigital_Click); + return; + } + case 28: + { + this.DetalhesGrid = (DataGrid)target; + return; + } + case 34: + { + this.PainelCritica = (Grid)target; + return; + } + case 35: + { + this.AutoCompleteCliente = (AutoCompleteBox)target; + this.AutoCompleteCliente.add_Populating(new PopulatingEventHandler(this, ComissaoView.AutoCompleteBox_Populating)); + return; + } + case 36: + { + this.TipoDocumentoPrincipalBox = (TextBox)target; + return; + } + case 37: + { + this.DocumentoPrincipalBox = (TextBox)target; + return; + } + case 38: + { + this.FiltroApoliceBox = (TextBox)target; + this.FiltroApoliceBox.TextChanged += new TextChangedEventHandler(this.AutoCompleteBoxDocumento_OnTextChanged); + return; + } + case 39: + { + this.ApoliceGrid = (DataGrid)target; + return; + } + case 42: + { + this.ParcelaGrid = (DataGrid)target; + return; + } + case 43: + { + this.ParcelaColumn = (DataGridTextColumn)target; + return; + } + case 44: + { + this.FaturaGrid = (DataGrid)target; + return; + } + default: + { + this._contentLoaded = true; + return; + } + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + if (connectionId == 9) + { + ((Chip)target).add_DeleteClick(new RoutedEventHandler(this.ExcluirFiltro_onClick)); + return; + } + switch (connectionId) + { + case 29: + { + ((Button)target).Click += new RoutedEventHandler(this.AcessarApolice_OnClick); + return; + } + case 30: + { + ((ComboBox)target).DropDownOpened += new EventHandler(this.Subtipo_OnDropDownOpened); + ((ComboBox)target).SelectionChanged += new SelectionChangedEventHandler(this.Subtipo_OnSelectionChanged); + return; + } + case 31: + { + ((Button)target).Click += new RoutedEventHandler(this.AbrirCritica_OnClick); + return; + } + case 32: + { + ((Button)target).Click += new RoutedEventHandler(this.Desconsiderar_OnClick); + return; + } + case 33: + { + ((Button)target).Click += new RoutedEventHandler(this.DesfazerParcela_OnClick); + return; + } + case 34: + case 35: + case 36: + case 37: + case 38: + case 39: + { + return; + } + case 40: + { + ((Button)target).Click += new RoutedEventHandler(this.AcessarApoliceCritica_OnClick); + return; + } + case 41: + { + ((Button)target).Click += new RoutedEventHandler(this.ArquivoDigitalButton_OnClick); + return; + } + default: + { + return; + } + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Seguros/ConsultaOriginalView.cs b/Codemerx/Gestor.Application/Views/Seguros/ConsultaOriginalView.cs new file mode 100644 index 0000000..0e5096d --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Seguros/ConsultaOriginalView.cs @@ -0,0 +1,1502 @@ +using Gestor.Application.Actions; +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Application.Views.Ferramentas; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.MalaDireta; +using Gestor.Model.Domain.Relatorios.ClientesAtivosInativos; +using Gestor.Model.Domain.Seguros; +using MaterialDesignThemes.Wpf; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Media; +using System.Windows.Threading; + +namespace Gestor.Application.Views.Seguros +{ + public class ConsultaOriginalView : BaseUserControl, IComponentConnector, IStyleConnector + { + public ConsultaViewModel ViewModel; + + private bool _carregarDocumetos = true; + + internal RadioButton ApoliceRadioButton; + + internal RadioButton EndossoRadioButton; + + internal MenuItem AcessarDocumentoMenuItem; + + internal DataGrid ApoliceGrid; + + internal DataGridTextColumn NomeField; + + internal DataGridTextColumn ApelidoField; + + internal DataGridTextColumn ApolicesComissaoColumn; + + internal DataGrid EndossoGrid; + + internal DataGridTextColumn EndossosComissaoColumn; + + internal WrapPanel Comissao; + + internal DataGrid ParcelaGrid; + + internal DataGridTextColumn ParcelasTotalColumn; + + internal DataGridTextColumn ParcelasRealizadoColumn; + + internal DataGridTextColumn ParcelasComissaoColumn; + + internal DataGridTextColumn ParcelasReciboColumn; + + internal DataGridTextColumn ParcelasValorComissaoDescColumn; + + internal DataGridTemplateColumn MaisInformacoesColumn; + + internal RadioButton AtivosRadioButton; + + internal RadioButton ApoliceItensRadioButton; + + internal RadioButton EndossoItensRadioButton; + + internal RadioButton InativosRadioButton; + + internal DataGrid ItemGrid; + + private bool _contentLoaded; + + private Documento _documentoAssistencia + { + get; + set; + } + + private string _linkAssistencia + { + get; + set; + } + + public ConsultaOriginalView(ConsultaViewModel viewModel) + { + base.Tag = "CONSULTA DE DOCUMENTOS"; + this.ViewModel = viewModel ?? new ConsultaViewModel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + Gestor.Application.Actions.Actions.UpdateRadioApolice = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.UpdateRadioApolice, new Action(this.SelecionarRadios)); + Gestor.Application.Actions.Actions.ScrollDocumento = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.ScrollDocumento, new Action(this.ScrollDocumento)); + Gestor.Application.Actions.Actions.ScrollToItem = new Action(this.ScrollToItem); + Gestor.Application.Actions.Actions.ScrollToItem = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.ScrollToItem, new Action(this.ScrollToItem)); + this.ItemGrid.DataContext = this.ViewModel; + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + + private async void AbrirAquivoDigital_Click(object sender, RoutedEventArgs e) + { + FiltroArquivoDigital filtroArquivoDigital = null; + ConsultaViewModel.DocumentoSelecionado.get_Controle().set_Cliente(this.ViewModel.SelectedCliente); + string name = ((Button)sender).Name; + if (name == "Apolice") + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 2).get_Consultar()) + { + this.ViewModel.SelectedControle.get_Controle().set_Cliente(this.ViewModel.SelectedCliente); + FiltroArquivoDigital filtroArquivoDigital1 = new FiltroArquivoDigital(); + filtroArquivoDigital1.set_Id(this.ViewModel.SelectedControle.get_Id()); + filtroArquivoDigital1.set_Tipo(2); + filtroArquivoDigital1.set_Parente(this.ViewModel.SelectedControle); + filtroArquivoDigital = filtroArquivoDigital1; + } + else + { + await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", ValidationHelper.GetDescription((TipoArquivoDigital)2), "."), "OK", "", false); + return; + } + } + else if (name == "Endosso") + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 2).get_Consultar()) + { + this.ViewModel.SelectedEndosso.get_Controle().set_Cliente(this.ViewModel.SelectedCliente); + FiltroArquivoDigital filtroArquivoDigital2 = new FiltroArquivoDigital(); + filtroArquivoDigital2.set_Id(this.ViewModel.SelectedEndosso.get_Id()); + filtroArquivoDigital2.set_Tipo(2); + filtroArquivoDigital2.set_Parente(this.ViewModel.SelectedEndosso); + filtroArquivoDigital = filtroArquivoDigital2; + } + else + { + await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", ValidationHelper.GetDescription((TipoArquivoDigital)2), "."), "OK", "", false); + return; + } + } + else if (name != "Parcela") + { + if (name == "Item") + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 4).get_Consultar()) + { + this.ViewModel.SelectedItem.set_Documento(ConsultaViewModel.DocumentoSelecionado); + FiltroArquivoDigital filtroArquivoDigital3 = new FiltroArquivoDigital(); + filtroArquivoDigital3.set_Id(this.ViewModel.SelectedItem.get_Id()); + filtroArquivoDigital3.set_IdApolice(this.ViewModel.SelectedItem.get_Documento().get_Id()); + filtroArquivoDigital3.set_Tipo(4); + filtroArquivoDigital3.set_Parente(this.ViewModel.SelectedItem); + filtroArquivoDigital = filtroArquivoDigital3; + } + else + { + await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", ValidationHelper.GetDescription((TipoArquivoDigital)4), "."), "OK", "", false); + return; + } + } + } + else if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 3).get_Consultar()) + { + this.ViewModel.SelectedParcela.set_Documento(ConsultaViewModel.DocumentoSelecionado); + FiltroArquivoDigital filtroArquivoDigital4 = new FiltroArquivoDigital(); + filtroArquivoDigital4.set_Id(this.ViewModel.SelectedParcela.get_Id()); + filtroArquivoDigital4.set_IdApolice(this.ViewModel.SelectedParcela.get_Documento().get_Id()); + filtroArquivoDigital4.set_Tipo(3); + filtroArquivoDigital4.set_Parente(this.ViewModel.SelectedParcela); + filtroArquivoDigital = filtroArquivoDigital4; + } + else + { + await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", ValidationHelper.GetDescription((TipoArquivoDigital)3), "."), "OK", "", false); + return; + } + this.ViewModel.ShowDrawer(new ArquivoDigitalDrawer(filtroArquivoDigital), 0, false); + } + + private async Task AbrirProspeccao(Prospeccao data) + { + do + { + Label1: + if (await this.ViewModel.ShowProspeccaoDialog(data) != null) + { + List> keyValuePairs = await this.ViewModel.SalvarProspeccao(data); + if (keyValuePairs == null || keyValuePairs.Count == 0) + { + this.ViewModel.ToggleSnackBar("PROSPECÇÃO SALVA COM SUCESSO.", true); + return; + } + else + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + goto Label1; + } + } + else + { + } + } + while (!await this.ViewModel.ShowMessage("DESEJA REALMENTE NÃO CADASTRAR UMA PROSPECÇÃO PARA ESSE DOCUMENTO?", "SIM", "NÃO", false)); + } + + private void AjustaItem() + { + this.AtivosRadioButton.IsChecked = new bool?(this.ViewModel.FilterItens == 0); + this.ApoliceItensRadioButton.IsChecked = new bool?(this.ViewModel.FilterItens == 1); + this.EndossoItensRadioButton.IsChecked = new bool?(this.ViewModel.FilterItens == 2); + this.InativosRadioButton.IsChecked = new bool?(this.ViewModel.FilterItens == 3); + } + + private async void ApoliceGrid_OnMouseDoubleClick(object sender, MouseButtonEventArgs e) + { + object obj; + long? nullable; + object obj1; + DataGridRow dataGridRow = (DataGridRow)sender; + if (dataGridRow != null) + { + if (dataGridRow.DataContext.GetType() == typeof(Documento)) + { + this.AtivosRadioButton.IsChecked = new bool?(true); + obj = (dataGridRow != null ? dataGridRow.Item : null); + Documento documento = (Documento)obj; + if (documento != null) + { + nullable = new long?(documento.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long id = this.ViewModel.SelectedControle.get_Id(); + if (nullable1.GetValueOrDefault() != id | !nullable1.HasValue) + { + ConsultaViewModel viewModel = this.ViewModel; + obj1 = (dataGridRow != null ? dataGridRow.Item : null); + await viewModel.SelecionaDocumento(0, (Documento)obj1); + } + Action acessaTela = Gestor.Application.Actions.Actions.AcessaTela; + if (acessaTela != null) + { + acessaTela(2, ""); + } + else + { + } + } + } + } + + private async void ApoliceGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + object obj; + DataGrid dataGrid = (DataGrid)sender; + if (dataGrid == null || dataGrid.SelectedIndex >= 0) + { + ConsultaViewModel viewModel = this.ViewModel; + obj = (dataGrid != null ? dataGrid.Items[dataGrid.SelectedIndex] : null); + await viewModel.SelecionaDocumento(0, (Documento)obj); + this.VisibilityValorPago(); + } + } + + private void ApoliceView_Click(object sender, RoutedEventArgs e) + { + Action acessaTela = Gestor.Application.Actions.Actions.AcessaTela; + if (acessaTela == null) + { + return; + } + acessaTela(2, ""); + } + + private void ClienteView_Click(object sender, RoutedEventArgs e) + { + Action acessaTela = Gestor.Application.Actions.Actions.AcessaTela; + if (acessaTela == null) + { + return; + } + acessaTela(1, ""); + } + + private void ContentLoad() + { + if (ConsultaViewModel.DocumentoSelecionado != null && ConsultaViewModel.DocumentoSelecionado.get_Tipo() != 0) + { + this.ViewModel.FilterDocumento = 1; + } + this.NomeField.Visibility = (this.ViewModel.Apelido ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible); + this.ApelidoField.Visibility = (!this.ViewModel.Apelido ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible); + this.ApoliceRadioButton.IsChecked = new bool?(this.ViewModel.FilterDocumento == 0); + this.EndossoRadioButton.IsChecked = new bool?(this.ViewModel.FilterDocumento == 1); + this.AjustaItem(); + this.ApoliceGrid.SelectionChanged += new SelectionChangedEventHandler(this.ApoliceGrid_OnSelectionChanged); + this.ParcelaGrid.MouseDoubleClick += new MouseButtonEventHandler(ConsultaOriginalView.ParcelaGrid_OnMouseDoubleClick); + this.EndossoGrid.SelectionChanged += new SelectionChangedEventHandler(this.EndossoGrid_OnSelectionChanged); + this.EndossoGrid.MouseDoubleClick += new MouseButtonEventHandler(this.EndossoGrid_OnMouseDoubleClick); + this.AtivosRadioButton.Checked += new RoutedEventHandler(this.Documento_OnChecked); + this.ApoliceItensRadioButton.Checked += new RoutedEventHandler(this.Documento_OnChecked); + this.EndossoItensRadioButton.Checked += new RoutedEventHandler(this.Documento_OnChecked); + this.InativosRadioButton.Checked += new RoutedEventHandler(this.Documento_OnChecked); + this.ApoliceRadioButton.Checked += new RoutedEventHandler(this.Documento_OnChecked); + this.EndossoRadioButton.Checked += new RoutedEventHandler(this.Documento_OnChecked); + this.ItemGrid.SelectionChanged += new SelectionChangedEventHandler(this.ItemGrid_OnSelectionChanged); + this.ItemGrid.MouseDoubleClick += new MouseButtonEventHandler(this.ItemGrid_OnMouseDoubleClick); + System.Windows.Visibility visibility = (this.ViewModel.Restricao(14) ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible); + this.ViewModel.ComissaoValorVisibility = (this.ViewModel.Restricao(14) ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible); + bool flag = this.ViewModel.Restricao(95); + this.ApolicesComissaoColumn.Visibility = (flag ? System.Windows.Visibility.Visible : visibility); + this.EndossosComissaoColumn.Visibility = (flag ? System.Windows.Visibility.Visible : visibility); + this.Comissao.Visibility = visibility; + bool flag1 = Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 5); + this.ParcelasRealizadoColumn.Visibility = visibility; + this.ParcelasComissaoColumn.Visibility = (flag ? System.Windows.Visibility.Visible : visibility); + this.ParcelasReciboColumn.Visibility = (flag1 ? System.Windows.Visibility.Collapsed : visibility); + this.ParcelasValorComissaoDescColumn.Visibility = (flag1 ? visibility : System.Windows.Visibility.Collapsed); + this.MaisInformacoesColumn.Visibility = visibility; + } + + private async void Documento_OnChecked(object sender, RoutedEventArgs e) + { + object obj; + object obj1; + MenuItem acessarDocumentoMenuItem = this.AcessarDocumentoMenuItem; + obj = (this.ViewModel.FilterDocumento == 0 ? "ACESSAR APÓLICE" : "ACESSAR ENDOSSO"); + acessarDocumentoMenuItem.Header = obj; + MenuItem menuItem = this.AcessarDocumentoMenuItem; + obj1 = (this.ViewModel.FilterDocumento == 0 ? "CLIQUE PARA ACESSAR A TELA DA APÓLICE" : "CLIQUE PARA ACESSAR A TELA DE ENDOSSO"); + menuItem.ToolTip = obj1; + RadioButton radioButton = (RadioButton)sender; + if (!string.IsNullOrEmpty(radioButton.GroupName)) + { + string groupName = radioButton.GroupName; + if (groupName != "Apolices") + { + if (groupName == "Itens") + { + string name = radioButton.Name; + if (name == "ApoliceItensRadioButton") + { + await this.ViewModel.SelecionaItens(1, null, (long)0, false); + } + else if (name == "EndossoItensRadioButton") + { + await this.ViewModel.SelecionaItens(2, null, (long)0, false); + } + else if (name == "InativosRadioButton") + { + await this.ViewModel.SelecionaItens(3, null, (long)0, false); + } + else + { + await this.ViewModel.SelecionaItens(0, null, (long)0, false); + } + } + } + else if (!this._carregarDocumetos) + { + return; + } + else if (radioButton.Name == "EndossoRadioButton") + { + this.AcessarDocumentoMenuItem.Header = "ACESSAR ENDOSSO"; + this.AcessarDocumentoMenuItem.ToolTip = "CLIQUE PARA ACESSAR A TELA DE ENDOSSO"; + this.ViewModel.CarregaDocumentos(1); + if (this.EndossoGrid.SelectedItem == null && this.EndossoGrid.Items.Count > 0) + { + this.EndossoGrid.SelectedItem = this.EndossoGrid.Items[0]; + } + if (this.EndossoGrid.SelectedItem != null) + { + await this.ViewModel.SelecionaDocumento(1, (Documento)this.EndossoGrid.SelectedItem); + } + } + else + { + this.AcessarDocumentoMenuItem.Header = "ACESSAR APÓLICE"; + this.AcessarDocumentoMenuItem.ToolTip = "CLIQUE PARA ACESSAR A TELA DA APÓLICE"; + this.ViewModel.CarregaDocumentos(0); + if (this.ApoliceGrid.SelectedItem == null && this.ApoliceGrid.Items.Count > 0) + { + this.ApoliceGrid.SelectedItem = this.ApoliceGrid.Items[0]; + } + if (this.ApoliceGrid.SelectedItem != null) + { + await this.ViewModel.SelecionaDocumento(0, (Documento)this.ApoliceGrid.SelectedItem); + } + } + } + } + + private async void EditarParcelas_OnClick(object sender, RoutedEventArgs e) + { + await this.ViewModel.EditarParcelas(); + } + + private async void Endossar_OnClick(object sender, RoutedEventArgs e) + { + if (this.ViewModel.Restricao(33)) + { + await this.ViewModel.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA ENDOSSAR. PROCURE O ADMINSTRADOR DO SISTEMA.", "OK", "", false); + } + else if (!this.ViewModel.EnableEndossar) + { + List> keyValuePairs = this.ViewModel.SelectedControle.ValidateEndossar(); + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + else if (ConsultaViewModel.DocumentoSelecionado.get_Situacao() != 7) + { + Action acessaTela = Gestor.Application.Actions.Actions.AcessaTela; + if (acessaTela != null) + { + acessaTela(2, "Endossar"); + } + else + { + } + } + else + { + await this.ViewModel.ShowMessage("NÃO É POSSÍVEL ENDOSSAR UM DOCUMENTO RECUSADO.", "OK", "", false); + } + } + + private async void EndossoGrid_OnMouseDoubleClick(object sender, MouseButtonEventArgs e) + { + object obj; + DataGrid dataGrid = (DataGrid)sender; + if (dataGrid == null || dataGrid.SelectedIndex >= 0) + { + this.AtivosRadioButton.IsChecked = new bool?(true); + ConsultaViewModel viewModel = this.ViewModel; + obj = (dataGrid != null ? dataGrid.Items[dataGrid.SelectedIndex] : null); + await viewModel.SelecionaDocumento(1, (Documento)obj); + Action acessaTela = Gestor.Application.Actions.Actions.AcessaTela; + if (acessaTela != null) + { + acessaTela(2, ""); + } + else + { + } + } + } + + private async void EndossoGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + object obj; + DataGrid dataGrid = (DataGrid)sender; + if (dataGrid == null || dataGrid.SelectedIndex >= 0) + { + ConsultaViewModel viewModel = this.ViewModel; + obj = (dataGrid != null ? dataGrid.Items[dataGrid.SelectedIndex] : null); + await viewModel.SelecionaDocumento(1, (Documento)obj); + this.VisibilityValorPago(); + } + } + + private void EnviarPorEmail_OnClick(object sender, RoutedEventArgs e) + { + if (this._documentoAssistencia == null) + { + return; + } + MalaDireta malaDiretum = new MalaDireta(); + malaDiretum.set_Cliente(this.ViewModel.SelectedCliente); + malaDiretum.set_Apolice(this._documentoAssistencia); + MalaDireta malaDiretum1 = malaDiretum; + if (Funcoes.IsWindowOpen("ENVIO DE E-MAIL")) + { + Funcoes.Destroy("ENVIO DE E-MAIL"); + } + (new HosterWindow(new MalaDiretaView(new List() + { + malaDiretum1 + }, string.Concat("CARTÃO ASSISTÊNCIA 24 HORAS - ", malaDiretum1.get_Cliente().get_Nome(), " ", malaDiretum1.get_Apolice().get_Apolice()), string.Concat(new string[] { "

Prezado(a) ", ValidationHelper.Captalize(this.ViewModel.SelectedCliente.get_Nome()), ", segue o link do seu Cartão Assistência 24 horas.

LINK CARTÃO ASSITÊNCIA

" }), null), "ENVIO DE E-MAIL", new double?((double)1200), new double?((double)600), true)).ShowDialog(); + } + + private async void EnviarPorWhatsApp_OnClick(object sender, RoutedEventArgs e) + { + string str; + if (!this.ViewModel.Restricao(32)) + { + Button button = (Button)sender; + if (button.DataContext != null) + { + ClienteTelefone dataContext = button.DataContext as ClienteTelefone; + if (dataContext != null) + { + str = (!dataContext.get_Tipo().HasValue || dataContext.get_Tipo().GetValueOrDefault() != 8 ? string.Concat("55", dataContext.get_Prefixo(), dataContext.get_Numero().Clear()) : string.Concat(dataContext.get_Prefixo(), dataContext.get_Numero()).Clear()); + if (!str.EnviarWhatsapp(this.ViewModel.Anotacoes)) + { + await this.ViewModel.ShowMessage("HOUVE UM PROBLEMA AO ABRIR LINK DO WHATSAPP, O LINK FOI COPIADO EM SUA MAQUINA, BASTA ABRIR O NAVEGADOR DE INTERNET E COLAR NA BARRA DE ENDEREÇOS", "OK", "", false); + } + return; + } + } + } + else + { + await this.ViewModel.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR O WHATSAPP", "OK", "", false); + } + } + + private async void ExpedicaoInfo_OnClick(object sender, RoutedEventArgs e) + { + if (await this.ViewModel.VerificarPermissao(46, false)) + { + if (ConsultaViewModel.DocumentoSelecionado != null) + { + this.ViewModel.ShowDrawer(new ExpedicaoDrawer(ConsultaViewModel.DocumentoSelecionado), 0, false); + } + else + { + await this.ViewModel.ShowMessage("NECESSÁRIO SELECIONAR UM DOCUMENTO PARA EXIBIR AS INFORMAÇÕES DE EXPEDIÇÃO.", "OK", "", false); + } + } + } + + private async void Extratos_OnClick(object sender, RoutedEventArgs e) + { + Relatorio? nullable; + if (await this.ViewModel.VerificarRestricao(13, false, true) && this.ViewModel.SelectedCliente.get_Id() != 0) + { + this.ViewModel.Loading(true); + if (this.ViewModel.SelectedControle != null) + { + int filterDocumento = this.ViewModel.FilterDocumento; + if (filterDocumento != 0) + { + if (filterDocumento == 1) + { + if (this.ViewModel.SelectedEndosso != null) + { + ConsultaViewModel viewModel = this.ViewModel; + List documentos = new List() + { + this.ViewModel.SelectedEndosso + }; + nullable = null; + List nums = new List() + { + this.ViewModel.SelectedEndosso.get_Id() + }; + viewModel.ShowDrawer(new ExtratosDrawer(null, documentos, nullable, nums, null, null), 0, false); + } + } + } + else if (this.ViewModel.SelectedControle != null) + { + ConsultaViewModel consultaViewModel = this.ViewModel; + List documentos1 = new List() + { + this.ViewModel.SelectedControle + }; + nullable = null; + List nums1 = new List() + { + this.ViewModel.SelectedControle.get_Id() + }; + consultaViewModel.ShowDrawer(new ExtratosDrawer(null, documentos1, nullable, nums1, null, null), 0, false); + } + this.ViewModel.Loading(false); + } + else + { + ConsultaViewModel viewModel1 = this.ViewModel; + List clientesAtivosInativos = new List(); + ClientesAtivosInativos clientesAtivosInativo = new ClientesAtivosInativos(); + clientesAtivosInativo.set_Selecionado(true); + clientesAtivosInativo.set_EntidadeCliente(this.ViewModel.SelectedCliente); + clientesAtivosInativo.set_Id(this.ViewModel.SelectedCliente.get_Id()); + clientesAtivosInativo.set_Nome(this.ViewModel.SelectedCliente.get_Nome()); + clientesAtivosInativo.set_Documento(this.ViewModel.SelectedCliente.get_Documento()); + clientesAtivosInativos.Add(clientesAtivosInativo); + viewModel1.ShowDrawer(new ExtratosDrawer(clientesAtivosInativos, null, new Relatorio?(0), null, null, null), 0, false); + this.ViewModel.Loading(false); + } + } + } + + public Visual GetDescendantByType(Visual element, Type type) + { + if (element == null) + { + return null; + } + if (element.GetType() == type) + { + return element; + } + Visual descendantByType = null; + FrameworkElement frameworkElement = element as FrameworkElement; + if (frameworkElement != null) + { + frameworkElement.ApplyTemplate(); + } + for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++) + { + Visual child = VisualTreeHelper.GetChild(element, i) as Visual; + descendantByType = this.GetDescendantByType(child, type); + if (descendantByType != null) + { + break; + } + } + return descendantByType; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/seguros/consultaoriginalview.xaml", UriKind.Relative)); + } + + private void Item_Click(object sender, RoutedEventArgs e) + { + Action acessaTela = Gestor.Application.Actions.Actions.AcessaTela; + if (acessaTela == null) + { + return; + } + acessaTela(3, ""); + } + + private void ItemGrid_OnMouseDoubleClick(object sender, MouseButtonEventArgs e) + { + DataGrid dataGrid = (DataGrid)sender; + if (dataGrid != null && dataGrid.SelectedIndex < 0) + { + return; + } + this.ViewModel.SelecionaItem((Item)((dataGrid != null ? dataGrid.Items[dataGrid.SelectedIndex] : null))); + Action acessaTela = Gestor.Application.Actions.Actions.AcessaTela; + if (acessaTela == null) + { + return; + } + acessaTela(3, ""); + } + + private void ItemGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + DataGrid dataGrid = (DataGrid)sender; + if (dataGrid != null && dataGrid.SelectedIndex < 0) + { + return; + } + Item selectedItem = (Item)dataGrid.SelectedItem; + if (!selectedItem.get_Cancelado() && !selectedItem.get_Substituido().HasValue && selectedItem.get_Status() != null) + { + this.AjustaItem(); + } + this.ViewModel.SelecionaItem((Item)((dataGrid != null ? dataGrid.Items[dataGrid.SelectedIndex] : null))); + } + + private async void ManutecaoItens_OnClick(object sender, RoutedEventArgs e) + { + if ((this.ViewModel.FilterDocumento != 0 || this.ViewModel.SelectedControle.get_Situacao() != 7) && (this.ViewModel.FilterDocumento != 1 || this.ViewModel.SelectedEndosso.get_Situacao() != 7)) + { + this.ViewModel.ManutecaoItens(); + } + else + { + await this.ViewModel.ShowMessage("NÃO É POSSÍVEL FAZER A MANUTENÇÃO DE ITENS DE UM DOCUMENTO RECUSADO.", "OK", "", false); + } + } + + private void MenuItem_OnClick(object sender, RoutedEventArgs e) + { + Tarefa tarefa = new Tarefa(); + tarefa.set_IdCliente(this.ViewModel.SelectedCliente.get_Id()); + tarefa.set_Cliente(this.ViewModel.SelectedCliente.get_Nome()); + tarefa.set_Entidade(0); + tarefa.set_IdEntidade(this.ViewModel.SelectedControle.get_Id()); + tarefa.set_Titulo(string.Concat(this.ViewModel.SelectedCliente.get_Nome(), " APÓLICE ", this.ViewModel.SelectedControle.get_Apolice())); + this.ViewModel.ShowDrawer(new TarefaDrawer(tarefa, true), 0, false); + } + + private async void MostrarItens_Click(object sender, RoutedEventArgs e) + { + bool valueOrDefault; + bool flag; + int num = 0; + if (!this.ApoliceRadioButton.IsFocused) + { + RadioButton apoliceItensRadioButton = this.ApoliceItensRadioButton; + if (apoliceItensRadioButton != null) + { + flag = apoliceItensRadioButton.IsChecked.GetValueOrDefault(); + } + else + { + flag = false; + } + if (!flag) + { + goto Label0; + } + } + num = 1; + Label0: + if (!this.EndossoRadioButton.IsFocused) + { + RadioButton endossoItensRadioButton = this.EndossoItensRadioButton; + if (endossoItensRadioButton != null) + { + valueOrDefault = endossoItensRadioButton.IsChecked.GetValueOrDefault(); + } + else + { + valueOrDefault = false; + } + if (!valueOrDefault) + { + if (this.InativosRadioButton.IsFocused) + { + num = 3; + } + await this.ViewModel.MostrarItens(num); + return; + } + } + num = 2; + if (this.InativosRadioButton.IsFocused) + { + num = 3; + } + await this.ViewModel.MostrarItens(num); + } + + private void Observacoes_OnClick(object sender, RoutedEventArgs e) + { + long id = (long)0; + TipoTela tipoTela = 0; + string name = ((Button)sender).Name; + if (name == "ObservacaoApolice") + { + id = this.ViewModel.SelectedControle.get_Id(); + tipoTela = 2; + } + else if (name == "EndossoInfo") + { + id = this.ViewModel.SelectedEndosso.get_Id(); + tipoTela = 2; + } + else if (name == "ObservacaoParcela") + { + id = this.ViewModel.SelectedParcela.get_Id(); + tipoTela = 5; + } + this.ViewModel.ShowDrawer(new ObservacoesDrawer(id, tipoTela), 0, true); + } + + private void Parcela_Click(object sender, RoutedEventArgs e) + { + Action acessaTela = Gestor.Application.Actions.Actions.AcessaTela; + if (acessaTela == null) + { + return; + } + acessaTela(2, "Parcela"); + } + + private static void ParcelaGrid_OnMouseDoubleClick(object sender, MouseButtonEventArgs e) + { + DataGrid dataGrid = (DataGrid)sender; + if (dataGrid != null && dataGrid.SelectedIndex < 0) + { + return; + } + ConsultaViewModel.ParcelaSelecionada = (Parcela)((dataGrid != null ? dataGrid.Items[dataGrid.SelectedIndex] : null)); + Action acessaTela = Gestor.Application.Actions.Actions.AcessaTela; + if (acessaTela == null) + { + return; + } + acessaTela(2, "Parcela"); + } + + private async void Perdido_OnClick(object sender, RoutedEventArgs e) + { + object prefixo; + object numero; + string str; + string numero1; + object email; + DateTime dateTime; + string descricao; + object selectedItem; + bool count; + Cliente cliente; + if (ConsultaViewModel.DocumentoSelecionado.get_Situacao() == 7) + { + await this.ViewModel.ShowMessage("NÃO É POSSÍVEL ALTERAR O STATUS PARA PERDIDO DE UM DOCUMENTO RECUSADO.", "OK", "", false); + } + else if (await this.ViewModel.ShowMessage("DESEJA REALMENTE ALTERAR O STATUS DO SEGURO PARA PERDIDO?", "SIM", "NÃO", false)) + { + this.ViewModel.Loading(true); + cliente = await (new ClienteServico()).BuscarCliente(this.ViewModel.SelectedControle.get_Controle().get_Cliente().get_Id()); + Cliente cliente1 = cliente; + ObservableCollection observableCollection = await (new ClienteServico()).BuscarTelefonesAsync(this.ViewModel.SelectedControle.get_Controle().get_Cliente().get_Id()); + cliente1.set_Telefones(observableCollection); + cliente1 = null; + cliente1 = cliente; + ObservableCollection observableCollection1 = await (new ClienteServico()).BuscarEmailsAsync(this.ViewModel.SelectedControle.get_Controle().get_Cliente().get_Id()); + cliente1.set_Emails(observableCollection1); + cliente1 = null; + if (await (new ApoliceServico()).Perdido(this.ViewModel.SelectedControle.get_Controle().get_Id())) + { + Prospeccao prospeccao = new Prospeccao(); + prospeccao.set_Nome(cliente.get_Nome()); + prospeccao.set_Documento(cliente.get_Documento()); + prospeccao.set_Nascimento(cliente.get_Nascimento()); + ObservableCollection telefones = cliente.get_Telefones(); + if (telefones != null) + { + ClienteTelefone clienteTelefone = telefones.FirstOrDefault(); + if (clienteTelefone != null) + { + prefixo = clienteTelefone.get_Prefixo(); + } + else + { + prefixo = null; + } + } + else + { + prefixo = null; + } + if (prefixo == null) + { + prefixo = ""; + } + prospeccao.set_Prefixo1((string)prefixo); + ObservableCollection telefones1 = cliente.get_Telefones(); + if (telefones1 != null) + { + ClienteTelefone clienteTelefone1 = telefones1.FirstOrDefault(); + if (clienteTelefone1 != null) + { + numero = clienteTelefone1.get_Numero(); + } + else + { + numero = null; + } + } + else + { + numero = null; + } + if (numero == null) + { + numero = ""; + } + prospeccao.set_Telefone1((string)numero); + str = (cliente.get_Telefones() == null || cliente.get_Telefones().Count <= 1 ? "" : cliente.get_Telefones()[1].get_Prefixo()); + prospeccao.set_Prefixo2(str); + if (cliente.get_Telefones() != null) + { + ObservableCollection telefones2 = cliente.get_Telefones(); + if (telefones2 != null) + { + count = telefones2.Count > 1; + } + else + { + count = false; + } + if (!count) + { + goto Label1; + } + numero1 = cliente.get_Telefones()[1].get_Numero(); + goto Label0; + } + Label1: + numero1 = ""; + Label0: + prospeccao.set_Telefone2(numero1); + ObservableCollection emails = cliente.get_Emails(); + if (emails != null) + { + ClienteEmail clienteEmail = emails.FirstOrDefault(); + if (clienteEmail != null) + { + email = clienteEmail.get_Email(); + } + else + { + email = null; + } + } + else + { + email = null; + } + if (email == null) + { + email = ""; + } + prospeccao.set_Email((string)email); + DateTime? vigencia2 = this.ViewModel.SelectedControle.get_Vigencia2(); + dateTime = (vigencia2.HasValue ? vigencia2.GetValueOrDefault() : Funcoes.GetNetworkTime().Date); + prospeccao.set_VigenciaFinal(new DateTime?(dateTime.AddYears(1))); + prospeccao.set_Vendedor(this.ViewModel.SelectedControle.get_VendedorPrincipal()); + Item item = this.ViewModel.Itens.FirstOrDefault(); + if (item != null) + { + descricao = item.get_Descricao(); + } + else + { + descricao = null; + } + prospeccao.set_Item(descricao); + prospeccao.set_Tipo("SEGURO PERDIDO"); + prospeccao.set_Observacao(string.Concat("SEGURO PERDIDO: PROPOSTA: ", this.ViewModel.SelectedControle.get_Proposta(), ", APÓLICE: ", this.ViewModel.SelectedControle.get_Apolice())); + prospeccao.set_Status(new StatusProspeccao?(1)); + prospeccao.set_Renovacao(true); + await this.AbrirProspeccao(prospeccao); + this.ViewModel.CarregaDocumentos(0); + await this.ViewModel.SelecionaCliente(this.ViewModel.SelectedCliente, true); + this.ApoliceItensRadioButton.IsChecked = new bool?(true); + if (this.ApoliceGrid != null && this.ApoliceGrid.Items.Count > 0 && this.ApoliceGrid.SelectedItem == null) + { + this.ApoliceGrid.SelectedItem = this.ApoliceGrid.Items[0]; + ConsultaViewModel viewModel = this.ViewModel; + DataGrid apoliceGrid = this.ApoliceGrid; + if (apoliceGrid != null) + { + selectedItem = apoliceGrid.SelectedItem; + } + else + { + selectedItem = null; + } + await viewModel.SelecionaDocumento(0, (Documento)selectedItem); + } + this.ViewModel.Loading(false); + } + else + { + this.ViewModel.Loading(false); + } + } + cliente = null; + } + + public async void Pesquisar(PesquisaAvancada pesquisa) + { + await this.ViewModel.Pesquisar(pesquisa); + if (this.ViewModel.SelectedControle != null) + { + this.ScrollToIndex(this.ApoliceGrid, this.ApoliceGrid.SelectedIndex); + } + if (this.ViewModel.SelectedEndosso != null) + { + this.ScrollToIndex(this.EndossoGrid, this.EndossoGrid.SelectedIndex); + } + if (this.ViewModel.SelectedItem != null) + { + this.ScrollToIndex(this.ItemGrid, this.ItemGrid.SelectedIndex); + } + if (this.ViewModel.SelectedParcela != null) + { + this.ScrollToIndex(this.ParcelaGrid, this.ParcelaGrid.SelectedIndex); + } + } + + private void PopupBox_OnClosed(object sender, RoutedEventArgs e) + { + this._documentoAssistencia = null; + this.ViewModel.Anotacoes = ""; + this._linkAssistencia = ""; + } + + private async void PopupBox_OnOpened(object sender, RoutedEventArgs e) + { + this._documentoAssistencia = (Documento)((PopupBox)sender).DataContext; + this._linkAssistencia = await this.ViewModel.CreateLink(this._documentoAssistencia); + if (!string.IsNullOrEmpty(this._linkAssistencia)) + { + string[] strArrays = new string[] { "Prezado(a) ", ValidationHelper.Captalize(this.ViewModel.SelectedCliente.get_Nome()), ", segue o link do seu Cartão Assistência 24 horas.", Environment.NewLine, Environment.NewLine, "LINK CARTÃO ASSISTÊNCIA 24 HORAS", Environment.NewLine, this._linkAssistencia }; + string str = string.Concat(strArrays); + this.ViewModel.Anotacoes = str; + } + } + + private async void Recusar_OnClick(object sender, RoutedEventArgs e) + { + if (!this.ViewModel.Restricao(18)) + { + await this.ViewModel.RecusarDocumento(); + } + else + { + await this.ViewModel.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA RECUSAR. PROCURE O ADMINSTRADOR DO SISTEMA.", "OK", "", false); + } + } + + private async void RelacaoItens_OnClick(object sender, RoutedEventArgs e) + { + await this.ViewModel.GerarExcel(this.ViewModel.FilterItens); + } + + private async void Renovar_OnClick(object sender, RoutedEventArgs e) + { + if (this.ViewModel.Restricao(17)) + { + await this.ViewModel.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA RENOVAR. PROCURE O ADMINSTRADOR DO SISTEMA.", "OK", "", false); + } + else if (!this.ViewModel.EnableRenovar) + { + await this.ViewModel.ShowMessage("NÃO É POSSÍVEL RENOVAR UM DOCUMENTO SEM EMISSÃO OU SEM FINAL DE VIGÊNCIA.", "OK", "", false); + } + else if (ConsultaViewModel.DocumentoSelecionado.get_Situacao() != 7) + { + Action acessaTela = Gestor.Application.Actions.Actions.AcessaTela; + if (acessaTela != null) + { + acessaTela(2, "Renovar"); + } + else + { + } + } + else + { + await this.ViewModel.ShowMessage("NÃO É POSSÍVEL RENOVAR UM DOCUMENTO RECUSADO.", "OK", "", false); + } + } + + private async void ReordenarItem_Click(object sender, RoutedEventArgs e) + { + ObservableCollection itens = this.ViewModel.Itens; + List list = ( + from x in itens + select x.get_Id()).ToList(); + ConsultaViewModel viewModel = this.ViewModel; + viewModel.SalvarOrdem(await this.ViewModel.ShowReordenarItensDialog(list)); + viewModel = null; + } + + private void ScrollDocumento() + { + if (this.ViewModel.UpdatingScroll && this.ApoliceGrid.SelectedItem != null) + { + this.ApoliceGrid.ScrollIntoView(this.ApoliceGrid.SelectedItem); + } + this.ViewModel.UpdatingScroll = false; + } + + public void ScrollToIndex(DataGrid grid, int index) + { + ScrollViewer descendantByType = this.GetDescendantByType(grid, typeof(ScrollViewer)) as ScrollViewer; + int num = (index - 5 > 0 ? index - 5 : 0); + if (descendantByType == null) + { + return; + } + descendantByType.ScrollToVerticalOffset((double)num); + } + + private void ScrollToItem() + { + if (this.ItemGrid.SelectedItem == null) + { + return; + } + this.ScrollToIndex(this.ItemGrid, this.ItemGrid.SelectedIndex); + } + + private void SelecionarRadios(int filter) + { + this._carregarDocumetos = false; + this.ApoliceRadioButton.IsChecked = new bool?(filter == 0); + this.EndossoRadioButton.IsChecked = new bool?(filter == 1); + this._carregarDocumetos = true; + } + + private void Sinistros_OnClick(object sender, RoutedEventArgs e) + { + Action acessaTela = Gestor.Application.Actions.Actions.AcessaTela; + if (acessaTela == null) + { + return; + } + acessaTela(7, ""); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.ApoliceRadioButton = (RadioButton)target; + return; + } + case 2: + { + this.EndossoRadioButton = (RadioButton)target; + return; + } + case 3: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.ClienteView_Click); + return; + } + case 4: + { + this.AcessarDocumentoMenuItem = (MenuItem)target; + this.AcessarDocumentoMenuItem.Click += new RoutedEventHandler(this.ApoliceView_Click); + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Renovar_OnClick); + return; + } + case 6: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Perdido_OnClick); + return; + } + case 7: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Endossar_OnClick); + return; + } + case 8: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Recusar_OnClick); + return; + } + case 9: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.MenuItem_OnClick); + return; + } + case 10: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Extratos_OnClick); + return; + } + case 11: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.TrocarCliente_OnClick); + return; + } + case 12: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.EditarParcelas_OnClick); + return; + } + case 13: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.ExpedicaoInfo_OnClick); + return; + } + case 14: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.ValoresInfo_OnClick); + return; + } + case 15: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.ManutecaoItens_OnClick); + return; + } + case 16: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.RelacaoItens_OnClick); + return; + } + case 17: + { + this.ApoliceGrid = (DataGrid)target; + return; + } + case 18: + case 22: + case 23: + case 24: + case 25: + case 26: + case 29: + case 30: + case 40: + case 41: + case 42: + { + this._contentLoaded = true; + return; + } + case 19: + { + this.NomeField = (DataGridTextColumn)target; + return; + } + case 20: + { + this.ApelidoField = (DataGridTextColumn)target; + return; + } + case 21: + { + this.ApolicesComissaoColumn = (DataGridTextColumn)target; + return; + } + case 27: + { + this.EndossoGrid = (DataGrid)target; + return; + } + case 28: + { + this.EndossosComissaoColumn = (DataGridTextColumn)target; + return; + } + case 31: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Parcela_Click); + return; + } + case 32: + { + this.Comissao = (WrapPanel)target; + return; + } + case 33: + { + this.ParcelaGrid = (DataGrid)target; + return; + } + case 34: + { + this.ParcelasTotalColumn = (DataGridTextColumn)target; + return; + } + case 35: + { + this.ParcelasRealizadoColumn = (DataGridTextColumn)target; + return; + } + case 36: + { + this.ParcelasComissaoColumn = (DataGridTextColumn)target; + return; + } + case 37: + { + this.ParcelasReciboColumn = (DataGridTextColumn)target; + return; + } + case 38: + { + this.ParcelasValorComissaoDescColumn = (DataGridTextColumn)target; + return; + } + case 39: + { + this.MaisInformacoesColumn = (DataGridTemplateColumn)target; + return; + } + case 43: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Item_Click); + return; + } + case 44: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Sinistros_OnClick); + return; + } + case 45: + { + this.AtivosRadioButton = (RadioButton)target; + return; + } + case 46: + { + this.ApoliceItensRadioButton = (RadioButton)target; + return; + } + case 47: + { + this.EndossoItensRadioButton = (RadioButton)target; + return; + } + case 48: + { + this.InativosRadioButton = (RadioButton)target; + return; + } + case 49: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.MostrarItens_Click); + return; + } + case 50: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.ReordenarItem_Click); + return; + } + case 51: + { + this.ItemGrid = (DataGrid)target; + return; + } + default: + { + this._contentLoaded = true; + return; + } + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 18: + { + EventSetter eventSetter = new EventSetter() + { + Event = Control.MouseDoubleClickEvent, + Handler = new MouseButtonEventHandler(this.ApoliceGrid_OnMouseDoubleClick) + }; + ((System.Windows.Style)target).Setters.Add(eventSetter); + return; + } + case 19: + case 20: + case 21: + case 27: + case 28: + { + return; + } + case 22: + { + ((Button)target).Click += new RoutedEventHandler(this.AbrirAquivoDigital_Click); + return; + } + case 23: + { + ((Button)target).Click += new RoutedEventHandler(this.Observacoes_OnClick); + return; + } + case 24: + { + ((PopupBox)target).add_Opened(new RoutedEventHandler(this.PopupBox_OnOpened)); + ((PopupBox)target).add_Closed(new RoutedEventHandler(this.PopupBox_OnClosed)); + return; + } + case 25: + { + ((Button)target).Click += new RoutedEventHandler(this.EnviarPorWhatsApp_OnClick); + return; + } + case 26: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.EnviarPorEmail_OnClick); + return; + } + case 29: + { + ((Button)target).Click += new RoutedEventHandler(this.AbrirAquivoDigital_Click); + return; + } + case 30: + { + ((Button)target).Click += new RoutedEventHandler(this.Observacoes_OnClick); + return; + } + default: + { + switch (connectionId) + { + case 40: + { + ((Button)target).Click += new RoutedEventHandler(this.ValoresParcelaInfo_OnClick); + return; + } + case 41: + { + ((Button)target).Click += new RoutedEventHandler(this.AbrirAquivoDigital_Click); + return; + } + case 42: + { + ((Button)target).Click += new RoutedEventHandler(this.Observacoes_OnClick); + return; + } + default: + { + if (connectionId != 52) + { + return; + } + ((Button)target).Click += new RoutedEventHandler(this.AbrirAquivoDigital_Click); + return; + } + } + break; + } + } + } + + private async void TrocarCliente_OnClick(object sender, RoutedEventArgs e) + { + (new HosterWindow(new TrocarClienteView(this.ViewModel.SelectedControle), "TROCAR CLIENTE", new double?((double)500), new double?((double)200), false)).ShowDialog(); + await this.ViewModel.SelecionaCliente(MainViewModel.ClienteSelecionado, true); + Action recarregarDocumentos = Gestor.Application.Actions.Actions.RecarregarDocumentos; + if (recarregarDocumentos != null) + { + recarregarDocumentos(null); + } + else + { + } + } + + private async void ValoresInfo_OnClick(object sender, RoutedEventArgs e) + { + bool flag = this.ViewModel.Restricao(97); + if (!flag) + { + Documento documento = await this.ViewModel.AbrirDetalhes(); + this.ViewModel.ShowDrawer(new ValoresApoliceDrawer(documento), 0, true); + } + if (flag) + { + await this.ViewModel.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR MAIS INFORMAÇÕES.", "OK", "", false); + } + } + + private async void ValoresParcelaInfo_OnClick(object sender, RoutedEventArgs e) + { + Parcela parcela = await this.ViewModel.AbrirDetalhesParcela(); + this.ViewModel.ShowDrawer(new ValoresParcelaDrawer(parcela, this.ViewModel.SelectedControle), 0, true); + } + + private void VisibilityValorPago() + { + bool flag; + DataGridTextColumn parcelasTotalColumn = this.ParcelasTotalColumn; + ObservableCollection parcelas = this.ViewModel.Parcelas; + if (parcelas != null) + { + flag = parcelas.Sum((Parcela p) => p.get_ValorPago()) > new decimal(); + } + else + { + flag = false; + } + parcelasTotalColumn.Visibility = (flag ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Seguros/CriticaApoliceView.cs b/Codemerx/Gestor.Application/Views/Seguros/CriticaApoliceView.cs new file mode 100644 index 0000000..9c8b3ec --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Seguros/CriticaApoliceView.cs @@ -0,0 +1,2010 @@ +using CsQuery.ExtensionMethods; +using CurrencyTextBoxControl; +using Gestor.Application.Componentes; +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Application.Views.Generic; +using Gestor.Application.Views.Seguros.Itens; +using Gestor.Common.Helpers; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using MaterialDesignThemes.Wpf; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; +using Xceed.Wpf.AvalonDock.Controls; + +namespace Gestor.Application.Views.Seguros +{ + public class CriticaApoliceView : BaseUserControl, IComponentConnector, IStyleConnector + { + internal ComboBox UsuarioBox; + + internal ComboBox SeguradoraBox; + + internal DatePicker InicioBox; + + internal DatePicker FimBox; + + internal ToggleButton CriticadoBox; + + internal DataGrid CriticaGrid; + + internal MenuItem ConcluirCriticaButton; + + internal MenuItem CancelarDocumento; + + internal ComboBox ProdutoBox; + + internal ComboBox NegocioCorretoraBox; + + internal ComboBox SituacaoBox; + + internal DatePicker TransmissaoBox; + + internal TextBox ApoliceBox; + + internal TextBox EndossoBox; + + internal DatePicker EmissaoBox; + + internal DatePicker Vigencia1Box; + + internal DatePicker Vigencia2Box; + + internal ToggleButton AdicionalBox; + + internal CustomIsReadOnlyControl Comissao; + + internal CurrencyTextBox ComissaoBox; + + internal CurrencyTextBox PremioLiquidoBox; + + internal CurrencyTextBox PremioAdicionalBox; + + internal CurrencyTextBox IofBox; + + internal CurrencyTextBox DiferencaBox; + + internal CurrencyTextBox PremioTotalBox; + + internal CurrencyTextBox ParcelasBox; + + internal ToggleButton SeguroCombinadoBox; + + internal MenuItem EditarVendedorButton; + + internal MenuItem SalvarVendedorButton; + + internal MenuItem CancelarVendedorButton; + + internal WrapPanel VendedorFields; + + internal ToggleButton CoCorretagemToogle; + + internal ComboBox TipoVendedorBox; + + internal ComboBox VendedorBox; + + internal CustomItemValidation ComissaoNovoBox; + + internal ComboBox ComissaoNovoComboBox; + + internal CustomItemValidation ComissaoRenovacaoBox; + + internal ComboBox ComissaoRenovacaoComboBox; + + internal CurrencyTextBox ValorRepasseBox; + + internal TextBox FormaRecebidaBox; + + internal DataGrid VendedorGrid; + + internal DataGridTextColumn RepasseVendedor; + + internal TextBox NomeBox; + + internal ComboBox TipoDocumentoPrincipalBox; + + internal TextBox DocumentoPrincipalBox; + + internal DatePicker NascimentoBox; + + internal TextBox IdentidadeBox; + + internal TextBox EmissorBox; + + internal TextBox EstadoEmissorBox; + + internal ListBox TelefoneListBox; + + internal ListBox EmailListBox; + + internal DataGrid ItemGrid; + + private bool _contentLoaded; + + private bool AdicionandoVendedor + { + get; + set; + } + + private int Ordem { get; set; } = 1; + + public CriticaApoliceViewModel ViewModel + { + get; + set; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public CriticaApoliceView() + { + base.Tag = "CRÍTICA DE IMPORTAÇÃO"; + this.ViewModel = new CriticaApoliceViewModel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + + private async void AbrirAquivoDigital_Click(object sender, RoutedEventArgs e) + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 2).get_Consultar()) + { + FiltroArquivoDigital filtroArquivoDigital = new FiltroArquivoDigital(); + filtroArquivoDigital.set_Id(this.ViewModel.SelectedCritica.get_Documento().get_Id()); + filtroArquivoDigital.set_Tipo(2); + filtroArquivoDigital.set_Parente(this.ViewModel.SelectedCritica.get_Documento()); + this.ViewModel.ShowDrawer(new ArquivoDigitalDrawer(filtroArquivoDigital), 0, false); + } + else + { + await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", EnumHelper.GetDescription(2), "."), "OK", "", false); + } + } + + private void AdicionalBox_OnChecked(object sender, RoutedEventArgs e) + { + if (this.ViewModel.SelectedDocumento == null) + { + return; + } + this.AlteracaoDePremio_LostFocus(this.PremioAdicionalBox, new RoutedEventArgs()); + } + + private void AdicionarCoCorretagem_OnClick(object sender, RoutedEventArgs e) + { + bool valueOrDefault; + bool selectedItem; + bool flag; + ToggleButton toggleButton = (ToggleButton)sender; + if (toggleButton != null) + { + valueOrDefault = toggleButton.IsChecked.GetValueOrDefault(); + } + else + { + valueOrDefault = false; + } + bool flag1 = valueOrDefault; + ComboBox comissaoNovoComboBox = this.ComissaoNovoComboBox; + if (comissaoNovoComboBox != null) + { + selectedItem = comissaoNovoComboBox.SelectedItem; + } + else + { + selectedItem = false; + } + if (selectedItem) + { + this.ComissaoNovoComboBox.SelectedItem = null; + } + if (flag1) + { + this.TipoVendedorBox.SelectedIndex = 0; + } + else if (this.TipoVendedorBox.SelectedItem != null) + { + this.TipoVendedorBox.SelectedItem = null; + } + ComboBox vendedorBox = this.VendedorBox; + if (vendedorBox != null) + { + flag = vendedorBox.SelectedItem; + } + else + { + flag = false; + } + if (flag) + { + this.VendedorBox.SelectedItem = null; + } + if (ValidationHelper.IsNotNullOrEmpty(this.ValorRepasseBox.Text)) + { + this.ValorRepasseBox.Text = ""; + } + this.ViewModel.VendedorCoCorretagem(flag1); + } + + private void AdicionarFiltro_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AdcionarFiltro(); + } + + private void AlteracaoDePremio_LostFocus(object sender, RoutedEventArgs e) + { + decimal iof; + if (!this.ViewModel.AllowEditApolice) + { + return; + } + if (this.ViewModel.SelectedDocumento == null) + { + return; + } + CurrencyTextBox currencyTextBox = (CurrencyTextBox)sender; + if (currencyTextBox == null) + { + return; + } + string name = currencyTextBox.Name; + if ((name == "PremioLiquidoBox" || name == "PremioAdicionalBox") && this.IofBox.get_Number() == decimal.Zero) + { + decimal number = this.PremioLiquidoBox.get_Number() + this.PremioAdicionalBox.get_Number(); + Ramo ramo = this.ViewModel.SelectedDocumento.get_Controle().get_Ramo(); + if (ramo != null) + { + iof = ramo.get_Iof(); + } + else + { + iof = decimal.Zero; + } + decimal num = number * iof; + this.IofBox.set_Number(num); + CurrencyTextBox premioTotalBox = this.PremioTotalBox; + premioTotalBox.set_Number(premioTotalBox.get_Number() + num); + } + this.PremioTotalBox.set_Number(((this.PremioLiquidoBox.get_Number() + this.PremioAdicionalBox.get_Number()) + this.IofBox.get_Number()) + this.DiferencaBox.get_Number()); + name = currencyTextBox.Name; + if ((name == "PremioLiquidoBox" || name == "PremioAdicionalBox" || name == "ComissaoBox") && this.ViewModel.HabilitarVendedor(0).Count == 0) + { + this.ViewModel.RecalculaRepasses(); + } + this.ValidarDocumento(); + } + + private async void Alterar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Alterar(true); + this.ViewModel.EnableGrid = false; + List configuracoes = Recursos.Configuracoes; + if (configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 3)) + { + this.SituacaoBox.SelectedIndex = -1; + } + await this.ViewModel.SelecionaCritica(this.ViewModel.SelectedCritica); + this.ValidarDocumento(); + } + + private async void Apolice_OnClick(object sender, RoutedEventArgs e) + { + if (this.ViewModel.SelectedDocumento != null) + { + double? nullable = null; + double? nullable1 = nullable; + nullable = null; + (new HosterWindow(new ApoliceView(this.ViewModel.SelectedDocumento, true, false, 0, (long)0, true), string.Concat("CADASTRO DE APÓLICES - ", this.ViewModel.SelectedDocumento.get_Controle().get_Cliente().get_Nome(), " - ", this.ViewModel.SelectedDocumento.get_Apolice()), nullable1, nullable, false)).ShowDialog(); + await this.ViewModel.SelecionaDocumento(this.ViewModel.SelectedDocumento); + } + } + + private async void Atualizar_OnClick(object sender, RoutedEventArgs e) + { + await this.ViewModel.CarregaCritica(this.ViewModel.SelectedUsuario.get_Id(), this.ViewModel.SelectedSeguradora.get_Id(), this.ViewModel.Criticado); + } + + private async void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + List repasses = this.ViewModel.Repasses; + if (!( + from repasse in repasses + where !repasse.get_Vendedor().get_Corretora() + select repasse).Any()) + { + if (!this.ViewModel.HasChange && (this.ViewModel.SelectedDocumento == null || !this.ViewModel.SelectedDocumento.HasChange()) && (this.ViewModel.SelectedCliente == null || !this.ViewModel.SelectedCliente.HasChange())) + { + if (this.ViewModel.Telefones != null) + { + ObservableCollection telefones = this.ViewModel.Telefones; + if (!telefones.Any((ClienteTelefone x) => x.HasChange())) + { + goto Label0; + } + } + else + { + goto Label0; + } + } + if (!await this.ViewModel.ShowMessage(string.Concat("HÁ ALTERAÇÕES PENDENTES AINDA NÃO SALVAS, DESEJA CONTINUAR? ", Environment.NewLine, "O PROCEDIMENTO IRÁ CANCELAR AS ALTERAÇÕES REALIZADAS."), "SIM", "NÃO", false)) + { + return; + } + Label0: + await this.ViewModel.SelecionaCritica(this.ViewModel.SelectedCritica); + this.ViewModel.Alterar(false); + this.ViewModel.EnableGrid = true; + } + else + { + await this.ViewModel.ShowMessage("PARA CANCELAR AS ALTERAÇÕES É NECESSÁRIO REMOVER OS VENDEDORES COM REPASSE CONFIGURADO.", "OK", "", false); + } + } + + private void CancelarVendedor_Click(object sender, RoutedEventArgs e) + { + this.EditarVendedor(false); + this.ViewModel.SelectedPagamento = null; + this.ViewModel.SelecionarVendedor(); + } + + private async void Cliente_OnClick(object sender, RoutedEventArgs e) + { + double? nullable = null; + double? nullable1 = nullable; + nullable = null; + (new HosterWindow(new ClienteView(this.ViewModel.SelectedDocumento.get_Controle().get_Cliente(), true, null), string.Concat("CADASTRO DE CLIENTES - ", this.ViewModel.SelectedDocumento.get_Controle().get_Cliente().get_Nome()), nullable1, nullable, false)).ShowDialog(); + CriticaApoliceViewModel viewModel = this.ViewModel; + Cliente cliente = await this.ViewModel.CarregaCliente(this.ViewModel.SelectedCliente.get_Id()); + viewModel.SelectedCliente = cliente; + viewModel = null; + await this.ViewModel.SelecionaCliente(this.ViewModel.SelectedCliente); + } + + private void ComissaoVendedorBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + decimal? valorRepasse; + ComboBox comboBox = (ComboBox)sender; + if (comboBox.SelectedItem == null) + { + return; + } + Repasse selectedItem = (Repasse)comboBox.SelectedItem; + if (selectedItem != null && selectedItem.get_Tipo().GetValueOrDefault() == 3) + { + decimal comissao = (this.ViewModel.SelectedDocumento.get_Comissao() * selectedItem.get_ValorNovo() * new decimal(1, 0, 0, false, 2)) * new decimal(1, 0, 0, false, 2); + this.ViewModel.SelectedPagamento.set_ValorRepasse(new decimal?(this.ViewModel.SelectedDocumento.get_PremioTotal() * comissao)); + CurrencyTextBox valorRepasseBox = this.ValorRepasseBox; + valorRepasse = this.ViewModel.SelectedPagamento.get_ValorRepasse(); + valorRepasseBox.set_Number(valorRepasse.Value); + return; + } + this.ViewModel.SelectedPagamento.set_Repasse(selectedItem); + this.ViewModel.SelectedPagamento.set_PorcentagemRepasse(new decimal?((this.ViewModel.SelectedDocumento.get_Situacao() != 2 || this.ViewModel.SelectedDocumento.get_Negocio().GetValueOrDefault() != 1 ? selectedItem.get_ValorNovo() : selectedItem.get_ValorRenovacao()))); + if (this.ViewModel.SelectedParcela == null) + { + CriticaApoliceViewModel viewModel = this.ViewModel; + Parcela parcela = new Parcela(); + parcela.set_SubTipo(1); + viewModel.SelectedParcela = parcela; + } + this.ViewModel.SelectedParcela.set_Documento(this.ViewModel.SelectedDocumento); + this.ViewModel.SelectedPagamento.set_ValorRepasse(new decimal?(Funcoes.CalculaRepasse(selectedItem, this.ViewModel.SelectedParcela, (this.ViewModel.SelectedParcela == null ? true : this.ViewModel.SelectedParcela.get_SubTipo() == 1)))); + this.ViewModel.SelectedPagamento.set_ValorTotal(this.ViewModel.SelectedPagamento.get_ValorRepasse()); + CurrencyTextBox currencyTextBox = this.ValorRepasseBox; + valorRepasse = this.ViewModel.SelectedPagamento.get_ValorRepasse(); + currencyTextBox.set_Number(valorRepasse.Value); + this.FormaRecebidaBox.Text = EnumHelper.GetDescription(selectedItem.get_Forma()); + } + + private async void ConcluirCritica_OnClick(object sender, RoutedEventArgs e) + { + this.ConcluirCriticaButton.Click -= new RoutedEventHandler(this.ConcluirCritica_OnClick); + this.ViewModel.EnableGrid = false; + this.ExecutarValidacaoData(); + this.NomeBox.Focus(); + if (this.ViewModel.CompararValores()) + { + this.PremioTotalBox.set_Number(((this.PremioLiquidoBox.get_Number() + this.PremioAdicionalBox.get_Number()) + this.IofBox.get_Number()) + this.DiferencaBox.get_Number()); + } + await this.SalvarDocumento(); + this.ConcluirCriticaButton.Click += new RoutedEventHandler(this.ConcluirCritica_OnClick); + } + + private async void ContentLoad() + { + System.Windows.Visibility visibility; + this.DocumentoPrincipalBox.LostFocus += new RoutedEventHandler(this.DocumentoPrincipalBox_OnLostFocus); + CriticaApoliceView criticaApoliceView = this; + this.DocumentoPrincipalBox.PreviewTextInput += new TextCompositionEventHandler(criticaApoliceView.SomenteNumeros); + this.CriticadoBox.Checked += new RoutedEventHandler(this.Criticado_OnChecked); + this.CriticadoBox.Unchecked += new RoutedEventHandler(this.Criticado_OnChecked); + this.UsuarioBox.SelectionChanged += new SelectionChangedEventHandler(this.Usuario_OnSelectionChanged); + this.SeguradoraBox.SelectionChanged += new SelectionChangedEventHandler(this.Seguradora_OnSelectionChanged); + this.InicioBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.InicioBox.PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + this.InicioBox.SelectedDateChanged += new EventHandler(this.FiltroDataBox_OnSelectedDateChanged); + this.FimBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.FimBox.PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + this.FimBox.SelectedDateChanged += new EventHandler(this.FiltroDataBox_OnSelectedDateChanged); + this.TransmissaoBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.TransmissaoBox.PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + this.EmissaoBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.EmissaoBox.PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + this.Vigencia1Box.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.Vigencia1Box.PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + this.Vigencia2Box.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.Vigencia2Box.PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + this.NegocioCorretoraBox.SelectionChanged += new SelectionChangedEventHandler(this.NegocioCorretoraBox_OnSelectionChanged); + this.PremioLiquidoBox.LostFocus += new RoutedEventHandler(this.AlteracaoDePremio_LostFocus); + this.PremioAdicionalBox.LostFocus += new RoutedEventHandler(this.AlteracaoDePremio_LostFocus); + this.IofBox.LostFocus += new RoutedEventHandler(this.AlteracaoDePremio_LostFocus); + this.DiferencaBox.LostFocus += new RoutedEventHandler(this.AlteracaoDePremio_LostFocus); + this.AdicionalBox.Unchecked += new RoutedEventHandler(this.AdicionalBox_OnChecked); + this.AdicionalBox.Checked += new RoutedEventHandler(this.AdicionalBox_OnChecked); + this.VendedorBox.SelectionChanged += new SelectionChangedEventHandler(this.VendedorBox_OnSelectionChanged); + this.TipoVendedorBox.SelectionChanged += new SelectionChangedEventHandler(this.TipoVendedorBox_OnSelectionChanged); + this.TipoDocumentoPrincipalBox.SelectionChanged += new SelectionChangedEventHandler(this.TipoDocumentoPrincipalBox_OnSelectionChanged); + this.CriticaGrid.SelectionChanged += new SelectionChangedEventHandler(this.Grid_OnSelectionChanged); + DataGridTextColumn repasseVendedor = this.RepasseVendedor; + visibility = (this.ViewModel.Restricao(95) ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible); + repasseVendedor.Visibility = visibility; + await this.ViewModel.InitialLoad(); + } + + private async void Criticado_OnChecked(object sender, RoutedEventArgs e) + { + bool flag; + bool selectedItem; + ToggleButton toggleButton = (ToggleButton)sender; + flag = (toggleButton != null ? !toggleButton.IsChecked.HasValue : true); + if (!flag) + { + ComboBox usuarioBox = this.UsuarioBox; + if (usuarioBox != null) + { + selectedItem = usuarioBox.SelectedItem; + } + else + { + selectedItem = false; + } + if (selectedItem) + { + if (!this.ViewModel.IsLoading) + { + bool value = toggleButton.IsChecked.Value; + this.SeguradoraBox.SelectionChanged -= new SelectionChangedEventHandler(this.Seguradora_OnSelectionChanged); + this.UsuarioBox.SelectionChanged -= new SelectionChangedEventHandler(this.Usuario_OnSelectionChanged); + this.CriticadoBox.Checked -= new RoutedEventHandler(this.Criticado_OnChecked); + await this.ViewModel.CarregarUsuarios(((Usuario)this.UsuarioBox.SelectedItem).get_Id(), value); + await this.ViewModel.CarregaCritica(this.ViewModel.SelectedUsuario.get_Id(), this.ViewModel.SelectedSeguradora.get_Id(), value); + this.SeguradoraBox.SelectionChanged += new SelectionChangedEventHandler(this.Seguradora_OnSelectionChanged); + this.UsuarioBox.SelectionChanged += new SelectionChangedEventHandler(this.Usuario_OnSelectionChanged); + this.CriticadoBox.Checked += new RoutedEventHandler(this.Criticado_OnChecked); + } + } + } + } + + private void DocumentoPrincipalBox_LostFocus(object sender, RoutedEventArgs e) + { + if (((TextBox)sender).IsReadOnly) + { + return; + } + string str = ValidationHelper.Clear(this.DocumentoPrincipalBox.Text); + if (string.IsNullOrEmpty(str)) + { + return; + } + this.DocumentoPrincipalBox.Text = (str.Length == 11 ? ValidationHelper.FormatDocument(str.PadLeft(11, '0').Substring(0, 11)) : ValidationHelper.FormatDocument(str.PadLeft(14, '0').Substring(0, 14))); + this.ViewModel.JuridicaouFisica(this.DocumentoPrincipalBox.Text); + } + + private void DocumentoPrincipalBox_OnLostFocus(object sender, RoutedEventArgs e) + { + if (this.TipoDocumentoPrincipalBox.SelectedItem == null) + { + this.TipoDocumentoPrincipalBox.SelectedItem = (TipoDocumento)0; + } + if ((TipoDocumento)this.TipoDocumentoPrincipalBox.SelectedItem == null) + { + TextBox textBox = (TextBox)sender; + textBox.Text = ValidationHelper.FormatDocument(textBox.Text); + } + } + + private void EditarVendedor(bool editar) + { + bool count; + ObservableCollection pagamentos; + bool flag; + ObservableCollection observableCollection; + this.AdicionandoVendedor = editar; + this.SalvarVendedorButton.Visibility = (editar ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.CancelarVendedorButton.Visibility = (editar ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.EditarVendedorButton.Visibility = (editar ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible); + this.VendedorFields.Visibility = (editar ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.VendedorGrid.IsEnabled = !editar; + if (this.ViewModel.SelectedDocumento == null) + { + return; + } + if (editar) + { + if (Recursos.Configuracoes.Any((ConfiguracaoSistema config) => config.get_Configuracao() == 56)) + { + ObservableCollection pagamentos1 = this.ViewModel.Pagamentos; + if (pagamentos1 != null) + { + count = pagamentos1.Count == 1; + } + else + { + count = false; + } + if (count) + { + if (!this.ViewModel.Pagamentos.Any((VendedorParcela vendedor) => vendedor.get_Repasse() == null)) + { + pagamentos = this.ViewModel.Pagamentos; + if (pagamentos != null) + { + flag = pagamentos.Count == 0; + } + else + { + observableCollection = pagamentos; + flag = false; + } + this.CoCorretagemToogle.IsEnabled = flag; + this.ComissaoNovoBox.Visibility = System.Windows.Visibility.Visible; + this.ComissaoRenovacaoBox.Visibility = System.Windows.Visibility.Collapsed; + this.CoCorretagemToogle.IsChecked = new bool?(false); + return; + } + flag = true; + this.CoCorretagemToogle.IsEnabled = flag; + this.ComissaoNovoBox.Visibility = System.Windows.Visibility.Visible; + this.ComissaoRenovacaoBox.Visibility = System.Windows.Visibility.Collapsed; + this.CoCorretagemToogle.IsChecked = new bool?(false); + return; + } + pagamentos = this.ViewModel.Pagamentos; + if (pagamentos != null) + { + flag = pagamentos.Count == 0; + } + else + { + observableCollection = pagamentos; + flag = false; + } + this.CoCorretagemToogle.IsEnabled = flag; + this.ComissaoNovoBox.Visibility = System.Windows.Visibility.Visible; + this.ComissaoRenovacaoBox.Visibility = System.Windows.Visibility.Collapsed; + this.CoCorretagemToogle.IsChecked = new bool?(false); + return; + } + } + NegocioCorretora? negocioCorretora = this.ViewModel.SelectedDocumento.get_NegocioCorretora(); + bool valueOrDefault = negocioCorretora.GetValueOrDefault() == 1; + this.ComissaoNovoBox.Visibility = (!editar || valueOrDefault ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible); + this.ComissaoRenovacaoBox.Visibility = (editar & valueOrDefault ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + } + + private async void EditarVendedorButton_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + bool hasValue; + List> keyValuePairs = this.ViewModel.SelectedDocumento.Validate(); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + bool flag1 = flag; + if (flag1) + { + Parcela selectedParcela = this.ViewModel.SelectedParcela; + if (selectedParcela != null) + { + hasValue = selectedParcela.get_DataRecebimento().HasValue; + } + else + { + hasValue = false; + } + if (hasValue) + { + await this.ViewModel.ShowMessage("DOCUMENTO COM PARCELA(S) JÁ BAIXADA(S), NÃO É POSSÍVEL ALTERAR VENDEDORES!", "OK", "", false); + return; + } + } + if (flag1) + { + this.ViewModel.IncluirVendedor(); + this.EditarVendedor(true); + this.ViewModel.VendedorCoCorretagem(false); + } + else + { + this.ValidateFields(keyValuePairs, true); + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + } + + private void ExcluirEmail_OnClick(object sender, RoutedEventArgs e) + { + Button button = sender as Button; + if (button == null) + { + return; + } + if (button.DataContext == null) + { + return; + } + ClienteEmail dataContext = (ClienteEmail)button.DataContext; + this.ViewModel.ExcluirEmail(dataContext); + } + + private void ExcluirFiltro_OnClick(object sender, RoutedEventArgs e) + { + Chip chip = sender as Chip; + if (chip == null) + { + return; + } + ListBox listBox = Extentions.FindVisualAncestor(chip); + string item = (string)listBox.Items[listBox.Items.IndexOf(chip.DataContext)]; + if (item == null) + { + return; + } + this.ViewModel.PesquisaCritica.Remove(item); + this.ViewModel.Pesquisar(); + } + + private void ExcluirTelefone_OnClick(object sender, RoutedEventArgs e) + { + Button button = sender as Button; + if (button == null) + { + return; + } + if (button.DataContext == null) + { + return; + } + ClienteTelefone dataContext = (ClienteTelefone)button.DataContext; + this.ViewModel.ExcluirTelefone(dataContext); + } + + private async void ExcluirVendedor_OnClick(object sender, RoutedEventArgs e) + { + TipoRepasse? nullable; + bool selectedIndex; + object item; + TipoRepasse? tipo; + bool valueOrDefault; + object obj; + System.Windows.Visibility visibility; + DataGrid vendedorGrid = this.VendedorGrid; + if (vendedorGrid != null) + { + selectedIndex = vendedorGrid.SelectedIndex < 0; + } + else + { + selectedIndex = false; + } + if (!selectedIndex) + { + DataGrid dataGrid = this.VendedorGrid; + if (dataGrid != null) + { + item = dataGrid.Items[this.VendedorGrid.SelectedIndex]; + } + else + { + item = null; + } + VendedorParcela vendedorParcela = (VendedorParcela)item; + if (vendedorParcela != null) + { + Repasse repasse = vendedorParcela.get_Repasse(); + if (repasse != null) + { + tipo = repasse.get_Tipo(); + } + else + { + nullable = null; + tipo = nullable; + } + nullable = tipo; + valueOrDefault = nullable.GetValueOrDefault() == 3; + } + else + { + valueOrDefault = false; + } + bool flag = valueOrDefault; + CriticaApoliceViewModel viewModel = this.ViewModel; + DataGrid vendedorGrid1 = this.VendedorGrid; + if (vendedorGrid1 != null) + { + obj = vendedorGrid1.Items[this.VendedorGrid.SelectedIndex]; + } + else + { + obj = null; + } + await viewModel.ExcluirVendedor((VendedorParcela)obj, true); + await this.ViewModel.SelecionaParcela(this.ViewModel.Parcelas.FirstOrDefault()); + this.ComissaoBox.IsReadOnly = this.ViewModel.VerificaCoCorretagem(); + CriticaApoliceViewModel criticaApoliceViewModel = this.ViewModel; + visibility = (this.ComissaoBox.IsReadOnly ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + criticaApoliceViewModel.ComissOriginalVisibility = visibility; + if (flag) + { + await this.ViewModel.AjusteComissãoCoCorretagem(true); + } + } + } + + private void ExecutarValidacaoData() + { + DateTime dateTime; + DateTime? nullable; + DateTime? nullable1; + DateTime? nullable2; + DateTime? nullable3; + DateTime? nullable4; + Cliente selectedCliente = this.ViewModel.SelectedCliente; + if (this.NascimentoBox.Text == null || !DateTime.TryParse(ValidationHelper.FormatDate(this.NascimentoBox.Text), out dateTime)) + { + nullable = null; + nullable1 = nullable; + } + else + { + nullable1 = new DateTime?(dateTime); + } + selectedCliente.set_Nascimento(nullable1); + Documento selectedDocumento = this.ViewModel.SelectedDocumento; + if (this.TransmissaoBox.Text == null || !DateTime.TryParse(ValidationHelper.FormatDate(this.TransmissaoBox.Text), out dateTime)) + { + nullable = null; + nullable2 = nullable; + } + else + { + nullable2 = new DateTime?(dateTime); + } + selectedDocumento.set_Remessa(nullable2); + Documento documento = this.ViewModel.SelectedDocumento; + if (this.EmissaoBox.Text == null || !DateTime.TryParse(ValidationHelper.FormatDate(this.EmissaoBox.Text), out dateTime)) + { + nullable = null; + nullable3 = nullable; + } + else + { + nullable3 = new DateTime?(dateTime); + } + documento.set_Emissao(nullable3); + this.ViewModel.SelectedDocumento.set_Vigencia1((this.Vigencia1Box.Text == null || !DateTime.TryParse(ValidationHelper.FormatDate(this.Vigencia1Box.Text), out dateTime) ? Funcoes.GetNetworkTime().Date : dateTime)); + Documento selectedDocumento1 = this.ViewModel.SelectedDocumento; + if (this.Vigencia2Box.Text == null || !DateTime.TryParse(ValidationHelper.FormatDate(this.Vigencia2Box.Text), out dateTime)) + { + nullable = null; + nullable4 = nullable; + } + else + { + nullable4 = new DateTime?(dateTime); + } + selectedDocumento1.set_Vigencia2(nullable4); + } + + private async void FiltroDataBox_OnSelectedDateChanged(object sender, SelectionChangedEventArgs e) + { + bool hasValue; + bool selectedItem; + DatePicker datePicker = (DatePicker)sender; + if (datePicker != null) + { + hasValue = !datePicker.SelectedDate.HasValue; + } + else + { + hasValue = true; + } + if (!hasValue) + { + ComboBox usuarioBox = this.UsuarioBox; + if (usuarioBox != null) + { + selectedItem = usuarioBox.SelectedItem; + } + else + { + selectedItem = false; + } + if (selectedItem) + { + this.SeguradoraBox.SelectionChanged -= new SelectionChangedEventHandler(this.Seguradora_OnSelectionChanged); + this.UsuarioBox.SelectionChanged -= new SelectionChangedEventHandler(this.Usuario_OnSelectionChanged); + this.CriticadoBox.Checked -= new RoutedEventHandler(this.Criticado_OnChecked); + await this.ViewModel.CarregarUsuarios(((Usuario)this.UsuarioBox.SelectedItem).get_Id(), this.ViewModel.Criticado); + await this.ViewModel.CarregaCritica(this.ViewModel.SelectedUsuario.get_Id(), this.ViewModel.SelectedSeguradora.get_Id(), this.ViewModel.Criticado); + this.SeguradoraBox.SelectionChanged += new SelectionChangedEventHandler(this.Seguradora_OnSelectionChanged); + this.UsuarioBox.SelectionChanged += new SelectionChangedEventHandler(this.Usuario_OnSelectionChanged); + this.CriticadoBox.Checked += new RoutedEventHandler(this.Criticado_OnChecked); + } + } + } + + private async void Grid_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + if (this.ViewModel.EnableGrid) + { + DataGrid dataGrid = (DataGrid)sender; + if (dataGrid != null) + { + if (dataGrid.SelectedIndex >= 0) + { + this.ViewModel.EnableGrid = false; + this.ViewModel.Index = dataGrid.SelectedIndex; + await this.ViewModel.SelecionaCritica((CriticaApolice)dataGrid.Items[dataGrid.SelectedIndex]); + this.ViewModel.EnableGrid = true; + } + } + } + } + + private void Initial_DatePicker_OnLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) + { + base.DatePicker_OnLostKeyboardFocus(sender, e); + if (string.IsNullOrEmpty(this.Vigencia1Box.Text)) + { + this.Vigencia1Box.SelectedDate = new DateTime?(DateTime.MinValue); + this.ViewModel.SelectedDocumento.set_Vigencia1(DateTime.MinValue); + } + if (string.IsNullOrWhiteSpace(this.Vigencia2Box.Text)) + { + DatePicker vigencia2Box = this.Vigencia2Box; + DateTime dateTime = ValidationHelper.ToDateTime(this.Vigencia1Box.Text); + vigencia2Box.DisplayDate = dateTime.AddYears(1); + DatePicker shortDateString = this.Vigencia2Box; + dateTime = this.Vigencia2Box.DisplayDate; + shortDateString.Text = dateTime.ToShortDateString(); + } + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/seguros/criticaapoliceview.xaml", UriKind.Relative)); + } + + private async void Item_Click(object sender, RoutedEventArgs e) + { + Item dataContext; + UserControl patrimonialView; + double? nullable; + double? nullable1; + bool? nullable2; + Button button = (Button)sender; + if (button.DataContext != null) + { + dataContext = (Item)button.DataContext; + dataContext.set_Documento(this.ViewModel.SelectedDocumento); + long id = this.ViewModel.SelectedDocumento.get_Controle().get_Ramo().get_Id(); + long num = id - (long)1; + if (num <= (long)19) + { + switch ((uint)num) + { + case 0: + case 1: + case 2: + case 14: + case 17: + { + patrimonialView = new PatrimonialView(null, true, false, null, dataContext, this.ViewModel.SelectedDocumento.get_Controle().get_Ramo(), false); + nullable = null; + nullable1 = nullable; + nullable = null; + nullable2 = (new HosterWindow(patrimonialView, string.Concat("CADASTRO DE CLIENTES - ", this.ViewModel.SelectedDocumento.get_Controle().get_Cliente().get_Nome()), nullable1, nullable, false)).ShowDialog(); + await this.ViewModel.SelecionaItens(this.ViewModel.SelectedDocumento.get_Controle().get_Id()); + return; + } + case 3: + case 7: + case 10: + case 11: + case 13: + case 15: + case 16: + case 18: + { + patrimonialView = new RiscosDiversosView(null, false, false, null, dataContext, this.ViewModel.SelectedDocumento.get_Controle().get_Ramo(), false); + nullable = null; + nullable1 = nullable; + nullable = null; + nullable2 = (new HosterWindow(patrimonialView, string.Concat("CADASTRO DE CLIENTES - ", this.ViewModel.SelectedDocumento.get_Controle().get_Cliente().get_Nome()), nullable1, nullable, false)).ShowDialog(); + await this.ViewModel.SelecionaItens(this.ViewModel.SelectedDocumento.get_Controle().get_Id()); + return; + } + case 4: + { + patrimonialView = new AutoView(null, true, false, null, dataContext, this.ViewModel.SelectedDocumento.get_Controle().get_Ramo(), false); + nullable = null; + nullable1 = nullable; + nullable = null; + nullable2 = (new HosterWindow(patrimonialView, string.Concat("CADASTRO DE CLIENTES - ", this.ViewModel.SelectedDocumento.get_Controle().get_Cliente().get_Nome()), nullable1, nullable, false)).ShowDialog(); + await this.ViewModel.SelecionaItens(this.ViewModel.SelectedDocumento.get_Controle().get_Id()); + return; + } + case 5: + case 6: + case 8: + case 9: + { + patrimonialView = new VidaView(null, true, false, null, dataContext, this.ViewModel.SelectedDocumento.get_Controle().get_Ramo(), false); + nullable = null; + nullable1 = nullable; + nullable = null; + nullable2 = (new HosterWindow(patrimonialView, string.Concat("CADASTRO DE CLIENTES - ", this.ViewModel.SelectedDocumento.get_Controle().get_Cliente().get_Nome()), nullable1, nullable, false)).ShowDialog(); + await this.ViewModel.SelecionaItens(this.ViewModel.SelectedDocumento.get_Controle().get_Id()); + return; + } + case 12: + { + patrimonialView = new AeronauticoView(null, true, false, null, dataContext, this.ViewModel.SelectedDocumento.get_Controle().get_Ramo(), false); + nullable = null; + nullable1 = nullable; + nullable = null; + nullable2 = (new HosterWindow(patrimonialView, string.Concat("CADASTRO DE CLIENTES - ", this.ViewModel.SelectedDocumento.get_Controle().get_Cliente().get_Nome()), nullable1, nullable, false)).ShowDialog(); + await this.ViewModel.SelecionaItens(this.ViewModel.SelectedDocumento.get_Controle().get_Id()); + return; + } + case 19: + { + patrimonialView = new GranizoView(null, true, false, null, dataContext, this.ViewModel.SelectedDocumento.get_Controle().get_Ramo(), false); + nullable = null; + nullable1 = nullable; + nullable = null; + nullable2 = (new HosterWindow(patrimonialView, string.Concat("CADASTRO DE CLIENTES - ", this.ViewModel.SelectedDocumento.get_Controle().get_Cliente().get_Nome()), nullable1, nullable, false)).ShowDialog(); + await this.ViewModel.SelecionaItens(this.ViewModel.SelectedDocumento.get_Controle().get_Id()); + return; + } + } + } + else + { + } + long num1 = id - (long)36; + if (num1 <= (long)2) + { + switch ((uint)num1) + { + case 0: + { + patrimonialView = new ConsorcioView(null, true, false, null, dataContext, this.ViewModel.SelectedDocumento.get_Controle().get_Ramo(), false); + nullable = null; + nullable1 = nullable; + nullable = null; + nullable2 = (new HosterWindow(patrimonialView, string.Concat("CADASTRO DE CLIENTES - ", this.ViewModel.SelectedDocumento.get_Controle().get_Cliente().get_Nome()), nullable1, nullable, false)).ShowDialog(); + await this.ViewModel.SelecionaItens(this.ViewModel.SelectedDocumento.get_Controle().get_Id()); + return; + } + case 1: + { + patrimonialView = new AutoView(null, true, false, null, dataContext, this.ViewModel.SelectedDocumento.get_Controle().get_Ramo(), false); + nullable = null; + nullable1 = nullable; + nullable = null; + nullable2 = (new HosterWindow(patrimonialView, string.Concat("CADASTRO DE CLIENTES - ", this.ViewModel.SelectedDocumento.get_Controle().get_Cliente().get_Nome()), nullable1, nullable, false)).ShowDialog(); + await this.ViewModel.SelecionaItens(this.ViewModel.SelectedDocumento.get_Controle().get_Id()); + return; + } + case 2: + { + patrimonialView = new PatrimonialView(null, true, false, null, dataContext, this.ViewModel.SelectedDocumento.get_Controle().get_Ramo(), false); + nullable = null; + nullable1 = nullable; + nullable = null; + nullable2 = (new HosterWindow(patrimonialView, string.Concat("CADASTRO DE CLIENTES - ", this.ViewModel.SelectedDocumento.get_Controle().get_Cliente().get_Nome()), nullable1, nullable, false)).ShowDialog(); + await this.ViewModel.SelecionaItens(this.ViewModel.SelectedDocumento.get_Controle().get_Id()); + return; + } + } + } + else + { + } + if (id != (long)53) + { + patrimonialView = new RiscosDiversosView(null, false, false, null, dataContext, this.ViewModel.SelectedDocumento.get_Controle().get_Ramo(), false); + nullable = null; + nullable1 = nullable; + nullable = null; + nullable2 = (new HosterWindow(patrimonialView, string.Concat("CADASTRO DE CLIENTES - ", this.ViewModel.SelectedDocumento.get_Controle().get_Cliente().get_Nome()), nullable1, nullable, false)).ShowDialog(); + await this.ViewModel.SelecionaItens(this.ViewModel.SelectedDocumento.get_Controle().get_Id()); + return; + } + patrimonialView = new VidaView(null, true, false, null, dataContext, this.ViewModel.SelectedDocumento.get_Controle().get_Ramo(), false); + nullable = null; + nullable1 = nullable; + nullable = null; + nullable2 = (new HosterWindow(patrimonialView, string.Concat("CADASTRO DE CLIENTES - ", this.ViewModel.SelectedDocumento.get_Controle().get_Cliente().get_Nome()), nullable1, nullable, false)).ShowDialog(); + await this.ViewModel.SelecionaItens(this.ViewModel.SelectedDocumento.get_Controle().get_Id()); + return; + } + return; + nullable = null; + nullable1 = nullable; + nullable = null; + nullable2 = (new HosterWindow(patrimonialView, string.Concat("CADASTRO DE CLIENTES - ", this.ViewModel.SelectedDocumento.get_Controle().get_Cliente().get_Nome()), nullable1, nullable, false)).ShowDialog(); + await this.ViewModel.SelecionaItens(this.ViewModel.SelectedDocumento.get_Controle().get_Id()); + return; + patrimonialView = new PatrimonialView(null, true, false, null, dataContext, this.ViewModel.SelectedDocumento.get_Controle().get_Ramo(), false); + nullable = null; + nullable1 = nullable; + nullable = null; + nullable2 = (new HosterWindow(patrimonialView, string.Concat("CADASTRO DE CLIENTES - ", this.ViewModel.SelectedDocumento.get_Controle().get_Cliente().get_Nome()), nullable1, nullable, false)).ShowDialog(); + await this.ViewModel.SelecionaItens(this.ViewModel.SelectedDocumento.get_Controle().get_Id()); + return; + patrimonialView = new RiscosDiversosView(null, false, false, null, dataContext, this.ViewModel.SelectedDocumento.get_Controle().get_Ramo(), false); + nullable = null; + nullable1 = nullable; + nullable = null; + nullable2 = (new HosterWindow(patrimonialView, string.Concat("CADASTRO DE CLIENTES - ", this.ViewModel.SelectedDocumento.get_Controle().get_Cliente().get_Nome()), nullable1, nullable, false)).ShowDialog(); + await this.ViewModel.SelecionaItens(this.ViewModel.SelectedDocumento.get_Controle().get_Id()); + return; + patrimonialView = new AutoView(null, true, false, null, dataContext, this.ViewModel.SelectedDocumento.get_Controle().get_Ramo(), false); + nullable = null; + nullable1 = nullable; + nullable = null; + nullable2 = (new HosterWindow(patrimonialView, string.Concat("CADASTRO DE CLIENTES - ", this.ViewModel.SelectedDocumento.get_Controle().get_Cliente().get_Nome()), nullable1, nullable, false)).ShowDialog(); + await this.ViewModel.SelecionaItens(this.ViewModel.SelectedDocumento.get_Controle().get_Id()); + return; + patrimonialView = new RiscosDiversosView(null, false, false, null, dataContext, this.ViewModel.SelectedDocumento.get_Controle().get_Ramo(), false); + nullable = null; + nullable1 = nullable; + nullable = null; + nullable2 = (new HosterWindow(patrimonialView, string.Concat("CADASTRO DE CLIENTES - ", this.ViewModel.SelectedDocumento.get_Controle().get_Cliente().get_Nome()), nullable1, nullable, false)).ShowDialog(); + await this.ViewModel.SelecionaItens(this.ViewModel.SelectedDocumento.get_Controle().get_Id()); + } + + private void NegocioCorretoraBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + bool selectedItem; + ComboBox comboBox = (ComboBox)sender; + if (comboBox != null) + { + selectedItem = comboBox.SelectedItem; + } + else + { + selectedItem = false; + } + if (!selectedItem) + { + return; + } + this.AlteracaoDePremio_LostFocus(this.PremioLiquidoBox, new RoutedEventArgs()); + if (this.SalvarVendedorButton.Visibility != System.Windows.Visibility.Visible) + { + return; + } + this.EditarVendedor(true); + this.ComissaoVendedorBox_OnSelectionChanged((this.ComissaoNovoBox.Visibility == System.Windows.Visibility.Visible ? this.ComissaoNovoComboBox : this.ComissaoRenovacaoComboBox), e); + } + + private void OrdemBox_OnLostFocus(object sender, RoutedEventArgs e) + { + int num; + int num1; + TextBox textBox = sender as TextBox; + if (textBox == null) + { + return; + } + if (textBox.IsReadOnly) + { + return; + } + if (!int.TryParse(textBox.Text, out num)) + { + return; + } + WrapPanel wrapPanel = Extentions.FindVisualAncestor(Extentions.FindVisualAncestor(textBox)); + ListBox listBox = Extentions.FindVisualAncestor(wrapPanel); + if (listBox != null) + { + for (int i = 0; i < listBox.Items.Count; i++) + { + if (i != listBox.Items.IndexOf(wrapPanel.DataContext)) + { + ContentPresenter contentPresenter = FindVisualChild.Find((ListBoxItem)listBox.ItemContainerGenerator.ContainerFromIndex(i)); + TextBox str = (TextBox)contentPresenter.ContentTemplate.FindName("OrdemBox", contentPresenter); + if (int.TryParse(str.Text, out num1) && num1 == num) + { + str.Text = this.Ordem.ToString(); + } + } + } + } + } + + private void OrdemBox_OnPreviewGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) + { + int num; + TextBox textBox = sender as TextBox; + if (textBox == null) + { + return; + } + if (!int.TryParse(textBox.Text, out num)) + { + return; + } + this.Ordem = num; + } + + private async void Perfil_OnClick(object sender, RoutedEventArgs e) + { + PerfilView perfilView = new PerfilView(this.ViewModel.SelectedDocumento.get_Controle()); + if (await this.ViewModel.VerificarPermissao(32, false)) + { + (new HosterWindow(perfilView, "PERFIL", new double?((double)800), new double?((double)370), false)).ShowDialog(); + } + perfilView = null; + } + + private void Pesquisa_OnPreviewKeyDown(object sender, KeyEventArgs e) + { + if (e.Key != Key.Return) + { + return; + } + this.ViewModel.AdcionarFiltro(); + } + + private async Task SalvarDocumento() + { + bool flag; + bool flag1; + bool flag2; + bool flag3; + this.ViewModel.Loading(true); + List> keyValuePairs = null; + if (this.AdicionandoVendedor) + { + keyValuePairs = await this.ViewModel.AdicionarVendedor(); + } + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + if (flag) + { + keyValuePairs = await this.ViewModel.SalvarCliente(); + flag1 = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + if (flag1) + { + if (!this.ViewModel.StatusDocumento.HasValue) + { + keyValuePairs = new List>() + { + new KeyValuePair("STATUS DO SEGURO", "OBRIGATÓRIO") + }; + } + flag2 = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + if (flag2) + { + if (!this.ViewModel.StatusDocumento.HasValue) + { + this.ViewModel.SelectedDocumento.set_Situacao(1); + } + keyValuePairs = await this.ViewModel.Salvar(true); + flag3 = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + if (flag3) + { + await this.ViewModel.ConcluirCritica(); + this.EditarVendedor(false); + this.ViewModel.EnableGrid = true; + this.SeguroCombinadoBox.IsChecked = new bool?(false); + } + else + { + List> keyValuePairs1 = keyValuePairs; + if (!keyValuePairs1.Any>((KeyValuePair x) => x.Value == "VIGENCIANAOACEITA")) + { + this.ViewModel.Loading(false); + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + else + { + this.ViewModel.Loading(false); + } + } + } + else + { + this.ViewModel.Loading(false); + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + } + else + { + this.ViewModel.Loading(false); + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + } + else + { + this.ViewModel.Loading(false); + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + } + + private async void SalvarVendedor_Click(object sender, RoutedEventArgs e) + { + TipoRepasse? nullable; + List> keyValuePairs; + bool valueOrDefault; + TipoRepasse? tipo; + bool flag; + decimal num; + bool flag1; + ((MenuItem)sender).Click -= new RoutedEventHandler(this.SalvarVendedor_Click); + bool coCorretagem = this.ViewModel.CoCorretagem; + if (coCorretagem) + { + coCorretagem = !await this.ViewModel.ShowMessage("AO ADICIONAR CO-CORRETAGEM COMO VENDEDOR, O DOCUMENTO ACIMA SERÁ SALVO.\nDESEJÁ CONTINUAR?", "SIM", "NÃO", false); + } + if (!coCorretagem) + { + if (this.ViewModel.SelectedParcela == null) + { + valueOrDefault = true; + } + else if (this.ViewModel.SelectedParcela.get_SubTipo() != 1) + { + valueOrDefault = false; + } + else + { + TipoRecebimento? tipoRecebimento = this.ViewModel.SelectedDocumento.get_TipoRecebimento(); + valueOrDefault = tipoRecebimento.GetValueOrDefault() == 1; + } + bool flag2 = valueOrDefault; + NegocioCorretora? negocioCorretora = this.ViewModel.SelectedDocumento.get_NegocioCorretora(); + bool valueOrDefault1 = negocioCorretora.GetValueOrDefault() == 1; + if (this.ComissaoRenovacaoComboBox.SelectedItem != null || this.ComissaoNovoComboBox.SelectedItem != null) + { + VendedorParcela selectedPagamento = this.ViewModel.SelectedPagamento; + if (selectedPagamento != null) + { + Repasse repasse = selectedPagamento.get_Repasse(); + if (repasse != null) + { + tipo = repasse.get_Tipo(); + } + else + { + nullable = null; + tipo = nullable; + } + nullable = tipo; + flag = nullable.GetValueOrDefault() == 3; + } + else + { + flag = false; + } + if (flag) + { + valueOrDefault1 = false; + } + object selectedItem = this.ComissaoRenovacaoComboBox.SelectedItem; + if (selectedItem == null) + { + selectedItem = this.ComissaoNovoComboBox.SelectedItem; + } + object obj = selectedItem; + VendedorParcela vendedorParcela = this.ViewModel.SelectedPagamento; + num = (valueOrDefault1 ? ((Repasse)obj).get_ValorRenovacao() : ((Repasse)obj).get_ValorNovo()); + vendedorParcela.set_PorcentagemRepasse(new decimal?(num)); + keyValuePairs = (!flag2 ? await this.ViewModel.AdicionarVendedorParcelaEspecial() : await this.ViewModel.AdicionarVendedor()); + List> keyValuePairs1 = keyValuePairs; + flag1 = (keyValuePairs1 == null ? true : keyValuePairs1.Count == 0); + if (!flag1) + { + await this.ViewModel.ShowMessage(keyValuePairs1, this.ViewModel.ErroCamposInvalidos, "OK", ""); + ((MenuItem)sender).Click += new RoutedEventHandler(this.SalvarVendedor_Click); + } + else + { + this.EditarVendedor(false); + if (this.ViewModel.VerificaCoCorretagem()) + { + this.ComissaoBox.IsReadOnly = true; + this.ViewModel.ComissOriginalVisibility = System.Windows.Visibility.Visible; + } + ((MenuItem)sender).Click += new RoutedEventHandler(this.SalvarVendedor_Click); + } + } + else + { + await this.ViewModel.ShowMessage("NECESSÁRIOS ESCOLHER O VALOR DE REPASSE ANTES DE ADICIONAR O VENDEDOR", "OK", "", false); + ((MenuItem)sender).Click += new RoutedEventHandler(this.SalvarVendedor_Click); + } + } + else + { + ((MenuItem)sender).Click += new RoutedEventHandler(this.SalvarVendedor_Click); + } + } + + private async void Seguradora_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + bool hasValue; + ComboBox comboBox = (ComboBox)sender; + if (comboBox != null && comboBox.SelectedItem != null) + { + ToggleButton criticadoBox = this.CriticadoBox; + if (criticadoBox != null) + { + hasValue = !criticadoBox.IsChecked.HasValue; + } + else + { + hasValue = true; + } + if (!hasValue) + { + this.SeguradoraBox.SelectionChanged -= new SelectionChangedEventHandler(this.Seguradora_OnSelectionChanged); + this.UsuarioBox.SelectionChanged -= new SelectionChangedEventHandler(this.Usuario_OnSelectionChanged); + this.CriticadoBox.Checked -= new RoutedEventHandler(this.Criticado_OnChecked); + this.ViewModel.SelectedSeguradora = (Seguradora)comboBox.SelectedItem; + await this.ViewModel.CarregaCritica(this.ViewModel.SelectedUsuario.get_Id(), ((Seguradora)comboBox.SelectedItem).get_Id(), this.ViewModel.Criticado); + this.SeguradoraBox.SelectionChanged += new SelectionChangedEventHandler(this.Seguradora_OnSelectionChanged); + this.UsuarioBox.SelectionChanged += new SelectionChangedEventHandler(this.Usuario_OnSelectionChanged); + this.CriticadoBox.Checked += new RoutedEventHandler(this.Criticado_OnChecked); + } + } + } + + private void SituacaoBox_SelectionChanged(object sender, SelectionChangedEventArgs e) + { + ComboBox comboBox = (ComboBox)sender; + if (this.ViewModel.EnableFields) + { + this.ViewModel.StatusDocumento = (TipoSeguro?)comboBox.SelectedItem; + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.UsuarioBox = (ComboBox)target; + return; + } + case 2: + { + this.SeguradoraBox = (ComboBox)target; + return; + } + case 3: + { + this.InicioBox = (DatePicker)target; + this.InicioBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.InicioBox.PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + this.InicioBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 4: + { + this.FimBox = (DatePicker)target; + this.FimBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.FimBox.PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + this.FimBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 5: + { + this.CriticadoBox = (ToggleButton)target; + return; + } + case 6: + { + ((Button)target).Click += new RoutedEventHandler(this.Atualizar_OnClick); + return; + } + case 7: + { + ((TextBox)target).PreviewKeyDown += new KeyEventHandler(this.Pesquisa_OnPreviewKeyDown); + return; + } + case 8: + { + ((Button)target).Click += new RoutedEventHandler(this.AdicionarFiltro_OnClick); + return; + } + case 9: + case 53: + case 63: + case 64: + case 65: + case 66: + case 67: + case 69: + case 70: + { + this._contentLoaded = true; + return; + } + case 10: + { + this.CriticaGrid = (DataGrid)target; + return; + } + case 11: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 12: + { + this.ConcluirCriticaButton = (MenuItem)target; + this.ConcluirCriticaButton.Click += new RoutedEventHandler(this.ConcluirCritica_OnClick); + return; + } + case 13: + { + this.CancelarDocumento = (MenuItem)target; + this.CancelarDocumento.Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 14: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Cliente_OnClick); + return; + } + case 15: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Apolice_OnClick); + return; + } + case 16: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Tarefa_OnClick); + return; + } + case 17: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Perfil_OnClick); + return; + } + case 18: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirAquivoDigital_Click); + return; + } + case 19: + { + this.ProdutoBox = (ComboBox)target; + return; + } + case 20: + { + this.NegocioCorretoraBox = (ComboBox)target; + return; + } + case 21: + { + this.SituacaoBox = (ComboBox)target; + this.SituacaoBox.SelectionChanged += new SelectionChangedEventHandler(this.SituacaoBox_SelectionChanged); + return; + } + case 22: + { + this.TransmissaoBox = (DatePicker)target; + this.TransmissaoBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.TransmissaoBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 23: + { + this.ApoliceBox = (TextBox)target; + return; + } + case 24: + { + this.EndossoBox = (TextBox)target; + return; + } + case 25: + { + this.EmissaoBox = (DatePicker)target; + this.EmissaoBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.EmissaoBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 26: + { + this.Vigencia1Box = (DatePicker)target; + this.Vigencia1Box.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.Initial_DatePicker_OnLostKeyboardFocus); + this.Vigencia1Box.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 27: + { + this.Vigencia2Box = (DatePicker)target; + this.Vigencia2Box.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.Vigencia2Box.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 28: + { + this.AdicionalBox = (ToggleButton)target; + return; + } + case 29: + { + this.Comissao = (CustomIsReadOnlyControl)target; + return; + } + case 30: + { + this.ComissaoBox = (CurrencyTextBox)target; + return; + } + case 31: + { + this.PremioLiquidoBox = (CurrencyTextBox)target; + return; + } + case 32: + { + this.PremioAdicionalBox = (CurrencyTextBox)target; + return; + } + case 33: + { + this.IofBox = (CurrencyTextBox)target; + return; + } + case 34: + { + this.DiferencaBox = (CurrencyTextBox)target; + return; + } + case 35: + { + this.PremioTotalBox = (CurrencyTextBox)target; + return; + } + case 36: + { + this.ParcelasBox = (CurrencyTextBox)target; + return; + } + case 37: + { + this.SeguroCombinadoBox = (ToggleButton)target; + return; + } + case 38: + { + this.EditarVendedorButton = (MenuItem)target; + this.EditarVendedorButton.Click += new RoutedEventHandler(this.EditarVendedorButton_OnClick); + return; + } + case 39: + { + this.SalvarVendedorButton = (MenuItem)target; + this.SalvarVendedorButton.Click += new RoutedEventHandler(this.SalvarVendedor_Click); + return; + } + case 40: + { + this.CancelarVendedorButton = (MenuItem)target; + this.CancelarVendedorButton.Click += new RoutedEventHandler(this.CancelarVendedor_Click); + return; + } + case 41: + { + this.VendedorFields = (WrapPanel)target; + return; + } + case 42: + { + this.CoCorretagemToogle = (ToggleButton)target; + this.CoCorretagemToogle.Click += new RoutedEventHandler(this.AdicionarCoCorretagem_OnClick); + return; + } + case 43: + { + this.TipoVendedorBox = (ComboBox)target; + return; + } + case 44: + { + this.VendedorBox = (ComboBox)target; + return; + } + case 45: + { + this.ComissaoNovoBox = (CustomItemValidation)target; + return; + } + case 46: + { + this.ComissaoNovoComboBox = (ComboBox)target; + this.ComissaoNovoComboBox.SelectionChanged += new SelectionChangedEventHandler(this.ComissaoVendedorBox_OnSelectionChanged); + return; + } + case 47: + { + this.ComissaoRenovacaoBox = (CustomItemValidation)target; + return; + } + case 48: + { + this.ComissaoRenovacaoComboBox = (ComboBox)target; + this.ComissaoRenovacaoComboBox.SelectionChanged += new SelectionChangedEventHandler(this.ComissaoVendedorBox_OnSelectionChanged); + return; + } + case 49: + { + this.ValorRepasseBox = (CurrencyTextBox)target; + return; + } + case 50: + { + this.FormaRecebidaBox = (TextBox)target; + return; + } + case 51: + { + this.VendedorGrid = (DataGrid)target; + return; + } + case 52: + { + this.RepasseVendedor = (DataGridTextColumn)target; + return; + } + case 54: + { + this.NomeBox = (TextBox)target; + return; + } + case 55: + { + this.TipoDocumentoPrincipalBox = (ComboBox)target; + return; + } + case 56: + { + this.DocumentoPrincipalBox = (TextBox)target; + CriticaApoliceView criticaApoliceView = this; + this.DocumentoPrincipalBox.PreviewTextInput += new TextCompositionEventHandler(criticaApoliceView.SomenteNumeros); + this.DocumentoPrincipalBox.LostFocus += new RoutedEventHandler(this.DocumentoPrincipalBox_LostFocus); + return; + } + case 57: + { + this.NascimentoBox = (DatePicker)target; + this.NascimentoBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.NascimentoBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 58: + { + this.IdentidadeBox = (TextBox)target; + return; + } + case 59: + { + this.EmissorBox = (TextBox)target; + return; + } + case 60: + { + this.EstadoEmissorBox = (TextBox)target; + return; + } + case 61: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + ((DatePicker)target).PreviewTextInput += new TextCompositionEventHandler(this.SomenteData); + return; + } + case 62: + { + this.TelefoneListBox = (ListBox)target; + return; + } + case 68: + { + this.EmailListBox = (ListBox)target; + return; + } + case 71: + { + this.ItemGrid = (DataGrid)target; + return; + } + default: + { + this._contentLoaded = true; + return; + } + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + if (connectionId == 9) + { + ((Chip)target).add_DeleteClick(new RoutedEventHandler(this.ExcluirFiltro_OnClick)); + return; + } + if (connectionId == 53) + { + ((Button)target).Click += new RoutedEventHandler(this.ExcluirVendedor_OnClick); + return; + } + switch (connectionId) + { + case 63: + { + ((ComboBox)target).SelectionChanged += new SelectionChangedEventHandler(this.TipoComboBox_OnSelectionChanged); + return; + } + case 64: + { + CriticaApoliceView criticaApoliceView = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(criticaApoliceView.SomenteNumeros); + return; + } + case 65: + { + CriticaApoliceView criticaApoliceView1 = this; + ((TextBox)target).LostFocus += new RoutedEventHandler(criticaApoliceView1.FormatarTelefone); + CriticaApoliceView criticaApoliceView2 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(criticaApoliceView2.SomenteNumeros); + return; + } + case 66: + { + ((TextBox)target).PreviewGotKeyboardFocus += new KeyboardFocusChangedEventHandler(this.OrdemBox_OnPreviewGotKeyboardFocus); + ((TextBox)target).LostFocus += new RoutedEventHandler(this.OrdemBox_OnLostFocus); + CriticaApoliceView criticaApoliceView3 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(criticaApoliceView3.SomenteNumeros); + return; + } + case 67: + { + ((Button)target).Click += new RoutedEventHandler(this.ExcluirTelefone_OnClick); + return; + } + case 68: + case 71: + { + return; + } + case 69: + { + ((TextBox)target).PreviewGotKeyboardFocus += new KeyboardFocusChangedEventHandler(this.OrdemBox_OnPreviewGotKeyboardFocus); + ((TextBox)target).LostFocus += new RoutedEventHandler(this.OrdemBox_OnLostFocus); + CriticaApoliceView criticaApoliceView4 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(criticaApoliceView4.SomenteNumeros); + return; + } + case 70: + { + ((Button)target).Click += new RoutedEventHandler(this.ExcluirEmail_OnClick); + return; + } + case 72: + { + ((Button)target).Click += new RoutedEventHandler(this.Item_Click); + return; + } + default: + { + return; + } + } + } + + private void Tarefa_OnClick(object sender, RoutedEventArgs e) + { + Tarefa tarefa = new Tarefa(); + tarefa.set_IdCliente(this.ViewModel.SelectedDocumento.get_Controle().get_Cliente().get_Id()); + tarefa.set_Cliente(this.ViewModel.SelectedDocumento.get_Controle().get_Cliente().get_Nome()); + tarefa.set_Entidade(0); + tarefa.set_IdEntidade(this.ViewModel.SelectedDocumento.get_Id()); + tarefa.set_Titulo(string.Concat(this.ViewModel.SelectedDocumento.get_Controle().get_Cliente().get_Nome(), " APÓLICE ", this.ViewModel.SelectedDocumento.get_Apolice())); + Tarefa tarefa1 = tarefa; + this.ViewModel.ShowDrawer(new TarefaDrawer(tarefa1, true), 0, false); + } + + private void TipoComboBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + int num; + ComboBox comboBox = (ComboBox)sender; + CustomIsReadOnlyControl customIsReadOnlyControl = Extentions.FindVisualAncestor(comboBox); + if (customIsReadOnlyControl == null) + { + return; + } + WrapPanel wrapPanel = Extentions.FindVisualAncestor(customIsReadOnlyControl); + ListBox listBox = Extentions.FindVisualAncestor(wrapPanel); + ContentPresenter contentPresenter = FindVisualChild.Find((ListBoxItem)listBox.ItemContainerGenerator.ContainerFromIndex(listBox.Items.IndexOf(wrapPanel.DataContext))); + DataTemplate contentTemplate = contentPresenter.ContentTemplate; + CustomItemValidation customItemValidation = (CustomItemValidation)contentTemplate.FindName("Prefixo", contentPresenter); + CustomItemValidation customItemValidation1 = (CustomItemValidation)contentTemplate.FindName("Telefone", contentPresenter); + TextBox textBox = ViewHelper.FindChildren(customItemValidation).FirstOrDefault(); + TextBox textBox1 = ViewHelper.FindChildren(customItemValidation1).FirstOrDefault(); + if (textBox == null || textBox1 == null) + { + return; + } + if ((TipoTelefone)comboBox.SelectedValue == 8) + { + customItemValidation.Visibility = System.Windows.Visibility.Collapsed; + textBox1.MaxLength = 20; + return; + } + customItemValidation.Visibility = System.Windows.Visibility.Visible; + textBox1.MaxLength = 10; + num = (textBox1.Text.Length >= 10 ? 10 : textBox1.Text.Length); + textBox1.Text = textBox1.Text.Substring(0, num); + } + + private void TipoDocumentoPrincipalBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + this.ViewModel.AlteraDocumentoPrincipal(); + } + + private void TipoVendedorBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + ComboBox comboBox = (ComboBox)sender; + if (comboBox.SelectedItem == null) + { + return; + } + if (this.ViewModel.SelectedPagamento == null) + { + this.ViewModel.SelectedPagamento = new VendedorParcela(); + } + this.ViewModel.SelectedPagamento.set_TipoVendedor((TipoVendedor)comboBox.SelectedItem); + } + + private async void Usuario_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + bool hasValue; + ComboBox comboBox = (ComboBox)sender; + if (comboBox != null && comboBox.SelectedItem != null) + { + ToggleButton criticadoBox = this.CriticadoBox; + if (criticadoBox != null) + { + hasValue = !criticadoBox.IsChecked.HasValue; + } + else + { + hasValue = true; + } + if (!hasValue) + { + if (this.ViewModel.SelectedSeguradora != null) + { + this.SeguradoraBox.SelectionChanged -= new SelectionChangedEventHandler(this.Seguradora_OnSelectionChanged); + this.UsuarioBox.SelectionChanged -= new SelectionChangedEventHandler(this.Usuario_OnSelectionChanged); + this.CriticadoBox.Checked -= new RoutedEventHandler(this.Criticado_OnChecked); + this.ViewModel.SelectedUsuario = (Usuario)comboBox.SelectedItem; + await this.ViewModel.CarregaCritica(((Usuario)comboBox.SelectedItem).get_Id(), this.ViewModel.SelectedSeguradora.get_Id(), this.ViewModel.Criticado); + this.SeguradoraBox.SelectionChanged += new SelectionChangedEventHandler(this.Seguradora_OnSelectionChanged); + this.UsuarioBox.SelectionChanged += new SelectionChangedEventHandler(this.Usuario_OnSelectionChanged); + this.CriticadoBox.Checked += new RoutedEventHandler(this.Criticado_OnChecked); + } + } + } + } + + private void ValidarDocumento() + { + if (this.ViewModel.SelectedDocumento == null) + { + return; + } + List> keyValuePairs1 = this.ViewModel.SelectedDocumento.Validate(); + if (this.ViewModel.Telefones != null) + { + ExtensionMethods.ForEach(this.ViewModel.Telefones, (ClienteTelefone x) => { + List> keyValuePairs = x.Validate(); + keyValuePairs1.AddRange(keyValuePairs); + }); + } + this.ValidateFields(keyValuePairs1, false); + ExtensionMethods.ForEach(Extentions.FindVisualChildren(this.TelefoneListBox), (DependencyObject child) => child.ValidateFields(keyValuePairs1, false)); + } + + private void VendedorBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + ComboBox comboBox = (ComboBox)sender; + if (comboBox.SelectedItem == null) + { + return; + } + this.ViewModel.FiltrarRepasse((Vendedor)comboBox.SelectedItem); + NegocioCorretora? negocioCorretora = this.ViewModel.SelectedDocumento.get_NegocioCorretora(); + bool valueOrDefault = negocioCorretora.GetValueOrDefault() == 1; + if (valueOrDefault && this.ViewModel.CoCorretagem) + { + this.ComissaoNovoBox.Visibility = System.Windows.Visibility.Visible; + this.ComissaoRenovacaoBox.Visibility = System.Windows.Visibility.Collapsed; + return; + } + this.ComissaoNovoBox.Visibility = (!valueOrDefault ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.ComissaoRenovacaoBox.Visibility = (valueOrDefault ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Seguros/Itens/AeronauticoView.cs b/Codemerx/Gestor.Application/Views/Seguros/Itens/AeronauticoView.cs new file mode 100644 index 0000000..d0bef66 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Seguros/Itens/AeronauticoView.cs @@ -0,0 +1,373 @@ +using Gestor.Application.Componentes; +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Application.ViewModels.Seguros.Itens; +using Gestor.Application.Views.Generic; +using Gestor.Application.Views.Seguros; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Views.Seguros.Itens +{ + public class AeronauticoView : BaseUserControl, IComponentConnector + { + public AeronauticoViewModel ViewModel; + + private readonly MenuItemViewModel _menuItemViewModel; + + private string _lastCategory = ""; + + internal MenuItem IncluirItemButton; + + internal MenuItem SinistroButton; + + internal RadioButton CoberturasRadioButton; + + internal RadioButton MaisInformacoesRadioButton; + + internal System.Windows.Controls.ContentControl ContentControl; + + internal CustomItemValidation MaisInformacoes; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public AeronauticoView(MenuItemViewModel menuItemViewModel, bool lockInsert = false, bool substituir = false, ManutencaoItem manutencao = null, Item itemSelecionado = null, Ramo ramo = null, bool endossoRenovacao = false) + { + this._menuItemViewModel = menuItemViewModel; + this.ViewModel = new AeronauticoViewModel(substituir, manutencao, itemSelecionado, ramo, endossoRenovacao); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher != null) + { + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + else + { + } + if (!lockInsert) + { + return; + } + this.IncluirItemButton.IsEnabled = false; + this.SinistroButton.Visibility = System.Windows.Visibility.Collapsed; + } + + private async void AbrirAquivoDigital_Click(object sender, RoutedEventArgs e) + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 4).get_Consultar()) + { + FiltroArquivoDigital filtroArquivoDigital = new FiltroArquivoDigital(); + filtroArquivoDigital.set_Id(this.ViewModel.SelectedItem.get_Id()); + filtroArquivoDigital.set_IdApolice(this.ViewModel.SelectedItem.get_Documento().get_Id()); + filtroArquivoDigital.set_Tipo(4); + filtroArquivoDigital.set_Parente(this.ViewModel.SelectedItem); + this.ViewModel.ShowDrawer(new ArquivoDigitalDrawer(filtroArquivoDigital), 0, false); + } + else + { + await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", ValidationHelper.GetDescription((TipoArquivoDigital)4), "."), "OK", "", false); + } + } + + private void AbrirLog_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLog(3, this.ViewModel.SelectedItem.get_Id()); + } + + private void AbrirLogEmail_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLogEmail(3, this.ViewModel.SelectedItem.get_Id()); + } + + private void Alterar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Alterar(true); + } + + private void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelarAlteracao(); + } + + private void ContentLoad() + { + this.CoberturasRadioButton.Checked += new RoutedEventHandler(this.Documento_OnChecked); + this.MaisInformacoesRadioButton.Checked += new RoutedEventHandler(this.Documento_OnChecked); + } + + private void CopyCodItem(object sender, MouseButtonEventArgs e) + { + this.ViewModel.CodigoItem.CopyToClipboard(); + this.ViewModel.ToggleSnackBar(string.Concat("COPIADO - ", this.ViewModel.CodigoItem), true); + } + + private void Documento_OnChecked(object sender, RoutedEventArgs e) + { + RadioButton radioButton = (RadioButton)sender; + if (string.IsNullOrEmpty(radioButton.GroupName)) + { + return; + } + this.ViewModel.Descarregar(); + this.ContentControl.Visibility = System.Windows.Visibility.Collapsed; + this.MaisInformacoes.Visibility = System.Windows.Visibility.Collapsed; + this.MaisInformacoes.ClearInvalid(); + this.ContentControl.ClearInvalid(); + if (radioButton.Name == "MaisInformacoesRadioButton") + { + this.MaisInformacoes.Visibility = System.Windows.Visibility.Visible; + return; + } + this.ContentControl.Visibility = System.Windows.Visibility.Visible; + this.ViewModel.CarregaCobertura(); + } + + private async void Excluir_OnClick(object sender, RoutedEventArgs e) + { + await this.ViewModel.Excluir(); + MenuItemViewModel menuItemViewModel = this._menuItemViewModel; + if (menuItemViewModel != null) + { + menuItemViewModel.RecarregarItens(null); + } + else + { + } + } + + private async void Incluir_OnClick(object sender, RoutedEventArgs e) + { + await this.ViewModel.Incluir(false); + List> keyValuePairs = this.ViewModel.SelectedItem.Validate(); + this.ValidateFields(keyValuePairs, true); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/seguros/itens/aeronauticoview.xaml", UriKind.Relative)); + } + + public void Manter(ManutencaoItem manutencao) + { + this.ViewModel.Manter(ConsultaViewModel.ItemSelecionado, manutencao); + } + + private void MenuItem_OnClick(object sender, RoutedEventArgs e) + { + double? nullable = null; + double? nullable1 = nullable; + nullable = null; + (new HosterWindow(new SinistroView(this.ViewModel.SelectedItem, false), string.Concat("CADASTRO DE SINISTROS - ", this.ViewModel.SelectedItem.get_Descricao()), nullable1, nullable, false)).ShowDialog(); + MenuItemViewModel menuItemViewModel = this._menuItemViewModel; + if (menuItemViewModel == null) + { + return; + } + menuItemViewModel.RecarregarItens(this.ViewModel.SelectedItem); + } + + public async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.Loading(true); + List> keyValuePairs = await this.ViewModel.Salvar(); + this.ValidateFields(keyValuePairs, true); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + else if (this.ViewModel.SelectedItem.get_Id() > (long)0) + { + MenuItemViewModel menuItemViewModel = this._menuItemViewModel; + if (menuItemViewModel != null) + { + menuItemViewModel.RecarregarItens(this.ViewModel.SelectedItem); + } + else + { + } + } + } + + public async Task Selecionar(Item item) + { + await this.ViewModel.SelecionaItem(item, true); + } + + public void Substituir() + { + this.ViewModel.Substituir(ConsultaViewModel.ItemSelecionado); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.IncluirItemButton = (MenuItem)target; + this.IncluirItemButton.Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + case 2: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 3: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 4: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Excluir_OnClick); + return; + } + case 6: + { + ((TextBox)target).MouseDoubleClick += new MouseButtonEventHandler(this.CopyCodItem); + return; + } + case 7: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirAquivoDigital_Click); + return; + } + case 8: + { + this.SinistroButton = (MenuItem)target; + this.SinistroButton.Click += new RoutedEventHandler(this.MenuItem_OnClick); + return; + } + case 9: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick); + return; + } + case 10: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLogEmail_OnClick); + return; + } + case 11: + { + ((ComboBox)target).SelectionChanged += new SelectionChangedEventHandler(this.Tipo_OnSelectionChanged); + return; + } + case 12: + { + AeronauticoView aeronauticoView = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(aeronauticoView.SomenteNumeros); + return; + } + case 13: + { + AeronauticoView aeronauticoView1 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(aeronauticoView1.SomenteNumeros); + return; + } + case 14: + { + AeronauticoView aeronauticoView2 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(aeronauticoView2.SomenteNumeros); + return; + } + case 15: + { + AeronauticoView aeronauticoView3 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(aeronauticoView3.SomenteNumeros); + return; + } + case 16: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 17: + { + this.CoberturasRadioButton = (RadioButton)target; + return; + } + case 18: + { + this.MaisInformacoesRadioButton = (RadioButton)target; + return; + } + case 19: + { + this.ContentControl = (System.Windows.Controls.ContentControl)target; + return; + } + case 20: + { + this.MaisInformacoes = (CustomItemValidation)target; + return; + } + } + this._contentLoaded = true; + } + + private void Tipo_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + if (((ComboBox)sender).SelectedItem == null) + { + return; + } + if (ValidationHelper.GetCategory((TipoAeronautico)((ComboBox)sender).SelectedItem) == this._lastCategory) + { + return; + } + this.ViewModel.SelectedItem.get_Aeronautico().set_Tipo((TipoAeronautico)((ComboBox)sender).SelectedItem); + this.ViewModel.UpdateAero(); + this.ValidateFields(this.ViewModel.SelectedItem.Validate(), true); + this._lastCategory = ValidationHelper.GetCategory(this.ViewModel.SelectedItem.get_Aeronautico().get_Tipo()); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Seguros/Itens/AutoView.cs b/Codemerx/Gestor.Application/Views/Seguros/Itens/AutoView.cs new file mode 100644 index 0000000..4a9c3be --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Seguros/Itens/AutoView.cs @@ -0,0 +1,718 @@ +using Gestor.Application.Actions; +using Gestor.Application.Componentes; +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Application.ViewModels.Seguros.Itens; +using Gestor.Application.Views.Generic; +using Gestor.Application.Views.Seguros; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Views.Seguros.Itens +{ + public class AutoView : BaseUserControl, IComponentConnector + { + public AutoViewModel ViewModel; + + private readonly MenuItemViewModel _menuItemViewModel; + + internal MenuItem IncluirItemButton; + + internal MenuItem SinistroButton; + + internal WrapPanel PainelDadosAuto; + + internal TextBox FipeBox; + + internal AutoCompleteBox AutoCompleteFabricacao; + + internal TextBox ModeloBox; + + internal TextBox AnoModeloBox; + + internal TextBox CepCirculacaoBox; + + internal TextBox CepPernoiteBox; + + internal ComboBox ComboBoxTipoCorrecao; + + internal RadioButton CoberturasRadioButton; + + internal RadioButton MaisInformacoesRadioButton; + + internal System.Windows.Controls.ContentControl ContentControl; + + internal CustomItemValidation MaisInformacoes; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public AutoView(MenuItemViewModel menuItemViewModel, bool lockInsert = false, bool substituir = false, ManutencaoItem manutencao = null, Item itemSelecionado = null, Ramo ramo = null, bool endossoRenovacao = false) + { + this._menuItemViewModel = menuItemViewModel; + this.ViewModel = new AutoViewModel(substituir, manutencao, itemSelecionado, ramo, endossoRenovacao); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher != null) + { + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + else + { + } + if (!lockInsert) + { + return; + } + this.IncluirItemButton.IsEnabled = false; + this.SinistroButton.Visibility = System.Windows.Visibility.Collapsed; + } + + private async void AbrirAquivoDigital_Click(object sender, RoutedEventArgs e) + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 4).get_Consultar()) + { + FiltroArquivoDigital filtroArquivoDigital = new FiltroArquivoDigital(); + filtroArquivoDigital.set_Id(this.ViewModel.SelectedItem.get_Id()); + filtroArquivoDigital.set_IdApolice(this.ViewModel.SelectedItem.get_Documento().get_Id()); + filtroArquivoDigital.set_Tipo(4); + filtroArquivoDigital.set_Parente(this.ViewModel.SelectedItem); + this.ViewModel.ShowDrawer(new ArquivoDigitalDrawer(filtroArquivoDigital), 0, false); + } + else + { + await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", Gestor.Common.Validation.ValidationHelper.GetDescription((TipoArquivoDigital)4), "."), "OK", "", false); + } + } + + private void AbrirLog_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLog(3, this.ViewModel.SelectedItem.get_Id()); + } + + private void AbrirLogEmail_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLogEmail(3, this.ViewModel.SelectedItem.get_Id()); + } + + private void Alterar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Alterar(true); + } + + private void AutoCompleteFabricanteBox_Populating(object sender, PopulatingEventArgs e) + { + if (e.get_Parameter().Length < 3) + { + return; + } + e.set_Cancel(true); + this.ViewModel.BuscaFabricante(Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void BaixarXls_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.BaixarXls(); + } + + private async void BuscarModelo_OnClick(object sender, RoutedEventArgs e) + { + Fipe fipe = await this.ViewModel.ShowBuscaModeloDialog(this.ModeloBox.Text, this.AnoModeloBox.Text); + Fipe fipe1 = fipe; + if (fipe1 != null) + { + this.FipeBox.Text = fipe1.get_Codigo(); + this.ModeloBox.Text = fipe1.get_Modelo(); + this.AutoCompleteFabricacao.set_Text(fipe1.get_Marca()); + this.ViewModel.SelectedItem.get_Auto().set_Fabricante(this.ViewModel.Fabricantes.FirstOrDefault((Fabricante x) => x.get_Descricao() == fipe1.get_Marca())); + } + } + + private void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelarAlteracao(); + } + + private void Cep_OnLostFocus(object sender, RoutedEventArgs e) + { + bool auto; + TextBox textBox = (TextBox)sender; + Item selectedItem = this.ViewModel.SelectedItem; + if (selectedItem != null) + { + auto = selectedItem.get_Auto(); + } + else + { + auto = false; + } + if (!auto) + { + return; + } + if (string.IsNullOrWhiteSpace(textBox.Text)) + { + return; + } + if ((textBox.Name == "CepCirculacaoBox" || textBox.Name == "CepPernoiteBox") && Gestor.Common.Validation.ValidationHelper.ValidaCep(textBox.Text)) + { + return; + } + if (!Gestor.Model.Helper.ValidationHelper.ValidacaoCep(Gestor.Common.Validation.ValidationHelper.FormatPostCode(textBox.Text))) + { + return; + } + textBox.Text = Gestor.Common.Validation.ValidationHelper.FormatPostCode(textBox.Text); + } + + private void Ci_OnLostFocus(object sender, RoutedEventArgs e) + { + TextBox textBox = (TextBox)sender; + textBox.Text = Gestor.Common.Validation.ValidationHelper.FormatCi(textBox.Text); + } + + private void ComboBoxTipoCorrecao_SelectionChanged(object sender, SelectionChangedEventArgs e) + { + if (this.ComboBoxTipoCorrecao.SelectedItem == null) + { + return; + } + this.ViewModel.Atualiza(this.ComboBoxTipoCorrecao.SelectedItem.ToString().ToUpper()); + } + + private void ContentLoad() + { + this.CoberturasRadioButton.Checked += new RoutedEventHandler(this.Documento_OnChecked); + this.MaisInformacoesRadioButton.Checked += new RoutedEventHandler(this.Documento_OnChecked); + } + + private void CopyCodItem(object sender, MouseButtonEventArgs e) + { + this.ViewModel.CodigoItem.CopyToClipboard(); + this.ViewModel.ToggleSnackBar(string.Concat("COPIADO - ", this.ViewModel.CodigoItem), true); + } + + private void Documento_OnChecked(object sender, RoutedEventArgs e) + { + RadioButton radioButton = (RadioButton)sender; + if (string.IsNullOrEmpty(radioButton.GroupName)) + { + return; + } + this.ViewModel.Descarregar(); + this.ContentControl.Visibility = System.Windows.Visibility.Collapsed; + this.MaisInformacoes.Visibility = System.Windows.Visibility.Collapsed; + this.MaisInformacoes.ClearInvalid(); + this.ContentControl.ClearInvalid(); + if (radioButton.Name == "MaisInformacoesRadioButton") + { + this.MaisInformacoes.Visibility = System.Windows.Visibility.Visible; + return; + } + this.ContentControl.Visibility = System.Windows.Visibility.Visible; + this.ViewModel.CarregaCobertura(); + } + + private async void Excluir_OnClick(object sender, RoutedEventArgs e) + { + if (await this.ViewModel.Excluir()) + { + MenuItemViewModel menuItemViewModel = this._menuItemViewModel; + if (menuItemViewModel != null) + { + menuItemViewModel.RecarregarItens(null); + } + else + { + } + } + } + + private async void Fipe_LostFocus(object sender, RoutedEventArgs e) + { + int num; + bool auto; + object obj; + TextBox textBox = (TextBox)sender; + Item selectedItem = this.ViewModel.SelectedItem; + if (selectedItem != null) + { + auto = selectedItem.get_Auto(); + } + else + { + auto = false; + } + if (auto) + { + if (!string.IsNullOrWhiteSpace(textBox.Text)) + { + string str = Gestor.Model.Helper.ValidationHelper.FormataFipe(textBox.Text.Replace("-", "")); + if (Gestor.Model.Helper.ValidationHelper.ValidaFipe(str)) + { + textBox.Text = str; + if (!int.TryParse(Gestor.Model.Helper.ValidationHelper.OnlyNumber(str), out num) || num != 0) + { + Fipe fipe = await this.ViewModel.BuscaModelo(textBox.Text); + if (fipe != null) + { + this.ModeloBox.Text = fipe.get_Modelo(); + AutoCompleteBox autoCompleteFabricacao = this.AutoCompleteFabricacao; + List fabricantes = this.ViewModel.Fabricantes; + if (fabricantes != null) + { + obj = fabricantes.FirstOrDefault((Fabricante x) => x.get_Descricao() == fipe.get_Marca()); + } + else + { + obj = null; + } + autoCompleteFabricacao.set_SelectedItem(obj); + } + else + { + this.ViewModel.ToggleSnackBar(string.Concat("MODELO NÃO ENCONTRADO PARA O CÓDIGO FIPE ", textBox.Text), true); + } + } + } + } + } + textBox = null; + } + + private async void ImportarXls_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.Loading(true); + Action enablePesquisarClientes = Gestor.Application.Actions.Actions.EnablePesquisarClientes; + if (enablePesquisarClientes != null) + { + enablePesquisarClientes(false); + } + else + { + } + Action enableMenu = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu != null) + { + enableMenu(false); + } + else + { + } + Action enableMainMenu = Gestor.Application.Actions.Actions.EnableMainMenu; + if (enableMainMenu != null) + { + enableMainMenu(false); + } + else + { + } + List> keyValuePairs = await this.ViewModel.ImportarXls(); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + Action action = Gestor.Application.Actions.Actions.EnablePesquisarClientes; + if (action != null) + { + action(true); + } + else + { + } + Action enableMenu1 = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu1 != null) + { + enableMenu1(true); + } + else + { + } + Action enableMainMenu1 = Gestor.Application.Actions.Actions.EnableMainMenu; + if (enableMainMenu1 != null) + { + enableMainMenu1(true); + } + else + { + } + this.ViewModel.Loading(false); + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + else if (this.ViewModel.SelectedItem.get_Id() > (long)0) + { + MenuItemViewModel menuItemViewModel = this._menuItemViewModel; + if (menuItemViewModel != null) + { + menuItemViewModel.RecarregarItens(this.ViewModel.SelectedItem); + } + else + { + } + } + } + + private async void Incluir_OnClick(object sender, RoutedEventArgs e) + { + await this.ViewModel.Incluir(false); + Item selectedItem = this.ViewModel.SelectedItem; + List configuracoes = Recursos.Configuracoes; + bool flag = configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 18); + List configuracaoSistemas = Recursos.Configuracoes; + List> keyValuePairs = selectedItem.Validate(flag, configuracaoSistemas.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 27)); + this.ValidateFields(keyValuePairs, true); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/seguros/itens/autoview.xaml", UriKind.Relative)); + } + + private void KeyUpBase_OnKeyUp(object sender, KeyEventArgs e) + { + TextBox textBox = (TextBox)sender; + if (!Regex.IsMatch(textBox.Text.Replace(".", ""), "^[0-9.]{11}$")) + { + textBox.Text = Regex.Replace(textBox.Text, "[^\\d]*", ""); + } + } + + public void Manter(ManutencaoItem manutencao) + { + this.ViewModel.Manter(ConsultaViewModel.ItemSelecionado, manutencao); + } + + private void MenuItem_OnClick(object sender, RoutedEventArgs e) + { + double? nullable = null; + double? nullable1 = nullable; + nullable = null; + (new HosterWindow(new SinistroView(this.ViewModel.SelectedItem, false), string.Concat("CADASTRO DE SINISTROS - ", this.ViewModel.SelectedItem.get_Descricao()), nullable1, nullable, false)).ShowDialog(); + MenuItemViewModel menuItemViewModel = this._menuItemViewModel; + if (menuItemViewModel == null) + { + return; + } + menuItemViewModel.RecarregarItens(this.ViewModel.SelectedItem); + } + + private void Placa(object sender, KeyEventArgs e) + { + Gestor.Model.Helper.ValidationHelper.FormataPlaca(((TextBox)sender).Text); + } + + private void Renavam_OnLostFocus(object sender, RoutedEventArgs e) + { + TextBox textBox = (TextBox)sender; + textBox.Text = Gestor.Common.Validation.ValidationHelper.FormatRenavam(textBox.Text); + } + + public async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.Loading(true); + this.FipeBox.Focus(); + List> keyValuePairs = await this.ViewModel.Salvar(); + this.ValidateFields(keyValuePairs, true); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + else if (this.ViewModel.SelectedItem.get_Id() > (long)0) + { + MenuItemViewModel menuItemViewModel = this._menuItemViewModel; + if (menuItemViewModel != null) + { + menuItemViewModel.RecarregarItens(this.ViewModel.SelectedItem); + } + else + { + } + } + } + + public async Task Selecionar(Item item) + { + await this.ViewModel.SelecionaItem(item, true); + } + + private void SelecionaUsoVeiculo(object sender, SelectionChangedEventArgs e) + { + if (this.ViewModel.UsoVeiculo.GetValueOrDefault() == 2 || this.ViewModel.UsoVeiculo.GetValueOrDefault() == 3) + { + this.ViewModel.SelectedItem.get_Auto().set_Categoria(new Categoria?(3)); + } + } + + public void Substituir() + { + this.ViewModel.Substituir(ConsultaViewModel.ItemSelecionado); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.IncluirItemButton = (MenuItem)target; + this.IncluirItemButton.Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + case 2: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 3: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 4: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Excluir_OnClick); + return; + } + case 6: + { + ((TextBox)target).MouseDoubleClick += new MouseButtonEventHandler(this.CopyCodItem); + return; + } + case 7: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirAquivoDigital_Click); + return; + } + case 8: + { + this.SinistroButton = (MenuItem)target; + this.SinistroButton.Click += new RoutedEventHandler(this.MenuItem_OnClick); + return; + } + case 9: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick); + return; + } + case 10: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLogEmail_OnClick); + return; + } + case 11: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.ImportarXls_OnClick); + return; + } + case 12: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.BaixarXls_OnClick); + return; + } + case 13: + { + this.PainelDadosAuto = (WrapPanel)target; + return; + } + case 14: + { + this.FipeBox = (TextBox)target; + AutoView autoView = this; + this.FipeBox.PreviewTextInput += new TextCompositionEventHandler(autoView.SomenteNumeros); + this.FipeBox.LostFocus += new RoutedEventHandler(this.Fipe_LostFocus); + return; + } + case 15: + { + AutoView autoView1 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(autoView1.Placa); + ((TextBox)target).PreviewKeyDown += new KeyEventHandler(this.Placa); + return; + } + case 16: + { + this.AutoCompleteFabricacao = (AutoCompleteBox)target; + this.AutoCompleteFabricacao.add_Populating(new PopulatingEventHandler(this, AutoView.AutoCompleteFabricanteBox_Populating)); + return; + } + case 17: + { + this.ModeloBox = (TextBox)target; + return; + } + case 18: + { + ((Button)target).Click += new RoutedEventHandler(this.BuscarModelo_OnClick); + return; + } + case 19: + { + ((ComboBox)target).SelectionChanged += new SelectionChangedEventHandler(this.SelecionaUsoVeiculo); + return; + } + case 20: + { + AutoView autoView2 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(autoView2.SomenteNumeros); + ((TextBox)target).LostFocus += new RoutedEventHandler(this.Renavam_OnLostFocus); + ((TextBox)target).PreviewKeyUp += new KeyEventHandler(this.KeyUpBase_OnKeyUp); + return; + } + case 21: + { + ((ToggleButton)target).Checked += new RoutedEventHandler(this.ZeroKmToggleButton_Changed); + ((ToggleButton)target).Unchecked += new RoutedEventHandler(this.ZeroKmToggleButton_Changed); + return; + } + case 22: + { + AutoView autoView3 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(autoView3.SomenteNumeros); + return; + } + case 23: + { + this.AnoModeloBox = (TextBox)target; + AutoView autoView4 = this; + this.AnoModeloBox.PreviewTextInput += new TextCompositionEventHandler(autoView4.SomenteNumeros); + return; + } + case 24: + { + AutoView autoView5 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(autoView5.SomenteNumeros); + return; + } + case 25: + { + AutoView autoView6 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(autoView6.SomenteNumeros); + return; + } + case 26: + { + this.CepCirculacaoBox = (TextBox)target; + this.CepCirculacaoBox.LostFocus += new RoutedEventHandler(this.Cep_OnLostFocus); + AutoView autoView7 = this; + this.CepCirculacaoBox.PreviewTextInput += new TextCompositionEventHandler(autoView7.SomenteNumeros); + return; + } + case 27: + { + this.CepPernoiteBox = (TextBox)target; + this.CepPernoiteBox.LostFocus += new RoutedEventHandler(this.Cep_OnLostFocus); + AutoView autoView8 = this; + this.CepPernoiteBox.PreviewTextInput += new TextCompositionEventHandler(autoView8.SomenteNumeros); + return; + } + case 28: + { + this.ComboBoxTipoCorrecao = (ComboBox)target; + this.ComboBoxTipoCorrecao.SelectionChanged += new SelectionChangedEventHandler(this.ComboBoxTipoCorrecao_SelectionChanged); + return; + } + case 29: + { + ((TextBox)target).LostFocus += new RoutedEventHandler(this.Ci_OnLostFocus); + AutoView autoView9 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(autoView9.SomenteNumeros); + return; + } + case 30: + { + AutoView autoView10 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(autoView10.SomenteNumeros); + return; + } + case 31: + { + this.CoberturasRadioButton = (RadioButton)target; + return; + } + case 32: + { + this.MaisInformacoesRadioButton = (RadioButton)target; + return; + } + case 33: + { + this.ContentControl = (System.Windows.Controls.ContentControl)target; + return; + } + case 34: + { + this.MaisInformacoes = (CustomItemValidation)target; + return; + } + } + this._contentLoaded = true; + } + + private void ZeroKmToggleButton_Changed(object sender, RoutedEventArgs e) + { + if (this.ViewModel.SelectedItem == null) + { + return; + } + List> keyValuePairs = this.ViewModel.SelectedItem.Validate(); + this.ValidateFields(keyValuePairs, true); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Seguros/Itens/BuscarModeloView.cs b/Codemerx/Gestor.Application/Views/Seguros/Itens/BuscarModeloView.cs new file mode 100644 index 0000000..1f89612 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Seguros/Itens/BuscarModeloView.cs @@ -0,0 +1,85 @@ +using Gestor.Application.ViewModels.Seguros.Itens; +using Gestor.Application.Views.Generic; +using System; +using System.CodeDom.Compiler; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Markup; + +namespace Gestor.Application.Views.Seguros.Itens +{ + public class BuscarModeloView : BaseUserControl, IComponentConnector + { + internal DataGrid BuscaModeloGrid; + + private bool _contentLoaded; + + public BuscarModeloViewModel ViewModel + { + get; + set; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public BuscarModeloView(BuscarModeloViewModel viewModel) + { + this.ViewModel = viewModel; + base.DataContext = this.ViewModel; + this.InitializeComponent(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/seguros/itens/buscarmodeloview.xaml", UriKind.Relative)); + } + + private void Pesquisar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Pesquisar(); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + BuscarModeloView buscarModeloView = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(buscarModeloView.SomenteNumeros); + return; + } + case 2: + { + ((Button)target).Click += new RoutedEventHandler(this.Pesquisar_OnClick); + return; + } + case 3: + { + this.BuscaModeloGrid = (DataGrid)target; + return; + } + } + this._contentLoaded = true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Seguros/Itens/ConsorcioView.cs b/Codemerx/Gestor.Application/Views/Seguros/Itens/ConsorcioView.cs new file mode 100644 index 0000000..3b14a0c --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Seguros/Itens/ConsorcioView.cs @@ -0,0 +1,320 @@ +using Gestor.Application.Componentes; +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Application.ViewModels.Seguros.Itens; +using Gestor.Application.Views.Generic; +using Gestor.Application.Views.Seguros; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Views.Seguros.Itens +{ + public class ConsorcioView : BaseUserControl, IComponentConnector + { + public ConsorcioViewModel ViewModel; + + private readonly MenuItemViewModel _menuItemViewModel; + + private bool _salvando; + + internal MenuItem IncluirItemButton; + + internal MenuItem SinistroButton; + + internal RadioButton CoberturasRadioButton; + + internal RadioButton MaisInformacoesRadioButton; + + internal System.Windows.Controls.ContentControl ContentControl; + + internal CustomItemValidation MaisInformacoes; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public ConsorcioView(MenuItemViewModel menuItemViewModel, bool lockInsert = false, bool substituir = false, ManutencaoItem manutencao = null, Item itemSelecionado = null, Ramo ramo = null, bool endossoRenovacao = false) + { + this._menuItemViewModel = menuItemViewModel; + this.ViewModel = new ConsorcioViewModel(substituir, manutencao, itemSelecionado, ramo, endossoRenovacao); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher != null) + { + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + else + { + } + if (!lockInsert) + { + return; + } + this.IncluirItemButton.IsEnabled = false; + this.SinistroButton.Visibility = System.Windows.Visibility.Collapsed; + } + + private async void AbrirAquivoDigital_Click(object sender, RoutedEventArgs e) + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 4).get_Consultar()) + { + FiltroArquivoDigital filtroArquivoDigital = new FiltroArquivoDigital(); + filtroArquivoDigital.set_Id(this.ViewModel.SelectedItem.get_Id()); + filtroArquivoDigital.set_IdApolice(this.ViewModel.SelectedItem.get_Documento().get_Id()); + filtroArquivoDigital.set_Tipo(4); + filtroArquivoDigital.set_Parente(this.ViewModel.SelectedItem); + this.ViewModel.ShowDrawer(new ArquivoDigitalDrawer(filtroArquivoDigital), 0, false); + } + else + { + await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", ValidationHelper.GetDescription((TipoArquivoDigital)4), "."), "OK", "", false); + } + } + + private void AbrirLog_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLog(3, this.ViewModel.SelectedItem.get_Id()); + } + + private void AbrirLogEmail_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLogEmail(3, this.ViewModel.SelectedItem.get_Id()); + } + + private void Alterar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Alterar(true); + } + + private void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelarAlteracao(); + } + + private void ContentLoad() + { + this.CoberturasRadioButton.Checked += new RoutedEventHandler(this.Documento_OnChecked); + this.MaisInformacoesRadioButton.Checked += new RoutedEventHandler(this.Documento_OnChecked); + } + + private void CopyCodItem(object sender, MouseButtonEventArgs e) + { + this.ViewModel.CodigoItem.CopyToClipboard(); + this.ViewModel.ToggleSnackBar(string.Concat("COPIADO - ", this.ViewModel.CodigoItem), true); + } + + private void Documento_OnChecked(object sender, RoutedEventArgs e) + { + RadioButton radioButton = (RadioButton)sender; + if (string.IsNullOrEmpty(radioButton.GroupName)) + { + return; + } + this.ViewModel.Descarregar(); + this.ContentControl.Visibility = System.Windows.Visibility.Collapsed; + this.MaisInformacoes.Visibility = System.Windows.Visibility.Collapsed; + this.MaisInformacoes.ClearInvalid(); + this.ContentControl.ClearInvalid(); + if (radioButton.Name == "MaisInformacoesRadioButton") + { + this.MaisInformacoes.Visibility = System.Windows.Visibility.Visible; + return; + } + this.ContentControl.Visibility = System.Windows.Visibility.Visible; + this.ViewModel.CarregaCobertura(); + } + + private async void Excluir_OnClick(object sender, RoutedEventArgs e) + { + await this.ViewModel.Excluir(); + MenuItemViewModel menuItemViewModel = this._menuItemViewModel; + if (menuItemViewModel != null) + { + menuItemViewModel.RecarregarItens(null); + } + else + { + } + } + + private async void Incluir_OnClick(object sender, RoutedEventArgs e) + { + await this.ViewModel.Incluir(false); + List> keyValuePairs = this.ViewModel.SelectedItem.Validate(); + this.ValidateFields(keyValuePairs, true); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/seguros/itens/consorcioview.xaml", UriKind.Relative)); + } + + public void Manter(ManutencaoItem manutencao) + { + this.ViewModel.Manter(ConsultaViewModel.ItemSelecionado, manutencao); + } + + private void MenuItem_OnClick(object sender, RoutedEventArgs e) + { + double? nullable = null; + double? nullable1 = nullable; + nullable = null; + (new HosterWindow(new SinistroView(this.ViewModel.SelectedItem, false), string.Concat("CADASTRO DE SINISTROS - ", this.ViewModel.SelectedItem.get_Descricao()), nullable1, nullable, false)).ShowDialog(); + MenuItemViewModel menuItemViewModel = this._menuItemViewModel; + if (menuItemViewModel == null) + { + return; + } + menuItemViewModel.RecarregarItens(this.ViewModel.SelectedItem); + } + + public async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.Loading(true); + List> keyValuePairs = await this.ViewModel.Salvar(); + this.ValidateFields(keyValuePairs, true); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + else if (this.ViewModel.SelectedItem.get_Id() > (long)0) + { + MenuItemViewModel menuItemViewModel = this._menuItemViewModel; + if (menuItemViewModel != null) + { + menuItemViewModel.RecarregarItens(this.ViewModel.SelectedItem); + } + else + { + } + } + } + + public async Task Selecionar(Item item) + { + await this.ViewModel.SelecionaItem(item, true); + } + + public void Substituir() + { + this.ViewModel.Substituir(ConsultaViewModel.ItemSelecionado); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.IncluirItemButton = (MenuItem)target; + this.IncluirItemButton.Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + case 2: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 3: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 4: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Excluir_OnClick); + return; + } + case 6: + { + ((TextBox)target).MouseDoubleClick += new MouseButtonEventHandler(this.CopyCodItem); + return; + } + case 7: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirAquivoDigital_Click); + return; + } + case 8: + { + this.SinistroButton = (MenuItem)target; + this.SinistroButton.Click += new RoutedEventHandler(this.MenuItem_OnClick); + return; + } + case 9: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick); + return; + } + case 10: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLogEmail_OnClick); + return; + } + case 11: + { + this.CoberturasRadioButton = (RadioButton)target; + return; + } + case 12: + { + this.MaisInformacoesRadioButton = (RadioButton)target; + return; + } + case 13: + { + this.ContentControl = (System.Windows.Controls.ContentControl)target; + return; + } + case 14: + { + this.MaisInformacoes = (CustomItemValidation)target; + return; + } + } + this._contentLoaded = true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Seguros/Itens/GranizoView.cs b/Codemerx/Gestor.Application/Views/Seguros/Itens/GranizoView.cs new file mode 100644 index 0000000..9382fe6 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Seguros/Itens/GranizoView.cs @@ -0,0 +1,383 @@ +using Gestor.Application.Componentes; +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Application.ViewModels.Seguros.Itens; +using Gestor.Application.Views.Generic; +using Gestor.Application.Views.Seguros; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Views.Seguros.Itens +{ + public class GranizoView : BaseUserControl, IComponentConnector + { + public GranizoViewModel ViewModel; + + private readonly MenuItemViewModel _menuItemViewModel; + + internal MenuItem IncluirItemButton; + + internal MenuItem SinistroButton; + + internal TextBox CepBox; + + internal TextBox EnderecoBox; + + internal TextBox BairroBox; + + internal TextBox CidadeBox; + + internal TextBox EstadoBox; + + internal RadioButton CoberturasRadioButton; + + internal RadioButton MaisInformacoesRadioButton; + + internal System.Windows.Controls.ContentControl ContentControl; + + internal CustomItemValidation MaisInformacoes; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public GranizoView(MenuItemViewModel menuItemViewModel, bool lockInsert = false, bool substituir = false, ManutencaoItem manutencao = null, Item itemSelecionado = null, Ramo ramo = null, bool endossoRenovacao = false) + { + this._menuItemViewModel = menuItemViewModel; + this.ViewModel = new GranizoViewModel(substituir, manutencao, itemSelecionado, ramo, endossoRenovacao); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher != null) + { + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + else + { + } + if (!lockInsert) + { + return; + } + this.IncluirItemButton.IsEnabled = false; + this.SinistroButton.Visibility = System.Windows.Visibility.Collapsed; + } + + private async void AbrirAquivoDigital_Click(object sender, RoutedEventArgs e) + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 4).get_Consultar()) + { + FiltroArquivoDigital filtroArquivoDigital = new FiltroArquivoDigital(); + filtroArquivoDigital.set_Id(this.ViewModel.SelectedItem.get_Id()); + filtroArquivoDigital.set_IdApolice(this.ViewModel.SelectedItem.get_Documento().get_Id()); + filtroArquivoDigital.set_Tipo(4); + filtroArquivoDigital.set_Parente(this.ViewModel.SelectedItem); + this.ViewModel.ShowDrawer(new ArquivoDigitalDrawer(filtroArquivoDigital), 0, false); + } + else + { + await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", ValidationHelper.GetDescription((TipoArquivoDigital)4), "."), "OK", "", false); + } + } + + private void AbrirLog_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLog(3, this.ViewModel.SelectedItem.get_Id()); + } + + private void AbrirLogEmail_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLogEmail(3, this.ViewModel.SelectedItem.get_Id()); + } + + private void Alterar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Alterar(true); + } + + private void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelarAlteracao(); + } + + private void ContentLoad() + { + this.CoberturasRadioButton.Checked += new RoutedEventHandler(this.Documento_OnChecked); + this.MaisInformacoesRadioButton.Checked += new RoutedEventHandler(this.Documento_OnChecked); + } + + private void CopyCodItem(object sender, MouseButtonEventArgs e) + { + this.ViewModel.CodigoItem.CopyToClipboard(); + this.ViewModel.ToggleSnackBar(string.Concat("COPIADO - ", this.ViewModel.CodigoItem), true); + } + + private void Documento_OnChecked(object sender, RoutedEventArgs e) + { + RadioButton radioButton = (RadioButton)sender; + if (string.IsNullOrEmpty(radioButton.GroupName)) + { + return; + } + this.ViewModel.Descarregar(); + this.ContentControl.Visibility = System.Windows.Visibility.Collapsed; + this.MaisInformacoes.Visibility = System.Windows.Visibility.Collapsed; + this.MaisInformacoes.ClearInvalid(); + this.ContentControl.ClearInvalid(); + if (radioButton.Name == "MaisInformacoesRadioButton") + { + this.MaisInformacoes.Visibility = System.Windows.Visibility.Visible; + return; + } + this.ContentControl.Visibility = System.Windows.Visibility.Visible; + this.ViewModel.CarregaCobertura(); + } + + private async void Excluir_OnClick(object sender, RoutedEventArgs e) + { + if (await this.ViewModel.Excluir()) + { + MenuItemViewModel menuItemViewModel = this._menuItemViewModel; + if (menuItemViewModel != null) + { + menuItemViewModel.RecarregarItens(null); + } + else + { + } + } + } + + private async void Incluir_OnClick(object sender, RoutedEventArgs e) + { + await this.ViewModel.IncluirItem(false); + List> keyValuePairs = this.ViewModel.SelectedItem.Validate(); + this.ValidateFields(keyValuePairs, true); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/seguros/itens/granizoview.xaml", UriKind.Relative)); + } + + public void Manter(ManutencaoItem manutencao) + { + this.ViewModel.Manter(ConsultaViewModel.ItemSelecionado, manutencao); + } + + private void MenuItem_OnClick(object sender, RoutedEventArgs e) + { + double? nullable = null; + double? nullable1 = nullable; + nullable = null; + (new HosterWindow(new SinistroView(this.ViewModel.SelectedItem, false), string.Concat("CADASTRO DE SINISTROS - ", this.ViewModel.SelectedItem.get_Descricao()), nullable1, nullable, false)).ShowDialog(); + MenuItemViewModel menuItemViewModel = this._menuItemViewModel; + if (menuItemViewModel == null) + { + return; + } + menuItemViewModel.RecarregarItens(this.ViewModel.SelectedItem); + } + + private async void PostcodeBox_OnLostFocus(object sender, RoutedEventArgs e) + { + TextBox textBox = (TextBox)sender; + if (!string.IsNullOrWhiteSpace(textBox.Text)) + { + string str = ValidationHelper.FormatPostCode(textBox.Text); + this.CepBox.Text = str; + if (ValidationHelper.ValidatePostCode(str)) + { + EnderecoBase enderecoBase = await this.ViewModel.BuscaCep(str); + if (enderecoBase != null) + { + this.EnderecoBox.Text = enderecoBase.get_Endereco(); + this.CidadeBox.Text = enderecoBase.get_Cidade(); + this.EstadoBox.Text = enderecoBase.get_Estado(); + this.BairroBox.Text = enderecoBase.get_Bairro(); + } + } + } + } + + public async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.Loading(true); + List> keyValuePairs = await this.ViewModel.Salvar(); + this.ValidateFields(keyValuePairs, true); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + else if (this.ViewModel.SelectedItem.get_Id() > (long)0) + { + MenuItemViewModel menuItemViewModel = this._menuItemViewModel; + if (menuItemViewModel != null) + { + menuItemViewModel.RecarregarItens(this.ViewModel.SelectedItem); + } + else + { + } + } + } + + public async Task Selecionar(Item item) + { + await this.ViewModel.SelecionaItem(item, true); + } + + public void Substituir() + { + this.ViewModel.Substituir(ConsultaViewModel.ItemSelecionado); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.IncluirItemButton = (MenuItem)target; + this.IncluirItemButton.Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + case 2: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 3: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 4: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Excluir_OnClick); + return; + } + case 6: + { + ((TextBox)target).MouseDoubleClick += new MouseButtonEventHandler(this.CopyCodItem); + return; + } + case 7: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirAquivoDigital_Click); + return; + } + case 8: + { + this.SinistroButton = (MenuItem)target; + this.SinistroButton.Click += new RoutedEventHandler(this.MenuItem_OnClick); + return; + } + case 9: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick); + return; + } + case 10: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLogEmail_OnClick); + return; + } + case 11: + { + this.CepBox = (TextBox)target; + this.CepBox.LostFocus += new RoutedEventHandler(this.PostcodeBox_OnLostFocus); + return; + } + case 12: + { + this.EnderecoBox = (TextBox)target; + return; + } + case 13: + { + GranizoView granizoView = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(granizoView.SomenteNumeros); + return; + } + case 14: + { + this.BairroBox = (TextBox)target; + return; + } + case 15: + { + this.CidadeBox = (TextBox)target; + return; + } + case 16: + { + this.EstadoBox = (TextBox)target; + return; + } + case 17: + { + this.CoberturasRadioButton = (RadioButton)target; + return; + } + case 18: + { + this.MaisInformacoesRadioButton = (RadioButton)target; + return; + } + case 19: + { + this.ContentControl = (System.Windows.Controls.ContentControl)target; + return; + } + case 20: + { + this.MaisInformacoes = (CustomItemValidation)target; + return; + } + } + this._contentLoaded = true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Seguros/Itens/PatrimonialView.cs b/Codemerx/Gestor.Application/Views/Seguros/Itens/PatrimonialView.cs new file mode 100644 index 0000000..42e03ce --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Seguros/Itens/PatrimonialView.cs @@ -0,0 +1,466 @@ +using Gestor.Application.Componentes; +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Application.ViewModels.Seguros.Itens; +using Gestor.Application.Views.Generic; +using Gestor.Application.Views.Seguros; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Views.Seguros.Itens +{ + public class PatrimonialView : BaseUserControl, IComponentConnector + { + public PatrimonialViewModel ViewModel; + + private readonly MenuItemViewModel _menuItemViewModel; + + internal MenuItem IncluirItemButton; + + internal MenuItem SinistroButton; + + internal TextBox CepBox; + + internal TextBox EnderecoBox; + + internal TextBox BairroBox; + + internal TextBox CidadeBox; + + internal TextBox EstadoBox; + + internal RadioButton CoberturasRadioButton; + + internal RadioButton MaisInformacoesRadioButton; + + internal System.Windows.Controls.ContentControl ContentControl; + + internal CustomItemValidation MaisInformacoes; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public PatrimonialView(MenuItemViewModel menuItemViewModel, bool lockInsert = false, bool substituir = false, ManutencaoItem manutencao = null, Item itemSelecionado = null, Ramo ramo = null, bool endossoRenovacao = false) + { + this._menuItemViewModel = menuItemViewModel; + this.ViewModel = new PatrimonialViewModel(substituir, manutencao, itemSelecionado, ramo, endossoRenovacao); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher != null) + { + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + else + { + } + if (!lockInsert) + { + return; + } + this.IncluirItemButton.IsEnabled = false; + this.SinistroButton.Visibility = System.Windows.Visibility.Collapsed; + } + + private async void AbrirAquivoDigital_Click(object sender, RoutedEventArgs e) + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 4).get_Consultar()) + { + FiltroArquivoDigital filtroArquivoDigital = new FiltroArquivoDigital(); + filtroArquivoDigital.set_Id(this.ViewModel.SelectedItem.get_Id()); + filtroArquivoDigital.set_IdApolice(this.ViewModel.SelectedItem.get_Documento().get_Id()); + filtroArquivoDigital.set_Tipo(4); + filtroArquivoDigital.set_Parente(this.ViewModel.SelectedItem); + this.ViewModel.ShowDrawer(new ArquivoDigitalDrawer(filtroArquivoDigital), 0, false); + } + else + { + await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", ValidationHelper.GetDescription((TipoArquivoDigital)4), "."), "OK", "", false); + } + } + + private void AbrirLog_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLog(3, this.ViewModel.SelectedItem.get_Id()); + } + + private void AbrirLogEmail_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLogEmail(3, this.ViewModel.SelectedItem.get_Id()); + } + + private void Alterar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Alterar(true); + } + + private void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelarAlteracao(); + } + + private void ContentLoad() + { + this.CoberturasRadioButton.Checked += new RoutedEventHandler(this.Documento_OnChecked); + this.MaisInformacoesRadioButton.Checked += new RoutedEventHandler(this.Documento_OnChecked); + } + + private void CopyCodItem(object sender, MouseButtonEventArgs e) + { + this.ViewModel.CodigoItem.CopyToClipboard(); + this.ViewModel.ToggleSnackBar(string.Concat("COPIADO - ", this.ViewModel.CodigoItem), true); + } + + private void CpfBox_OnLostFocus(object sender, RoutedEventArgs e) + { + TextBox textBox = (TextBox)sender; + textBox.Text = ValidationHelper.FormatDocument(textBox.Text); + } + + private void Documento_OnChecked(object sender, RoutedEventArgs e) + { + RadioButton radioButton = (RadioButton)sender; + if (string.IsNullOrEmpty(radioButton.GroupName)) + { + return; + } + this.ViewModel.Descarregar(); + this.ContentControl.Visibility = System.Windows.Visibility.Collapsed; + this.MaisInformacoes.Visibility = System.Windows.Visibility.Collapsed; + this.MaisInformacoes.ClearInvalid(); + this.ContentControl.ClearInvalid(); + if (radioButton.Name == "MaisInformacoesRadioButton") + { + this.MaisInformacoes.Visibility = System.Windows.Visibility.Visible; + return; + } + this.ContentControl.Visibility = System.Windows.Visibility.Visible; + this.ViewModel.CarregaCobertura(); + } + + private async void Excluir_OnClick(object sender, RoutedEventArgs e) + { + if (await this.ViewModel.Excluir()) + { + MenuItemViewModel menuItemViewModel = this._menuItemViewModel; + if (menuItemViewModel != null) + { + menuItemViewModel.RecarregarItens(null); + } + else + { + } + } + } + + private async void Incluir_OnClick(object sender, RoutedEventArgs e) + { + await this.ViewModel.Incluir(false); + List> keyValuePairs = this.ViewModel.SelectedItem.Validate(); + this.ValidateFields(keyValuePairs, true); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/seguros/itens/patrimonialview.xaml", UriKind.Relative)); + } + + public void Manter(ManutencaoItem manutencao) + { + this.ViewModel.Manter(ConsultaViewModel.ItemSelecionado, manutencao); + } + + private void MenuItem_OnClick(object sender, RoutedEventArgs e) + { + double? nullable = null; + double? nullable1 = nullable; + nullable = null; + (new HosterWindow(new SinistroView(this.ViewModel.SelectedItem, false), string.Concat("CADASTRO DE SINISTROS - ", this.ViewModel.SelectedItem.get_Descricao()), nullable1, nullable, false)).ShowDialog(); + MenuItemViewModel menuItemViewModel = this._menuItemViewModel; + if (menuItemViewModel == null) + { + return; + } + menuItemViewModel.RecarregarItens(this.ViewModel.SelectedItem); + } + + private async void PostcodeBox_OnLostFocus(object sender, RoutedEventArgs e) + { + TextBox textBox = (TextBox)sender; + if (!string.IsNullOrWhiteSpace(textBox.Text)) + { + string str = ValidationHelper.FormatPostCode(textBox.Text); + if (ValidationHelper.ValidatePostCode(str)) + { + this.CepBox.Text = str; + EnderecoBase enderecoBase = await this.ViewModel.BuscaCep(str); + if (enderecoBase != null) + { + this.EnderecoBox.Text = enderecoBase.get_Endereco(); + this.CidadeBox.Text = enderecoBase.get_Cidade(); + this.EstadoBox.Text = enderecoBase.get_Estado(); + this.BairroBox.Text = enderecoBase.get_Bairro(); + } + } + } + } + + public async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.Loading(true); + List> keyValuePairs = await this.ViewModel.Salvar(); + this.ValidateFields(keyValuePairs, true); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + else if (this.ViewModel.SelectedItem.get_Id() > (long)0) + { + MenuItemViewModel menuItemViewModel = this._menuItemViewModel; + if (menuItemViewModel != null) + { + menuItemViewModel.RecarregarItens(this.ViewModel.SelectedItem); + } + else + { + } + } + } + + public async Task Selecionar(Item item) + { + await this.ViewModel.SelecionaItem(item, true); + } + + public void Substituir() + { + this.ViewModel.Substituir(ConsultaViewModel.ItemSelecionado); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.IncluirItemButton = (MenuItem)target; + this.IncluirItemButton.Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + case 2: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 3: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 4: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Excluir_OnClick); + return; + } + case 6: + { + ((TextBox)target).MouseDoubleClick += new MouseButtonEventHandler(this.CopyCodItem); + return; + } + case 7: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirAquivoDigital_Click); + return; + } + case 8: + { + this.SinistroButton = (MenuItem)target; + this.SinistroButton.Click += new RoutedEventHandler(this.MenuItem_OnClick); + return; + } + case 9: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick); + return; + } + case 10: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLogEmail_OnClick); + return; + } + case 11: + { + this.CepBox = (TextBox)target; + this.CepBox.LostFocus += new RoutedEventHandler(this.PostcodeBox_OnLostFocus); + return; + } + case 12: + { + this.EnderecoBox = (TextBox)target; + return; + } + case 13: + { + PatrimonialView patrimonialView = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(patrimonialView.SomenteNumeros); + return; + } + case 14: + { + this.BairroBox = (TextBox)target; + return; + } + case 15: + { + this.CidadeBox = (TextBox)target; + return; + } + case 16: + { + this.EstadoBox = (TextBox)target; + return; + } + case 17: + { + PatrimonialView patrimonialView1 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(patrimonialView1.SomenteNumeros); + return; + } + case 18: + { + PatrimonialView patrimonialView2 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(patrimonialView2.SomenteNumeros); + PatrimonialView patrimonialView3 = this; + ((TextBox)target).LostFocus += new RoutedEventHandler(patrimonialView3.FormatarTelefone); + return; + } + case 19: + { + PatrimonialView patrimonialView4 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(patrimonialView4.SomenteNumeros); + ((TextBox)target).LostFocus += new RoutedEventHandler(this.CpfBox_OnLostFocus); + return; + } + case 20: + { + PatrimonialView patrimonialView5 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(patrimonialView5.SomenteNumeros); + return; + } + case 21: + { + PatrimonialView patrimonialView6 = this; + ((TextBox)target).LostFocus += new RoutedEventHandler(patrimonialView6.FormatarTelefone); + PatrimonialView patrimonialView7 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(patrimonialView7.SomenteNumeros); + return; + } + case 22: + { + PatrimonialView patrimonialView8 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(patrimonialView8.SomenteNumeros); + ((TextBox)target).LostFocus += new RoutedEventHandler(this.CpfBox_OnLostFocus); + return; + } + case 23: + { + PatrimonialView patrimonialView9 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(patrimonialView9.SomenteNumeros); + return; + } + case 24: + { + PatrimonialView patrimonialView10 = this; + ((TextBox)target).LostFocus += new RoutedEventHandler(patrimonialView10.FormatarTelefone); + PatrimonialView patrimonialView11 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(patrimonialView11.SomenteNumeros); + return; + } + case 25: + { + PatrimonialView patrimonialView12 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(patrimonialView12.SomenteNumeros); + ((TextBox)target).LostFocus += new RoutedEventHandler(this.CpfBox_OnLostFocus); + return; + } + case 26: + { + PatrimonialView patrimonialView13 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(patrimonialView13.SomenteNumeros); + return; + } + case 27: + { + PatrimonialView patrimonialView14 = this; + ((TextBox)target).LostFocus += new RoutedEventHandler(patrimonialView14.FormatarTelefone); + PatrimonialView patrimonialView15 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(patrimonialView15.SomenteNumeros); + return; + } + case 28: + { + this.CoberturasRadioButton = (RadioButton)target; + return; + } + case 29: + { + this.MaisInformacoesRadioButton = (RadioButton)target; + return; + } + case 30: + { + this.ContentControl = (System.Windows.Controls.ContentControl)target; + return; + } + case 31: + { + this.MaisInformacoes = (CustomItemValidation)target; + return; + } + } + this._contentLoaded = true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Seguros/Itens/RiscosDiversosView.cs b/Codemerx/Gestor.Application/Views/Seguros/Itens/RiscosDiversosView.cs new file mode 100644 index 0000000..70a30b9 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Seguros/Itens/RiscosDiversosView.cs @@ -0,0 +1,683 @@ +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Application.ViewModels.Seguros.Itens; +using Gestor.Application.Views.Generic; +using Gestor.Application.Views.Seguros; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Data; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Views.Seguros.Itens +{ + public class RiscosDiversosView : BaseUserControl, IComponentConnector, IStyleConnector + { + public RiscosDiversosViewModel ViewModel; + + private readonly MenuItemViewModel _menuItemViewModel; + + private bool _salvando; + + internal MenuItem IncluirItemButton; + + internal MenuItem SinistroButton; + + internal RadioButton CoberturasRadioButton; + + internal RadioButton MaisInformacoesRadioButton; + + internal Menu BotoesTitulares; + + internal Separator SeparadorMaisInformacoes; + + internal System.Windows.Controls.ContentControl ContentControl; + + internal DataGrid DataGridTitulares; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public RiscosDiversosView(MenuItemViewModel menuItemViewModel, bool lockInsert = false, bool substituir = false, ManutencaoItem manutencao = null, Item itemSelecionado = null, Ramo ramo = null, bool endossoRenovacao = false) + { + this._menuItemViewModel = menuItemViewModel; + this.ViewModel = new RiscosDiversosViewModel(substituir, manutencao, itemSelecionado, ramo, endossoRenovacao); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher != null) + { + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + else + { + } + if (!lockInsert) + { + return; + } + this.IncluirItemButton.IsEnabled = false; + this.SinistroButton.Visibility = System.Windows.Visibility.Collapsed; + } + + private async void AbrirAquivoDigital_Click(object sender, RoutedEventArgs e) + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 4).get_Consultar()) + { + FiltroArquivoDigital filtroArquivoDigital = new FiltroArquivoDigital(); + filtroArquivoDigital.set_Id(this.ViewModel.SelectedItem.get_Id()); + filtroArquivoDigital.set_IdApolice(this.ViewModel.SelectedItem.get_Documento().get_Id()); + filtroArquivoDigital.set_Tipo(4); + filtroArquivoDigital.set_Parente(this.ViewModel.SelectedItem); + this.ViewModel.ShowDrawer(new ArquivoDigitalDrawer(filtroArquivoDigital), 0, false); + } + else + { + await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", ValidationHelper.GetDescription((TipoArquivoDigital)4), "."), "OK", "", false); + } + } + + private void AbrirLog_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLog(3, this.ViewModel.SelectedItem.get_Id()); + } + + private void AbrirLogEmail_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLogEmail(3, this.ViewModel.SelectedItem.get_Id()); + } + + private void Alterar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Alterar(true); + } + + private void AlterarTitular_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AlterarTitular(); + } + + private void AplicarTitular_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AplicarTitular(); + } + + private void AutoCompleteBox_Populating(object sender, PopulatingEventArgs e) + { + if (e.get_Parameter().Trim().Length < 3) + { + return; + } + e.set_Cancel(true); + this.ViewModel.BuscarTitulares(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void BotoesTitulares_OnIsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e) + { + bool flag; + if (!((Menu)sender).IsEnabled) + { + this.ViewModel.AlteracaoTitularesVisibility = System.Windows.Visibility.Collapsed; + } + DataGrid dataGridTitulares = this.DataGridTitulares; + if (dataGridTitulares != null) + { + flag = dataGridTitulares.Columns.First(); + } + else + { + flag = false; + } + if (!flag) + { + return; + } + this.DataGridTitulares.Columns.First().Visibility = (((Menu)sender).IsEnabled ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + } + + private void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelarAlteracao(); + } + + private void ContentLoad() + { + this.CoberturasRadioButton.Checked += new RoutedEventHandler(this.Documento_OnChecked); + this.MaisInformacoesRadioButton.Checked += new RoutedEventHandler(this.Documento_OnChecked); + } + + private void CopyCodItem(object sender, MouseButtonEventArgs e) + { + this.ViewModel.CodigoItem.CopyToClipboard(); + this.ViewModel.ToggleSnackBar(string.Concat("COPIADO - ", this.ViewModel.CodigoItem), true); + } + + private void DataGridTitulares_OnCellEditEnding(object sender, DataGridCellEditEndingEventArgs e) + { + string text; + string str; + string text1; + if (!(e.EditingElement is TextBox)) + { + return; + } + TextBox editingElement = e.EditingElement as TextBox; + string stringFormat = e.Column.ClipboardContentBinding.StringFormat; + if (stringFormat == "d") + { + if (editingElement != null) + { + text = editingElement.Text; + } + else + { + text = null; + } + if (!string.IsNullOrEmpty(text)) + { + editingElement.Text = ValidationHelper.FormatDate(editingElement.Text); + return; + } + if (editingElement != null) + { + editingElement.Text = null; + return; + } + } + else if (stringFormat == "c") + { + if (editingElement != null) + { + str = editingElement.Text; + } + else + { + str = null; + } + if (!string.IsNullOrEmpty(str)) + { + editingElement.Text = ValidationHelper.FormatCurrency(editingElement.Text); + return; + } + if (editingElement != null) + { + editingElement.Text = null; + } + } + else + { + if (editingElement != null) + { + text1 = editingElement.Text; + } + else + { + text1 = null; + } + if (!string.IsNullOrEmpty(text1)) + { + if (e.Column.SortMemberPath == "Cpf") + { + editingElement.Text = ValidationHelper.FormatDocument(editingElement.Text); + return; + } + } + else if (editingElement != null) + { + editingElement.Text = null; + return; + } + } + } + + private void Dependente_CellLoaded(object sender, RoutedEventArgs e) + { + bool valueOrDefault; + if (sender == null) + { + return; + } + DataGridCell dataGridCell = (DataGridCell)sender; + TitularesVida dataContext = (TitularesVida)((DataGridCell)sender).DataContext; + if (dataContext != null) + { + valueOrDefault = dataContext.get_Tipo().GetValueOrDefault() == 2; + } + else + { + valueOrDefault = false; + } + dataGridCell.Visibility = (valueOrDefault ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + } + + private void Documento_OnChecked(object sender, RoutedEventArgs e) + { + RadioButton radioButton = (RadioButton)sender; + if (string.IsNullOrEmpty(radioButton.GroupName)) + { + return; + } + this.ViewModel.Descarregar(); + this.ContentControl.Visibility = System.Windows.Visibility.Collapsed; + this.DataGridTitulares.Visibility = System.Windows.Visibility.Collapsed; + this.SeparadorMaisInformacoes.Visibility = System.Windows.Visibility.Collapsed; + this.BotoesTitulares.Visibility = System.Windows.Visibility.Collapsed; + this.DataGridTitulares.ClearInvalid(); + this.ContentControl.ClearInvalid(); + if (radioButton.Name != "MaisInformacoesRadioButton") + { + this.ContentControl.Visibility = System.Windows.Visibility.Visible; + this.ViewModel.CarregaCobertura(); + return; + } + this.SeparadorMaisInformacoes.Visibility = System.Windows.Visibility.Visible; + this.DataGridTitulares.Visibility = System.Windows.Visibility.Visible; + this.BotoesTitulares.Visibility = System.Windows.Visibility.Visible; + } + + private async void Excluir_OnClick(object sender, RoutedEventArgs e) + { + if (await this.ViewModel.Excluir()) + { + MenuItemViewModel menuItemViewModel = this._menuItemViewModel; + if (menuItemViewModel != null) + { + menuItemViewModel.RecarregarItens(null); + } + else + { + } + } + } + + private void ExcluirTitular_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.ExcluirTitular(); + } + + private async void ImportarTitulares_OnClick(object sender, RoutedEventArgs e) + { + await this.ViewModel.ImportarTitulares(); + } + + private async void Incluir_OnClick(object sender, RoutedEventArgs e) + { + await this.ViewModel.Incluir(false); + List> keyValuePairs = this.ViewModel.SelectedItem.Validate(); + this.ValidateFields(keyValuePairs, true); + } + + private void IncluirTitular_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.IncluirTitular(); + this.UpdateAutocompleteDependente(this.DataGridTitulares.Items.Cast().First()); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/seguros/itens/riscosdiversosview.xaml", UriKind.Relative)); + } + + public void Manter(ManutencaoItem manutencao) + { + this.ViewModel.Manter(ConsultaViewModel.ItemSelecionado, manutencao); + } + + private void MenuItem_OnClick(object sender, RoutedEventArgs e) + { + double? nullable = null; + double? nullable1 = nullable; + nullable = null; + (new HosterWindow(new SinistroView(this.ViewModel.SelectedItem, false), string.Concat("CADASTRO DE SINISTROS - ", this.ViewModel.SelectedItem.get_Descricao()), nullable1, nullable, false)).ShowDialog(); + MenuItemViewModel menuItemViewModel = this._menuItemViewModel; + if (menuItemViewModel == null) + { + return; + } + menuItemViewModel.RecarregarItens(this.ViewModel.SelectedItem); + } + + public async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this._salvando = true; + this.ViewModel.Loading(true); + this.DataGridTitulares.Focus(); + List> keyValuePairs = await this.ViewModel.Salvar(this.DataGridTitulares.Items.Cast().ToList()); + this.ValidateFields(keyValuePairs, true); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + this._salvando = false; + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + else if (this.ViewModel.SelectedItem.get_Id() > (long)0) + { + MenuItemViewModel menuItemViewModel = this._menuItemViewModel; + if (menuItemViewModel != null) + { + menuItemViewModel.RecarregarItens(this.ViewModel.SelectedItem); + } + else + { + } + } + } + + public async Task Selecionar(Item item) + { + await this.ViewModel.SelecionaItem(item, true); + } + + public void Substituir() + { + this.ViewModel.Substituir(ConsultaViewModel.ItemSelecionado); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.IncluirItemButton = (MenuItem)target; + this.IncluirItemButton.Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + case 2: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 3: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 4: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Excluir_OnClick); + return; + } + case 6: + { + ((TextBox)target).MouseDoubleClick += new MouseButtonEventHandler(this.CopyCodItem); + return; + } + case 7: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirAquivoDigital_Click); + return; + } + case 8: + { + this.SinistroButton = (MenuItem)target; + this.SinistroButton.Click += new RoutedEventHandler(this.MenuItem_OnClick); + return; + } + case 9: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick); + return; + } + case 10: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLogEmail_OnClick); + return; + } + case 11: + { + this.CoberturasRadioButton = (RadioButton)target; + return; + } + case 12: + { + this.MaisInformacoesRadioButton = (RadioButton)target; + return; + } + case 13: + { + this.BotoesTitulares = (Menu)target; + this.BotoesTitulares.IsEnabledChanged += new DependencyPropertyChangedEventHandler(this.BotoesTitulares_OnIsEnabledChanged); + return; + } + case 14: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.IncluirTitular_OnClick); + return; + } + case 15: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AlterarTitular_OnClick); + return; + } + case 16: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.ExcluirTitular_OnClick); + return; + } + case 17: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.ImportarTitulares_OnClick); + return; + } + case 18: + { + this.SeparadorMaisInformacoes = (Separator)target; + return; + } + case 19: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 20: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 21: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 22: + { + RiscosDiversosView riscosDiversosView = this; + ((TextBox)target).LostFocus += new RoutedEventHandler(riscosDiversosView.FormatarDocumento); + RiscosDiversosView riscosDiversosView1 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(riscosDiversosView1.SomenteNumeros); + return; + } + case 23: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AplicarTitular_OnClick); + return; + } + case 24: + { + this.ContentControl = (System.Windows.Controls.ContentControl)target; + return; + } + case 25: + { + this.DataGridTitulares = (DataGrid)target; + this.DataGridTitulares.CellEditEnding += new EventHandler(this.DataGridTitulares_OnCellEditEnding); + return; + } + } + this._contentLoaded = true; + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 26: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 27: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 28: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 29: + { + RiscosDiversosView riscosDiversosView = this; + ((TextBox)target).LostFocus += new RoutedEventHandler(riscosDiversosView.FormatarDocumento); + RiscosDiversosView riscosDiversosView1 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(riscosDiversosView1.SomenteNumeros); + return; + } + case 30: + { + ((ComboBox)target).SelectionChanged += new SelectionChangedEventHandler(this.TipoComboBoxSelectionChanged); + return; + } + case 31: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, RiscosDiversosView.AutoCompleteBox_Populating)); + return; + } + case 32: + { + EventSetter eventSetter = new EventSetter() + { + Event = FrameworkElement.LoadedEvent, + Handler = new RoutedEventHandler(this.Dependente_CellLoaded) + }; + ((System.Windows.Style)target).Setters.Add(eventSetter); + return; + } + default: + { + return; + } + } + } + + private async void TipoComboBoxSelectionChanged(object sender, SelectionChangedEventArgs e) + { + bool dataContext; + ComboBox comboBox = (ComboBox)sender; + if (comboBox != null) + { + dataContext = comboBox.DataContext; + } + else + { + dataContext = false; + } + if (dataContext) + { + TipoTitular? nullable = ((TitularesVida)((ComboBox)sender).DataContext).get_Tipo(); + if (nullable.GetValueOrDefault() == 2 && !this._salvando) + { + ObservableCollection titulares = this.ViewModel.Titulares; + if (!titulares.Any((TitularesVida x) => { + TipoTitular? tipo = x.get_Tipo(); + if (tipo.GetValueOrDefault() == 1) + { + return true; + } + tipo = x.get_Tipo(); + return tipo.GetValueOrDefault() == 0 & tipo.HasValue; + })) + { + ((ComboBox)sender).SelectedIndex = -1; + nullable = null; + ((TitularesVida)((ComboBox)sender).DataContext).set_Tipo(nullable); + await this.ViewModel.ShowMessage("É NECESSÁRIO ADICIONAR PELO MENOS UM TITULAR DO TIPO SÓCIO OU FUNCIONÁRIO\nANTES DE ADICIONAR UM DEPENDENTE.", "OK", "", false); + return; + } + } + this.UpdateAutocompleteDependente((TitularesVida)((ComboBox)sender).DataContext); + } + } + + private void UpdateAutocompleteDependente(TitularesVida item) + { + this.DataGridTitulares.ScrollIntoView(item, this.DataGridTitulares.Columns.First((DataGridColumn x) => (string)x.Header == "TITULAR DEPENDENTE")); + this.DataGridTitulares.UpdateLayout(); + DataGridRow dataGridRow = (DataGridRow)this.DataGridTitulares.ItemContainerGenerator.ContainerFromItem(item); + if (dataGridRow == null) + { + return; + } + ((DataGridCell)DataGridExtensions.GetVisualChild(dataGridRow).ItemContainerGenerator.ContainerFromIndex(12)).Visibility = (item.get_Tipo().GetValueOrDefault() == 2 ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + this.DataGridTitulares.ScrollIntoView(item, this.DataGridTitulares.Columns.First()); + this.DataGridTitulares.UpdateLayout(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Seguros/Itens/VidaView.cs b/Codemerx/Gestor.Application/Views/Seguros/Itens/VidaView.cs new file mode 100644 index 0000000..afb86b5 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Seguros/Itens/VidaView.cs @@ -0,0 +1,705 @@ +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Application.ViewModels.Seguros.Itens; +using Gestor.Application.Views.Generic; +using Gestor.Application.Views.Seguros; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Data; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Views.Seguros.Itens +{ + public class VidaView : BaseUserControl, IComponentConnector, IStyleConnector + { + public VidaViewModel ViewModel; + + private readonly MenuItemViewModel _menuItemViewModel; + + private bool _salvando; + + internal MenuItem IncluirItemButton; + + internal MenuItem SinistroButton; + + internal TextBox PlanoBox; + + internal RadioButton CoberturasRadioButton; + + internal RadioButton MaisInformacoesRadioButton; + + internal Menu BotoesTitulares; + + internal Separator SeparadorMaisInformacoes; + + internal System.Windows.Controls.ContentControl ContentControl; + + internal DataGrid DataGridTitulares; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public VidaView(MenuItemViewModel menuItemViewModel, bool lockInsert = false, bool substituir = false, ManutencaoItem manutencao = null, Item itemSelecionado = null, Ramo ramo = null, bool endossoRenovacao = false) + { + this._menuItemViewModel = menuItemViewModel; + this.ViewModel = new VidaViewModel(substituir, manutencao, itemSelecionado, ramo, endossoRenovacao); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher != null) + { + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + else + { + } + if (!lockInsert) + { + return; + } + this.IncluirItemButton.IsEnabled = false; + this.SinistroButton.Visibility = System.Windows.Visibility.Collapsed; + } + + private async void AbrirAquivoDigital_Click(object sender, RoutedEventArgs e) + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 4).get_Consultar()) + { + FiltroArquivoDigital filtroArquivoDigital = new FiltroArquivoDigital(); + filtroArquivoDigital.set_Id(this.ViewModel.SelectedItem.get_Id()); + filtroArquivoDigital.set_IdApolice(this.ViewModel.SelectedItem.get_Documento().get_Id()); + filtroArquivoDigital.set_Tipo(4); + filtroArquivoDigital.set_Parente(this.ViewModel.SelectedItem); + this.ViewModel.ShowDrawer(new ArquivoDigitalDrawer(filtroArquivoDigital), 0, false); + } + else + { + await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", ValidationHelper.GetDescription((TipoArquivoDigital)4), "."), "OK", "", false); + } + } + + private void AbrirLog_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLog(3, this.ViewModel.SelectedItem.get_Id()); + } + + private void AbrirLogEmail_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLogEmail(3, this.ViewModel.SelectedItem.get_Id()); + } + + private void Alterar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Alterar(true); + } + + private void AlterarTitular_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AlterarTitular(); + } + + private void AplicarTitular_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AplicarTitular(); + } + + private void AutoCompleteBox_Populating(object sender, PopulatingEventArgs e) + { + if (e.get_Parameter().Trim().Length < 3) + { + return; + } + e.set_Cancel(true); + this.ViewModel.BuscarTitulares(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void BotoesTitulares_OnIsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e) + { + bool flag; + if (!((Menu)sender).IsEnabled) + { + this.ViewModel.AlteracaoTitularesVisibility = System.Windows.Visibility.Collapsed; + } + DataGrid dataGridTitulares = this.DataGridTitulares; + if (dataGridTitulares != null) + { + flag = dataGridTitulares.Columns.First(); + } + else + { + flag = false; + } + if (!flag) + { + return; + } + this.DataGridTitulares.Columns.First().Visibility = (((Menu)sender).IsEnabled ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + } + + private void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelarAlteracao(); + } + + private void ContentLoad() + { + this.CoberturasRadioButton.Checked += new RoutedEventHandler(this.Documento_OnChecked); + this.MaisInformacoesRadioButton.Checked += new RoutedEventHandler(this.Documento_OnChecked); + } + + private void CopyCodItem(object sender, MouseButtonEventArgs e) + { + this.ViewModel.CodigoItem.CopyToClipboard(); + this.ViewModel.ToggleSnackBar(string.Concat("COPIADO - ", this.ViewModel.CodigoItem), true); + } + + private void DataGridTitulares_OnCellEditEnding(object sender, DataGridCellEditEndingEventArgs e) + { + string text; + string str; + string text1; + if (!(e.EditingElement is TextBox)) + { + return; + } + TextBox editingElement = e.EditingElement as TextBox; + string stringFormat = e.Column.ClipboardContentBinding.StringFormat; + if (stringFormat == "d") + { + if (editingElement != null) + { + text = editingElement.Text; + } + else + { + text = null; + } + if (!string.IsNullOrEmpty(text)) + { + editingElement.Text = ValidationHelper.FormatDate(editingElement.Text); + return; + } + if (editingElement != null) + { + editingElement.Text = null; + return; + } + } + else if (stringFormat == "c") + { + if (editingElement != null) + { + str = editingElement.Text; + } + else + { + str = null; + } + if (!string.IsNullOrEmpty(str)) + { + editingElement.Text = ValidationHelper.FormatCurrency(editingElement.Text); + return; + } + if (editingElement != null) + { + editingElement.Text = null; + } + } + else + { + if (editingElement != null) + { + text1 = editingElement.Text; + } + else + { + text1 = null; + } + if (!string.IsNullOrEmpty(text1)) + { + if (e.Column.SortMemberPath == "Cpf") + { + editingElement.Text = ValidationHelper.FormatDocument(editingElement.Text); + return; + } + } + else if (editingElement != null) + { + editingElement.Text = null; + return; + } + } + } + + private void Dependente_CellLoaded(object sender, RoutedEventArgs e) + { + bool valueOrDefault; + if (sender == null) + { + return; + } + DataGridCell dataGridCell = (DataGridCell)sender; + TitularesVida dataContext = (TitularesVida)((DataGridCell)sender).DataContext; + if (dataContext != null) + { + valueOrDefault = dataContext.get_Tipo().GetValueOrDefault() == 2; + } + else + { + valueOrDefault = false; + } + dataGridCell.Visibility = (valueOrDefault ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + } + + private void Documento_OnChecked(object sender, RoutedEventArgs e) + { + RadioButton radioButton = (RadioButton)sender; + if (string.IsNullOrEmpty(radioButton.GroupName)) + { + return; + } + this.ViewModel.Descarregar(); + this.ContentControl.Visibility = System.Windows.Visibility.Collapsed; + this.DataGridTitulares.Visibility = System.Windows.Visibility.Collapsed; + this.SeparadorMaisInformacoes.Visibility = System.Windows.Visibility.Collapsed; + this.BotoesTitulares.Visibility = System.Windows.Visibility.Collapsed; + this.DataGridTitulares.ClearInvalid(); + this.ContentControl.ClearInvalid(); + if (radioButton.Name != "MaisInformacoesRadioButton") + { + this.ContentControl.Visibility = System.Windows.Visibility.Visible; + this.ViewModel.CarregaCobertura(); + return; + } + this.SeparadorMaisInformacoes.Visibility = System.Windows.Visibility.Visible; + this.DataGridTitulares.Visibility = System.Windows.Visibility.Visible; + this.BotoesTitulares.Visibility = System.Windows.Visibility.Visible; + } + + private async void Excluir_OnClick(object sender, RoutedEventArgs e) + { + if (await this.ViewModel.Excluir()) + { + MenuItemViewModel menuItemViewModel = this._menuItemViewModel; + if (menuItemViewModel != null) + { + menuItemViewModel.RecarregarItens(null); + } + else + { + } + } + } + + private void ExcluirTitular_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.ExcluirTitular(); + } + + private async void ImportarTitulares_OnClick(object sender, RoutedEventArgs e) + { + await this.ViewModel.ImportarTitulares(); + } + + private async void Incluir_OnClick(object sender, RoutedEventArgs e) + { + await this.ViewModel.Incluir(false); + List> keyValuePairs = this.ViewModel.SelectedItem.Validate(); + this.ValidateFields(keyValuePairs, true); + } + + private async void IncluirTitular_OnClick(object sender, RoutedEventArgs e) + { + TitularesVida titularesVida = this.DataGridTitulares.Items.Cast().FirstOrDefault(); + if (titularesVida == null || titularesVida.get_Inicio().HasValue || titularesVida.get_Fim().HasValue || titularesVida.get_Nome() != null || titularesVida.get_Fatura() != null || titularesVida.get_Cpf() != null || titularesVida.get_Tipo().HasValue || titularesVida.get_Observacao() != null) + { + this.ViewModel.IncluirTitular(); + this.UpdateAutocompleteDependente(this.DataGridTitulares.Items.Cast().First(), false); + } + else + { + await this.ViewModel.ShowMessage("JÁ EXISTE UM CAMPO DE CADASTRO DE TITULAR CRIADO", "OK", "", false); + } + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/seguros/itens/vidaview.xaml", UriKind.Relative)); + } + + public void Manter(ManutencaoItem manutencao) + { + this.ViewModel.Manter(ConsultaViewModel.ItemSelecionado, manutencao); + } + + private void MenuItem_OnClick(object sender, RoutedEventArgs e) + { + double? nullable = null; + double? nullable1 = nullable; + nullable = null; + (new HosterWindow(new SinistroView(this.ViewModel.SelectedItem, false), string.Concat("CADASTRO DE SINISTROS - ", this.ViewModel.SelectedItem.get_Descricao()), nullable1, nullable, false)).ShowDialog(); + MenuItemViewModel menuItemViewModel = this._menuItemViewModel; + if (menuItemViewModel == null) + { + return; + } + menuItemViewModel.RecarregarItens(this.ViewModel.SelectedItem); + } + + public async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this._salvando = true; + this.ViewModel.Loading(true); + this.ViewModel.SelectedItem.get_Vida().set_Plano(this.PlanoBox.Text); + this.DataGridTitulares.Focus(); + List> keyValuePairs = await this.ViewModel.Salvar(this.DataGridTitulares.Items.Cast().ToList()); + this.ValidateFields(keyValuePairs, true); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + this._salvando = false; + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + else if (this.ViewModel.SelectedItem.get_Id() > (long)0) + { + MenuItemViewModel menuItemViewModel = this._menuItemViewModel; + if (menuItemViewModel != null) + { + menuItemViewModel.RecarregarItens(this.ViewModel.SelectedItem); + } + else + { + } + } + } + + public async Task Selecionar(Item item) + { + await this.ViewModel.SelecionaItem(item, true); + } + + public void Substituir() + { + this.ViewModel.Substituir(ConsultaViewModel.ItemSelecionado); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.IncluirItemButton = (MenuItem)target; + this.IncluirItemButton.Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + case 2: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 3: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 4: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Excluir_OnClick); + return; + } + case 6: + { + ((TextBox)target).MouseDoubleClick += new MouseButtonEventHandler(this.CopyCodItem); + return; + } + case 7: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirAquivoDigital_Click); + return; + } + case 8: + { + this.SinistroButton = (MenuItem)target; + this.SinistroButton.Click += new RoutedEventHandler(this.MenuItem_OnClick); + return; + } + case 9: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLog_OnClick); + return; + } + case 10: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLogEmail_OnClick); + return; + } + case 11: + { + this.PlanoBox = (TextBox)target; + return; + } + case 12: + { + this.CoberturasRadioButton = (RadioButton)target; + return; + } + case 13: + { + this.MaisInformacoesRadioButton = (RadioButton)target; + return; + } + case 14: + { + this.BotoesTitulares = (Menu)target; + this.BotoesTitulares.IsEnabledChanged += new DependencyPropertyChangedEventHandler(this.BotoesTitulares_OnIsEnabledChanged); + return; + } + case 15: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.IncluirTitular_OnClick); + return; + } + case 16: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AlterarTitular_OnClick); + return; + } + case 17: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.ExcluirTitular_OnClick); + return; + } + case 18: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.ImportarTitulares_OnClick); + return; + } + case 19: + { + this.SeparadorMaisInformacoes = (Separator)target; + return; + } + case 20: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 21: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 22: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 23: + { + VidaView vidaView = this; + ((TextBox)target).LostFocus += new RoutedEventHandler(vidaView.FormatarDocumento); + VidaView vidaView1 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(vidaView1.SomenteNumeros); + return; + } + case 24: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AplicarTitular_OnClick); + return; + } + case 25: + { + this.ContentControl = (System.Windows.Controls.ContentControl)target; + return; + } + case 26: + { + this.DataGridTitulares = (DataGrid)target; + this.DataGridTitulares.CellEditEnding += new EventHandler(this.DataGridTitulares_OnCellEditEnding); + return; + } + } + this._contentLoaded = true; + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 27: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 28: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 29: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 30: + { + VidaView vidaView = this; + ((TextBox)target).LostFocus += new RoutedEventHandler(vidaView.FormatarDocumento); + VidaView vidaView1 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(vidaView1.SomenteNumeros); + return; + } + case 31: + { + ((ComboBox)target).SelectionChanged += new SelectionChangedEventHandler(this.TipoComboBoxSelectionChanged); + return; + } + case 32: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, VidaView.AutoCompleteBox_Populating)); + return; + } + case 33: + { + EventSetter eventSetter = new EventSetter() + { + Event = FrameworkElement.LoadedEvent, + Handler = new RoutedEventHandler(this.Dependente_CellLoaded) + }; + ((System.Windows.Style)target).Setters.Add(eventSetter); + return; + } + default: + { + return; + } + } + } + + private async void TipoComboBoxSelectionChanged(object sender, SelectionChangedEventArgs e) + { + bool dataContext; + ComboBox comboBox = (ComboBox)sender; + if (comboBox != null) + { + dataContext = comboBox.DataContext; + } + else + { + dataContext = false; + } + if (dataContext) + { + TipoTitular? nullable = ((TitularesVida)((ComboBox)sender).DataContext).get_Tipo(); + if (nullable.GetValueOrDefault() == 2 && !this._salvando && this.ViewModel.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Id() != (long)6) + { + ObservableCollection titulares = this.ViewModel.Titulares; + if (!titulares.Any((TitularesVida x) => { + TipoTitular? tipo = x.get_Tipo(); + if (tipo.GetValueOrDefault() == 1) + { + return true; + } + tipo = x.get_Tipo(); + return tipo.GetValueOrDefault() == 0 & tipo.HasValue; + })) + { + ((ComboBox)sender).SelectedIndex = -1; + nullable = null; + ((TitularesVida)((ComboBox)sender).DataContext).set_Tipo(nullable); + await this.ViewModel.ShowMessage("É NECESSÁRIO ADICIONAR PELO MENOS UM TITULAR DO TIPO SÓCIO OU FUNCIONÁRIO\nANTES DE ADICIONAR UM DEPENDENTE.", "OK", "", false); + return; + } + } + this.UpdateAutocompleteDependente((TitularesVida)((ComboBox)sender).DataContext, false); + } + } + + private void UpdateAutocompleteDependente(TitularesVida item, bool scroll = true) + { + if (scroll) + { + this.DataGridTitulares.ScrollIntoView(item, this.DataGridTitulares.Columns.First((DataGridColumn x) => (string)x.Header == "TITULAR DEPENDENTE")); + } + this.DataGridTitulares.UpdateLayout(); + DataGridRow dataGridRow = (DataGridRow)this.DataGridTitulares.ItemContainerGenerator.ContainerFromItem(item); + if (dataGridRow == null) + { + return; + } + ((DataGridCell)DataGridExtensions.GetVisualChild(dataGridRow).ItemContainerGenerator.ContainerFromIndex(12)).Visibility = (item.get_Tipo().GetValueOrDefault() == 2 ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed); + if (scroll) + { + this.DataGridTitulares.ScrollIntoView(item, this.DataGridTitulares.Columns.First()); + } + this.DataGridTitulares.UpdateLayout(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Seguros/PerfilEmpresaView.cs b/Codemerx/Gestor.Application/Views/Seguros/PerfilEmpresaView.cs new file mode 100644 index 0000000..3d80f8c --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Seguros/PerfilEmpresaView.cs @@ -0,0 +1,267 @@ +using Gestor.Application.Componentes; +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Application.Views.Generic; +using Gestor.Common.Helpers; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using Xceed.Wpf.Toolkit; + +namespace Gestor.Application.Views.Seguros +{ + public class PerfilEmpresaView : BaseUserControl, IComponentConnector + { + public PerfilEmpresaViewModel ViewModel; + + private Controle _controle; + + internal MenuItem CancelarApoliceButton; + + internal TextBox TextAtividade; + + internal CustomIsReadOnlyControl ComboSegurancaControl; + + internal CheckComboBox ComboSeguranca; + + internal CustomIsReadOnlyControl ComboIncendioControl; + + internal CheckComboBox ComboIncendio; + + internal CheckBox ExclusivoDeposito; + + internal CheckBox DivisaTerrenoBaldio; + + internal CheckBox PatrimonioHistorio; + + internal CheckBox PossuiTelhado; + + internal CheckBox CaixasEletronicos; + + internal CheckBox Isopainel; + + internal CheckBox ConstrucaoReforma; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public PerfilEmpresaView(Controle controle) + { + this._controle = controle; + base.Tag = "CADASTRO DE PERFIL"; + this.ViewModel = new PerfilEmpresaViewModel(controle); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + this.LoadData(); + } + + private void Alterar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Alterar(true); + } + + private void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + bool id; + this.ViewModel.CancelarAlteracao(); + PerfilEmpresa selectedPerfilEmpresa = this.ViewModel.SelectedPerfilEmpresa; + if (selectedPerfilEmpresa != null) + { + id = selectedPerfilEmpresa.get_Id() == (long)0; + } + else + { + id = false; + } + if (id || this.ViewModel.SelectedPerfilEmpresa == null) + { + this.ViewModel.EnableIncluirPerfil = true; + } + } + + private async void Excluir_OnClick(object sender, RoutedEventArgs e) + { + await this.ViewModel.Excluir(); + } + + private void Incluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.EnableIncluirPerfil = false; + this.ViewModel.Incluir(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/seguros/perfilempresaview.xaml", UriKind.Relative)); + } + + private void LoadData() + { + this.ComboSeguranca.BindData(false, true, "", false); + this.ComboIncendio.BindData(false, true, "", false); + } + + private async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Loading(true); + List> keyValuePairs = await this.ViewModel.Salvar(); + this.ViewModel.Loading(false); + if (keyValuePairs != null) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + case 2: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 3: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 4: + { + this.CancelarApoliceButton = (MenuItem)target; + this.CancelarApoliceButton.Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Excluir_OnClick); + return; + } + case 6: + { + PerfilEmpresaView perfilEmpresaView = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(perfilEmpresaView.SomenteNumeros); + return; + } + case 7: + { + ((ComboBox)target).SelectionChanged += new SelectionChangedEventHandler(this.VerificaOnSelected); + return; + } + case 8: + { + this.TextAtividade = (TextBox)target; + return; + } + case 9: + { + this.ComboSegurancaControl = (CustomIsReadOnlyControl)target; + return; + } + case 10: + { + this.ComboSeguranca = (CheckComboBox)target; + return; + } + case 11: + { + this.ComboIncendioControl = (CustomIsReadOnlyControl)target; + return; + } + case 12: + { + this.ComboIncendio = (CheckComboBox)target; + return; + } + case 13: + { + this.ExclusivoDeposito = (CheckBox)target; + return; + } + case 14: + { + this.DivisaTerrenoBaldio = (CheckBox)target; + return; + } + case 15: + { + this.PatrimonioHistorio = (CheckBox)target; + return; + } + case 16: + { + this.PossuiTelhado = (CheckBox)target; + return; + } + case 17: + { + this.CaixasEletronicos = (CheckBox)target; + return; + } + case 18: + { + this.Isopainel = (CheckBox)target; + return; + } + case 19: + { + this.ConstrucaoReforma = (CheckBox)target; + return; + } + } + this._contentLoaded = true; + } + + private void VerificaOnSelected(object sender, SelectionChangedEventArgs e) + { + ComboBox comboBox = (ComboBox)sender; + if (comboBox.SelectedItem == null) + { + return; + } + if (EnumHelper.GetDescription(comboBox.SelectedItem) == EnumHelper.GetDescription(0)) + { + this.ViewModel.AtivaCampos = System.Windows.Visibility.Visible; + return; + } + if (this.ViewModel.AtivaCampos == System.Windows.Visibility.Visible) + { + this.TextAtividade.Text = ""; + this.ViewModel.AtivaCampos = System.Windows.Visibility.Collapsed; + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Seguros/PerfilView.cs b/Codemerx/Gestor.Application/Views/Seguros/PerfilView.cs new file mode 100644 index 0000000..2a23628 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Seguros/PerfilView.cs @@ -0,0 +1,320 @@ +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Views.Seguros +{ + public class PerfilView : BaseUserControl, IComponentConnector + { + public PerfilViewModel ViewModel; + + private Controle _controle; + + internal MenuItem CancelarApoliceButton; + + internal DatePicker NascimentoBox; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public PerfilView(Controle controle) + { + this._controle = controle; + base.Tag = "CADASTRO DE PERFIL"; + this.ViewModel = new PerfilViewModel(controle); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + + private void Alterar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Alterar(true); + this.ValidarTela(); + } + + private void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelarAlteracao(); + } + + private void ContentLoad() + { + this.NascimentoBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(Funcoes.DatePicker_OnLostKeyboardFocus); + this.NascimentoBox.PreviewKeyDown += new KeyEventHandler(Funcoes.DatePicker_PreviewKeyDown); + } + + private void CpfBox_OnLostFocus(object sender, RoutedEventArgs e) + { + TextBox textBox = (TextBox)sender; + textBox.Text = ValidationHelper.FormatDocument(textBox.Text); + } + + private async void Excluir_OnClick(object sender, RoutedEventArgs e) + { + await this.ViewModel.Excluir(); + } + + private void Incluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Incluir(); + this.ValidarTela(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/seguros/perfilview.xaml", UriKind.Relative)); + } + + private void PostcodeBox_OnLostFocus(object sender, RoutedEventArgs e) + { + TextBox textBox = (TextBox)sender; + if (string.IsNullOrWhiteSpace(textBox.Text)) + { + return; + } + string str = ValidationHelper.FormatPostCode(textBox.Text); + if (!ValidationHelper.ValidatePostCode(str)) + { + return; + } + textBox.Text = str; + } + + private void RelacaoComboBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + string documento; + TimeSpan? nullable; + if (((ComboBox)sender).SelectedIndex == 0) + { + Cliente cliente = this._controle.get_Cliente(); + if (cliente != null) + { + documento = cliente.get_Documento(); + } + else + { + documento = null; + } + string str = ValidationHelper.FormatDocument(ValidationHelper.Clear(documento)); + bool flag = Regex.IsMatch(str, "\\d{3}\\.\\d{3}\\.\\d{3}-\\d{2}"); + Perfil perfil = (Perfil)this.ViewModel.SelectedPerfil.Clone(); + perfil.set_Cpf((flag ? str : "")); + perfil.set_Nome(this._controle.get_Cliente().get_Nome()); + perfil.set_Nascimento(this._controle.get_Cliente().get_Nascimento()); + perfil.set_Sexo(this._controle.get_Cliente().get_Sexo()); + perfil.set_EstadoCivil(this._controle.get_Cliente().get_EstadoCivil()); + perfil.set_Habilitacao(this._controle.get_Cliente().get_Habilitacao()); + DateTime? primeiraHabilitacao = this._controle.get_Cliente().get_PrimeiraHabilitacao(); + if (primeiraHabilitacao.HasValue) + { + DateTime networkTime = Funcoes.GetNetworkTime(); + primeiraHabilitacao = this._controle.get_Cliente().get_PrimeiraHabilitacao(); + if (primeiraHabilitacao.HasValue) + { + nullable = new TimeSpan?(networkTime - primeiraHabilitacao.GetValueOrDefault()); + } + else + { + nullable = null; + } + TimeSpan? nullable1 = nullable; + if (nullable1.Value.Days > 3650) + { + perfil.set_TempoHabilitacao(new TempoHabilitacao?(10)); + } + else if (nullable1.Value.Days > 3285) + { + perfil.set_TempoHabilitacao(new TempoHabilitacao?(9)); + } + else if (nullable1.Value.Days > 2920) + { + perfil.set_TempoHabilitacao(new TempoHabilitacao?(8)); + } + else if (nullable1.Value.Days > 2555) + { + perfil.set_TempoHabilitacao(new TempoHabilitacao?(7)); + } + else if (nullable1.Value.Days > 2190) + { + perfil.set_TempoHabilitacao(new TempoHabilitacao?(6)); + } + else if (nullable1.Value.Days > 1825) + { + perfil.set_TempoHabilitacao(new TempoHabilitacao?(5)); + } + else if (nullable1.Value.Days > 1460) + { + perfil.set_TempoHabilitacao(new TempoHabilitacao?(4)); + } + else if (nullable1.Value.Days > 1095) + { + perfil.set_TempoHabilitacao(new TempoHabilitacao?(3)); + } + else if (nullable1.Value.Days > 730) + { + perfil.set_TempoHabilitacao(new TempoHabilitacao?(2)); + } + else if (nullable1.Value.Days <= 365) + { + perfil.set_TempoHabilitacao(new TempoHabilitacao?(0)); + } + else + { + perfil.set_TempoHabilitacao(new TempoHabilitacao?(1)); + } + } + this.ViewModel.SelectedPerfil = perfil; + } + } + + private async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.Loading(true); + List> keyValuePairs = await this.ViewModel.Salvar(); + this.ValidateFields(keyValuePairs, true); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + case 2: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 3: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 4: + { + this.CancelarApoliceButton = (MenuItem)target; + this.CancelarApoliceButton.Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Excluir_OnClick); + return; + } + case 6: + { + ((ComboBox)target).SelectionChanged += new SelectionChangedEventHandler(this.RelacaoComboBox_OnSelectionChanged); + return; + } + case 7: + { + ((TextBox)target).LostFocus += new RoutedEventHandler(this.CpfBox_OnLostFocus); + PerfilView perfilView = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(perfilView.SomenteNumeros); + return; + } + case 8: + { + this.NascimentoBox = (DatePicker)target; + this.NascimentoBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + this.NascimentoBox.MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 9: + { + PerfilView perfilView1 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(perfilView1.SomenteNumeros); + return; + } + case 10: + { + PerfilView perfilView2 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(perfilView2.SomenteNumeros); + return; + } + case 11: + { + PerfilView perfilView3 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(perfilView3.SomenteNumeros); + return; + } + case 12: + { + ((TextBox)target).LostFocus += new RoutedEventHandler(this.PostcodeBox_OnLostFocus); + PerfilView perfilView4 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(perfilView4.SomenteNumeros); + return; + } + case 13: + { + ((TextBox)target).LostFocus += new RoutedEventHandler(this.PostcodeBox_OnLostFocus); + PerfilView perfilView5 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(perfilView5.SomenteNumeros); + return; + } + } + this._contentLoaded = true; + } + + private void ValidarTela() + { + if (this.ViewModel.SelectedPerfil == null) + { + return; + } + List> keyValuePairs = this.ViewModel.SelectedPerfil.Validate(); + this.ValidateFields(keyValuePairs, false); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Seguros/SinistroView.cs b/Codemerx/Gestor.Application/Views/Seguros/SinistroView.cs new file mode 100644 index 0000000..6bd6e00 --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Seguros/SinistroView.cs @@ -0,0 +1,1003 @@ +using Gestor.Application.Componentes; +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.ViewModels.Ferramentas; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Application.Views.Ferramentas; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using MaterialDesignThemes.Wpf; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Views.Seguros +{ + public class SinistroView : BaseUserControl, IComponentConnector + { + public SinistroViewModel ViewModel; + + internal DataGrid ControleGrid; + + internal MenuItem SalvarSinistroButton; + + internal MenuItem CancelarApoliceButton; + + internal CustomIsReadOnlyControl TipoSinistroBox; + + internal ComboBox ParceiroMecanica; + + internal ComboBox ParceiroFunilaria; + + internal RadioButton AnotacoesButton; + + internal RadioButton AnotacoesInternasButton; + + internal CustomItemControl AnotacoesHoster; + + internal WebEditor Anotacoes; + + internal CustomItemControl ObservacoesHoster; + + internal WebEditor Observacoes; + + internal CustomItemControl AnotacoesInternasHoster; + + internal WebEditor AnotacoesInternas; + + internal CustomItemControl ObservacoesInternasHoster; + + internal WebEditor ObservacoesInternas; + + internal MaterialDesignThemes.Wpf.Snackbar Snackbar; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public SinistroView(Item item = null, bool attached = true) + { + item = item ?? ConsultaViewModel.ItemSelecionado; + base.Tag = "CADASTRO DE SINISTRO"; + this.ViewModel = new SinistroViewModel(item, attached); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + + private void AbrirInfo_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirInfo(); + } + + private void AbrirLogEmail_OnClick(object sender, RoutedEventArgs e) + { + if (this.ViewModel.SelectedSinistro == null) + { + return; + } + this.ViewModel.AbrirLogEmail(7, this.ViewModel.SelectedSinistro.get_Id()); + } + + private void Alterar_OnClick(object sender, RoutedEventArgs e) + { + bool? nullable; + bool valueOrDefault; + bool flag; + if (this.ViewModel.SelectedSinistro == null) + { + return; + } + this.ViewModel.Alterar(true); + CustomIsReadOnlyControl tipoSinistroBox = this.TipoSinistroBox; + ControleSinistro selectedControle = this.ViewModel.SelectedControle; + if (selectedControle != null) + { + List sinistros = selectedControle.get_Sinistros(); + if (sinistros != null) + { + nullable = new bool?(sinistros.Any((Sinistro x) => { + TipoSinistro? tipoSinistro = x.get_TipoSinistro(); + return tipoSinistro.GetValueOrDefault() == 0 & tipoSinistro.HasValue; + })); + } + else + { + nullable = null; + } + bool? nullable1 = nullable; + bool flag1 = false; + valueOrDefault = nullable1.GetValueOrDefault() == flag1 & nullable1.HasValue; + } + else + { + valueOrDefault = false; + } + if (valueOrDefault) + { + flag = true; + } + else + { + Sinistro selectedSinistro = this.ViewModel.SelectedSinistro; + if (selectedSinistro != null) + { + TipoSinistro? nullable2 = selectedSinistro.get_TipoSinistro(); + TipoSinistro tipoSinistro1 = 0; + flag = nullable2.GetValueOrDefault() == tipoSinistro1 & nullable2.HasValue; + } + else + { + flag = false; + } + } + tipoSinistroBox.IsEnabled = flag; + this.ToggleAnotacoes(this.ViewModel.IsAnotacoes, false); + Sinistro sinistro = this.ViewModel.SelectedSinistro; + if (sinistro == null) + { + return; + } + sinistro.Initialize(); + } + + private void Anotacoes_OnChecked(object sender, RoutedEventArgs e) + { + this.ToggleAnotacoes(true, false); + } + + private void AnotacoesInternas_OnChecked(object sender, RoutedEventArgs e) + { + this.ToggleAnotacoes(false, false); + } + + private async void ArquivoDigital_OnClick(object sender, RoutedEventArgs e) + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 5).get_Consultar()) + { + FiltroArquivoDigital filtroArquivoDigital = new FiltroArquivoDigital(); + filtroArquivoDigital.set_Id(this.ViewModel.SelectedSinistro.get_Id()); + filtroArquivoDigital.set_IdApolice(this.ViewModel.SelectedSinistro.get_ControleSinistro().get_Item().get_Documento().get_Id()); + filtroArquivoDigital.set_Tipo(5); + filtroArquivoDigital.set_Parente(this.ViewModel.SelectedSinistro); + this.ViewModel.ShowDrawer(new ArquivoDigitalDrawer(filtroArquivoDigital), 0, false); + } + else + { + await this.ViewModel.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", ValidationHelper.GetDescription((TipoArquivoDigital)5), "."), "OK", "", false); + } + } + + private void AutoCompleteBoxItem_OnTextChanged(object sender, RoutedEventArgs e) + { + if (!string.IsNullOrWhiteSpace(((AutoCompleteBox)sender).get_Text())) + { + return; + } + this.ViewModel.FiltrarItem(""); + } + + private void AutoCompleteBoxItem_Populating(object sender, PopulatingEventArgs e) + { + e.set_Cancel(true); + this.ViewModel.ItemFiltrar(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void AutoCompleteBoxSinistro_OnTextChanged(object sender, RoutedEventArgs e) + { + if (!string.IsNullOrWhiteSpace(((AutoCompleteBox)sender).get_Text())) + { + return; + } + this.ViewModel.FiltrarSinistro(""); + } + + private void AutoCompleteBoxSinistro_Populating(object sender, PopulatingEventArgs e) + { + e.set_Cancel(true); + this.ViewModel.SinistroFiltrar(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim())).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void Cancelar_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.CancelarAlteracao(); + this.Anotacoes.Initialize(null); + this.AnotacoesInternas.Initialize(null); + this.ViewModel.EnableFields = false; + this.ToggleAnotacoes(this.ViewModel.IsAnotacoes, false); + } + + private void ContentLoad() + { + this.ControleGrid.SelectionChanged += new SelectionChangedEventHandler(this.SinistroGrid_OnSelectionChanged); + this.AnotacoesButton.IsChecked = new bool?(this.ViewModel.IsAnotacoes); + this.AnotacoesInternasButton.IsChecked = new bool?(!this.ViewModel.IsAnotacoes); + this.ToggleAnotacoes(this.ViewModel.IsAnotacoes, false); + this.AnotacoesButton.Checked += new RoutedEventHandler(this.Anotacoes_OnChecked); + this.AnotacoesInternasButton.Checked += new RoutedEventHandler(this.AnotacoesInternas_OnChecked); + } + + private void EnviarHistorico_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.EnviarLogEmail(); + } + + private void Excluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Excluir(); + } + + private void FunilariaButton_OnClick(object sender, RoutedEventArgs e) + { + Parceiro parceiroFunilaria; + long num; + object obj; + object obj1; + if (this.ViewModel.SelectedSinistro.get_SinistroAuto().get_ParceiroFunilaria() == null || this.ViewModel.SelectedSinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Id() == 0) + { + parceiroFunilaria = null; + } + else + { + parceiroFunilaria = this.ViewModel.SelectedSinistro.get_SinistroAuto().get_ParceiroFunilaria(); + } + CadastroParceiroView cadastroParceiroView = new CadastroParceiroView(parceiroFunilaria); + (new HosterWindow(cadastroParceiroView, "CADASTRO DE PARCEIROS", new double?((double)1000), new double?((double)600), false)).ShowDialog(); + Parceiro selectedItem = (Parceiro)this.ParceiroMecanica.SelectedItem; + if (selectedItem != null) + { + num = selectedItem.get_Id(); + } + else + { + num = (long)0; + } + long num1 = num; + this.ViewModel.CarregarParceiros(); + ComboBox parceiroMecanica = this.ParceiroMecanica; + if (num1 > (long)0) + { + ObservableCollection parceiros = this.ViewModel.Parceiros; + if (parceiros != null) + { + obj = parceiros.FirstOrDefault((Parceiro x) => x.get_Id() == num1); + } + else + { + obj = null; + } + } + else + { + obj = null; + } + parceiroMecanica.SelectedItem = obj; + ComboBox comboBox = this.ParceiroFunilaria; + ObservableCollection observableCollection = this.ViewModel.Parceiros; + if (observableCollection != null) + { + obj1 = observableCollection.FirstOrDefault((Parceiro x) => { + long? nullable; + long id = x.get_Id(); + Parceiro selectedParceiro = cadastroParceiroView.ViewModel.SelectedParceiro; + if (selectedParceiro != null) + { + nullable = new long?(selectedParceiro.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + return id == nullable1.GetValueOrDefault() & nullable1.HasValue; + }); + } + else + { + obj1 = null; + } + comboBox.SelectedItem = obj1; + } + + private void ImprimirHistorico_OnClick(object sender, RoutedEventArgs e) + { + if (this.ViewModel.SelectedSinistro.get_Id() == 0) + { + return; + } + this.ViewModel.ImprimirHistorico(); + } + + private async void Incluir_OnClick(object sender, RoutedEventArgs e) + { + if (this.ViewModel.SelectedItem != null) + { + await this.ViewModel.IncluirSinistro(); + List> keyValuePairs = this.ViewModel.SelectedSinistro.Validate(); + this.ValidateFields(keyValuePairs, true); + this.ToggleAnotacoes(this.ViewModel.IsAnotacoes, false); + } + else + { + await this.ViewModel.ShowMessage("NECESSÁRIO INCLUIR O ITEM ANTES DE INCLUIR UM SINISTRO.", "OK", "", false); + } + } + + private void IncluirEnvolvido_OnClick(object sender, RoutedEventArgs e) + { + bool? nullable; + bool valueOrDefault; + bool flag; + List> keyValuePairs; + this.ViewModel.IncluirEnvolvido(); + CustomIsReadOnlyControl tipoSinistroBox = this.TipoSinistroBox; + ControleSinistro selectedControle = this.ViewModel.SelectedControle; + if (selectedControle != null) + { + List sinistros = selectedControle.get_Sinistros(); + if (sinistros != null) + { + nullable = new bool?(sinistros.Any((Sinistro x) => { + TipoSinistro? tipoSinistro = x.get_TipoSinistro(); + return tipoSinistro.GetValueOrDefault() == 0 & tipoSinistro.HasValue; + })); + } + else + { + nullable = null; + } + bool? nullable1 = nullable; + bool flag1 = false; + valueOrDefault = nullable1.GetValueOrDefault() == flag1 & nullable1.HasValue; + } + else + { + valueOrDefault = false; + } + if (valueOrDefault) + { + flag = true; + } + else + { + Sinistro selectedSinistro = this.ViewModel.SelectedSinistro; + if (selectedSinistro != null) + { + TipoSinistro? nullable2 = selectedSinistro.get_TipoSinistro(); + TipoSinistro tipoSinistro1 = 0; + flag = nullable2.GetValueOrDefault() == tipoSinistro1 & nullable2.HasValue; + } + else + { + flag = false; + } + } + tipoSinistroBox.IsEnabled = flag; + Sinistro sinistro = this.ViewModel.SelectedSinistro; + if (sinistro != null) + { + keyValuePairs = sinistro.Validate(); + } + else + { + keyValuePairs = null; + } + this.ValidateFields(keyValuePairs, true); + this.ToggleAnotacoes(this.ViewModel.IsAnotacoes, true); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/seguros/sinistroview.xaml", UriKind.Relative)); + } + + private void ItemGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + DataGrid dataGrid = (DataGrid)sender; + if (dataGrid != null && dataGrid.SelectedIndex < 0) + { + return; + } + this.ViewModel.SelecionaItem((Item)((dataGrid != null ? dataGrid.Items[dataGrid.SelectedIndex] : null))); + } + + private void Log_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.AbrirLog(7, this.ViewModel.SelectedSinistro.get_Id()); + } + + private void MecanicaButton_OnClick(object sender, RoutedEventArgs e) + { + Parceiro parceiroMecanica; + long num; + object obj; + object obj1; + if (this.ViewModel.SelectedSinistro.get_SinistroAuto().get_ParceiroMecanica() == null || this.ViewModel.SelectedSinistro.get_SinistroAuto().get_ParceiroMecanica().get_Id() == 0) + { + parceiroMecanica = null; + } + else + { + parceiroMecanica = this.ViewModel.SelectedSinistro.get_SinistroAuto().get_ParceiroMecanica(); + } + CadastroParceiroView cadastroParceiroView = new CadastroParceiroView(parceiroMecanica); + (new HosterWindow(cadastroParceiroView, "CADASTRO DE PARCEIROS", new double?((double)1000), new double?((double)600), false)).ShowDialog(); + Parceiro selectedItem = (Parceiro)this.ParceiroFunilaria.SelectedItem; + if (selectedItem != null) + { + num = selectedItem.get_Id(); + } + else + { + num = (long)0; + } + long num1 = num; + this.ViewModel.CarregarParceiros(); + ComboBox parceiroFunilaria = this.ParceiroFunilaria; + if (num1 > (long)0) + { + ObservableCollection parceiros = this.ViewModel.Parceiros; + if (parceiros != null) + { + obj = parceiros.FirstOrDefault((Parceiro x) => x.get_Id() == num1); + } + else + { + obj = null; + } + } + else + { + obj = null; + } + parceiroFunilaria.SelectedItem = obj; + ComboBox comboBox = this.ParceiroMecanica; + ObservableCollection observableCollection = this.ViewModel.Parceiros; + if (observableCollection != null) + { + obj1 = observableCollection.FirstOrDefault((Parceiro x) => { + long? nullable; + long id = x.get_Id(); + Parceiro selectedParceiro = cadastroParceiroView.ViewModel.SelectedParceiro; + if (selectedParceiro != null) + { + nullable = new long?(selectedParceiro.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + return id == nullable1.GetValueOrDefault() & nullable1.HasValue; + }); + } + else + { + obj1 = null; + } + comboBox.SelectedItem = obj1; + } + + private void ParceiroBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + SinistroViewModel viewModel; + ComboBox comboBox = (ComboBox)sender; + if (comboBox == null || comboBox.SelectedItem == null) + { + return; + } + Parceiro selectedItem = (Parceiro)comboBox.SelectedItem; + if (comboBox.Name != "ParceiroMecanica") + { + if (this.ViewModel.SelectedSinistro.get_SinistroAuto().get_ParceiroFunilaria() == null) + { + this.ViewModel.SelectedSinistro.get_SinistroAuto().set_ParceiroFunilaria(selectedItem); + } + this.ParceiroFunilaria.Text = selectedItem.get_Nome(); + this.ViewModel.TelefonesFunileiro = ""; + bool flag = true; + if (!string.IsNullOrWhiteSpace(selectedItem.get_Ddd1()) || !string.IsNullOrWhiteSpace(selectedItem.get_Telefone1())) + { + flag = false; + viewModel = this.ViewModel; + viewModel.TelefonesFunileiro = string.Concat(new string[] { viewModel.TelefonesFunileiro, "TELEFONE 1: (", selectedItem.get_Ddd1(), ") ", ValidationHelper.FormatarTelefone(selectedItem.get_Telefone1()) }); + } + if (!string.IsNullOrWhiteSpace(selectedItem.get_Ddd2()) || !string.IsNullOrWhiteSpace(selectedItem.get_Telefone2())) + { + flag = false; + viewModel = this.ViewModel; + viewModel.TelefonesFunileiro = string.Concat(new string[] { viewModel.TelefonesFunileiro, "\nTELEFONE 2: (", selectedItem.get_Ddd2(), ") ", ValidationHelper.FormatarTelefone(selectedItem.get_Telefone2()) }); + } + if (!string.IsNullOrWhiteSpace(selectedItem.get_Ddd3()) || !string.IsNullOrWhiteSpace(selectedItem.get_Telefone3())) + { + flag = false; + viewModel = this.ViewModel; + viewModel.TelefonesFunileiro = string.Concat(new string[] { viewModel.TelefonesFunileiro, "\nTELEFONE 3: (", selectedItem.get_Ddd3(), ") ", ValidationHelper.FormatarTelefone(selectedItem.get_Telefone3()) }); + } + if (!string.IsNullOrWhiteSpace(selectedItem.get_Endereco()) || !string.IsNullOrWhiteSpace(selectedItem.get_Cidade()) || !string.IsNullOrWhiteSpace(selectedItem.get_Uf()) || !string.IsNullOrWhiteSpace(selectedItem.get_Bairro()) || !string.IsNullOrWhiteSpace(selectedItem.get_Cep()) || !string.IsNullOrWhiteSpace(selectedItem.get_Numero()) || !string.IsNullOrWhiteSpace(selectedItem.get_Complemento())) + { + flag = false; + viewModel = this.ViewModel; + SinistroViewModel sinistroViewModel = viewModel; + string[] telefonesFunileiro = new string[] { viewModel.TelefonesFunileiro, "\nENDEREÇO: ", selectedItem.get_Endereco(), ", ", selectedItem.get_Numero(), ", ", null, null, null, null, null, null, null, null, null }; + telefonesFunileiro[6] = (string.IsNullOrWhiteSpace(selectedItem.get_Complemento()) ? "-" : selectedItem.get_Complemento() ?? ""); + telefonesFunileiro[7] = ", "; + telefonesFunileiro[8] = selectedItem.get_Bairro(); + telefonesFunileiro[9] = ", "; + telefonesFunileiro[10] = selectedItem.get_Cidade(); + telefonesFunileiro[11] = "/"; + telefonesFunileiro[12] = selectedItem.get_Uf(); + telefonesFunileiro[13] = " - "; + telefonesFunileiro[14] = selectedItem.get_Cep(); + sinistroViewModel.TelefonesFunileiro = string.Concat(telefonesFunileiro); + } + if (!string.IsNullOrWhiteSpace(selectedItem.get_Email())) + { + flag = false; + SinistroViewModel viewModel1 = this.ViewModel; + viewModel1.TelefonesFunileiro = string.Concat(viewModel1.TelefonesFunileiro, "\nEMAIL: ", selectedItem.get_Email()); + } + if (!string.IsNullOrWhiteSpace(selectedItem.get_Cgccpf())) + { + flag = false; + SinistroViewModel sinistroViewModel1 = this.ViewModel; + sinistroViewModel1.TelefonesFunileiro = string.Concat(sinistroViewModel1.TelefonesFunileiro, "\nDOCUMENTO: ", selectedItem.get_Cgccpf()); + } + if (flag) + { + this.ViewModel.TelefonesFunileiro = "PARCEIRO SEM MAIS INFORMAÇÕES"; + } + } + else + { + if (this.ViewModel.SelectedSinistro.get_SinistroAuto().get_ParceiroMecanica() == null) + { + this.ViewModel.SelectedSinistro.get_SinistroAuto().set_ParceiroMecanica(selectedItem); + } + this.ParceiroMecanica.Text = selectedItem.get_Nome(); + this.ViewModel.TelefonesMecanica = ""; + bool flag1 = true; + if (!string.IsNullOrWhiteSpace(selectedItem.get_Ddd1()) || !string.IsNullOrWhiteSpace(selectedItem.get_Telefone1())) + { + flag1 = false; + viewModel = this.ViewModel; + viewModel.TelefonesMecanica = string.Concat(new string[] { viewModel.TelefonesMecanica, "TELEFONE 1: (", selectedItem.get_Ddd1(), ") ", ValidationHelper.FormatarTelefone(selectedItem.get_Telefone1()) }); + } + if (!string.IsNullOrWhiteSpace(selectedItem.get_Ddd2()) || !string.IsNullOrWhiteSpace(selectedItem.get_Telefone2())) + { + flag1 = false; + viewModel = this.ViewModel; + viewModel.TelefonesMecanica = string.Concat(new string[] { viewModel.TelefonesMecanica, "\nTELEFONE 2: (", selectedItem.get_Ddd2(), ") ", ValidationHelper.FormatarTelefone(selectedItem.get_Telefone2()) }); + } + if (!string.IsNullOrWhiteSpace(selectedItem.get_Ddd3()) || !string.IsNullOrWhiteSpace(selectedItem.get_Telefone3())) + { + flag1 = false; + viewModel = this.ViewModel; + viewModel.TelefonesMecanica = string.Concat(new string[] { viewModel.TelefonesMecanica, "\nTELEFONE 3: (", selectedItem.get_Ddd3(), ") ", ValidationHelper.FormatarTelefone(selectedItem.get_Telefone3()) }); + } + if (!string.IsNullOrWhiteSpace(selectedItem.get_Endereco()) || !string.IsNullOrWhiteSpace(selectedItem.get_Cidade()) || !string.IsNullOrWhiteSpace(selectedItem.get_Uf()) || !string.IsNullOrWhiteSpace(selectedItem.get_Bairro()) || !string.IsNullOrWhiteSpace(selectedItem.get_Cep()) || !string.IsNullOrWhiteSpace(selectedItem.get_Numero()) || !string.IsNullOrWhiteSpace(selectedItem.get_Complemento())) + { + flag1 = false; + viewModel = this.ViewModel; + SinistroViewModel sinistroViewModel2 = viewModel; + string[] telefonesMecanica = new string[] { viewModel.TelefonesMecanica, "\nENDEREÇO: ", selectedItem.get_Endereco(), ", ", selectedItem.get_Numero(), ", ", null, null, null, null, null, null, null, null, null }; + telefonesMecanica[6] = (string.IsNullOrWhiteSpace(selectedItem.get_Complemento()) ? "-" : selectedItem.get_Complemento() ?? ""); + telefonesMecanica[7] = ", "; + telefonesMecanica[8] = selectedItem.get_Bairro(); + telefonesMecanica[9] = ", "; + telefonesMecanica[10] = selectedItem.get_Cidade(); + telefonesMecanica[11] = "/"; + telefonesMecanica[12] = selectedItem.get_Uf(); + telefonesMecanica[13] = " - "; + telefonesMecanica[14] = selectedItem.get_Cep(); + sinistroViewModel2.TelefonesMecanica = string.Concat(telefonesMecanica); + } + if (!string.IsNullOrWhiteSpace(selectedItem.get_Email())) + { + flag1 = false; + SinistroViewModel viewModel2 = this.ViewModel; + viewModel2.TelefonesMecanica = string.Concat(viewModel2.TelefonesMecanica, "\nEMAIL: ", selectedItem.get_Email()); + } + if (!string.IsNullOrWhiteSpace(selectedItem.get_Cgccpf())) + { + flag1 = false; + SinistroViewModel viewModel3 = this.ViewModel; + viewModel3.TelefonesMecanica = string.Concat(viewModel3.TelefonesMecanica, "\nDOCUMENTO: ", selectedItem.get_Cgccpf()); + } + if (flag1) + { + this.ViewModel.TelefonesMecanica = "PARCEIRO SEM MAIS INFORMAÇÕES"; + return; + } + } + } + + private async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + bool flag; + this.ViewModel.Loading(true); + this.ViewModel.Anotacoes = this.Anotacoes.GetHtml(); + this.ViewModel.AnotacoesInternas = this.AnotacoesInternas.GetHtml(); + if (this.ViewModel.EditarObservacao) + { + this.ViewModel.SelectedSinistro.set_ObservacaoInterna(this.ObservacoesInternas.GetHtml()); + this.ViewModel.SelectedSinistro.set_Observacao(this.Observacoes.GetHtml()); + } + List> keyValuePairs = await this.ViewModel.Salvar(); + this.ValidateFields(keyValuePairs, true); + flag = (keyValuePairs == null ? true : keyValuePairs.Count == 0); + this.ViewModel.Loading(false); + if (!flag) + { + await this.ViewModel.ShowMessage(keyValuePairs, this.ViewModel.ErroCamposInvalidos, "OK", ""); + } + else + { + this.Anotacoes.Initialize(null); + this.AnotacoesInternas.Initialize(null); + this.ToggleAnotacoes(this.ViewModel.IsAnotacoes, false); + } + } + + private void SinistroGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + DataGrid dataGrid = (DataGrid)sender; + if (dataGrid != null && dataGrid.SelectedIndex < 0) + { + return; + } + this.ViewModel.SelecionaControle((ControleSinistro)((dataGrid != null ? dataGrid.Items[dataGrid.SelectedIndex] : null))); + } + + private void SituacaoBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e) + { + ComboBox comboBox = (ComboBox)sender; + if (comboBox == null || comboBox.SelectedItem == null) + { + return; + } + if ((StatusSinistro)comboBox.SelectedItem == 1) + { + this.ViewModel.SelectedSinistro.set_DataLiquidacao(null); + this.ViewModel.LiquidacaoVisibility = System.Windows.Visibility.Collapsed; + } + else + { + this.ViewModel.LiquidacaoVisibility = System.Windows.Visibility.Visible; + } + this.Validar(); + } + + private void SnackbarMessage_ActionClick(object sender, RoutedEventArgs e) + { + this.Snackbar.set_IsActive(false); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, SinistroView.AutoCompleteBoxSinistro_Populating)); + ((AutoCompleteBox)target).add_TextChanged(new RoutedEventHandler(this.AutoCompleteBoxSinistro_OnTextChanged)); + return; + } + case 2: + { + this.ControleGrid = (DataGrid)target; + return; + } + case 3: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + case 4: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Incluir_OnClick); + return; + } + case 5: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.IncluirEnvolvido_OnClick); + return; + } + case 6: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Alterar_OnClick); + return; + } + case 7: + { + this.SalvarSinistroButton = (MenuItem)target; + this.SalvarSinistroButton.Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 8: + { + this.CancelarApoliceButton = (MenuItem)target; + this.CancelarApoliceButton.Click += new RoutedEventHandler(this.Cancelar_OnClick); + return; + } + case 9: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Excluir_OnClick); + return; + } + case 10: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Tarefas_OnClick); + return; + } + case 11: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.ArquivoDigital_OnClick); + return; + } + case 12: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.ImprimirHistorico_OnClick); + return; + } + case 13: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.EnviarHistorico_OnClick); + return; + } + case 14: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Log_OnClick); + return; + } + case 15: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirLogEmail_OnClick); + return; + } + case 16: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.AbrirInfo_OnClick); + return; + } + case 17: + { + this.TipoSinistroBox = (CustomIsReadOnlyControl)target; + return; + } + case 18: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 19: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 20: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 21: + { + ((ComboBox)target).SelectionChanged += new SelectionChangedEventHandler(this.SituacaoBox_OnSelectionChanged); + return; + } + case 22: + { + ((DatePicker)target).LostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.DatePicker_OnLostKeyboardFocus); + ((DatePicker)target).PreviewKeyDown += new KeyEventHandler(this.DatePicker_PreviewKeyDown); + ((DatePicker)target).MouseDoubleClick += new MouseButtonEventHandler(this.DataAtual_OnDoubleClick); + return; + } + case 23: + { + SinistroView sinistroView = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(sinistroView.SomenteNumeros); + return; + } + case 24: + { + SinistroView sinistroView1 = this; + ((TextBox)target).PreviewTextInput += new TextCompositionEventHandler(sinistroView1.SomenteNumeros); + SinistroView sinistroView2 = this; + ((TextBox)target).LostFocus += new RoutedEventHandler(sinistroView2.FormatarTelefone); + return; + } + case 25: + { + this.ParceiroMecanica = (ComboBox)target; + this.ParceiroMecanica.SelectionChanged += new SelectionChangedEventHandler(this.ParceiroBox_OnSelectionChanged); + return; + } + case 26: + { + ((Button)target).Click += new RoutedEventHandler(this.MecanicaButton_OnClick); + return; + } + case 27: + { + this.ParceiroFunilaria = (ComboBox)target; + this.ParceiroFunilaria.SelectionChanged += new SelectionChangedEventHandler(this.ParceiroBox_OnSelectionChanged); + return; + } + case 28: + { + ((Button)target).Click += new RoutedEventHandler(this.FunilariaButton_OnClick); + return; + } + case 29: + { + this.AnotacoesButton = (RadioButton)target; + return; + } + case 30: + { + this.AnotacoesInternasButton = (RadioButton)target; + return; + } + case 31: + { + this.AnotacoesHoster = (CustomItemControl)target; + return; + } + case 32: + { + this.Anotacoes = (WebEditor)target; + return; + } + case 33: + { + this.ObservacoesHoster = (CustomItemControl)target; + return; + } + case 34: + { + this.Observacoes = (WebEditor)target; + return; + } + case 35: + { + this.AnotacoesInternasHoster = (CustomItemControl)target; + return; + } + case 36: + { + this.AnotacoesInternas = (WebEditor)target; + return; + } + case 37: + { + this.ObservacoesInternasHoster = (CustomItemControl)target; + return; + } + case 38: + { + this.ObservacoesInternas = (WebEditor)target; + return; + } + case 39: + { + this.Snackbar = (MaterialDesignThemes.Wpf.Snackbar)target; + return; + } + case 40: + { + ((SnackbarMessage)target).add_ActionClick(new RoutedEventHandler(this.SnackbarMessage_ActionClick)); + return; + } + } + this._contentLoaded = true; + } + + private async void Tarefas_OnClick(object sender, RoutedEventArgs e) + { + Cliente cliente = await this.ViewModel.BuscarClienteSinistro(); + Tarefa tarefa = new Tarefa(); + tarefa.set_IdCliente(this.ViewModel.SelectedSinistro.get_Id()); + tarefa.set_Cliente(cliente.get_Nome()); + tarefa.set_Entidade(4); + tarefa.set_IdEntidade(this.ViewModel.SelectedSinistro.get_Id()); + tarefa.set_Titulo(string.Concat("SINISTRO ", this.ViewModel.SelectedSinistro.get_Numero(), " ITEM ", this.ViewModel.SelectedSinistro.get_ItemSinistrado())); + this.ViewModel.ShowDrawer(new TarefaDrawer(tarefa, true), 0, false); + } + + private void ToggleAnotacoes(bool anotacoes, bool inclusao = false) + { + if (anotacoes) + { + this.ViewModel.IsAnotacoes = true; + if (this.ViewModel.EnableFields | inclusao) + { + this.AnotacoesHoster.Visibility = System.Windows.Visibility.Visible; + this.AnotacoesInternasHoster.Visibility = System.Windows.Visibility.Collapsed; + return; + } + this.AnotacoesHoster.Visibility = System.Windows.Visibility.Collapsed; + this.AnotacoesInternasHoster.Visibility = System.Windows.Visibility.Collapsed; + return; + } + this.ViewModel.IsAnotacoes = false; + if (this.ViewModel.EnableFields | inclusao) + { + this.AnotacoesHoster.Visibility = System.Windows.Visibility.Collapsed; + this.AnotacoesInternasHoster.Visibility = System.Windows.Visibility.Visible; + return; + } + this.AnotacoesHoster.Visibility = System.Windows.Visibility.Collapsed; + this.AnotacoesInternasHoster.Visibility = System.Windows.Visibility.Collapsed; + } + + private void Validar() + { + if (this.ViewModel.SelectedSinistro == null) + { + return; + } + List> keyValuePairs = this.ViewModel.SelectedSinistro.Validate(); + this.ValidateFields(keyValuePairs, false); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/Seguros/TrocarClienteView.cs b/Codemerx/Gestor.Application/Views/Seguros/TrocarClienteView.cs new file mode 100644 index 0000000..61be59b --- /dev/null +++ b/Codemerx/Gestor.Application/Views/Seguros/TrocarClienteView.cs @@ -0,0 +1,154 @@ +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Seguros; +using MaterialDesignThemes.Wpf; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Markup; +using System.Windows.Threading; + +namespace Gestor.Application.Views.Seguros +{ + public class TrocarClienteView : BaseUserControl, IComponentConnector + { + public TrocarClienteViewModel ViewModel; + + internal System.Windows.Controls.ProgressBar ProgressBar; + + internal MaterialDesignThemes.Wpf.Snackbar Snackbar; + + private bool _contentLoaded; + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public TrocarClienteView(Documento documento) + { + this.ViewModel = new TrocarClienteViewModel() + { + SelectedDocumento = documento + }; + base.DataContext = this.ViewModel; + this.InitializeComponent(); + } + + private void AutoCompleteBox_Populating(object sender, PopulatingEventArgs e) + { + if (e.get_Parameter().Length < 3) + { + return; + } + e.set_Cancel(true); + this.ViewModel.BuscarCliente(ValidationHelper.RemoveDiacritics(e.get_Parameter().Trim()), null, 2).ContinueWith((Task> searchResult) => { + if (searchResult.Result == null) + { + return; + } + AutoCompleteBox autoCompleteBox = (AutoCompleteBox)sender; + autoCompleteBox.set_ItemsSource(searchResult.Result); + autoCompleteBox.PopulateComplete(); + }, TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void CloseSlackBar() + { + Thread.Sleep(5000); + System.Windows.Threading.Dispatcher dispatcher = this.ProgressBar.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => this.ToggleSnackBar("", false))); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/seguros/trocarclienteview.xaml", UriKind.Relative)); + } + + private async void Salvar_OnClick(object sender, RoutedEventArgs e) + { + if (!await this.ViewModel.Salvar()) + { + this.ToggleSnackBar("ERRO AO TROCAR CLIENTE.", true); + } + else + { + this.ToggleSnackBar("CLIENTE TROCADO COM SUCESSO.", true); + } + } + + private void SnackbarMessage_ActionClick(object sender, RoutedEventArgs e) + { + this.Snackbar.set_IsActive(false); + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.ProgressBar = (System.Windows.Controls.ProgressBar)target; + return; + } + case 2: + { + ((MenuItem)target).Click += new RoutedEventHandler(this.Salvar_OnClick); + return; + } + case 3: + { + ((AutoCompleteBox)target).add_Populating(new PopulatingEventHandler(this, TrocarClienteView.AutoCompleteBox_Populating)); + return; + } + case 4: + { + this.Snackbar = (MaterialDesignThemes.Wpf.Snackbar)target; + return; + } + case 5: + { + ((SnackbarMessage)target).add_ActionClick(new RoutedEventHandler(this.SnackbarMessage_ActionClick)); + return; + } + } + this._contentLoaded = true; + } + + public void ToggleSnackBar(string message, bool active = true) + { + this.Snackbar.get_Message().Content = message; + this.Snackbar.set_IsActive(active); + if (!active) + { + return; + } + Task.Factory.StartNew(new Action(this.CloseSlackBar)); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/Views/TutorialView.cs b/Codemerx/Gestor.Application/Views/TutorialView.cs new file mode 100644 index 0000000..10e45ae --- /dev/null +++ b/Codemerx/Gestor.Application/Views/TutorialView.cs @@ -0,0 +1,369 @@ +using Gestor.Application; +using Gestor.Application.Componentes; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using System; +using System.CodeDom.Compiler; +using System.ComponentModel; +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Media; +using System.Windows.Shapes; +using System.Windows.Shell; +using System.Windows.Threading; + +namespace Gestor.Application.Views +{ + public class TutorialView : Window, IComponentConnector + { + public TutorialViewModel ViewModel; + + private bool _buttonClickable; + + internal System.Windows.Shell.WindowChrome WindowChrome; + + internal Grid CloseButton; + + internal Grid ProgressRing; + + internal Image ProgressBar; + + internal TextBox NomeBox; + + internal TextBox UserBox; + + internal CustomSenhaLoginBox PasswordBox; + + internal CustomSenhaLoginBox ConfirmacaoBox; + + private bool _contentLoaded; + + private Tuple PrimeiroAcesso + { + get; + set; + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + internal Delegate _CreateDelegate(Type delegateType, string handler) + { + return Delegate.CreateDelegate(delegateType, this, handler); + } + + public TutorialView(Tuple primeiroacesso) + { + this.PrimeiroAcesso = primeiroacesso; + this.ViewModel = new TutorialViewModel(); + base.DataContext = this.ViewModel; + this.InitializeComponent(); + System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; + if (dispatcher != null) + { + dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(this.ContentLoad)); + } + else + { + } + this.CloseButton.MouseEnter += new MouseEventHandler(TutorialView.TopControls_OnMouseEnter); + this.CloseButton.MouseLeave += new MouseEventHandler(this.TopControls_OnMouseLeave); + } + + public void CloseButton_Click() + { + base.Close(); + } + + private async void Concluir_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.EnableFields = false; + this.Loading(true); + bool flag = await this.ViewModel.Concluir(); + this.Loading(false); + this.ViewModel.EnableFields = true; + if (!flag) + { + base.Close(); + } + else if (await this.ViewModel.VerificaAcesso()) + { + (new MainWindow()).Show(); + base.Close(); + } + else + { + base.Close(); + } + } + + private void ConfirmacaoBox_LostFocus(object sender, RoutedEventArgs e) + { + this.ViewModel.ConfirmacaoSenha = this.ConfirmacaoBox.Text; + } + + private async void ContentLoad() + { + string str = null; + this.Loading(true); + if (this.PrimeiroAcesso.Item1) + { + await this.ViewModel.VerificarUsuario(); + } + else + { + str = await this.ViewModel.CriarBanco(); + } + this.Loading(false); + if (str == null) + { + str = await this.ViewModel.VerificaEmpresa(); + if (str == null) + { + this.ViewModel.Fase1 = true; + await this.ViewModel.IniciarConfiguracoes(); + } + else + { + await this.ViewModel.ShowMessage(str, "OK", "", false); + } + } + else + { + await this.ViewModel.ShowMessage(str, "OK", "", false); + } + str = null; + } + + private void DestativarTodasAsSeguradoras_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.DesativarSeguradoras(); + } + + private void DestativarTodosOsRamos_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.DesativarRamos(); + } + + [DebuggerNonUserCode] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + public void InitializeComponent() + { + if (this._contentLoaded) + { + return; + } + this._contentLoaded = true; + System.Windows.Application.LoadComponent(this, new Uri("/Gestor.Application;component/views/tutorialview.xaml", UriKind.Relative)); + } + + private void Loading(bool loading) + { + if (loading) + { + TutorialViewModel viewModel = this.ViewModel; + TutorialViewModel tutorialViewModel = this.ViewModel; + int num = 0; + bool flag = (bool)num; + this.ViewModel.Fase3 = (bool)num; + bool flag1 = flag; + bool flag2 = flag1; + tutorialViewModel.Fase2 = flag1; + viewModel.Fase1 = flag2; + } + this.ViewModel.LoadingVisibility = loading; + } + + protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) + { + Size newSize; + base.OnRenderSizeChanged(sizeInfo); + if (sizeInfo.HeightChanged) + { + double top = base.Top; + double height = sizeInfo.PreviousSize.Height; + newSize = sizeInfo.NewSize; + base.Top = top + (height - newSize.Height) / 2; + } + if (sizeInfo.WidthChanged) + { + double left = base.Left; + double width = sizeInfo.PreviousSize.Width; + newSize = sizeInfo.NewSize; + base.Left = left + (width - newSize.Width) / 2; + } + } + + private void PasswordBox_LostFocus(object sender, RoutedEventArgs e) + { + this.ViewModel.Senha = this.PasswordBox.Text; + } + + private async void ProsseguirFase1_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.EnableFields = false; + this.Loading(true); + if (!await this.ViewModel.ValidarLogin()) + { + base.Close(); + } + this.Loading(false); + this.ViewModel.EnableFields = true; + } + + private async void ProsseguirFase2_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.EnableFields = false; + this.Loading(true); + await this.ViewModel.ValidarSeguradoras(); + this.Loading(false); + this.ViewModel.EnableFields = true; + } + + [DebuggerNonUserCode] + [EditorBrowsable(EditorBrowsableState.Never)] + [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] + void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) + { + switch (connectionId) + { + case 1: + { + this.WindowChrome = (System.Windows.Shell.WindowChrome)target; + return; + } + case 2: + { + this.CloseButton = (Grid)target; + this.CloseButton.MouseLeftButtonDown += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonDown); + this.CloseButton.MouseLeftButtonUp += new MouseButtonEventHandler(this.TopControls_OnMouseLeftButtonUp); + return; + } + case 3: + { + this.ProgressRing = (Grid)target; + return; + } + case 4: + { + this.ProgressBar = (Image)target; + return; + } + case 5: + { + this.NomeBox = (TextBox)target; + return; + } + case 6: + { + this.UserBox = (TextBox)target; + return; + } + case 7: + { + this.PasswordBox = (CustomSenhaLoginBox)target; + return; + } + case 8: + { + this.ConfirmacaoBox = (CustomSenhaLoginBox)target; + return; + } + case 9: + { + ((RepeatButton)target).Click += new RoutedEventHandler(this.ProsseguirFase1_OnClick); + return; + } + case 10: + { + ((RepeatButton)target).Click += new RoutedEventHandler(this.DestativarTodasAsSeguradoras_OnClick); + return; + } + case 11: + { + ((RepeatButton)target).Click += new RoutedEventHandler(this.VoltarFase2_OnClick); + return; + } + case 12: + { + ((RepeatButton)target).Click += new RoutedEventHandler(this.ProsseguirFase2_OnClick); + return; + } + case 13: + { + ((RepeatButton)target).Click += new RoutedEventHandler(this.DestativarTodosOsRamos_OnClick); + return; + } + case 14: + { + ((RepeatButton)target).Click += new RoutedEventHandler(this.VoltarFase3_OnClick); + return; + } + case 15: + { + ((RepeatButton)target).Click += new RoutedEventHandler(this.Concluir_OnClick); + return; + } + } + this._contentLoaded = true; + } + + private static void TopControls_OnMouseEnter(object sender, MouseEventArgs e) + { + ((Grid)sender).Background = (((Grid)sender).Name == "CloseButton" ? new SolidColorBrush(Colors.IndianRed) : new SolidColorBrush(Colors.Gray)); + Path child = VisualTreeHelper.GetChild((Grid)sender, 0) as Path; + if (child != null) + { + child.Stroke = new SolidColorBrush(Colors.White); + } + } + + private void TopControls_OnMouseLeave(object sender, MouseEventArgs e) + { + this._buttonClickable = false; + ((Grid)sender).Background = new SolidColorBrush(Colors.Transparent); + Path child = VisualTreeHelper.GetChild((Grid)sender, 0) as Path; + if (child != null) + { + child.Stroke = new SolidColorBrush(Colors.White); + } + } + + private void TopControls_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e) + { + this._buttonClickable = true; + ((Grid)sender).Background = (((Grid)sender).Name == "CloseButton" ? new SolidColorBrush(Colors.Red) : new SolidColorBrush(Colors.DimGray)); + } + + private void TopControls_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e) + { + if (this._buttonClickable) + { + MethodInfo method = base.GetType().GetMethod(string.Concat(((Grid)sender).Name, "_Click")); + if (method == null) + { + return; + } + method.Invoke(this, null); + } + } + + private void VoltarFase2_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Fase1 = true; + this.ViewModel.Fase2 = false; + } + + private void VoltarFase3_OnClick(object sender, RoutedEventArgs e) + { + this.ViewModel.Fase2 = true; + this.ViewModel.Fase3 = false; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/ApolicePendenteConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/ApolicePendenteConverter.cs new file mode 100644 index 0000000..ae3003e --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/ApolicePendenteConverter.cs @@ -0,0 +1,33 @@ +using System; +using System.Globalization; +using System.Windows.Data; +using System.Windows.Markup; + +namespace Gestor.Common.Converters +{ + public class ApolicePendenteConverter : MarkupExtension, IValueConverter + { + public ApolicePendenteConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value != null && !string.IsNullOrEmpty((string)value)) + { + return value; + } + return "PENDENTE DE EMISSÃO"; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return null; + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/ArquivoDigitalToolTipConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/ArquivoDigitalToolTipConverter.cs new file mode 100644 index 0000000..3c9e6dc --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/ArquivoDigitalToolTipConverter.cs @@ -0,0 +1,38 @@ +using Gestor.Model.Domain.Common; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Runtime.CompilerServices; +using System.Windows.Data; +using System.Windows.Markup; + +namespace Gestor.Common.Converters +{ + public class ArquivoDigitalToolTipConverter : MarkupExtension, IValueConverter + { + public ArquivoDigitalToolTipConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value == null || ((List)value).Count == 0) + { + return ""; + } + return string.Join(Environment.NewLine, + from v in (List)value + select v.Descricao); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return null; + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/AtivoConverterColor.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/AtivoConverterColor.cs new file mode 100644 index 0000000..cc99edf --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/AtivoConverterColor.cs @@ -0,0 +1,35 @@ +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; +using System.Windows.Markup; +using System.Windows.Media; + +namespace Gestor.Common.Converters +{ + public class AtivoConverterColor : MarkupExtension, IValueConverter + { + public AtivoConverterColor() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value == null || !(bool)value) + { + return new SolidColorBrush(Colors.Red); + } + return new SolidColorBrush((Color)Application.Current.Resources["AggerBlue"]); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return null; + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/AtivoVisibilityConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/AtivoVisibilityConverter.cs new file mode 100644 index 0000000..d8ffe3f --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/AtivoVisibilityConverter.cs @@ -0,0 +1,38 @@ +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; + +namespace Gestor.Common.Converters +{ + public class AtivoVisibilityConverter : IMultiValueConverter + { + public AtivoVisibilityConverter() + { + } + + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) + { + object obj = values[0]; + if (obj is bool && (bool)obj) + { + return Visibility.Collapsed; + } + if (values[1] == null) + { + return Visibility.Visible; + } + obj = values[1]; + if (obj is long && (long)obj > (long)0) + { + return Visibility.Collapsed; + } + return Visibility.Visible; + } + + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) + { + return null; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/BoolToEyeConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/BoolToEyeConverter.cs new file mode 100644 index 0000000..062b96b --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/BoolToEyeConverter.cs @@ -0,0 +1,37 @@ +using System; +using System.Globalization; +using System.Windows.Data; +using System.Windows.Markup; + +namespace Gestor.Common.Converters +{ + public class BoolToEyeConverter : MarkupExtension, IValueConverter + { + public BoolToEyeConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value == null) + { + return "Eye"; + } + if (!(bool)value) + { + return "Eye"; + } + return "EyeOff"; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return (value == null || string.IsNullOrEmpty(value.ToString()) ? 0 : int.Parse(value.ToString())); + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/BoolToYesNoConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/BoolToYesNoConverter.cs new file mode 100644 index 0000000..529a9e7 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/BoolToYesNoConverter.cs @@ -0,0 +1,33 @@ +using System; +using System.Globalization; +using System.Windows.Data; +using System.Windows.Markup; + +namespace Gestor.Common.Converters +{ + public class BoolToYesNoConverter : MarkupExtension, IValueConverter + { + public BoolToYesNoConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value != null && (bool)value) + { + return "SIM"; + } + return "NÃO"; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return null; + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/ComissaoColorConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/ComissaoColorConverter.cs new file mode 100644 index 0000000..88df822 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/ComissaoColorConverter.cs @@ -0,0 +1,39 @@ +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; +using System.Windows.Markup; +using System.Windows.Media; + +namespace Gestor.Common.Converters +{ + public class ComissaoColorConverter : MarkupExtension, IValueConverter + { + public ComissaoColorConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value == null) + { + return new SolidColorBrush(Colors.Red); + } + if ((int)Math.Round(double.Parse(value.ToString())) >= 0 && (int)Math.Round(double.Parse(value.ToString())) != 0) + { + return new SolidColorBrush(Colors.Red); + } + return new SolidColorBrush((Color)Application.Current.Resources["AggerBlue"]); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return (value == null || string.IsNullOrEmpty(value.ToString()) ? 0 : int.Parse(value.ToString())); + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/ComissaoConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/ComissaoConverter.cs new file mode 100644 index 0000000..d66a902 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/ComissaoConverter.cs @@ -0,0 +1,43 @@ +using System; +using System.Globalization; +using System.Windows.Data; +using System.Windows.Markup; + +namespace Gestor.Common.Converters +{ + public class ComissaoConverter : MarkupExtension, IValueConverter + { + public ComissaoConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + decimal? nullable; + decimal? nullable1; + decimal? nullable2 = (decimal?)value; + decimal num = 100; + if (nullable2.HasValue) + { + nullable1 = new decimal?(nullable2.GetValueOrDefault() / num); + } + else + { + nullable = null; + nullable1 = nullable; + } + nullable = nullable1; + return nullable.GetValueOrDefault(); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return null; + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/ComissaoConverterMulti.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/ComissaoConverterMulti.cs new file mode 100644 index 0000000..5797387 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/ComissaoConverterMulti.cs @@ -0,0 +1,74 @@ +using Gestor.Model.Common; +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; + +namespace Gestor.Common.Converters +{ + public class ComissaoConverterMulti : IMultiValueConverter + { + public ComissaoConverterMulti() + { + } + + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) + { + decimal? nullable; + decimal? nullable1; + if (values[0] == DependencyProperty.UnsetValue && values[1] == DependencyProperty.UnsetValue) + { + return null; + } + if (values[1] == DependencyProperty.UnsetValue) + { + return values[0]; + } + object obj = values[0]; + TipoRepasse tipoRepasse = (TipoRepasse)values[1]; + string lower = parameter.ToString().ToLower(); + if (lower == "tipovendedorcolumn") + { + if (tipoRepasse == TipoRepasse.CoCorretagem) + { + return "CO-CORRETAGEM"; + } + return obj; + } + if (lower == "formapagamentocolumn" || lower == "incidenciacolumn") + { + if (tipoRepasse == TipoRepasse.CoCorretagem) + { + return "--"; + } + return obj; + } + if (lower == "pagamentosvalorrepassecolumn" || lower == "repassevendedor") + { + return obj; + } + if (tipoRepasse == TipoRepasse.ValorFixo) + { + return "--"; + } + decimal? nullable2 = (decimal?)obj; + decimal num = 100; + if (nullable2.HasValue) + { + nullable1 = new decimal?(nullable2.GetValueOrDefault() / num); + } + else + { + nullable = null; + nullable1 = nullable; + } + nullable = nullable1; + return nullable.GetValueOrDefault(); + } + + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) + { + return null; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/ComparativoColorConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/ComparativoColorConverter.cs new file mode 100644 index 0000000..700be13 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/ComparativoColorConverter.cs @@ -0,0 +1,71 @@ +using System; +using System.Globalization; +using System.Windows.Data; +using System.Windows.Media; + +namespace Gestor.Common.Converters +{ + public class ComparativoColorConverter : IMultiValueConverter + { + public ComparativoColorConverter() + { + } + + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) + { + decimal num; + decimal num1; + object darkGoldenrod; + try + { + if (values[0] == null) + { + darkGoldenrod = 0; + } + else if (values[1] != null) + { + num = (!(values[0] is int) ? ((decimal?)values[0]).GetValueOrDefault() : (int)values[0]); + num1 = (!(values[1] is int) ? ((decimal?)values[1]).GetValueOrDefault() : (int)values[1]); + if (num == decimal.Zero && num1 == decimal.Zero) + { + darkGoldenrod = Brushes.DarkGoldenrod; + } + else if (num == decimal.Zero && num1 > decimal.Zero) + { + darkGoldenrod = Brushes.Red; + } + else if (num1 == decimal.Zero && num > decimal.Zero) + { + darkGoldenrod = Brushes.Green; + } + else if (num == decimal.Zero && num1 < decimal.Zero) + { + darkGoldenrod = Brushes.Green; + } + else if (!(num1 == decimal.Zero) || !(num < decimal.Zero)) + { + darkGoldenrod = (((num / num1) - decimal.One) > decimal.Zero ? Brushes.Green : Brushes.Red); + } + else + { + darkGoldenrod = Brushes.Red; + } + } + else + { + darkGoldenrod = 0; + } + } + catch (Exception exception) + { + darkGoldenrod = Brushes.Black; + } + return darkGoldenrod; + } + + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) + { + return null; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/ComparativoConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/ComparativoConverter.cs new file mode 100644 index 0000000..fb7ee01 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/ComparativoConverter.cs @@ -0,0 +1,55 @@ +using System; +using System.Globalization; +using System.Windows.Data; + +namespace Gestor.Common.Converters +{ + public class ComparativoConverter : IMultiValueConverter + { + public ComparativoConverter() + { + } + + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) + { + decimal num; + decimal num1; + if (values[0] == null) + { + return 0; + } + if (values[1] == null) + { + return 0; + } + num = (!(values[0] is int) ? ((decimal?)values[0]).GetValueOrDefault() : (int)values[0]); + num1 = (!(values[1] is int) ? ((decimal?)values[1]).GetValueOrDefault() : (int)values[1]); + if (num == decimal.Zero && num1 == decimal.Zero) + { + return 0; + } + if (num == decimal.Zero && num1 > decimal.Zero) + { + return -1; + } + if (num1 == decimal.Zero && num > decimal.Zero) + { + return 1; + } + if (num == decimal.Zero && num1 < decimal.Zero) + { + return 1; + } + if (num1 == decimal.Zero && num < decimal.Zero) + { + return -1; + } + return (num - num1) / (num1 > decimal.Zero ? num1 : -num1); + } + + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) + { + return null; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/ComparativoPercentualToolTipConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/ComparativoPercentualToolTipConverter.cs new file mode 100644 index 0000000..a978ec0 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/ComparativoPercentualToolTipConverter.cs @@ -0,0 +1,33 @@ +using System; +using System.Globalization; +using System.Windows.Data; + +namespace Gestor.Common.Converters +{ + public class ComparativoPercentualToolTipConverter : IMultiValueConverter + { + public ComparativoPercentualToolTipConverter() + { + } + + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) + { + object obj; + try + { + decimal num = (decimal)values[1] * new decimal(100); + obj = string.Format("VALOR EM {0}: {1}%", values[0], num); + } + catch (Exception exception) + { + obj = ""; + } + return obj; + } + + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) + { + return null; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/ComparativoToolTipConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/ComparativoToolTipConverter.cs new file mode 100644 index 0000000..c10c19a --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/ComparativoToolTipConverter.cs @@ -0,0 +1,24 @@ +using System; +using System.Globalization; +using System.Windows.Data; + +namespace Gestor.Common.Converters +{ + public class ComparativoToolTipConverter : IMultiValueConverter + { + public ComparativoToolTipConverter() + { + } + + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) + { + string str = (!(values[0] is int) ? "R$" : ""); + return string.Format("VALOR EM {0}: {1} {2}", values[0], str, values[1]); + } + + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) + { + return null; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/EnumDescriptionConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/EnumDescriptionConverter.cs new file mode 100644 index 0000000..64de689 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/EnumDescriptionConverter.cs @@ -0,0 +1,34 @@ +using Gestor.Common.Validation; +using System; +using System.Globalization; +using System.Windows.Data; +using System.Windows.Markup; + +namespace Gestor.Common.Converters +{ + public class EnumDescriptionConverter : MarkupExtension, IValueConverter + { + public EnumDescriptionConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (!(value is Enum)) + { + return ""; + } + return ((Enum)value).GetDescription(); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return null; + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/ExpanderHeaderConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/ExpanderHeaderConverter.cs new file mode 100644 index 0000000..8e65056 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/ExpanderHeaderConverter.cs @@ -0,0 +1,33 @@ +using System; +using System.Globalization; +using System.Windows.Data; +using System.Windows.Markup; + +namespace Gestor.Common.Converters +{ + public class ExpanderHeaderConverter : MarkupExtension, IValueConverter + { + public ExpanderHeaderConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value != null && (bool)value) + { + return "MENOS INFORMAÇÕES"; + } + return "MAIS INFORMAÇÕES"; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return null; + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/IdToVisibilityConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/IdToVisibilityConverter.cs new file mode 100644 index 0000000..ff9f6a3 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/IdToVisibilityConverter.cs @@ -0,0 +1,30 @@ +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; +using System.Windows.Markup; + +namespace Gestor.Common.Converters +{ + public class IdToVisibilityConverter : MarkupExtension, IValueConverter + { + public IdToVisibilityConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + return (value == null || (int)Math.Round(double.Parse(value.ToString())) == 0 ? Visibility.Visible : Visibility.Collapsed); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return (value == null || string.IsNullOrEmpty(value.ToString()) ? 0 : int.Parse(value.ToString())); + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/InativoVisibilityConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/InativoVisibilityConverter.cs new file mode 100644 index 0000000..4969d70 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/InativoVisibilityConverter.cs @@ -0,0 +1,38 @@ +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; + +namespace Gestor.Common.Converters +{ + public class InativoVisibilityConverter : IMultiValueConverter + { + public InativoVisibilityConverter() + { + } + + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) + { + object obj = values[0]; + if (obj is bool && (bool)obj) + { + return Visibility.Visible; + } + if (values[1] == null) + { + return Visibility.Collapsed; + } + obj = values[1]; + if (obj is long && (long)obj > (long)0) + { + return Visibility.Visible; + } + return Visibility.Collapsed; + } + + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) + { + return null; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/InvertedBooleanConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/InvertedBooleanConverter.cs new file mode 100644 index 0000000..a0c0284 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/InvertedBooleanConverter.cs @@ -0,0 +1,29 @@ +using System; +using System.Globalization; +using System.Windows.Data; +using System.Windows.Markup; + +namespace Gestor.Common.Converters +{ + public class InvertedBooleanConverter : MarkupExtension, IValueConverter + { + public InvertedBooleanConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + return (value == null ? false : !(bool)value); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return null; + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/InvertedBooleanToVisibilityConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/InvertedBooleanToVisibilityConverter.cs new file mode 100644 index 0000000..9170c1e --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/InvertedBooleanToVisibilityConverter.cs @@ -0,0 +1,30 @@ +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; +using System.Windows.Markup; + +namespace Gestor.Common.Converters +{ + public class InvertedBooleanToVisibilityConverter : MarkupExtension, IValueConverter + { + public InvertedBooleanToVisibilityConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + return (value == null || !(bool)value ? Visibility.Visible : Visibility.Collapsed); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return null; + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/InvertedVisibilityConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/InvertedVisibilityConverter.cs new file mode 100644 index 0000000..34067d0 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/InvertedVisibilityConverter.cs @@ -0,0 +1,30 @@ +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; +using System.Windows.Markup; + +namespace Gestor.Common.Converters +{ + public class InvertedVisibilityConverter : MarkupExtension, IValueConverter + { + public InvertedVisibilityConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + return (value == null || (Visibility)value != Visibility.Visible ? Visibility.Visible : Visibility.Collapsed); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return null; + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/IsInsertedBoolConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/IsInsertedBoolConverter.cs new file mode 100644 index 0000000..341ff5e --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/IsInsertedBoolConverter.cs @@ -0,0 +1,29 @@ +using System; +using System.Globalization; +using System.Windows.Data; +using System.Windows.Markup; + +namespace Gestor.Common.Converters +{ + public class IsInsertedBoolConverter : MarkupExtension, IValueConverter + { + public IsInsertedBoolConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + return (value == null ? false : (long)value != (long)0); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return null; + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/IsNotNullBoolConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/IsNotNullBoolConverter.cs new file mode 100644 index 0000000..afd3293 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/IsNotNullBoolConverter.cs @@ -0,0 +1,29 @@ +using System; +using System.Globalization; +using System.Windows.Data; +using System.Windows.Markup; + +namespace Gestor.Common.Converters +{ + public class IsNotNullBoolConverter : MarkupExtension, IValueConverter + { + public IsNotNullBoolConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + return value != null; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return null; + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/MesConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/MesConverter.cs new file mode 100644 index 0000000..825d4b9 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/MesConverter.cs @@ -0,0 +1,39 @@ +using Gestor.Common.Validation; +using Gestor.Model.Common; +using System; +using System.Globalization; +using System.Windows.Data; +using System.Windows.Markup; + +namespace Gestor.Common.Converters +{ + public class MesConverter : MarkupExtension, IValueConverter + { + public MesConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value == null) + { + return ""; + } + if (!(value is Mes)) + { + return ""; + } + return (Mes)value.GetDescription(); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return null; + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/MultiBoolAndConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/MultiBoolAndConverter.cs new file mode 100644 index 0000000..e59ded6 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/MultiBoolAndConverter.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Windows.Data; + +namespace Gestor.Common.Converters +{ + public class MultiBoolAndConverter : IMultiValueConverter + { + public MultiBoolAndConverter() + { + } + + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) + { + object obj; + try + { + obj = ((IEnumerable)values).All((object value) => (bool)value); + } + catch + { + obj = false; + } + return obj; + } + + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) + { + return null; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/NegativoColorConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/NegativoColorConverter.cs new file mode 100644 index 0000000..4d0ca3a --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/NegativoColorConverter.cs @@ -0,0 +1,38 @@ +using System; +using System.Globalization; +using System.Windows.Data; +using System.Windows.Markup; +using System.Windows.Media; + +namespace Gestor.Common.Converters +{ + public class NegativoColorConverter : MarkupExtension, IValueConverter + { + public NegativoColorConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value == null || string.IsNullOrEmpty(value.ToString())) + { + return new SolidColorBrush(Colors.Black); + } + if (!value.ToString().Contains("-")) + { + return new SolidColorBrush(Colors.Black); + } + return new SolidColorBrush(Colors.Red); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return null; + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/NullVisibilityConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/NullVisibilityConverter.cs new file mode 100644 index 0000000..25b4679 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/NullVisibilityConverter.cs @@ -0,0 +1,30 @@ +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; +using System.Windows.Markup; + +namespace Gestor.Common.Converters +{ + public class NullVisibilityConverter : MarkupExtension, IValueConverter + { + public NullVisibilityConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + return (value != null ? Visibility.Visible : Visibility.Collapsed); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return null; + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/NullVisibilityInvertedConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/NullVisibilityInvertedConverter.cs new file mode 100644 index 0000000..5e26f34 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/NullVisibilityInvertedConverter.cs @@ -0,0 +1,30 @@ +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; +using System.Windows.Markup; + +namespace Gestor.Common.Converters +{ + public class NullVisibilityInvertedConverter : MarkupExtension, IValueConverter + { + public NullVisibilityInvertedConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + return (value != null ? Visibility.Collapsed : Visibility.Visible); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return null; + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/ObjectToStringConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/ObjectToStringConverter.cs new file mode 100644 index 0000000..5d36295 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/ObjectToStringConverter.cs @@ -0,0 +1,56 @@ +using System; +using System.ComponentModel; +using System.Globalization; +using System.Linq; +using System.Reflection; +using System.Windows.Data; + +namespace Gestor.Common.Converters +{ + public class ObjectToStringConverter : IValueConverter + { + public readonly static ObjectToStringConverter Instance; + + static ObjectToStringConverter() + { + ObjectToStringConverter.Instance = new ObjectToStringConverter(); + } + + public ObjectToStringConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + Enum @enum = value as Enum; + if (@enum == null) + { + if (value is DateTime) + { + return ((DateTime)value).ToShortDateString(); + } + if (value == null) + { + return null; + } + return value.ToString(); + } + MemberInfo[] member = @enum.GetType().GetMember(@enum.ToString()); + if (member.Length == 0) + { + return @enum.ToString(); + } + object[] customAttributes = member[0].GetCustomAttributes(typeof(DescriptionAttribute), false); + if (!customAttributes.Any()) + { + return @enum.ToString().Trim(); + } + return ((DescriptionAttribute)customAttributes.ElementAt(0)).Description.Trim(); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return null; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/ObjectVisibilityConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/ObjectVisibilityConverter.cs new file mode 100644 index 0000000..c17787e --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/ObjectVisibilityConverter.cs @@ -0,0 +1,31 @@ +using Gestor.Model.Common; +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; +using System.Windows.Markup; + +namespace Gestor.Common.Converters +{ + public class ObjectVisibilityConverter : MarkupExtension, IValueConverter + { + public ObjectVisibilityConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + return (value == null || (TipoTelefone)value != TipoTelefone.Gratuita && (TipoTelefone)value != TipoTelefone.TarifaUnica ? Visibility.Visible : Visibility.Collapsed); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return null; + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/PagamentoVendedorCorretoraVisibilityConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/PagamentoVendedorCorretoraVisibilityConverter.cs new file mode 100644 index 0000000..421b4e7 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/PagamentoVendedorCorretoraVisibilityConverter.cs @@ -0,0 +1,28 @@ +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; + +namespace Gestor.Common.Converters +{ + public class PagamentoVendedorCorretoraVisibilityConverter : IMultiValueConverter + { + public PagamentoVendedorCorretoraVisibilityConverter() + { + } + + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) + { + if (values[1] is bool && values[0] == null && (bool)values[1]) + { + return Visibility.Collapsed; + } + return Visibility.Visible; + } + + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) + { + return null; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/ParcelaVisibilityConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/ParcelaVisibilityConverter.cs new file mode 100644 index 0000000..7bbfdaa --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/ParcelaVisibilityConverter.cs @@ -0,0 +1,31 @@ +using Gestor.Model.Common; +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; +using System.Windows.Markup; + +namespace Gestor.Common.Converters +{ + public class ParcelaVisibilityConverter : MarkupExtension, IValueConverter + { + public ParcelaVisibilityConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + return (value == null || (TipoRecebimento)value != TipoRecebimento.Fatura ? Visibility.Visible : Visibility.Collapsed); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return null; + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/PendenciaConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/PendenciaConverter.cs new file mode 100644 index 0000000..b2ab4e6 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/PendenciaConverter.cs @@ -0,0 +1,35 @@ +using Gestor.Common.Helpers; +using System; +using System.Globalization; +using System.Windows.Data; +using System.Windows.Markup; + +namespace Gestor.Common.Converters +{ + public class PendenciaConverter : MarkupExtension, IValueConverter + { + public PendenciaConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value == null) + { + return ""; + } + TimeSpan date = Functions.GetNetworkTime().Date - ((DateTime)value).Date; + return string.Format("{0:N0} DIAS", date.TotalDays); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return null; + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/PendenciaVisibilityConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/PendenciaVisibilityConverter.cs new file mode 100644 index 0000000..c05b93f --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/PendenciaVisibilityConverter.cs @@ -0,0 +1,35 @@ +using Gestor.Common.Helpers; +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; +using System.Windows.Markup; + +namespace Gestor.Common.Converters +{ + public class PendenciaVisibilityConverter : MarkupExtension, IValueConverter + { + public PendenciaVisibilityConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value == null) + { + return ""; + } + return (Functions.GetNetworkTime().Date < (DateTime)value ? Visibility.Collapsed : Visibility.Visible); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return null; + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/RamoAutoVisibilityConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/RamoAutoVisibilityConverter.cs new file mode 100644 index 0000000..353da3c --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/RamoAutoVisibilityConverter.cs @@ -0,0 +1,50 @@ +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; +using System.Windows.Markup; + +namespace Gestor.Common.Converters +{ + public class RamoAutoVisibilityConverter : MarkupExtension, IValueConverter + { + public RamoAutoVisibilityConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + bool ramo; + Documento documento = (Documento)value; + if (documento != null) + { + Controle controle = documento.Controle; + if (controle != null) + { + ramo = controle.Ramo; + } + else + { + ramo = false; + } + } + else + { + ramo = false; + } + return (!ramo || ((Documento)value).Controle.Ramo.Id != (long)5 && ((Documento)value).Controle.Ramo.Id != (long)2 ? Visibility.Collapsed : Visibility.Visible); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return null; + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/RecebidoColorConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/RecebidoColorConverter.cs new file mode 100644 index 0000000..e068a77 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/RecebidoColorConverter.cs @@ -0,0 +1,32 @@ +using System; +using System.Globalization; +using System.Windows.Data; +using System.Windows.Media; + +namespace Gestor.Common.Converters +{ + public class RecebidoColorConverter : IMultiValueConverter + { + public RecebidoColorConverter() + { + } + + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) + { + if (values[1] != null) + { + return new SolidColorBrush(Colors.Green); + } + if ((DateTime)values[0] >= DateTime.Today) + { + return new SolidColorBrush(Colors.Black); + } + return new SolidColorBrush(Colors.Red); + } + + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) + { + return null; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/SaldoWeightConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/SaldoWeightConverter.cs new file mode 100644 index 0000000..78482d3 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/SaldoWeightConverter.cs @@ -0,0 +1,30 @@ +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; +using System.Windows.Markup; + +namespace Gestor.Common.Converters +{ + public class SaldoWeightConverter : MarkupExtension, IValueConverter + { + public SaldoWeightConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + return (value == null || (bool)value ? FontWeights.Bold : FontWeights.Regular); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return null; + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/SinalColorConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/SinalColorConverter.cs new file mode 100644 index 0000000..895a11e --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/SinalColorConverter.cs @@ -0,0 +1,35 @@ +using Gestor.Model.Common; +using System; +using System.Globalization; +using System.Windows.Data; +using System.Windows.Markup; +using System.Windows.Media; + +namespace Gestor.Common.Converters +{ + public class SinalColorConverter : MarkupExtension, IValueConverter + { + public SinalColorConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value != null && (Sinal)value == Sinal.Debito) + { + return new SolidColorBrush(Colors.Red); + } + return new SolidColorBrush(Colors.Black); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return null; + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/StatusExtratoColorConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/StatusExtratoColorConverter.cs new file mode 100644 index 0000000..d6e2fba --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/StatusExtratoColorConverter.cs @@ -0,0 +1,65 @@ +using Gestor.Model.Common; +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; +using System.Windows.Markup; +using System.Windows.Media; + +namespace Gestor.Common.Converters +{ + public class StatusExtratoColorConverter : MarkupExtension, IValueConverter + { + public StatusExtratoColorConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value == null) + { + return new SolidColorBrush(Colors.Black); + } + switch ((StatusParcela)value) + { + case StatusParcela.Baixada: + case StatusParcela.BaixadaAnteriormente: + case StatusParcela.BaixadaDiferencaPercentual: + case StatusParcela.BaixadaManualmente: + case StatusParcela.ParcelaEspecialBaixadaAnteriormente: + { + return new SolidColorBrush(Colors.Green); + } + case StatusParcela.DocumentoNaoEncontrado: + case StatusParcela.ParcelaNaoEncontrada: + case StatusParcela.DesconsideradaUsuario: + case StatusParcela.ParcelaAnteriorNaoBaixada: + { + return new SolidColorBrush(Colors.Red); + } + case StatusParcela.DesconsideradaSistema: + { + return new SolidColorBrush(Colors.Gray); + } + case StatusParcela.ApoliceDuplicada: + { + return new SolidColorBrush((Color)Application.Current.Resources["AggerYellow100"]); + } + default: + { + return new SolidColorBrush(Colors.Black); + } + } + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return (value == null || string.IsNullOrEmpty(value.ToString()) ? 0 : int.Parse(value.ToString())); + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/StatusParcelaVisibilityConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/StatusParcelaVisibilityConverter.cs new file mode 100644 index 0000000..41efabb --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/StatusParcelaVisibilityConverter.cs @@ -0,0 +1,42 @@ +using Gestor.Model.Common; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Windows; +using System.Windows.Data; +using System.Windows.Markup; + +namespace Gestor.Common.Converters +{ + public class StatusParcelaVisibilityConverter : MarkupExtension, IValueConverter + { + public StatusParcelaVisibilityConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value == null) + { + return Visibility.Collapsed; + } + return ((new List() + { + StatusParcela.Baixada, + StatusParcela.BaixadaDiferencaPercentual, + StatusParcela.BaixadaManualmente, + StatusParcela.BaixadaCritica + }).Contains((StatusParcela)value) ? Visibility.Visible : Visibility.Collapsed); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return null; + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/StatusTarefaVisibilityConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/StatusTarefaVisibilityConverter.cs new file mode 100644 index 0000000..4a6184c --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/StatusTarefaVisibilityConverter.cs @@ -0,0 +1,43 @@ +using Gestor.Model.Common; +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; +using System.Windows.Markup; + +namespace Gestor.Common.Converters +{ + public class StatusTarefaVisibilityConverter : MarkupExtension, IValueConverter + { + public StatusTarefaVisibilityConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + bool flag = false; + Visibility visibility; + bool flag1 = (parameter == null ? false : bool.TryParse(parameter.ToString(), out flag)) & flag; + Visibility visibility1 = (value == null || (StatusTarefa)value == StatusTarefa.Realizado ? Visibility.Visible : Visibility.Collapsed); + if (flag1) + { + visibility = (visibility1 == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible); + } + else + { + visibility = visibility1; + } + return visibility; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return null; + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/StringNullOrEmptyToVisibilityConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/StringNullOrEmptyToVisibilityConverter.cs new file mode 100644 index 0000000..8903884 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/StringNullOrEmptyToVisibilityConverter.cs @@ -0,0 +1,30 @@ +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; +using System.Windows.Markup; + +namespace Gestor.Common.Converters +{ + public class StringNullOrEmptyToVisibilityConverter : MarkupExtension, IValueConverter + { + public StringNullOrEmptyToVisibilityConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + return (string.IsNullOrEmpty(value as string) ? Visibility.Collapsed : Visibility.Visible); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return null; + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/TarefaBackgroundColorConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/TarefaBackgroundColorConverter.cs new file mode 100644 index 0000000..afe3120 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/TarefaBackgroundColorConverter.cs @@ -0,0 +1,54 @@ +using Gestor.Common.Helpers; +using System; +using System.Globalization; +using System.Windows.Data; +using System.Windows.Markup; +using System.Windows.Media; + +namespace Gestor.Common.Converters +{ + public class TarefaBackgroundColorConverter : MarkupExtension, IValueConverter + { + public TarefaBackgroundColorConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value != null && !((DateTime)value < Functions.GetNetworkTime())) + { + return new SolidColorBrush(Colors.Black); + } + return new SolidColorBrush(this.ConvertStringToColor("#fc636b")); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return null; + } + + public Color ConvertStringToColor(string hex) + { + hex = hex.Replace("#", ""); + byte num = 255; + byte num1 = 255; + byte num2 = 255; + byte num3 = 255; + int num4 = 0; + if (hex.Length == 8) + { + num = byte.Parse(hex.Substring(0, 2), NumberStyles.HexNumber); + num4 = 2; + } + num1 = byte.Parse(hex.Substring(num4, 2), NumberStyles.HexNumber); + num2 = byte.Parse(hex.Substring(num4 + 2, 2), NumberStyles.HexNumber); + num3 = byte.Parse(hex.Substring(num4 + 4, 2), NumberStyles.HexNumber); + return Color.FromArgb(num, num1, num2, num3); + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/TemTarefaVisibilityConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/TemTarefaVisibilityConverter.cs new file mode 100644 index 0000000..9b565f3 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/TemTarefaVisibilityConverter.cs @@ -0,0 +1,32 @@ +using Gestor.Model.Domain.Ferramentas; +using System; +using System.Collections.ObjectModel; +using System.Globalization; +using System.Windows; +using System.Windows.Data; +using System.Windows.Markup; + +namespace Gestor.Common.Converters +{ + public class TemTarefaVisibilityConverter : MarkupExtension, IValueConverter + { + public TemTarefaVisibilityConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + return (value == null || ((ObservableCollection)value).Count == 0 ? Visibility.Collapsed : Visibility.Visible); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return null; + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/TipoCriticaConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/TipoCriticaConverter.cs new file mode 100644 index 0000000..c88e9c7 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/TipoCriticaConverter.cs @@ -0,0 +1,40 @@ +using System; +using System.Globalization; +using System.Windows.Data; + +namespace Gestor.Common.Converters +{ + public class TipoCriticaConverter : IMultiValueConverter + { + public TipoCriticaConverter() + { + } + + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) + { + object obj; + try + { + string str = (string)values[0]; + if (str == "0") + { + obj = (string)values[1]; + } + else + { + obj = (str == "1" ? (string)values[2] : ""); + } + } + catch (Exception exception) + { + obj = ""; + } + return obj; + } + + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) + { + return null; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/TipoSinistroConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/TipoSinistroConverter.cs new file mode 100644 index 0000000..4455982 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/TipoSinistroConverter.cs @@ -0,0 +1,43 @@ +using Gestor.Model.Common; +using System; +using System.Globalization; +using System.Windows.Data; + +namespace Gestor.Common.Converters +{ + public class TipoSinistroConverter : IMultiValueConverter + { + public TipoSinistroConverter() + { + } + + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) + { + object obj = values[0]; + if (obj as TipoSinistro == TipoSinistro.Cliente) + { + return ""; + } + if ((TipoSinistro)obj == TipoSinistro.Cliente) + { + return "CLIENTE"; + } + obj = values[1]; + if (obj == null) + { + return "TERCEIRO"; + } + string str = obj as string; + if (str == null) + { + return ""; + } + return string.Concat("TERCEIRO Nº ", str); + } + + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) + { + return null; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/TipoTelefoneVisibilityConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/TipoTelefoneVisibilityConverter.cs new file mode 100644 index 0000000..37a212e --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/TipoTelefoneVisibilityConverter.cs @@ -0,0 +1,39 @@ +using Gestor.Model.Common; +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; + +namespace Gestor.Common.Converters +{ + public class TipoTelefoneVisibilityConverter : IMultiValueConverter + { + public TipoTelefoneVisibilityConverter() + { + } + + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) + { + if (values[0] == null) + { + return Visibility.Collapsed; + } + object obj = values[0]; + if (obj is TipoTelefone && (TipoTelefone)obj != TipoTelefone.Celular) + { + return Visibility.Collapsed; + } + obj = values[1]; + if (obj is bool && (bool)obj) + { + return Visibility.Collapsed; + } + return Visibility.Visible; + } + + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) + { + return null; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/TotalizacaoExpanderConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/TotalizacaoExpanderConverter.cs new file mode 100644 index 0000000..701e944 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/TotalizacaoExpanderConverter.cs @@ -0,0 +1,33 @@ +using System; +using System.Globalization; +using System.Windows.Data; +using System.Windows.Markup; + +namespace Gestor.Common.Converters +{ + public class TotalizacaoExpanderConverter : MarkupExtension, IValueConverter + { + public TotalizacaoExpanderConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value != null && (bool)value) + { + return "ESCONDER TOTALIZAÇÃO"; + } + return "MOSTRAR TOTALIZAÇÃO"; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return null; + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/ValorTipoConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/ValorTipoConverter.cs new file mode 100644 index 0000000..1e100a0 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/ValorTipoConverter.cs @@ -0,0 +1,47 @@ +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; +using System.Windows.Markup; + +namespace Gestor.Common.Converters +{ + public class ValorTipoConverter : MarkupExtension, IMultiValueConverter + { + public ValorTipoConverter() + { + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + + object System.Windows.Data.IMultiValueConverter.Convert(object[] values, Type targetType, object parameter, CultureInfo culture) + { + if (values == null || values[1] == null || values[0] == DependencyProperty.UnsetValue) + { + return null; + } + if (values[0] == null) + { + return values[1].ToString(); + } + string str = values[0].ToString(); + if (str == "VALOR") + { + return ((decimal)values[1]).ToString("c2"); + } + if (str != "PERCENTUAL") + { + return values[1].ToString(); + } + return ((decimal)values[1]).ToString("p2"); + } + + object[] System.Windows.Data.IMultiValueConverter.ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/ZeroToEmptyConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/ZeroToEmptyConverter.cs new file mode 100644 index 0000000..bcedd65 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/ZeroToEmptyConverter.cs @@ -0,0 +1,41 @@ +using System; +using System.Globalization; +using System.Windows.Data; +using System.Windows.Markup; + +namespace Gestor.Common.Converters +{ + public class ZeroToEmptyConverter : MarkupExtension, IValueConverter + { + public ZeroToEmptyConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value == null) + { + return ""; + } + if (value is string) + { + return value; + } + if (Math.Abs(Convert.ToDouble(value)) < 0.01) + { + return ""; + } + return value.ToString(); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return (value == null || string.IsNullOrEmpty(value.ToString()) ? 0 : int.Parse(value.ToString())); + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/ZeroToVisibilityConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/ZeroToVisibilityConverter.cs new file mode 100644 index 0000000..6422f0b --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/ZeroToVisibilityConverter.cs @@ -0,0 +1,30 @@ +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; +using System.Windows.Markup; + +namespace Gestor.Common.Converters +{ + public class ZeroToVisibilityConverter : MarkupExtension, IValueConverter + { + public ZeroToVisibilityConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + return (value == null || (int)Math.Round(double.Parse(value.ToString())) == 0 ? Visibility.Collapsed : Visibility.Visible); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return (value == null || string.IsNullOrEmpty(value.ToString()) ? 0 : int.Parse(value.ToString())); + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/ZeroToVisibilityInvertedConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/ZeroToVisibilityInvertedConverter.cs new file mode 100644 index 0000000..356332b --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/ZeroToVisibilityInvertedConverter.cs @@ -0,0 +1,30 @@ +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; +using System.Windows.Markup; + +namespace Gestor.Common.Converters +{ + public class ZeroToVisibilityInvertedConverter : MarkupExtension, IValueConverter + { + public ZeroToVisibilityInvertedConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + return (value == null || (int)Math.Round(double.Parse(value.ToString())) == 0 ? Visibility.Visible : Visibility.Collapsed); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return (value == null || string.IsNullOrEmpty(value.ToString()) ? 0 : int.Parse(value.ToString())); + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Converters/ZeroToVisibilityValorConverter.cs b/Codemerx/Gestor.Common/Gestor.Common.Converters/ZeroToVisibilityValorConverter.cs new file mode 100644 index 0000000..ac8afa4 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Converters/ZeroToVisibilityValorConverter.cs @@ -0,0 +1,31 @@ +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; +using System.Windows.Markup; + +namespace Gestor.Common.Converters +{ + public class ZeroToVisibilityValorConverter : MarkupExtension, IValueConverter + { + public ZeroToVisibilityValorConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + decimal num; + return (value == null || !decimal.TryParse(value.ToString(), out num) && decimal.Parse(value.ToString()) <= decimal.Zero ? Visibility.Collapsed : Visibility.Visible); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return (value == null || string.IsNullOrEmpty(value.ToString()) ? 0 : int.Parse(value.ToString())); + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + return this; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Exceptions/AbortException.cs b/Codemerx/Gestor.Common/Gestor.Common.Exceptions/AbortException.cs new file mode 100644 index 0000000..6fc2511 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Exceptions/AbortException.cs @@ -0,0 +1,11 @@ +using System; + +namespace Gestor.Common.Exceptions +{ + public class AbortException : Exception + { + public AbortException() : base(string.Empty) + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Exceptions/BaseException.cs b/Codemerx/Gestor.Common/Gestor.Common.Exceptions/BaseException.cs new file mode 100644 index 0000000..6078b23 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Exceptions/BaseException.cs @@ -0,0 +1,15 @@ +using System; + +namespace Gestor.Common.Exceptions +{ + public class BaseException : Exception + { + public BaseException(string message) : base(message) + { + } + + public BaseException() : base(string.Empty) + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Exceptions/ForbiddenException.cs b/Codemerx/Gestor.Common/Gestor.Common.Exceptions/ForbiddenException.cs new file mode 100644 index 0000000..a608b24 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Exceptions/ForbiddenException.cs @@ -0,0 +1,15 @@ +using System; + +namespace Gestor.Common.Exceptions +{ + public class ForbiddenException : Exception + { + public ForbiddenException(string message) : base(message) + { + } + + public ForbiddenException() : base(string.Empty) + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Exceptions/MailingException.cs b/Codemerx/Gestor.Common/Gestor.Common.Exceptions/MailingException.cs new file mode 100644 index 0000000..9fd65a5 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Exceptions/MailingException.cs @@ -0,0 +1,15 @@ +using System; + +namespace Gestor.Common.Exceptions +{ + public class MailingException : BaseException + { + public MailingException(string message) : base(message) + { + } + + public MailingException() : base(string.Empty) + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Exceptions/PermissionException.cs b/Codemerx/Gestor.Common/Gestor.Common.Exceptions/PermissionException.cs new file mode 100644 index 0000000..f80f0dc --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Exceptions/PermissionException.cs @@ -0,0 +1,15 @@ +using System; + +namespace Gestor.Common.Exceptions +{ + public class PermissionException : Exception + { + public PermissionException() + { + } + + public PermissionException(string message) : base(message) + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Exceptions/UnauthorizedException.cs b/Codemerx/Gestor.Common/Gestor.Common.Exceptions/UnauthorizedException.cs new file mode 100644 index 0000000..7e95254 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Exceptions/UnauthorizedException.cs @@ -0,0 +1,15 @@ +using System; + +namespace Gestor.Common.Exceptions +{ + public class UnauthorizedException : Exception + { + public UnauthorizedException(string message) : base(message) + { + } + + public UnauthorizedException() : base(string.Empty) + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Exceptions/ValidationException.cs b/Codemerx/Gestor.Common/Gestor.Common.Exceptions/ValidationException.cs new file mode 100644 index 0000000..b2a3bca --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Exceptions/ValidationException.cs @@ -0,0 +1,15 @@ +using System; + +namespace Gestor.Common.Exceptions +{ + public class ValidationException : Exception + { + public ValidationException(string message) : base(message) + { + } + + public ValidationException() : base(string.Empty) + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Helpers/DataBaseParameters.cs b/Codemerx/Gestor.Common/Gestor.Common.Helpers/DataBaseParameters.cs new file mode 100644 index 0000000..03ccc65 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Helpers/DataBaseParameters.cs @@ -0,0 +1,14 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Common.Helpers +{ + public static class DataBaseParameters + { + public static bool NovoGestor + { + get; + set; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Helpers/DefaultAttribute.cs b/Codemerx/Gestor.Common/Gestor.Common.Helpers/DefaultAttribute.cs new file mode 100644 index 0000000..b79d623 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Helpers/DefaultAttribute.cs @@ -0,0 +1,19 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Common.Helpers +{ + public class DefaultAttribute : Attribute + { + public bool DefaultProperty + { + get; + private set; + } + + public DefaultAttribute(bool defaultProperty) + { + this.DefaultProperty = defaultProperty; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Helpers/EncryptionHelper.cs b/Codemerx/Gestor.Common/Gestor.Common.Helpers/EncryptionHelper.cs new file mode 100644 index 0000000..b2102d2 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Helpers/EncryptionHelper.cs @@ -0,0 +1,106 @@ +using System; +using System.IO; +using System.Runtime.CompilerServices; +using System.Security.Cryptography; +using System.Text; + +namespace Gestor.Common.Helpers +{ + public static class EncryptionHelper + { + private readonly static byte[] Salt; + + private readonly static string EncryptionKey; + + static EncryptionHelper() + { + EncryptionHelper.Salt = new byte[] { 38, 220, 255, 0, 173, 237, 122, 238, 197, 254, 7, 175, 77, 8, 34, 60 }; + EncryptionHelper.EncryptionKey = string.Format("aGG3r{0}#w3BDz$", 1012); + } + + public static string Decrypt(this string cipher) + { + string str; + if (string.IsNullOrEmpty(cipher)) + { + return null; + } + try + { + byte[] numArray = Convert.FromBase64String(cipher); + if ((int)numArray.Length >= 16) + { + byte[] numArray1 = numArray.DecryptBytes(); + str = (numArray1 == null ? cipher : Encoding.UTF8.GetString(numArray1)); + } + else + { + str = cipher; + } + } + catch (Exception exception) + { + str = cipher; + } + return str; + } + + public static byte[] DecryptBytes(this byte[] plainTextBytes) + { + byte[] array; + try + { + using (Rfc2898DeriveBytes rfc2898DeriveByte = new Rfc2898DeriveBytes(EncryptionHelper.EncryptionKey, EncryptionHelper.Salt)) + { + using (Rijndael bytes = Rijndael.Create()) + { + bytes.Key = rfc2898DeriveByte.GetBytes(32); + bytes.IV = rfc2898DeriveByte.GetBytes(16); + using (MemoryStream memoryStream = new MemoryStream()) + { + using (CryptoStream cryptoStream = new CryptoStream(memoryStream, bytes.CreateDecryptor(), CryptoStreamMode.Write)) + { + cryptoStream.Write(plainTextBytes, 0, (int)plainTextBytes.Length); + cryptoStream.FlushFinalBlock(); + array = memoryStream.ToArray(); + } + } + } + } + } + catch (Exception exception) + { + array = null; + } + return array; + } + + public static string Encrypt(this string plain) + { + return Convert.ToBase64String(Encoding.UTF8.GetBytes(plain).EncryptBytes()); + } + + public static byte[] EncryptBytes(this byte[] plainTextBytes) + { + byte[] array; + using (Rfc2898DeriveBytes rfc2898DeriveByte = new Rfc2898DeriveBytes(EncryptionHelper.EncryptionKey, EncryptionHelper.Salt)) + { + using (Rijndael bytes = Rijndael.Create()) + { + bytes.Key = rfc2898DeriveByte.GetBytes(32); + bytes.IV = rfc2898DeriveByte.GetBytes(16); + using (MemoryStream memoryStream = new MemoryStream()) + { + using (CryptoStream cryptoStream = new CryptoStream(memoryStream, bytes.CreateEncryptor(), CryptoStreamMode.Write)) + { + cryptoStream.Write(plainTextBytes, 0, (int)plainTextBytes.Length); + cryptoStream.FlushFinalBlock(); + array = memoryStream.ToArray(); + } + } + } + } + return array; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Helpers/EnumBindingSourceExtension.cs b/Codemerx/Gestor.Common/Gestor.Common.Helpers/EnumBindingSourceExtension.cs new file mode 100644 index 0000000..7ce699e --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Helpers/EnumBindingSourceExtension.cs @@ -0,0 +1,59 @@ +using System; +using System.Windows.Markup; + +namespace Gestor.Common.Helpers +{ + public class EnumBindingSourceExtension : MarkupExtension + { + private Type _enumType; + + public Type EnumType + { + get + { + return this._enumType; + } + set + { + if (value == this._enumType) + { + return; + } + if (null != value) + { + if (!(Nullable.GetUnderlyingType(value) ?? value).IsEnum) + { + throw new ArgumentException("Type must be for an Enum."); + } + } + this._enumType = value; + } + } + + public EnumBindingSourceExtension() + { + } + + public EnumBindingSourceExtension(Type enumType) + { + this.EnumType = enumType; + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + if (null == this._enumType) + { + throw new InvalidOperationException("The EnumType must be specified."); + } + Type underlyingType = Nullable.GetUnderlyingType(this._enumType) ?? this._enumType; + Array values = Enum.GetValues(underlyingType); + if (underlyingType == this._enumType) + { + return values; + } + Array arrays = Array.CreateInstance(underlyingType, values.Length + 1); + values.CopyTo(arrays, 1); + return arrays; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Helpers/EnumHelper.cs b/Codemerx/Gestor.Common/Gestor.Common.Helpers/EnumHelper.cs new file mode 100644 index 0000000..33529b8 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Helpers/EnumHelper.cs @@ -0,0 +1,166 @@ +using Gestor.Model.Attributes; +using System; +using System.ComponentModel; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace Gestor.Common.Helpers +{ + public static class EnumHelper + { + public static T2 GetAttribute(this T enumValue) + where T2 : class + { + T2 customAttribute; + string name = Enum.GetName(enumValue.GetType(), enumValue); + try + { + customAttribute = (T2)(Attribute.GetCustomAttribute(enumValue.GetType().GetField(name), typeof(T2)) as T2); + } + catch (Exception exception) + { + customAttribute = default(T2); + } + return customAttribute; + } + + public static bool? GetDefault(this T enumValue) + { + object customAttribute; + string name = Enum.GetName(enumValue.GetType(), enumValue); + FieldInfo field = enumValue.GetType().GetField(name); + if (field == null) + { + customAttribute = null; + } + else + { + customAttribute = Attribute.GetCustomAttribute(field, typeof(DefaultAttribute)) as DefaultAttribute; + } + if (customAttribute != null) + { + return new bool?(((DefaultAttribute)customAttribute).DefaultProperty); + } + return null; + } + + public static string GetDescription(this T enumValue) + { + object customAttribute; + string name = Enum.GetName(enumValue.GetType(), enumValue); + if (name == null) + { + return null; + } + FieldInfo field = enumValue.GetType().GetField(name); + if (field == null) + { + customAttribute = null; + } + else + { + customAttribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute; + } + if (customAttribute != null) + { + return ((DescriptionAttribute)customAttribute).Description; + } + return null; + } + + public static bool GetHidden(this T enumValue) + { + object customAttribute; + string name = Enum.GetName(enumValue.GetType(), enumValue); + FieldInfo field = enumValue.GetType().GetField(name); + if (field == null) + { + customAttribute = null; + } + else + { + customAttribute = Attribute.GetCustomAttribute(field, typeof(HiddenAttribute)) as HiddenAttribute; + } + return customAttribute != null; + } + + public static string GetOldValue(this T enumValue) + { + OldValueAttribute attribute = enumValue.GetAttribute(); + if (attribute != null) + { + return attribute.OldValue; + } + return null; + } + + public static string GetOldValue2(this T enumValue) + { + OldValue2Attribute attribute = enumValue.GetAttribute(); + if (attribute != null) + { + return attribute.OldValue2; + } + return null; + } + + public static int? GetOrder(this T enumValue) + { + object customAttribute; + string name = Enum.GetName(enumValue.GetType(), enumValue); + FieldInfo field = enumValue.GetType().GetField(name); + if (field == null) + { + customAttribute = null; + } + else + { + customAttribute = Attribute.GetCustomAttribute(field, typeof(OrderAttribute)) as OrderAttribute; + } + if (customAttribute != null) + { + return new int?(((OrderAttribute)customAttribute).OrderProperty); + } + return null; + } + + public static T ToEnumByOldValue(this string oldValue) + { + Type type = typeof(T); + Type type1 = typeof(OldValueAttribute); + FieldInfo[] fields = type.GetFields(); + for (int i = 0; i < (int)fields.Length; i++) + { + FieldInfo fieldInfo = fields[i]; + OldValueAttribute customAttribute = Attribute.GetCustomAttribute(fieldInfo, type1) as OldValueAttribute; + if (customAttribute != null && customAttribute.OldValue == oldValue) + { + return (T)fieldInfo.GetValue(null); + } + } + return default(T); + } + + public static T ToEnumByOldValue2(this string oldValue) + { + Type type = typeof(T); + Type type1 = typeof(OldValue2Attribute); + FieldInfo[] fields = type.GetFields(); + for (int i = 0; i < (int)fields.Length; i++) + { + FieldInfo fieldInfo = fields[i]; + OldValue2Attribute customAttribute = Attribute.GetCustomAttribute(fieldInfo, type1) as OldValue2Attribute; + if (customAttribute != null && customAttribute.OldValue2 == oldValue) + { + return (T)fieldInfo.GetValue(null); + } + } + return default(T); + } + + public static string Value(this T enumValue) + { + return Convert.ToInt32(enumValue).ToString(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Helpers/FindVisualChild.cs b/Codemerx/Gestor.Common/Gestor.Common.Helpers/FindVisualChild.cs new file mode 100644 index 0000000..4cabf7c --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Helpers/FindVisualChild.cs @@ -0,0 +1,32 @@ +using System; +using System.Windows; +using System.Windows.Media; + +namespace Gestor.Common.Helpers +{ + public class FindVisualChild + { + public FindVisualChild() + { + } + + public static childItem Find(DependencyObject obj) + where childItem : DependencyObject + { + for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++) + { + DependencyObject child = VisualTreeHelper.GetChild(obj, i); + if (child != null && child is childItem) + { + return (childItem)child; + } + childItem _childItem = FindVisualChild.Find(child); + if (_childItem != null) + { + return _childItem; + } + } + return default(childItem); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Helpers/FindVisualChildren.cs b/Codemerx/Gestor.Common/Gestor.Common.Helpers/FindVisualChildren.cs new file mode 100644 index 0000000..9b7f11d --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Helpers/FindVisualChildren.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Windows; +using System.Windows.Media; + +namespace Gestor.Common.Helpers +{ + public class FindVisualChildren + { + public FindVisualChildren() + { + } + + public static IEnumerable Find(DependencyObject depObj) + where T : DependencyObject + { + if (depObj != null) + { + for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++) + { + DependencyObject dependencyObject = VisualTreeHelper.GetChild(depObj, i); + if (dependencyObject != null && dependencyObject is T) + { + yield return (T)dependencyObject; + } + foreach (T t in FindVisualChildren.Find(dependencyObject)) + { + yield return t; + } + dependencyObject = null; + } + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Helpers/Functions.cs b/Codemerx/Gestor.Common/Gestor.Common.Helpers/Functions.cs new file mode 100644 index 0000000..25ffadf --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Helpers/Functions.cs @@ -0,0 +1,110 @@ +using Gestor.Common.Validation; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; + +namespace Gestor.Common.Helpers +{ + public class Functions + { + public static System.Diagnostics.Stopwatch Stopwatch; + + public static DateTime? StartTime; + + public Functions() + { + } + + public static int Compare(string original, string modified) + { + if (original == null) + { + original = ""; + } + if (modified == null) + { + modified = ""; + } + string str = original.ToLongNullable().ToString(); + if (!string.IsNullOrWhiteSpace(str)) + { + original = str; + } + str = modified.ToLongNullable().ToString(); + if (!string.IsNullOrWhiteSpace(str)) + { + modified = str; + } + int length = original.Length; + int num = modified.Length; + int[,] numArray = new int[length + 1, num + 1]; + for (int i = 0; i <= length; i++) + { + numArray[i, 0] = i; + } + for (int j = 0; j <= num; j++) + { + numArray[0, j] = j; + } + for (int k = 1; k <= length; k++) + { + for (int l = 1; l <= num; l++) + { + int num1 = modified[l - 1] != original[k - 1]; + numArray[k, l] = (new int[] { numArray[k - 1, l] + 1, numArray[k, l - 1] + 1, numArray[k - 1, l - 1] + num1 }).Min(); + if (k > 1 && l > 1 && original[k - 1] == modified[l - 2] && original[k - 2] == modified[l - 1]) + { + numArray[k, l] = Math.Min(numArray[k, l], numArray[k - 2, l - 2] + num1); + } + } + } + return numArray[length, num]; + } + + public static DateTime GetNetworkTime() + { + DateTime value; + try + { + if (!Functions.StartTime.HasValue) + { + byte[] numArray = new byte[48]; + numArray[0] = 27; + IPEndPoint pEndPoint = new IPEndPoint(((IEnumerable)Dns.GetHostEntry("time.google.com").AddressList).First((IPAddress a) => a.AddressFamily == AddressFamily.InterNetwork), 123); + using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) + { + socket.Connect(pEndPoint); + socket.ReceiveTimeout = 3000; + socket.Send(numArray); + socket.Receive(numArray); + socket.Close(); + } + ulong num = (ulong)numArray[40] << 24 | (ulong)numArray[41] << 16 | (ulong)numArray[42] << 8 | (ulong)numArray[43]; + ulong num1 = (ulong)numArray[44] << 24 | (ulong)numArray[45] << 16 | (ulong)numArray[46] << 8 | (ulong)numArray[47]; + ulong num2 = num * (long)1000 + num1 * (long)1000 / 4294967296L; + DateTime dateTime = new DateTime(1900, 1, 1); + dateTime = dateTime.AddMilliseconds((double)num2); + Functions.StartTime = new DateTime?(dateTime.ToLocalTime()); + Functions.Stopwatch = System.Diagnostics.Stopwatch.StartNew(); + value = Functions.StartTime.Value; + } + else + { + value = Functions.StartTime.Value; + value = value.AddMilliseconds((double)Functions.Stopwatch.ElapsedMilliseconds); + } + } + catch (Exception exception) + { + Functions.StartTime = new DateTime?(DateTime.Now); + Functions.Stopwatch = System.Diagnostics.Stopwatch.StartNew(); + value = Functions.StartTime.Value; + } + return value; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Helpers/HiddenAttribute.cs b/Codemerx/Gestor.Common/Gestor.Common.Helpers/HiddenAttribute.cs new file mode 100644 index 0000000..236be6f --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Helpers/HiddenAttribute.cs @@ -0,0 +1,12 @@ +using System; + +namespace Gestor.Common.Helpers +{ + [AttributeUsage(AttributeTargets.All)] + public class HiddenAttribute : Attribute + { + public HiddenAttribute() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Helpers/HttpHelper.cs b/Codemerx/Gestor.Common/Gestor.Common.Helpers/HttpHelper.cs new file mode 100644 index 0000000..26b53e3 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Helpers/HttpHelper.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Runtime.CompilerServices; + +namespace Gestor.Common.Helpers +{ + public static class HttpHelper + { + public static HttpRequestMessage CreateRequest(this Uri requestUri, HttpMethod httpMethod, Version httpVersion = null) + { + HttpRequestMessage httpRequestMessage = new HttpRequestMessage(); + httpRequestMessage.set_Version(httpVersion ?? HttpVersion.Version11); + httpRequestMessage.set_RequestUri(requestUri); + httpRequestMessage.set_Method(httpMethod); + return httpRequestMessage; + } + + public static FormUrlEncodedContent Encode(this List> keyValuePairs) + { + return new FormUrlEncodedContent(keyValuePairs); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Helpers/OrderAttribute.cs b/Codemerx/Gestor.Common/Gestor.Common.Helpers/OrderAttribute.cs new file mode 100644 index 0000000..58dba77 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Helpers/OrderAttribute.cs @@ -0,0 +1,20 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Common.Helpers +{ + [AttributeUsage(AttributeTargets.All)] + public class OrderAttribute : Attribute + { + public int OrderProperty + { + get; + private set; + } + + public OrderAttribute(int orderProperty) + { + this.OrderProperty = orderProperty; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Helpers/ScrollAnimationBehavior.cs b/Codemerx/Gestor.Common/Gestor.Common.Helpers/ScrollAnimationBehavior.cs new file mode 100644 index 0000000..6332e15 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Helpers/ScrollAnimationBehavior.cs @@ -0,0 +1,124 @@ +using System; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Media.Animation; + +namespace Gestor.Common.Helpers +{ + public static class ScrollAnimationBehavior + { + public static DependencyProperty VerticalOffsetProperty; + + public static DependencyProperty TimeDurationProperty; + + public static DependencyProperty PointsToScrollProperty; + + public static DependencyProperty IsEnabledProperty; + + private static double _currentToValue; + + private static Storyboard _storyboard; + + static ScrollAnimationBehavior() + { + ScrollAnimationBehavior.VerticalOffsetProperty = DependencyProperty.RegisterAttached("VerticalOffset", typeof(double), typeof(ScrollAnimationBehavior), new UIPropertyMetadata((object)0, new PropertyChangedCallback(ScrollAnimationBehavior.OnVerticalOffsetChanged))); + ScrollAnimationBehavior.TimeDurationProperty = DependencyProperty.RegisterAttached("TimeDuration", typeof(TimeSpan), typeof(ScrollAnimationBehavior), new PropertyMetadata((object)(new TimeSpan(0, 0, 0, 0, 0)))); + ScrollAnimationBehavior.PointsToScrollProperty = DependencyProperty.RegisterAttached("PointsToScroll", typeof(double), typeof(ScrollAnimationBehavior), new PropertyMetadata((object)0)); + ScrollAnimationBehavior.IsEnabledProperty = DependencyProperty.RegisterAttached("IsEnabled", typeof(bool), typeof(ScrollAnimationBehavior), new UIPropertyMetadata(false, new PropertyChangedCallback(ScrollAnimationBehavior.OnIsEnabledChanged))); + } + + private static void AnimateScroll(ScrollViewer scrollViewer) + { + DoubleAnimationUsingKeyFrames doubleAnimationUsingKeyFrame = new DoubleAnimationUsingKeyFrames() + { + Duration = new Duration(ScrollAnimationBehavior.GetTimeDuration(scrollViewer)) + }; + doubleAnimationUsingKeyFrame.KeyFrames.Add(new EasingDoubleKeyFrame(scrollViewer.VerticalOffset, KeyTime.FromPercent(0))); + doubleAnimationUsingKeyFrame.KeyFrames.Add(new EasingDoubleKeyFrame(ScrollAnimationBehavior._currentToValue, KeyTime.FromPercent(1), new SineEase() + { + EasingMode = EasingMode.EaseOut + })); + ScrollAnimationBehavior._storyboard = new Storyboard(); + ScrollAnimationBehavior._storyboard.Children.Add(doubleAnimationUsingKeyFrame); + Storyboard.SetTarget(doubleAnimationUsingKeyFrame, scrollViewer); + Storyboard.SetTargetProperty(doubleAnimationUsingKeyFrame, new PropertyPath(ScrollAnimationBehavior.VerticalOffsetProperty)); + ScrollAnimationBehavior._storyboard.Begin(); + } + + public static TimeSpan GetTimeDuration(FrameworkElement target) + { + return (TimeSpan)target.GetValue(ScrollAnimationBehavior.TimeDurationProperty); + } + + private static void OnIsEnabledChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) + { + ScrollViewer scrollViewer = sender as ScrollViewer; + if (scrollViewer != null) + { + scrollViewer.Loaded += new RoutedEventHandler(ScrollAnimationBehavior.ScrollerLoaded); + } + } + + private static void OnVerticalOffsetChanged(DependencyObject target, DependencyPropertyChangedEventArgs e) + { + ScrollViewer scrollViewer = target as ScrollViewer; + if (scrollViewer != null) + { + scrollViewer.ScrollToVerticalOffset((double)e.NewValue); + } + } + + private static void ScrollerLoaded(object sender, RoutedEventArgs e) + { + ScrollAnimationBehavior.SetEventHandlersForScrollViewer(sender as ScrollViewer); + } + + private static void ScrollViewerPreviewMouseWheel(object sender, MouseWheelEventArgs e) + { + double num; + double num1 = ScrollAnimationBehavior._currentToValue; + double delta = (double)e.Delta; + ScrollViewer scrollViewer = (ScrollViewer)sender; + double num2 = delta * 2 / 3; + if (ScrollAnimationBehavior._storyboard == null || ScrollAnimationBehavior._storyboard.GetCurrentState() == ClockState.Filling) + { + ScrollAnimationBehavior._currentToValue = scrollViewer.VerticalOffset; + } + if (num2 > ScrollAnimationBehavior._currentToValue) + { + num = 0; + } + else + { + num = (ScrollAnimationBehavior._currentToValue - num2 > scrollViewer.ScrollableHeight ? scrollViewer.ScrollableHeight : ScrollAnimationBehavior._currentToValue - num2); + } + ScrollAnimationBehavior._currentToValue = num; + if (ScrollAnimationBehavior._currentToValue != scrollViewer.VerticalOffset && ScrollAnimationBehavior._currentToValue != num1) + { + ScrollAnimationBehavior.AnimateScroll(scrollViewer); + } + e.Handled = true; + } + + private static void SetEventHandlersForScrollViewer(ScrollViewer scroller) + { + scroller.PreviewMouseWheel += new MouseWheelEventHandler(ScrollAnimationBehavior.ScrollViewerPreviewMouseWheel); + } + + public static void SetIsEnabled(FrameworkElement target, bool value) + { + target.SetValue(ScrollAnimationBehavior.IsEnabledProperty, value); + } + + public static void SetPointsToScroll(FrameworkElement target, double value) + { + target.SetValue(ScrollAnimationBehavior.PointsToScrollProperty, value); + } + + public static void SetTimeDuration(FrameworkElement target, TimeSpan value) + { + target.SetValue(ScrollAnimationBehavior.TimeDurationProperty, value); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Security/Token.cs b/Codemerx/Gestor.Common/Gestor.Common.Security/Token.cs new file mode 100644 index 0000000..c2d76b1 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Security/Token.cs @@ -0,0 +1,148 @@ +using Gestor.Common.Helpers; +using System; +using System.IO; +using System.Security.Cryptography; +using System.Text; + +namespace Gestor.Common.Security +{ + public class Token + { + private readonly byte[] _key = new byte[] { 45, 103, 73, 146, 210, 184, 220, 224, 94, 3, 114, 60, 211, 119, 21, 100, 18, 201, 230, 195, 119, 252, 73, 208, 209, 39, 222, 48, 47, 142, 94, 24 }; + + private readonly byte[] _initializationVector = new byte[] { 95, 17, 151, 243, 209, 243, 119, 80, 63, 252, 13, 180, 162, 13, 23, 218 }; + + private readonly static byte[] Salt; + + static Token() + { + Token.Salt = new byte[] { 38, 220, 255, 0, 173, 237, 122, 238, 197, 254, 7, 175, 77, 8, 34, 60 }; + } + + public Token() + { + } + + public string AggerDecrypt(string cipher) + { + string str = string.Concat("aGG3r", Convert.ToString(1012), "#w3BDz$"); + byte[] numArray = Convert.FromBase64String(cipher); + Rijndael bytes = Rijndael.Create(); + Rfc2898DeriveBytes rfc2898DeriveByte = new Rfc2898DeriveBytes(str, Token.Salt); + bytes.Key = rfc2898DeriveByte.GetBytes(32); + bytes.IV = rfc2898DeriveByte.GetBytes(16); + MemoryStream memoryStream = new MemoryStream(); + CryptoStream cryptoStream = new CryptoStream(memoryStream, bytes.CreateDecryptor(), CryptoStreamMode.Write); + cryptoStream.Write(numArray, 0, (int)numArray.Length); + cryptoStream.Close(); + byte[] array = memoryStream.ToArray(); + return Encoding.UTF8.GetString(array); + } + + public string AggerEncrypt(string plain) + { + string str = string.Concat("aGG3r", Convert.ToString(1012), "#w3BDz$"); + byte[] bytes = Encoding.UTF8.GetBytes(plain); + Rijndael rijndael = Rijndael.Create(); + Rfc2898DeriveBytes rfc2898DeriveByte = new Rfc2898DeriveBytes(str, Token.Salt); + rijndael.Key = rfc2898DeriveByte.GetBytes(32); + rijndael.IV = rfc2898DeriveByte.GetBytes(16); + MemoryStream memoryStream = new MemoryStream(); + CryptoStream cryptoStream = new CryptoStream(memoryStream, rijndael.CreateEncryptor(), CryptoStreamMode.Write); + cryptoStream.Write(bytes, 0, (int)bytes.Length); + cryptoStream.Close(); + return Convert.ToBase64String(memoryStream.ToArray()); + } + + public string Decrypt(string plainText) + { + string end; + string str; + try + { + byte[] numArray = Convert.FromBase64String(plainText); + using (AesCryptoServiceProvider aesCryptoServiceProvider = new AesCryptoServiceProvider()) + { + ICryptoTransform cryptoTransform = aesCryptoServiceProvider.CreateDecryptor(this._key, this._initializationVector); + using (MemoryStream memoryStream = new MemoryStream(numArray)) + { + using (CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Read)) + { + using (StreamReader streamReader = new StreamReader(cryptoStream)) + { + end = streamReader.ReadToEnd(); + } + } + } + } + str = end; + } + catch (Exception exception) + { + str = null; + } + return str; + } + + public bool DefaultDecryption(string ecryptedText) + { + return this.DefaultVerification(this.Decrypt(ecryptedText).Split(new char[] { ':' })); + } + + public string DefaultEncryption(long clientId, long providerId) + { + object obj = providerId; + DateTime universalTime = Functions.GetNetworkTime().ToUniversalTime(); + string str = string.Format("{0}:{1}", obj, universalTime.Ticks); + return this.Encrypt(str); + } + + public bool DefaultVerification(string[] textDecrypted) + { + if ((int)textDecrypted.Length < 2) + { + return false; + } + DateTime dateTime = new DateTime(long.Parse(textDecrypted[1]), DateTimeKind.Utc); + dateTime = dateTime.Date; + DateTime dateTime1 = dateTime.AddHours(5); + dateTime = Functions.GetNetworkTime().ToUniversalTime(); + return dateTime1 >= dateTime.Date; + } + + public string Encrypt(string plainText) + { + byte[] array; + using (AesCryptoServiceProvider aesCryptoServiceProvider = new AesCryptoServiceProvider()) + { + ICryptoTransform cryptoTransform = aesCryptoServiceProvider.CreateEncryptor(this._key, this._initializationVector); + using (MemoryStream memoryStream = new MemoryStream()) + { + using (CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write)) + { + using (StreamWriter streamWriter = new StreamWriter(cryptoStream)) + { + streamWriter.Write(plainText); + } + array = memoryStream.ToArray(); + } + } + } + return Convert.ToBase64String(array); + } + + public bool VerifyToken(string authHeader) + { + bool flag; + try + { + flag = (authHeader.Contains("Token") ? this.DefaultDecryption(authHeader.Replace("Token ", "")) : false); + } + catch (Exception exception) + { + flag = false; + } + return flag; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/SemValicao.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/SemValicao.cs new file mode 100644 index 0000000..7c6fde3 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/SemValicao.cs @@ -0,0 +1,18 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class SemValicao : ValidationRule + { + public SemValicao() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + return ValidationResult.ValidResult; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoAno.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoAno.cs new file mode 100644 index 0000000..ccdc82b --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoAno.cs @@ -0,0 +1,27 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoAno : ValidationRule + { + public ValidacaoAno() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString()) || value.ToString().ValidateAno()) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "Ano Inválido"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoAnoObrigatorio.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoAnoObrigatorio.cs new file mode 100644 index 0000000..5b6c947 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoAnoObrigatorio.cs @@ -0,0 +1,31 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoAnoObrigatorio : ValidationRule + { + public ValidacaoAnoObrigatorio() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString())) + { + return new ValidationResult(false, "Obrigatório"); + } + if (value.ToString().ValidateAno()) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "Ano Inválido"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoCeiObrigatorio.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoCeiObrigatorio.cs new file mode 100644 index 0000000..c2598d5 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoCeiObrigatorio.cs @@ -0,0 +1,31 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoCeiObrigatorio : ValidationRule + { + public ValidacaoCeiObrigatorio() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString())) + { + return new ValidationResult(false, "Obrigatório"); + } + if (value.ToString().ValidateCei()) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "CEI Inválido"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoCep.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoCep.cs new file mode 100644 index 0000000..1ef2a5e --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoCep.cs @@ -0,0 +1,27 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoCep : ValidationRule + { + public ValidacaoCep() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString()) || value.ToString().ValidatePostCode()) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "CEP Inválido"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoCepObrigatorio.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoCepObrigatorio.cs new file mode 100644 index 0000000..7f801fc --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoCepObrigatorio.cs @@ -0,0 +1,31 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoCepObrigatorio : ValidationRule + { + public ValidacaoCepObrigatorio() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString())) + { + return new ValidationResult(false, "Obrigatório"); + } + if (value.ToString().ValidatePostCode()) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "CEP Inválido"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoChassi.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoChassi.cs new file mode 100644 index 0000000..5ec78c0 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoChassi.cs @@ -0,0 +1,27 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoChassi : ValidationRule + { + public ValidacaoChassi() + { + } + + public override ValidationResult Validate(object chassiNumber, CultureInfo cultureInfo) + { + object obj = chassiNumber; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString()) || chassiNumber.ToString().ValidateChassi()) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "Chassi Inválido"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoChassiObrigatorio.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoChassiObrigatorio.cs new file mode 100644 index 0000000..a2e81ab --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoChassiObrigatorio.cs @@ -0,0 +1,31 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoChassiObrigatorio : ValidationRule + { + public ValidacaoChassiObrigatorio() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString())) + { + return new ValidationResult(false, "Obrigatório"); + } + if (value.ToString().ValidateChassi()) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "Chassi Inválido"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoData.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoData.cs new file mode 100644 index 0000000..98b507a --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoData.cs @@ -0,0 +1,27 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoData : ValidationRule + { + public ValidacaoData() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString()) || value.ToString().ValidateDate()) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "Data Inválida"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoDataFutura.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoDataFutura.cs new file mode 100644 index 0000000..4180751 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoDataFutura.cs @@ -0,0 +1,27 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoDataFutura : ValidationRule + { + public ValidacaoDataFutura() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString()) || value.ToString().ValidateFutureDate()) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "Data Inválida"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoDataMaior.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoDataMaior.cs new file mode 100644 index 0000000..4345958 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoDataMaior.cs @@ -0,0 +1,38 @@ +using System; +using System.Globalization; +using System.Runtime.CompilerServices; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoDataMaior : ValidationRule + { + public DateTime BaseDate + { + get; + set; + } + + public ValidacaoDataMaior() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString())) + { + return new ValidationResult(false, "Obrigatório"); + } + if ((DateTime)value >= this.BaseDate) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "Data Inválida"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoDataObrigatoria.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoDataObrigatoria.cs new file mode 100644 index 0000000..6a498dc --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoDataObrigatoria.cs @@ -0,0 +1,31 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoDataObrigatoria : ValidationRule + { + public ValidacaoDataObrigatoria() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString())) + { + return new ValidationResult(false, "Obrigatório"); + } + if (value.ToString().ValidateDate()) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "Data Inválida"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoDataPassada.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoDataPassada.cs new file mode 100644 index 0000000..cb22fb4 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoDataPassada.cs @@ -0,0 +1,27 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoDataPassada : ValidationRule + { + public ValidacaoDataPassada() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString()) || value.ToString().ValidatePastDate()) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "Data Inválida"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoDataPassadaObrigatoria.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoDataPassadaObrigatoria.cs new file mode 100644 index 0000000..f5fd4c8 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoDataPassadaObrigatoria.cs @@ -0,0 +1,31 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoDataPassadaObrigatoria : ValidationRule + { + public ValidacaoDataPassadaObrigatoria() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString())) + { + return new ValidationResult(false, "Obrigatório"); + } + if (value.ToString().ValidatePastDate()) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "Data Inválida"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoDocumento.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoDocumento.cs new file mode 100644 index 0000000..2f1a886 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoDocumento.cs @@ -0,0 +1,27 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoDocumento : ValidationRule + { + public ValidacaoDocumento() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString()) || value.ToString().ValidateDocument()) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "Documento Inválido"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoDocumentoObrigatorio.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoDocumentoObrigatorio.cs new file mode 100644 index 0000000..787942f --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoDocumentoObrigatorio.cs @@ -0,0 +1,31 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoDocumentoObrigatorio : ValidationRule + { + public ValidacaoDocumentoObrigatorio() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString())) + { + return new ValidationResult(false, "Obrigatório"); + } + if (value.ToString().ValidateDocument()) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "Documento Inválido"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoDouble.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoDouble.cs new file mode 100644 index 0000000..ce33724 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoDouble.cs @@ -0,0 +1,27 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoDouble : ValidationRule + { + public ValidacaoDouble() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString()) || value.ToString().ValidateDouble()) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "Valor Inválido"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoEmail.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoEmail.cs new file mode 100644 index 0000000..504fd63 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoEmail.cs @@ -0,0 +1,27 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoEmail : ValidationRule + { + public ValidacaoEmail() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString()) || value.ToString().ValidateMail()) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "E-mail Inválido"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoEmailObrigatorio.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoEmailObrigatorio.cs new file mode 100644 index 0000000..ab1a6ad --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoEmailObrigatorio.cs @@ -0,0 +1,31 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoEmailObrigatorio : ValidationRule + { + public ValidacaoEmailObrigatorio() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString())) + { + return new ValidationResult(false, "Obrigatório"); + } + if (value.ToString().ValidateMail()) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "E-mail Inválido"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoEstado.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoEstado.cs new file mode 100644 index 0000000..de54bc8 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoEstado.cs @@ -0,0 +1,27 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoEstado : ValidationRule + { + public ValidacaoEstado() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString()) || value.ToString().ValidateState()) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "Estado Inválido"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoEstadoObrigatorio.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoEstadoObrigatorio.cs new file mode 100644 index 0000000..526327e --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoEstadoObrigatorio.cs @@ -0,0 +1,31 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoEstadoObrigatorio : ValidationRule + { + public ValidacaoEstadoObrigatorio() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString())) + { + return new ValidationResult(false, "Obrigatório"); + } + if (value.ToString().ValidateState()) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "Estado Inválido"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoFipeObrigatorio.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoFipeObrigatorio.cs new file mode 100644 index 0000000..a3547da --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoFipeObrigatorio.cs @@ -0,0 +1,31 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoFipeObrigatorio : ValidationRule + { + public ValidacaoFipeObrigatorio() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString())) + { + return new ValidationResult(false, "Obrigatório"); + } + if (value.ToString().ValidateFipe()) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "FIPE Inválido"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoInt.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoInt.cs new file mode 100644 index 0000000..551a95e --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoInt.cs @@ -0,0 +1,27 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoInt : ValidationRule + { + public ValidacaoInt() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString()) || value.ToString().ValidateInt()) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "Número Inválido"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoIntObrigatorio.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoIntObrigatorio.cs new file mode 100644 index 0000000..c62cf85 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoIntObrigatorio.cs @@ -0,0 +1,31 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoIntObrigatorio : ValidationRule + { + public ValidacaoIntObrigatorio() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString())) + { + return new ValidationResult(false, "Obrigatório"); + } + if (value.ToString().ValidateInt()) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "Número Inválido"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoLong.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoLong.cs new file mode 100644 index 0000000..042454d --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoLong.cs @@ -0,0 +1,27 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoLong : ValidationRule + { + public ValidacaoLong() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString()) || value.ToString().ValidateLong()) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "Número Inválido"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoLongObrigatorio.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoLongObrigatorio.cs new file mode 100644 index 0000000..fd4773b --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoLongObrigatorio.cs @@ -0,0 +1,31 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoLongObrigatorio : ValidationRule + { + public ValidacaoLongObrigatorio() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString())) + { + return new ValidationResult(false, "Obrigatório"); + } + if (value.ToString().ValidateLong()) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "Número Inválido"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoObrigatorio.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoObrigatorio.cs new file mode 100644 index 0000000..23eb517 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoObrigatorio.cs @@ -0,0 +1,27 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoObrigatorio : ValidationRule + { + public ValidacaoObrigatorio() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (!string.IsNullOrWhiteSpace(obj.ToString())) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "OBRIGATÓRIO"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoOrgao.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoOrgao.cs new file mode 100644 index 0000000..d2f3dd1 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoOrgao.cs @@ -0,0 +1,27 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoOrgao : ValidationRule + { + public ValidacaoOrgao() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString()) || value.ToString().ValidateOrgao()) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "Orgão Inválido"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoPlaca.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoPlaca.cs new file mode 100644 index 0000000..b1825e1 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoPlaca.cs @@ -0,0 +1,27 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoPlaca : ValidationRule + { + public ValidacaoPlaca() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString()) || value.ToString().ValidatePlate()) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "Placa Inválida"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoPlacaObrigatorio.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoPlacaObrigatorio.cs new file mode 100644 index 0000000..cd56924 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoPlacaObrigatorio.cs @@ -0,0 +1,31 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoPlacaObrigatorio : ValidationRule + { + public ValidacaoPlacaObrigatorio() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString())) + { + return new ValidationResult(false, "Obrigatório"); + } + if (value.ToString().ValidatePlate()) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "Placa Inválida"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoPrefixo.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoPrefixo.cs new file mode 100644 index 0000000..8b4197b --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoPrefixo.cs @@ -0,0 +1,27 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoPrefixo : ValidationRule + { + public ValidacaoPrefixo() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString()) || value.ToString().ValidatePrefix()) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "DDD Inválido"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoPrefixoObrigatorio.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoPrefixoObrigatorio.cs new file mode 100644 index 0000000..36f2157 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoPrefixoObrigatorio.cs @@ -0,0 +1,31 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoPrefixoObrigatorio : ValidationRule + { + public ValidacaoPrefixoObrigatorio() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString())) + { + return new ValidationResult(false, "Obrigatório"); + } + if (value.ToString().ValidatePrefix()) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "DDD Inválido"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoRneObrigatorio.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoRneObrigatorio.cs new file mode 100644 index 0000000..5314ac6 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoRneObrigatorio.cs @@ -0,0 +1,31 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoRneObrigatorio : ValidationRule + { + public ValidacaoRneObrigatorio() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString())) + { + return new ValidationResult(false, "Obrigatório"); + } + if (value.ToString().ValidateRne()) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "RNE Inválido"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoTelefone.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoTelefone.cs new file mode 100644 index 0000000..1723d56 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoTelefone.cs @@ -0,0 +1,27 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoTelefone : ValidationRule + { + public ValidacaoTelefone() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString()) || value.ToString().ValidatePhone()) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "Telefone Inválido"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoTelefoneObrigatorio.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoTelefoneObrigatorio.cs new file mode 100644 index 0000000..37f33c6 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoTelefoneObrigatorio.cs @@ -0,0 +1,31 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoTelefoneObrigatorio : ValidationRule + { + public ValidacaoTelefoneObrigatorio() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString())) + { + return new ValidationResult(false, "Obrigatório"); + } + if (value.ToString().ValidatePhone()) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "Telefone Inválido"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoValorDiferenteZero.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoValorDiferenteZero.cs new file mode 100644 index 0000000..f7f7aa3 --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoValorDiferenteZero.cs @@ -0,0 +1,31 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoValorDiferenteZero : ValidationRule + { + public ValidacaoValorDiferenteZero() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString())) + { + return new ValidationResult(false, "Obrigatório"); + } + if (value.ToString().ValidateDouble() && !((decimal)value == decimal.Zero)) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "Valor Inválido"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoValorMaiorQueZero.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoValorMaiorQueZero.cs new file mode 100644 index 0000000..5ab3a4f --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidacaoValorMaiorQueZero.cs @@ -0,0 +1,31 @@ +using System; +using System.Globalization; +using System.Windows.Controls; + +namespace Gestor.Common.Validation +{ + public class ValidacaoValorMaiorQueZero : ValidationRule + { + public ValidacaoValorMaiorQueZero() + { + } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + object obj = value; + if (obj == null) + { + obj = ""; + } + if (string.IsNullOrWhiteSpace(obj.ToString())) + { + return new ValidationResult(false, "Obrigatório"); + } + if (value.ToString().ValidateDouble() && !((decimal)value < new decimal(1, 0, 0, false, 2))) + { + return ValidationResult.ValidResult; + } + return new ValidationResult(false, "Valor Inválido"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidationHelper.cs b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidationHelper.cs new file mode 100644 index 0000000..585565c --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.Validation/ValidationHelper.cs @@ -0,0 +1,992 @@ +using Gestor.Common.Helpers; +using Gestor.Model.Attributes; +using Gestor.Model.Helper; +using Microsoft.Win32; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading; + +namespace Gestor.Common.Validation +{ + public static class ValidationHelper + { + public static void AddSorted(this ObservableCollection list, T item, IComparer comparer = null) + { + if (comparer == null) + { + comparer = Comparer.Default; + } + int num = 0; + while (num < list.Count && comparer.Compare(list[num], item) < 0) + { + num++; + } + list.Insert(num, item); + } + + public static int Age(this DateTime birthDate) + { + DateTime date = Functions.GetNetworkTime().Date; + int year = date.Year - birthDate.Year; + if (birthDate > date.AddYears(-year)) + { + year--; + } + return year; + } + + public static string Alphanumeric(this string stringToClean, string replaceWith = "") + { + return Regex.Replace(stringToClean, "[^a-zA-Z0-9]", replaceWith); + } + + public static string AlphanumericAndSpace(this string stringToClean) + { + return Regex.Replace(stringToClean, "[^a-zA-Z0-9 ]", string.Empty); + } + + public static string Captalize(this string text) + { + return (new CultureInfo("pt-Br", false)).TextInfo.ToTitleCase(text.ToLower()); + } + + public static string Clear(this string stringToClean) + { + if (stringToClean == null) + { + return null; + } + return Regex.Replace(stringToClean, "[^\\d]", string.Empty); + } + + public static string ClearCurrency(this string stringToClean) + { + if (string.IsNullOrEmpty(stringToClean)) + { + return string.Empty; + } + return Regex.Replace(stringToClean, "[^\\d\\,\\.]", string.Empty); + } + + public static bool ContainsAny(this string stringToCheck, params string[] stringArray) + { + return stringArray.Any(new Func(stringToCheck.Contains)); + } + + public static bool ContainsEquals(this T @this, params T[] possibles) + { + return possibles.Contains(@this); + } + + public static string DescriptionAttribute(this PropertyInfo pi) + { + object obj = pi.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault(); + if (obj == null) + { + return ""; + } + return ((DescriptionAttribute)obj).Description; + } + + public static string FormatarTelefone(this string number) + { + string str; + int? nullable; + if (number != null) + { + str = number.OnlyNumber(); + } + else + { + str = null; + } + number = str; + if (number != null) + { + nullable = new int?(number.Length); + } + else + { + nullable = null; + } + int? nullable1 = nullable; + if (nullable1.HasValue) + { + switch (nullable1.GetValueOrDefault()) + { + case 8: + { + return Convert.ToUInt64(number).ToString("0000\\-0000"); + } + case 9: + { + return Convert.ToUInt64(number).ToString("00000\\-0000"); + } + case 11: + { + return Convert.ToUInt64(number).ToString("0000 000 0000"); + } + } + } + return number.Clear(); + } + + public static string FormatCi(this string value) + { + long num; + string str = value.OnlyNumber().Trim(); + if (string.IsNullOrEmpty(str)) + { + return string.Empty; + } + if (!long.TryParse(str, out num)) + { + return str; + } + return Convert.ToUInt64(str).ToString("00\\.000\\.000\\.000\\.000"); + } + + public static string FormatCompetencia(this string date) + { + if (string.IsNullOrEmpty(date)) + { + return ""; + } + date = date.OnlyNumber(); + switch (date.Length) + { + case 2: + { + int year = Functions.GetNetworkTime().Date.Year; + date = string.Concat(date, year.ToString()); + return Convert.ToUInt64(date).ToString("00\\/0000"); + } + case 3: + case 5: + { + return date; + } + case 4: + { + return Convert.ToUInt64(date).ToString("00\\/00"); + } + case 6: + { + return Convert.ToUInt64(date).ToString("00\\/0000"); + } + default: + { + return date; + } + } + } + + public static string FormatCurrency(this string value) + { + if (string.IsNullOrEmpty(value)) + { + return ""; + } + return value.ToCurrency("pt-BR").ToString("c"); + } + + public static string FormatDate(this string date) + { + if (string.IsNullOrEmpty(date)) + { + return ""; + } + date = date.OnlyNumber(); + switch (date.Length) + { + case 4: + { + int year = Functions.GetNetworkTime().Date.Year; + date = string.Concat(date, year.ToString()); + return Convert.ToUInt64(date).ToString("00\\/00\\/0000"); + } + case 5: + case 7: + { + return date; + } + case 6: + { + return Convert.ToUInt64(date).ToString("00\\/00\\/00"); + } + case 8: + { + return Convert.ToUInt64(date).ToString("00\\/00\\/0000"); + } + default: + { + return date; + } + } + } + + public static string FormatDocument(this string number) + { + number = number.OnlyNumber(); + int length = number.Length; + if (length == 11) + { + return Convert.ToUInt64(number).ToString("000\\.000\\.000\\-00"); + } + if (length != 14) + { + return number; + } + return Convert.ToUInt64(number).ToString("00\\.000\\.000\\/0000\\-00"); + } + + public static string FormatFipe(this string value) + { + if (string.IsNullOrEmpty(value)) + { + return ""; + } + ulong num = Convert.ToUInt64(value.OnlyNumber()); + return num.ToString("000000\\-0"); + } + + public static string FormatPostCode(this string postCode) + { + if (string.IsNullOrEmpty(postCode)) + { + return ""; + } + return postCode.FormataCep(); + } + + public static string FormatRegiao(this string str) + { + if (Regex.Match(str, "[^0-9-.]").Success) + { + return str; + } + if (string.IsNullOrEmpty(str)) + { + return ""; + } + ulong num = Convert.ToUInt64(str.OnlyNumber()); + return num.ToString("00\\.000\\-000"); + } + + public static string FormatRenavam(this string value) + { + long num; + if (string.IsNullOrEmpty(value)) + { + return string.Empty; + } + if (!long.TryParse(value.OnlyNumber(), out num)) + { + return string.Empty; + } + return num.ToString("00\\.000\\.000\\.000"); + } + + public static string FormatTime(this string time) + { + if (string.IsNullOrEmpty(time)) + { + return null; + } + time = time.OnlyNumber(); + int length = time.Length; + if (length == 3) + { + return Convert.ToUInt64(time).ToString("00:00"); + } + if (length != 4) + { + return null; + } + return Convert.ToUInt64(time).ToString("00:00"); + } + + public static string GetCategory(this Enum genericEnum) + { + MemberInfo[] member = genericEnum.GetType().GetMember(genericEnum.ToString()); + if (member.Length == 0) + { + return genericEnum.ToString(); + } + object[] customAttributes = member[0].GetCustomAttributes(typeof(CategoryAttribute), false); + if (!customAttributes.Any()) + { + return genericEnum.ToString(); + } + return ((CategoryAttribute)customAttributes.ElementAt(0)).Category; + } + + public static string GetDefaultExtension(this string mimeType) + { + object value; + RegistryKey registryKey = Registry.ClassesRoot.OpenSubKey(string.Concat("MIME\\Database\\Content Type\\", mimeType), false); + if (registryKey != null) + { + value = registryKey.GetValue("Extension", null); + } + else + { + value = null; + } + object obj = value; + if (obj != null) + { + return obj.ToString(); + } + return string.Join(string.Empty, mimeType.Split(Path.GetInvalidPathChars())).Replace("/", "."); + } + + public static string GetDescription(this Enum genericEnum) + { + if (genericEnum == null) + { + return ""; + } + MemberInfo[] member = genericEnum.GetType().GetMember(genericEnum.ToString()); + if (member.Length == 0) + { + return genericEnum.ToString(); + } + object[] customAttributes = member[0].GetCustomAttributes(typeof(DescriptionAttribute), false); + if (!customAttributes.Any()) + { + return genericEnum.ToString().Trim(); + } + return ((DescriptionAttribute)customAttributes.ElementAt(0)).Description.Trim(); + } + + public static string GetEntity(this Enum genericEnum) + { + MemberInfo[] member = genericEnum.GetType().GetMember(genericEnum.ToString()); + if (member.Length == 0) + { + return genericEnum.ToString(); + } + object[] customAttributes = member[0].GetCustomAttributes(typeof(EntityAttribute), false); + if (!customAttributes.Any()) + { + return genericEnum.ToString(); + } + return ((EntityAttribute)customAttributes.ElementAt(0)).Description; + } + + public static T GetEnumFromDescription(string description) + { + Type type = typeof(T); + if (!type.IsEnum) + { + throw new InvalidOperationException(); + } + FieldInfo[] fields = type.GetFields(); + for (int i = 0; i < (int)fields.Length; i++) + { + FieldInfo fieldInfo = fields[i]; + DescriptionAttribute customAttribute = Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute)) as DescriptionAttribute; + if (customAttribute != null) + { + if (customAttribute.Description == description) + { + return (T)fieldInfo.GetValue(null); + } + } + else if (fieldInfo.Name == description) + { + return (T)fieldInfo.GetValue(null); + } + } + throw new ArgumentException("Not found.", "description"); + } + + public static T GetEnumFromEntity(this string entityName) + { + T t; + Type type = typeof(T); + if (!type.IsEnum) + { + t = default(T); + return t; + } + FieldInfo[] fields = type.GetFields(); + for (int i = 0; i < (int)fields.Length; i++) + { + FieldInfo fieldInfo = fields[i]; + EntityAttribute customAttribute = Attribute.GetCustomAttribute(fieldInfo, typeof(EntityAttribute)) as EntityAttribute; + if (customAttribute != null) + { + if (customAttribute.Description == entityName) + { + return (T)fieldInfo.GetValue(null); + } + } + else if (fieldInfo.Name == entityName) + { + return (T)fieldInfo.GetValue(null); + } + } + t = default(T); + return t; + } + + public static string GetHelp(this Enum genericEnum) + { + MemberInfo[] member = genericEnum.GetType().GetMember(genericEnum.ToString()); + if (member.Length == 0) + { + return genericEnum.ToString(); + } + object[] customAttributes = member[0].GetCustomAttributes(typeof(HelpAttribute), false); + if (!customAttributes.Any()) + { + return genericEnum.ToString(); + } + return ((HelpAttribute)customAttributes.ElementAt(0)).Description; + } + + public static string GetTipo(this Enum genericEnum) + { + MemberInfo[] member = genericEnum.GetType().GetMember(genericEnum.ToString()); + if (member.Length == 0) + { + return genericEnum.ToString(); + } + object[] customAttributes = member[0].GetCustomAttributes(typeof(TipoAttribute), false); + if (!customAttributes.Any()) + { + return genericEnum.ToString(); + } + return ((TipoAttribute)customAttributes.ElementAt(0)).Description; + } + + public static bool IsNotNullOrEmpty(this string stringToVerify) + { + return !string.IsNullOrEmpty(stringToVerify); + } + + public static bool IsNullOrEmpty(this string stringToVerify) + { + return string.IsNullOrEmpty(stringToVerify); + } + + public static string Join(this IEnumerable stringValues, string separator) + { + return string.Join(separator, stringValues); + } + + public static string Length(this string stringValue, int maxLength) + { + if (stringValue.Length <= maxLength) + { + return stringValue; + } + return stringValue.Substring(0, maxLength); + } + + public static string Mask(this string value, string mask) + { + int num = mask.Count((char x) => x == '#'); + if (string.IsNullOrEmpty(value) || num != value.Length) + { + return string.Empty; + } + string empty = string.Empty; + int num1 = 0; + int num2 = 0; + for (int i = 0; i < mask.Length; i++) + { + if (mask[i] != '#') + { + empty = string.Concat(empty, string.Format("{0}{1}", value.Substring(num1, i - num1 - num2), mask[i])); + num1 = i - num2; + num2++; + } + } + empty = string.Concat(empty, value.Substring(num1, mask.Length - num1 - num2)); + return empty; + } + + public static string Normalized(this string word) + { + if (string.IsNullOrEmpty(word)) + { + return string.Empty; + } + return Encoding.ASCII.GetString(Encoding.GetEncoding("Cyrillic").GetBytes(word)).ToUpper().Trim(); + } + + public static string NormalizePath(this string fullFilename) + { + int i; + char[] invalidPathChars = Path.GetInvalidPathChars(); + char[] invalidFileNameChars = Path.GetInvalidFileNameChars(); + fullFilename = fullFilename.Replace("/", string.Empty); + string fileName = Path.GetFileName(fullFilename); + string directoryName = Path.GetDirectoryName(fullFilename); + char[] chrArray = invalidPathChars; + for (i = 0; i < (int)chrArray.Length; i++) + { + char chr = chrArray[i]; + directoryName = directoryName.Replace(chr.ToString(), string.Empty); + } + chrArray = invalidFileNameChars; + for (i = 0; i < (int)chrArray.Length; i++) + { + char chr1 = chrArray[i]; + fileName = fileName.Replace(chr1.ToString(), string.Empty); + } + return string.Concat(directoryName, "\\", fileName); + } + + public static bool NotEquals(this string obj, string value) + { + return !obj.Equals(value); + } + + public static string OnlyNumber(this string sentence) + { + if (sentence == null) + { + return null; + } + return (new Regex("[^\\d]")).Replace(sentence, ""); + } + + public static string RemoveDiacritics(this string stringWithAccents) + { + if (stringWithAccents == null) + { + return ""; + } + return Encoding.ASCII.GetString(Encoding.GetEncoding("Cyrillic").GetBytes(stringWithAccents)); + } + + public static string RemoverAcentos(this string text) + { + if (string.IsNullOrEmpty(text)) + { + return string.Empty; + } + return new string(( + from c in text.Normalize(NormalizationForm.FormD) + where char.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark + select c).ToArray()); + } + + public static string RemoveTag(this string stringWithTag) + { + return Regex.Replace(stringWithTag, "<(.|\\n)*?>", string.Empty); + } + + public static string StringValue(this decimal decimalValue) + { + return decimalValue.ToString("F", new CultureInfo("en-US")); + } + + public static string ToCurrency(this T currencyDecimal, string currentCulture = "pt-BR") + { + return string.Format(new CultureInfo(currentCulture), "{0:N2}", currencyDecimal); + } + + public static decimal ToCurrency(this string currencyString, string currentCulture = "pt-BR") + { + decimal num; + decimal.TryParse(currencyString.ClearCurrency(), NumberStyles.Any, new CultureInfo(currentCulture), out num); + return num; + } + + public static string ToCurrencyWithSymbol(this T currencyDecimal, string currentCulture = "pt-BR") + { + return string.Format(new CultureInfo(currentCulture), "R$ {0:N2}", currencyDecimal); + } + + public static DateTime ToDateTime(this string dateString) + { + DateTime dateTime; + DateTime.TryParse(dateString.Trim(), out dateTime); + return dateTime; + } + + public static DateTime? ToDateTimeNullable(this string dateString) + { + DateTime dateTime; + DateTime? nullable; + if (dateString == null) + { + nullable = null; + return nullable; + } + DateTime.TryParse(dateString.Trim(), out dateTime); + if (dateTime != DateTime.MinValue) + { + return new DateTime?(dateTime); + } + nullable = null; + return nullable; + } + + public static string ToFloating(this T currencyDecimal, string currentCulture = "pt-BR") + { + return string.Format(new CultureInfo(currentCulture), "{0:F}", currencyDecimal); + } + + public static int ToInt(this string stringValue) + { + int num; + int.TryParse(stringValue, out num); + return num; + } + + public static int? ToIntNullable(this string stringValue) + { + int num; + if (int.TryParse(stringValue, out num)) + { + return new int?(num); + } + return null; + } + + public static long ToLong(this string stringValue) + { + long num; + long.TryParse(stringValue, out num); + return num; + } + + public static long? ToLongNullable(this string stringValue) + { + long num; + if (long.TryParse(stringValue, out num)) + { + return new long?(num); + } + return null; + } + + public static string ToTitleCase(this string stringValue) + { + return Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(stringValue.ToLower()); + } + + public static string ToToken(this string postCode) + { + return Functions.GetNetworkTime().ToFileTime().ToString(); + } + + public static bool ValidaCep(this string cep) + { + if (!string.IsNullOrWhiteSpace(cep)) + { + return false; + } + return Regex.IsMatch(cep, "^\\d{5}-?\\d{3}$"); + } + + public static bool ValidateAno(this string ano) + { + int num; + if (!int.TryParse(ano, out num)) + { + return false; + } + return ano.Length == 4; + } + + public static bool ValidateAttendanceNumber(this string number) + { + if (number == null) + { + return false; + } + return Regex.Match(number, "^[0-9]").Success; + } + + public static bool ValidateCaepf(this string caepf) + { + return !string.IsNullOrEmpty(caepf); + } + + public static bool ValidateCei(this string cei) + { + if (string.IsNullOrEmpty(cei)) + { + return false; + } + cei = cei.Trim(); + cei = Regex.Replace(cei, "[^\\d]", ""); + if (cei.Length != 12) + { + return false; + } + int num = 0; + for (int i = 1; i < 12; i++) + { + int num1 = Convert.ToInt32("74185216374".Substring(i - 1, 1)); + int num2 = Convert.ToInt32(cei.Substring(i - 1, 1)); + num = num + num1 * num2; + } + int num3 = num / 10; + int num4 = num - num / 10 * 10; + num = num3 + num4; + num4 = num - num / 10 * 10; + int num5 = 10 - num4; + return Convert.ToInt32(cei.Substring(11, 1)) == num5; + } + + public static bool ValidateChassi(this string chassiNumber) + { + string upper; + if (chassiNumber != null) + { + upper = chassiNumber.ToUpper(); + } + else + { + upper = null; + } + chassiNumber = upper; + if (string.IsNullOrEmpty(chassiNumber)) + { + return true; + } + if (chassiNumber.Length != 17 || Regex.IsMatch(chassiNumber, "^0| |^.{4,}([0-9A-Z])\\1{5,}|[iIoOqQ]")) + { + return false; + } + return Regex.IsMatch(chassiNumber, "[0-9]{4}$"); + } + + public static bool ValidateDate(this string birthday) + { + DateTime dateTime; + return DateTime.TryParse(birthday, out dateTime); + } + + public static bool ValidateDecimal(this string value) + { + decimal num; + return decimal.TryParse(value, out num); + } + + public static bool ValidateDocument(this string cpfCnpj) + { + int j; + int i; + int num; + if (string.IsNullOrEmpty(cpfCnpj)) + { + return false; + } + string str = cpfCnpj.Clear(); + int[] numArray = new int[14]; + int[] numArray1 = new int[2]; + if (str == string.Empty || new string(str[0], str.Length) == str) + { + return false; + } + if (str.Length == 11) + { + for (i = 0; i <= 10; i++) + { + numArray[i] = Convert.ToInt32(str.Substring(i, 1)); + } + for (i = 0; i <= 1; i++) + { + num = 0; + for (j = 0; j <= 8 + i; j++) + { + num = num + numArray[j] * (10 + i - j); + } + numArray1[i] = num * 10 % 11; + if (numArray1[i] == 10) + { + numArray1[i] = 0; + } + } + return numArray1[0] == numArray[9] & numArray1[1] == numArray[10]; + } + if (str.Length != 14) + { + return false; + } + for (i = 0; i <= 13; i++) + { + numArray[i] = Convert.ToInt32(str.Substring(i, 1)); + } + for (i = 0; i <= 1; i++) + { + num = 0; + for (j = 0; j <= 11 + i; j++) + { + num = num + numArray[j] * Convert.ToInt32("6543298765432".Substring(j + 1 - i, 1)); + } + numArray1[i] = num * 10 % 11; + if (numArray1[i] == 10) + { + numArray1[i] = 0; + } + } + return numArray1[0] == numArray[12] & numArray1[1] == numArray[13]; + } + + public static bool ValidateDouble(this string number) + { + double num; + return double.TryParse(number, out num); + } + + public static bool ValidateFipe(this string value) + { + if ((new Regex("^\\d{6}\\-\\d{1}$")).IsMatch(value)) + { + return true; + } + return false; + } + + public static bool ValidateFutureDate(this string birthday) + { + DateTime dateTime; + if (!DateTime.TryParse(birthday, out dateTime)) + { + return false; + } + return dateTime > Functions.GetNetworkTime().Date; + } + + public static bool ValidateInt(this string value) + { + int num; + return int.TryParse(value, out num); + } + + public static bool ValidateLong(this string value) + { + long num; + return long.TryParse(value, out num); + } + + public static bool ValidateMail(this string mail) + { + if (mail == null) + { + return false; + } + return (new Regex("^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$")).IsMatch(mail); + } + + public static bool ValidateOrgao(this string orgao) + { + if (string.IsNullOrEmpty(orgao)) + { + return false; + } + return (new string[] { "SSP", "DETRAN", "ABNC", "CGPI", "DUREX", "DPF", "CGPI", "CGPMAF", "CNIG", "CNT", "COREN", "CORECON", "CRA", "CRAS", "CRB", "CRC", "CRE", "CREA", "CRECI", "CREFIT", "CRESS", "CRF", "CRM", "CRN", "CRO", "CRP", "CRPRE", "CRQ", "CRRC", "CRMV", "CSC", "CTPS", "DIC", "DIREX", "DPMAF", "DPT", "DST", "FGTS", "FIPE", "FLS", "GOVGO", "I CLA", "IFP", "IGP", "IICCECF/RO", "IIMG", "IML", "IPC", "IPF", "MAE", "MEX", "MMA", "OAB", "OMB", "PCMG", "PMMG", "POM", "SDS", "SNJ", "SECC", "SEJUSP", "SES", "EST", "SESP", "SJS", "SJTC", "SJTS", "SPTC", "DGPC", "" }).Contains(orgao.ToUpper()); + } + + public static bool ValidatePastDate(this string birthday) + { + DateTime dateTime; + if (!DateTime.TryParse(birthday, out dateTime)) + { + return false; + } + return dateTime < Functions.GetNetworkTime().Date; + } + + public static bool ValidatePhone(this string number) + { + if (number == null) + { + return false; + } + return Regex.Match(number, "^([2-9][0-9]{3,4})\\-([0-9]{4})$").Success; + } + + public static bool ValidatePlate(this string plateNumber) + { + string str; + if (plateNumber != null) + { + str = plateNumber.Alphanumeric(""); + } + else + { + str = null; + } + if (string.IsNullOrEmpty(str)) + { + return true; + } + return Regex.IsMatch(plateNumber, "^[a-zA-Z]{3}-?[0-9]{4}$"); + } + + public static bool ValidatePostCode(this string postCode) + { + if (postCode == null) + { + return false; + } + return Regex.Match(postCode, "^[0-9]{2}.?[0-9]{3}-[0-9]{3}$").Success; + } + + public static bool ValidatePrefix(this string prefix) + { + int num; + if (!int.TryParse(prefix, out num)) + { + return false; + } + if (num != 20 && num != 23 && num != 25 && num != 26 && num != 29 && num != 30 && num != 36 && num != 39 && num != 40 && num != 50 && num != 52 && num != 56 && num != 57 && num != 58 && num != 59 && num != 60 && num != 70 && num != 72 && num != 76 && num != 78 && num != 80 && num != 90 && num >= 11 && num <= 99) + { + return true; + } + return false; + } + + public static bool ValidateRne(this string rne) + { + if (string.IsNullOrEmpty(rne)) + { + return false; + } + return true; + } + + public static bool ValidateState(this string state) + { + if (string.IsNullOrEmpty(state)) + { + return false; + } + return (new string[] { "AC", "AL", "AP", "AM", "BA", "CE", "DF", "ES", "GO", "MA", "MT", "MS", "MG", "PA", "PB", "PR", "PE", "PI", "RJ", "RN", "RS", "RO", "RR", "SC", "SP", "SE", "TO" }).Contains(state.ToUpper()); + } + + public static bool ValidateValor(this string value) + { + string[] strArrays = value.Split(new char[] { '.' }); + if ((int)strArrays.Length < 2) + { + return true; + } + if ((int)strArrays.Length != 2) + { + return false; + } + return strArrays[1].Length <= 2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.csproj b/Codemerx/Gestor.Common/Gestor.Common.csproj new file mode 100644 index 0000000..c6a309d --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.csproj @@ -0,0 +1,490 @@ + + + + {AF38021A-3584-40B5-88EF-4742A4C443F5} + Debug + AnyCPU + Gestor.Common + Library + v4.8 + + + bin\Debug\ + true + DEBUG;TRACE + false + 4 + full + prompt + AnyCPU + + + bin\Release\ + false + TRACE + true + 4 + pdbonly + prompt + AnyCPU + + + + + + .\Gestor.CommonReferences\Gestor.Model.dll + + + + + + + + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + false + false + + + + \ No newline at end of file diff --git a/Codemerx/Gestor.Common/Gestor.Common.sln b/Codemerx/Gestor.Common/Gestor.Common.sln new file mode 100644 index 0000000..f22689d --- /dev/null +++ b/Codemerx/Gestor.Common/Gestor.Common.sln @@ -0,0 +1,21 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29728.190 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Gestor.Common", "Gestor.Common.csproj", "{AF38021A-3584-40B5-88EF-4742A4C443F5}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {AF38021A-3584-40B5-88EF-4742A4C443F5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AF38021A-3584-40B5-88EF-4742A4C443F5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AF38021A-3584-40B5-88EF-4742A4C443F5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AF38021A-3584-40B5-88EF-4742A4C443F5}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Codemerx/Gestor.Common/Gestor.CommonReferences/Gestor.Model.dll b/Codemerx/Gestor.Common/Gestor.CommonReferences/Gestor.Model.dll new file mode 100644 index 0000000..2b2b2d0 Binary files /dev/null and b/Codemerx/Gestor.Common/Gestor.CommonReferences/Gestor.Model.dll differ diff --git a/Codemerx/Gestor.Common/Properties/AssemblyInfo.cs b/Codemerx/Gestor.Common/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..4107ae2 --- /dev/null +++ b/Codemerx/Gestor.Common/Properties/AssemblyInfo.cs @@ -0,0 +1,20 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; + +[assembly: AssemblyCompany("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCopyright("Copyright © 2019")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyFileVersion("8.4.0.0")] +[assembly: AssemblyProduct("Gestor.Common")] +[assembly: AssemblyTitle("Gestor.Common")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyVersion("8.4.0.0")] +[assembly: CompilationRelaxations(8)] +[assembly: ComVisible(false)] +[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] +[assembly: Guid("73d1cb17-a0c5-4e22-884f-171c125d27bc")] +[assembly: RuntimeCompatibility(WrapNonExceptionThrows=true)] diff --git a/Codemerx/Gestor.Infrastructure/.vs/Gestor.Infrastructure/FileContentIndex/57a0321b-2dd7-4d59-adab-1ed08962f43e.vsidx b/Codemerx/Gestor.Infrastructure/.vs/Gestor.Infrastructure/FileContentIndex/57a0321b-2dd7-4d59-adab-1ed08962f43e.vsidx new file mode 100644 index 0000000..b761246 Binary files /dev/null and b/Codemerx/Gestor.Infrastructure/.vs/Gestor.Infrastructure/FileContentIndex/57a0321b-2dd7-4d59-adab-1ed08962f43e.vsidx differ diff --git a/Codemerx/Gestor.Infrastructure/.vs/Gestor.Infrastructure/v18/.suo b/Codemerx/Gestor.Infrastructure/.vs/Gestor.Infrastructure/v18/.suo new file mode 100644 index 0000000..95a33ae Binary files /dev/null and b/Codemerx/Gestor.Infrastructure/.vs/Gestor.Infrastructure/v18/.suo differ diff --git a/Codemerx/Gestor.Infrastructure/.vs/Gestor.Infrastructure/v18/DocumentLayout.backup.json b/Codemerx/Gestor.Infrastructure/.vs/Gestor.Infrastructure/v18/DocumentLayout.backup.json new file mode 100644 index 0000000..bd7eb28 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/.vs/Gestor.Infrastructure/v18/DocumentLayout.backup.json @@ -0,0 +1,12 @@ +{ + "Version": 1, + "WorkspaceRootPath": "C:\\Users\\Usuario\\Downloads\\CodemerxDecompile-windows-x64\\Gestor\\Gestor.Infra\\", + "Documents": [], + "DocumentGroupContainers": [ + { + "Orientation": 0, + "VerticalTabListWidth": 256, + "DocumentGroups": [] + } + ] +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/.vs/Gestor.Infrastructure/v18/DocumentLayout.json b/Codemerx/Gestor.Infrastructure/.vs/Gestor.Infrastructure/v18/DocumentLayout.json new file mode 100644 index 0000000..7777b96 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/.vs/Gestor.Infrastructure/v18/DocumentLayout.json @@ -0,0 +1,37 @@ +{ + "Version": 1, + "WorkspaceRootPath": "C:\\Users\\Usuario\\Downloads\\CodemerxDecompile-windows-x64\\Gestor\\Gestor.Infra\\", + "Documents": [ + { + "AbsoluteMoniker": "D:0:0:{21360061-8C6F-4A8A-8E1B-2850369E55AA}|Gestor.Infrastructure.csproj|c:\\users\\usuario\\downloads\\codemerxdecompile-windows-x64\\gestor\\gestor.infra\\gestor.infrastructure.helpers\\funcoes.cs||{A6C744A8-0E4A-4FC6-886A-064283054674}", + "RelativeMoniker": "D:0:0:{21360061-8C6F-4A8A-8E1B-2850369E55AA}|Gestor.Infrastructure.csproj|solutionrelative:gestor.infrastructure.helpers\\funcoes.cs||{A6C744A8-0E4A-4FC6-886A-064283054674}" + } + ], + "DocumentGroupContainers": [ + { + "Orientation": 0, + "VerticalTabListWidth": 256, + "DocumentGroups": [ + { + "DockedWidth": 200, + "SelectedChildIndex": 0, + "Children": [ + { + "$type": "Document", + "DocumentIndex": 0, + "Title": "Funcoes.cs", + "DocumentMoniker": "C:\\Users\\Usuario\\Downloads\\CodemerxDecompile-windows-x64\\Gestor\\Gestor.Infra\\Gestor.Infrastructure.Helpers\\Funcoes.cs", + "RelativeDocumentMoniker": "Gestor.Infrastructure.Helpers\\Funcoes.cs", + "ToolTip": "C:\\Users\\Usuario\\Downloads\\CodemerxDecompile-windows-x64\\Gestor\\Gestor.Infra\\Gestor.Infrastructure.Helpers\\Funcoes.cs", + "RelativeToolTip": "Gestor.Infrastructure.Helpers\\Funcoes.cs", + "ViewState": "AgIAACADAAAAAAAAAAAewCsDAAALAAAAAAAAAA==", + "Icon": "ae27a6b0-e345-4288-96df-5eaf394ee369.000738|", + "WhenOpened": "2026-03-30T11:32:40.79Z", + "EditorCaption": "" + } + ] + } + ] + } + ] +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Configuration/ConfigurationFileCache.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Configuration/ConfigurationFileCache.cs new file mode 100644 index 0000000..4864edc --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Configuration/ConfigurationFileCache.cs @@ -0,0 +1,133 @@ +using Gestor.Common.Helpers; +using NHibernate.Cfg; +using System; +using System.ComponentModel; +using System.Data.SqlClient; +using System.IO; +using System.Reflection; +using System.Runtime.Serialization.Formatters.Binary; + +namespace Gestor.Infrastructure.Configuration +{ + public class ConfigurationFileCache + { + private readonly string _cacheFile; + + private readonly Assembly _definitionsAssembly; + + private bool IsConfigurationFileValid + { + get + { + string location; + if (!File.Exists(this._cacheFile)) + { + return false; + } + FileInfo fileInfo = new FileInfo(this._cacheFile); + Assembly assembly = this._definitionsAssembly; + if (assembly != null) + { + location = assembly.Location; + } + else + { + location = null; + } + string str = location; + if (str == null) + { + return false; + } + FileInfo fileInfo1 = new FileInfo(str); + if (fileInfo.Length < (long)5120) + { + return false; + } + return fileInfo.LastWriteTime >= fileInfo1.LastWriteTime; + } + } + + public ConfigurationFileCache(string connectionString) + { + if (connectionString == null) + { + return; + } + this._definitionsAssembly = Assembly.GetExecutingAssembly(); + SqlConnection sqlConnection = new SqlConnection(connectionString); + string str = string.Concat("Data_", sqlConnection.Database, ".cfg"); + sqlConnection.Dispose(); + this._cacheFile = string.Concat(AppDomain.CurrentDomain.BaseDirectory, str); + } + + public void DeleteCacheFile() + { + try + { + if (File.Exists(this._cacheFile)) + { + File.Delete(this._cacheFile); + } + } + catch (Exception exception) + { + } + } + + public NHibernate.Cfg.Configuration LoadConfigurationFromFile() + { + NHibernate.Cfg.Configuration configuration; + if (!this.IsConfigurationFileValid) + { + return null; + } + try + { + using (FileStream fileStream = File.Open(this._cacheFile, FileMode.Open, FileAccess.Read)) + { + using (MemoryStream memoryStream = new MemoryStream(ConfigurationFileCache.ReadFully(fileStream).DecryptBytes())) + { + configuration = (new BinaryFormatter()).Deserialize(memoryStream) as NHibernate.Cfg.Configuration; + } + } + } + catch (Exception exception) + { + this.DeleteCacheFile(); + configuration = null; + } + return configuration; + } + + private static byte[] ReadFully(Stream inputStream) + { + byte[] array; + using (MemoryStream memoryStream = new MemoryStream()) + { + inputStream.CopyTo(memoryStream); + array = memoryStream.ToArray(); + } + return array; + } + + public void SaveConfigurationToFile(NHibernate.Cfg.Configuration configuration) + { + try + { + using (FileStream fileStream = File.Open(this._cacheFile, FileMode.Create, FileAccess.Write, FileShare.ReadWrite)) + { + using (MemoryStream memoryStream = new MemoryStream()) + { + (new BinaryFormatter()).Serialize(memoryStream, configuration); + byte[] numArray = memoryStream.ToArray().EncryptBytes(); + fileStream.Write(numArray, 0, (int)numArray.Length); + } + } + } + catch (Exception exception) + { + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Configuration/SessionFactory.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Configuration/SessionFactory.cs new file mode 100644 index 0000000..236c026 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Configuration/SessionFactory.cs @@ -0,0 +1,144 @@ +using FluentNHibernate.Cfg; +using FluentNHibernate.Cfg.Db; +using Gestor.Infrastructure.Entities.Seguros; +using NHibernate; +using NHibernate.Cfg; +using NHibernate.Connection; +using NHibernate.Impl; +using NHibernate.Mapping; +using NHibernate.Tool.hbm2ddl; +using System; +using System.ComponentModel; +using System.Data.SqlClient; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Configuration +{ + public class SessionFactory + { + private static ISessionFactory _sessionFactory; + + private static string ConnectionString + { + get; + set; + } + + public static bool Retry + { + get; + set; + } + + private static ISessionFactory Session + { + get + { + object connection; + SessionFactoryImpl sessionFactoryImpl = SessionFactory._sessionFactory as SessionFactoryImpl; + if (sessionFactoryImpl != null) + { + connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + SqlConnection sqlConnection = connection as SqlConnection; + SqlConnection sqlConnection1 = new SqlConnection(SessionFactory.ConnectionString); + if (sqlConnection == null || sqlConnection.Database != sqlConnection1.Database) + { + SessionFactory.Initialize(); + } + sqlConnection1.Dispose(); + return SessionFactory._sessionFactory; + } + } + + public SessionFactory() + { + } + + private static NHibernate.Cfg.Configuration BuildConfiguration() + { + MsSqlConfiguration msSqlConfiguration = MsSqlConfiguration.MsSql2012.ConnectionString(SessionFactory.ConnectionString).ShowSql(); + return Fluently.Configure().Database(msSqlConfiguration).Mappings((MappingConfiguration m) => m.FluentMappings.AddFromAssemblyOf()).ExposeConfiguration((NHibernate.Cfg.Configuration cfg) => (new SchemaUpdate(cfg)).Execute(false, true)).BuildConfiguration(); + } + + private static void BuildSessionFactory(bool withDelete = false) + { + SessionFactory._sessionFactory = SessionFactory.ConfigurationFile(withDelete).BuildSessionFactory(); + } + + private static FluentConfiguration ConfigurationFile(bool withDelete) + { + NHibernate.Cfg.Configuration configuration; + ConfigurationFileCache configurationFileCache = new ConfigurationFileCache(SessionFactory.ConnectionString); + if (withDelete) + { + configurationFileCache.DeleteCacheFile(); + } + NHibernate.Cfg.Configuration configuration1 = configurationFileCache.LoadConfigurationFromFile(); + configuration1 = SessionFactory.FixConfiguration(configuration1); + if (configuration1 != null) + { + configuration = configuration1; + configuration.SetProperty("connection.connection_string", SessionFactory.ConnectionString); + } + else + { + configuration = SessionFactory.BuildConfiguration(); + configurationFileCache.SaveConfigurationToFile(configuration); + } + return Fluently.Configure(configuration); + } + + private static NHibernate.Cfg.Configuration FixConfiguration(NHibernate.Cfg.Configuration cachedConfiguration) + { + NHibernate.Cfg.Configuration configuration; + if (cachedConfiguration == null) + { + return cachedConfiguration; + } + Type type = typeof(ClienteDb); + if (cachedConfiguration.ClassMappings.Any((PersistentClass x) => x.EntityName == type.FullName)) + { + configuration = cachedConfiguration; + } + else + { + configuration = null; + } + cachedConfiguration = configuration; + return cachedConfiguration; + } + + public static void Initialize() + { + if (SessionFactory.ConnectionString == null) + { + throw new ArgumentNullException(); + } + try + { + SessionFactory.BuildSessionFactory(false); + } + catch (Exception exception) + { + SessionFactory.BuildSessionFactory(true); + } + } + + public static ISession OpenSession(string connectionString) + { + SessionFactory.ConnectionString = connectionString; + ISessionFactory session = SessionFactory.Session; + if (session != null) + { + return session.OpenSession(); + } + return null; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Aggilizador/VinculoDocumentoDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Aggilizador/VinculoDocumentoDb.cs new file mode 100644 index 0000000..1af8f09 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Aggilizador/VinculoDocumentoDb.cs @@ -0,0 +1,31 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Aggilizador +{ + public class VinculoDocumentoDb : EntityBase + { + public virtual long IdApoliceDigital + { + get; + set; + } + + public virtual long IdDocumento + { + get; + set; + } + + public virtual long IdPropostaDigital + { + get; + set; + } + + public VinculoDocumentoDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/AtividadeDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/AtividadeDb.cs new file mode 100644 index 0000000..6b5c04f --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/AtividadeDb.cs @@ -0,0 +1,25 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Common +{ + public class AtividadeDb : EntityBase + { + public virtual string Cnac + { + get; + set; + } + + public virtual string Nome + { + get; + set; + } + + public AtividadeDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/AtualizacaoDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/AtualizacaoDb.cs new file mode 100644 index 0000000..4e93f60 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/AtualizacaoDb.cs @@ -0,0 +1,24 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Common +{ + public class AtualizacaoDb + { + public virtual DateTime DataAtualizacao + { + get; + set; + } + + public virtual long IdArquivo + { + get; + set; + } + + public AtualizacaoDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/BancoDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/BancoDb.cs new file mode 100644 index 0000000..db60a00 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/BancoDb.cs @@ -0,0 +1,36 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Common +{ + public class BancoDb + { + public virtual int Codigo + { + get; + set; + } + + public virtual int Id + { + get; + set; + } + + public virtual string Nome + { + get; + set; + } + + public virtual string Site + { + get; + set; + } + + public BancoDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/ControleArquivoDigitalDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/ControleArquivoDigitalDb.cs new file mode 100644 index 0000000..d9324c0 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/ControleArquivoDigitalDb.cs @@ -0,0 +1,25 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Common +{ + public class ControleArquivoDigitalDb : EntityBase + { + public virtual string Catalogo + { + get; + set; + } + + public virtual string Tabela + { + get; + set; + } + + public ControleArquivoDigitalDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/EmpresaDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/EmpresaDb.cs new file mode 100644 index 0000000..aba1186 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/EmpresaDb.cs @@ -0,0 +1,189 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Common +{ + public class EmpresaDb : EnderecoBase + { + private string _email; + + public virtual string Documento + { + get; + set; + } + + public virtual string Email + { + get + { + string str = this._email; + if (str != null) + { + return str.ToLower(); + } + return null; + } + set + { + this._email = value; + } + } + + public virtual string EmailResponsavel + { + get; + set; + } + + public virtual string Facebook + { + get; + set; + } + + public virtual string Instagram + { + get; + set; + } + + public virtual string Linkdin + { + get; + set; + } + + public virtual string Localizacao + { + get; + set; + } + + public virtual byte[] Logo + { + get; + set; + } + + public virtual string LogoId + { + get; + set; + } + + public virtual int MaxFileSize + { + get; + set; + } + + public virtual string Nome + { + get; + set; + } + + public virtual string NomeSocial + { + get; + set; + } + + public virtual string PrimeiroPrefixo + { + get; + set; + } + + public virtual string PrimeiroTelefone + { + get; + set; + } + + public virtual string QuantidadeFiliais + { + get; + set; + } + + public virtual long QuantidadeFuncionarios + { + get; + set; + } + + public virtual string Responsavel + { + get; + set; + } + + public virtual string SegundoPrefixo + { + get; + set; + } + + public virtual string SegundoTelefone + { + get; + set; + } + + public virtual string SenhaAdmin + { + get; + set; + } + + public virtual string Serial + { + get; + set; + } + + public virtual string Site + { + get; + set; + } + + public virtual TipoTelefone? TipoTelefone1 + { + get; + set; + } + + public virtual TipoTelefone? TipoTelefone2 + { + get; + set; + } + + public virtual string Twitter + { + get; + set; + } + + public virtual string Whatsapp + { + get; + set; + } + + public virtual string WhatsappSinistro + { + get; + set; + } + + public EmpresaDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/IndiceArquivoDigitalDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/IndiceArquivoDigitalDb.cs new file mode 100644 index 0000000..fafb4aa --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/IndiceArquivoDigitalDb.cs @@ -0,0 +1,181 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Common +{ + public class IndiceArquivoDigitalDb : EntityBase + { + public virtual Guid? AzureGuid + { + get; + set; + } + + public virtual string AzureStorage + { + get; + set; + } + + public virtual string BD + { + get; + set; + } + + public virtual DateTime? DataAtualizacao + { + get; + set; + } + + public virtual DateTime? DataCriacao + { + get; + set; + } + + public virtual string Descricao + { + get; + set; + } + + public virtual bool Excluido + { + get; + set; + } + + public virtual string Extensao + { + get; + set; + } + + public virtual long IdArquivoDigital + { + get; + set; + } + + public virtual long IdCliente + { + get; + set; + } + + public virtual long IdDocumento + { + get; + set; + } + + public virtual long IdEmpresa + { + get; + set; + } + + public virtual long IdEstipulante + { + get; + set; + } + + public virtual long IdExtrato + { + get; + set; + } + + public virtual long IdFornecedor + { + get; + set; + } + + public virtual long IdItem + { + get; + set; + } + + public virtual long IdLancamento + { + get; + set; + } + + public virtual long IdNotaFiscal + { + get; + set; + } + + public virtual long IdParcela + { + get; + set; + } + + public virtual long IdProspeccao + { + get; + set; + } + + public virtual long IdSeguradora + { + get; + set; + } + + public virtual long IdSinistro + { + get; + set; + } + + public virtual long IdSocio + { + get; + set; + } + + public virtual long IdTarefa + { + get; + set; + } + + public virtual long IdUsuario + { + get; + set; + } + + public virtual long IdVendedor + { + get; + set; + } + + public virtual long UsuarioAtualizacao + { + get; + set; + } + + public virtual long UsuarioCriacao + { + get; + set; + } + + public IndiceArquivoDigitalDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/ModeloMalaDiretaDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/ModeloMalaDiretaDb.cs new file mode 100644 index 0000000..9e1eb04 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/ModeloMalaDiretaDb.cs @@ -0,0 +1,25 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Common +{ + public class ModeloMalaDiretaDb : EntityBase + { + public virtual string Assunto + { + get; + set; + } + + public virtual string Corpo + { + get; + set; + } + + public ModeloMalaDiretaDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/ProfissaoDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/ProfissaoDb.cs new file mode 100644 index 0000000..15d2d47 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/ProfissaoDb.cs @@ -0,0 +1,31 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Common +{ + public class ProfissaoDb : EntityBase + { + public virtual string Aniversario + { + get; + set; + } + + public virtual string Codigo + { + get; + set; + } + + public virtual string Nome + { + get; + set; + } + + public ProfissaoDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/RegistroAcaoDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/RegistroAcaoDb.cs new file mode 100644 index 0000000..edaece7 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/RegistroAcaoDb.cs @@ -0,0 +1,81 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Common +{ + public class RegistroAcaoDb : EntityBase + { + public virtual DateTime DataHora + { + get; + set; + } + + public virtual string Descricao + { + get; + set; + } + + public virtual long EntidadeId + { + get; + set; + } + + public virtual string Ip + { + get; + set; + } + + public virtual string NomeMaquina + { + get; + set; + } + + public virtual string Observacao + { + get; + set; + } + + public virtual Gestor.Model.Common.Relatorio? Relatorio + { + get; + set; + } + + public virtual TipoTela? Tela + { + get; + set; + } + + public virtual UsuarioDb Usuario + { + get; + set; + } + + public virtual string UsuarioMaquina + { + get; + set; + } + + public virtual string Versao + { + get; + set; + } + + public RegistroAcaoDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/RegistroLogDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/RegistroLogDb.cs new file mode 100644 index 0000000..97b1384 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/RegistroLogDb.cs @@ -0,0 +1,81 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Common +{ + public class RegistroLogDb : EntityBase + { + public virtual TipoAcao Acao + { + get; + set; + } + + public virtual DateTime DataHora + { + get; + set; + } + + public virtual string Descricao + { + get; + set; + } + + public virtual long EntidadeId + { + get; + set; + } + + public virtual string Ip + { + get; + set; + } + + public virtual bool ModeloNovo + { + get; + set; + } + + public virtual string NomeMaquina + { + get; + set; + } + + public virtual TipoTela Tela + { + get; + set; + } + + public virtual UsuarioDb Usuario + { + get; + set; + } + + public virtual string UsuarioMaquina + { + get; + set; + } + + public virtual string Versao + { + get; + set; + } + + public RegistroLogDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/SocioDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/SocioDb.cs new file mode 100644 index 0000000..8a5e7d2 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Common/SocioDb.cs @@ -0,0 +1,62 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Common +{ + public class SocioDb : EnderecoBase + { + private string _email; + + public virtual string Email + { + get + { + string str = this._email; + if (str != null) + { + return str.ToLower(); + } + return null; + } + set + { + this._email = value; + } + } + + public virtual bool Excluido + { + get; + set; + } + + public virtual long IdEmpresa + { + get; + set; + } + + public virtual string Nome + { + get; + set; + } + + public virtual string Prefixo + { + get; + set; + } + + public virtual string Telefone + { + get; + set; + } + + public SocioDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Configuracoes/ConfiguracaoSistemaDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Configuracoes/ConfiguracaoSistemaDb.cs new file mode 100644 index 0000000..5177d60 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Configuracoes/ConfiguracaoSistemaDb.cs @@ -0,0 +1,20 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Configuracoes +{ + public class ConfiguracaoSistemaDb : EntityBase + { + public virtual Gestor.Model.Common.Configuracao Configuracao + { + get; + set; + } + + public ConfiguracaoSistemaDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/AgendaDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/AgendaDb.cs new file mode 100644 index 0000000..2f0a9d7 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/AgendaDb.cs @@ -0,0 +1,67 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Ferramentas +{ + public class AgendaDb : EntityBase + { + public virtual string Bairro + { + get; + set; + } + + public virtual string Cep + { + get; + set; + } + + public virtual string Cidade + { + get; + set; + } + + public virtual string Complemento + { + get; + set; + } + + public virtual string Endereco + { + get; + set; + } + + public virtual string Estado + { + get; + set; + } + + public virtual string Nome + { + get; + set; + } + + public virtual string Numero + { + get; + set; + } + + public virtual string Observacao + { + get; + set; + } + + public AgendaDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/AgendaEmailDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/AgendaEmailDb.cs new file mode 100644 index 0000000..184e2eb --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/AgendaEmailDb.cs @@ -0,0 +1,19 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Ferramentas +{ + public class AgendaEmailDb : EmailBase + { + public virtual AgendaDb Agenda + { + get; + set; + } + + public AgendaEmailDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/AgendaTelefoneDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/AgendaTelefoneDb.cs new file mode 100644 index 0000000..0cd687f --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/AgendaTelefoneDb.cs @@ -0,0 +1,25 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Ferramentas +{ + public class AgendaTelefoneDb : TelefoneBase + { + public virtual AgendaDb Agenda + { + get; + set; + } + + public virtual string Observacao + { + get; + set; + } + + public AgendaTelefoneDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/CategoriaTarefaDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/CategoriaTarefaDb.cs new file mode 100644 index 0000000..ffc907e --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/CategoriaTarefaDb.cs @@ -0,0 +1,19 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Ferramentas +{ + public class CategoriaTarefaDb : EntityBase + { + public virtual string Descricao + { + get; + set; + } + + public CategoriaTarefaDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/CredencialDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/CredencialDb.cs new file mode 100644 index 0000000..d211925 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/CredencialDb.cs @@ -0,0 +1,104 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Ferramentas +{ + public class CredencialDb : EntityBase + { + public virtual string Assinatura + { + get; + set; + } + + public virtual string Cabecalho + { + get; + set; + } + + public virtual string Descricao + { + get; + set; + } + + public virtual string Dominio + { + get; + set; + } + + public virtual string Email + { + get; + set; + } + + public virtual bool Excluido + { + get; + set; + } + + public virtual string Header + { + get; + set; + } + + public virtual long IdEmpresa + { + get; + set; + } + + public virtual long IdUsuario + { + get; + set; + } + + public virtual int Porta + { + get; + set; + } + + public virtual string Replyto + { + get; + set; + } + + public virtual bool Seguro + { + get; + set; + } + + public virtual string Senha + { + get; + set; + } + + public virtual TipoEmail Tipo + { + get; + set; + } + + public virtual string Usuario + { + get; + set; + } + + public CredencialDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/FaseDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/FaseDb.cs new file mode 100644 index 0000000..732fdfc --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/FaseDb.cs @@ -0,0 +1,37 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Ferramentas +{ + public class FaseDb : EntityBase + { + public virtual string Descricao + { + get; + set; + } + + public virtual DateTime? Expiracao + { + get; + set; + } + + public virtual string Titulo + { + get; + set; + } + + public virtual TrilhaDb Trilha + { + get; + set; + } + + public FaseDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/ImpostoDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/ImpostoDb.cs new file mode 100644 index 0000000..cea3290 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/ImpostoDb.cs @@ -0,0 +1,56 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Ferramentas +{ + public class ImpostoDb : EntityBase + { + public virtual bool Ativo + { + get; + set; + } + + public virtual decimal Desconto + { + get; + set; + } + + public virtual decimal Ir + { + get; + set; + } + + public virtual decimal Iss + { + get; + set; + } + + public virtual decimal Outros + { + get; + set; + } + + public virtual RamoDb Ramo + { + get; + set; + } + + public virtual SeguradoraDb Seguradora + { + get; + set; + } + + public ImpostoDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/LogEmailDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/LogEmailDb.cs new file mode 100644 index 0000000..97e7735 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/LogEmailDb.cs @@ -0,0 +1,105 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Ferramentas +{ + public class LogEmailDb : EntityBase + { + public virtual string Anexos + { + get; + set; + } + + public virtual string Assunto + { + get; + set; + } + + public virtual string Cco + { + get; + set; + } + + public virtual string Corpo + { + get; + set; + } + + public virtual CredencialDb Credencial + { + get; + set; + } + + public virtual DateTime Data + { + get; + set; + } + + public virtual string Destinatarios + { + get; + set; + } + + public virtual long EntityId + { + get; + set; + } + + public virtual string Ip + { + get; + set; + } + + public virtual string NomeMaquina + { + get; + set; + } + + public virtual Gestor.Model.Common.Relatorio Relatorio + { + get; + set; + } + + public virtual TipoTela Tela + { + get; + set; + } + + public virtual UsuarioDb Usuario + { + get; + set; + } + + public virtual string UsuarioMaquina + { + get; + set; + } + + public virtual string Versao + { + get; + set; + } + + public LogEmailDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/NotaFiscalDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/NotaFiscalDb.cs new file mode 100644 index 0000000..0c5e593 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/NotaFiscalDb.cs @@ -0,0 +1,74 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Ferramentas +{ + public class NotaFiscalDb : EntityBase + { + public virtual DateTime? Data + { + get; + set; + } + + public virtual EstipulanteDb Estipulante + { + get; + set; + } + + public virtual string Extrato + { + get; + set; + } + + public virtual long? IdExtrato + { + get; + set; + } + + public virtual decimal Ir + { + get; + set; + } + + public virtual decimal Iss + { + get; + set; + } + + public virtual string Obs + { + get; + set; + } + + public virtual SeguradoraDb Seguradora + { + get; + set; + } + + public virtual decimal ValorBruto + { + get; + set; + } + + public virtual decimal ValorLiquido + { + get; + set; + } + + public NotaFiscalDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/OrigemClienteDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/OrigemClienteDb.cs new file mode 100644 index 0000000..eb5a9d2 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/OrigemClienteDb.cs @@ -0,0 +1,32 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Ferramentas +{ + public class OrigemClienteDb : EntityBase + { + public virtual ClienteDb Cliente + { + get; + set; + } + + public virtual string Nome + { + get; + set; + } + + public virtual long TipoOrigem + { + get; + set; + } + + public OrigemClienteDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/ReciboDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/ReciboDb.cs new file mode 100644 index 0000000..beebff1 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/ReciboDb.cs @@ -0,0 +1,68 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Ferramentas +{ + public class ReciboDb : EntityBase + { + public virtual DateTime? DataRecibo + { + get; + set; + } + + public virtual string DocumentoPagante + { + get; + set; + } + + public virtual string DocumentoRecebedor + { + get; + set; + } + + public virtual TipoPagamento? Pagamento + { + get; + set; + } + + public virtual string Pagante + { + get; + set; + } + + public virtual string Recebedor + { + get; + set; + } + + public virtual string Referente + { + get; + set; + } + + public virtual TipoRecibo? Tipo + { + get; + set; + } + + public virtual decimal Valor + { + get; + set; + } + + public ReciboDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/ResponsavelTarefaDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/ResponsavelTarefaDb.cs new file mode 100644 index 0000000..766eb0a --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/ResponsavelTarefaDb.cs @@ -0,0 +1,26 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Ferramentas +{ + public class ResponsavelTarefaDb : EntityBase + { + public virtual long IdTarefa + { + get; + set; + } + + public virtual UsuarioDb Usuario + { + get; + set; + } + + public ResponsavelTarefaDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/StatusDeProspeccaoDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/StatusDeProspeccaoDb.cs new file mode 100644 index 0000000..70f50d4 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/StatusDeProspeccaoDb.cs @@ -0,0 +1,37 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Ferramentas +{ + public class StatusDeProspeccaoDb : EntityBase + { + public virtual bool Ativo + { + get; + set; + } + + public virtual string Descricao + { + get; + set; + } + + public virtual bool Excluido + { + get; + set; + } + + public virtual string Nome + { + get; + set; + } + + public StatusDeProspeccaoDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/TarefaDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/TarefaDb.cs new file mode 100644 index 0000000..34906e7 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/TarefaDb.cs @@ -0,0 +1,123 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Ferramentas +{ + public class TarefaDb : EntityBase + { + public virtual DateTime Agendamento + { + get; + set; + } + + public virtual CategoriaTarefaDb Categoria + { + get; + set; + } + + public virtual string Cliente + { + get; + set; + } + + public virtual DateTime? Conclusao + { + get; + set; + } + + public virtual string Descricao + { + get; + set; + } + + public virtual string DescricaoInterna + { + get; + set; + } + + public virtual TipoTarefa Entidade + { + get; + set; + } + + public virtual FaseDb Fase + { + get; + set; + } + + public virtual long IdCliente + { + get; + set; + } + + public virtual long IdEntidade + { + get; + set; + } + + public virtual string Referencia + { + get; + set; + } + + public virtual bool? Restrito + { + get; + set; + } + + public virtual StatusTarefa Status + { + get; + set; + } + + public virtual TipoDeTarefaDb TipoDeTarefa + { + get; + set; + } + + public virtual string Titulo + { + get; + set; + } + + public virtual TrilhaDb Trilha + { + get; + set; + } + + public virtual UsuarioDb Usuario + { + get; + set; + } + + public virtual UsuarioDb UsuarioCadastro + { + get; + set; + } + + public TarefaDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/TipoDeTarefaDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/TipoDeTarefaDb.cs new file mode 100644 index 0000000..f6137ef --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/TipoDeTarefaDb.cs @@ -0,0 +1,37 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Ferramentas +{ + public class TipoDeTarefaDb : EntityBase + { + public virtual bool Ativo + { + get; + set; + } + + public virtual string Descricao + { + get; + set; + } + + public virtual bool Excluido + { + get; + set; + } + + public virtual string Nome + { + get; + set; + } + + public TipoDeTarefaDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/TrilhaDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/TrilhaDb.cs new file mode 100644 index 0000000..337dd61 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/TrilhaDb.cs @@ -0,0 +1,44 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Ferramentas +{ + public class TrilhaDb : EntityBase + { + public virtual bool Ativo + { + get; + set; + } + + public virtual string Descricao + { + get; + set; + } + + public virtual int Intervalo + { + get; + set; + } + + public virtual TipoTrilha Tipo + { + get; + set; + } + + public virtual string Titulo + { + get; + set; + } + + public TrilhaDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/VinculoRepasseDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/VinculoRepasseDb.cs new file mode 100644 index 0000000..883430e --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Ferramentas/VinculoRepasseDb.cs @@ -0,0 +1,38 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Ferramentas +{ + public class VinculoRepasseDb : EntityBase + { + public virtual long IdRepasse + { + get; + set; + } + + public virtual RepasseDb RepasseVinculo + { + get; + set; + } + + public virtual TipoVendedorDb TipoVendedor + { + get; + set; + } + + public virtual TipoVendedorDb TipoVendedorVinculo + { + get; + set; + } + + public VinculoRepasseDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Financeiro/BancosContasDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Financeiro/BancosContasDb.cs new file mode 100644 index 0000000..14b8314 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Financeiro/BancosContasDb.cs @@ -0,0 +1,56 @@ +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Financeiro +{ + public class BancosContasDb : EntityBase + { + public virtual string Agencia + { + get; + set; + } + + public virtual bool Ativo + { + get; + set; + } + + public virtual BancoDb Banco + { + get; + set; + } + + public virtual string Conta + { + get; + set; + } + + public virtual string Descricao + { + get; + set; + } + + public virtual long IdEmpresa + { + get; + set; + } + + public virtual string Observacao + { + get; + set; + } + + public BancosContasDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Financeiro/CentroDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Financeiro/CentroDb.cs new file mode 100644 index 0000000..0947564 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Financeiro/CentroDb.cs @@ -0,0 +1,31 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Financeiro +{ + public class CentroDb : EntityBase + { + public virtual bool Ativo + { + get; + set; + } + + public virtual string Descricao + { + get; + set; + } + + public virtual long IdEmpresa + { + get; + set; + } + + public CentroDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Financeiro/ControleFinanceiroDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Financeiro/ControleFinanceiroDb.cs new file mode 100644 index 0000000..1aeefbf --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Financeiro/ControleFinanceiroDb.cs @@ -0,0 +1,43 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Financeiro +{ + public class ControleFinanceiroDb : EntityBase + { + public virtual CentroDb Centro + { + get; + set; + } + + public virtual FornecedorDb Fornecedor + { + get; + set; + } + + public virtual string Historico + { + get; + set; + } + + public virtual int Parcelas + { + get; + set; + } + + public virtual PlanosDb Plano + { + get; + set; + } + + public ControleFinanceiroDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Financeiro/FornecedorDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Financeiro/FornecedorDb.cs new file mode 100644 index 0000000..bd1efaf --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Financeiro/FornecedorDb.cs @@ -0,0 +1,110 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Financeiro +{ + public class FornecedorDb : EnderecoBase + { + public virtual bool Ativo + { + get; + set; + } + + public virtual string Documento + { + get; + set; + } + + public virtual string Email + { + get; + set; + } + + public virtual long? IdCentro + { + get; + set; + } + + public virtual long? IdConta + { + get; + set; + } + + public virtual long IdEmpresa + { + get; + set; + } + + public virtual long? IdPlano + { + get; + set; + } + + public virtual string Nome + { + get; + set; + } + + public virtual string Observacao + { + get; + set; + } + + public virtual string Prefixo1 + { + get; + set; + } + + public virtual string Prefixo2 + { + get; + set; + } + + public virtual string Telefone1 + { + get; + set; + } + + public virtual string Telefone2 + { + get; + set; + } + + public virtual Gestor.Model.Common.TipoPagamento? TipoPagamento + { + get; + set; + } + + public virtual TipoTelefone? TipoTelefone1 + { + get; + set; + } + + public virtual TipoTelefone? TipoTelefone2 + { + get; + set; + } + + public FornecedorDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Financeiro/LancamentoDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Financeiro/LancamentoDb.cs new file mode 100644 index 0000000..3a86b17 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Financeiro/LancamentoDb.cs @@ -0,0 +1,116 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Financeiro +{ + public class LancamentoDb : EntityBase + { + public virtual DateTime? Baixa + { + get; + set; + } + + public virtual string CodigoBanco + { + get; + set; + } + + public virtual string Competencia + { + get; + set; + } + + public virtual string Complemento + { + get; + set; + } + + public virtual BancosContasDb Conta + { + get; + set; + } + + public virtual ControleFinanceiroDb Controle + { + get; + set; + } + + public virtual DateTime? DataLancamento + { + get; + set; + } + + public virtual string Documento + { + get; + set; + } + + public virtual string Historico + { + get; + set; + } + + public virtual string Observacao + { + get; + set; + } + + public virtual DateTime? Pagamento + { + get; + set; + } + + public virtual int Parcela + { + get; + set; + } + + public virtual Gestor.Model.Common.Sinal Sinal + { + get; + set; + } + + public virtual Gestor.Model.Common.TipoPagamento TipoPagamento + { + get; + set; + } + + public virtual decimal Valor + { + get; + set; + } + + public virtual decimal? ValorPago + { + get; + set; + } + + public virtual DateTime Vencimento + { + get; + set; + } + + public LancamentoDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Financeiro/PlanoDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Financeiro/PlanoDb.cs new file mode 100644 index 0000000..e53f981 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Financeiro/PlanoDb.cs @@ -0,0 +1,25 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Financeiro +{ + public class PlanoDb : EntityBase + { + public virtual bool Ativo + { + get; + set; + } + + public virtual string Descricao + { + get; + set; + } + + public PlanoDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Financeiro/PlanosDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Financeiro/PlanosDb.cs new file mode 100644 index 0000000..0bbdb29 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Financeiro/PlanosDb.cs @@ -0,0 +1,45 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Financeiro +{ + public class PlanosDb : EntityBase + { + public virtual bool Ativo + { + get; + set; + } + + public virtual string Descricao + { + get; + set; + } + + public virtual PlanoDb Plano + { + get; + set; + } + + public virtual Gestor.Model.Common.Sinal Sinal + { + get; + set; + } + + public virtual TipoContaDb TipoConta + { + get; + set; + } + + public PlanosDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Financeiro/SaldoDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Financeiro/SaldoDb.cs new file mode 100644 index 0000000..3b1b42f --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Financeiro/SaldoDb.cs @@ -0,0 +1,49 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Financeiro +{ + public class SaldoDb : EntityBase + { + public virtual BancosContasDb Conta + { + get; + set; + } + + public virtual DateTime? DataFinal + { + get; + set; + } + + public virtual DateTime DataInicio + { + get; + set; + } + + public virtual string Extrato + { + get; + set; + } + + public virtual decimal? ValorFinal + { + get; + set; + } + + public virtual decimal ValorInicio + { + get; + set; + } + + public SaldoDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Generic/EmailBase.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Generic/EmailBase.cs new file mode 100644 index 0000000..157621b --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Generic/EmailBase.cs @@ -0,0 +1,20 @@ +using Gestor.Model.Attributes; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Generic +{ + public class EmailBase : EntityBase + { + [ForceLog(true)] + public virtual string Email + { + get; + set; + } + + public EmailBase() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Generic/EnderecoBase.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Generic/EnderecoBase.cs new file mode 100644 index 0000000..4cab406 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Generic/EnderecoBase.cs @@ -0,0 +1,54 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Generic +{ + public class EnderecoBase : EntityBase + { + public virtual string Bairro + { + get; + set; + } + + public virtual string Cep + { + get; + set; + } + + public virtual string Cidade + { + get; + set; + } + + public virtual string Complemento + { + get; + set; + } + + public virtual string Endereco + { + get; + set; + } + + public virtual string Estado + { + get; + set; + } + + public virtual string Numero + { + get; + set; + } + + public EnderecoBase() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Generic/EntityBase.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Generic/EntityBase.cs new file mode 100644 index 0000000..38b6909 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Generic/EntityBase.cs @@ -0,0 +1,18 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Generic +{ + public class EntityBase + { + public virtual long Id + { + get; + set; + } + + public EntityBase() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Generic/TelefoneBase.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Generic/TelefoneBase.cs new file mode 100644 index 0000000..d415272 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Generic/TelefoneBase.cs @@ -0,0 +1,31 @@ +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Generic +{ + public class TelefoneBase : EntityBase + { + public virtual string Numero + { + get; + set; + } + + public virtual string Prefixo + { + get; + set; + } + + public virtual TipoTelefone? Tipo + { + get; + set; + } + + public TelefoneBase() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Relatorios/ParametrosRelatorioDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Relatorios/ParametrosRelatorioDb.cs new file mode 100644 index 0000000..3523ba2 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Relatorios/ParametrosRelatorioDb.cs @@ -0,0 +1,56 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Relatorios +{ + public class ParametrosRelatorioDb : EntityBase + { + public virtual string Campo + { + get; + set; + } + + public virtual string Header + { + get; + set; + } + + public virtual long IdUsuario + { + get; + set; + } + + public virtual int Ordem + { + get; + set; + } + + public virtual Gestor.Model.Common.Relatorio Relatorio + { + get; + set; + } + + public virtual string Tipo + { + get; + set; + } + + public virtual int Width + { + get; + set; + } + + public ParametrosRelatorioDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Relatorios/ParametrosTotalizacaoDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Relatorios/ParametrosTotalizacaoDb.cs new file mode 100644 index 0000000..fb50590 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Relatorios/ParametrosTotalizacaoDb.cs @@ -0,0 +1,44 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Relatorios +{ + public class ParametrosTotalizacaoDb : EntityBase + { + public virtual bool Ativa + { + get; + set; + } + + public virtual string Campo + { + get; + set; + } + + public virtual string Header + { + get; + set; + } + + public virtual long IdUsuario + { + get; + set; + } + + public virtual Gestor.Model.Common.Relatorio Relatorio + { + get; + set; + } + + public ParametrosTotalizacaoDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/AdiantamentoDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/AdiantamentoDb.cs new file mode 100644 index 0000000..68ff3c5 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/AdiantamentoDb.cs @@ -0,0 +1,56 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class AdiantamentoDb : EntityBase + { + public virtual DateTime? Data + { + get; + set; + } + + public virtual string Historico + { + get; + set; + } + + public virtual DateTime? Pagamento + { + get; + set; + } + + public virtual bool Pago + { + get; + set; + } + + public virtual Gestor.Model.Common.TipoPagamento? TipoPagamento + { + get; + set; + } + + public virtual decimal Valor + { + get; + set; + } + + public virtual VendedorDb Vendedor + { + get; + set; + } + + public AdiantamentoDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/AeronauticoDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/AeronauticoDb.cs new file mode 100644 index 0000000..f42b908 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/AeronauticoDb.cs @@ -0,0 +1,110 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class AeronauticoDb : EntityBase + { + public virtual string Casco + { + get; + set; + } + + public virtual string Certificado + { + get; + set; + } + + public virtual int? Fabricacao + { + get; + set; + } + + public virtual string Fabricante + { + get; + set; + } + + public virtual ItemDb Item + { + get; + set; + } + + public virtual string MarinaAero + { + get; + set; + } + + public virtual string Modelo + { + get; + set; + } + + public virtual string Navegacao + { + get; + set; + } + + public virtual string Observacao + { + get; + set; + } + + public virtual int? Passageiros + { + get; + set; + } + + public virtual long? Peso + { + get; + set; + } + + public virtual string Prefixo + { + get; + set; + } + + public virtual string Serie + { + get; + set; + } + + public virtual TipoAeronautico Tipo + { + get; + set; + } + + public virtual int? Tripulantes + { + get; + set; + } + + public virtual DateTime? Vistoria + { + get; + set; + } + + public AeronauticoDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/AutoDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/AutoDb.cs new file mode 100644 index 0000000..a73e5bf --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/AutoDb.cs @@ -0,0 +1,218 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class AutoDb : EntityBase + { + public virtual string AnoFabricacao + { + get; + set; + } + + public virtual string AnoModelo + { + get; + set; + } + + public virtual bool? Blindagem + { + get; + set; + } + + public virtual int? Bonus + { + get; + set; + } + + public virtual string Capacidade + { + get; + set; + } + + public virtual Gestor.Model.Common.Categoria? Categoria + { + get; + set; + } + + public virtual string CepPernoite + { + get; + set; + } + + public virtual string Chassi + { + get; + set; + } + + public virtual string Ci + { + get; + set; + } + + public virtual Gestor.Model.Common.Combustivel? Combustivel + { + get; + set; + } + + public virtual ControleDb Controle + { + get; + set; + } + + public virtual Gestor.Model.Common.Cor? Cor + { + get; + set; + } + + public virtual Gestor.Model.Common.Correcao? Correcao + { + get; + set; + } + + public virtual DocumentoDb Documento + { + get; + set; + } + + public virtual FabricanteDb Fabricante + { + get; + set; + } + + public virtual bool? Financiado + { + get; + set; + } + + public virtual string Fipe + { + get; + set; + } + + public virtual Gestor.Model.Common.Isencao? Isencao + { + get; + set; + } + + public virtual ItemDb Item + { + get; + set; + } + + public virtual bool? KitGas + { + get; + set; + } + + public virtual string Modelo + { + get; + set; + } + + public virtual string Observacao + { + get; + set; + } + + public virtual bool? Pcd + { + get; + set; + } + + public virtual string Placa + { + get; + set; + } + + public virtual decimal PorcentagemReferencia + { + get; + set; + } + + public virtual string Portas + { + get; + set; + } + + public virtual Gestor.Model.Common.Rastreador Rastreador + { + get; + set; + } + + public virtual string RegiaoCirculacao + { + get; + set; + } + + public virtual string Renavam + { + get; + set; + } + + public virtual Gestor.Model.Common.TabelaReferencia? TabelaReferencia + { + get; + set; + } + + public virtual Gestor.Model.Common.TipoCobertura? TipoCobertura + { + get; + set; + } + + public virtual Gestor.Model.Common.UsoVeiculo? UsoVeiculo + { + get; + set; + } + + public virtual decimal ValorDeterminado + { + get; + set; + } + + public virtual bool? ZeroKm + { + get; + set; + } + + public AutoDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ClienteDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ClienteDb.cs new file mode 100644 index 0000000..be9b406 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ClienteDb.cs @@ -0,0 +1,213 @@ +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class ClienteDb : EntityBase + { + public virtual string Agencia + { + get; + set; + } + + public virtual AtividadeDb Atividade + { + get; + set; + } + + public virtual BancoDb Banco + { + get; + set; + } + + public virtual string Caepf + { + get; + set; + } + + public virtual string CategoriaHabilitacao + { + get; + set; + } + + public virtual string Cei + { + get; + set; + } + + public virtual DateTime? ClienteDesde + { + get; + set; + } + + public virtual string Conta + { + get; + set; + } + + public virtual string Documento + { + get; + set; + } + + public virtual TipoDocumento? DocumentoPrincipal + { + get; + set; + } + + public virtual string Emissor + { + get; + set; + } + + public virtual Gestor.Model.Common.EstadoCivil? EstadoCivil + { + get; + set; + } + + public virtual string EstadoEmissor + { + get; + set; + } + + public virtual bool EstaNaCentralSegurado + { + get; + set; + } + + public virtual bool Excluido + { + get; + set; + } + + public virtual DateTime? Expedicao + { + get; + set; + } + + public virtual bool Falecido + { + get; + set; + } + + public virtual string Habilitacao + { + get; + set; + } + + public virtual long IdEmpresa + { + get; + set; + } + + public virtual string Identidade + { + get; + set; + } + + public virtual bool? MalaDireta + { + get; + set; + } + + public virtual DateTime? Nascimento + { + get; + set; + } + + public virtual string Nome + { + get; + set; + } + + public virtual string NomeSocialRg + { + get; + set; + } + + public virtual string Observacao + { + get; + set; + } + + public virtual string Pasta + { + get; + set; + } + + public virtual DateTime? PrimeiraHabilitacao + { + get; + set; + } + + public virtual ProfissaoDb Profissao + { + get; + set; + } + + public virtual decimal RendaMensal + { + get; + set; + } + + public virtual string Rne + { + get; + set; + } + + public virtual Gestor.Model.Common.Sexo? Sexo + { + get; + set; + } + + public virtual string TipoConta + { + get; + set; + } + + public virtual DateTime? VencimentoHabilitacao + { + get; + set; + } + + public ClienteDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ClienteEmailDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ClienteEmailDb.cs new file mode 100644 index 0000000..d3d4ede --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ClienteEmailDb.cs @@ -0,0 +1,31 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class ClienteEmailDb : EmailBase + { + public virtual ClienteDb Cliente + { + get; + set; + } + + public virtual string Observacao + { + get; + set; + } + + public virtual int? Ordem + { + get; + set; + } + + public ClienteEmailDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ClienteEnderecoDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ClienteEnderecoDb.cs new file mode 100644 index 0000000..b4ad2c6 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ClienteEnderecoDb.cs @@ -0,0 +1,31 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class ClienteEnderecoDb : EnderecoBase + { + public virtual ClienteDb Cliente + { + get; + set; + } + + public virtual string Observacao + { + get; + set; + } + + public virtual int? Ordem + { + get; + set; + } + + public ClienteEnderecoDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ClienteTelefoneDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ClienteTelefoneDb.cs new file mode 100644 index 0000000..0a6ef64 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ClienteTelefoneDb.cs @@ -0,0 +1,31 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class ClienteTelefoneDb : TelefoneBase + { + public virtual ClienteDb Cliente + { + get; + set; + } + + public virtual string Observacao + { + get; + set; + } + + public virtual int? Ordem + { + get; + set; + } + + public ClienteTelefoneDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ClienteVinculoDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ClienteVinculoDb.cs new file mode 100644 index 0000000..638260a --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ClienteVinculoDb.cs @@ -0,0 +1,32 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class ClienteVinculoDb : EntityBase + { + public virtual ClienteDb Cliente1 + { + get; + set; + } + + public virtual ClienteDb Cliente2 + { + get; + set; + } + + public virtual ParentescoVinculo? Parentesco + { + get; + set; + } + + public ClienteVinculoDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/CoberturaDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/CoberturaDb.cs new file mode 100644 index 0000000..51bc57c --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/CoberturaDb.cs @@ -0,0 +1,49 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class CoberturaDb : EntityBase + { + public virtual CoberturaPadraoDb CoberturaPadrao + { + get; + set; + } + + public virtual decimal Franquia + { + get; + set; + } + + public virtual ItemDb Item + { + get; + set; + } + + public virtual decimal Lmi + { + get; + set; + } + + public virtual string Observacao + { + get; + set; + } + + public virtual decimal Premio + { + get; + set; + } + + public CoberturaDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/CoberturaGranizoDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/CoberturaGranizoDb.cs new file mode 100644 index 0000000..2a896d6 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/CoberturaGranizoDb.cs @@ -0,0 +1,61 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class CoberturaGranizoDb : EntityBase + { + public virtual decimal? Area + { + get; + set; + } + + public virtual GranizoDb Granizo + { + get; + set; + } + + public virtual decimal? Lmi + { + get; + set; + } + + public virtual DateTime? Plantio + { + get; + set; + } + + public virtual decimal? Premio + { + get; + set; + } + + public virtual decimal? Produtividade + { + get; + set; + } + + public virtual string Quadra + { + get; + set; + } + + public virtual string Variedade + { + get; + set; + } + + public CoberturaGranizoDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/CoberturaPadraoDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/CoberturaPadraoDb.cs new file mode 100644 index 0000000..96b4ff0 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/CoberturaPadraoDb.cs @@ -0,0 +1,31 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class CoberturaPadraoDb : EntityBase + { + public virtual string Descricao + { + get; + set; + } + + public virtual long IdRamo + { + get; + set; + } + + public virtual bool Padrao + { + get; + set; + } + + public CoberturaPadraoDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/CondicaoRepasseDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/CondicaoRepasseDb.cs new file mode 100644 index 0000000..5c6d533 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/CondicaoRepasseDb.cs @@ -0,0 +1,31 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class CondicaoRepasseDb : EntityBase + { + public virtual int Parcela + { + get; + set; + } + + public virtual RamoDb Ramo + { + get; + set; + } + + public virtual SeguradoraDb Seguradora + { + get; + set; + } + + public CondicaoRepasseDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ConfigExtratoImportDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ConfigExtratoImportDb.cs new file mode 100644 index 0000000..8e112b2 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ConfigExtratoImportDb.cs @@ -0,0 +1,37 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class ConfigExtratoImportDb : EntityBase + { + public virtual bool Ativo + { + get; + set; + } + + public virtual string Codigo + { + get; + set; + } + + public virtual string Descricao + { + get; + set; + } + + public virtual long IdSeguradora + { + get; + set; + } + + public ConfigExtratoImportDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ConsorcioDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ConsorcioDb.cs new file mode 100644 index 0000000..4ef1a68 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ConsorcioDb.cs @@ -0,0 +1,49 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class ConsorcioDb : EntityBase + { + public virtual string BensConsorcio + { + get; + set; + } + + public virtual string Cota + { + get; + set; + } + + public virtual string Grupo + { + get; + set; + } + + public virtual ItemDb Item + { + get; + set; + } + + public virtual string Observacao + { + get; + set; + } + + public virtual decimal? ValorCredito + { + get; + set; + } + + public ConsorcioDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ControleDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ControleDb.cs new file mode 100644 index 0000000..a13cb4f --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ControleDb.cs @@ -0,0 +1,62 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class ControleDb : EntityBase + { + public virtual string AssistenciaId + { + get; + set; + } + + public virtual ClienteDb Cliente + { + get; + set; + } + + public virtual IList Documentos + { + get; + set; + } + + public virtual long IdEmpresa + { + get; + set; + } + + public virtual ProdutoDb Produto + { + get; + set; + } + + public virtual RamoDb Ramo + { + get; + set; + } + + public virtual SeguradoraDb Seguradora + { + get; + set; + } + + public virtual SeguradoraDb SeguradoraAnterior + { + get; + set; + } + + public ControleDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ControleSinistroDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ControleSinistroDb.cs new file mode 100644 index 0000000..4f7da17 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ControleSinistroDb.cs @@ -0,0 +1,25 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class ControleSinistroDb : EntityBase + { + public virtual DateTime? DataSinistro + { + get; + set; + } + + public virtual ItemDb Item + { + get; + set; + } + + public ControleSinistroDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/CriticaApoliceDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/CriticaApoliceDb.cs new file mode 100644 index 0000000..527cf27 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/CriticaApoliceDb.cs @@ -0,0 +1,67 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class CriticaApoliceDb : EntityBase + { + public virtual bool? Aggilizador + { + get; + set; + } + + public virtual bool? Critica + { + get; + set; + } + + public virtual DateTime? DataCritica + { + get; + set; + } + + public virtual DateTime? DataImportacao + { + get; + set; + } + + public virtual DocumentoDb Documento + { + get; + set; + } + + public virtual string NaoEncontrados + { + get; + set; + } + + public virtual string Tipo + { + get; + set; + } + + public virtual long? UsuarioCritica + { + get; + set; + } + + public virtual UsuarioDb UsuarioImportacao + { + get; + set; + } + + public CriticaApoliceDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/DetalheExtratoDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/DetalheExtratoDb.cs new file mode 100644 index 0000000..c222240 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/DetalheExtratoDb.cs @@ -0,0 +1,110 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class DetalheExtratoDb : EntityBase + { + public virtual string Apolice + { + get; + set; + } + + public virtual string Cliente + { + get; + set; + } + + public virtual decimal? Comissao + { + get; + set; + } + + public virtual bool Corrigir + { + get; + set; + } + + public virtual DateTime? Credito + { + get; + set; + } + + public virtual long? Documento + { + get; + set; + } + + public virtual string Endosso + { + get; + set; + } + + public virtual ExtratoDb Extrato + { + get; + set; + } + + public virtual string Historico + { + get; + set; + } + + public virtual string NumeroParcela + { + get; + set; + } + + public virtual long? Parcela + { + get; + set; + } + + public virtual DateTime? Recebimento + { + get; + set; + } + + public virtual StatusParcela? Status + { + get; + set; + } + + public virtual Gestor.Model.Common.SubTipo? SubTipo + { + get; + set; + } + + public virtual decimal? Valor + { + get; + set; + } + + public virtual decimal? ValorComissao + { + get; + set; + } + + public DetalheExtratoDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/DocumentoDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/DocumentoDb.cs new file mode 100644 index 0000000..8951f31 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/DocumentoDb.cs @@ -0,0 +1,321 @@ +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class DocumentoDb : EntityBase + { + public virtual bool AdicionalComiss + { + get; + set; + } + + public virtual string Agencia + { + get; + set; + } + + public virtual string Apolice + { + get; + set; + } + + public virtual string ApoliceAnterior + { + get; + set; + } + + public virtual bool ApoliceConferida + { + get; + set; + } + + public virtual BancoDb Banco + { + get; + set; + } + + public virtual BandeiraCartao? Bandeira + { + get; + set; + } + + public virtual decimal Comissao + { + get; + set; + } + + public virtual decimal? ComissaoTotal + { + get; + set; + } + + public virtual string Conta + { + get; + set; + } + + public virtual ControleDb Controle + { + get; + set; + } + + public virtual decimal Custo + { + get; + set; + } + + public virtual DateTime? DataControle + { + get; + set; + } + + public virtual DateTime? DataCriacao + { + get; + set; + } + + public virtual decimal Diferenca + { + get; + set; + } + + public virtual DateTime? Emissao + { + get; + set; + } + + public virtual string Endosso + { + get; + set; + } + + public virtual EstipulanteDb Estipulante1 + { + get; + set; + } + + public virtual EstipulanteDb Estipulante2 + { + get; + set; + } + + public virtual EstipulanteDb Estipulante3 + { + get; + set; + } + + public virtual EstipulanteDb Estipulante4 + { + get; + set; + } + + public virtual EstipulanteDb Estipulante5 + { + get; + set; + } + + public virtual bool Excluido + { + get; + set; + } + + public virtual bool FinalVigencia + { + get; + set; + } + + public virtual Gestor.Model.Common.FormaPagamento? FormaPagamento + { + get; + set; + } + + public virtual decimal Iof + { + get; + set; + } + + public virtual Gestor.Model.Common.Negocio? Negocio + { + get; + set; + } + + public virtual Gestor.Model.Common.NegocioCorretora? NegocioCorretora + { + get; + set; + } + + public virtual string NomeProponente + { + get; + set; + } + + public virtual string NumeroCartao + { + get; + set; + } + + public virtual int NumeroParcelas + { + get; + set; + } + + public virtual string Observacao + { + get; + set; + } + + public virtual int Ordem + { + get; + set; + } + + public virtual string Pasta + { + get; + set; + } + + public virtual decimal PremioAdicional + { + get; + set; + } + + public virtual decimal PremioLiquido + { + get; + set; + } + + public virtual decimal PremioTotal + { + get; + set; + } + + public virtual string Proposta + { + get; + set; + } + + public virtual bool PropostaAssinada + { + get; + set; + } + + public virtual string PropostaEndosso + { + get; + set; + } + + public virtual DateTime? Remessa + { + get; + set; + } + + public virtual TipoSeguro Situacao + { + get; + set; + } + + public virtual TipoSeguro? SituacaoAnterior + { + get; + set; + } + + public virtual StatusDb Status + { + get; + set; + } + + public virtual int Tipo + { + get; + set; + } + + public virtual Gestor.Model.Common.TipoEndosso? TipoEndosso + { + get; + set; + } + + public virtual Gestor.Model.Common.TipoRecebimento? TipoRecebimento + { + get; + set; + } + + public virtual UsuarioDb UsuarioCriacao + { + get; + set; + } + + public virtual string VencimentoCartao + { + get; + set; + } + + public virtual DateTime Vigencia1 + { + get; + set; + } + + public virtual DateTime? Vigencia2 + { + get; + set; + } + + public DocumentoDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/EstipulanteDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/EstipulanteDb.cs new file mode 100644 index 0000000..3a4b427 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/EstipulanteDb.cs @@ -0,0 +1,86 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class EstipulanteDb : EnderecoBase + { + public virtual bool Ativo + { + get; + set; + } + + public virtual string Documento + { + get; + set; + } + + public virtual string Email + { + get; + set; + } + + public virtual long IdEmpresa + { + get; + set; + } + + public virtual string Nome + { + get; + set; + } + + public virtual string Observacao + { + get; + set; + } + + public virtual string PrimeiroPrefixo + { + get; + set; + } + + public virtual string PrimeiroTelefone + { + get; + set; + } + + public virtual TipoTelefone? PrimeiroTipo + { + get; + set; + } + + public virtual string SegundoPrefixo + { + get; + set; + } + + public virtual string SegundoTelefone + { + get; + set; + } + + public virtual TipoTelefone? SegundoTipo + { + get; + set; + } + + public EstipulanteDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ExpedicaoDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ExpedicaoDb.cs new file mode 100644 index 0000000..eb3c276 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ExpedicaoDb.cs @@ -0,0 +1,73 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class ExpedicaoDb : EntityBase + { + public virtual DocumentoDb Apolice + { + get; + set; + } + + public virtual DateTime? DataAlteracao + { + get; + set; + } + + public virtual DateTime? DataCriacao + { + get; + set; + } + + public virtual DateTime? DataEnvio + { + get; + set; + } + + public virtual DateTime? DataRecebimento + { + get; + set; + } + + public virtual string Destino + { + get; + set; + } + + public virtual string Documento + { + get; + set; + } + + public virtual string Responsavel + { + get; + set; + } + + public virtual long? UsuarioAlteracao + { + get; + set; + } + + public virtual long? UsuarioCriacao + { + get; + set; + } + + public ExpedicaoDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ExtratoDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ExtratoDb.cs new file mode 100644 index 0000000..525c4f4 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ExtratoDb.cs @@ -0,0 +1,98 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class ExtratoDb : EntityBase + { + public virtual decimal? Bruto + { + get; + set; + } + + public virtual DateTime? Data + { + get; + set; + } + + public virtual DateTime? DataCredito + { + get; + set; + } + + public virtual string Historico + { + get; + set; + } + + public virtual long IdEmpresa + { + get; + set; + } + + public virtual long IdUsuario + { + get; + set; + } + + public virtual decimal? Ir + { + get; + set; + } + + public virtual decimal? Iss + { + get; + set; + } + + public virtual decimal? Liquido + { + get; + set; + } + + public virtual string Numero + { + get; + set; + } + + public virtual string Observacao + { + get; + set; + } + + public virtual decimal? Outro + { + get; + set; + } + + public virtual SeguradoraDb Seguradora + { + get; + set; + } + + public virtual StatusExtrato Status + { + get; + set; + } + + public ExtratoDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/FabricanteDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/FabricanteDb.cs new file mode 100644 index 0000000..fe751e0 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/FabricanteDb.cs @@ -0,0 +1,24 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class FabricanteDb + { + public virtual string Descricao + { + get; + set; + } + + public virtual int Id + { + get; + set; + } + + public FabricanteDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/FaturaDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/FaturaDb.cs new file mode 100644 index 0000000..869f0e2 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/FaturaDb.cs @@ -0,0 +1,43 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class FaturaDb : EntityBase + { + public virtual DateTime? Emissao + { + get; + set; + } + + public virtual string Fatura + { + get; + set; + } + + public virtual ParcelaDb Parcela + { + get; + set; + } + + public virtual DateTime? VigenciaFinal + { + get; + set; + } + + public virtual DateTime? VigenciaInicial + { + get; + set; + } + + public FaturaDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/GranizoDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/GranizoDb.cs new file mode 100644 index 0000000..aafcb3f --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/GranizoDb.cs @@ -0,0 +1,55 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class GranizoDb : EnderecoBase + { + public virtual string Area + { + get; + set; + } + + public virtual string Cultura + { + get; + set; + } + + public virtual ItemDb Item + { + get; + set; + } + + public virtual string Observacao + { + get; + set; + } + + public virtual string Sitio + { + get; + set; + } + + public virtual decimal? SubsidioEstadual + { + get; + set; + } + + public virtual decimal? SubsidioFederal + { + get; + set; + } + + public GranizoDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ItemDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ItemDb.cs new file mode 100644 index 0000000..4fd0d56 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ItemDb.cs @@ -0,0 +1,105 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class ItemDb : EntityBase + { + public virtual bool Cancelado + { + get; + set; + } + + public virtual IList Coberturas + { + get; + set; + } + + public virtual string Descricao + { + get; + set; + } + + public virtual DocumentoDb Documento + { + get; + set; + } + + public virtual long? Endosso + { + get; + set; + } + + public virtual long? IdDocumentoCancelado + { + get; + set; + } + + public virtual string Observacao + { + get; + set; + } + + public virtual int Ordem + { + get; + set; + } + + public virtual bool Sinistrado + { + get; + set; + } + + public virtual IList Sinistros + { + get; + set; + } + + public virtual string Status + { + get; + set; + } + + public virtual string StatusInclusao + { + get; + set; + } + + public virtual long? Substituicao + { + get; + set; + } + + public virtual long? Substituido + { + get; + set; + } + + public virtual Gestor.Model.Common.TipoEndosso? TipoEndosso + { + get; + set; + } + + public ItemDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/MaisContatoDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/MaisContatoDb.cs new file mode 100644 index 0000000..f000db8 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/MaisContatoDb.cs @@ -0,0 +1,123 @@ +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class MaisContatoDb : EntityBase + { + public virtual string Agencia + { + get; + set; + } + + public virtual string Banco + { + get; + set; + } + + public virtual ClienteDb Cliente + { + get; + set; + } + + public virtual string Conta + { + get; + set; + } + + public virtual string Documento + { + get; + set; + } + + public virtual string Email + { + get; + set; + } + + public virtual bool Excluido + { + get; + set; + } + + public virtual DateTime? Expedicao + { + get; + set; + } + + public virtual string Habilitacao + { + get; + set; + } + + public virtual string Identidade + { + get; + set; + } + + public virtual DateTime? Nascimento + { + get; + set; + } + + public virtual string Nome + { + get; + set; + } + + public virtual Gestor.Model.Common.Parentesco? Parentesco + { + get; + set; + } + + public virtual string Prefixo + { + get; + set; + } + + public virtual DateTime? PrimeiraHabilitacao + { + get; + set; + } + + public virtual ProfissaoDb Profissao + { + get; + set; + } + + public virtual string Telefone + { + get; + set; + } + + public virtual TipoTelefone? Tipo + { + get; + set; + } + + public MaisContatoDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/MetaSeguradoraDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/MetaSeguradoraDb.cs new file mode 100644 index 0000000..d798d27 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/MetaSeguradoraDb.cs @@ -0,0 +1,56 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class MetaSeguradoraDb : EntityBase + { + public virtual long Ano + { + get; + set; + } + + public virtual long? IdAggilizador + { + get; + set; + } + + public virtual Gestor.Model.Common.Mes Mes + { + get; + set; + } + + public virtual bool Recorrente + { + get; + set; + } + + public virtual SeguradoraDb Seguradora + { + get; + set; + } + + public virtual int TipoCalculo + { + get; + set; + } + + public virtual decimal Valor + { + get; + set; + } + + public MetaSeguradoraDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/MetaVendedorDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/MetaVendedorDb.cs new file mode 100644 index 0000000..92be6d5 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/MetaVendedorDb.cs @@ -0,0 +1,38 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class MetaVendedorDb : EntityBase + { + public virtual long Ano + { + get; + set; + } + + public virtual Gestor.Model.Common.Mes Mes + { + get; + set; + } + + public virtual decimal Valor + { + get; + set; + } + + public virtual VendedorDb Vendedor + { + get; + set; + } + + public MetaVendedorDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ParceiroDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ParceiroDb.cs new file mode 100644 index 0000000..c09d537 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ParceiroDb.cs @@ -0,0 +1,128 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class ParceiroDb : EntityBase + { + public virtual string Bairro + { + get; + set; + } + + public virtual string Cep + { + get; + set; + } + + public virtual string Cgccpf + { + get; + set; + } + + public virtual string Cidade + { + get; + set; + } + + public virtual string Complemento + { + get; + set; + } + + public virtual string Contato + { + get; + set; + } + + public virtual string Ddd1 + { + get; + set; + } + + public virtual string Ddd2 + { + get; + set; + } + + public virtual string Ddd3 + { + get; + set; + } + + public virtual string Email + { + get; + set; + } + + public virtual string Endereco + { + get; + set; + } + + public virtual string Nome + { + get; + set; + } + + public virtual string Numero + { + get; + set; + } + + public virtual string Obs + { + get; + set; + } + + public virtual string Telefone1 + { + get; + set; + } + + public virtual string Telefone2 + { + get; + set; + } + + public virtual string Telefone3 + { + get; + set; + } + + public virtual Gestor.Model.Common.TipoPerda? TipoPerda + { + get; + set; + } + + public virtual string Uf + { + get; + set; + } + + public ParceiroDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ParcelaDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ParcelaDb.cs new file mode 100644 index 0000000..f56299f --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ParcelaDb.cs @@ -0,0 +1,212 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class ParcelaDb : EntityBase + { + public virtual decimal Comissao + { + get; + set; + } + + public virtual DateTime? DataControle + { + get; + set; + } + + public virtual DateTime? DataCredito + { + get; + set; + } + + public virtual DateTime? DataCriacao + { + get; + set; + } + + public virtual DateTime? DataQuitacao + { + get; + set; + } + + public virtual DateTime? DataRecebimento + { + get; + set; + } + + public virtual decimal Desconto + { + get; + set; + } + + public virtual DocumentoDb Documento + { + get; + set; + } + + public virtual DateTime? Emissao + { + get; + set; + } + + public virtual string Extrato + { + get; + set; + } + + public virtual string Fatura + { + get; + set; + } + + public virtual FaturaDb FaturaInfo + { + get; + set; + } + + public virtual long IdEmpresa + { + get; + set; + } + + public virtual long IdParcelaPendente + { + get; + set; + } + + public virtual decimal Irr + { + get; + set; + } + + public virtual decimal Iss + { + get; + set; + } + + public virtual int NumeroParcela + { + get; + set; + } + + public virtual string Observacao + { + get; + set; + } + + public virtual decimal Outros + { + get; + set; + } + + public virtual Gestor.Model.Common.StatusPagamento StatusPagamento + { + get; + set; + } + + public virtual Gestor.Model.Common.SubTipo SubTipo + { + get; + set; + } + + public virtual Gestor.Model.Common.TipoPagamento TipoPagamento + { + get; + set; + } + + public virtual long UsuarioCriacao + { + get; + set; + } + + public virtual decimal Valor + { + get; + set; + } + + public virtual decimal ValorComDesconto + { + get; + set; + } + + public virtual decimal ValorComissao + { + get; + set; + } + + public virtual decimal ValorExtrato + { + get; + set; + } + + public virtual decimal ValorLiquidoFatura + { + get; + set; + } + + public virtual decimal ValorPago + { + get; + set; + } + + public virtual decimal ValorRealizado + { + get; + set; + } + + public virtual DateTime Vencimento + { + get; + set; + } + + public virtual DateTime? VigenciaFinal + { + get; + set; + } + + public virtual DateTime? VigenciaIncial + { + get; + set; + } + + public ParcelaDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/PatrimonialDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/PatrimonialDb.cs new file mode 100644 index 0000000..aab77c1 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/PatrimonialDb.cs @@ -0,0 +1,140 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class PatrimonialDb : EnderecoBase + { + public virtual string Bens + { + get; + set; + } + + public virtual string Contato + { + get; + set; + } + + public virtual string CpfLocatario1 + { + get; + set; + } + + public virtual string CpfLocatario2 + { + get; + set; + } + + public virtual string CpfLocatario3 + { + get; + set; + } + + public virtual string Imobiliaria + { + get; + set; + } + + public virtual ItemDb Item + { + get; + set; + } + + public virtual string Locatario1 + { + get; + set; + } + + public virtual string Locatario2 + { + get; + set; + } + + public virtual string Locatario3 + { + get; + set; + } + + public virtual string Prefixo + { + get; + set; + } + + public virtual string PrefixoLocatario1 + { + get; + set; + } + + public virtual string PrefixoLocatario2 + { + get; + set; + } + + public virtual string PrefixoLocatario3 + { + get; + set; + } + + public virtual string Telefone + { + get; + set; + } + + public virtual string TelefoneLocatario1 + { + get; + set; + } + + public virtual string TelefoneLocatario2 + { + get; + set; + } + + public virtual string TelefoneLocatario3 + { + get; + set; + } + + public virtual TipoTelefone? Tipo + { + get; + set; + } + + public virtual Gestor.Model.Common.TipoMoradia? TipoMoradia + { + get; + set; + } + + public virtual Gestor.Model.Common.Utilizacao? Utilizacao + { + get; + set; + } + + public PatrimonialDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/PerfilCondominioDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/PerfilCondominioDb.cs new file mode 100644 index 0000000..b51cd3e --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/PerfilCondominioDb.cs @@ -0,0 +1,11 @@ +using System; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class PerfilCondominioDb + { + public PerfilCondominioDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/PerfilDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/PerfilDb.cs new file mode 100644 index 0000000..7c3e96d --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/PerfilDb.cs @@ -0,0 +1,170 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class PerfilDb : EntityBase + { + public virtual Antifurto? AntiFurto + { + get; + set; + } + + public virtual string CepCirculacao + { + get; + set; + } + + public virtual string CepPernoite + { + get; + set; + } + + public virtual ClienteDb Cliente + { + get; + set; + } + + public virtual ControleDb Controle + { + get; + set; + } + + public virtual string Cpf + { + get; + set; + } + + public virtual DistanciaTrabalho? DistanciaResidenciaTrabalho + { + get; + set; + } + + public virtual Gestor.Model.Common.EstadoCivil? EstadoCivil + { + get; + set; + } + + public virtual bool? EstenderCobertura + { + get; + set; + } + + public virtual GaragemTrabalhoEstudo? GaragemEstudo + { + get; + set; + } + + public virtual Gestor.Model.Common.GaragemResidencia? GaragemResidencia + { + get; + set; + } + + public virtual GaragemTrabalhoEstudo? GaragemTrabalho + { + get; + set; + } + + public virtual string Habilitacao + { + get; + set; + } + + public virtual bool? Isencao + { + get; + set; + } + + public virtual string KmMensal + { + get; + set; + } + + public virtual DateTime? Nascimento + { + get; + set; + } + + public virtual string Nome + { + get; + set; + } + + public virtual Gestor.Model.Common.Ocupacao? Ocupacao + { + get; + set; + } + + public virtual Gestor.Model.Common.Relacao? Relacao + { + get; + set; + } + + public virtual bool? SeguroVida + { + get; + set; + } + + public virtual Gestor.Model.Common.Sexo? Sexo + { + get; + set; + } + + public virtual Gestor.Model.Common.TempoHabilitacao? TempoHabilitacao + { + get; + set; + } + + public virtual Gestor.Model.Common.TipoResidencia? TipoResidencia + { + get; + set; + } + + public virtual UsoDependetes? UsoDependentes + { + get; + set; + } + + public virtual bool? UsoProfissional + { + get; + set; + } + + public virtual int? VeiculoResidencia + { + get; + set; + } + + public PerfilDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/PerfilEmpresaDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/PerfilEmpresaDb.cs new file mode 100644 index 0000000..b5ba2ae --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/PerfilEmpresaDb.cs @@ -0,0 +1,116 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class PerfilEmpresaDb : EntityBase + { + public virtual DateTime? AnoConstrucao + { + get; + set; + } + + public virtual Gestor.Model.Common.AtividadeEmpresa? AtividadeEmpresa + { + get; + set; + } + + public virtual string AtividadePrincipal + { + get; + set; + } + + public virtual bool? CaixasEletronicos + { + get; + set; + } + + public virtual ClienteDb Cliente + { + get; + set; + } + + public virtual bool? ConstrucaoReforma + { + get; + set; + } + + public virtual ControleDb Controle + { + get; + set; + } + + public virtual bool? DivisaTerrenoBaldio + { + get; + set; + } + + public virtual string EquipamentoIncendio + { + get; + set; + } + + public virtual string EquipamentoSeguranca + { + get; + set; + } + + public virtual bool? ExclusivoDeposito + { + get; + set; + } + + public virtual bool? Isopainel + { + get; + set; + } + + public virtual Gestor.Model.Common.Localizacao? Localizacao + { + get; + set; + } + + public virtual bool? PatrimonioHistorio + { + get; + set; + } + + public virtual bool? PossuiTelhado + { + get; + set; + } + + public virtual Gestor.Model.Common.TipoConstrucao? TipoConstrucao + { + get; + set; + } + + public virtual TipoPavimentacao? TipoPavimento + { + get; + set; + } + + public PerfilEmpresaDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/PermissaoArquivoDigitalDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/PermissaoArquivoDigitalDb.cs new file mode 100644 index 0000000..43640ce --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/PermissaoArquivoDigitalDb.cs @@ -0,0 +1,44 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class PermissaoArquivoDigitalDb : EntityBase + { + public virtual bool Consultar + { + get; + set; + } + + public virtual bool Excluir + { + get; + set; + } + + public virtual bool Incluir + { + get; + set; + } + + public virtual TipoArquivoDigital Tela + { + get; + set; + } + + public virtual UsuarioDb Usuario + { + get; + set; + } + + public PermissaoArquivoDigitalDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/PermissaoUsuarioDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/PermissaoUsuarioDb.cs new file mode 100644 index 0000000..e4e8fe3 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/PermissaoUsuarioDb.cs @@ -0,0 +1,50 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class PermissaoUsuarioDb : EntityBase + { + public virtual bool Alterar + { + get; + set; + } + + public virtual bool Consultar + { + get; + set; + } + + public virtual bool Excluir + { + get; + set; + } + + public virtual bool Incluir + { + get; + set; + } + + public virtual TipoTela Tela + { + get; + set; + } + + public virtual UsuarioDb Usuario + { + get; + set; + } + + public PermissaoUsuarioDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ProdutoDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ProdutoDb.cs new file mode 100644 index 0000000..76309b3 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ProdutoDb.cs @@ -0,0 +1,25 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class ProdutoDb : EntityBase + { + public virtual bool Ativo + { + get; + set; + } + + public virtual string Nome + { + get; + set; + } + + public ProdutoDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ProspeccaoDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ProspeccaoDb.cs new file mode 100644 index 0000000..4aefc45 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ProspeccaoDb.cs @@ -0,0 +1,159 @@ +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class ProspeccaoDb : EntityBase + { + public virtual bool CriarTarefa + { + get; + set; + } + + public virtual DateTime? DataCriacao + { + get; + set; + } + + public virtual string Documento + { + get; + set; + } + + public virtual string Email + { + get; + set; + } + + public virtual long IdEmpresa + { + get; + set; + } + + public virtual string Item + { + get; + set; + } + + public virtual DateTime? Nascimento + { + get; + set; + } + + public virtual string Nome + { + get; + set; + } + + public virtual string Observacao + { + get; + set; + } + + public virtual string Prefixo1 + { + get; + set; + } + + public virtual string Prefixo2 + { + get; + set; + } + + public virtual ProdutoDb Produto + { + get; + set; + } + + public virtual RamoDb Ramo + { + get; + set; + } + + public virtual bool? Renovacao + { + get; + set; + } + + public virtual StatusProspeccao? Status + { + get; + set; + } + + public virtual StatusDeProspeccaoDb StatusPersonalizado + { + get; + set; + } + + public virtual TarefaDb Tarefa + { + get; + set; + } + + public virtual string Telefone1 + { + get; + set; + } + + public virtual string Telefone2 + { + get; + set; + } + + public virtual string Tipo + { + get; + set; + } + + public virtual long UsuarioCriacao + { + get; + set; + } + + public virtual decimal Valor + { + get; + set; + } + + public virtual VendedorDb Vendedor + { + get; + set; + } + + public virtual DateTime? VigenciaFinal + { + get; + set; + } + + public ProspeccaoDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/QualificacaoDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/QualificacaoDb.cs new file mode 100644 index 0000000..6c27053 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/QualificacaoDb.cs @@ -0,0 +1,67 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class QualificacaoDb : EntityBase + { + public virtual decimal Comissao1 + { + get; + set; + } + + public virtual decimal Comissao2 + { + get; + set; + } + + public virtual decimal Comissao3 + { + get; + set; + } + + public virtual decimal Liquido1 + { + get; + set; + } + + public virtual decimal Liquido2 + { + get; + set; + } + + public virtual decimal Liquido3 + { + get; + set; + } + + public virtual decimal Resultado1 + { + get; + set; + } + + public virtual decimal Resultado2 + { + get; + set; + } + + public virtual decimal Resultado3 + { + get; + set; + } + + public QualificacaoDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/RamoDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/RamoDb.cs new file mode 100644 index 0000000..c8727c0 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/RamoDb.cs @@ -0,0 +1,49 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class RamoDb : EntityBase + { + public virtual bool Ativo + { + get; + set; + } + + public virtual long CodigoSusep + { + get; + set; + } + + public virtual bool Fatura + { + get; + set; + } + + public virtual decimal Iof + { + get; + set; + } + + public virtual string Nome + { + get; + set; + } + + public virtual string RamoSusep + { + get; + set; + } + + public RamoDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/RepasseDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/RepasseDb.cs new file mode 100644 index 0000000..6ced2af --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/RepasseDb.cs @@ -0,0 +1,74 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class RepasseDb : EntityBase + { + public virtual bool Ativo + { + get; + set; + } + + public virtual BaseRepasse? Base + { + get; + set; + } + + public virtual FormaRepasse? Forma + { + get; + set; + } + + public virtual TipoIncidencia? Incidencia + { + get; + set; + } + + public virtual RamoDb Ramo + { + get; + set; + } + + public virtual long? Seguradora + { + get; + set; + } + + public virtual TipoRepasse? Tipo + { + get; + set; + } + + public virtual decimal ValorNovo + { + get; + set; + } + + public virtual decimal ValorRenovacao + { + get; + set; + } + + public virtual VendedorDb Vendedor + { + get; + set; + } + + public RepasseDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ResponsavelAssinaturaDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ResponsavelAssinaturaDb.cs new file mode 100644 index 0000000..b8b62aa --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/ResponsavelAssinaturaDb.cs @@ -0,0 +1,37 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class ResponsavelAssinaturaDb : EntityBase + { + public virtual string DocumentoResponsavel + { + get; + set; + } + + public virtual string EmailResponsavel + { + get; + set; + } + + public virtual long IdCliente + { + get; + set; + } + + public virtual string NomeResponsavel + { + get; + set; + } + + public ResponsavelAssinaturaDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/RestricaoUsuarioCamposRelatoriosDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/RestricaoUsuarioCamposRelatoriosDb.cs new file mode 100644 index 0000000..121eaca --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/RestricaoUsuarioCamposRelatoriosDb.cs @@ -0,0 +1,38 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class RestricaoUsuarioCamposRelatoriosDb : EntityBase + { + public virtual string Campo + { + get; + set; + } + + public virtual Gestor.Model.Common.Relatorio Relatorio + { + get; + set; + } + + public virtual bool Restricao + { + get; + set; + } + + public virtual UsuarioDb Usuario + { + get; + set; + } + + public RestricaoUsuarioCamposRelatoriosDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/RestricaoUsuarioDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/RestricaoUsuarioDb.cs new file mode 100644 index 0000000..2af302f --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/RestricaoUsuarioDb.cs @@ -0,0 +1,32 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class RestricaoUsuarioDb : EntityBase + { + public virtual bool Restricao + { + get; + set; + } + + public virtual TipoRestricao Tipo + { + get; + set; + } + + public virtual UsuarioDb Usuario + { + get; + set; + } + + public RestricaoUsuarioDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/RiscosDiversosDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/RiscosDiversosDb.cs new file mode 100644 index 0000000..7ef60c4 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/RiscosDiversosDb.cs @@ -0,0 +1,43 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class RiscosDiversosDb : EntityBase + { + public virtual string Area + { + get; + set; + } + + public virtual ItemDb Item + { + get; + set; + } + + public virtual string Observacao + { + get; + set; + } + + public virtual decimal? SubsidioEstadual + { + get; + set; + } + + public virtual decimal? SubsidioFederal + { + get; + set; + } + + public RiscosDiversosDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/SeguradoraContatoDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/SeguradoraContatoDb.cs new file mode 100644 index 0000000..9180362 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/SeguradoraContatoDb.cs @@ -0,0 +1,45 @@ +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class SeguradoraContatoDb : TelefoneBase + { + public virtual string Email + { + get; + set; + } + + public virtual EmpresaDb Empresa + { + get; + set; + } + + public virtual string NomeContato + { + get; + set; + } + + public virtual SeguradoraDb Seguradora + { + get; + set; + } + + public virtual TipoContatoSeguradora TipoContato + { + get; + set; + } + + public SeguradoraContatoDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/SeguradoraDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/SeguradoraDb.cs new file mode 100644 index 0000000..14a08cd --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/SeguradoraDb.cs @@ -0,0 +1,121 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class SeguradoraDb : EntityBase + { + public virtual string Assistencia + { + get; + set; + } + + public virtual bool Ativo + { + get; + set; + } + + public virtual string Codigo + { + get; + set; + } + + public virtual string CodigoSeguradora + { + get; + set; + } + + public virtual string CodigoSusep + { + get; + set; + } + + public virtual string CustomId + { + get; + set; + } + + public virtual string Documento + { + get; + set; + } + + public virtual long? IdAggilizador + { + get; + set; + } + + public virtual string LinkAppAndroid + { + get; + set; + } + + public virtual string LinkAppIos + { + get; + set; + } + + public virtual string Nome + { + get; + set; + } + + public virtual string NomeSocial + { + get; + set; + } + + public virtual string Observacao + { + get; + set; + } + + public virtual string Senha + { + get; + set; + } + + public virtual string Susep + { + get; + set; + } + + public virtual decimal? Tolerancia + { + get; + set; + } + + public virtual decimal? ToleranciaPremio + { + get; + set; + } + + public virtual string Usuario + { + get; + set; + } + + public SeguradoraDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/SeguradoraEnderecoDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/SeguradoraEnderecoDb.cs new file mode 100644 index 0000000..cce706e --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/SeguradoraEnderecoDb.cs @@ -0,0 +1,33 @@ +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class SeguradoraEnderecoDb : EnderecoBase + { + public virtual EmpresaDb Empresa + { + get; + set; + } + + public virtual SeguradoraDb Seguradora + { + get; + set; + } + + public virtual TipoEndereco Tipo + { + get; + set; + } + + public SeguradoraEnderecoDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/SinistroAutoDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/SinistroAutoDb.cs new file mode 100644 index 0000000..fb54488 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/SinistroAutoDb.cs @@ -0,0 +1,110 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class SinistroAutoDb : EntityBase + { + public virtual string Cnh + { + get; + set; + } + + public virtual bool? Culpado + { + get; + set; + } + + public virtual string Ddd + { + get; + set; + } + + public virtual string Email + { + get; + set; + } + + public virtual string Endereco + { + get; + set; + } + + public virtual string Envolvido + { + get; + set; + } + + public virtual string Motorista + { + get; + set; + } + + public virtual string NumeroBo + { + get; + set; + } + + public virtual ParceiroDb ParceiroFunilaria + { + get; + set; + } + + public virtual ParceiroDb ParceiroMecanica + { + get; + set; + } + + public virtual SinistroDb Sinistro + { + get; + set; + } + + public virtual string Telefone + { + get; + set; + } + + public virtual Gestor.Model.Common.TipoPerda? TipoPerda + { + get; + set; + } + + public virtual DateTime? UltimoDocEnviado + { + get; + set; + } + + public virtual decimal ValorFunilaria + { + get; + set; + } + + public virtual decimal ValorMecanica + { + get; + set; + } + + public SinistroAutoDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/SinistroDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/SinistroDb.cs new file mode 100644 index 0000000..d6c3751 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/SinistroDb.cs @@ -0,0 +1,152 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class SinistroDb : EntityBase + { + public virtual string Auxiliar + { + get; + set; + } + + public virtual ControleSinistroDb ControleSinistro + { + get; + set; + } + + public virtual DateTime? DataAlteracao + { + get; + set; + } + + public virtual DateTime? DataCriacao + { + get; + set; + } + + public virtual DateTime? DataLiquidacao + { + get; + set; + } + + public virtual DateTime? DataReclamacao + { + get; + set; + } + + public virtual string Descricao + { + get; + set; + } + + public virtual long IdUsuarioAlteracao + { + get; + set; + } + + public virtual long IdUsuarioCriacao + { + get; + set; + } + + public virtual string ItemSinistrado + { + get; + set; + } + + public virtual string Motivo + { + get; + set; + } + + public virtual string Numero + { + get; + set; + } + + public virtual string Observacao + { + get; + set; + } + + public virtual string ObservacaoInterna + { + get; + set; + } + + public virtual string StatusPersonalizado + { + get; + set; + } + + public virtual Gestor.Model.Common.StatusSinistro? StatusSinistro + { + get; + set; + } + + public virtual Gestor.Model.Common.TipoSinistro? TipoSinistro + { + get; + set; + } + + public virtual decimal Valor + { + get; + set; + } + + public virtual decimal ValorFranquia + { + get; + set; + } + + public virtual decimal ValorLiberado + { + get; + set; + } + + public virtual decimal ValorOrcado + { + get; + set; + } + + public virtual decimal ValorPago + { + get; + set; + } + + public virtual decimal? ValorSalvado + { + get; + set; + } + + public SinistroDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/SinistroVidaDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/SinistroVidaDb.cs new file mode 100644 index 0000000..f45a07f --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/SinistroVidaDb.cs @@ -0,0 +1,56 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class SinistroVidaDb : EntityBase + { + public virtual bool? AuxFuneral + { + get; + set; + } + + public virtual string Beneficiario + { + get; + set; + } + + public virtual string CertObito + { + get; + set; + } + + public virtual Gestor.Model.Common.EstadoCivil? EstadoCivil + { + get; + set; + } + + public virtual string Observacao + { + get; + set; + } + + public virtual SinistroDb Sinistro + { + get; + set; + } + + public virtual Gestor.Model.Common.TipoPerda? TipoPerda + { + get; + set; + } + + public SinistroVidaDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/StatusDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/StatusDb.cs new file mode 100644 index 0000000..9236925 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/StatusDb.cs @@ -0,0 +1,25 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class StatusDb : EntityBase + { + public virtual bool Ativo + { + get; + set; + } + + public virtual string Nome + { + get; + set; + } + + public StatusDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/TipoContaDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/TipoContaDb.cs new file mode 100644 index 0000000..93ee688 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/TipoContaDb.cs @@ -0,0 +1,25 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class TipoContaDb : EntityBase + { + public virtual bool Ativo + { + get; + set; + } + + public virtual string Descricao + { + get; + set; + } + + public TipoContaDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/TipoVendedorDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/TipoVendedorDb.cs new file mode 100644 index 0000000..d306198 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/TipoVendedorDb.cs @@ -0,0 +1,25 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class TipoVendedorDb : EntityBase + { + public virtual bool? Ativo + { + get; + set; + } + + public virtual string Descricao + { + get; + set; + } + + public TipoVendedorDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/TitularesVidaDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/TitularesVidaDb.cs new file mode 100644 index 0000000..2ce50f7 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/TitularesVidaDb.cs @@ -0,0 +1,98 @@ +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class TitularesVidaDb : EntityBase + { + public virtual decimal? Capital + { + get; + set; + } + + public virtual string Codigo + { + get; + set; + } + + public virtual string Cpf + { + get; + set; + } + + public virtual TitularesVidaDb Dependente + { + get; + set; + } + + public virtual string Fatura + { + get; + set; + } + + public virtual DateTime? Fim + { + get; + set; + } + + public virtual long IdItem + { + get; + set; + } + + public virtual DateTime Inicio + { + get; + set; + } + + public virtual string Matricula + { + get; + set; + } + + public virtual DateTime? Nascimento + { + get; + set; + } + + public virtual string Nome + { + get; + set; + } + + public virtual string Observacao + { + get; + set; + } + + public virtual decimal? Premio + { + get; + set; + } + + public virtual TipoTitular Tipo + { + get; + set; + } + + public TitularesVidaDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/UsuarioDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/UsuarioDb.cs new file mode 100644 index 0000000..dca2f99 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/UsuarioDb.cs @@ -0,0 +1,267 @@ +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class UsuarioDb : EnderecoBase + { + public virtual bool? Administrador + { + get; + set; + } + + public virtual bool? AdministradorCentralSegurado + { + get; + set; + } + + public virtual string Agencia + { + get; + set; + } + + public virtual bool Aggilizador + { + get; + set; + } + + public virtual BancoDb Banco + { + get; + set; + } + + public virtual string Cargo + { + get; + set; + } + + public virtual string Conta + { + get; + set; + } + + public virtual bool? Dashboard + { + get; + set; + } + + public virtual string Documento + { + get; + set; + } + + public virtual bool? Domingo + { + get; + set; + } + + public virtual string Email + { + get; + set; + } + + public virtual string EstadoEmissor + { + get; + set; + } + + public virtual bool? Excluido + { + get; + set; + } + + public virtual DateTime? Expedicao + { + get; + set; + } + + public virtual TipoFiltroCliente? FiltroInicial + { + get; + set; + } + + public virtual DateTime? FimAcesso + { + get; + set; + } + + public virtual long IdEmpresa + { + get; + set; + } + + public virtual string Identidade + { + get; + set; + } + + public virtual DateTime? InicioAcesso + { + get; + set; + } + + public virtual string Login + { + get; + set; + } + + public virtual bool Mobile + { + get; + set; + } + + public virtual DateTime? Nascimento + { + get; + set; + } + + public virtual string Nome + { + get; + set; + } + + public virtual long? PermissaoAggilizador + { + get; + set; + } + + public virtual string Prefixo + { + get; + set; + } + + public virtual string Prefixo2 + { + get; + set; + } + + public virtual bool? Quarta + { + get; + set; + } + + public virtual bool? Quinta + { + get; + set; + } + + public virtual bool Resultados + { + get; + set; + } + + public virtual bool? Sabado + { + get; + set; + } + + public virtual bool? Segunda + { + get; + set; + } + + public virtual string Senha + { + get; + set; + } + + public virtual Gestor.Model.Common.Sexo Sexo + { + get; + set; + } + + public virtual bool? Sexta + { + get; + set; + } + + public virtual string SsoId + { + get; + set; + } + + public virtual TipoTelaInicial? TelaInicial + { + get; + set; + } + + public virtual string Telefone + { + get; + set; + } + + public virtual string Telefone2 + { + get; + set; + } + + public virtual bool? Terca + { + get; + set; + } + + public virtual Gestor.Model.Common.TipoTelefone? TipoTelefone + { + get; + set; + } + + public virtual Gestor.Model.Common.TipoTelefone? TipoTelefone2 + { + get; + set; + } + + public virtual string Visita + { + get; + set; + } + + public UsuarioDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/VendedorDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/VendedorDb.cs new file mode 100644 index 0000000..21714de --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/VendedorDb.cs @@ -0,0 +1,98 @@ +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class VendedorDb : EnderecoBase + { + public virtual string Agencia + { + get; + set; + } + + public virtual bool Ativo + { + get; + set; + } + + public virtual BancoDb Banco + { + get; + set; + } + + public virtual string Conta + { + get; + set; + } + + public virtual bool Corretora + { + get; + set; + } + + public virtual decimal? Desconto + { + get; + set; + } + + public virtual string Documento + { + get; + set; + } + + public virtual long IdEmpresa + { + get; + set; + } + + public virtual string Nome + { + get; + set; + } + + public virtual string Observacao + { + get; + set; + } + + public virtual int TipoConta + { + get; + set; + } + + public virtual int TipoIncidenciaDesconto + { + get; + set; + } + + public virtual string TitularConta + { + get; + set; + } + + public virtual string TitularDocumento + { + get; + set; + } + + public VendedorDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/VendedorParcelaDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/VendedorParcelaDb.cs new file mode 100644 index 0000000..db81367 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/VendedorParcelaDb.cs @@ -0,0 +1,103 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class VendedorParcelaDb : EntityBase + { + public virtual bool? CoCorretagem + { + get; + set; + } + + public virtual CondicaoRepasseDb CondicaoRepasse + { + get; + set; + } + + public virtual DateTime? DataPagamento + { + get; + set; + } + + public virtual DateTime? DataPrePagamento + { + get; + set; + } + + public virtual DocumentoDb Documento + { + get; + set; + } + + public virtual ParcelaDb Parcela + { + get; + set; + } + + public virtual decimal? PorcentagemRepasse + { + get; + set; + } + + public virtual decimal? PorcentagemRepasseB + { + get; + set; + } + + public virtual RepasseDb Repasse + { + get; + set; + } + + public virtual TipoVendedorDb TipoVendedor + { + get; + set; + } + + public virtual decimal? ValorRepasse + { + get; + set; + } + + public virtual decimal? ValorRepasseB + { + get; + set; + } + + public virtual decimal? ValorTotal + { + get; + set; + } + + public virtual string VCondRep + { + get; + set; + } + + public virtual VendedorDb Vendedor + { + get; + set; + } + + public VendedorParcelaDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/VendedorTelefoneDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/VendedorTelefoneDb.cs new file mode 100644 index 0000000..29e0ecb --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/VendedorTelefoneDb.cs @@ -0,0 +1,31 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class VendedorTelefoneDb : TelefoneBase + { + public virtual string Email + { + get; + set; + } + + public virtual string Nome + { + get; + set; + } + + public virtual VendedorDb Vendedor + { + get; + set; + } + + public VendedorTelefoneDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/VendedorUsuarioDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/VendedorUsuarioDb.cs new file mode 100644 index 0000000..d4848ad --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/VendedorUsuarioDb.cs @@ -0,0 +1,25 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class VendedorUsuarioDb : EntityBase + { + public virtual UsuarioDb Usuario + { + get; + set; + } + + public virtual VendedorDb Vendedor + { + get; + set; + } + + public VendedorUsuarioDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/VidaDb.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/VidaDb.cs new file mode 100644 index 0000000..99353e8 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Entities.Seguros/VidaDb.cs @@ -0,0 +1,55 @@ +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Entities.Seguros +{ + public class VidaDb : EntityBase + { + public virtual decimal? CapitalFuncionarios + { + get; + set; + } + + public virtual decimal? CapitalSocios + { + get; + set; + } + + public virtual int? Funcionarios + { + get; + set; + } + + public virtual ItemDb Item + { + get; + set; + } + + public virtual string Observacao + { + get; + set; + } + + public virtual string Plano + { + get; + set; + } + + public virtual int? Socios + { + get; + set; + } + + public VidaDb() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Helpers/Auxiliar.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Helpers/Auxiliar.cs new file mode 100644 index 0000000..79dbd5f --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Helpers/Auxiliar.cs @@ -0,0 +1,2068 @@ +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Helpers +{ + public static class Auxiliar + { + public static List Banco + { + get; + set; + } + + public static List CategoriaTarefa + { + get; + set; + } + + public static List CoberturasPadrao + { + get; + set; + } + + public static List Empresas + { + get; + set; + } + + public static List Estipulantes + { + get; + set; + } + + public static List Parceiros + { + get; + set; + } + + public static List Produtos + { + get; + set; + } + + public static List Profissoes + { + get; + set; + } + + public static List Ramos + { + get; + set; + } + + public static List Repasses + { + get; + set; + } + + public static List Seguradoras + { + get; + set; + } + + public static List StatusApolice + { + get; + set; + } + + public static List StatusProspeccao + { + get; + set; + } + + public static List TiposTarefa + { + get; + set; + } + + public static List TipoVendedores + { + get; + set; + } + + public static List Usuarios + { + get; + set; + } + + public static List Vendedores + { + get; + set; + } + + public static void CriarAuxiliar(SqlCommand sqlCommand, bool force = false) + { + DataTable dataTable = new DataTable(); + if (force || Auxiliar.Empresas == null) + { + sqlCommand.CommandText = "SELECT DISTINCT idempresa as id, nome, NomeSocial, cgccpf FROM empresa;"; + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + Auxiliar.Empresas = new List(); + dataTable.AsEnumerable().ToList().ForEach((DataRow a) => Auxiliar.Empresas.Add(new Empresa() + { + Id = a.Field("id"), + Nome = a.Field("nome"), + NomeSocial = a.Field("NomeSocial") ?? a.Field("nome"), + Documento = a.Field("cgccpf") + })); + } + if (force || Auxiliar.Seguradoras == null) + { + Auxiliar.LoadSeguradoras(sqlCommand); + } + if (force || Auxiliar.Ramos == null) + { + dataTable = new DataTable(); + sqlCommand.CommandText = "SELECT DISTINCT idramo as id, nome, ativo, iof FROM ramo;"; + using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) + { + sqlDataAdapter1.SelectCommand = sqlCommand; + sqlDataAdapter1.Fill(dataTable); + } + Auxiliar.Ramos = new List(); + dataTable.AsEnumerable().ToList().ForEach((DataRow a) => Auxiliar.Ramos.Add(new Ramo() + { + Id = a.Field("id"), + Nome = a.Field("nome"), + Iof = a.Field("iof").GetValueOrDefault(), + Ativo = (a.Field("ativo") == null ? true : a.Field("ativo").ToString() == "1") + })); + } + if (force || Auxiliar.Banco == null) + { + dataTable = new DataTable(); + sqlCommand.CommandText = "SELECT DISTINCT IDCODIGOBANCO as id, NOMEBANCO as nome FROM codigobanco;"; + using (SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter()) + { + sqlDataAdapter2.SelectCommand = sqlCommand; + sqlDataAdapter2.Fill(dataTable); + } + Auxiliar.Banco = new List(); + dataTable.AsEnumerable().ToList().ForEach((DataRow a) => Auxiliar.Banco.Add(new Gestor.Model.Domain.Common.Banco() + { + Id = a.Field("id"), + Nome = a.Field("nome") + })); + } + dataTable = new DataTable(); + sqlCommand.CommandText = "SELECT DISTINCT idestipulante as id, nome, ativo FROM estipulante;"; + using (SqlDataAdapter sqlDataAdapter3 = new SqlDataAdapter()) + { + sqlDataAdapter3.SelectCommand = sqlCommand; + sqlDataAdapter3.Fill(dataTable); + } + Auxiliar.Estipulantes = new List(); + dataTable.AsEnumerable().ToList().ForEach((DataRow a) => Auxiliar.Estipulantes.Add(new Estipulante() + { + Id = a.Field("id"), + Nome = a.Field("nome"), + Ativo = (a.Field("ativo") == null ? true : a.Field("ativo").ToString() == "1") + })); + if (force || Auxiliar.Vendedores == null) + { + dataTable = new DataTable(); + sqlCommand.CommandText = "SELECT DISTINCT idvendedor as id, nome, cpfcnpj, corretora, tipoincidenciadesconto, desconto, ativo, idempresa, idcodigobanco, agencia, conta FROM vendedor;"; + using (SqlDataAdapter sqlDataAdapter4 = new SqlDataAdapter()) + { + sqlDataAdapter4.SelectCommand = sqlCommand; + sqlDataAdapter4.Fill(dataTable); + } + Auxiliar.Vendedores = new List(); + dataTable.AsEnumerable().ToList().ForEach((DataRow a) => Auxiliar.Vendedores.Add(new Vendedor() + { + IdEmpresa = a.Field("idempresa").GetValueOrDefault((long)1), + Id = a.Field("id"), + Nome = a.Field("nome"), + Documento = a.Field("cpfcnpj"), + Corretora = (string.IsNullOrEmpty(a.Field("corretora")) ? false : a.Field("corretora") == "1"), + TipoIncidenciaDesconto = (a.Field("tipoincidenciadesconto") == null ? TipoIncidenciaDesconto.Ambos : a.Field("tipoincidenciadesconto")), + Desconto = new decimal?((a.Field("desconto") == null ? decimal.Zero : a.Field("desconto") * new decimal(1, 0, 0, false, 2))), + Ativo = (a.Field("ativo") == null ? true : a.Field("ativo").ToString() == "1"), + Banco = (a.Field("idcodigobanco") == null ? null : Auxiliar.Banco.FirstOrDefault((Gestor.Model.Domain.Common.Banco p) => p.Id == a.Field("idcodigobanco"))), + Agencia = a.Field("agencia"), + Conta = a.Field("conta") + })); + } + if (force || Auxiliar.Repasses == null) + { + dataTable = new DataTable(); + sqlCommand.CommandText = "SELECT DISTINCT * FROM repasse;"; + using (SqlDataAdapter sqlDataAdapter5 = new SqlDataAdapter()) + { + sqlDataAdapter5.SelectCommand = sqlCommand; + sqlDataAdapter5.Fill(dataTable); + } + Auxiliar.Repasses = dataTable.AsEnumerable().Select((DataRow x) => { + Repasse repasse = new Repasse() + { + Id = x.Field("idrepasse"), + Vendedor = Auxiliar.Vendedores.Find((Vendedor v) => v.Id == x.Field("idvendedor")), + Ramo = (x.Field("idramo") != null ? Auxiliar.Ramos.Find((Ramo r) => r.Id == x.Field("idramo")) : null), + Ativo = (x.Field("ativo") == null ? true : x.Field("ativo").ToString() == "1"), + Tipo = (x.Field("tipo") != null ? new TipoRepasse?((TipoRepasse)int.Parse(x.Field("tipo").ToString())) : null), + Incidencia = (x.Field("incidencia") != null ? new TipoIncidencia?((TipoIncidencia)int.Parse(x.Field("incidencia").ToString())) : null), + Forma = (x.Field("forma") != null ? new FormaRepasse?((FormaRepasse)int.Parse(x.Field("forma").ToString())) : null), + Base = (x.Field("base") != null ? new BaseRepasse?((BaseRepasse)int.Parse(x.Field("base").ToString())) : null) + }; + decimal? nullable = x.Field("vlrnovo"); + repasse.ValorNovo = nullable.GetValueOrDefault(); + nullable = x.Field("vlrrenovacao"); + repasse.ValorRenovacao = nullable.GetValueOrDefault(); + return repasse; + }).ToList(); + } + if (force || Auxiliar.Produtos == null) + { + dataTable = new DataTable(); + sqlCommand.CommandText = "SELECT DISTINCT idproduto as id, nome, ativo FROM produto;"; + using (SqlDataAdapter sqlDataAdapter6 = new SqlDataAdapter()) + { + sqlDataAdapter6.SelectCommand = sqlCommand; + sqlDataAdapter6.Fill(dataTable); + } + Auxiliar.Produtos = new List(); + dataTable.AsEnumerable().OrderBy((DataRow x) => x.Field("nome")).ToList().ForEach((DataRow a) => Auxiliar.Produtos.Add(new Produto() + { + Id = a.Field("id"), + Nome = a.Field("nome"), + Ativo = a.Field("ativo").GetValueOrDefault(true) + })); + } + dataTable = new DataTable(); + sqlCommand.CommandText = "SELECT DISTINCT idstatus as id, nome, ativo FROM status;"; + using (SqlDataAdapter sqlDataAdapter7 = new SqlDataAdapter()) + { + sqlDataAdapter7.SelectCommand = sqlCommand; + sqlDataAdapter7.Fill(dataTable); + } + Auxiliar.StatusApolice = new List(); + dataTable.AsEnumerable().ToList().ForEach((DataRow a) => Auxiliar.StatusApolice.Add(new Status() + { + Id = a.Field("id"), + Nome = a.Field("nome"), + Ativo = a.Field("ativo").GetValueOrDefault(true) + })); + if (force || Auxiliar.TipoVendedores == null) + { + Auxiliar.LoadTipoVendedor(sqlCommand); + } + if (force || Auxiliar.Usuarios == null) + { + dataTable = new DataTable(); + sqlCommand.CommandText = "SELECT DISTINCT idusuario as id, idpermissao, nome, removido, inativo, idempresa, identif, Visita FROM usuario;"; + using (SqlDataAdapter sqlDataAdapter8 = new SqlDataAdapter()) + { + sqlDataAdapter8.SelectCommand = sqlCommand; + sqlDataAdapter8.Fill(dataTable); + } + Auxiliar.Usuarios = new List(); + dataTable.AsEnumerable().ToList().ForEach((DataRow a) => Auxiliar.Usuarios.Add(new Usuario() + { + IdEmpresa = a.Field("idempresa").GetValueOrDefault((long)1), + Id = a.Field("id"), + Nome = a.Field("nome"), + Login = a.Field("identif"), + Visita = a.Field("Visita"), + Excluido = a.Field("removido").GetValueOrDefault(), + PermissaoAggilizador = a.Field("idpermissao") + })); + } + if (force || Auxiliar.Parceiros == null) + { + dataTable = new DataTable(); + sqlCommand.CommandText = "SELECT DISTINCT idparceiro as id, nome FROM parceiro;"; + using (SqlDataAdapter sqlDataAdapter9 = new SqlDataAdapter()) + { + sqlDataAdapter9.SelectCommand = sqlCommand; + sqlDataAdapter9.Fill(dataTable); + } + Auxiliar.Parceiros = new List(); + dataTable.AsEnumerable().ToList().ForEach((DataRow a) => Auxiliar.Parceiros.Add(new Parceiro() + { + Id = a.Field("id"), + Nome = a.Field("nome") + })); + } + if (force || Auxiliar.Profissoes == null) + { + dataTable = new DataTable(); + sqlCommand.CommandText = "SELECT DISTINCT idprofissao AS id, nome FROM profissao;"; + using (SqlDataAdapter sqlDataAdapter10 = new SqlDataAdapter()) + { + sqlDataAdapter10.SelectCommand = sqlCommand; + sqlDataAdapter10.Fill(dataTable); + } + Auxiliar.Profissoes = new List(); + dataTable.AsEnumerable().ToList().ForEach((DataRow a) => Auxiliar.Profissoes.Add(new Profissao() + { + Id = a.Field("id"), + Nome = a.Field("nome") + })); + } + if (force || Auxiliar.TiposTarefa == null) + { + Auxiliar.LoadTipoTarefa(sqlCommand); + } + if (force || Auxiliar.StatusProspeccao == null) + { + dataTable = new DataTable(); + sqlCommand.CommandText = "SELECT * FROM StatusProspeccao;"; + using (SqlDataAdapter sqlDataAdapter11 = new SqlDataAdapter()) + { + sqlDataAdapter11.SelectCommand = sqlCommand; + sqlDataAdapter11.Fill(dataTable); + } + Auxiliar.StatusProspeccao = new List(); + dataTable.AsEnumerable().ToList().ForEach((DataRow a) => Auxiliar.StatusProspeccao.Add(new StatusDeProspeccao() + { + Id = a.Field("Id"), + Nome = a.Field("Nome"), + Descricao = a.Field("Descricao"), + Ativo = a.Field("Ativo"), + Excluido = a.Field("Excluido") + })); + } + if (force || Auxiliar.CategoriaTarefa == null) + { + dataTable = new DataTable(); + sqlCommand.CommandText = "SELECT * FROM CategoriaTarefa;"; + using (SqlDataAdapter sqlDataAdapter12 = new SqlDataAdapter()) + { + sqlDataAdapter12.SelectCommand = sqlCommand; + sqlDataAdapter12.Fill(dataTable); + } + Auxiliar.CategoriaTarefa = new List(); + dataTable.AsEnumerable().ToList().ForEach((DataRow a) => Auxiliar.CategoriaTarefa.Add(new Gestor.Model.Domain.Ferramentas.CategoriaTarefa() + { + Id = a.Field("Id"), + Descricao = a.Field("Descricao") + })); + } + if (force || Auxiliar.CoberturasPadrao == null) + { + dataTable = new DataTable(); + sqlCommand.CommandText = "SELECT * FROM coberturapadrao;"; + using (SqlDataAdapter sqlDataAdapter13 = new SqlDataAdapter()) + { + sqlDataAdapter13.SelectCommand = sqlCommand; + sqlDataAdapter13.Fill(dataTable); + } + Auxiliar.CoberturasPadrao = new List(); + dataTable.AsEnumerable().ToList().ForEach((DataRow a) => Auxiliar.CoberturasPadrao.Add(new CoberturaPadrao() + { + Id = a.Field("idcoberturapadrao"), + IdRamo = a.Field("idramo"), + Descricao = a.Field("Descricao"), + Padrao = a.Field("padrao") == "1" + })); + } + } + + public static void CriarAuxiliarUsuario(SqlCommand sqlCommand) + { + if (Auxiliar.Usuarios != null) + { + return; + } + DataTable dataTable = new DataTable(); + sqlCommand.CommandText = "SELECT DISTINCT idusuario as id, nome, idpermissao, removido, inativo, idempresa, identif, Visita FROM usuario;"; + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + Auxiliar.Usuarios = new List(); + dataTable.AsEnumerable().ToList().ForEach((DataRow a) => Auxiliar.Usuarios.Add(new Usuario() + { + IdEmpresa = a.Field("idempresa").GetValueOrDefault((long)1), + Id = a.Field("id"), + Nome = a.Field("nome"), + Login = a.Field("identif"), + Excluido = a.Field("removido").GetValueOrDefault(), + Visita = a.Field("Visita"), + PermissaoAggilizador = a.Field("idpermissao") + })); + } + + public static void CriarVendedor(SqlCommand sqlCommand, bool force = false) + { + DataTable dataTable = new DataTable(); + if (force || Auxiliar.Vendedores == null) + { + sqlCommand.CommandText = "SELECT DISTINCT idvendedor as id, nome, corretora, desconto, tipoincidenciadesconto, ativo, idempresa FROM vendedor;"; + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + Auxiliar.Vendedores = new List(); + dataTable.AsEnumerable().ToList().ForEach((DataRow a) => Auxiliar.Vendedores.Add(new Vendedor() + { + IdEmpresa = a.Field("idempresa").GetValueOrDefault((long)1), + Id = a.Field("id"), + Nome = a.Field("nome"), + Corretora = (string.IsNullOrEmpty(a.Field("corretora")) ? false : a.Field("corretora") == "1"), + Desconto = new decimal?((a.Field("desconto") == null ? decimal.Zero : a.Field("desconto") * new decimal(1, 0, 0, false, 2))), + TipoIncidenciaDesconto = (a.Field("tipoincidenciadesconto") == null ? TipoIncidenciaDesconto.Ambos : a.Field("tipoincidenciadesconto")), + Ativo = (a.Field("ativo") == null ? true : a.Field("ativo").ToString() == "1") + })); + } + if (force || Auxiliar.Ramos == null) + { + dataTable = new DataTable(); + sqlCommand.CommandText = "SELECT DISTINCT idramo as id, nome, ativo, iof FROM ramo;"; + using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) + { + sqlDataAdapter1.SelectCommand = sqlCommand; + sqlDataAdapter1.Fill(dataTable); + } + Auxiliar.Ramos = new List(); + dataTable.AsEnumerable().ToList().ForEach((DataRow a) => Auxiliar.Ramos.Add(new Ramo() + { + Id = a.Field("id"), + Nome = a.Field("nome"), + Iof = a.Field("iof").GetValueOrDefault(), + Ativo = (a.Field("ativo") == null ? true : a.Field("ativo").ToString() == "1") + })); + } + if (force || Auxiliar.Repasses == null) + { + dataTable = new DataTable(); + sqlCommand.CommandText = "SELECT DISTINCT * FROM repasse;"; + using (SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter()) + { + sqlDataAdapter2.SelectCommand = sqlCommand; + sqlDataAdapter2.Fill(dataTable); + } + Auxiliar.Repasses = dataTable.AsEnumerable().Select((DataRow x) => { + Repasse repasse = new Repasse() + { + Id = x.Field("idrepasse"), + Vendedor = Auxiliar.Vendedores.Find((Vendedor v) => v.Id == x.Field("idvendedor")), + Ramo = (x.Field("idramo") != null ? Auxiliar.Ramos.Find((Ramo r) => r.Id == x.Field("idramo")) : null), + Ativo = (x.Field("ativo") == null ? true : x.Field("ativo").ToString() == "1"), + Tipo = (x.Field("tipo") != null ? new TipoRepasse?((TipoRepasse)int.Parse(x.Field("tipo").ToString())) : null), + Incidencia = (x.Field("incidencia") != null ? new TipoIncidencia?((TipoIncidencia)int.Parse(x.Field("incidencia").ToString())) : null), + Forma = (x.Field("forma") != null ? new FormaRepasse?((FormaRepasse)int.Parse(x.Field("forma").ToString())) : null), + Base = (x.Field("base") != null ? new BaseRepasse?((BaseRepasse)int.Parse(x.Field("base").ToString())) : null) + }; + decimal? nullable = x.Field("vlrnovo"); + repasse.ValorNovo = nullable.GetValueOrDefault(); + nullable = x.Field("vlrrenovacao"); + repasse.ValorRenovacao = nullable.GetValueOrDefault(); + return repasse; + }).ToList(); + } + } + + public static void LoadSeguradoras(SqlCommand sqlCommand) + { + DataTable dataTable = new DataTable(); + sqlCommand.CommandText = "SELECT DISTINCT idciaseg as id, nome, nomesocial, tolerancia, ativo, id as idaggilizador, LinkAppAndroid, LinkAppIos, cgccpf FROM ciaseg;"; + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + Auxiliar.Seguradoras = new List(); + dataTable.AsEnumerable().ToList().ForEach((DataRow a) => { + long id; + Seguradora seguradora = new Seguradora() + { + Id = a.Field("id"), + Nome = a.Field("nome"), + NomeSocial = a.Field("nomesocial"), + Tolerancia = new decimal?((a.Field("tolerancia") == null ? decimal.Zero : Math.Abs(a.Field("tolerancia")))), + Ativo = (a.Field("ativo") == null ? true : a.Field("ativo").ToString() == "1"), + IdAggilizador = a.Field("idaggilizador"), + LinkAppAndroid = a.Field("LinkAppAndroid"), + LinkAppIos = a.Field("LinkAppIos"), + Documento = (a.Field("cgccpf") == null || a.Field("cgccpf") == "" ? "" : a.Field("cgccpf")) + }; + if (string.IsNullOrWhiteSpace(seguradora.NomeSocial)) + { + id = seguradora.Id; + if (id <= (long)694) + { + if (id <= (long)678) + { + long num = id - (long)1; + if (num <= (long)606) + { + switch ((uint)num) + { + case 0: + { + seguradora.NomeSocial = "ABSOLUTA"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 1: + case 2: + case 3: + case 4: + { + seguradora.NomeSocial = "ACE"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 5: + case 6: + case 7: + case 19: + case 20: + case 21: + case 22: + case 23: + case 28: + case 29: + case 30: + case 31: + case 35: + case 36: + case 37: + case 38: + case 42: + case 43: + case 44: + case 45: + case 46: + case 47: + case 49: + case 50: + case 51: + case 57: + case 58: + case 61: + case 62: + case 66: + case 67: + case 68: + case 70: + case 71: + case 72: + case 73: + case 74: + case 75: + case 76: + case 77: + case 78: + case 79: + case 80: + case 81: + case 82: + case 83: + case 84: + case 85: + case 86: + case 87: + case 97: + case 101: + case 102: + case 103: + case 104: + case 109: + case 110: + case 113: + case 114: + case 118: + case 121: + case 122: + case 123: + case 124: + case 127: + case 131: + case 132: + case 133: + case 134: + case 135: + case 136: + case 137: + case 138: + case 139: + case 140: + case 141: + case 142: + case 143: + case 146: + case 147: + case 148: + case 149: + case 150: + case 153: + case 154: + case 155: + case 156: + case 157: + case 158: + case 159: + case 162: + case 163: + case 164: + case 165: + case 166: + case 167: + case 168: + case 169: + case 170: + case 171: + case 172: + case 173: + case 174: + case 175: + case 179: + case 182: + case 183: + case 186: + case 187: + case 189: + case 190: + case 191: + case 192: + case 193: + case 194: + case 195: + case 198: + case 199: + case 202: + case 203: + case 204: + case 207: + case 208: + case 209: + case 210: + case 211: + case 214: + case 219: + case 220: + case 223: + case 224: + case 227: + case 228: + case 229: + case 233: + case 234: + case 237: + case 238: + case 239: + case 240: + case 244: + case 245: + case 246: + case 247: + case 250: + case 252: + case 253: + case 256: + case 261: + case 262: + case 263: + case 270: + case 276: + case 277: + case 278: + case 279: + case 280: + case 281: + case 282: + case 286: + case 287: + case 288: + case 300: + case 301: + case 302: + case 303: + case 304: + case 305: + case 306: + case 312: + case 313: + case 314: + case 315: + case 316: + case 329: + case 331: + case 332: + case 333: + case 334: + case 335: + case 338: + case 339: + case 341: + case 342: + case 343: + case 344: + case 350: + case 357: + case 358: + case 359: + case 360: + case 361: + case 362: + case 363: + case 366: + case 367: + case 368: + case 369: + case 370: + case 371: + case 373: + case 376: + case 377: + case 381: + case 382: + case 383: + case 388: + case 389: + case 390: + case 391: + case 392: + case 393: + case 396: + case 397: + case 402: + case 403: + case 404: + case 405: + case 406: + case 407: + case 408: + case 409: + case 410: + case 413: + case 414: + case 415: + case 419: + case 420: + case 421: + case 422: + case 425: + case 433: + case 434: + case 442: + case 443: + case 444: + case 451: + case 452: + case 453: + case 454: + case 457: + case 460: + case 461: + case 462: + case 463: + case 464: + case 467: + case 468: + case 469: + case 470: + case 472: + case 473: + case 488: + case 495: + case 496: + case 502: + case 504: + case 505: + case 506: + case 510: + case 511: + case 512: + case 519: + case 524: + case 525: + case 526: + case 529: + case 530: + case 531: + case 532: + case 533: + case 534: + case 535: + case 536: + case 552: + case 555: + case 562: + case 563: + case 564: + case 565: + case 566: + case 567: + case 568: + case 575: + case 576: + case 577: + case 578: + case 580: + case 585: + case 586: + case 587: + case 588: + case 589: + case 592: + case 596: + case 598: + case 599: + case 600: + case 601: + { + goto Label6; + } + case 8: + case 9: + case 517: + case 518: + { + seguradora.NomeSocial = "AIG"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 10: + { + seguradora.NomeSocial = "AJAX"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 11: + case 12: + case 13: + { + seguradora.NomeSocial = "ALFA"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 14: + case 15: + case 16: + case 176: + case 177: + { + seguradora.NomeSocial = "ALIANÇA"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 17: + case 18: + { + seguradora.NomeSocial = "ALLIANZ"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 24: + case 25: + case 26: + case 180: + { + seguradora.NomeSocial = "ALLSEG"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 27: + case 590: + case 591: + case 593: + { + seguradora.NomeSocial = "AMIL"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 32: + case 33: + case 34: + { + seguradora.NomeSocial = "APLUB"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 39: + case 40: + { + seguradora.NomeSocial = "ARCH"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 41: + { + seguradora.NomeSocial = "ARGO"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 48: + case 243: + { + seguradora.NomeSocial = "GENERALI"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 52: + case 53: + case 54: + case 55: + case 56: + { + seguradora.NomeSocial = "ATLANTICA"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 59: + case 60: + { + seguradora.NomeSocial = "AUSTRAL"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 63: + case 64: + case 65: + case 602: + { + seguradora.NomeSocial = "AXA"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 69: + { + seguradora.NomeSocial = "AZUL"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 88: + case 89: + case 90: + case 91: + case 92: + case 583: + { + seguradora.NomeSocial = "BRADESCO"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 93: + { + seguradora.NomeSocial = "BRASIL LIBANO"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 94: + { + seguradora.NomeSocial = "BRASILCAP"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 95: + case 96: + { + seguradora.NomeSocial = "BRASILPREV"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 98: + case 100: + { + seguradora.NomeSocial = "BRASILUSITANA"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 99: + { + seguradora.NomeSocial = "BRASIL VEÍCULOS"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 105: + case 106: + case 107: + case 108: + case 372: + { + seguradora.NomeSocial = "CAIXA"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 111: + case 112: + { + seguradora.NomeSocial = "CAPEMISA"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 115: + case 116: + case 117: + { + seguradora.NomeSocial = "CARDIF"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 119: + case 120: + { + seguradora.NomeSocial = "CASTELLO"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 125: + case 126: + { + seguradora.NomeSocial = "CESCEBRASIL"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 128: + case 129: + { + seguradora.NomeSocial = "CHARTIS"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 130: + { + seguradora.NomeSocial = "CHUBB"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 144: + case 184: + case 185: + { + seguradora.NomeSocial = "INTERNACIONAL"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 145: + case 289: + case 292: + case 293: + case 294: + { + seguradora.NomeSocial = "ITAÉ"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 151: + case 152: + case 188: + case 416: + case 417: + case 418: + { + seguradora.NomeSocial = "REAL"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 160: + case 161: + { + seguradora.NomeSocial = "URBANIA"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 178: + case 251: + { + seguradora.NomeSocial = "GRALHA AZUL"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 181: + { + seguradora.NomeSocial = "EXCELSIOR"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 196: + case 197: + { + seguradora.NomeSocial = "CREDITO Y CAUCIAN"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 200: + case 201: + { + seguradora.NomeSocial = "CRUZEIRO DO SUL"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 205: + case 206: + { + seguradora.NomeSocial = "ECC"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 212: + case 213: + { + seguradora.NomeSocial = "EQUITATIVA"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 215: + { + seguradora.NomeSocial = "ESSOR"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 216: + case 217: + case 218: + { + seguradora.NomeSocial = "EULER HERMES"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 221: + case 222: + { + seguradora.NomeSocial = "EVEREST"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 225: + case 226: + { + seguradora.NomeSocial = "FACTORY"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 230: + case 231: + case 232: + { + seguradora.NomeSocial = "FEDERAL"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 235: + case 236: + { + seguradora.NomeSocial = "FINANCIAL"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 241: + case 242: + { + seguradora.NomeSocial = "GENERAL"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 248: + case 249: + { + seguradora.NomeSocial = "GNPP"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 254: + case 255: + { + seguradora.NomeSocial = "HANNOVER"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 257: + case 258: + case 259: + case 260: + case 569: + case 597: + { + seguradora.NomeSocial = "HDI"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 264: + case 265: + case 266: + case 267: + case 268: + case 269: + { + seguradora.NomeSocial = "HSBC"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 271: + case 272: + { + seguradora.NomeSocial = "ICATU"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 273: + case 274: + { + seguradora.NomeSocial = "IF P&C INSURANCE"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 275: + { + seguradora.NomeSocial = "INDIANA"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 283: + case 284: + case 285: + case 603: + { + seguradora.NomeSocial = "KOVR"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 290: + case 291: + case 295: + case 296: + { + seguradora.NomeSocial = "ITAÚ"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 297: + case 298: + case 299: + { + seguradora.NomeSocial = "J. MALUCELLI"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 307: + case 308: + case 309: + { + seguradora.NomeSocial = "YELUM"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 310: + case 311: + { + seguradora.NomeSocial = "LIDERANÇA"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 317: + case 318: + case 319: + case 320: + case 321: + case 322: + case 323: + case 324: + case 325: + case 326: + case 327: + case 328: + { + seguradora.NomeSocial = "MAPFRE"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 330: + case 542: + case 561: + { + seguradora.NomeSocial = "YASUDA MARITIMA"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 336: + case 337: + { + seguradora.NomeSocial = "MBM"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 340: + { + seguradora.NomeSocial = "METLIFE"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 345: + case 346: + case 347: + { + seguradora.NomeSocial = "MITSUI"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 348: + case 349: + { + seguradora.NomeSocial = "MONGERAL"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 351: + case 352: + case 353: + case 354: + case 355: + case 356: + { + seguradora.NomeSocial = "MONTEPIO"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 364: + case 365: + case 380: + { + seguradora.NomeSocial = "NATIONAL"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 374: + case 375: + { + seguradora.NomeSocial = "NOVA YORK"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 378: + case 379: + { + seguradora.NomeSocial = "ODYSSEY"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 384: + case 385: + { + seguradora.NomeSocial = "PARANÁ"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 386: + case 387: + { + seguradora.NomeSocial = "PARIS"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 394: + case 395: + { + seguradora.NomeSocial = "PLANALTO"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 398: + case 399: + case 400: + case 401: + case 553: + case 554: + case 573: + { + seguradora.NomeSocial = "PORTO SEGURO"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 411: + case 412: + { + seguradora.NomeSocial = "PRUDENTIAL"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 423: + case 424: + { + seguradora.NomeSocial = "ROYAL & SUN ALLIANCE"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 426: + case 427: + case 428: + { + seguradora.NomeSocial = "SABEMI"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 429: + case 430: + case 431: + case 432: + { + seguradora.NomeSocial = "SAFRA"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 435: + case 436: + case 437: + { + seguradora.NomeSocial = "SANTANDER"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 438: + case 439: + { + seguradora.NomeSocial = "SANTOS"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 440: + case 441: + { + seguradora.NomeSocial = "SANTOS"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 445: + case 446: + case 447: + case 448: + { + seguradora.NomeSocial = "SCOR"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 449: + case 450: + { + seguradora.NomeSocial = "SDB"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 455: + case 456: + { + seguradora.NomeSocial = "MINEIRA"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 458: + case 459: + { + seguradora.NomeSocial = "PONTUAL"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 465: + case 466: + { + seguradora.NomeSocial = "SIRIUS"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 471: + case 594: + { + seguradora.NomeSocial = "SOMPO"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 474: + case 475: + case 476: + case 477: + case 478: + case 479: + case 480: + case 481: + case 482: + case 483: + case 484: + case 485: + case 486: + case 487: + case 557: + case 579: + { + seguradora.NomeSocial = "SULAMERICA"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 489: + case 490: + case 491: + case 492: + case 493: + case 494: + { + seguradora.NomeSocial = "SWISS"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 497: + case 498: + case 499: + case 500: + case 501: + { + seguradora.NomeSocial = "TOKIO"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 503: + { + seguradora.NomeSocial = "TOTAL"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 507: + case 508: + case 509: + { + seguradora.NomeSocial = "TREVO"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 513: + case 514: + case 515: + case 516: + { + seguradora.NomeSocial = "UNIÃO"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 520: + case 521: + case 584: + case 595: + { + seguradora.NomeSocial = "UNIMED"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 522: + case 523: + { + seguradora.NomeSocial = "UNIVERSAL"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 527: + case 528: + { + seguradora.NomeSocial = "VALOR CAPITALIZAÇÃO"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 537: + case 538: + case 539: + case 540: + case 541: + { + seguradora.NomeSocial = "XL"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 543: + case 544: + case 545: + case 546: + case 547: + case 548: + case 549: + case 550: + case 551: + { + seguradora.NomeSocial = "ZURICH"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 556: + { + seguradora.NomeSocial = "SUHAI"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 558: + { + seguradora.NomeSocial = "SANCOR"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 559: + { + seguradora.NomeSocial = "AGROBRASIL"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 560: + case 570: + { + seguradora.NomeSocial = "SURA"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 571: + case 572: + case 574: + case 605: + case 606: + { + seguradora.NomeSocial = "SÃO FRANCISCO"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 581: + { + seguradora.NomeSocial = "SANTA CASA"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 582: + { + seguradora.NomeSocial = "AMEX"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 604: + { + seguradora.NomeSocial = "BANCO DO BRASIL"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + } + } + else + { + } + long num1 = id - (long)621; + if (num1 <= (long)57) + { + switch ((uint)num1) + { + case 0: + case 3: + case 24: + case 32: + case 33: + case 34: + case 35: + case 36: + case 37: + case 41: + case 42: + { + seguradora.NomeSocial = "UNIMED"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 9: + case 18: + { + seguradora.NomeSocial = "ALIRO"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 10: + { + break; + } + case 11: + { + seguradora.NomeSocial = "VR"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 14: + { + seguradora.NomeSocial = "ALLIANZ"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 15: + { + seguradora.NomeSocial = "HS"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 20: + case 22: + case 53: + { + seguradora.NomeSocial = "PORTO SEGURO"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 21: + { + seguradora.NomeSocial = "SURA"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 28: + { + seguradora.NomeSocial = "AMIL"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 29: + { + seguradora.NomeSocial = "YELUM"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 43: + { + seguradora.NomeSocial = "SULAMERICA"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 45: + { + seguradora.NomeSocial = "AFFINITY"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 46: + { + seguradora.NomeSocial = "BR"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 52: + { + seguradora.NomeSocial = "YAMAHA"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 55: + { + seguradora.NomeSocial = "SÃO FRANCISCO"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 56: + { + seguradora.NomeSocial = "EMBRACON"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 57: + { + seguradora.NomeSocial = "MAPFRE"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + default: + { + goto Label6; + } + } + } + else + { + goto Label6; + } + seguradora.NomeSocial = "METLIFE"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + else if (id != (long)683) + { + long num2 = id - (long)687; + if (num2 <= (long)3) + { + switch ((uint)num2) + { + case 0: + { + seguradora.NomeSocial = "ITAÚ"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 1: + { + goto Label6; + } + case 2: + { + seguradora.NomeSocial = "SÃO LUCAS"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 3: + { + seguradora.NomeSocial = "UNIMED"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + } + } + else + { + } + if (id == (long)694) + { + seguradora.NomeSocial = "PORTO SEGURO"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + goto Label6; + } + else + { + seguradora.NomeSocial = "UNIMED"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + seguradora.NomeSocial = "PORTO SEGURO"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + else if (id > (long)716) + { + if (id == (long)717) + { + seguradora.NomeSocial = "CHUBB"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + if (id != (long)734) + { + goto Label5; + } + seguradora.NomeSocial = "RC"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + else + { + long num3 = id - (long)703; + if (num3 <= (long)8) + { + switch ((uint)num3) + { + case 0: + case 6: + { + seguradora.NomeSocial = "UNIMED"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 1: + case 4: + case 8: + { + seguradora.NomeSocial = "MAPFRE"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + case 2: + case 3: + case 5: + case 7: + { + goto Label6; + } + } + } + else + { + } + if (id == (long)716) + { + seguradora.NomeSocial = "UNIMED"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + } + Label6: + seguradora.NomeSocial = seguradora.Nome; + } + Auxiliar.Seguradoras.Add(seguradora); + return; + Label5: + if (id == (long)741) + { + seguradora.NomeSocial = "SOMPO"; + Auxiliar.Seguradoras.Add(seguradora); + return; + } + else + { + goto Label6; + } + }); + } + + public static void LoadTipoTarefa(SqlCommand sqlCommand) + { + DataTable dataTable = new DataTable(); + sqlCommand.CommandText = "SELECT * FROM TipoTarefa;"; + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + Auxiliar.TiposTarefa = new List(); + dataTable.AsEnumerable().ToList().ForEach((DataRow a) => Auxiliar.TiposTarefa.Add(new TipoDeTarefa() + { + Id = a.Field("Id"), + Nome = a.Field("Nome"), + Descricao = a.Field("Descricao"), + Ativo = a.Field("Ativo"), + Excluido = a.Field("Excluido") + })); + } + + public static void LoadTipoVendedor(SqlCommand sqlCommand) + { + DataTable dataTable = new DataTable(); + sqlCommand.CommandText = "SELECT DISTINCT idtipovendedor as id, descricao, ativo FROM tipovendedor;"; + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + Auxiliar.TipoVendedores = new List(); + dataTable.AsEnumerable().ToList().ForEach((DataRow a) => Auxiliar.TipoVendedores.Add(new TipoVendedor() + { + Id = a.Field("id"), + Descricao = a.Field("descricao"), + Ativo = new bool?(a.Field("ativo").GetValueOrDefault(true)) + })); + } + + public static List PesquisaAvancada(FiltroStatusDocumento status, DataTable documentos, DataTable itens, List controles) + { + DateTime date = Funcoes.GetNetworkTime().Date; + switch (status) + { + case FiltroStatusDocumento.Vencidos: + { + return documentos.AsEnumerable().Where((DataRow x) => { + if (controles == null || controles.Contains(x.Field("idcontrole")) && (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()) == TipoSeguro.Renovado) + { + return true; + } + return x.Field("vigencia2") < date.AddDays(-5); + }).Select((DataRow x) => new PesquisaAvancada() + { + IdCliente = x.Field("idcliente"), + IdDocumento = x.Field("iddocumento"), + IdItem = itens.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("iditem"), + Nome = x.Field("cliente"), + Pesquisa = (x.Field("tipo") == 0 ? string.Concat(new string[] { "ITEM: ", itens.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("descricao"), " - NÚMERO DA APÓLICE: ", x.Field("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field("proposta") }) : string.Concat(new string[] { "ITEM: ", itens.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("descricao"), " - NÚMERO DA APÓLICE: ", x.Field("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field("proposta"), " - NÚMERO DO ENDOSSO: ", x.Field("endosso") })) + }).ToList(); + } + case FiltroStatusDocumento.Cancelados: + { + return documentos.AsEnumerable().Where((DataRow x) => { + if (controles == null) + { + return true; + } + if (!controles.Contains(x.Field("idcontrole"))) + { + return false; + } + return (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()) == TipoSeguro.Cancelado; + }).Select((DataRow x) => new PesquisaAvancada() + { + IdCliente = x.Field("idcliente"), + IdDocumento = x.Field("iddocumento"), + IdItem = itens.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("iditem"), + Nome = x.Field("cliente"), + Pesquisa = (x.Field("tipo") == 0 ? string.Concat(new string[] { "ITEM: ", itens.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("descricao"), " - NÚMERO DA APÓLICE: ", x.Field("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field("proposta") }) : string.Concat(new string[] { "ITEM: ", itens.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("descricao"), " - NÚMERO DA APÓLICE: ", x.Field("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field("proposta"), " - NÚMERO DO ENDOSSO: ", x.Field("endosso") })) + }).ToList(); + } + case FiltroStatusDocumento.Recusados: + { + return documentos.AsEnumerable().Where((DataRow x) => { + if (controles == null) + { + return true; + } + if (!controles.Contains(x.Field("idcontrole"))) + { + return false; + } + return (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()) == TipoSeguro.Recusado; + }).Select((DataRow x) => new PesquisaAvancada() + { + IdCliente = x.Field("idcliente"), + IdDocumento = x.Field("iddocumento"), + IdItem = itens.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("iditem"), + Nome = x.Field("cliente"), + Pesquisa = (x.Field("tipo") == 0 ? string.Concat(new string[] { "ITEM: ", itens.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("descricao"), " - NÚMERO DA APÓLICE: ", x.Field("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field("proposta") }) : string.Concat(new string[] { "ITEM: ", itens.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("descricao"), " - NÚMERO DA APÓLICE: ", x.Field("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field("proposta"), " - NÚMERO DO ENDOSSO: ", x.Field("endosso") })) + }).ToList(); + } + case FiltroStatusDocumento.Todos: + { + return documentos.AsEnumerable().Where((DataRow x) => { + if (controles == null) + { + return true; + } + return controles.Contains(x.Field("idcontrole")); + }).Select((DataRow x) => new PesquisaAvancada() + { + IdCliente = x.Field("idcliente"), + IdDocumento = x.Field("iddocumento"), + IdItem = itens.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("iditem"), + Nome = x.Field("cliente"), + Pesquisa = (x.Field("tipo") == 0 ? string.Concat(new string[] { "ITEM: ", itens.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("descricao"), " - NÚMERO DA APÓLICE: ", x.Field("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field("proposta") }) : string.Concat(new string[] { "ITEM: ", itens.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("descricao"), " - NÚMERO DA APÓLICE: ", x.Field("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field("proposta"), " - NÚMERO DO ENDOSSO: ", x.Field("endosso") })) + }).ToList(); + } + default: + { + return documentos.AsEnumerable().Where((DataRow x) => { + if (controles == null) + { + return true; + } + if (!controles.Contains(x.Field("idcontrole")) || (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()) != TipoSeguro.Novo && (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()) != TipoSeguro.Renovacao) + { + return false; + } + return x.Field("vigencia2") >= date.AddDays(-5); + }).Select((DataRow x) => new PesquisaAvancada() + { + IdCliente = x.Field("idcliente"), + IdDocumento = x.Field("iddocumento"), + IdItem = itens.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("iditem"), + Nome = x.Field("cliente"), + Pesquisa = (x.Field("tipo") == 0 ? string.Concat(new string[] { "ITEM: ", itens.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("descricao"), " - NÚMERO DA APÓLICE: ", x.Field("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field("proposta") }) : string.Concat(new string[] { "ITEM: ", itens.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("descricao"), " - NÚMERO DA APÓLICE: ", x.Field("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field("proposta"), " - NÚMERO DO ENDOSSO: ", x.Field("endosso") })) + }).ToList(); + } + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Helpers/AuxiliarFinanceiro.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Helpers/AuxiliarFinanceiro.cs new file mode 100644 index 0000000..b9ecf17 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Helpers/AuxiliarFinanceiro.cs @@ -0,0 +1,127 @@ +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Helpers +{ + public static class AuxiliarFinanceiro + { + public static List Centros + { + get; + set; + } + + public static List Contas + { + get; + set; + } + + public static List Plano + { + get; + set; + } + + public static List Planos + { + get; + set; + } + + public static List TiposConta + { + get; + set; + } + + public static void Criar(SqlCommand sqlCommand) + { + DataTable dataTable = new DataTable(); + sqlCommand.CommandText = "SELECT DISTINCT idcplano as id, descricao as nome, ativo FROM cplano;"; + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + AuxiliarFinanceiro.Plano = new List(); + dataTable.AsEnumerable().ToList().ForEach((DataRow a) => AuxiliarFinanceiro.Plano.Add(new Gestor.Model.Domain.Financeiro.Plano() + { + Id = a.Field("id"), + Descricao = a.Field("nome"), + Ativo = (a.Field("ativo") == null ? true : a.Field("ativo").ToString() == "1") + })); + dataTable = new DataTable(); + sqlCommand.CommandText = "SELECT DISTINCT cs.idcplanos as id, cs.descricao as nome, cs.ativo, cs.idcplano, cp.descricao FROM cplanos cs INNER JOIN cplano cp ON cs.idcplano = cp.idcplano;"; + using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) + { + sqlDataAdapter1.SelectCommand = sqlCommand; + sqlDataAdapter1.Fill(dataTable); + } + AuxiliarFinanceiro.Planos = new List(); + dataTable.AsEnumerable().ToList().ForEach((DataRow a) => AuxiliarFinanceiro.Planos.Add(new Gestor.Model.Domain.Financeiro.Planos() + { + Id = a.Field("id"), + Descricao = a.Field("nome"), + Nome = a.Field("descricao"), + Ativo = (a.Field("ativo") == null ? true : a.Field("ativo").ToString() == "1"), + Plano = AuxiliarFinanceiro.Plano.FirstOrDefault((Gestor.Model.Domain.Financeiro.Plano x) => { + if (x == null) + { + return false; + } + return x.Id == a.Field("idcplano"); + }) + })); + dataTable = new DataTable(); + sqlCommand.CommandText = "SELECT DISTINCT idconta as id, descricao as nome, ativo FROM conta;"; + using (SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter()) + { + sqlDataAdapter2.SelectCommand = sqlCommand; + sqlDataAdapter2.Fill(dataTable); + } + AuxiliarFinanceiro.Contas = new List(); + dataTable.AsEnumerable().ToList().ForEach((DataRow a) => AuxiliarFinanceiro.Contas.Add(new BancosContas() + { + Id = a.Field("id"), + Descricao = a.Field("nome"), + Ativo = (a.Field("ativo") == null ? true : a.Field("ativo").ToString() == "1") + })); + dataTable = new DataTable(); + sqlCommand.CommandText = "SELECT DISTINCT idcentro as id, descricao as nome, ativo FROM centro;"; + using (SqlDataAdapter sqlDataAdapter3 = new SqlDataAdapter()) + { + sqlDataAdapter3.SelectCommand = sqlCommand; + sqlDataAdapter3.Fill(dataTable); + } + AuxiliarFinanceiro.Centros = new List(); + dataTable.AsEnumerable().ToList().ForEach((DataRow a) => AuxiliarFinanceiro.Centros.Add(new Centro() + { + Id = a.Field("id"), + Descricao = a.Field("nome"), + Ativo = (a.Field("ativo") == null ? true : a.Field("ativo").ToString() == "1") + })); + dataTable = new DataTable(); + sqlCommand.CommandText = "SELECT DISTINCT idtipoconta as id, descricao as nome, ativo FROM tipoconta;"; + using (SqlDataAdapter sqlDataAdapter4 = new SqlDataAdapter()) + { + sqlDataAdapter4.SelectCommand = sqlCommand; + sqlDataAdapter4.Fill(dataTable); + } + AuxiliarFinanceiro.TiposConta = new List(); + dataTable.AsEnumerable().ToList().ForEach((DataRow a) => AuxiliarFinanceiro.TiposConta.Add(new TipoConta() + { + Id = a.Field("id"), + Descricao = a.Field("nome"), + Ativo = (a.Field("ativo") == null ? true : a.Field("ativo").ToString() == "1") + })); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Helpers/Comparador.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Helpers/Comparador.cs new file mode 100644 index 0000000..9ce4873 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Helpers/Comparador.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Helpers +{ + public class Comparador : IEqualityComparer + { + private string Comparacao1 + { + get; + set; + } + + private string Comparacao2 + { + get; + set; + } + + public Comparador(string comparacao1 = "id", string comparacao2 = "id") + { + this.Comparacao1 = comparacao1; + this.Comparacao2 = comparacao2; + } + + public bool Equals(DataRow x, DataRow y) + { + return (long)x[this.Comparacao1] == (long)y[this.Comparacao2]; + } + + public int GetHashCode(DataRow obj) + { + return obj.ToString().GetHashCode(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Helpers/Funcoes.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Helpers/Funcoes.cs new file mode 100644 index 0000000..d3fdcde --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Helpers/Funcoes.cs @@ -0,0 +1,1403 @@ +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Validation; +using Microsoft.CSharp.RuntimeBinder; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using NHibernate.Util; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Diagnostics; +using System.Linq; +using System.Linq.Expressions; +using System.Net; +using System.Net.Sockets; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Helpers +{ + internal static class Funcoes + { + public static System.Diagnostics.Stopwatch Stopwatch; + + public static DateTime? StartTime; + + private static Dictionary TypeMap + { + get; + } + + static Funcoes() + { + Dictionary types = new Dictionary(); + types[typeof(string)] = SqlDbType.NVarChar; + types[typeof(char[])] = SqlDbType.NVarChar; + types[typeof(byte)] = SqlDbType.TinyInt; + types[typeof(short)] = SqlDbType.SmallInt; + types[typeof(int)] = SqlDbType.Int; + types[typeof(long)] = SqlDbType.BigInt; + types[typeof(long)] = SqlDbType.BigInt; + types[typeof(byte[])] = SqlDbType.Image; + types[typeof(bool)] = SqlDbType.Bit; + types[typeof(DateTime)] = SqlDbType.DateTime2; + types[typeof(DateTimeOffset)] = SqlDbType.DateTimeOffset; + types[typeof(decimal)] = SqlDbType.Money; + types[typeof(float)] = SqlDbType.Real; + types[typeof(double)] = SqlDbType.Float; + types[typeof(TimeSpan)] = SqlDbType.Time; + Gestor.Infrastructure.Helpers.Funcoes.TypeMap = types; + } + + public static T Campo(this DataRow row, string field) + { + string name; + bool isEnum; + string str; + object obj = row.Obj(field); + if (!typeof(T).IsNullable()) + { + if (typeof(T).IsEnum) + { + if (obj == null) + { + return (T)typeof(T).GetEnumValues().First(); + } + return (T)Enum.Parse(typeof(T), obj.ToString()); + } + name = typeof(T).Name; + if (name == "String") + { + if (obj == null) + { + return (T)""; + } + return (T)obj.ToString(); + } + if (name == "DateTime") + { + if (obj == null) + { + return (T)(object)DateTime.MinValue; + } + return (T)(object)DateTime.Parse(obj.ToString()); + } + if (name == "Decimal") + { + if (obj == null) + { + return (T)(object)0; + } + return (T)(object)decimal.Parse(obj.ToString()); + } + if (name == "Int64") + { + if (obj == null) + { + return (T)(object)0; + } + return (T)(object)long.Parse(obj.ToString()); + } + if (name != "Int") + { + return (T)null; + } + if (obj == null) + { + return (T)(object)0; + } + return (T)(object)int.Parse(obj.ToString()); + } + Type underlyingType = Nullable.GetUnderlyingType(typeof(T)); + if (underlyingType != null) + { + isEnum = underlyingType.IsEnum; + } + else + { + isEnum = false; + } + if (isEnum) + { + if (obj == null) + { + return (T)null; + } + return (T)Enum.Parse(typeof(T), obj.ToString()); + } + Type type = Nullable.GetUnderlyingType(typeof(T)); + if (type != null) + { + str = type.Name; + } + else + { + str = null; + } + name = str; + if (name == "String") + { + if (obj == null) + { + return (T)null; + } + return (T)obj.ToString(); + } + if (name == "DateTime") + { + if (obj == null) + { + return (T)null; + } + return (T)(object)DateTime.Parse(obj.ToString()); + } + if (name == "Decimal") + { + if (obj == null) + { + return (T)null; + } + return (T)(object)decimal.Parse(obj.ToString()); + } + if (name == "Int64") + { + if (obj == null) + { + return (T)null; + } + return (T)(object)long.Parse(obj.ToString()); + } + if (name != "Int") + { + return (T)null; + } + if (obj == null) + { + return (T)null; + } + return (T)(object)int.Parse(obj.ToString()); + } + + public static TipoTela? Convert(this string form) + { + TipoTela tipoTela; + TipoTela? nullable; + char chr; + if (string.IsNullOrWhiteSpace(form)) + { + nullable = null; + return nullable; + } + if (form.Contains("View") || form.Contains("Renovacao")) + { + nullable = null; + return nullable; + } + string lower = form.ToLower(); + if (lower != null) + { + switch (lower.Length) + { + case 7: + { + chr = lower[3]; + if (chr == 'N') + { + if (lower == "frmNota") + { + return new TipoTela?(TipoTela.NotaFiscal); + } + tipoTela = ((TipoTela[])Enum.GetValues(typeof(TipoTela))).ToList().FirstOrDefault((TipoTela x) => form.ToLower().Contains(x.ToString().ToLower())); + if (tipoTela != TipoTela.Todas) + { + return new TipoTela?(tipoTela); + } + nullable = null; + return nullable; + } + else if (chr == 'a') + { + if (lower == "frmauto") + { + break; + } + tipoTela = ((TipoTela[])Enum.GetValues(typeof(TipoTela))).ToList().FirstOrDefault((TipoTela x) => form.ToLower().Contains(x.ToString().ToLower())); + if (tipoTela != TipoTela.Todas) + { + return new TipoTela?(tipoTela); + } + nullable = null; + return nullable; + } + else + { + tipoTela = ((TipoTela[])Enum.GetValues(typeof(TipoTela))).ToList().FirstOrDefault((TipoTela x) => form.ToLower().Contains(x.ToString().ToLower())); + if (tipoTela != TipoTela.Todas) + { + return new TipoTela?(tipoTela); + } + nullable = null; + return nullable; + } + } + case 8: + case 9: + case 11: + case 15: + case 16: + case 19: + case 20: + { + tipoTela = ((TipoTela[])Enum.GetValues(typeof(TipoTela))).ToList().FirstOrDefault((TipoTela x) => form.ToLower().Contains(x.ToString().ToLower())); + if (tipoTela != TipoTela.Todas) + { + return new TipoTela?(tipoTela); + } + nullable = null; + return nullable; + } + case 10: + { + chr = lower[3]; + if (chr == 'e') + { + if (lower == "frmendosso") + { + return new TipoTela?(TipoTela.Apolice); + } + tipoTela = ((TipoTela[])Enum.GetValues(typeof(TipoTela))).ToList().FirstOrDefault((TipoTela x) => form.ToLower().Contains(x.ToString().ToLower())); + if (tipoTela != TipoTela.Todas) + { + return new TipoTela?(tipoTela); + } + nullable = null; + return nullable; + } + else if (chr == 'i') + { + if (lower == "frmitemman") + { + break; + } + tipoTela = ((TipoTela[])Enum.GetValues(typeof(TipoTela))).ToList().FirstOrDefault((TipoTela x) => form.ToLower().Contains(x.ToString().ToLower())); + if (tipoTela != TipoTela.Todas) + { + return new TipoTela?(tipoTela); + } + nullable = null; + return nullable; + } + else if (chr == 'p') + { + if (lower == "frmparcela") + { + return new TipoTela?(TipoTela.Parcela); + } + tipoTela = ((TipoTela[])Enum.GetValues(typeof(TipoTela))).ToList().FirstOrDefault((TipoTela x) => form.ToLower().Contains(x.ToString().ToLower())); + if (tipoTela != TipoTela.Todas) + { + return new TipoTela?(tipoTela); + } + nullable = null; + return nullable; + } + else + { + tipoTela = ((TipoTela[])Enum.GetValues(typeof(TipoTela))).ToList().FirstOrDefault((TipoTela x) => form.ToLower().Contains(x.ToString().ToLower())); + if (tipoTela != TipoTela.Todas) + { + return new TipoTela?(tipoTela); + } + nullable = null; + return nullable; + } + } + case 12: + { + chr = lower[3]; + if (chr == 'r') + { + if (lower == "frmrenovacao") + { + return new TipoTela?(TipoTela.Apolice); + } + tipoTela = ((TipoTela[])Enum.GetValues(typeof(TipoTela))).ToList().FirstOrDefault((TipoTela x) => form.ToLower().Contains(x.ToString().ToLower())); + if (tipoTela != TipoTela.Todas) + { + return new TipoTela?(tipoTela); + } + nullable = null; + return nullable; + } + else if (chr == 'v') + { + if (lower == "frmvidagrupo") + { + break; + } + tipoTela = ((TipoTela[])Enum.GetValues(typeof(TipoTela))).ToList().FirstOrDefault((TipoTela x) => form.ToLower().Contains(x.ToString().ToLower())); + if (tipoTela != TipoTela.Todas) + { + return new TipoTela?(tipoTela); + } + nullable = null; + return nullable; + } + else + { + tipoTela = ((TipoTela[])Enum.GetValues(typeof(TipoTela))).ToList().FirstOrDefault((TipoTela x) => form.ToLower().Contains(x.ToString().ToLower())); + if (tipoTela != TipoTela.Todas) + { + return new TipoTela?(tipoTela); + } + nullable = null; + return nullable; + } + } + case 13: + { + chr = lower[3]; + if (chr == 'c') + { + if (lower == "frmcriticapdf") + { + return new TipoTela?(TipoTela.CriticaApolice); + } + tipoTela = ((TipoTela[])Enum.GetValues(typeof(TipoTela))).ToList().FirstOrDefault((TipoTela x) => form.ToLower().Contains(x.ToString().ToLower())); + if (tipoTela != TipoTela.Todas) + { + return new TipoTela?(tipoTela); + } + nullable = null; + return nullable; + } + else + { + switch (chr) + { + case 'p': + { + if (lower == "frmparcelanew") + { + return new TipoTela?(TipoTela.Parcela); + } + tipoTela = ((TipoTela[])Enum.GetValues(typeof(TipoTela))).ToList().FirstOrDefault((TipoTela x) => form.ToLower().Contains(x.ToString().ToLower())); + if (tipoTela != TipoTela.Todas) + { + return new TipoTela?(tipoTela); + } + nullable = null; + return nullable; + } + case 'q': + case 's': + { + tipoTela = ((TipoTela[])Enum.GetValues(typeof(TipoTela))).ToList().FirstOrDefault((TipoTela x) => form.ToLower().Contains(x.ToString().ToLower())); + if (tipoTela != TipoTela.Todas) + { + return new TipoTela?(tipoTela); + } + nullable = null; + return nullable; + } + case 'r': + { + if (lower == "frmresidencia") + { + return new TipoTela?(TipoTela.Item); + } + tipoTela = ((TipoTela[])Enum.GetValues(typeof(TipoTela))).ToList().FirstOrDefault((TipoTela x) => form.ToLower().Contains(x.ToString().ToLower())); + if (tipoTela != TipoTela.Todas) + { + return new TipoTela?(tipoTela); + } + nullable = null; + return nullable; + } + case 't': + { + if (lower == "frmtransporte") + { + return new TipoTela?(TipoTela.Item); + } + tipoTela = ((TipoTela[])Enum.GetValues(typeof(TipoTela))).ToList().FirstOrDefault((TipoTela x) => form.ToLower().Contains(x.ToString().ToLower())); + if (tipoTela != TipoTela.Todas) + { + return new TipoTela?(tipoTela); + } + nullable = null; + return nullable; + } + default: + { + tipoTela = ((TipoTela[])Enum.GetValues(typeof(TipoTela))).ToList().FirstOrDefault((TipoTela x) => form.ToLower().Contains(x.ToString().ToLower())); + if (tipoTela != TipoTela.Todas) + { + return new TipoTela?(tipoTela); + } + nullable = null; + return nullable; + } + } + } + break; + } + case 14: + { + chr = lower[3]; + if (chr == 'a') + { + if (lower == "frmaeronautico") + { + break; + } + tipoTela = ((TipoTela[])Enum.GetValues(typeof(TipoTela))).ToList().FirstOrDefault((TipoTela x) => form.ToLower().Contains(x.ToString().ToLower())); + if (tipoTela != TipoTela.Todas) + { + return new TipoTela?(tipoTela); + } + nullable = null; + return nullable; + } + else if (chr == 'e') + { + if (lower == "frmeducacional") + { + break; + } + tipoTela = ((TipoTela[])Enum.GetValues(typeof(TipoTela))).ToList().FirstOrDefault((TipoTela x) => form.ToLower().Contains(x.ToString().ToLower())); + if (tipoTela != TipoTela.Todas) + { + return new TipoTela?(tipoTela); + } + nullable = null; + return nullable; + } + else + { + tipoTela = ((TipoTela[])Enum.GetValues(typeof(TipoTela))).ToList().FirstOrDefault((TipoTela x) => form.ToLower().Contains(x.ToString().ToLower())); + if (tipoTela != TipoTela.Todas) + { + return new TipoTela?(tipoTela); + } + nullable = null; + return nullable; + } + } + case 17: + { + chr = lower[3]; + if (chr == 'm') + { + if (lower == "frmmanutpagamento") + { + return new TipoTela?(TipoTela.ManutencaoPagamentos); + } + tipoTela = ((TipoTela[])Enum.GetValues(typeof(TipoTela))).ToList().FirstOrDefault((TipoTela x) => form.ToLower().Contains(x.ToString().ToLower())); + if (tipoTela != TipoTela.Todas) + { + return new TipoTela?(tipoTela); + } + nullable = null; + return nullable; + } + else if (chr == 'r') + { + if (lower == "frmriscosdiversos") + { + break; + } + tipoTela = ((TipoTela[])Enum.GetValues(typeof(TipoTela))).ToList().FirstOrDefault((TipoTela x) => form.ToLower().Contains(x.ToString().ToLower())); + if (tipoTela != TipoTela.Todas) + { + return new TipoTela?(tipoTela); + } + nullable = null; + return nullable; + } + else if (chr == 'v') + { + if (lower == "frmvidaindividual") + { + break; + } + tipoTela = ((TipoTela[])Enum.GetValues(typeof(TipoTela))).ToList().FirstOrDefault((TipoTela x) => form.ToLower().Contains(x.ToString().ToLower())); + if (tipoTela != TipoTela.Todas) + { + return new TipoTela?(tipoTela); + } + nullable = null; + return nullable; + } + else + { + tipoTela = ((TipoTela[])Enum.GetValues(typeof(TipoTela))).ToList().FirstOrDefault((TipoTela x) => form.ToLower().Contains(x.ToString().ToLower())); + if (tipoTela != TipoTela.Todas) + { + return new TipoTela?(tipoTela); + } + nullable = null; + return nullable; + } + } + case 18: + { + if (lower == "frmparcelascritica") + { + return new TipoTela?(TipoTela.Parcela); + } + tipoTela = ((TipoTela[])Enum.GetValues(typeof(TipoTela))).ToList().FirstOrDefault((TipoTela x) => form.ToLower().Contains(x.ToString().ToLower())); + if (tipoTela != TipoTela.Todas) + { + return new TipoTela?(tipoTela); + } + nullable = null; + return nullable; + } + case 21: + { + if (lower == "frmredirecionacritica") + { + return new TipoTela?(TipoTela.CriticaApolice); + } + tipoTela = ((TipoTela[])Enum.GetValues(typeof(TipoTela))).ToList().FirstOrDefault((TipoTela x) => form.ToLower().Contains(x.ToString().ToLower())); + if (tipoTela != TipoTela.Todas) + { + return new TipoTela?(tipoTela); + } + nullable = null; + return nullable; + } + default: + { + tipoTela = ((TipoTela[])Enum.GetValues(typeof(TipoTela))).ToList().FirstOrDefault((TipoTela x) => form.ToLower().Contains(x.ToString().ToLower())); + if (tipoTela != TipoTela.Todas) + { + return new TipoTela?(tipoTela); + } + nullable = null; + return nullable; + } + } + return new TipoTela?(TipoTela.Item); + } + tipoTela = ((TipoTela[])Enum.GetValues(typeof(TipoTela))).ToList().FirstOrDefault((TipoTela x) => form.ToLower().Contains(x.ToString().ToLower())); + if (tipoTela != TipoTela.Todas) + { + return new TipoTela?(tipoTela); + } + nullable = null; + return nullable; + } + + public static Relatorio? ConvertRelatorio(this string form) + { + Relatorio? nullable; + char chr; + if (string.IsNullOrWhiteSpace(form)) + { + nullable = null; + return nullable; + } + if (form != null) + { + int length = form.Length; + switch (length) + { + case 9: + { + if (form == "Renovacao") + { + break; + } + nullable = null; + return nullable; + } + case 10: + case 13: + case 16: + { + nullable = null; + return nullable; + } + case 11: + { + chr = form[3]; + if (chr == 'M') + { + if (form == "frmMetaView") + { + return new Relatorio?(Relatorio.MetaSeguradora); + } + nullable = null; + return nullable; + } + else if (chr == 'N') + { + if (form == "frmNotaView") + { + return new Relatorio?(Relatorio.NotaFiscal); + } + nullable = null; + return nullable; + } + else + { + nullable = null; + return nullable; + } + } + case 12: + { + if (form == "frmRenovacao") + { + break; + } + nullable = null; + return nullable; + } + case 14: + { + chr = form[3]; + if (chr == 'C') + { + if (form == "frmClienteView") + { + return new Relatorio?(Relatorio.Cliente); + } + nullable = null; + return nullable; + } + else if (chr == 'E') + { + if (form == "frmExtratoView") + { + return new Relatorio?(Relatorio.ExtratosBaixados); + } + nullable = null; + return nullable; + } + else + { + nullable = null; + return nullable; + } + } + case 15: + { + chr = form[3]; + if (chr == 'C') + { + if (form == "frmComissaoView") + { + return new Relatorio?(Relatorio.Comissao); + } + nullable = null; + return nullable; + } + else if (chr == 'P') + { + if (form == "frmProducaoView") + { + return new Relatorio?(Relatorio.Producao); + } + nullable = null; + return nullable; + } + else if (chr == 'S') + { + if (form == "frmSinistroView") + { + return new Relatorio?(Relatorio.Sinistro); + } + nullable = null; + return nullable; + } + else + { + nullable = null; + return nullable; + } + } + case 17: + { + chr = form[3]; + if (chr == 'F') + { + if (form == "frmFechamentoView") + { + return new Relatorio?(Relatorio.Fechamento); + } + nullable = null; + return nullable; + } + else if (chr == 'U') + { + if (form == "frmUtilizacaoView") + { + return new Relatorio?(Relatorio.LogsUtilizacao); + } + nullable = null; + return nullable; + } + else + { + nullable = null; + return nullable; + } + } + default: + { + if (length == 23) + { + if (form == "frmAgendaVencimentoView") + { + return new Relatorio?(Relatorio.Renovacao); + } + nullable = null; + return nullable; + } + else + { + nullable = null; + return nullable; + } + } + } + return new Relatorio?(Relatorio.Renovacao); + } + nullable = null; + return nullable; + } + + public static SqlQueryCondition CreateParameters(this List keyValues, int indexStart = 0) + { + if (keyValues == null) + { + return null; + } + List sqlParameters = new List(); + List strs2 = new List(); + int num = indexStart; + ( + from x in keyValues + orderby x.Grupo + group x by x.Grupo).ForEach>((IGrouping g) => { + List strs1 = new List(); + g.ForEach((Condicao x) => { + string str = string.Concat(x.Campo, " "); + List strs = new List(); + if (x.Valores != null) + { + List valores = x.Valores; + if (valores != null) + { + valores.ForEach((object v) => { + SqlParameter sqlParameter; + SqlParameter sqlParameter1; + if (Gestor.Infrastructure.Helpers.Funcoes.u003cu003eo__15.u003cu003ep__0 == null) + { + Gestor.Infrastructure.Helpers.Funcoes.u003cu003eo__15.u003cu003ep__0 = CallSite>.Create(Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(CSharpBinderFlags.None, "GetType", null, typeof(Gestor.Infrastructure.Helpers.Funcoes), (IEnumerable)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + object target = Gestor.Infrastructure.Helpers.Funcoes.u003cu003eo__15.u003cu003ep__0.Target(Gestor.Infrastructure.Helpers.Funcoes.u003cu003eo__15.u003cu003ep__0, v); + if (Gestor.Infrastructure.Helpers.Funcoes.u003cu003eo__15.u003cu003ep__2 == null) + { + Gestor.Infrastructure.Helpers.Funcoes.u003cu003eo__15.u003cu003ep__2 = CallSite>.Create(Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(CSharpBinderFlags.None, ExpressionType.IsTrue, typeof(Gestor.Infrastructure.Helpers.Funcoes), (IEnumerable)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + !0 _u00210 = Gestor.Infrastructure.Helpers.Funcoes.u003cu003eo__15.u003cu003ep__2.Target; + CallSite> u003cu003ep_2 = Gestor.Infrastructure.Helpers.Funcoes.u003cu003eo__15.u003cu003ep__2; + if (Gestor.Infrastructure.Helpers.Funcoes.u003cu003eo__15.u003cu003ep__1 == null) + { + Gestor.Infrastructure.Helpers.Funcoes.u003cu003eo__15.u003cu003ep__1 = CallSite>.Create(Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(CSharpBinderFlags.None, ExpressionType.Equal, typeof(Gestor.Infrastructure.Helpers.Funcoes), (IEnumerable)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType, null) }))); + } + if (_u00210(u003cu003ep_2, Gestor.Infrastructure.Helpers.Funcoes.u003cu003eo__15.u003cu003ep__1.Target(Gestor.Infrastructure.Helpers.Funcoes.u003cu003eo__15.u003cu003ep__1, target, typeof(string)))) + { + sqlParameter = new SqlParameter() + { + ParameterName = string.Format("@param_{0}", num) + }; + SqlParameter target1 = sqlParameter; + if (Gestor.Infrastructure.Helpers.Funcoes.u003cu003eo__15.u003cu003ep__4 == null) + { + Gestor.Infrastructure.Helpers.Funcoes.u003cu003eo__15.u003cu003ep__4 = CallSite>.Create(Microsoft.CSharp.RuntimeBinder.Binder.Convert(CSharpBinderFlags.None, typeof(SqlDbType), typeof(Gestor.Infrastructure.Helpers.Funcoes))); + } + !0 _u002101 = Gestor.Infrastructure.Helpers.Funcoes.u003cu003eo__15.u003cu003ep__4.Target; + CallSite> u003cu003ep_4 = Gestor.Infrastructure.Helpers.Funcoes.u003cu003eo__15.u003cu003ep__4; + if (Gestor.Infrastructure.Helpers.Funcoes.u003cu003eo__15.u003cu003ep__3 == null) + { + Gestor.Infrastructure.Helpers.Funcoes.u003cu003eo__15.u003cu003ep__3 = CallSite>.Create(Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(CSharpBinderFlags.None, "GetDbType", null, typeof(Gestor.Infrastructure.Helpers.Funcoes), (IEnumerable)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType | CSharpArgumentInfoFlags.IsStaticType, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + target1.SqlDbType = _u002101(u003cu003ep_4, Gestor.Infrastructure.Helpers.Funcoes.u003cu003eo__15.u003cu003ep__3.Target(Gestor.Infrastructure.Helpers.Funcoes.u003cu003eo__15.u003cu003ep__3, typeof(Gestor.Infrastructure.Helpers.Funcoes), target)); + sqlParameter.Size = 255; + sqlParameter.Value = (x.Operador == Operador.Like || x.Operador == Operador.NotLike ? string.Format("%{0}%", v) : (x.Operador == Operador.ComecaCom ? string.Format("{0}%", v) : (x.Operador == Operador.TerminaCom ? string.Format("%{0}", v) : v))); + sqlParameter1 = sqlParameter; + } + else + { + sqlParameter = new SqlParameter() + { + ParameterName = string.Format("@param_{0}", num) + }; + SqlParameter target2 = sqlParameter; + if (Gestor.Infrastructure.Helpers.Funcoes.u003cu003eo__15.u003cu003ep__6 == null) + { + Gestor.Infrastructure.Helpers.Funcoes.u003cu003eo__15.u003cu003ep__6 = CallSite>.Create(Microsoft.CSharp.RuntimeBinder.Binder.Convert(CSharpBinderFlags.None, typeof(SqlDbType), typeof(Gestor.Infrastructure.Helpers.Funcoes))); + } + !0 _u002102 = Gestor.Infrastructure.Helpers.Funcoes.u003cu003eo__15.u003cu003ep__6.Target; + CallSite> u003cu003ep_6 = Gestor.Infrastructure.Helpers.Funcoes.u003cu003eo__15.u003cu003ep__6; + if (Gestor.Infrastructure.Helpers.Funcoes.u003cu003eo__15.u003cu003ep__5 == null) + { + Gestor.Infrastructure.Helpers.Funcoes.u003cu003eo__15.u003cu003ep__5 = CallSite>.Create(Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(CSharpBinderFlags.None, "GetDbType", null, typeof(Gestor.Infrastructure.Helpers.Funcoes), (IEnumerable)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType | CSharpArgumentInfoFlags.IsStaticType, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + target2.SqlDbType = _u002102(u003cu003ep_6, Gestor.Infrastructure.Helpers.Funcoes.u003cu003eo__15.u003cu003ep__5.Target(Gestor.Infrastructure.Helpers.Funcoes.u003cu003eo__15.u003cu003ep__5, typeof(Gestor.Infrastructure.Helpers.Funcoes), target)); + sqlParameter.Value = v; + sqlParameter1 = sqlParameter; + } + SqlParameter sqlParameter2 = sqlParameter1; + sqlParameters.Add(sqlParameter2); + int cSu0024u003cu003e8_locals1 = num; + num = cSu0024u003cu003e8_locals1 + 1; + strs.Add(sqlParameter2.ParameterName); + }); + } + else + { + } + } + else + { + str = string.Concat(str, (x.Operador == Operador.Igual ? "IS NULL" : "IS NOT NULL")); + } + if (strs.Count == 1) + { + str = string.Concat(str, x.Operador.GetDescription(), " "); + str = string.Concat(str, strs.First()); + } + if (strs.Count > 1) + { + str = string.Concat(str, (x.Operador == Operador.Igual ? "IN" : (x.Operador == Operador.Diferente ? "NOT IN" : x.Operador.GetDescription())), " "); + str = string.Concat(str, "(", string.Join(",", strs), ")"); + } + strs1.Add(str); + }); + strs2.Add(string.Concat("(", string.Join(g.First().Operacao.GetDescription(), strs1), ")")); + }); + return new SqlQueryCondition() + { + Condicao = string.Join(" AND ", strs2), + Parametros = sqlParameters + }; + } + + public static DataTable CriarAuxiliar(this GenericUnitOfWork _unitOfWork) + { + DataTable dataTable; + object connection; + DataTable dataTable1 = new DataTable(); + SessionFactoryImpl sessionFactory = _unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + if (sqlConnection != null) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandTimeout = 15000; + Auxiliar.CriarAuxiliar(sqlCommand, true); + return dataTable1; + } + } + else + { + dataTable = null; + } + } + return dataTable; + } + + public static List CriarCondicao(this Filtros filtro, string referencia) + { + bool count; + bool flag; + bool count1; + bool flag1; + bool count2; + bool flag2; + bool count3; + bool flag3; + bool count4; + bool flag4; + bool count5; + List condicaos = new List() + { + new Condicao() + { + Campo = referencia, + Valores = filtro.Inicio.CriarValor(), + Operador = Operador.MaiorEIgual + }, + new Condicao() + { + Campo = referencia, + Valores = filtro.Fim.CriarValor(), + Operador = Operador.MenorEIgual + } + }; + List seguradoras = filtro.Seguradoras; + if (seguradoras != null) + { + count = seguradoras.Count > 0; + } + else + { + count = false; + } + if (count) + { + condicaos.Add(new Condicao() + { + Campo = "c.idciaseg", + Valores = filtro.Seguradoras.CriarValor() + }); + } + List ramos = filtro.Ramos; + if (ramos != null) + { + flag = ramos.Count > 0; + } + else + { + flag = false; + } + if (flag) + { + condicaos.Add(new Condicao() + { + Campo = "c.idramo", + Valores = filtro.Ramos.CriarValor() + }); + } + List status = filtro.Status; + if (status != null) + { + count1 = status.Count > 0; + } + else + { + count1 = false; + } + if (count1) + { + condicaos.Add(new Condicao() + { + Campo = "d.situacao", + Valores = filtro.Status.CriarValor() + }); + } + List vendedores = filtro.Vendedores; + if (vendedores != null) + { + flag1 = vendedores.Count > 0; + } + else + { + flag1 = false; + } + if (flag1) + { + condicaos.Add(new Condicao() + { + Campo = "vp.idvendedor", + Valores = filtro.Vendedores.CriarValor() + }); + } + List estipulantes = filtro.Estipulantes; + if (estipulantes != null) + { + count2 = estipulantes.Count > 0; + } + else + { + count2 = false; + } + if (count2) + { + condicaos.Add(new Condicao() + { + Campo = "d.idestipulante", + Valores = filtro.Estipulantes.CriarValor() + }); + } + List produtos = filtro.Produtos; + if (produtos != null) + { + flag2 = produtos.Count > 0; + } + else + { + flag2 = false; + } + if (flag2) + { + condicaos.Add(new Condicao() + { + Campo = "c.idproduto", + Valores = filtro.Produtos.CriarValor() + }); + } + List negocio = filtro.Negocio; + if (negocio != null) + { + count3 = negocio.Count > 0; + } + else + { + count3 = false; + } + if (count3) + { + condicaos.Add(new Condicao() + { + Campo = "d.NegocioCorretora", + Valores = filtro.Negocio.CriarValor() + }); + } + List usuarios = filtro.Usuarios; + if (usuarios != null) + { + flag3 = usuarios.Count > 0; + } + else + { + flag3 = false; + } + if (flag3) + { + condicaos.Add(new Condicao() + { + Campo = "IdUsuario", + Valores = filtro.Usuarios.CriarValor() + }); + } + List telas = filtro.Telas; + if (telas != null) + { + count4 = telas.Count > 0; + } + else + { + count4 = false; + } + if (count4) + { + condicaos.Add(new Condicao() + { + Campo = "Tela", + Valores = filtro.Telas.CriarValor() + }); + } + List relatorios = filtro.Relatorios; + if (relatorios != null) + { + flag4 = relatorios.Count > 0; + } + else + { + flag4 = false; + } + if (flag4) + { + condicaos.Add(new Condicao() + { + Campo = "Relatorio", + Valores = filtro.Relatorios.CriarValor() + }); + } + List parcelasEspeciais = filtro.ParcelasEspeciais; + if (parcelasEspeciais != null) + { + count5 = parcelasEspeciais.Count > 0; + } + else + { + count5 = false; + } + if (count5) + { + if (filtro.ParcelasEspeciais.Any((FiltroTipoParcela x) => x.Selecionado)) + { + condicaos.Add(new Condicao() + { + Campo = "p.idsubtipo", + Valores = ( + from x in filtro.ParcelasEspeciais + where x.Selecionado + select (int)x.Tipo).CriarValor>() + }); + } + } + if (filtro.IdEmpresa > (long)0) + { + condicaos.Add(new Condicao() + { + Campo = "c.idempresa", + Valores = filtro.IdEmpresa.CriarValor() + }); + } + return condicaos; + } + + public static List CriarValor(this T valor) + { + return new List() + { + valor + }; + } + + public static List CriarValor(this List lista) + { + return ( + from in lista + select x).ToList(); + } + + public static SqlDbType GetDbType(Type giveType) + { + giveType = Nullable.GetUnderlyingType(giveType) ?? giveType; + if (!Gestor.Infrastructure.Helpers.Funcoes.TypeMap.ContainsKey(giveType)) + { + throw new ArgumentException(string.Concat(giveType.FullName, " is not a supported .NET class")); + } + return Gestor.Infrastructure.Helpers.Funcoes.TypeMap[giveType]; + } + + public static SqlDbType GetDbType() + { + return Gestor.Infrastructure.Helpers.Funcoes.GetDbType(typeof(T)); + } + + public static DateTime GetNetworkTime() + { + DateTime value; + try + { + if (!Gestor.Infrastructure.Helpers.Funcoes.StartTime.HasValue) + { + byte[] numArray = new byte[48]; + numArray[0] = 27; + IPEndPoint pEndPoint = new IPEndPoint(((IEnumerable)Dns.GetHostEntry("time.google.com").AddressList).First((IPAddress a) => a.AddressFamily == AddressFamily.InterNetwork), 123); + using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) + { + socket.Connect(pEndPoint); + socket.ReceiveTimeout = 3000; + socket.Send(numArray); + socket.Receive(numArray); + socket.Close(); + } + ulong num = (ulong)numArray[40] << 24 | (ulong)numArray[41] << 16 | (ulong)numArray[42] << 8 | (ulong)numArray[43]; + ulong num1 = (ulong)numArray[44] << 24 | (ulong)numArray[45] << 16 | (ulong)numArray[46] << 8 | (ulong)numArray[47]; + ulong num2 = num * (long)1000 + num1 * (long)1000 / 4294967296L; + DateTime dateTime = new DateTime(1900, 1, 1); + dateTime = dateTime.AddMilliseconds((double)num2); + Gestor.Infrastructure.Helpers.Funcoes.StartTime = new DateTime?(dateTime.ToLocalTime()); + Gestor.Infrastructure.Helpers.Funcoes.Stopwatch = System.Diagnostics.Stopwatch.StartNew(); + value = Gestor.Infrastructure.Helpers.Funcoes.StartTime.Value; + } + else + { + value = Gestor.Infrastructure.Helpers.Funcoes.StartTime.Value; + value = value.AddMilliseconds((double)Gestor.Infrastructure.Helpers.Funcoes.Stopwatch.ElapsedMilliseconds); + } + } + catch (Exception exception) + { + Gestor.Infrastructure.Helpers.Funcoes.StartTime = new DateTime?(DateTime.Now); + Gestor.Infrastructure.Helpers.Funcoes.Stopwatch = System.Diagnostics.Stopwatch.StartNew(); + value = Gestor.Infrastructure.Helpers.Funcoes.StartTime.Value; + } + return value; + } + + public static bool IsNull(this DataRow row, string field) + { + return row.Obj(field) == null; + } + + public static IQueryable NullSafeWhere(this IQueryable source, Expression> predicate) + { + if (predicate == null) + { + return source; + } + return source.Where(predicate); + } + + public static object Obj(this DataRow row, string field) + { + return row.Field(field); + } + + public static DataTable Select(this SqlCommand sqlCommand, SqlQueryCondition sqlCondition, string command, string group = "") + { + bool count; + DataTable dataTable = new DataTable(); + try + { + sqlCommand.CommandText = string.Concat(new string[] { command, " ", sqlCondition.Condicao, " ", group }); + List parametros = sqlCondition.Parametros; + if (parametros != null) + { + count = parametros.Count > 0; + } + else + { + count = false; + } + if (count) + { + sqlCondition.Parametros.ForEach((SqlParameter x) => sqlCommand.Parameters.Add(x)); + } + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + sqlCommand.Parameters.Clear(); + } + catch (Exception exception) + { + sqlCommand.CommandText = string.Empty; + sqlCommand.Parameters.Clear(); + throw; + } + return dataTable; + } + + public static DataTable Select(this GenericUnitOfWork _unitOfWork, SqlQueryCondition sqlCondition, string command, string group = "") + { + DataTable dataTable; + object connection; + bool count; + DataTable dataTable1 = new DataTable(); + SessionFactoryImpl sessionFactory = _unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + if (sqlConnection != null) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandTimeout = 15000; + sqlCommand.CommandText = string.Concat(new string[] { command, " ", sqlCondition.Condicao, " ", group }); + List parametros = sqlCondition.Parametros; + if (parametros != null) + { + count = parametros.Count > 0; + } + else + { + count = false; + } + if (count) + { + sqlCondition.Parametros.ForEach((SqlParameter x) => sqlCommand.Parameters.Add(x)); + } + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable1); + return dataTable1; + } + } + } + else + { + dataTable = null; + } + } + return dataTable; + } + + public static bool Update(this SqlCommand sqlCommand, SqlQueryCondition sqlCondition, string command, List parameters = null) + { + bool flag; + string condicao; + bool count; + if (string.IsNullOrEmpty(command)) + { + return false; + } + if (sqlCondition != null) + { + condicao = sqlCondition.Condicao; + } + else + { + condicao = null; + } + if (string.IsNullOrEmpty(condicao)) + { + return false; + } + if (sqlCondition.Parametros.Count == 0) + { + return false; + } + if (command.ToUpper().Contains("SELECT")) + { + return false; + } + try + { + sqlCommand.CommandText = string.Concat(command, " ", sqlCondition.Condicao); + List parametros = sqlCondition.Parametros; + if (parametros != null) + { + count = parametros.Count > 0; + } + else + { + count = false; + } + if (count) + { + sqlCondition.Parametros.ForEach((SqlParameter x) => sqlCommand.Parameters.Add(x)); + } + if (parameters != null && parameters.Count > 0) + { + parameters.ForEach((SqlParameter x) => sqlCommand.Parameters.Add(x)); + } + sqlCommand.ExecuteNonQuery(); + sqlCommand.Parameters.Clear(); + return true; + } + catch (Exception exception) + { + sqlCommand.CommandText = string.Empty; + sqlCommand.Parameters.Clear(); + flag = false; + } + return flag; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Helpers/QueryableHelper.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Helpers/QueryableHelper.cs new file mode 100644 index 0000000..1848882 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Helpers/QueryableHelper.cs @@ -0,0 +1,48 @@ +using System; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Helpers +{ + public static class QueryableHelper + { + public static IQueryable WhereNotEmpty(this IQueryable source, T compareVaue, Expression> predicateIf, Expression> predicateElse = null) + { + // + // Current member / type: System.Linq.IQueryable`1 Gestor.Infrastructure.Helpers.QueryableHelper::WhereNotEmpty(System.Linq.IQueryable`1,T,System.Linq.Expressions.Expression`1>,System.Linq.Expressions.Expression`1>) + // File path: C:\AggerSeguros\Lib\Gestor.Infrastructure.dll + // + // Product version: 0.0.0.0 + // Exception in: System.Linq.IQueryable WhereNotEmpty(System.Linq.IQueryable,T,System.Linq.Expressions.Expression>,System.Linq.Expressions.Expression>) + // + // Managed pointer usage not in SSA + // at Telerik.JustDecompiler.Steps.ManagedPointersRemovalStep.CheckForAssignment(BinaryExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\ManagedPointersRemovalStep.cs:line 100 + // at Telerik.JustDecompiler.Steps.ManagedPointersRemovalStep.VisitBinaryExpression(BinaryExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\ManagedPointersRemovalStep.cs:line 80 + // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 351 + // at Telerik.JustDecompiler.Steps.ManagedPointersRemovalStep.VisitExpressions() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\ManagedPointersRemovalStep.cs:line 41 + // at Telerik.JustDecompiler.Steps.ManagedPointersRemovalStep.Process(DecompilationContext context, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\ManagedPointersRemovalStep.cs:line 29 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.Extensions.RunPipeline(DecompilationPipeline pipeline, ILanguage language, MethodBody body, DecompilationContext& context) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 95 + // at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61 + // at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 118 + // + // mailto: JustDecompilePublicFeedback@telerik.com + + } + + public static IQueryable WhereTrue(this IQueryable source, bool compareVaue, Expression> predicateIf, Expression> predicateElse = null) + { + if (compareVaue) + { + return source.Where(predicateIf); + } + if (predicateElse == null) + { + return source; + } + return source.Where(predicateElse); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Helpers/SqlDataReaderHelper.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Helpers/SqlDataReaderHelper.cs new file mode 100644 index 0000000..c4087f8 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Helpers/SqlDataReaderHelper.cs @@ -0,0 +1,66 @@ +using System; +using System.Data.Common; +using System.Data.SqlClient; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Infrastructure.Helpers +{ + internal static class SqlDataReaderHelper + { + public static bool FieldIsNull(this SqlDataReader rd, string fieldName) + { + return rd.IsDBNull(rd.GetOrdinal(fieldName)); + } + + public static async Task FieldIsNullAsync(SqlDataReader rd, string fieldName) + { + return await rd.IsDBNullAsync(rd.GetOrdinal(fieldName)); + } + + public static T GetFieldValue(this SqlDataReader rd, string fieldName, bool normalizeNull = true, bool transformField = true) + { + Type type = rd[fieldName].GetType(); + Type type1 = typeof(T); + if (type == typeof(DBNull)) + { + if (normalizeNull && (!type1.IsGenericType || !(type1.GetGenericTypeDefinition() == typeof(Nullable<>)))) + { + if (type1 == typeof(int) || type1 == typeof(double) || type1 == typeof(decimal) || type1 == typeof(long)) + { + return (T)Convert.ChangeType(0, type1); + } + if (type1 == typeof(DateTime)) + { + return (T)Convert.ChangeType(DateTime.MinValue, type1); + } + if (type1 == typeof(bool)) + { + return (T)Convert.ChangeType(false, type1); + } + } + return default(T); + } + Type underlyingType = Nullable.GetUnderlyingType(type1) ?? type1; + if (type == underlyingType) + { + return (T)rd[fieldName]; + } + if (!transformField) + { + return (T)rd[fieldName]; + } + object item = rd[fieldName]; + if (underlyingType.IsEnum) + { + item = Enum.Parse(underlyingType, item.ToString()); + } + if (type == typeof(string) && underlyingType == typeof(bool)) + { + item = (string)item == "1"; + } + return (T)Convert.ChangeType(item, underlyingType); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappers/ApplicationMapper.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappers/ApplicationMapper.cs new file mode 100644 index 0000000..3f15d41 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappers/ApplicationMapper.cs @@ -0,0 +1,123 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Entities.Configuracoes; +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Entities.Financeiro; +using Gestor.Infrastructure.Entities.Relatorios; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.MalaDireta; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappers +{ + public class ApplicationMapper + { + public static IMapper Mapper + { + get; + set; + } + + static ApplicationMapper() + { + ApplicationMapper.Initialize(); + } + + public ApplicationMapper() + { + } + + private static void Initialize() + { + ApplicationMapper.Mapper = (new MapperConfiguration((IMapperConfigurationExpression cfg) => { + cfg.CreateMissingTypeMaps = new bool?(true); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + cfg.CreateMap().ReverseMap(); + })).CreateMapper(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappers/CustomMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappers/CustomMap.cs new file mode 100644 index 0000000..7f7574b --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappers/CustomMap.cs @@ -0,0 +1,1185 @@ +using Gestor.Common.Validation; +using Gestor.Infrastructure.Helpers; +using Gestor.Model.API; +using Gestor.Model.Common; +using Gestor.Model.Domain.Aggilizador; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappers +{ + public static class CustomMap + { + public static Usuario FromUserSso(this Usuario usuario, UserSso userSso) + { + usuario.SsoId = userSso.Id; + usuario.Nome = userSso.Name; + usuario.Login = userSso.Username; + usuario.Excluido = userSso.IsDeleted; + if (userSso.Password.IsNotNullOrEmpty()) + { + usuario.Senha = userSso.Password; + } + return usuario; + } + + public static List MapAdiantamento(this DataTable data) + { + if (data == null) + { + return null; + } + return data.AsEnumerable().Select((DataRow x) => new Adiantamento() + { + Id = x.Field("idadiantamento"), + Vendedor = Auxiliar.Vendedores.Find((Vendedor v) => v.Id == x.Field("idvendedor")), + TipoPagamento = (x.Field("idtipopagto") != null ? new TipoPagamento?((TipoPagamento)int.Parse(x.Field("idtipopagto").ToString())) : null), + Historico = x.Field("historico"), + Data = x.Field("data"), + Valor = x.Field("valor").GetValueOrDefault(), + Pago = (x.Field("pago") == null ? false : x.Field("pago").ToString() == "1"), + Pagamento = x.Field("Pagamento") + }).ToList(); + } + + public static List MapArquivoVinculo(DataTable data) + { + return data.AsEnumerable().Select((DataRow x) => new ArquivoVinculo() + { + Id = x.Field("Id"), + Arquivo = x.Field("Arquivo"), + IdVinculo = x.Field("IdVinculo"), + Chave = x.Field("Chave"), + Ano = x.Field("Ano"), + Storage = x.Field("Storage") + }).ToList(); + } + + internal static List MapCamposRelatorio(this DataTable data) + { + return ( + from x in data.AsEnumerable().ToList() + select new ParametrosRelatorio() + { + Id = x.Field("Id"), + IdUsuario = x.Field("IdUsuario"), + Relatorio = (Relatorio)x.Field("Relatorio"), + Campo = x.Field("Campo"), + Header = x.Field("Header"), + Width = x.Field("Width").GetValueOrDefault(), + Tipo = x.Field("Tipo"), + Ordem = x.Field("Ordem") + }).ToList(); + } + + internal static List MapCliente(this DataTable data) + { + return ( + from x in data.AsEnumerable().ToList() + select new Cliente() + { + Id = x.Field("id"), + IdEmpresa = x.Field("idempresa"), + Nome = x.Field("nome"), + Documento = x.Field("documento"), + Cei = x.Field("cei"), + Rne = x.Field("rne"), + DocumentoPrincipal = new TipoDocumento?((x.Field("documentoprincipal") == null ? TipoDocumento.Cpf : (TipoDocumento)Enum.Parse(typeof(TipoDocumento), x.Field("documentoprincipal").ToString()))), + Observacao = x.Field("anotacoes"), + Nascimento = x.Field("nascimento"), + Profissao = (x.Field("idprofissao") == null ? null : Auxiliar.Profissoes.Find((Profissao p) => p.Id == x.Field("idprofissao"))), + VencimentoHabilitacao = x.Field("vencimento"), + RendaMensal = x.Field("RendaMensal").GetValueOrDefault(), + Pasta = x.Field("pasta"), + MalaDireta = new bool?(x.Field("MalaDireta").GetValueOrDefault(true)) + }).ToList(); + } + + internal static List MapConta(DataTable data) + { + return data.AsEnumerable().Select((DataRow x) => new BancosContas() + { + Id = x.Field("idconta"), + IdEmpresa = x.Field("idempresa"), + Banco = Auxiliar.Banco.Find((Banco u) => u.Id == x.Field("idcodigobanco")), + Descricao = x.Field("descricao"), + Agencia = x.Field("agencia"), + Conta = x.Field("conta"), + Observacao = x.Field("obs"), + Ativo = (x.Field("ativo") == null ? true : x.Field("ativo").ToString() == "1") + }).ToList(); + } + + internal static List MapDocumento(this DataTable data, List sinistros) + { + return data.AsEnumerable().Select((DataRow x) => { + Documento documento = new Documento() + { + Id = x.Field("iddocumento"), + Controle = new Controle() + { + Id = x.Field("idcontrole"), + IdEmpresa = (x.Field("idempresa") != null ? x.Field("idempresa") : (long)1), + Cliente = new Cliente() + { + Id = x.Field("idcliente") + }, + Seguradora = (x.Field("idciaseg") != null ? Auxiliar.Seguradoras.Find((Seguradora p) => p.Id == x.Field("idciaseg")) : null), + Ramo = (x.Field("idramo") != null ? Auxiliar.Ramos.Find((Ramo p) => p.Id == x.Field("idramo")) : null), + Produto = (x.Field("idproduto") != null ? Auxiliar.Produtos.Find((Produto p) => p.Id == x.Field("idproduto")) : null) + }, + Ordem = x.Field("ordem"), + TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), x.Field("tiporecebimento").ToString())), + AdicionalComiss = x.Field("adinacomis") == "1", + PremioAdicional = x.Field("pr_adic"), + Proposta = x.Field("proposta"), + Apolice = x.Field("contrato"), + PropostaEndosso = x.Field("pedadit"), + Endosso = x.Field("aditamento"), + Comissao = x.Field("com01"), + Negocio = new Negocio?((x.Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field("idnegocio").ToString()))), + PremioLiquido = x.Field("pr_liq"), + PremioTotal = x.Field("pr_total"), + Vigencia2 = x.Field("vigencia2") + }; + DateTime? nullable = x.Field("vigencia1"); + documento.Vigencia1 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue); + documento.Emissao = x.Field("emissao"); + documento.Remessa = x.Field("remessa"); + documento.Estipulante1 = (x.Field("idestipulante") != null ? Auxiliar.Estipulantes.Find((Estipulante p) => p.Id == x.Field("idestipulante")) : null); + documento.NegocioCorretora = new NegocioCorretora?((x.Field("negociocorretora") == null ? NegocioCorretora.Proprio : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), x.Field("negociocorretora").ToString()))); + documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()); + documento.Tipo = x.Field("tipo"); + documento.Sinistro = (sinistros == null ? false : sinistros.Any((long s) => s == x.Field("idcontrole"))); + documento.NumeroParcelas = x.Field("numeroParcelas"); + documento.Pasta = x.Field("Pasta"); + documento.Agencia = x.Field("agencia"); + documento.Conta = x.Field("conta"); + documento.Excluido = (x.Field("excluido") == null ? false : x.Field("excluido").ToString() == "1"); + return documento; + }).ToList(); + } + + public static List MapEmail(DataTable data) + { + return data.AsEnumerable().Select((DataRow x) => { + string str; + string str1; + ClienteEmail clienteEmail = new ClienteEmail() + { + Id = x.Field("Id"), + Cliente = new Cliente() + { + Id = x.Field("IdCliente"), + Nome = x.Field("NomeCliente") + } + }; + string str2 = x.Field("Email"); + if (str2 != null) + { + str = str2.Trim(); + } + else + { + str = null; + } + clienteEmail.Email = str; + string str3 = x.Field("Observacao"); + if (str3 != null) + { + str1 = str3.Trim(); + } + else + { + str1 = null; + } + clienteEmail.Observacao = str1; + clienteEmail.Ordem = x.Field("Ordem"); + return clienteEmail; + }).ToList(); + } + + public static List MapEndereco(this DataTable data) + { + return data.AsEnumerable().Select((DataRow x) => new ClienteEndereco() + { + Id = x.Field("idcliend"), + Endereco = x.Field("endereco"), + Bairro = x.Field("bairro"), + Estado = x.Field("uf"), + Cep = x.Field("cep"), + Numero = x.Field("numero"), + Cidade = x.Field("cidade"), + Complemento = x.Field("comp_end"), + Cliente = new Cliente() + { + Id = x.Field("idcliente"), + Nome = x.Field("nomecliente") + }, + Ordem = x.Field("Ordem"), + Observacao = x.Field("obs") + }).ToList(); + } + + internal static List MapEstipulante(this DataTable data) + { + return data.AsEnumerable().Select((DataRow x) => { + string str; + string str1; + string str2; + string str3; + string str4; + Estipulante estipulante = new Estipulante() + { + IdEmpresa = x.Field("idempresa").GetValueOrDefault((long)1), + Id = x.Field("idestipulante"), + Nome = x.Field("nome"), + Documento = x.Field("cpfcnpj"), + Ativo = (x.Field("ativo") == null ? true : x.Field("ativo").ToString() == "1"), + Cep = x.Field("cep"), + Cidade = x.Field("cidade"), + Estado = x.Field("uf"), + Bairro = x.Field("bairro"), + Endereco = x.Field("endereco"), + Numero = x.Field("numero"), + Complemento = x.Field("complemento"), + PrimeiroTipo = new TipoTelefone?((x.Field("idfonetipo1") == null ? TipoTelefone.Outros : int.Parse(x.Field("idfonetipo1").ToString()))) + }; + string str5 = x.Field("ddd1"); + if (str5 != null) + { + str = str5.Trim(); + } + else + { + str = null; + } + estipulante.PrimeiroPrefixo = str; + string str6 = x.Field("fone1"); + if (str6 != null) + { + str1 = str6.Trim(); + } + else + { + str1 = null; + } + estipulante.PrimeiroTelefone = str1; + estipulante.SegundoTipo = new TipoTelefone?((x.Field("idfonetipo2") == null ? TipoTelefone.Outros : int.Parse(x.Field("idfonetipo2").ToString()))); + string str7 = x.Field("ddd2"); + if (str7 != null) + { + str2 = str7.Trim(); + } + else + { + str2 = null; + } + estipulante.SegundoPrefixo = str2; + string str8 = x.Field("fone2"); + if (str8 != null) + { + str3 = str8.Trim(); + } + else + { + str3 = null; + } + estipulante.SegundoTelefone = str3; + string str9 = x.Field("email"); + if (str9 != null) + { + str4 = str9.Trim(); + } + else + { + str4 = null; + } + estipulante.Email = str4; + estipulante.Observacao = (x.Field("obs") != null ? x.Field("obs").ToString() : null); + return estipulante; + }).ToList(); + } + + public static List MapExtrato(DataTable data, DataTable parcelas = null) + { + return data.AsEnumerable().ToList().Select((DataRow x) => { + Extrato extrato = new Extrato() + { + Id = x.Field("idextrato") + }; + decimal? nullable = x.Field("bruto"); + extrato.Bruto = new decimal?(nullable.GetValueOrDefault()); + extrato.Data = x.Field("data"); + DateTime? nullable1 = x.Field("DataCredito"); + extrato.DataCredito = (nullable1.HasValue ? nullable1 : x.Field("data")); + extrato.Historico = x.Field("historico"); + nullable = x.Field("ir"); + extrato.Ir = new decimal?(nullable.GetValueOrDefault()); + nullable = x.Field("iss"); + extrato.Iss = new decimal?(nullable.GetValueOrDefault()); + nullable = x.Field("liquido"); + extrato.Liquido = new decimal?(nullable.GetValueOrDefault()); + extrato.Numero = x.Field("extrato"); + extrato.Observacao = (x.Field("obsextrato") == null ? "" : x.Field("obsextrato").ToString()); + extrato.Seguradora = (x.Field("idciaseg") != null ? Auxiliar.Seguradoras.FirstOrDefault((Seguradora p) => p.Id == x.Field("idciaseg")) : null); + nullable = x.Field("outro"); + extrato.Outro = new decimal?(nullable.GetValueOrDefault()); + extrato.Status = (x.Field("idstatusextrato") == null ? StatusExtrato.Pendente : (x.Field("idstatusextrato").ToString() == "2" ? StatusExtrato.Baixado : (StatusExtrato)Enum.Parse(typeof(StatusExtrato), x.Field("idstatusextrato").ToString()))); + extrato.IdEmpresa = x.Field("idempresa"); + extrato.Completo = (parcelas == null ? false : parcelas.AsEnumerable().All((DataRow p) => p.Field("idextrato") != x.Field("idextrato"))); + extrato.IdUsuario = x.Field("usuariocriacao"); + return extrato; + }).ToList(); + } + + internal static List MapFornecedor(DataTable data) + { + return data.AsEnumerable().Select((DataRow x) => { + TipoTelefone? nullable; + TipoTelefone? nullable1; + TipoTelefone? nullable2; + Fornecedor fornecedor = new Fornecedor() + { + Id = x.Field("idfornecedor"), + Nome = x.Field("nome"), + Documento = x.Field("cpfcnpj") + }; + if (x.Field("idfonetipo1") != null) + { + nullable1 = new TipoTelefone?((TipoTelefone)int.Parse(x.Field("idfonetipo1").ToString())); + } + else + { + nullable = null; + nullable1 = nullable; + } + fornecedor.TipoTelefone1 = nullable1; + fornecedor.Prefixo1 = x.Field("ddd1"); + fornecedor.Telefone1 = x.Field("fone1"); + if (x.Field("idfonetipo2") != null) + { + nullable2 = new TipoTelefone?((TipoTelefone)int.Parse(x.Field("idfonetipo2").ToString())); + } + else + { + nullable = null; + nullable2 = nullable; + } + fornecedor.TipoTelefone2 = nullable2; + fornecedor.Prefixo2 = x.Field("ddd2"); + fornecedor.Telefone2 = x.Field("fone2"); + fornecedor.Email = x.Field("email"); + fornecedor.Complemento = x.Field("complemento"); + fornecedor.Cidade = x.Field("cidade"); + fornecedor.Bairro = x.Field("bairro"); + fornecedor.Numero = x.Field("numero"); + fornecedor.Cep = x.Field("cep"); + fornecedor.Estado = x.Field("uf"); + fornecedor.Endereco = x.Field("endereco"); + fornecedor.IdCentro = x.Field("idcentro"); + fornecedor.IdConta = x.Field("idconta"); + fornecedor.IdPlano = x.Field("idcplanos"); + fornecedor.IdEmpresa = x.Field("idempresa"); + fornecedor.Observacao = x.Field("observacao"); + fornecedor.TipoPagamento = (x.Field("idtipopagto") != null ? new TipoPagamento?((TipoPagamento)int.Parse(x.Field("idtipopagto").ToString())) : null); + fornecedor.Ativo = x.Field("Ativo"); + return fornecedor; + }).ToList(); + } + + internal static List MapImportacao(this DataTable data) + { + return data.AsEnumerable().ToList().Select((DataRow x) => { + CriticaApolice criticaApolouse = new CriticaApolice() + { + Id = x.Field("id"), + UsuarioImportacao = (x.Field("idusuario") != null ? Auxiliar.Usuarios.Find((Usuario p) => p.Id == x.Field("idusuario")) : null), + Critica = new bool?((x.Field("critica") == null ? false : x.Field("critica").ToString() == "1")) + }; + DateTime? nullable = x.Field("dataimportacao"); + criticaApolouse.DataImportacao = new DateTime?((nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue)); + criticaApolouse.Tipo = x.Field("tipo"); + criticaApolouse.Documento = new Documento() + { + Id = x.Field("iddocumento"), + Controle = new Controle() + { + Id = x.Field("idcontrole"), + Seguradora = Auxiliar.Seguradoras.Find((Seguradora s) => s.Id == x.Field("idciaseg")), + Ramo = Auxiliar.Ramos.Find((Ramo s) => s.Id == x.Field("idramo")), + Cliente = new Cliente() + { + Id = x.Field("idcliente"), + Nome = x.Field("cliente"), + Documento = x.Field("documento"), + Cei = x.Field("cei"), + Rne = x.Field("rne"), + DocumentoPrincipal = new TipoDocumento?((x.Field("documentoprincipal") == null ? TipoDocumento.Cpf : (TipoDocumento)Enum.Parse(typeof(TipoDocumento), x.Field("documentoprincipal").ToString()))) + } + }, + Apolice = x.Field("apolice"), + Proposta = x.Field("proposta"), + Vigencia1 = x.Field("vigencia1"), + Vigencia2 = x.Field("vigencia2") + }; + criticaApolouse.UsuarioCritica = x.Field("idusuariocritica"); + criticaApolouse.DataCritica = x.Field("datacritica"); + return criticaApolouse; + }).ToList(); + } + + public static List MapImposto(DataTable data) + { + return data.AsEnumerable().Select((DataRow x) => new Imposto() + { + Id = x.Field("Id"), + Seguradora = (x.Field("idciaseg") != null ? Auxiliar.Seguradoras.Find((Seguradora s) => s.Id == x.Field("idciaseg")) : null), + Ramo = (x.Field("idramo") != null ? Auxiliar.Ramos.Find((Ramo s) => s.Id == x.Field("idramo")) : null), + Ir = x.Field("Ir"), + Iss = x.Field("Iss"), + Outros = x.Field("Outros"), + Desconto = x.Field("Desconto"), + Ativo = x.Field("Ativo") + }).ToList(); + } + + public static List MapLancamento(DataTable data) + { + return data.AsEnumerable().Select((DataRow x) => { + object fornecedor; + Lancamento lancamento = new Lancamento() + { + Id = x.Field("idlancamen") + }; + ControleFinanceiro controleFinanceiro = new ControleFinanceiro() + { + Id = x.Field("idcfinan") + }; + if (x.Field("idfornecedor") != null) + { + fornecedor = new Fornecedor(); + ((Fornecedor)fornecedor).Id = x.Field("idfornecedor"); + ((Fornecedor)fornecedor).Nome = x.Field("nome"); + bool? nullable = x.Field("Ativo"); + ((Fornecedor)fornecedor).Ativo = nullable.GetValueOrDefault(); + } + else + { + fornecedor = null; + } + controleFinanceiro.Fornecedor = (Fornecedor)fornecedor; + controleFinanceiro.Plano = (x.Field("idcplanos") != null ? AuxiliarFinanceiro.Planos.Find((Planos p) => p.Id == x.Field("idcplanos")) : null); + controleFinanceiro.Centro = (x.Field("idcentro") != null ? AuxiliarFinanceiro.Centros.Find((Centro p) => p.Id == x.Field("idcentro")) : null); + controleFinanceiro.Historico = x.Field("historicocfinan"); + controleFinanceiro.Parcelas = x.Field("parcelas"); + lancamento.Controle = controleFinanceiro; + lancamento.Historico = x.Field("historico"); + lancamento.Documento = x.Field("documento"); + lancamento.Complemento = x.Field("complemento"); + lancamento.Competencia = x.Field("competencia"); + lancamento.Parcela = x.Field("parcela"); + decimal? nullable1 = x.Field("vlrpre"); + lancamento.Valor = nullable1.GetValueOrDefault(); + lancamento.Vencimento = x.Field("dtpre"); + nullable1 = x.Field("vlrbaixa"); + lancamento.ValorPago = new decimal?(nullable1.GetValueOrDefault()); + lancamento.Baixa = x.Field("dtbaixa"); + lancamento.Pagamento = x.Field("dtpagto"); + lancamento.Conta = AuxiliarFinanceiro.Contas.Find((BancosContas p) => p.Id == x.Field("idconta")); + lancamento.Sinal = (Sinal)Enum.Parse(typeof(Sinal), x.Field("sinal").ToString()); + lancamento.TipoPagamento = (x.Field("idtipopagto") != null ? (TipoPagamento)Enum.Parse(typeof(TipoPagamento), x.Field("idtipopagto").ToString()) : TipoPagamento.Nenhum); + lancamento.Observacao = x.Field("obs"); + lancamento.Baixado = x.Field("dtbaixa").HasValue; + lancamento.CodigoBanco = x.Field("CodigoBanco"); + lancamento.DataLancamento = x.Field("datacriacao"); + return lancamento; + }).ToList(); + } + + internal static List MapLogAcao(DataTable data) + { + return data.AsEnumerable().Select((DataRow x) => new RegistroAcao() + { + Id = x.Field("Id"), + EntidadeId = x.Field("EntidadeId"), + Tela = (x.Field("Tela") != null ? new TipoTela?((TipoTela)x.Field("Tela")) : null), + Relatorio = (x.Field("Relatorio") != null ? new Relatorio?((Relatorio)x.Field("Relatorio")) : null), + Usuario = Auxiliar.Usuarios.Find((Usuario u) => u.Id == x.Field("IdUsuario")), + DataHora = x.Field("DataHora"), + Descricao = x.Field("Descricao"), + Observacao = x.Field("Observacao"), + Ip = x.Field("Ip"), + NomeMaquina = x.Field("NomeMaquina"), + UsuarioMaquina = x.Field("UsuarioMaquina"), + Versao = x.Field("Versao") + }).ToList(); + } + + internal static List MapMaisContatos(this DataTable data, Cliente cliente) + { + return ( + from x in data.AsEnumerable().ToList() + select new MaisContato() + { + Id = x.Field("idclicontato"), + Cliente = cliente, + Profissao = (x.Field("idprofissao") != null ? Auxiliar.Profissoes.Find((Profissao p) => p.Id == x.Field("idprofissao")) : null), + Nome = x.Field("contato"), + Tipo = (x.Field("tipo") != null ? new TipoTelefone?((TipoTelefone)int.Parse(x.Field("tipo").ToString())) : null), + Nascimento = x.Field("dtnasc"), + Documento = x.Field("cgccpf"), + Identidade = x.Field("rg"), + Expedicao = x.Field("rgexpedicao"), + Parentesco = (x.Field("idparentesco") != null ? new Parentesco?((Parentesco)((int)long.Parse(x.Field("idparentesco").ToString()))) : null), + Prefixo = x.Field("ddd"), + Telefone = x.Field("fone"), + Email = x.Field("email"), + Habilitacao = x.Field("cnh"), + PrimeiraHabilitacao = x.Field("prihabilitacao"), + Banco = x.Field("banco"), + Agencia = x.Field("agencia"), + Conta = x.Field("conta"), + Excluido = (x.Field("excluido") == null ? false : x.Field("excluido") == "1") + }).ToList(); + } + + internal static List MapManutencao(this DataTable data) + { + return data.AsEnumerable().ToList().Select((DataRow x) => { + string str; + string nome; + string nomeSocial; + string nome1; + string str1; + ManutencaoPagamentos manutencaoPagamento = new ManutencaoPagamentos() + { + Id = x.Field("idvendedorparcela"), + IdParcela = x.Field("idparcela"), + IdDocumento = x.Field("iddocumento") + }; + string str2 = x.Field("nomecliente"); + if (str2 != null) + { + str = str2.Trim(); + } + else + { + str = null; + } + manutencaoPagamento.Nome = str; + Empresa empresa = Auxiliar.Empresas.Find((Empresa e) => e.Id == x.Field("idempresa")); + if (empresa != null) + { + nome = empresa.Nome; + } + else + { + nome = null; + } + manutencaoPagamento.Empresa = nome; + manutencaoPagamento.Apolice = x.Field("apolice"); + manutencaoPagamento.Endosso = x.Field("endosso"); + Seguradora seguradora = Auxiliar.Seguradoras.Find((Seguradora s) => s.Id == x.Field("idseguradora")); + if (seguradora != null) + { + nomeSocial = seguradora.NomeSocial; + } + else + { + nomeSocial = null; + } + manutencaoPagamento.Seguradora = nomeSocial; + Ramo ramo = Auxiliar.Ramos.Find((Ramo s) => s.Id == x.Field("idramo")); + if (ramo != null) + { + nome1 = ramo.Nome; + } + else + { + nome1 = null; + } + manutencaoPagamento.Ramo = nome1; + if (x.Field("idproduto") == null) + { + str1 = ""; + } + else + { + Produto produto = Auxiliar.Produtos.Find((Produto s) => s.Id == x.Field("idproduto")); + if (produto != null) + { + str1 = produto.Nome; + } + else + { + str1 = null; + } + } + manutencaoPagamento.Produto = str1; + manutencaoPagamento.Parcela = int.Parse(x.Field("numeroparcela").ToString()); + manutencaoPagamento.Tipo = (x.Field("idsubtipo") == null ? SubTipo.ParcelaNormal : int.Parse(x.Field("idsubtipo").ToString())); + decimal? nullable = x.Field("valor"); + manutencaoPagamento.Valor = nullable.GetValueOrDefault(); + manutencaoPagamento.Recebimento = x.Field("datarecebimento"); + manutencaoPagamento.Vendedor = x.Field("nomevendedor"); + DateTime? nullable1 = x.Field("dataprepagamento"); + manutencaoPagamento.PrevisaoPagamento = (nullable1.HasValue ? nullable1.GetValueOrDefault() : x.Field("datapagamento")); + manutencaoPagamento.Pagamento = x.Field("datapagamento"); + nullable = x.Field("vlrrep"); + manutencaoPagamento.ValorRepasse = nullable.GetValueOrDefault(); + return manutencaoPagamento; + }).ToList(); + } + + internal static List MapOldLogAcao(DataTable data) + { + List registroAcaos = new List(); + data.AsEnumerable().ToList().ForEach((DataRow x) => { + TipoTela? nullable = x.Field("FORM").Convert(); + Relatorio? nullable1 = x.Field("FORM").ConvertRelatorio(); + if (!nullable.HasValue && !nullable1.HasValue) + { + nullable = new TipoTela?(TipoTela.Todas); + } + RegistroAcao registroAcao = new RegistroAcao() + { + Id = x.Field("IDACTION"), + EntidadeId = x.Field("ID"), + Tela = nullable, + Relatorio = nullable1, + Usuario = Auxiliar.Usuarios.Find((Usuario u) => u.Id == x.Field("IDUSUARIO")), + DataHora = x.Field("DATA"), + Descricao = x.Field("ACAO"), + Observacao = x.Field("historico"), + NomeMaquina = x.Field("maquina") + }; + registroAcaos.Add(registroAcao); + }); + return registroAcaos; + } + + internal static List MapParcela(this DataTable data, Documento documento) + { + return data.AsEnumerable().Select((DataRow x) => { + Parcela parcela = new Parcela() + { + Id = x.Field("idparcela"), + IdEmpresa = x.Field("idempresa"), + Documento = documento, + NumeroParcela = (x.Field("parcela") != null ? int.Parse(x.Field("parcela").ToString()) : 1) + }; + DateTime? nullable = x.Field("vencto"); + parcela.Vencimento = (nullable.HasValue ? nullable.GetValueOrDefault() : documento.Vigencia1); + parcela.DataRecebimento = x.Field("datarec"); + parcela.DataQuitacao = x.Field("dataquit"); + parcela.DataCredito = x.Field("datacred"); + decimal? nullable1 = x.Field("valor"); + parcela.Valor = nullable1.GetValueOrDefault(); + nullable1 = x.Field("valorp"); + parcela.ValorPago = nullable1.GetValueOrDefault(); + nullable1 = x.Field("valorr"); + parcela.ValorRealizado = nullable1.GetValueOrDefault(); + nullable1 = x.Field("comiss"); + parcela.Comissao = nullable1.GetValueOrDefault(); + nullable1 = x.Field("vlrcomiss"); + parcela.ValorComissao = nullable1.GetValueOrDefault(); + parcela.Observacao = (x.Field("obs") != null ? x.Field("obs").ToString() : ""); + parcela.Extrato = x.Field("extrato"); + nullable1 = x.Field("irr"); + parcela.Irr = nullable1.GetValueOrDefault(); + nullable1 = x.Field("iss"); + parcela.Iss = nullable1.GetValueOrDefault(); + nullable1 = x.Field("outros"); + parcela.Outros = nullable1.GetValueOrDefault(); + nullable1 = x.Field("desconto"); + parcela.Desconto = nullable1.GetValueOrDefault(); + nullable1 = x.Field("vlrextrato"); + parcela.ValorExtrato = nullable1.GetValueOrDefault(); + nullable1 = x.Field("vlrcomdesc"); + parcela.ValorComDesconto = nullable1.GetValueOrDefault(); + parcela.SubTipo = (x.Field("idsubtipo") == null ? SubTipo.ParcelaNormal : int.Parse(x.Field("idsubtipo").ToString())); + parcela.TipoPagamento = (x.Field("idtipopagto") == null ? TipoPagamento.Nenhum : int.Parse(x.Field("idtipopagto").ToString())); + nullable1 = x.Field("valorlf"); + parcela.ValorLiquidoFatura = nullable1.GetValueOrDefault(); + parcela.DataCriacao = x.Field("cri_data"); + long? nullable2 = x.Field("usuariocriacao"); + parcela.UsuarioCriacao = nullable2.GetValueOrDefault(); + parcela.DataControle = x.Field("datacontrole"); + parcela.Fatura = x.Field("fatura"); + parcela.VigenciaIncial = x.Field("vigenciainicial"); + parcela.VigenciaFinal = x.Field("vigenciafinal"); + parcela.Emissao = x.Field("emissao"); + parcela.StatusPagamento = new StatusPagamento?((x.Field("StatusPagamento") == null ? StatusPagamento.All : (StatusPagamento)Enum.Parse(typeof(StatusPagamento), x.Field("StatusPagamento").ToString()))); + nullable2 = x.Field("IdParcelaPendente"); + parcela.IdParcelaPendente = nullable2.GetValueOrDefault(); + return parcela; + }).ToList(); + } + + internal static Parcela MapParcela(this DataRow data) + { + SubTipo subTipo; + TipoPagamento tipoPagamento; + if (data == null) + { + return null; + } + Parcela parcela = new Parcela() + { + Id = data.Field("idparcela"), + IdEmpresa = data.Field("idempresa"), + Documento = new Documento() + { + Id = data.Field("iddocumento") + }, + NumeroParcela = (data.Field("parcela") != null ? int.Parse(data.Field("parcela").ToString()) : 1) + }; + DateTime? nullable = data.Field("vencto"); + parcela.Vencimento = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.Now); + parcela.DataRecebimento = data.Field("datarec"); + parcela.DataQuitacao = data.Field("dataquit"); + parcela.DataCredito = data.Field("datacred"); + decimal? nullable1 = data.Field("valor"); + parcela.Valor = nullable1.GetValueOrDefault(); + nullable1 = data.Field("valorp"); + parcela.ValorPago = nullable1.GetValueOrDefault(); + nullable1 = data.Field("valorr"); + parcela.ValorRealizado = nullable1.GetValueOrDefault(); + nullable1 = data.Field("comiss"); + parcela.Comissao = nullable1.GetValueOrDefault(); + nullable1 = data.Field("vlrcomiss"); + parcela.ValorComissao = nullable1.GetValueOrDefault(); + parcela.Observacao = (data.Field("obs") != null ? data.Field("obs").ToString() : ""); + parcela.Extrato = data.Field("extrato"); + nullable1 = data.Field("irr"); + parcela.Irr = nullable1.GetValueOrDefault(); + nullable1 = data.Field("iss"); + parcela.Iss = nullable1.GetValueOrDefault(); + nullable1 = data.Field("outros"); + parcela.Outros = nullable1.GetValueOrDefault(); + nullable1 = data.Field("desconto"); + parcela.Desconto = nullable1.GetValueOrDefault(); + nullable1 = data.Field("vlrextrato"); + parcela.ValorExtrato = nullable1.GetValueOrDefault(); + nullable1 = data.Field("vlrcomdesc"); + parcela.ValorComDesconto = nullable1.GetValueOrDefault(); + if (data.Field("idsubtipo") == null) + { + subTipo = SubTipo.ParcelaNormal; + } + else + { + subTipo = (SubTipo)int.Parse(data.Field("idsubtipo").ToString()); + } + parcela.SubTipo = subTipo; + if (data.Field("idtipopagto") == null) + { + tipoPagamento = TipoPagamento.Nenhum; + } + else + { + tipoPagamento = (TipoPagamento)int.Parse(data.Field("idtipopagto").ToString()); + } + parcela.TipoPagamento = tipoPagamento; + nullable1 = data.Field("valorlf"); + parcela.ValorLiquidoFatura = nullable1.GetValueOrDefault(); + parcela.DataCriacao = data.Field("cri_data"); + long? nullable2 = data.Field("usuariocriacao"); + parcela.UsuarioCriacao = nullable2.GetValueOrDefault(); + parcela.DataControle = data.Field("datacontrole"); + parcela.Fatura = data.Field("fatura"); + parcela.VigenciaIncial = data.Field("vigenciainicial"); + parcela.VigenciaFinal = data.Field("vigenciafinal"); + parcela.Emissao = data.Field("emissao"); + parcela.StatusPagamento = new StatusPagamento?((data.Field("StatusPagamento") == null ? StatusPagamento.All : (StatusPagamento)Enum.Parse(typeof(StatusPagamento), data.Field("StatusPagamento").ToString()))); + nullable2 = data.Field("IdParcelaPendente"); + parcela.IdParcelaPendente = nullable2.GetValueOrDefault(); + return parcela; + } + + internal static List MapPermissao(this DataTable data) + { + return data.AsEnumerable().Select((DataRow x) => new PermissaoUsuario() + { + Id = x.Field("Id"), + Usuario = Auxiliar.Usuarios.Find((Usuario u) => u.Id == x.Field("IdUsuario")), + Tela = (TipoTela)x.Field("Tela"), + Consultar = x.Field("Consultar"), + Incluir = x.Field("Incluir"), + Alterar = x.Field("Alterar"), + Excluir = x.Field("Excluir") + }).ToList(); + } + + internal static List MapPlanos(DataTable data) + { + return data.AsEnumerable().Select((DataRow x) => new Planos() + { + Id = x.Field("id"), + Descricao = x.Field("nome"), + Nome = x.Field("descricao"), + Ativo = (x.Field("ativo") == null ? true : x.Field("ativo").ToString() == "1"), + Plano = AuxiliarFinanceiro.Plano.Find((Plano p) => p.Id == x.Field("idcplano")), + TipoConta = (x.Field("idtipoconta").HasValue ? AuxiliarFinanceiro.TiposConta.Find((Gestor.Model.Domain.Financeiro.TipoConta p) => p.Id == x.Field("idtipoconta")) : null), + Sinal = (x.Field("ctipo") == null ? Sinal.Credito : (Sinal)Enum.Parse(typeof(Sinal), x.Field("ctipo").ToString())) + }).ToList(); + } + + internal static List MapRegistroLog(this DataTable data) + { + return ( + from x in data.AsEnumerable().ToList() + select new RegistroLog() + { + Id = x.Field("Id"), + Usuario = (x.Field("IdUsuario") != null ? Auxiliar.Usuarios.Find((Usuario u) => u.Id == x.Field("IdUsuario")) : null), + EntidadeId = x.Field("EntidadeId"), + Acao = (TipoAcao)x.Field("Acao"), + Tela = (TipoTela)x.Field("Tela"), + Versao = x.Field("Versao"), + DataHora = x.Field("DataHora"), + Descricao = (x.Field("Descricao") == null ? "" : x.Field("Descricao")), + NomeMaquina = x.Field("NomeMaquina"), + UsuarioMaquina = x.Field("UsuarioMaquina"), + Ip = x.Field("Ip"), + ModeloNovo = x.Field("ModeloNovo").GetValueOrDefault() + }).ToList(); + } + + internal static List MapSaldo(DataTable data) + { + return data.AsEnumerable().Select((DataRow x) => { + Saldo saldo = new Saldo() + { + Id = x.Field("idsaldo"), + Conta = AuxiliarFinanceiro.Contas.Find((BancosContas u) => u.Id == x.Field("idconta")) + }; + decimal? nullable = x.Field("vlrinicio"); + saldo.ValorInicio = nullable.GetValueOrDefault(); + saldo.DataInicio = new DateTime?(x.Field("dtinicio")); + nullable = x.Field("vlrfim"); + saldo.ValorFinal = new decimal?(nullable.GetValueOrDefault()); + saldo.DataFinal = x.Field("dtfim"); + saldo.Extrato = x.Field("extrato"); + return saldo; + }).ToList(); + } + + internal static List MapSeguradoraContato(this DataTable data) + { + return ( + from x in data.AsEnumerable().ToList() + select new SeguradoraContato() + { + Id = x.Field("idciacontato"), + Empresa = Auxiliar.Empresas.Find((Empresa e) => e.Id == x.Field("idempresa")), + Seguradora = Auxiliar.Seguradoras.Find((Seguradora s) => s.Id == x.Field("idciaseg")), + NomeContato = x.Field("nome"), + Tipo = (x.Field("idfonetipo") != null ? new TipoTelefone?((TipoTelefone)int.Parse(x.Field("idfonetipo").ToString())) : null), + Prefixo = x.Field("ddd"), + Numero = x.Field("fone"), + Email = x.Field("email"), + TipoContato = (TipoContatoSeguradora)((x.Field("TipoContato") != null ? int.Parse(x.Field("TipoContato").ToString()) : TipoContatoSeguradora.Contato)) + }).ToList(); + } + + internal static List MapSinistro(this DataTable data, DataTable apolice) + { + List sinistros = new List(); + data.AsEnumerable().ToList().ForEach((DataRow x) => { + DataRow dataRow = apolice.AsEnumerable().FirstOrDefault((DataRow d) => d.Field("iditem") == x.Field("iditem")); + if (dataRow == null) + { + return; + } + Sinistro sinistro = new Sinistro() + { + ControleSinistro = new ControleSinistro() + { + Id = x.Field("idcontrolesinistro"), + Item = new Item() + { + Id = dataRow.Field("iditem"), + Documento = new Documento() + { + Id = dataRow.Field("iddocumento"), + Apolice = dataRow.Field("apolice"), + Controle = new Controle() + { + Id = dataRow.Field("idcontrole"), + Cliente = new Cliente() + { + Id = dataRow.Field("idcliente"), + Nome = dataRow.Field("nome") + } + } + } + } + }, + Id = x.Field("idsinistro"), + Numero = x.Field("numsinistro"), + ItemSinistrado = x.Field("itemsinistrado") + }; + sinistros.Add(sinistro); + }); + return sinistros; + } + + public static List MapTarefa(DataTable data, DataTable responsaveis) + { + return data.AsEnumerable().Select((DataRow x) => { + Tarefa tarefa = new Tarefa() + { + Id = x.Field("Id") + }; + long? nullable = x.Field("IdCliente"); + tarefa.IdCliente = nullable.GetValueOrDefault(); + tarefa.Cliente = x.Field("Cliente"); + tarefa.Entidade = (TipoTarefa)x.Field("Entidade"); + nullable = x.Field("IdEntidade"); + tarefa.IdEntidade = nullable.GetValueOrDefault(); + DateTime? nullable1 = x.Field("Agendamento"); + tarefa.Agendamento = (nullable1.HasValue ? nullable1.GetValueOrDefault() : DateTime.Now); + tarefa.Conclusao = x.Field("Conclusao"); + tarefa.Referencia = x.Field("Referencia"); + tarefa.Titulo = x.Field("Titulo"); + tarefa.Descricao = x.Field("Descricao"); + tarefa.DescricaoInterna = x.Field("descricaointerna"); + tarefa.Status = (StatusTarefa)x.Field("Status"); + tarefa.Usuario = (x.Field("IdUsuario") != null ? Auxiliar.Usuarios.Find((Usuario u) => u.Id == x.Field("IdUsuario")) : null); + tarefa.UsuarioCadastro = (x.Field("IdUsuarioCadastro") != null ? Auxiliar.Usuarios.Find((Usuario u) => u.Id == x.Field("IdUsuarioCadastro")) : null); + tarefa.TipoDeTarefa = (x.Field("IdTipoTarefa") != null ? Auxiliar.TiposTarefa.Find((TipoDeTarefa t) => t.Id == x.Field("IdTipoTarefa")) : null); + tarefa.Restrito = new bool?(x.Field("Restrito").GetValueOrDefault()); + tarefa.Categoria = (x.Field("IdCategoria") != null ? Auxiliar.CategoriaTarefa.Find((CategoriaTarefa c) => c.Id == x.Field("IdCategoria")) : null); + EnumerableRowCollection dataRows = responsaveis.AsEnumerable().Where((DataRow r) => r.Field("IdTarefa") == x.Field("Id")); + Func u003cu003e9_46 = CustomMap.u003cu003ec.u003cu003e9__4_6; + if (u003cu003e9_46 == null) + { + u003cu003e9_46 = (DataRow r) => new ResponsavelTarefa() + { + Id = r.Field("Id"), + Usuario = Auxiliar.Usuarios.Find((Usuario u) => u.Id == r.Field("Usuario_id")) + }; + CustomMap.u003cu003ec.u003cu003e9__4_6 = u003cu003e9_46; + } + tarefa.Responsaveis = dataRows.Select(u003cu003e9_46).ToList(); + return tarefa; + }).ToList(); + } + + public static List MapTelefone(DataTable data) + { + return data.AsEnumerable().Select((DataRow x) => { + string str; + string str1; + string str2; + ClienteTelefone clienteTelefone = new ClienteTelefone() + { + Id = x.Field("Id"), + Cliente = new Cliente() + { + Id = x.Field("IdCliente"), + Nome = x.Field("NomeCliente") + } + }; + string str3 = x.Field("Prefixo"); + if (str3 != null) + { + str = str3.Trim(); + } + else + { + str = null; + } + clienteTelefone.Prefixo = str; + string str4 = x.Field("Numero"); + if (str4 != null) + { + str1 = str4.Trim(); + } + else + { + str1 = null; + } + clienteTelefone.Numero = str1; + clienteTelefone.Tipo = new TipoTelefone?((TipoTelefone)int.Parse(x.Field("Tipo").ToString())); + string str5 = x.Field("Observacao"); + if (str5 != null) + { + str2 = str5.Trim(); + } + else + { + str2 = null; + } + clienteTelefone.Observacao = str2; + clienteTelefone.Ordem = x.Field("Ordem"); + return clienteTelefone; + }).ToList(); + } + + public static List MapUsuario(DataTable data) + { + return data.AsEnumerable().ToList().Select((DataRow x) => { + TipoTelefone? nullable; + TipoTelefone? nullable1; + TipoTelefone? nullable2; + Usuario usuario = new Usuario() + { + IdEmpresa = x.Field("idempresa"), + Id = x.Field("idusuario"), + Nome = x.Field("nome"), + Login = x.Field("identif"), + Senha = x.Field("senha"), + Documento = x.Field("cgccpf"), + Nascimento = x.Field("dtnasc") + }; + bool? nullable3 = x.Field("removido"); + usuario.Excluido = nullable3.GetValueOrDefault(); + usuario.PermissaoAggilizador = x.Field("IdPermissao"); + nullable3 = x.Field("AdmGestor"); + usuario.Administrador = nullable3.GetValueOrDefault(); + nullable3 = x.Field("Segunda"); + usuario.Segunda = new bool?(nullable3.GetValueOrDefault(true)); + nullable3 = x.Field("Terca"); + usuario.Terca = new bool?(nullable3.GetValueOrDefault(true)); + nullable3 = x.Field("Quarta"); + usuario.Quarta = new bool?(nullable3.GetValueOrDefault(true)); + nullable3 = x.Field("Quinta"); + usuario.Quinta = new bool?(nullable3.GetValueOrDefault(true)); + nullable3 = x.Field("Sexta"); + usuario.Sexta = new bool?(nullable3.GetValueOrDefault(true)); + nullable3 = x.Field("Sabado"); + usuario.Sabado = new bool?(nullable3.GetValueOrDefault(true)); + nullable3 = x.Field("Domingo"); + usuario.Domingo = new bool?(nullable3.GetValueOrDefault(true)); + usuario.TelaInicial = new TipoTelaInicial?((x.Field("TelaInicial") == null ? TipoTelaInicial.Consulta : x.Field("TelaInicial"))); + usuario.Visita = x.Field("Visita"); + usuario.Cep = x.Field("cep"); + usuario.Endereco = x.Field("endereco"); + usuario.Numero = x.Field("numero"); + usuario.Complemento = x.Field("complemento"); + usuario.Bairro = x.Field("bairro"); + usuario.Cidade = x.Field("cidade"); + usuario.Estado = x.Field("uf"); + if (x.Field("TipoTelefone") == null) + { + nullable = null; + nullable1 = nullable; + } + else + { + nullable1 = new TipoTelefone?((TipoTelefone)x.Field("TipoTelefone")); + } + usuario.TipoTelefone = nullable1; + usuario.Prefixo = x.Field("ddd"); + usuario.Telefone = x.Field("telefone"); + if (x.Field("TipoTelefone2") == null) + { + nullable = null; + nullable2 = nullable; + } + else + { + nullable2 = new TipoTelefone?((TipoTelefone)x.Field("TipoTelefone2")); + } + usuario.TipoTelefone2 = nullable2; + usuario.Prefixo2 = x.Field("ddd2"); + usuario.Telefone2 = x.Field("telefone2"); + usuario.Email = x.Field("email"); + usuario.Identidade = x.Field("rg"); + usuario.EstadoEmissor = x.Field("rguf"); + usuario.Expedicao = x.Field("rgexpedicao"); + usuario.Agencia = x.Field("agencia"); + usuario.Conta = x.Field("conta"); + usuario.Mobile = (x.Field("mobile") == null ? false : x.Field("mobile").ToString() == "1"); + usuario.Resultados = (x.Field("acessoresult") == null ? false : x.Field("acessoresult").ToString() == "1"); + usuario.InicioAcesso = x.Field("InicioAcesso"); + usuario.FimAcesso = x.Field("FimAcesso"); + usuario.Cargo = x.Field("Cargo"); + usuario.FiltroInicial = new TipoFiltroCliente?((x.Field("FiltroInicial") == null ? TipoFiltroCliente.NomeSobrenome : x.Field("FiltroInicial"))); + nullable3 = x.Field("Dashboard"); + usuario.Dashboard = new bool?(nullable3.GetValueOrDefault(true)); + usuario.Banco = (x.Field("idcodigobanco") == null || !(x.Field("idcodigobanco").ToString() != "") ? null : Auxiliar.Banco.Find((Banco b) => (long)b.Id == long.Parse(x.Field("idcodigobanco").ToString()))); + usuario.Sexo = (x.Field("sexo") == null || !(x.Field("sexo").ToString() != "") ? Sexo.Masculino : int.Parse(x.Field("sexo").ToString())); + usuario.AdministradorCentralSegurado = (x.Field("AdmCentralSegurado") == null ? false : x.Field("AdmCentralSegurado")); + usuario.SsoId = x.Field("SsoId"); + return usuario; + }).ToList(); + } + + internal static List MapVendedor(this DataTable data) + { + return data.AsEnumerable().Select((DataRow x) => new Vendedor() + { + IdEmpresa = x.Field("idempresa").GetValueOrDefault((long)1), + Id = x.Field("idvendedor"), + Nome = x.Field("nome"), + Ativo = (x.Field("ativo") == null ? true : x.Field("ativo").ToString() == "1"), + Corretora = (x.Field("corretora") == null ? false : x.Field("corretora") == "1"), + TipoIncidenciaDesconto = (x.Field("tipoincidenciadesconto") == null ? TipoIncidenciaDesconto.Ambos : x.Field("tipoincidenciadesconto")), + Desconto = new decimal?((x.Field("desconto") == null ? decimal.Zero : x.Field("desconto") * new decimal(100, 0, 0, false, 2))), + Banco = (x.Field("idcodigobanco") == null ? null : Auxiliar.Banco.Find((Banco p) => p.Id == x.Field("idcodigobanco"))), + Agencia = x.Field("agencia"), + Conta = x.Field("conta"), + Documento = x.Field("cpfcnpj"), + TipoConta = (x.Field("idtipoconta") != null ? (Gestor.Model.Common.TipoConta)Enum.Parse(typeof(Gestor.Model.Common.TipoConta), x.Field("idtipoconta").ToString()) : Gestor.Model.Common.TipoConta.Nenhum), + TitularDocumento = x.Field("cpfcnpjtitular"), + TitularConta = x.Field("titularconta"), + Observacao = (x.Field("obs") == null ? "" : x.Field("obs").ToString()) + }).ToList(); + } + + internal static List MapVendedorParcela(DataTable data) + { + return data.AsEnumerable().Select((DataRow x) => { + VendedorParcela vendedorParcela = new VendedorParcela() + { + Id = x.Field("idvendedorparcela"), + Vendedor = Auxiliar.Vendedores.Find((Vendedor v) => v.Id == x.Field("idvendedor")), + Documento = new Documento() + { + Id = x.Field("iddocumento") + }, + Parcela = x.MapParcela(), + Repasse = (x.Field("idrepasse").HasValue ? Auxiliar.Repasses.Find((Repasse v) => v.Id == x.Field("idrepasse")) : null), + TipoVendedor = Auxiliar.TipoVendedores.Find((TipoVendedor v) => v.Id == x.Field("idtipovendedor")) + }; + decimal? nullable = x.Field("vlrrep"); + vendedorParcela.ValorRepasse = new decimal?(nullable.GetValueOrDefault()); + nullable = x.Field("vrep"); + vendedorParcela.PorcentagemRepasse = new decimal?(nullable.GetValueOrDefault()); + vendedorParcela.DataPrePagamento = x.Field("dataprepagto"); + vendedorParcela.DataPagamento = x.Field("datapgt"); + vendedorParcela.ValorTotal = x.Field("valortotal"); + vendedorParcela.CoCorretagem = x.Field("cocorretagem").GetValueOrDefault(); + return vendedorParcela; + }).ToList(); + } + + public static Usuario ToUsuario(this UserSso userSso, long idEmpresa) + { + return new Usuario() + { + SsoId = userSso.Id, + IdEmpresa = idEmpresa, + Nome = userSso.Name, + Login = userSso.Username, + Senha = userSso.Password, + Administrador = false, + Excluido = userSso.IsDeleted, + PermissaoAggilizador = new long?((long)1) + }; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Aggilizador/VinculoDocumentoMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Aggilizador/VinculoDocumentoMap.cs new file mode 100644 index 0000000..b658266 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Aggilizador/VinculoDocumentoMap.cs @@ -0,0 +1,22 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Aggilizador; +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Aggilizador +{ + public class VinculoDocumentoMap : ClassMap + { + public VinculoDocumentoMap() + { + base.Table("VinculoDocumento"); + base.LazyLoad(); + base.Id((VinculoDocumentoDb x) => (object)x.Id).GeneratedBy.Identity(); + base.Map((VinculoDocumentoDb x) => (object)x.IdDocumento); + base.Map((VinculoDocumentoDb x) => (object)x.IdPropostaDigital); + base.Map((VinculoDocumentoDb x) => (object)x.IdApoliceDigital); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/AtividadeMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/AtividadeMap.cs new file mode 100644 index 0000000..b484da6 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/AtividadeMap.cs @@ -0,0 +1,21 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Common +{ + public class AtividadeMap : ClassMap + { + public AtividadeMap() + { + base.Table("atividade"); + base.LazyLoad(); + base.Id((AtividadeDb x) => (object)x.Id).GeneratedBy.Assigned().Column("idatividade"); + base.Map((AtividadeDb x) => x.Cnac).Column("cnac"); + base.Map((AtividadeDb x) => x.Nome).Column("atividade"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/AtualizacaoMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/AtualizacaoMap.cs new file mode 100644 index 0000000..e6d6199 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/AtualizacaoMap.cs @@ -0,0 +1,19 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Common; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Common +{ + public class AtualizacaoMap : ClassMap + { + public AtualizacaoMap() + { + base.Table("AtualizacaoDados"); + base.LazyLoad(); + base.Id((AtualizacaoDb x) => (object)x.IdArquivo).GeneratedBy.Assigned().Column("IdArquivo"); + base.Map((AtualizacaoDb x) => (object)x.DataAtualizacao).Column("DataAtualizacao").Not.Nullable(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/BancoMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/BancoMap.cs new file mode 100644 index 0000000..84e8420 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/BancoMap.cs @@ -0,0 +1,21 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Common; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Common +{ + public class BancoMap : ClassMap + { + public BancoMap() + { + base.Table("codigobanco"); + base.LazyLoad(); + base.Id((BancoDb x) => (object)x.Id).GeneratedBy.Assigned().Column("idcodigobanco"); + base.Map((BancoDb x) => (object)x.Codigo).Column("codigo"); + base.Map((BancoDb x) => x.Nome).Column("nomebanco"); + base.Map((BancoDb x) => x.Site).Column("paginainternet"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/ControleArquivoDigitalMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/ControleArquivoDigitalMap.cs new file mode 100644 index 0000000..f65b72f --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/ControleArquivoDigitalMap.cs @@ -0,0 +1,21 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Common +{ + public class ControleArquivoDigitalMap : ClassMap + { + public ControleArquivoDigitalMap() + { + base.Table("controledbad"); + base.LazyLoad(); + base.Id((ControleArquivoDigitalDb x) => (object)x.Id).GeneratedBy.Identity().Column("idcontroledbad"); + base.Map((ControleArquivoDigitalDb x) => x.Catalogo).Column("bdname"); + base.Map((ControleArquivoDigitalDb x) => x.Tabela).Column("tabela"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/EmpresaMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/EmpresaMap.cs new file mode 100644 index 0000000..53d2e0c --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/EmpresaMap.cs @@ -0,0 +1,53 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Common +{ + public class EmpresaMap : ClassMap + { + public EmpresaMap() + { + base.Table("empresa"); + base.LazyLoad(); + base.Id((EmpresaDb x) => (object)x.Id).GeneratedBy.Identity().Column("idempresa"); + base.Map((EmpresaDb x) => x.Nome).Column("nome").Not.Nullable(); + base.Map((EmpresaDb x) => x.NomeSocial); + base.Map((EmpresaDb x) => x.Documento).Column("cgccpf"); + base.Map((EmpresaDb x) => x.Serial).Column("ns"); + base.Map((EmpresaDb x) => x.Cep).Column("cep"); + base.Map((EmpresaDb x) => x.Endereco).Column("endereco"); + base.Map((EmpresaDb x) => x.Numero).Column("numero"); + base.Map((EmpresaDb x) => x.Complemento).Column("complemento"); + base.Map((EmpresaDb x) => x.Bairro).Column("bairro"); + base.Map((EmpresaDb x) => x.Cidade).Column("cidade"); + base.Map((EmpresaDb x) => x.Estado).Column("uf"); + base.Map((EmpresaDb x) => x.Site).Column("site"); + base.Map((EmpresaDb x) => x.Email).Column("email"); + base.Map((EmpresaDb x) => (object)x.TipoTelefone1).CustomType(); + base.Map((EmpresaDb x) => x.PrimeiroPrefixo).Column("ddd"); + base.Map((EmpresaDb x) => x.PrimeiroTelefone).Column("telefone"); + base.Map((EmpresaDb x) => (object)x.TipoTelefone2).CustomType(); + base.Map((EmpresaDb x) => x.SegundoPrefixo).Column("ddd2"); + base.Map((EmpresaDb x) => x.SegundoTelefone).Column("telefone2"); + base.Map((EmpresaDb x) => (object)x.QuantidadeFuncionarios).Column("nfuncionarios"); + base.Map((EmpresaDb x) => x.QuantidadeFiliais).Column("unidade"); + base.Map((EmpresaDb x) => x.Responsavel).Column("nomeresponsavel"); + base.Map((EmpresaDb x) => x.EmailResponsavel).Column("emailresponsavel"); + base.Map((EmpresaDb x) => x.SenhaAdmin).Column("senhaadm"); + base.Map((EmpresaDb x) => x.Facebook); + base.Map((EmpresaDb x) => x.Instagram); + base.Map((EmpresaDb x) => x.Linkdin); + base.Map((EmpresaDb x) => x.Whatsapp); + base.Map((EmpresaDb x) => x.WhatsappSinistro); + base.Map((EmpresaDb x) => x.Twitter); + base.Map((EmpresaDb x) => x.Localizacao); + base.Map((EmpresaDb x) => x.Logo).CustomSqlType("varbinary(max)").Length(2147483647); + base.Map((EmpresaDb x) => x.LogoId); + base.Map((EmpresaDb x) => (object)x.MaxFileSize).Column("filesize"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/IndiceArquivoDigitalMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/IndiceArquivoDigitalMap.cs new file mode 100644 index 0000000..0ca7a29 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/IndiceArquivoDigitalMap.cs @@ -0,0 +1,47 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Common +{ + public class IndiceArquivoDigitalMap : ClassMap + { + public IndiceArquivoDigitalMap() + { + base.Table("newarquivodigital"); + base.LazyLoad(); + base.Id((IndiceArquivoDigitalDb x) => (object)x.Id).GeneratedBy.Identity().Column("idnewarquivodigital"); + base.Map((IndiceArquivoDigitalDb x) => (object)x.IdArquivoDigital).Column("idarquivodigital").Not.Nullable(); + base.Map((IndiceArquivoDigitalDb x) => x.BD).Column("banco"); + base.Map((IndiceArquivoDigitalDb x) => x.Descricao).Column("descricao"); + base.Map((IndiceArquivoDigitalDb x) => x.Extensao).Column("extension"); + base.Map((IndiceArquivoDigitalDb x) => (object)x.IdCliente).Column("idcliente"); + base.Map((IndiceArquivoDigitalDb x) => (object)x.IdDocumento).Column("iddocumento"); + base.Map((IndiceArquivoDigitalDb x) => (object)x.IdItem).Column("iditem"); + base.Map((IndiceArquivoDigitalDb x) => (object)x.IdParcela).Column("idparcela"); + base.Map((IndiceArquivoDigitalDb x) => (object)x.IdSinistro).Column("idsinistro"); + base.Map((IndiceArquivoDigitalDb x) => (object)x.IdSeguradora).Column("idciaseg"); + base.Map((IndiceArquivoDigitalDb x) => (object)x.IdVendedor).Column("idvendedor"); + base.Map((IndiceArquivoDigitalDb x) => (object)x.IdExtrato).Column("idextrato"); + base.Map((IndiceArquivoDigitalDb x) => (object)x.IdEmpresa).Column("idempresa"); + base.Map((IndiceArquivoDigitalDb x) => (object)x.IdLancamento).Column("idlancamen"); + base.Map((IndiceArquivoDigitalDb x) => (object)x.IdFornecedor).Column("idfornecedor"); + base.Map((IndiceArquivoDigitalDb x) => (object)x.IdProspeccao).Column("idvenctoaleatorio"); + base.Map((IndiceArquivoDigitalDb x) => (object)x.IdSocio).Column("idsocio"); + base.Map((IndiceArquivoDigitalDb x) => (object)x.IdTarefa); + base.Map((IndiceArquivoDigitalDb x) => (object)x.IdNotaFiscal); + base.Map((IndiceArquivoDigitalDb x) => (object)x.IdEstipulante); + base.Map((IndiceArquivoDigitalDb x) => (object)x.Excluido).Column("excluido").CustomType(); + base.Map((IndiceArquivoDigitalDb x) => (object)x.IdUsuario).Column("idusuarioarquivo"); + base.Map((IndiceArquivoDigitalDb x) => (object)x.UsuarioCriacao).Column("usuariocriacao"); + base.Map((IndiceArquivoDigitalDb x) => (object)x.UsuarioAtualizacao).Column("usuarioalteracao"); + base.Map((IndiceArquivoDigitalDb x) => (object)x.DataCriacao).Column("datacriacao"); + base.Map((IndiceArquivoDigitalDb x) => (object)x.DataAtualizacao).Column("dataalteracao"); + base.Map((IndiceArquivoDigitalDb x) => (object)x.AzureGuid); + base.Map((IndiceArquivoDigitalDb i) => i.AzureStorage).CustomType("AnsiString").Length(100).Default(string.Empty); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/ModeloMalaDiretaMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/ModeloMalaDiretaMap.cs new file mode 100644 index 0000000..bdd6a1a --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/ModeloMalaDiretaMap.cs @@ -0,0 +1,21 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Common +{ + public class ModeloMalaDiretaMap : ClassMap + { + public ModeloMalaDiretaMap() + { + base.Table("ModeloMalaDireta"); + base.LazyLoad(); + base.Id((ModeloMalaDiretaDb x) => (object)x.Id).GeneratedBy.Identity(); + base.Map((ModeloMalaDiretaDb x) => x.Assunto); + base.Map((ModeloMalaDiretaDb x) => x.Corpo).CustomType("StringClob").CustomSqlType("varchar(MAX)"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/ProfissaoMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/ProfissaoMap.cs new file mode 100644 index 0000000..c42619d --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/ProfissaoMap.cs @@ -0,0 +1,22 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Common +{ + public class ProfissaoMap : ClassMap + { + public ProfissaoMap() + { + base.Table("profissao"); + base.LazyLoad(); + base.Id((ProfissaoDb x) => (object)x.Id).GeneratedBy.Assigned().Column("idprofissao"); + base.Map((ProfissaoDb x) => x.Codigo).Column("codigo"); + base.Map((ProfissaoDb x) => x.Nome).Column("nome"); + base.Map((ProfissaoDb x) => x.Aniversario).Column("dataaniversario"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/RegistroAcaoMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/RegistroAcaoMap.cs new file mode 100644 index 0000000..f60ce6d --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/RegistroAcaoMap.cs @@ -0,0 +1,31 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Common +{ + public class RegistroAcaoMap : ClassMap + { + public RegistroAcaoMap() + { + base.Table("RegistroAcao"); + base.LazyLoad(); + base.Id((RegistroAcaoDb x) => (object)x.Id).GeneratedBy.Identity(); + base.References((RegistroAcaoDb x) => x.Usuario).Column("IdUsuario").Fetch.Join(); + base.Map((RegistroAcaoDb x) => (object)x.EntidadeId); + base.Map((RegistroAcaoDb x) => (object)x.Tela).CustomType(); + base.Map((RegistroAcaoDb x) => (object)x.Relatorio).CustomType(); + base.Map((RegistroAcaoDb x) => (object)x.DataHora); + base.Map((RegistroAcaoDb x) => x.Descricao).Length(1000); + base.Map((RegistroAcaoDb x) => x.Observacao).Length(4001); + base.Map((RegistroAcaoDb x) => x.NomeMaquina); + base.Map((RegistroAcaoDb x) => x.UsuarioMaquina); + base.Map((RegistroAcaoDb x) => x.Ip); + base.Map((RegistroAcaoDb x) => x.Versao); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/RegistroLogMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/RegistroLogMap.cs new file mode 100644 index 0000000..3e670da --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/RegistroLogMap.cs @@ -0,0 +1,31 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Common +{ + public class RegistroLogMap : ClassMap + { + public RegistroLogMap() + { + base.Table("RegistroLog"); + base.LazyLoad(); + base.Id((RegistroLogDb x) => (object)x.Id).GeneratedBy.Identity(); + base.Map((RegistroLogDb x) => (object)x.EntidadeId).Not.Nullable(); + base.Map((RegistroLogDb x) => (object)x.Acao).CustomType(); + base.Map((RegistroLogDb x) => (object)x.Tela).CustomType(); + base.Map((RegistroLogDb x) => x.Versao); + base.Map((RegistroLogDb x) => (object)x.DataHora).Not.Nullable(); + base.Map((RegistroLogDb x) => x.Descricao).CustomType("StringClob").CustomSqlType("varchar(MAX)").Not.Nullable(); + base.References((RegistroLogDb x) => x.Usuario).Column("IdUsuario").Fetch.Join(); + base.Map((RegistroLogDb x) => x.NomeMaquina); + base.Map((RegistroLogDb x) => x.UsuarioMaquina); + base.Map((RegistroLogDb x) => x.Ip); + base.Map((RegistroLogDb x) => (object)x.ModeloNovo).Default("0"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/SocioMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/SocioMap.cs new file mode 100644 index 0000000..a7276ba --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Common/SocioMap.cs @@ -0,0 +1,25 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Common +{ + public class SocioMap : ClassMap + { + public SocioMap() + { + base.Table("socio"); + base.LazyLoad(); + base.Id((SocioDb x) => (object)x.Id).GeneratedBy.Identity().Column("idsocio"); + base.Map((SocioDb x) => (object)x.IdEmpresa).Column("idempresa").Not.Nullable(); + base.Map((SocioDb x) => (object)x.Excluido).Column("excluido").Not.Nullable().CustomType(); + base.Map((SocioDb x) => x.Nome).Column("nome").Not.Nullable(); + base.Map((SocioDb x) => x.Email).Column("email"); + base.Map((SocioDb x) => x.Prefixo).Column("ddd"); + base.Map((SocioDb x) => x.Telefone).Column("telefone"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Configuracoes/ConfiguracaoSistemaMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Configuracoes/ConfiguracaoSistemaMap.cs new file mode 100644 index 0000000..8c66a19 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Configuracoes/ConfiguracaoSistemaMap.cs @@ -0,0 +1,20 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Configuracoes; +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Configuracoes +{ + public class ConfiguracaoSistemaMap : ClassMap + { + public ConfiguracaoSistemaMap() + { + base.Table("ConfigSistema"); + base.LazyLoad(); + base.Id((ConfiguracaoSistemaDb x) => (object)x.Id).GeneratedBy.Identity().Column("Id"); + base.Map((ConfiguracaoSistemaDb x) => (object)x.Configuracao).CustomType().Column("codigo").Not.Nullable(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/AgendaEmailMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/AgendaEmailMap.cs new file mode 100644 index 0000000..67624d1 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/AgendaEmailMap.cs @@ -0,0 +1,21 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Ferramentas +{ + public class AgendaEmailMap : ClassMap + { + public AgendaEmailMap() + { + base.Table("agendaemail"); + base.LazyLoad(); + base.Id((AgendaEmailDb x) => (object)x.Id).GeneratedBy.Identity().Column("idagendaemail"); + base.References((AgendaEmailDb x) => x.Agenda).Column("idagenda").Not.Nullable().Fetch.Join(); + base.Map((AgendaEmailDb x) => x.Email).Column("email").Not.Nullable(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/AgendaMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/AgendaMap.cs new file mode 100644 index 0000000..e70b806 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/AgendaMap.cs @@ -0,0 +1,28 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Ferramentas +{ + public class AgendaMap : ClassMap + { + public AgendaMap() + { + base.Table("agenda"); + base.LazyLoad(); + base.Id((AgendaDb x) => (object)x.Id).GeneratedBy.Identity().Column("idagenda"); + base.Map((AgendaDb x) => x.Nome).Column("nome").Not.Nullable(); + base.Map((AgendaDb x) => x.Endereco).Column("endereco"); + base.Map((AgendaDb x) => x.Cep).Column("cep"); + base.Map((AgendaDb x) => x.Numero).Column("numero"); + base.Map((AgendaDb x) => x.Complemento).Column("complemento"); + base.Map((AgendaDb x) => x.Bairro).Column("bairro"); + base.Map((AgendaDb x) => x.Cidade).Column("cidade"); + base.Map((AgendaDb x) => x.Estado).Column("estado"); + base.Map((AgendaDb x) => x.Observacao).Column("observacao").CustomType("StringClob").CustomSqlType("varchar(MAX)"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/AgendaTelefoneMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/AgendaTelefoneMap.cs new file mode 100644 index 0000000..a08d55e --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/AgendaTelefoneMap.cs @@ -0,0 +1,24 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Ferramentas +{ + public class AgendaTelefoneMap : ClassMap + { + public AgendaTelefoneMap() + { + base.Table("agendatelefone"); + base.LazyLoad(); + base.Id((AgendaTelefoneDb x) => (object)x.Id).GeneratedBy.Identity().Column("idagendatelefone"); + base.References((AgendaTelefoneDb x) => x.Agenda).Column("idagenda").Not.Nullable().Fetch.Join(); + base.Map((AgendaTelefoneDb x) => (object)x.Tipo).CustomType().Column("tipo"); + base.Map((AgendaTelefoneDb x) => x.Prefixo).Column("ddd"); + base.Map((AgendaTelefoneDb x) => x.Numero).Column("fone").Not.Nullable(); + base.Map((AgendaTelefoneDb x) => x.Observacao).Column("observacao").CustomType("StringClob").CustomSqlType("varchar(MAX)"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/CategoriaTarefaMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/CategoriaTarefaMap.cs new file mode 100644 index 0000000..b0cd7d1 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/CategoriaTarefaMap.cs @@ -0,0 +1,20 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Ferramentas +{ + public class CategoriaTarefaMap : ClassMap + { + public CategoriaTarefaMap() + { + base.Table("CategoriaTarefa"); + base.LazyLoad(); + base.Id((CategoriaTarefaDb x) => (object)x.Id).GeneratedBy.Identity(); + base.Map((CategoriaTarefaDb x) => x.Descricao); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/CredencialMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/CredencialMap.cs new file mode 100644 index 0000000..d7cff32 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/CredencialMap.cs @@ -0,0 +1,34 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Ferramentas +{ + public class CredencialMap : ClassMap + { + public CredencialMap() + { + base.Table("enviosmtp"); + base.LazyLoad(); + base.Id((CredencialDb x) => (object)x.Id).GeneratedBy.Identity().Column("idenviosmtp"); + base.Map((CredencialDb x) => (object)x.IdEmpresa).Column("idempresa").Not.Nullable(); + base.Map((CredencialDb x) => (object)x.IdUsuario).Column("idusuario").Not.Nullable(); + base.Map((CredencialDb x) => x.Header); + base.Map((CredencialDb x) => (object)x.Tipo).CustomType(); + base.Map((CredencialDb x) => x.Descricao).Column("nome"); + base.Map((CredencialDb x) => x.Email).Column("email"); + base.Map((CredencialDb x) => x.Dominio).Column("server"); + base.Map((CredencialDb x) => (object)x.Porta).Column("port"); + base.Map((CredencialDb x) => x.Usuario).Column("credential"); + base.Map((CredencialDb x) => x.Senha).Column("senha"); + base.Map((CredencialDb x) => (object)x.Seguro).Column("ssl").CustomType(); + base.Map((CredencialDb x) => x.Cabecalho).Column("cabecalho").Length(4001); + base.Map((CredencialDb x) => x.Assinatura).Column("assinatura").Length(4001); + base.Map((CredencialDb x) => x.Replyto); + base.Map((CredencialDb x) => (object)x.Excluido); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/FaseMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/FaseMap.cs new file mode 100644 index 0000000..4be2384 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/FaseMap.cs @@ -0,0 +1,23 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Ferramentas +{ + public class FaseMap : ClassMap + { + public FaseMap() + { + base.Table("Fase"); + base.LazyLoad(); + base.Id((FaseDb x) => (object)x.Id).GeneratedBy.Identity(); + base.References((FaseDb x) => x.Trilha).Column("IdTrilha").Not.Nullable(); + base.Map((FaseDb x) => x.Titulo); + base.Map((FaseDb x) => x.Descricao); + base.Map((FaseDb x) => (object)x.Expiracao); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/ImpostoMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/ImpostoMap.cs new file mode 100644 index 0000000..4cce11b --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/ImpostoMap.cs @@ -0,0 +1,27 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Ferramentas +{ + public class ImpostoMap : ClassMap + { + public ImpostoMap() + { + base.Table("Imposto"); + base.LazyLoad(); + base.Id((ImpostoDb x) => (object)x.Id).GeneratedBy.Identity(); + base.References((ImpostoDb x) => x.Seguradora).Column("idciaseg").NotFound.Ignore().Fetch.Join(); + base.References((ImpostoDb x) => x.Ramo).Column("idramo").NotFound.Ignore().Fetch.Join(); + base.Map((ImpostoDb x) => (object)x.Ir).Not.Nullable(); + base.Map((ImpostoDb x) => (object)x.Iss).Not.Nullable(); + base.Map((ImpostoDb x) => (object)x.Outros).Not.Nullable(); + base.Map((ImpostoDb x) => (object)x.Desconto).Not.Nullable(); + base.Map((ImpostoDb x) => (object)x.Ativo).Not.Nullable().Default("1"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/LogEmailMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/LogEmailMap.cs new file mode 100644 index 0000000..1bd1140 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/LogEmailMap.cs @@ -0,0 +1,34 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Ferramentas +{ + public class LogEmailMap : ClassMap + { + public LogEmailMap() + { + base.Table("LogEmail"); + base.LazyLoad(); + base.Id((LogEmailDb x) => (object)x.Id).GeneratedBy.Identity(); + base.References((LogEmailDb x) => x.Credencial); + base.References((LogEmailDb x) => x.Usuario); + base.Map((LogEmailDb x) => (object)x.Tela).CustomType(); + base.Map((LogEmailDb x) => (object)x.Data); + base.Map((LogEmailDb x) => x.Destinatarios).CustomType("StringClob").CustomSqlType("varchar(MAX)"); + base.Map((LogEmailDb x) => x.Assunto).CustomType("StringClob").CustomSqlType("varchar(MAX)"); + base.Map((LogEmailDb x) => (object)x.EntityId); + base.Map((LogEmailDb x) => x.Cco).CustomType("StringClob").CustomSqlType("varchar(MAX)"); + base.Map((LogEmailDb x) => x.Corpo).CustomType("StringClob").CustomSqlType("varchar(MAX)"); + base.Map((LogEmailDb x) => x.Anexos).CustomType("StringClob").CustomSqlType("varchar(MAX)"); + base.Map((LogEmailDb x) => x.Versao); + base.Map((LogEmailDb x) => x.NomeMaquina); + base.Map((LogEmailDb x) => x.UsuarioMaquina); + base.Map((LogEmailDb x) => x.Ip); + base.Map((LogEmailDb x) => (object)x.Relatorio).CustomType(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/NotaFiscalMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/NotaFiscalMap.cs new file mode 100644 index 0000000..3782c71 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/NotaFiscalMap.cs @@ -0,0 +1,30 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Ferramentas +{ + public class NotaFiscalMap : ClassMap + { + public NotaFiscalMap() + { + base.Table("NotaFiscal"); + base.LazyLoad(); + base.References((NotaFiscalDb x) => x.Seguradora).Column("IdSeguradora"); + base.References((NotaFiscalDb x) => x.Estipulante).Column("IdEstipulante").Fetch.Join().NotFound.Ignore(); + base.Id((NotaFiscalDb x) => (object)x.Id).GeneratedBy.Identity(); + base.Map((NotaFiscalDb x) => (object)x.IdExtrato); + base.Map((NotaFiscalDb x) => (object)x.Iss); + base.Map((NotaFiscalDb x) => (object)x.ValorLiquido); + base.Map((NotaFiscalDb x) => (object)x.ValorBruto); + base.Map((NotaFiscalDb x) => (object)x.Data); + base.Map((NotaFiscalDb x) => x.Obs).CustomSqlType("varchar(MAX)"); + base.Map((NotaFiscalDb x) => x.Extrato).CustomSqlType("varchar(100)"); + base.Map((NotaFiscalDb x) => (object)x.Ir); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/OrigemClienteMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/OrigemClienteMap.cs new file mode 100644 index 0000000..8366f28 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/OrigemClienteMap.cs @@ -0,0 +1,23 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Ferramentas +{ + internal class OrigemClienteMap : ClassMap + { + public OrigemClienteMap() + { + base.Table("origemcliente"); + base.LazyLoad(); + base.Id((OrigemClienteDb x) => (object)x.Id).Column("idorigemcliente").GeneratedBy.Identity(); + base.References((OrigemClienteDb x) => x.Cliente).Column("idcliente").Fetch.Join(); + base.Map((OrigemClienteDb x) => (object)x.TipoOrigem).Column("idtipoorigemcli"); + base.Map((OrigemClienteDb x) => x.Nome).Length(100); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/ReciboMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/ReciboMap.cs new file mode 100644 index 0000000..36ded4b --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/ReciboMap.cs @@ -0,0 +1,28 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Ferramentas +{ + public class ReciboMap : ClassMap + { + public ReciboMap() + { + base.Table("recibo"); + base.LazyLoad(); + base.Id((ReciboDb x) => (object)x.Id).GeneratedBy.Identity().Column("idrecibo"); + base.Map((ReciboDb x) => (object)x.Tipo).Column("IdTipoRecibo").CustomType(); + base.Map((ReciboDb x) => (object)x.Pagamento).Column("idtipopagto").CustomType(); + base.Map((ReciboDb x) => (object)x.Valor).Column("valor").Not.Nullable(); + base.Map((ReciboDb x) => (object)x.DataRecibo).Column("datarecibo").Not.Nullable(); + base.Map((ReciboDb x) => x.Pagante).Column("sacado"); + base.Map((ReciboDb x) => x.DocumentoPagante).Column("cpfcnpj"); + base.Map((ReciboDb x) => x.Recebedor).Column("recebedor"); + base.Map((ReciboDb x) => x.DocumentoRecebedor).Column("cpfcnpjrecebedor"); + base.Map((ReciboDb x) => x.Referente).Column("referente").Not.Nullable(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/ResponsavelTarefaMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/ResponsavelTarefaMap.cs new file mode 100644 index 0000000..82d9578 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/ResponsavelTarefaMap.cs @@ -0,0 +1,22 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Ferramentas +{ + public class ResponsavelTarefaMap : ClassMap + { + public ResponsavelTarefaMap() + { + base.Table("ResponsavelTarefa"); + base.LazyLoad(); + base.Id((ResponsavelTarefaDb x) => (object)x.Id).GeneratedBy.Identity(); + base.References((ResponsavelTarefaDb x) => x.Usuario).Not.Nullable().Fetch.Join(); + base.Map((ResponsavelTarefaDb x) => (object)x.IdTarefa).Not.Nullable(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/StatusProspeccaoMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/StatusProspeccaoMap.cs new file mode 100644 index 0000000..c11a811 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/StatusProspeccaoMap.cs @@ -0,0 +1,23 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Ferramentas +{ + public class StatusProspeccaoMap : ClassMap + { + public StatusProspeccaoMap() + { + base.Table("StatusProspeccao"); + base.LazyLoad(); + base.Id((StatusDeProspeccaoDb x) => (object)x.Id).GeneratedBy.Identity(); + base.Map((StatusDeProspeccaoDb x) => x.Nome); + base.Map((StatusDeProspeccaoDb x) => x.Descricao).CustomType("StringClob").CustomSqlType("nvarchar(max)"); + base.Map((StatusDeProspeccaoDb x) => (object)x.Ativo); + base.Map((StatusDeProspeccaoDb x) => (object)x.Excluido); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/TarefaMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/TarefaMap.cs new file mode 100644 index 0000000..d4ebb97 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/TarefaMap.cs @@ -0,0 +1,38 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Ferramentas +{ + public class TarefaMap : ClassMap + { + public TarefaMap() + { + base.Table("Tarefa"); + base.LazyLoad(); + base.Id((TarefaDb x) => (object)x.Id).GeneratedBy.Identity(); + base.Map((TarefaDb x) => (object)x.IdCliente); + base.Map((TarefaDb x) => x.Cliente); + base.References((TarefaDb x) => x.Trilha).Column("IdTrilha"); + base.References((TarefaDb x) => x.Fase).Column("IdFase"); + base.References((TarefaDb x) => x.Usuario).Column("IdUsuario"); + base.References((TarefaDb x) => x.UsuarioCadastro).Column("IdUsuarioCadastro"); + base.References((TarefaDb x) => x.Categoria).Column("IdCategoria").Fetch.Join(); + base.References((TarefaDb x) => x.TipoDeTarefa).Column("IdTipoTarefa"); + base.Map((TarefaDb x) => (object)x.Entidade).CustomType(); + base.Map((TarefaDb x) => (object)x.IdEntidade); + base.Map((TarefaDb x) => x.Titulo); + base.Map((TarefaDb x) => x.Descricao).CustomType("StringClob").CustomSqlType("nvarchar(max)"); + base.Map((TarefaDb x) => x.DescricaoInterna).Column("descricaointerna").CustomType("StringClob").CustomSqlType("nvarchar(max)"); + base.Map((TarefaDb x) => x.Referencia); + base.Map((TarefaDb x) => (object)x.Agendamento); + base.Map((TarefaDb x) => (object)x.Conclusao); + base.Map((TarefaDb x) => (object)x.Status).CustomType(); + base.Map((TarefaDb x) => (object)x.Restrito); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/TipoTarefaMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/TipoTarefaMap.cs new file mode 100644 index 0000000..19c52b0 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/TipoTarefaMap.cs @@ -0,0 +1,23 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Ferramentas +{ + public class TipoTarefaMap : ClassMap + { + public TipoTarefaMap() + { + base.Table("TipoTarefa"); + base.LazyLoad(); + base.Id((TipoDeTarefaDb x) => (object)x.Id).GeneratedBy.Identity(); + base.Map((TipoDeTarefaDb x) => x.Nome); + base.Map((TipoDeTarefaDb x) => x.Descricao).CustomType("StringClob").CustomSqlType("nvarchar(max)"); + base.Map((TipoDeTarefaDb x) => (object)x.Ativo); + base.Map((TipoDeTarefaDb x) => (object)x.Excluido); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/TrilhaMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/TrilhaMap.cs new file mode 100644 index 0000000..0a58cc8 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/TrilhaMap.cs @@ -0,0 +1,24 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Ferramentas +{ + public class TrilhaMap : ClassMap + { + public TrilhaMap() + { + base.Table("Trilha"); + base.LazyLoad(); + base.Id((TrilhaDb x) => (object)x.Id).GeneratedBy.Identity(); + base.Map((TrilhaDb x) => x.Titulo); + base.Map((TrilhaDb x) => x.Descricao); + base.Map((TrilhaDb x) => (object)x.Intervalo); + base.Map((TrilhaDb x) => (object)x.Ativo); + base.Map((TrilhaDb x) => (object)x.Tipo); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/VinculoRepasseMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/VinculoRepasseMap.cs new file mode 100644 index 0000000..d259e7e --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Ferramentas/VinculoRepasseMap.cs @@ -0,0 +1,24 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Ferramentas +{ + public class VinculoRepasseMap : ClassMap + { + public VinculoRepasseMap() + { + base.Table("VinculoRepasse"); + base.LazyLoad(); + base.Id((VinculoRepasseDb x) => (object)x.Id).GeneratedBy.Identity(); + base.Map((VinculoRepasseDb x) => (object)x.IdRepasse).Not.Nullable(); + base.References((VinculoRepasseDb x) => x.TipoVendedor).Not.Nullable().Fetch.Join(); + base.References((VinculoRepasseDb x) => x.RepasseVinculo).Not.Nullable().Fetch.Join(); + base.References((VinculoRepasseDb x) => x.TipoVendedorVinculo).Not.Nullable().Fetch.Join(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/BancosContasMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/BancosContasMap.cs new file mode 100644 index 0000000..c04a524 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/BancosContasMap.cs @@ -0,0 +1,27 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Entities.Financeiro; +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Financeiro +{ + public class BancosContasMap : ClassMap + { + public BancosContasMap() + { + base.Table("conta"); + base.LazyLoad(); + base.Id((BancosContasDb x) => (object)x.Id).GeneratedBy.Identity().Column("idconta"); + base.References((BancosContasDb x) => x.Banco).Column("idcodigobanco").Fetch.Join(); + base.Map((BancosContasDb x) => (object)x.IdEmpresa).Column("idempresa"); + base.Map((BancosContasDb x) => x.Descricao).Column("descricao"); + base.Map((BancosContasDb x) => x.Agencia).Column("agencia"); + base.Map((BancosContasDb x) => x.Conta).Column("conta"); + base.Map((BancosContasDb x) => x.Observacao).Column("obs").CustomType("StringClob").CustomSqlType("varchar(MAX)"); + base.Map((BancosContasDb x) => (object)x.Ativo).Column("ativo").CustomType(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/CentroMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/CentroMap.cs new file mode 100644 index 0000000..c59e823 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/CentroMap.cs @@ -0,0 +1,22 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Financeiro; +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Financeiro +{ + public class CentroMap : ClassMap + { + public CentroMap() + { + base.Table("centro"); + base.LazyLoad(); + base.Id((CentroDb x) => (object)x.Id).GeneratedBy.Identity().Column("idcentro"); + base.Map((CentroDb x) => x.Descricao).Column("descricao"); + base.Map((CentroDb x) => (object)x.Ativo).Column("ativo").CustomType(); + base.Map((CentroDb x) => (object)x.IdEmpresa).Column("idempresa"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/ControleFinanceiroMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/ControleFinanceiroMap.cs new file mode 100644 index 0000000..e5e420c --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/ControleFinanceiroMap.cs @@ -0,0 +1,24 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Financeiro; +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Financeiro +{ + public class ControleFinanceiroMap : ClassMap + { + public ControleFinanceiroMap() + { + base.Table("cfinan"); + base.LazyLoad(); + base.Id((ControleFinanceiroDb x) => (object)x.Id).GeneratedBy.Identity().Column("idcfinan"); + base.References((ControleFinanceiroDb x) => x.Fornecedor).Column("idfornecedor").NotFound.Ignore().Fetch.Join(); + base.References((ControleFinanceiroDb x) => x.Plano).Column("idcplanos").NotFound.Ignore().Fetch.Join(); + base.References((ControleFinanceiroDb x) => x.Centro).Column("idcentro").NotFound.Ignore().Fetch.Join(); + base.Map((ControleFinanceiroDb x) => x.Historico).Column("historico"); + base.Map((ControleFinanceiroDb x) => (object)x.Parcelas).Column("parcela"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/FornecedorMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/FornecedorMap.cs new file mode 100644 index 0000000..431c4a8 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/FornecedorMap.cs @@ -0,0 +1,42 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Financeiro; +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Financeiro +{ + public class FornecedorMap : ClassMap + { + public FornecedorMap() + { + base.Table("fornecedor"); + base.LazyLoad(); + base.Id((FornecedorDb x) => (object)x.Id).GeneratedBy.Identity().Column("idfornecedor"); + base.Map((FornecedorDb x) => (object)x.IdEmpresa).Column("idempresa").Not.Nullable(); + base.Map((FornecedorDb x) => (object)x.IdCentro).Column("idcentro"); + base.Map((FornecedorDb x) => (object)x.IdConta).Column("idconta"); + base.Map((FornecedorDb x) => (object)x.IdPlano).Column("idcplanos"); + base.Map((FornecedorDb x) => (object)x.TipoPagamento).CustomType().Column("idtipopagto"); + base.Map((FornecedorDb x) => x.Nome).Column("nome"); + base.Map((FornecedorDb x) => x.Documento).Column("cpfcnpj"); + base.Map((FornecedorDb x) => x.Cep).Column("cep"); + base.Map((FornecedorDb x) => x.Cidade).Column("cidade"); + base.Map((FornecedorDb x) => x.Estado).Column("uf"); + base.Map((FornecedorDb x) => x.Bairro).Column("bairro"); + base.Map((FornecedorDb x) => x.Endereco).Column("endereco"); + base.Map((FornecedorDb x) => x.Numero).Column("numero"); + base.Map((FornecedorDb x) => x.Complemento).Column("complemento"); + base.Map((FornecedorDb x) => (object)x.TipoTelefone1).CustomType().Column("idfonetipo1"); + base.Map((FornecedorDb x) => x.Prefixo1).Column("ddd1"); + base.Map((FornecedorDb x) => x.Telefone1).Column("fone1"); + base.Map((FornecedorDb x) => (object)x.TipoTelefone2).CustomType().Column("idfonetipo2"); + base.Map((FornecedorDb x) => x.Prefixo2).Column("ddd2"); + base.Map((FornecedorDb x) => x.Telefone2).Column("fone2"); + base.Map((FornecedorDb x) => (object)x.Ativo).Column("Ativo"); + base.Map((FornecedorDb x) => x.Email).Column("email"); + base.Map((FornecedorDb x) => x.Observacao).CustomType("StringClob").CustomSqlType("varchar(MAX)"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/LancamentoMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/LancamentoMap.cs new file mode 100644 index 0000000..baf3ce7 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/LancamentoMap.cs @@ -0,0 +1,36 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Financeiro; +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Financeiro +{ + public class LancamentoMap : ClassMap + { + public LancamentoMap() + { + base.Table("lancamen"); + base.LazyLoad(); + base.Id((LancamentoDb x) => (object)x.Id).GeneratedBy.Identity().Column("idlancamen"); + base.References((LancamentoDb x) => x.Controle).Column("idcfinan").Fetch.Join(); + base.References((LancamentoDb x) => x.Conta).Column("idconta").Fetch.Join(); + base.Map((LancamentoDb x) => (object)x.TipoPagamento).CustomType>().Column("idtipopagto"); + base.Map((LancamentoDb x) => x.Historico).Column("historico"); + base.Map((LancamentoDb x) => x.Documento).Column("documento"); + base.Map((LancamentoDb x) => x.Complemento).Column("complemento"); + base.Map((LancamentoDb x) => x.Competencia).Column("competencia"); + base.Map((LancamentoDb x) => (object)x.Parcela).Column("parcela"); + base.Map((LancamentoDb x) => (object)x.Valor).Column("vlrpre"); + base.Map((LancamentoDb x) => (object)x.Vencimento).Column("dtpre"); + base.Map((LancamentoDb x) => (object)x.Baixa).Column("dtbaixa"); + base.Map((LancamentoDb x) => (object)x.ValorPago).Column("vlrbaixa"); + base.Map((LancamentoDb x) => (object)x.Pagamento).Column("dtpagto"); + base.Map((LancamentoDb x) => (object)x.Sinal).CustomType>().Column("sinal"); + base.Map((LancamentoDb x) => x.Observacao).Column("obs").CustomType("StringClob").CustomSqlType("varchar(MAX)"); + base.Map((LancamentoDb x) => x.CodigoBanco); + base.Map((LancamentoDb x) => (object)x.DataLancamento).Column("datacriacao"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/PlanoMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/PlanoMap.cs new file mode 100644 index 0000000..7017c7a --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/PlanoMap.cs @@ -0,0 +1,21 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Financeiro; +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Financeiro +{ + public class PlanoMap : ClassMap + { + public PlanoMap() + { + base.Table("cplano"); + base.LazyLoad(); + base.Id((PlanoDb x) => (object)x.Id).GeneratedBy.Identity().Column("idcplano"); + base.Map((PlanoDb x) => x.Descricao).Column("descricao"); + base.Map((PlanoDb x) => (object)x.Ativo).Column("ativo").CustomType(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/PlanosMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/PlanosMap.cs new file mode 100644 index 0000000..bbbbc2b --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/PlanosMap.cs @@ -0,0 +1,25 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Financeiro; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Financeiro +{ + public class PlanosMap : ClassMap + { + public PlanosMap() + { + base.Table("cplanos"); + base.LazyLoad(); + base.Id((PlanosDb x) => (object)x.Id).GeneratedBy.Identity().Column("idcplanos"); + base.References((PlanosDb x) => x.TipoConta).Column("idtipoconta"); + base.References((PlanosDb x) => x.Plano).Column("idcplano").Fetch.Join(); + base.Map((PlanosDb x) => x.Descricao).Column("descricao"); + base.Map((PlanosDb x) => (object)x.Sinal).Column("ctipo").CustomType>(); + base.Map((PlanosDb x) => (object)x.Ativo).Column("ativo").CustomType(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/SaldoMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/SaldoMap.cs new file mode 100644 index 0000000..1549efe --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/SaldoMap.cs @@ -0,0 +1,25 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Financeiro; +using Gestor.Infrastructure.Entities.Generic; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Financeiro +{ + public class SaldoMap : ClassMap + { + public SaldoMap() + { + base.Table("saldo"); + base.LazyLoad(); + base.Id((SaldoDb x) => (object)x.Id).GeneratedBy.Identity().Column("idsaldo"); + base.References((SaldoDb x) => x.Conta).Column("idconta").Fetch.Join(); + base.Map((SaldoDb x) => (object)x.ValorInicio).Column("vlrinicio"); + base.Map((SaldoDb x) => (object)x.DataInicio).Column("dtinicio"); + base.Map((SaldoDb x) => (object)x.ValorFinal).Column("vlrfim"); + base.Map((SaldoDb x) => (object)x.DataFinal).Column("dtfim"); + base.Map((SaldoDb x) => x.Extrato).Column("extrato").CustomType("StringClob").CustomSqlType("varchar(MAX)"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/TipoContaMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/TipoContaMap.cs new file mode 100644 index 0000000..6cfee28 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Financeiro/TipoContaMap.cs @@ -0,0 +1,21 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Financeiro +{ + public class TipoContaMap : ClassMap + { + public TipoContaMap() + { + base.Table("tipoconta"); + base.LazyLoad(); + base.Id((TipoContaDb x) => (object)x.Id).GeneratedBy.Identity().Column("idtipoconta"); + base.Map((TipoContaDb x) => x.Descricao).Column("descricao"); + base.Map((TipoContaDb x) => (object)x.Ativo).Column("ativo").CustomType(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Relatorios/ParametrosRelatorioMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Relatorios/ParametrosRelatorioMap.cs new file mode 100644 index 0000000..76ed6c0 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Relatorios/ParametrosRelatorioMap.cs @@ -0,0 +1,26 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Relatorios; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Relatorios +{ + public class ParametrosRelatorioMap : ClassMap + { + public ParametrosRelatorioMap() + { + base.Table("CamposRelatorios"); + base.LazyLoad(); + base.Id((ParametrosRelatorioDb x) => (object)x.Id).GeneratedBy.Identity(); + base.Map((ParametrosRelatorioDb x) => (object)x.IdUsuario).Not.Nullable(); + base.Map((ParametrosRelatorioDb x) => (object)x.Relatorio).CustomType().Not.Nullable(); + base.Map((ParametrosRelatorioDb x) => x.Campo).Not.Nullable(); + base.Map((ParametrosRelatorioDb x) => x.Header); + base.Map((ParametrosRelatorioDb x) => (object)x.Width); + base.Map((ParametrosRelatorioDb x) => x.Tipo); + base.Map((ParametrosRelatorioDb x) => (object)x.Ordem).Not.Nullable(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Relatorios/ParametrosTotalizacaoMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Relatorios/ParametrosTotalizacaoMap.cs new file mode 100644 index 0000000..8df6f71 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Relatorios/ParametrosTotalizacaoMap.cs @@ -0,0 +1,24 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Relatorios; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Relatorios +{ + public class ParametrosTotalizacaoMap : ClassMap + { + public ParametrosTotalizacaoMap() + { + base.Table("CamposTotalizacao"); + base.LazyLoad(); + base.Id((ParametrosTotalizacaoDb x) => (object)x.Id).GeneratedBy.Identity(); + base.Map((ParametrosTotalizacaoDb x) => (object)x.IdUsuario).Not.Nullable(); + base.Map((ParametrosTotalizacaoDb x) => (object)x.Ativa).Not.Nullable(); + base.Map((ParametrosTotalizacaoDb x) => x.Campo).Not.Nullable(); + base.Map((ParametrosTotalizacaoDb x) => x.Header).Not.Nullable(); + base.Map((ParametrosTotalizacaoDb x) => (object)x.Relatorio).CustomType().Not.Nullable(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/AdiantamentoMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/AdiantamentoMap.cs new file mode 100644 index 0000000..2f85316 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/AdiantamentoMap.cs @@ -0,0 +1,26 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class AdiantamentoMap : ClassMap + { + public AdiantamentoMap() + { + base.Table("adiantamento"); + base.LazyLoad(); + base.Id((AdiantamentoDb x) => (object)x.Id).GeneratedBy.Identity().Column("idadiantamento"); + base.References((AdiantamentoDb x) => x.Vendedor).Column("IdVendedor").Not.Nullable().Fetch.Join(); + base.Map((AdiantamentoDb x) => (object)x.TipoPagamento).CustomType().Column("idtipopagto"); + base.Map((AdiantamentoDb x) => x.Historico).Column("historico"); + base.Map((AdiantamentoDb x) => (object)x.Data).Column("data"); + base.Map((AdiantamentoDb x) => (object)x.Valor).Column("valor"); + base.Map((AdiantamentoDb x) => (object)x.Pago).Column("pago").CustomType(); + base.Map((AdiantamentoDb x) => (object)x.Pagamento); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/AeronauticoMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/AeronauticoMap.cs new file mode 100644 index 0000000..9e1ad15 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/AeronauticoMap.cs @@ -0,0 +1,35 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class AeronauticoMap : ClassMap + { + public AeronauticoMap() + { + base.Table("aeronautico"); + base.LazyLoad(); + base.Id((AeronauticoDb x) => (object)x.Id).GeneratedBy.Identity().Column("idaeronautico"); + base.References((AeronauticoDb x) => x.Item).Column("iditem").Not.Nullable().Fetch.Join(); + base.Map((AeronauticoDb x) => (object)x.Tipo).CustomType().Column("idtipoaeronautico").Not.Nullable(); + base.Map((AeronauticoDb x) => x.Fabricante).Column("fabricante").Not.Nullable(); + base.Map((AeronauticoDb x) => x.Modelo).Column("modelo").Not.Nullable(); + base.Map((AeronauticoDb x) => x.Serie).Column("serieregistro").Not.Nullable(); + base.Map((AeronauticoDb x) => x.Prefixo).Column("nomeprefixo").Not.Nullable(); + base.Map((AeronauticoDb x) => (object)x.Fabricacao).Column("anofab").Not.Nullable(); + base.Map((AeronauticoDb x) => (object)x.Tripulantes).Column("tripulantes").Not.Nullable(); + base.Map((AeronauticoDb x) => (object)x.Passageiros).Column("passageiros").Not.Nullable(); + base.Map((AeronauticoDb x) => x.MarinaAero).Column("marinaaero").Not.Nullable(); + base.Map((AeronauticoDb x) => (object)x.Peso).Column("peso"); + base.Map((AeronauticoDb x) => x.Certificado).Column("certificado"); + base.Map((AeronauticoDb x) => (object)x.Vistoria).Column("vistoria"); + base.Map((AeronauticoDb x) => x.Casco).Column("casco"); + base.Map((AeronauticoDb x) => x.Navegacao).Column("navegacao"); + base.Map((AeronauticoDb x) => x.Observacao).Column("obs").CustomType("StringClob").CustomSqlType("varchar(MAX)"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/AutoMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/AutoMap.cs new file mode 100644 index 0000000..0f11065 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/AutoMap.cs @@ -0,0 +1,51 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class AutoMap : ClassMap + { + public AutoMap() + { + base.Table("auto"); + base.LazyLoad(); + base.Id((AutoDb x) => (object)x.Id).GeneratedBy.Identity().Column("idauto"); + base.References((AutoDb x) => x.Item).Column("iditem").Not.Nullable().Fetch.Join(); + base.References((AutoDb x) => x.Fabricante).Column("idfabricante").NotFound.Ignore().Cascade.None(); + base.Map((AutoDb x) => (object)x.Combustivel).CustomType().Column("idcombustivel"); + base.Map((AutoDb x) => x.Fipe).Column("codfipe"); + base.Map((AutoDb x) => x.Modelo).Column("modelo"); + base.Map((AutoDb x) => (object)x.Categoria).CustomType>().Column("idcategoria"); + base.Map((AutoDb x) => (object)x.UsoVeiculo).CustomType(); + base.Map((AutoDb x) => x.Chassi).Column("chassi"); + base.Map((AutoDb x) => x.Placa).Column("placa").Not.Nullable(); + base.Map((AutoDb x) => x.AnoFabricacao).Column("anofab"); + base.Map((AutoDb x) => x.AnoModelo).Column("anomod"); + base.Map((AutoDb x) => x.Renavam).Column("renavam"); + base.Map((AutoDb x) => x.Capacidade).Column("capacidade"); + base.Map((AutoDb x) => x.Portas).Column("portas"); + base.Map((AutoDb x) => (object)x.Cor).CustomType().Column("idcor"); + base.Map((AutoDb x) => x.Observacao).Column("obs").CustomType("StringClob").CustomSqlType("varchar(MAX)"); + base.Map((AutoDb x) => x.RegiaoCirculacao).Column("regiaocirculacao"); + base.Map((AutoDb x) => (object)x.TipoCobertura).CustomType>().Column("idtipocobertura"); + base.Map((AutoDb x) => (object)x.TabelaReferencia).CustomType>().Column("idtabelareferencia"); + base.Map((AutoDb x) => (object)x.Bonus).Column("bonus"); + base.Map((AutoDb x) => (object)x.PorcentagemReferencia).Column("porcentagemreferencia"); + base.Map((AutoDb x) => (object)x.ValorDeterminado).Column("valordeterminado"); + base.Map((AutoDb x) => x.Ci).Column("ci"); + base.Map((AutoDb x) => x.CepPernoite).Column("ceppernoite"); + base.Map((AutoDb x) => (object)x.Financiado).Column("financiado").CustomType(); + base.Map((AutoDb x) => (object)x.ZeroKm).Column("zerokm").CustomType(); + base.Map((AutoDb x) => (object)x.Isencao).CustomType>().Column("isencao"); + base.Map((AutoDb x) => (object)x.Pcd).Column("pcd").CustomType(); + base.Map((AutoDb x) => (object)x.Correcao).CustomType>().Column("correcao"); + base.Map((AutoDb x) => (object)x.Rastreador).CustomType>().Default("0"); + base.Map((AutoDb x) => (object)x.Blindagem).CustomType().Column("blindagem"); + base.Map((AutoDb x) => (object)x.KitGas).Column("kitgas"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ClienteEmailMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ClienteEmailMap.cs new file mode 100644 index 0000000..89188e4 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ClienteEmailMap.cs @@ -0,0 +1,23 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class ClienteEmailMap : ClassMap + { + public ClienteEmailMap() + { + base.Table("climail"); + base.LazyLoad(); + base.Id((ClienteEmailDb x) => (object)x.Id).GeneratedBy.Identity().Column("idclimail"); + base.References((ClienteEmailDb x) => x.Cliente).Column("idcliente").Not.Nullable().Fetch.Join(); + base.Map((ClienteEmailDb x) => x.Email).Column("email").Not.Nullable(); + base.Map((ClienteEmailDb x) => x.Observacao).Column("obs").CustomType("StringClob").CustomSqlType("varchar(MAX)"); + base.Map((ClienteEmailDb x) => (object)x.Ordem).Column("ordem"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ClienteEnderecoMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ClienteEnderecoMap.cs new file mode 100644 index 0000000..9a39598 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ClienteEnderecoMap.cs @@ -0,0 +1,29 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class ClienteEnderecoMap : ClassMap + { + public ClienteEnderecoMap() + { + base.Table("cliendereco"); + base.LazyLoad(); + base.Id((ClienteEnderecoDb x) => (object)x.Id).GeneratedBy.Identity().Column("idcliend"); + base.References((ClienteEnderecoDb x) => x.Cliente).Column("idcliente").Not.Nullable().Fetch.Join(); + base.Map((ClienteEnderecoDb x) => x.Cep).Column("cep"); + base.Map((ClienteEnderecoDb x) => x.Endereco).Column("endereco"); + base.Map((ClienteEnderecoDb x) => x.Numero).Column("numero"); + base.Map((ClienteEnderecoDb x) => x.Complemento).Column("comp_end"); + base.Map((ClienteEnderecoDb x) => x.Bairro).Column("bairro"); + base.Map((ClienteEnderecoDb x) => x.Cidade).Column("cidade"); + base.Map((ClienteEnderecoDb x) => x.Estado).Column("uf"); + base.Map((ClienteEnderecoDb x) => (object)x.Ordem).Column("ordem"); + base.Map((ClienteEnderecoDb x) => x.Observacao).Column("obs").CustomType("StringClob").CustomSqlType("varchar(MAX)"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ClienteMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ClienteMap.cs new file mode 100644 index 0000000..9195651 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ClienteMap.cs @@ -0,0 +1,53 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class ClienteMap : ClassMap + { + public ClienteMap() + { + base.Table("cliente"); + base.LazyLoad(); + base.Id((ClienteDb x) => (object)x.Id).GeneratedBy.Identity().Column("idcliente"); + base.References((ClienteDb x) => x.Atividade).Column("idatividade").Fetch.Join().NotFound.Ignore(); + base.References((ClienteDb x) => x.Profissao).Column("idprofissao").Fetch.Join().NotFound.Ignore(); + base.References((ClienteDb x) => x.Banco).Column("idcodigobanco").Fetch.Join().NotFound.Ignore(); + base.Map((ClienteDb x) => (object)x.IdEmpresa).Column("idempresa").Not.Nullable(); + base.Map((ClienteDb x) => x.Nome).Column("nome").Not.Nullable(); + base.Map((ClienteDb x) => (object)x.Nascimento).Column("dtnasc"); + base.Map((ClienteDb x) => (object)x.Sexo).CustomType>().Column("sexo"); + base.Map((ClienteDb x) => (object)x.EstadoCivil).CustomType>().Column("estadocivi"); + base.Map((ClienteDb x) => x.Documento).Column("cgccpf"); + base.Map((ClienteDb x) => x.Identidade).Column("rg"); + base.Map((ClienteDb x) => x.Emissor).Column("emissor"); + base.Map((ClienteDb x) => x.EstadoEmissor).Column("rguf"); + base.Map((ClienteDb x) => (object)x.Expedicao).Column("rgexpedica"); + base.Map((ClienteDb x) => x.Habilitacao).Column("numehabili"); + base.Map((ClienteDb x) => (object)x.PrimeiraHabilitacao).Column("primehabil"); + base.Map((ClienteDb x) => (object)x.VencimentoHabilitacao).Column("venchabili"); + base.Map((ClienteDb x) => x.CategoriaHabilitacao).Column("cathabili"); + base.Map((ClienteDb x) => x.Cei).Column("cei"); + base.Map((ClienteDb x) => x.Pasta).Column("pasta"); + base.Map((ClienteDb x) => x.Agencia).Column("agencia"); + base.Map((ClienteDb x) => x.TipoConta).Column("tipoconta"); + base.Map((ClienteDb x) => x.Conta).Column("conta"); + base.Map((ClienteDb x) => (object)x.ClienteDesde).Column("clidesde"); + base.Map((ClienteDb x) => x.Observacao).Column("anotacoes").CustomType("StringClob").CustomSqlType("varchar(MAX)"); + base.Map((ClienteDb x) => (object)x.Excluido).Column("excluido").CustomType(); + base.Map((ClienteDb x) => (object)x.DocumentoPrincipal).CustomType().Column("documentoprincipal"); + base.Map((ClienteDb x) => x.Rne).Column("rne"); + base.Map((ClienteDb x) => (object)x.Falecido).Column("Falecido"); + base.Map((ClienteDb x) => (object)x.RendaMensal).Column("RendaMensal"); + base.Map((ClienteDb x) => x.Caepf).Column("caepf"); + base.Map((ClienteDb x) => (object)x.MalaDireta).Default("1"); + base.Map((ClienteDb c) => (object)c.EstaNaCentralSegurado); + base.Map((ClienteDb x) => x.NomeSocialRg).Column("nomesocialRg"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ClienteTelefoneMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ClienteTelefoneMap.cs new file mode 100644 index 0000000..55ed216 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ClienteTelefoneMap.cs @@ -0,0 +1,25 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class ClienteTelefoneMap : ClassMap + { + public ClienteTelefoneMap() + { + base.Table("clitelefone"); + base.LazyLoad(); + base.Id((ClienteTelefoneDb x) => (object)x.Id).GeneratedBy.Identity().Column("idclitelefone"); + base.References((ClienteTelefoneDb x) => x.Cliente).Column("idcliente").Not.Nullable().Fetch.Join(); + base.Map((ClienteTelefoneDb x) => (object)x.Tipo).CustomType().Column("tipo"); + base.Map((ClienteTelefoneDb x) => x.Prefixo).Column("ddd"); + base.Map((ClienteTelefoneDb x) => x.Numero).Column("fone"); + base.Map((ClienteTelefoneDb x) => x.Observacao).Column("obs").CustomType("StringClob").CustomSqlType("varchar(MAX)"); + base.Map((ClienteTelefoneDb x) => (object)x.Ordem).Column("ordem"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ClienteVinculoMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ClienteVinculoMap.cs new file mode 100644 index 0000000..c57ef85 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ClienteVinculoMap.cs @@ -0,0 +1,22 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class ClienteVinculoMap : ClassMap + { + public ClienteVinculoMap() + { + base.Table("clivinculo"); + base.LazyLoad(); + base.Id((ClienteVinculoDb x) => (object)x.Id).GeneratedBy.Identity().Column("idvinculo"); + base.References((ClienteVinculoDb x) => x.Cliente1).Column("idcliente1").Fetch.Join(); + base.References((ClienteVinculoDb x) => x.Cliente2).Column("idcliente2").Fetch.Join(); + base.Map((ClienteVinculoDb x) => (object)x.Parentesco).CustomType().Column("parentesco"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/CoberturaGranizoMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/CoberturaGranizoMap.cs new file mode 100644 index 0000000..68aee56 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/CoberturaGranizoMap.cs @@ -0,0 +1,27 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class CoberturaGranizoMap : ClassMap + { + public CoberturaGranizoMap() + { + base.Table("coberturagranizo"); + base.LazyLoad(); + base.Id((CoberturaGranizoDb x) => (object)x.Id).GeneratedBy.Identity().Column("idcoberturagranizo"); + base.References((CoberturaGranizoDb x) => x.Granizo).Column("idgranizo").Not.Nullable().Fetch.Join(); + base.Map((CoberturaGranizoDb x) => x.Variedade).Column("variedade"); + base.Map((CoberturaGranizoDb x) => x.Quadra).Column("quadra"); + base.Map((CoberturaGranizoDb x) => (object)x.Produtividade).Column("produtividade"); + base.Map((CoberturaGranizoDb x) => (object)x.Lmi).Column("lmi"); + base.Map((CoberturaGranizoDb x) => (object)x.Premio).Column("premio"); + base.Map((CoberturaGranizoDb x) => (object)x.Area).Column("area"); + base.Map((CoberturaGranizoDb x) => (object)x.Plantio).Column("dtplantio"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/CoberturaMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/CoberturaMap.cs new file mode 100644 index 0000000..4252897 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/CoberturaMap.cs @@ -0,0 +1,25 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class CoberturaMap : ClassMap + { + public CoberturaMap() + { + base.Table("cobertura"); + base.LazyLoad(); + base.Id((CoberturaDb x) => (object)x.Id).GeneratedBy.Identity().Column("idcobertura"); + base.References((CoberturaDb x) => x.Item).Column("iditem").Not.Nullable().Fetch.Join(); + base.References((CoberturaDb x) => x.CoberturaPadrao).Column("idcoberturapadrao").NotFound.Ignore().Fetch.Join(); + base.Map((CoberturaDb x) => (object)x.Franquia).Column("franquia"); + base.Map((CoberturaDb x) => (object)x.Premio).Column("premio"); + base.Map((CoberturaDb x) => (object)x.Lmi).Column("lmi"); + base.Map((CoberturaDb x) => x.Observacao).Column("observacao").CustomType("StringClob").CustomSqlType("varchar(MAX)"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/CoberturaPadraoMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/CoberturaPadraoMap.cs new file mode 100644 index 0000000..31b0990 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/CoberturaPadraoMap.cs @@ -0,0 +1,22 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class CoberturaPadraoMap : ClassMap + { + public CoberturaPadraoMap() + { + base.Table("coberturapadrao"); + base.LazyLoad(); + base.Id((CoberturaPadraoDb x) => (object)x.Id).GeneratedBy.Assigned().Column("idcoberturapadrao"); + base.Map((CoberturaPadraoDb x) => (object)x.IdRamo).Column("idramo"); + base.Map((CoberturaPadraoDb x) => x.Descricao).Column("descricao"); + base.Map((CoberturaPadraoDb x) => (object)x.Padrao).Column("padrao").CustomType(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/CondicaoRepasseMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/CondicaoRepasseMap.cs new file mode 100644 index 0000000..099834d --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/CondicaoRepasseMap.cs @@ -0,0 +1,22 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class CondicaoRepasseMap : ClassMap + { + public CondicaoRepasseMap() + { + base.Table("condicao"); + base.LazyLoad(); + base.Id((CondicaoRepasseDb x) => (object)x.Id).GeneratedBy.Identity().Column("idcondicao"); + base.References((CondicaoRepasseDb x) => x.Ramo).Column("idramo").Fetch.Join(); + base.References((CondicaoRepasseDb x) => x.Seguradora).Column("idciaseg").Fetch.Join(); + base.Map((CondicaoRepasseDb x) => (object)x.Parcela).Column("parcela"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ConfigExtratoImportMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ConfigExtratoImportMap.cs new file mode 100644 index 0000000..1b8b11a --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ConfigExtratoImportMap.cs @@ -0,0 +1,23 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class ConfigExtratoImportMap : ClassMap + { + public ConfigExtratoImportMap() + { + base.Table("extratoconfig"); + base.LazyLoad(); + base.Id((ConfigExtratoImportDb x) => (object)x.Id).GeneratedBy.Identity().Column("idextratoconfig"); + base.Map((ConfigExtratoImportDb x) => (object)x.IdSeguradora).Column("idciaseg"); + base.Map((ConfigExtratoImportDb x) => x.Descricao).Column("descricao"); + base.Map((ConfigExtratoImportDb x) => x.Codigo).Column("codigocia"); + base.Map((ConfigExtratoImportDb x) => (object)x.Ativo).Column("ativo"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ConsorcioMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ConsorcioMap.cs new file mode 100644 index 0000000..a443f1d --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ConsorcioMap.cs @@ -0,0 +1,25 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class ConsorcioMap : ClassMap + { + public ConsorcioMap() + { + base.Table("consorcio"); + base.LazyLoad(); + base.Id((ConsorcioDb x) => (object)x.Id).GeneratedBy.Identity().Column("idconsorcio"); + base.References((ConsorcioDb x) => x.Item).Column("iditem").Not.Nullable().Fetch.Join(); + base.Map((ConsorcioDb x) => x.BensConsorcio).Column("bensconsorcio"); + base.Map((ConsorcioDb x) => (object)x.ValorCredito).Column("valorcredito"); + base.Map((ConsorcioDb x) => x.Grupo).Column("grupo"); + base.Map((ConsorcioDb x) => x.Cota).Column("cota"); + base.Map((ConsorcioDb x) => x.Observacao).Column("obs").CustomType("StringClob").CustomSqlType("varchar(MAX)"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ControleMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ControleMap.cs new file mode 100644 index 0000000..a1de969 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ControleMap.cs @@ -0,0 +1,27 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class ControleMap : ClassMap + { + public ControleMap() + { + base.Table("controle"); + base.LazyLoad(); + base.Id((ControleDb x) => (object)x.Id).GeneratedBy.Identity().Column("idcontrole"); + base.References((ControleDb x) => x.Cliente).Column("idcliente").Not.Nullable().Fetch.Join(); + base.References((ControleDb x) => x.Seguradora).Column("idciaseg").Fetch.Join(); + base.References((ControleDb x) => x.Ramo).Column("idramo").Fetch.Join(); + base.References((ControleDb x) => x.Produto).Column("idproduto").Fetch.Join(); + base.References((ControleDb x) => x.SeguradoraAnterior).Column("idciasegant").NotFound.Ignore().Fetch.Join(); + base.Map((ControleDb x) => (object)x.IdEmpresa).Column("idempresa").Not.Nullable(); + base.Map((ControleDb x) => x.AssistenciaId); + base.HasMany((ControleDb x) => x.Documentos).Fetch.Join(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ControleSinistroMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ControleSinistroMap.cs new file mode 100644 index 0000000..f404be8 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ControleSinistroMap.cs @@ -0,0 +1,21 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class ControleSinistroMap : ClassMap + { + public ControleSinistroMap() + { + base.Table("controlesinistro"); + base.LazyLoad(); + base.Id((ControleSinistroDb x) => (object)x.Id).GeneratedBy.Identity().Column("idcontrolesinistro"); + base.References((ControleSinistroDb x) => x.Item).Column("iditem").Not.Nullable().Fetch.Join(); + base.Map((ControleSinistroDb x) => (object)x.DataSinistro).Column("datasinistro"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/CriticaApoliceMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/CriticaApoliceMap.cs new file mode 100644 index 0000000..1f6b6ae --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/CriticaApoliceMap.cs @@ -0,0 +1,28 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class CriticaApoliceMap : ClassMap + { + public CriticaApoliceMap() + { + base.Table("importacao"); + base.LazyLoad(); + base.Id((CriticaApoliceDb x) => (object)x.Id).GeneratedBy.Identity().Column("idimportacao"); + base.References((CriticaApoliceDb x) => x.Documento).Column("iddocumento").Not.Nullable().Fetch.Join(); + base.References((CriticaApoliceDb x) => x.UsuarioImportacao).Column("idusuario").Not.Nullable().Fetch.Join(); + base.Map((CriticaApoliceDb x) => (object)x.Critica).Column("critica").CustomType(); + base.Map((CriticaApoliceDb x) => (object)x.UsuarioCritica).Column("idusuariocritica"); + base.Map((CriticaApoliceDb x) => x.NaoEncontrados).Column("naoencontrados"); + base.Map((CriticaApoliceDb x) => (object)x.DataImportacao).Column("dataimportacao"); + base.Map((CriticaApoliceDb x) => (object)x.DataCritica).Column("datacritica"); + base.Map((CriticaApoliceDb x) => x.Tipo).Column("tipo"); + base.Map((CriticaApoliceDb x) => (object)x.Aggilizador).Column("Aggilizador"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/DetalheExtratoMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/DetalheExtratoMap.cs new file mode 100644 index 0000000..021416c --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/DetalheExtratoMap.cs @@ -0,0 +1,35 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class DetalheExtratoMap : ClassMap + { + public DetalheExtratoMap() + { + base.Table("parcelaextrato"); + base.LazyLoad(); + base.Id((DetalheExtratoDb x) => (object)x.Id).GeneratedBy.Identity().Column("idparcelaextrato"); + base.References((DetalheExtratoDb x) => x.Extrato).Column("idextrato").Fetch.Join(); + base.Map((DetalheExtratoDb x) => (object)x.Status).CustomType().Column("idstatusparcela"); + base.Map((DetalheExtratoDb x) => (object)x.SubTipo).CustomType().Column("idsubtipo"); + base.Map((DetalheExtratoDb x) => (object)x.Parcela).Column("idparcela"); + base.Map((DetalheExtratoDb x) => x.Cliente).Column("cliente"); + base.Map((DetalheExtratoDb x) => x.Apolice).Column("apolice"); + base.Map((DetalheExtratoDb x) => x.Endosso).Column("endosso"); + base.Map((DetalheExtratoDb x) => x.NumeroParcela).Column("parcela"); + base.Map((DetalheExtratoDb x) => (object)x.Recebimento).Column("datarec"); + base.Map((DetalheExtratoDb x) => (object)x.Credito).Column("datacred"); + base.Map((DetalheExtratoDb x) => (object)x.Valor).Column("valor"); + base.Map((DetalheExtratoDb x) => (object)x.Comissao).Column("comiss"); + base.Map((DetalheExtratoDb x) => (object)x.ValorComissao).Column("vlrcomiss"); + base.Map((DetalheExtratoDb x) => x.Historico).Column("historico"); + base.Map((DetalheExtratoDb x) => (object)x.Documento).Column("iddocumento"); + base.Map((DetalheExtratoDb x) => (object)x.Corrigir).Column("corrigir"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/DocumentoMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/DocumentoMap.cs new file mode 100644 index 0000000..bbb4721 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/DocumentoMap.cs @@ -0,0 +1,70 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class DocumentoMap : ClassMap + { + public DocumentoMap() + { + base.Table("documento"); + base.LazyLoad(); + base.Id((DocumentoDb x) => (object)x.Id).GeneratedBy.Identity().Column("iddocumento"); + base.References((DocumentoDb x) => x.Controle).Column("idcontrole").Not.Nullable().Fetch.Join(); + base.References((DocumentoDb x) => x.UsuarioCriacao).Column("usuariocriacao"); + base.References((DocumentoDb x) => x.Status).Column("idstatus").Fetch.Join(); + base.Map((DocumentoDb x) => (object)x.DataCriacao).Column("cri_data"); + base.Map((DocumentoDb x) => (object)x.Ordem).Column("ordem").Not.Nullable(); + base.Map((DocumentoDb x) => (object)x.Tipo).Column("tipo").Not.Nullable(); + base.Map((DocumentoDb x) => x.Proposta).Column("proposta"); + base.Map((DocumentoDb x) => x.PropostaEndosso).Column("pedadit"); + base.Map((DocumentoDb x) => x.ApoliceAnterior).Column("apol_antes"); + base.Map((DocumentoDb x) => x.Apolice).Column("contrato"); + base.Map((DocumentoDb x) => x.Endosso).Column("aditamento"); + base.Map((DocumentoDb x) => (object)x.DataControle).Column("datacontrole"); + base.Map((DocumentoDb x) => (object)x.Excluido).Column("excluido").Not.Nullable().CustomType(); + base.Map((DocumentoDb x) => (object)x.PropostaAssinada).Column("propassinada").CustomType(); + base.Map((DocumentoDb x) => (object)x.ApoliceConferida).Column("apoconferida").CustomType(); + base.Map((DocumentoDb x) => (object)x.AdicionalComiss).Column("adinacomis").CustomType(); + base.Map((DocumentoDb x) => (object)x.Comissao).Column("com01"); + base.Map((DocumentoDb x) => (object)x.PremioLiquido).Column("pr_liq"); + base.Map((DocumentoDb x) => (object)x.PremioAdicional).Column("pr_adic"); + base.Map((DocumentoDb x) => (object)x.PremioTotal).Column("pr_total"); + base.Map((DocumentoDb x) => (object)x.NumeroParcelas).Column("n_parc"); + base.Map((DocumentoDb x) => (object)x.Custo).Column("pr_custo"); + base.Map((DocumentoDb x) => (object)x.Iof).Column("pr_iof"); + base.Map((DocumentoDb x) => (object)x.Diferenca).Column("diferenca"); + base.Map((DocumentoDb x) => (object)x.Negocio).CustomType().Column("idnegocio"); + base.Map((DocumentoDb x) => x.Observacao).Column("obs").CustomType("StringClob").CustomSqlType("varchar(MAX)"); + base.Map((DocumentoDb x) => x.Pasta).Column("pasta"); + base.Map((DocumentoDb x) => x.Agencia).Column("agencia"); + base.Map((DocumentoDb x) => x.Conta).Column("conta"); + base.Map((DocumentoDb x) => (object)x.TipoEndosso).CustomType>().Column("tipoadit"); + base.Map((DocumentoDb x) => (object)x.TipoRecebimento).CustomType().Column("tiporecebimento"); + base.Map((DocumentoDb x) => (object)x.Situacao).CustomType().Column("situacao").Not.Nullable(); + base.Map((DocumentoDb x) => (object)x.SituacaoAnterior).CustomType>().Column("situant"); + base.Map((DocumentoDb x) => x.NumeroCartao).Column("numerocart"); + base.Map((DocumentoDb x) => x.VencimentoCartao).Column("vencimentocart"); + base.Map((DocumentoDb x) => x.NomeProponente).Column("nomeprop"); + base.Map((DocumentoDb x) => (object)x.Vigencia1).Column("vigencia1").Not.Nullable(); + base.Map((DocumentoDb x) => (object)x.Vigencia2).Column("vigencia2"); + base.Map((DocumentoDb x) => (object)x.Emissao).Column("emissao"); + base.Map((DocumentoDb x) => (object)x.Remessa).Column("remessa"); + base.Map((DocumentoDb x) => (object)x.ComissaoTotal).Column("comissaototal"); + base.Map((DocumentoDb x) => (object)x.NegocioCorretora).CustomType().Column("NegocioCorretora"); + base.Map((DocumentoDb x) => (object)x.Bandeira).CustomType().Column("idbandeira"); + base.References((DocumentoDb x) => x.Banco).Column("idbanco").Cascade.None(); + base.References((DocumentoDb x) => x.Estipulante1).Column("idestipulante").Fetch.Join(); + base.References((DocumentoDb x) => x.Estipulante2).Column("idestipulante2").Fetch.Join(); + base.References((DocumentoDb x) => x.Estipulante3).Column("idestipulante3").Fetch.Join(); + base.References((DocumentoDb x) => x.Estipulante4).Column("idestipulante4").Fetch.Join(); + base.References((DocumentoDb x) => x.Estipulante5).Column("idestipulante5").Fetch.Join(); + base.Map((DocumentoDb x) => (object)x.FormaPagamento).CustomType>().Column("formapagamento"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/EstipulanteMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/EstipulanteMap.cs new file mode 100644 index 0000000..39c6fd7 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/EstipulanteMap.cs @@ -0,0 +1,38 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class EstipulanteMap : ClassMap + { + public EstipulanteMap() + { + base.Table("estipulante"); + base.LazyLoad(); + base.Id((EstipulanteDb x) => (object)x.Id).GeneratedBy.Identity().Column("idestipulante"); + base.Map((EstipulanteDb x) => (object)x.IdEmpresa).Column("idempresa"); + base.Map((EstipulanteDb x) => x.Nome).Column("nome"); + base.Map((EstipulanteDb x) => x.Documento).Column("cpfcnpj"); + base.Map((EstipulanteDb x) => x.Cep).Column("cep"); + base.Map((EstipulanteDb x) => x.Cidade).Column("cidade"); + base.Map((EstipulanteDb x) => x.Estado).Column("uf"); + base.Map((EstipulanteDb x) => x.Bairro).Column("bairro"); + base.Map((EstipulanteDb x) => x.Endereco).Column("endereco"); + base.Map((EstipulanteDb x) => x.Numero).Column("numero"); + base.Map((EstipulanteDb x) => x.Complemento).Column("complemento"); + base.Map((EstipulanteDb x) => (object)x.PrimeiroTipo).CustomType().Column("idfonetipo1"); + base.Map((EstipulanteDb x) => x.PrimeiroPrefixo).Column("ddd1"); + base.Map((EstipulanteDb x) => x.PrimeiroTelefone).Column("fone1"); + base.Map((EstipulanteDb x) => (object)x.SegundoTipo).CustomType().Column("idfonetipo2"); + base.Map((EstipulanteDb x) => x.SegundoPrefixo).Column("ddd2"); + base.Map((EstipulanteDb x) => x.SegundoTelefone).Column("fone2"); + base.Map((EstipulanteDb x) => x.Email).Column("email"); + base.Map((EstipulanteDb x) => x.Observacao).Column("obs").CustomType("StringClob").CustomSqlType("varchar(MAX)"); + base.Map((EstipulanteDb x) => (object)x.Ativo).Column("ativo").CustomType(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ExpedicaoMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ExpedicaoMap.cs new file mode 100644 index 0000000..93ede61 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ExpedicaoMap.cs @@ -0,0 +1,29 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class ExpedicaoMap : ClassMap + { + public ExpedicaoMap() + { + base.Table("infoexpedicao"); + base.LazyLoad(); + base.Id((ExpedicaoDb x) => (object)x.Id).GeneratedBy.Identity().Column("idinfoexpedicao"); + base.References((ExpedicaoDb x) => x.Apolice).Column("iddocumento").Not.Nullable().Fetch.Join(); + base.Map((ExpedicaoDb x) => x.Documento).Column("documento"); + base.Map((ExpedicaoDb x) => x.Destino).Column("destino"); + base.Map((ExpedicaoDb x) => (object)x.DataEnvio).Column("dtenvio"); + base.Map((ExpedicaoDb x) => (object)x.DataRecebimento).Column("dtrecto"); + base.Map((ExpedicaoDb x) => x.Responsavel).Column("responsavel"); + base.Map((ExpedicaoDb x) => (object)x.UsuarioCriacao).Column("usuariocriacao"); + base.Map((ExpedicaoDb x) => (object)x.DataCriacao).Column("datacriacao"); + base.Map((ExpedicaoDb x) => (object)x.UsuarioAlteracao).Column("usuarioalteracao"); + base.Map((ExpedicaoDb x) => (object)x.DataAlteracao).Column("dataalteracao"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ExtratoMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ExtratoMap.cs new file mode 100644 index 0000000..d4c997a --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ExtratoMap.cs @@ -0,0 +1,33 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class ExtratoMap : ClassMap + { + public ExtratoMap() + { + base.Table("extrato"); + base.LazyLoad(); + base.Id((ExtratoDb x) => (object)x.Id).GeneratedBy.Identity().Column("idextrato"); + base.References((ExtratoDb x) => x.Seguradora).Column("idciaseg").Fetch.Join(); + base.Map((ExtratoDb x) => (object)x.Status).CustomType().Column("idstatusextrato"); + base.Map((ExtratoDb x) => x.Numero).Column("extrato"); + base.Map((ExtratoDb x) => x.Historico).Column("historico"); + base.Map((ExtratoDb x) => (object)x.Data).Column("data"); + base.Map((ExtratoDb x) => (object)x.DataCredito).Column("DataCredito"); + base.Map((ExtratoDb x) => (object)x.Bruto).Column("bruto"); + base.Map((ExtratoDb x) => (object)x.Liquido).Column("liquido"); + base.Map((ExtratoDb x) => (object)x.Ir).Column("ir"); + base.Map((ExtratoDb x) => (object)x.Iss).Column("iss"); + base.Map((ExtratoDb x) => (object)x.Outro).Column("outro"); + base.Map((ExtratoDb x) => x.Observacao).Column("obsextrato").CustomType("StringClob").CustomSqlType("varchar(MAX)"); + base.Map((ExtratoDb x) => (object)x.IdUsuario).Column("usuariocriacao"); + base.Map((ExtratoDb x) => (object)x.IdEmpresa).Column("idempresa"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/FabricanteMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/FabricanteMap.cs new file mode 100644 index 0000000..95b8783 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/FabricanteMap.cs @@ -0,0 +1,19 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class FabricanteMap : ClassMap + { + public FabricanteMap() + { + base.Table("fabricante"); + base.LazyLoad(); + base.Id((FabricanteDb x) => (object)x.Id).GeneratedBy.Assigned().Column("idfabricante"); + base.Map((FabricanteDb x) => x.Descricao).Column("descricao"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/FaturaMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/FaturaMap.cs new file mode 100644 index 0000000..c1e4bb0 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/FaturaMap.cs @@ -0,0 +1,24 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class FaturaMap : ClassMap + { + public FaturaMap() + { + base.Table("fatura"); + base.LazyLoad(); + base.Id((FaturaDb x) => (object)x.Id).GeneratedBy.Identity().Column("idfatura"); + base.References((FaturaDb x) => x.Parcela).Column("idparcela").Not.Nullable().Fetch.Join(); + base.Map((FaturaDb x) => x.Fatura).Column("numfatura"); + base.Map((FaturaDb x) => (object)x.VigenciaInicial).Column("vigenciai"); + base.Map((FaturaDb x) => (object)x.VigenciaFinal).Column("vigenciaf"); + base.Map((FaturaDb x) => (object)x.Emissao).Column("emissao"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/GranizoMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/GranizoMap.cs new file mode 100644 index 0000000..202ea46 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/GranizoMap.cs @@ -0,0 +1,33 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class GranizoMap : ClassMap + { + public GranizoMap() + { + base.Table("granizo"); + base.LazyLoad(); + base.Id((GranizoDb x) => (object)x.Id).GeneratedBy.Identity().Column("idgranizo"); + base.References((GranizoDb x) => x.Item).Column("iditem").Not.Nullable().Fetch.Join(); + base.Map((GranizoDb x) => x.Cep).Column("cep"); + base.Map((GranizoDb x) => x.Endereco).Column("endereco"); + base.Map((GranizoDb x) => x.Numero).Column("numero"); + base.Map((GranizoDb x) => x.Complemento).Column("complemento"); + base.Map((GranizoDb x) => x.Bairro).Column("bairro"); + base.Map((GranizoDb x) => x.Cidade).Column("cidade"); + base.Map((GranizoDb x) => x.Estado).Column("uf"); + base.Map((GranizoDb x) => (object)x.SubsidioEstadual).Column("subest"); + base.Map((GranizoDb x) => (object)x.SubsidioFederal).Column("subfed"); + base.Map((GranizoDb x) => x.Cultura).Column("cultura"); + base.Map((GranizoDb x) => x.Sitio).Column("sitio"); + base.Map((GranizoDb x) => x.Observacao).Column("obs").CustomType("StringClob").CustomSqlType("varchar(MAX)"); + base.Map((GranizoDb x) => x.Area).Column("area"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ItemMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ItemMap.cs new file mode 100644 index 0000000..659373e --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ItemMap.cs @@ -0,0 +1,33 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class ItemMap : ClassMap + { + public ItemMap() + { + base.Table("item"); + base.LazyLoad(); + base.Id((ItemDb x) => (object)x.Id).GeneratedBy.Identity().Column("iditem"); + base.References((ItemDb x) => x.Documento).Column("iddocumento").Not.Nullable().Fetch.Join(); + base.Map((ItemDb x) => (object)x.Endosso).Column("idendosso"); + base.Map((ItemDb x) => (object)x.Substituicao).Column("idsubstituicao"); + base.Map((ItemDb x) => (object)x.Substituido).Column("idsubstituido"); + base.Map((ItemDb x) => (object)x.Ordem).Column("ordem"); + base.Map((ItemDb x) => x.Descricao).Column("descricao"); + base.Map((ItemDb x) => x.Status).Column("status"); + base.Map((ItemDb x) => x.StatusInclusao).Column("statusinc"); + base.Map((ItemDb x) => x.Observacao).Column("obs").CustomType("StringClob").CustomSqlType("varchar(MAX)"); + base.Map((ItemDb x) => (object)x.IdDocumentoCancelado); + base.Map((ItemDb x) => (object)x.Cancelado).Column("cancelado").CustomType(); + base.Map((ItemDb x) => (object)x.Sinistrado).Column("sinistrado").CustomType(); + base.HasMany((ItemDb x) => x.Sinistros).Not.KeyUpdate(); + base.HasMany((ItemDb x) => x.Coberturas).Not.KeyUpdate(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/MaisContatoMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/MaisContatoMap.cs new file mode 100644 index 0000000..70f39db --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/MaisContatoMap.cs @@ -0,0 +1,38 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class MaisContatoMap : ClassMap + { + public MaisContatoMap() + { + base.Table("clicontato"); + base.LazyLoad(); + base.Id((MaisContatoDb x) => (object)x.Id).GeneratedBy.Identity().Column("idclicontato"); + base.References((MaisContatoDb x) => x.Cliente).Column("idcliente").Not.Nullable().Fetch.Join(); + base.References((MaisContatoDb x) => x.Profissao).Column("idprofissao").Fetch.Join(); + base.Map((MaisContatoDb x) => x.Nome).Column("contato"); + base.Map((MaisContatoDb x) => (object)x.Tipo).CustomType().Column("tipo"); + base.Map((MaisContatoDb x) => (object)x.Nascimento).Column("dtnasc"); + base.Map((MaisContatoDb x) => x.Documento).Column("cgccpf"); + base.Map((MaisContatoDb x) => x.Identidade).Column("rg"); + base.Map((MaisContatoDb x) => (object)x.Expedicao).Column("rgexpedicao"); + base.Map((MaisContatoDb x) => (object)x.Parentesco).CustomType().Column("idparentesco"); + base.Map((MaisContatoDb x) => x.Prefixo).Column("ddd"); + base.Map((MaisContatoDb x) => x.Telefone).Column("fone"); + base.Map((MaisContatoDb x) => x.Email).Column("email"); + base.Map((MaisContatoDb x) => x.Habilitacao).Column("cnh"); + base.Map((MaisContatoDb x) => (object)x.PrimeiraHabilitacao).Column("prihabilitacao"); + base.Map((MaisContatoDb x) => x.Banco).Column("banco"); + base.Map((MaisContatoDb x) => x.Agencia).Column("agencia"); + base.Map((MaisContatoDb x) => x.Conta).Column("conta"); + base.Map((MaisContatoDb x) => (object)x.Excluido).Column("excluido").CustomType(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/MetaSeguradoraMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/MetaSeguradoraMap.cs new file mode 100644 index 0000000..0a43855 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/MetaSeguradoraMap.cs @@ -0,0 +1,26 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class MetaSeguradoraMap : ClassMap + { + public MetaSeguradoraMap() + { + base.Table("Meta"); + base.LazyLoad(); + base.Id((MetaSeguradoraDb x) => (object)x.Id).GeneratedBy.Identity().Column("IdMeta"); + base.References((MetaSeguradoraDb x) => x.Seguradora).Column("IdCiaSeg").Fetch.Join().NotFound.Ignore(); + base.Map((MetaSeguradoraDb x) => (object)x.Mes).CustomType().Column("Mes"); + base.Map((MetaSeguradoraDb x) => (object)x.Ano).Column("Ano"); + base.Map((MetaSeguradoraDb x) => (object)x.Valor).Column("Valor"); + base.Map((MetaSeguradoraDb x) => (object)x.IdAggilizador).Column("IdSeguradora"); + base.Map((MetaSeguradoraDb x) => (object)x.Recorrente).Column("Recorrente").Not.Nullable().Default("1"); + base.Map((MetaSeguradoraDb x) => (object)x.TipoCalculo).Column("TipoCalculo").Not.Nullable().Default("1"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/MetaVendedorMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/MetaVendedorMap.cs new file mode 100644 index 0000000..9bf42bf --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/MetaVendedorMap.cs @@ -0,0 +1,23 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class MetaVendedorMap : ClassMap + { + public MetaVendedorMap() + { + base.Table("MetaVendedor"); + base.LazyLoad(); + base.Id((MetaVendedorDb x) => (object)x.Id).GeneratedBy.Identity().Column("IdMetaVendedor"); + base.References((MetaVendedorDb x) => x.Vendedor).Column("IdVendedor").Not.Nullable().Fetch.Join(); + base.Map((MetaVendedorDb x) => (object)x.Mes).CustomType().Column("Mes"); + base.Map((MetaVendedorDb x) => (object)x.Ano).Column("Ano"); + base.Map((MetaVendedorDb x) => (object)x.Valor).Column("Valor"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ParceiroMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ParceiroMap.cs new file mode 100644 index 0000000..b7fafc7 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ParceiroMap.cs @@ -0,0 +1,37 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class ParceiroMap : ClassMap + { + public ParceiroMap() + { + base.Table("parceiro"); + base.LazyLoad(); + base.Id((ParceiroDb x) => (object)x.Id).GeneratedBy.Identity().Column("idparceiro"); + base.Map((ParceiroDb x) => x.Nome).Column("nome"); + base.Map((ParceiroDb x) => x.Cep).Column("cep"); + base.Map((ParceiroDb x) => x.Endereco).Column("endereco"); + base.Map((ParceiroDb x) => x.Numero).Column("numero"); + base.Map((ParceiroDb x) => x.Complemento).Column("complemento"); + base.Map((ParceiroDb x) => x.Bairro).Column("bairro"); + base.Map((ParceiroDb x) => x.Cidade).Column("cidade"); + base.Map((ParceiroDb x) => x.Uf).Column("uf"); + base.Map((ParceiroDb x) => x.Cgccpf).Column("cgccpf"); + base.Map((ParceiroDb x) => x.Contato).Column("contato"); + base.Map((ParceiroDb x) => x.Email).Column("email"); + base.Map((ParceiroDb x) => x.Ddd1).Column("ddd1"); + base.Map((ParceiroDb x) => x.Telefone1).Column("telefone1"); + base.Map((ParceiroDb x) => x.Ddd2).Column("ddd2"); + base.Map((ParceiroDb x) => x.Telefone2).Column("telefone2"); + base.Map((ParceiroDb x) => x.Ddd3).Column("ddd3"); + base.Map((ParceiroDb x) => x.Telefone3).Column("telefone3"); + base.Map((ParceiroDb x) => x.Obs).Column("Obs"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ParcelaMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ParcelaMap.cs new file mode 100644 index 0000000..52034d4 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ParcelaMap.cs @@ -0,0 +1,52 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class ParcelaMap : ClassMap + { + public ParcelaMap() + { + base.Table("parcela"); + base.LazyLoad(); + base.Id((ParcelaDb x) => (object)x.Id).GeneratedBy.Identity().Column("idparcela"); + base.References((ParcelaDb x) => x.Documento).Column("iddocumento").Not.Nullable().Fetch.Join(); + base.Map((ParcelaDb x) => (object)x.IdEmpresa).Column("idempresa").Not.Nullable(); + base.Map((ParcelaDb x) => (object)x.NumeroParcela).Column("parcela").Not.Nullable(); + base.Map((ParcelaDb x) => (object)x.Vencimento).Column("vencto"); + base.Map((ParcelaDb x) => (object)x.DataRecebimento).Column("datarec"); + base.Map((ParcelaDb x) => (object)x.DataQuitacao).Column("dataquit"); + base.Map((ParcelaDb x) => (object)x.DataCredito).Column("datacred"); + base.Map((ParcelaDb x) => (object)x.Valor).Column("valor").Not.Nullable(); + base.Map((ParcelaDb x) => (object)x.ValorPago).Column("valorp"); + base.Map((ParcelaDb x) => (object)x.ValorRealizado).Column("valorr"); + base.Map((ParcelaDb x) => (object)x.Comissao).Column("comiss"); + base.Map((ParcelaDb x) => (object)x.ValorComissao).Column("vlrcomiss"); + base.Map((ParcelaDb x) => x.Observacao).Column("obs").CustomType("StringClob").CustomSqlType("varchar(MAX)"); + base.Map((ParcelaDb x) => x.Extrato).Column("extrato"); + base.Map((ParcelaDb x) => (object)x.Irr).Column("irr"); + base.Map((ParcelaDb x) => (object)x.Iss).Column("iss"); + base.Map((ParcelaDb x) => (object)x.Outros).Column("outros"); + base.Map((ParcelaDb x) => (object)x.Desconto).Column("desconto"); + base.Map((ParcelaDb x) => (object)x.ValorExtrato).Column("vlrextrato"); + base.Map((ParcelaDb x) => (object)x.ValorComDesconto).Column("vlrcomdesc"); + base.Map((ParcelaDb x) => (object)x.SubTipo).Column("idsubtipo").CustomType(); + base.Map((ParcelaDb x) => (object)x.TipoPagamento).Column("idtipopagto").CustomType(); + base.Map((ParcelaDb x) => (object)x.ValorLiquidoFatura).Column("valorlf"); + base.Map((ParcelaDb x) => (object)x.DataCriacao).Column("cri_data"); + base.Map((ParcelaDb x) => (object)x.UsuarioCriacao).Column("usuariocriacao"); + base.Map((ParcelaDb x) => (object)x.DataControle).Column("datacontrole"); + base.Map((ParcelaDb x) => x.Fatura).Column("fatura"); + base.Map((ParcelaDb x) => (object)x.VigenciaIncial).Column("vigenciainicial"); + base.Map((ParcelaDb x) => (object)x.VigenciaFinal).Column("vigenciafinal"); + base.Map((ParcelaDb x) => (object)x.Emissao).Column("emissao"); + base.Map((ParcelaDb x) => (object)x.StatusPagamento).CustomType().Default("0"); + base.Map((ParcelaDb x) => (object)x.IdParcelaPendente).Default("0"); + base.HasOne((ParcelaDb x) => x.FaturaInfo).Cascade.All().PropertyRef("Parcela"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/PatrimonialMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/PatrimonialMap.cs new file mode 100644 index 0000000..62ed300 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/PatrimonialMap.cs @@ -0,0 +1,47 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class PatrimonialMap : ClassMap + { + public PatrimonialMap() + { + base.Table("resempco"); + base.LazyLoad(); + base.Id((PatrimonialDb x) => (object)x.Id).GeneratedBy.Identity().Column("idresempco"); + base.References((PatrimonialDb x) => x.Item).Column("iditem").Not.Nullable().Fetch.Join(); + base.Map((PatrimonialDb x) => x.Cep).Column("cep"); + base.Map((PatrimonialDb x) => x.Endereco).Column("endereco"); + base.Map((PatrimonialDb x) => x.Numero).Column("numero"); + base.Map((PatrimonialDb x) => x.Complemento).Column("complemento"); + base.Map((PatrimonialDb x) => x.Bairro).Column("bairro"); + base.Map((PatrimonialDb x) => x.Cidade).Column("cidade"); + base.Map((PatrimonialDb x) => x.Estado).Column("uf"); + base.Map((PatrimonialDb x) => x.Bens).Column("bens").CustomType("StringClob").CustomSqlType("varchar(MAX)"); + base.Map((PatrimonialDb x) => (object)x.Utilizacao).CustomType().Column("idutilizacao"); + base.Map((PatrimonialDb x) => x.Imobiliaria).Column("imobiliaria"); + base.Map((PatrimonialDb x) => x.Contato).Column("contato"); + base.Map((PatrimonialDb x) => (object)x.Tipo).CustomType().Column("idfonetipo"); + base.Map((PatrimonialDb x) => x.Prefixo).Column("ddd"); + base.Map((PatrimonialDb x) => x.Telefone).Column("fone"); + base.Map((PatrimonialDb x) => x.Locatario1).Column("locatario"); + base.Map((PatrimonialDb x) => x.CpfLocatario1).Column("cpfLocatario1"); + base.Map((PatrimonialDb x) => x.PrefixoLocatario1).Column("ddd2"); + base.Map((PatrimonialDb x) => x.TelefoneLocatario1).Column("fone2"); + base.Map((PatrimonialDb x) => x.Locatario2).Column("locatario2"); + base.Map((PatrimonialDb x) => x.CpfLocatario2).Column("cpfLocatario2"); + base.Map((PatrimonialDb x) => x.PrefixoLocatario2).Column("dddLocatario2"); + base.Map((PatrimonialDb x) => x.TelefoneLocatario2).Column("foneLocatario2"); + base.Map((PatrimonialDb x) => x.Locatario3).Column("locatario3"); + base.Map((PatrimonialDb x) => x.CpfLocatario3).Column("cpfLocatario3"); + base.Map((PatrimonialDb x) => x.PrefixoLocatario3).Column("dddLocatario3"); + base.Map((PatrimonialDb x) => x.TelefoneLocatario3).Column("foneLocatario3"); + base.Map((PatrimonialDb x) => (object)x.TipoMoradia).Column("tipoMoradia"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/PerfilEmpresaMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/PerfilEmpresaMap.cs new file mode 100644 index 0000000..9227d81 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/PerfilEmpresaMap.cs @@ -0,0 +1,36 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class PerfilEmpresaMap : ClassMap + { + public PerfilEmpresaMap() + { + base.Table("perfilempresa"); + base.LazyLoad(); + base.Id((PerfilEmpresaDb x) => (object)x.Id).GeneratedBy.Identity().Column("idperfilempresa"); + base.References((PerfilEmpresaDb x) => x.Cliente).Column("idcliente").Not.Nullable().Fetch.Join(); + base.References((PerfilEmpresaDb x) => x.Controle).Column("idcontrole").Not.Nullable().Fetch.Join(); + base.Map((PerfilEmpresaDb x) => (object)x.TipoPavimento).CustomType>().Column("tipopavimento"); + base.Map((PerfilEmpresaDb x) => (object)x.AnoConstrucao).Column("anoconstrucao"); + base.Map((PerfilEmpresaDb x) => (object)x.TipoConstrucao).CustomType>().Column("TipoConstrucao"); + base.Map((PerfilEmpresaDb x) => (object)x.Localizacao).CustomType>().Column("Localizacao"); + base.Map((PerfilEmpresaDb x) => x.EquipamentoSeguranca).Column("EquipamentoSeguranca"); + base.Map((PerfilEmpresaDb x) => x.EquipamentoIncendio).Column("EquipamentoIncendio"); + base.Map((PerfilEmpresaDb x) => (object)x.AtividadeEmpresa).CustomType>().Column("AtividadeEmpresa"); + base.Map((PerfilEmpresaDb x) => x.AtividadePrincipal).Column("AtividadePrincipal"); + base.Map((PerfilEmpresaDb x) => (object)x.ExclusivoDeposito).Column("ExclusivoDeposito"); + base.Map((PerfilEmpresaDb x) => (object)x.DivisaTerrenoBaldio).Column("DivisaTerrenoBaldio"); + base.Map((PerfilEmpresaDb x) => (object)x.PatrimonioHistorio).Column("PatrimonioHistorio"); + base.Map((PerfilEmpresaDb x) => (object)x.PossuiTelhado).Column("PossuiTelhado"); + base.Map((PerfilEmpresaDb x) => (object)x.CaixasEletronicos).Column("CaixasEletronicos"); + base.Map((PerfilEmpresaDb x) => (object)x.Isopainel).Column("Isopainel"); + base.Map((PerfilEmpresaDb x) => (object)x.ConstrucaoReforma).Column("ConstrucaoReforma"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/PerfilMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/PerfilMap.cs new file mode 100644 index 0000000..1729b6b --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/PerfilMap.cs @@ -0,0 +1,45 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class PerfilMap : ClassMap + { + public PerfilMap() + { + base.Table("perfil"); + base.LazyLoad(); + base.Id((PerfilDb x) => (object)x.Id).GeneratedBy.Identity().Column("idperfil"); + base.References((PerfilDb x) => x.Cliente).Column("idcliente").Not.Nullable().Fetch.Join(); + base.References((PerfilDb x) => x.Controle).Column("idcontrole").Not.Nullable().Fetch.Join(); + base.Map((PerfilDb x) => x.Nome).Column("nomecompleto").Not.Nullable(); + base.Map((PerfilDb x) => (object)x.Relacao).CustomType>().Column("relacao"); + base.Map((PerfilDb x) => x.CepPernoite).Column("ceppernoite"); + base.Map((PerfilDb x) => x.CepCirculacao).Column("cepcirculacao"); + base.Map((PerfilDb x) => x.KmMensal).Column("quilometragemmensal"); + base.Map((PerfilDb x) => (object)x.UsoProfissional).Column("usoprofissional").CustomType(); + base.Map((PerfilDb x) => (object)x.GaragemTrabalho).CustomType>().Column("garagemtrabalho"); + base.Map((PerfilDb x) => (object)x.GaragemEstudo).CustomType>().Column("garagemestudo"); + base.Map((PerfilDb x) => (object)x.GaragemResidencia).CustomType>().Column("garagemresidencia"); + base.Map((PerfilDb x) => (object)x.VeiculoResidencia).CustomType().Column("veiculosresidencia"); + base.Map((PerfilDb x) => (object)x.TipoResidencia).CustomType>().Column("tiporesidencia"); + base.Map((PerfilDb x) => (object)x.UsoDependentes).CustomType>().Column("usodependentes"); + base.Map((PerfilDb x) => (object)x.DistanciaResidenciaTrabalho).CustomType>().Column("distanciaresidenciatrabalho"); + base.Map((PerfilDb x) => (object)x.Ocupacao).CustomType>().Column("ocupacao"); + base.Map((PerfilDb x) => x.Cpf).Column("cpf"); + base.Map((PerfilDb x) => (object)x.Nascimento).Column("datanascimento"); + base.Map((PerfilDb x) => (object)x.Sexo).CustomType>().Column("sexo"); + base.Map((PerfilDb x) => (object)x.TempoHabilitacao).CustomType>().Column("tempohabilitacao"); + base.Map((PerfilDb x) => (object)x.EstadoCivil).CustomType>().Column("estadocivil"); + base.Map((PerfilDb x) => x.Habilitacao).Column("numerohabilitacao"); + base.Map((PerfilDb x) => (object)x.Isencao).Column("isencao").CustomType(); + base.Map((PerfilDb x) => (object)x.SeguroVida).Column("SeguroVida").CustomType(); + base.Map((PerfilDb x) => (object)x.AntiFurto).CustomType>().Column("antifurto"); + base.Map((PerfilDb x) => (object)x.EstenderCobertura).Column("EstenderCobertura"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/PermissaoArquivoDigitalMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/PermissaoArquivoDigitalMap.cs new file mode 100644 index 0000000..0838ac0 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/PermissaoArquivoDigitalMap.cs @@ -0,0 +1,24 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class PermissaoArquivoDigitalMap : ClassMap + { + public PermissaoArquivoDigitalMap() + { + base.Table("PermissaoArquivoDigital"); + base.LazyLoad(); + base.Id((PermissaoArquivoDigitalDb x) => (object)x.Id).GeneratedBy.Identity().Column("Id"); + base.References((PermissaoArquivoDigitalDb x) => x.Usuario).Column("IdUsuario").Not.Nullable().Fetch.Join(); + base.Map((PermissaoArquivoDigitalDb x) => (object)x.Tela).CustomType().Column("Tela"); + base.Map((PermissaoArquivoDigitalDb x) => (object)x.Consultar).Column("Consultar"); + base.Map((PermissaoArquivoDigitalDb x) => (object)x.Incluir).Column("Incluir"); + base.Map((PermissaoArquivoDigitalDb x) => (object)x.Excluir).Column("Excluir"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/PermissaoUsuarioMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/PermissaoUsuarioMap.cs new file mode 100644 index 0000000..eade562 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/PermissaoUsuarioMap.cs @@ -0,0 +1,25 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class PermissaoUsuarioMap : ClassMap + { + public PermissaoUsuarioMap() + { + base.Table("PermissaoUsuario"); + base.LazyLoad(); + base.Id((PermissaoUsuarioDb x) => (object)x.Id).GeneratedBy.Identity().Column("Id"); + base.References((PermissaoUsuarioDb x) => x.Usuario).Column("IdUsuario").Not.Nullable().Fetch.Join(); + base.Map((PermissaoUsuarioDb x) => (object)x.Tela).CustomType().Column("Tela"); + base.Map((PermissaoUsuarioDb x) => (object)x.Consultar).Column("Consultar"); + base.Map((PermissaoUsuarioDb x) => (object)x.Incluir).Column("Incluir"); + base.Map((PermissaoUsuarioDb x) => (object)x.Alterar).Column("Alterar"); + base.Map((PermissaoUsuarioDb x) => (object)x.Excluir).Column("Excluir"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ProdutoMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ProdutoMap.cs new file mode 100644 index 0000000..e04c26c --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ProdutoMap.cs @@ -0,0 +1,21 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class ProdutoMap : ClassMap + { + public ProdutoMap() + { + base.Table("produto"); + base.LazyLoad(); + base.Id((ProdutoDb x) => (object)x.Id).GeneratedBy.Identity().Column("idproduto"); + base.Map((ProdutoDb x) => x.Nome).Column("nome"); + base.Map((ProdutoDb x) => (object)x.Ativo).Column("ativo"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ProspeccaoMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ProspeccaoMap.cs new file mode 100644 index 0000000..604818a --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ProspeccaoMap.cs @@ -0,0 +1,44 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class ProspeccaoMap : ClassMap + { + public ProspeccaoMap() + { + base.Table("venctoaleatorio"); + base.LazyLoad(); + base.Id((ProspeccaoDb x) => (object)x.Id).GeneratedBy.Identity().Column("idvenctoaleatorio"); + base.References((ProspeccaoDb x) => x.Vendedor).Column("idvendedor").Not.Nullable().Fetch.Join(); + base.References((ProspeccaoDb x) => x.Produto).Column("IdProduto").Fetch.Join(); + base.References((ProspeccaoDb x) => x.StatusPersonalizado).Column("IdStatusPersonalizado").Fetch.Join(); + base.References((ProspeccaoDb x) => x.Ramo).Column("idramo").Fetch.Join(); + base.Map((ProspeccaoDb x) => (object)x.IdEmpresa).Column("idempresa"); + base.Map((ProspeccaoDb x) => x.Nome).Column("nome"); + base.Map((ProspeccaoDb x) => x.Documento).Column("cpfcnpj"); + base.Map((ProspeccaoDb x) => (object)x.Nascimento).Column("dtnascimento"); + base.Map((ProspeccaoDb x) => x.Prefixo1).Column("ddd"); + base.Map((ProspeccaoDb x) => x.Telefone1).Column("fone"); + base.Map((ProspeccaoDb x) => x.Prefixo2).Column("ddd2"); + base.Map((ProspeccaoDb x) => x.Telefone2).Column("fone2"); + base.Map((ProspeccaoDb x) => x.Email).Column("email"); + base.Map((ProspeccaoDb x) => (object)x.VigenciaFinal).Column("finalcontrato"); + base.Map((ProspeccaoDb x) => x.Item).Column("item").Not.Nullable(); + base.Map((ProspeccaoDb x) => (object)x.Status).CustomType>().Column("situacao"); + base.Map((ProspeccaoDb x) => x.Tipo).Column("tipoprospeccao"); + base.Map((ProspeccaoDb x) => x.Observacao).Column("obs").CustomType("StringClob").CustomSqlType("varchar(MAX)"); + base.Map((ProspeccaoDb x) => (object)x.DataCriacao).Column("datacriacao"); + base.Map((ProspeccaoDb x) => (object)x.UsuarioCriacao).Column("usuariocriacao"); + base.Map((ProspeccaoDb x) => (object)x.Valor).Column("valor"); + base.References((ProspeccaoDb x) => x.Tarefa).Column("idtarefa").Fetch.Join(); + base.Map((ProspeccaoDb x) => (object)x.CriarTarefa).Column("criartarefa"); + base.Map((ProspeccaoDb x) => (object)x.Renovacao).Column("renovacao"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/QualificacaoMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/QualificacaoMap.cs new file mode 100644 index 0000000..cb0e5b1 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/QualificacaoMap.cs @@ -0,0 +1,28 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class QualificacaoMap : ClassMap + { + public QualificacaoMap() + { + base.Table("qualificacao"); + base.LazyLoad(); + base.Id((QualificacaoDb x) => (object)x.Id).GeneratedBy.Identity().Column("idqualificacao"); + base.Map((QualificacaoDb x) => (object)x.Liquido1).Column("liquido1"); + base.Map((QualificacaoDb x) => (object)x.Liquido2).Column("liquido2"); + base.Map((QualificacaoDb x) => (object)x.Liquido3).Column("liquido3"); + base.Map((QualificacaoDb x) => (object)x.Comissao1).Column("comissao1"); + base.Map((QualificacaoDb x) => (object)x.Comissao2).Column("comissao2"); + base.Map((QualificacaoDb x) => (object)x.Comissao3).Column("comissao3"); + base.Map((QualificacaoDb x) => (object)x.Resultado1).Column("resultado1"); + base.Map((QualificacaoDb x) => (object)x.Resultado2).Column("resultado2"); + base.Map((QualificacaoDb x) => (object)x.Resultado3).Column("resultado3"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/RamoMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/RamoMap.cs new file mode 100644 index 0000000..734b2f6 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/RamoMap.cs @@ -0,0 +1,25 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class RamoMap : ClassMap + { + public RamoMap() + { + base.Table("ramo"); + base.LazyLoad(); + base.Id((RamoDb x) => (object)x.Id).GeneratedBy.Assigned().Column("idramo"); + base.Map((RamoDb x) => x.Nome).Column("nome"); + base.Map((RamoDb x) => (object)x.Iof).Column("iof"); + base.Map((RamoDb x) => (object)x.Ativo).Column("ativo").CustomType(); + base.Map((RamoDb x) => (object)x.Fatura).Column("fatura").CustomType(); + base.Map((RamoDb x) => x.RamoSusep).Column("ramosusep"); + base.Map((RamoDb x) => (object)x.CodigoSusep).Column("codsusep"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/RepasseMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/RepasseMap.cs new file mode 100644 index 0000000..cff9f61 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/RepasseMap.cs @@ -0,0 +1,29 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class RepasseMap : ClassMap + { + public RepasseMap() + { + base.Table("repasse"); + base.LazyLoad(); + base.Id((RepasseDb x) => (object)x.Id).GeneratedBy.Identity().Column("idrepasse"); + base.References((RepasseDb x) => x.Vendedor).Column("idvendedor").Not.Nullable().Fetch.Join(); + base.References((RepasseDb x) => x.Ramo).Column("idramo").Fetch.Join(); + base.Map((RepasseDb x) => (object)x.Tipo).CustomType>().Column("tipo"); + base.Map((RepasseDb x) => (object)x.Incidencia).CustomType>().Column("incidencia"); + base.Map((RepasseDb x) => (object)x.Forma).CustomType>().Column("forma"); + base.Map((RepasseDb x) => (object)x.ValorNovo).Column("vlrnovo"); + base.Map((RepasseDb x) => (object)x.ValorRenovacao).Column("vlrrenovacao"); + base.Map((RepasseDb x) => (object)x.Base).CustomType>().Column("base"); + base.Map((RepasseDb x) => (object)x.Seguradora).Column("idciaseg"); + base.Map((RepasseDb x) => (object)x.Ativo).Column("ativo").CustomType(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ResponsavelAssinaturaMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ResponsavelAssinaturaMap.cs new file mode 100644 index 0000000..6fc3456 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/ResponsavelAssinaturaMap.cs @@ -0,0 +1,23 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class ResponsavelAssinaturaMap : ClassMap + { + public ResponsavelAssinaturaMap() + { + base.Table("ResponsavelAssinatura"); + base.LazyLoad(); + base.Id((ResponsavelAssinaturaDb x) => (object)x.Id).GeneratedBy.Identity(); + base.Map((ResponsavelAssinaturaDb x) => (object)x.IdCliente).Not.Nullable(); + base.Map((ResponsavelAssinaturaDb x) => x.NomeResponsavel).Not.Nullable(); + base.Map((ResponsavelAssinaturaDb x) => x.DocumentoResponsavel).Not.Nullable(); + base.Map((ResponsavelAssinaturaDb x) => x.EmailResponsavel).Not.Nullable(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/RestricaoUsuarioCamposRelatoriosMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/RestricaoUsuarioCamposRelatoriosMap.cs new file mode 100644 index 0000000..5c25982 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/RestricaoUsuarioCamposRelatoriosMap.cs @@ -0,0 +1,23 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class RestricaoUsuarioCamposRelatoriosMap : ClassMap + { + public RestricaoUsuarioCamposRelatoriosMap() + { + base.Table("RestricaoUsuarioCampos"); + base.LazyLoad(); + base.Id((RestricaoUsuarioCamposRelatoriosDb x) => (object)x.Id).GeneratedBy.Identity(); + base.References((RestricaoUsuarioCamposRelatoriosDb x) => x.Usuario).Not.Nullable().Fetch.Join(); + base.Map((RestricaoUsuarioCamposRelatoriosDb x) => x.Campo); + base.Map((RestricaoUsuarioCamposRelatoriosDb x) => (object)x.Relatorio).CustomType().Not.Nullable(); + base.Map((RestricaoUsuarioCamposRelatoriosDb x) => (object)x.Restricao); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/RestricaoUsuarioMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/RestricaoUsuarioMap.cs new file mode 100644 index 0000000..0e9fdc0 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/RestricaoUsuarioMap.cs @@ -0,0 +1,22 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class RestricaoUsuarioMap : ClassMap + { + public RestricaoUsuarioMap() + { + base.Table("RestricaoUsuario"); + base.LazyLoad(); + base.Id((RestricaoUsuarioDb x) => (object)x.Id).GeneratedBy.Identity().Column("Id"); + base.References((RestricaoUsuarioDb x) => x.Usuario).Column("IdUsuario").Not.Nullable().Fetch.Join(); + base.Map((RestricaoUsuarioDb x) => (object)x.Tipo).CustomType().Column("Tipo"); + base.Map((RestricaoUsuarioDb x) => (object)x.Restricao).Column("Restricao"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/RiscosDiversosMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/RiscosDiversosMap.cs new file mode 100644 index 0000000..843a0a0 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/RiscosDiversosMap.cs @@ -0,0 +1,24 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class RiscosDiversosMap : ClassMap + { + public RiscosDiversosMap() + { + base.Table("riscosdiversos"); + base.LazyLoad(); + base.Id((RiscosDiversosDb x) => (object)x.Id).GeneratedBy.Identity().Column("idriscosdiversos"); + base.References((RiscosDiversosDb x) => x.Item).Column("iditem").Not.Nullable().Fetch.Join(); + base.Map((RiscosDiversosDb x) => x.Observacao).Column("obs").CustomType("StringClob").CustomSqlType("varchar(MAX)"); + base.Map((RiscosDiversosDb x) => (object)x.SubsidioEstadual).Column("subfed"); + base.Map((RiscosDiversosDb x) => (object)x.SubsidioFederal).Column("subest"); + base.Map((RiscosDiversosDb x) => x.Area).Column("area"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/SeguradoraContatoMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/SeguradoraContatoMap.cs new file mode 100644 index 0000000..8c19c92 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/SeguradoraContatoMap.cs @@ -0,0 +1,28 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class SeguradoraContatoMap : ClassMap + { + public SeguradoraContatoMap() + { + base.Table("ciacontato"); + base.LazyLoad(); + base.Id((SeguradoraContatoDb x) => (object)x.Id).GeneratedBy.Identity().Column("idciacontato"); + base.References((SeguradoraContatoDb x) => x.Empresa).Column("idempresa").Not.Nullable().Fetch.Join(); + base.References((SeguradoraContatoDb x) => x.Seguradora).Column("idciaseg").Not.Nullable().Fetch.Join(); + base.Map((SeguradoraContatoDb x) => x.NomeContato).Column("nome"); + base.Map((SeguradoraContatoDb x) => (object)x.Tipo).CustomType().Column("idfonetipo"); + base.Map((SeguradoraContatoDb x) => x.Prefixo).Column("ddd"); + base.Map((SeguradoraContatoDb x) => x.Numero).Column("fone"); + base.Map((SeguradoraContatoDb x) => x.Email).Column("email"); + base.Map((SeguradoraContatoDb x) => (object)x.TipoContato).CustomType().Default("0"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/SeguradoraEnderecoMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/SeguradoraEnderecoMap.cs new file mode 100644 index 0000000..d90a445 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/SeguradoraEnderecoMap.cs @@ -0,0 +1,30 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class SeguradoraEnderecoMap : ClassMap + { + public SeguradoraEnderecoMap() + { + base.Table("ciaend"); + base.LazyLoad(); + base.Id((SeguradoraEnderecoDb x) => (object)x.Id).GeneratedBy.Identity().Column("idciaend"); + base.References((SeguradoraEnderecoDb x) => x.Empresa).Column("idempresa").Not.Nullable().Fetch.Join(); + base.References((SeguradoraEnderecoDb x) => x.Seguradora).Column("idciaseg").Not.Nullable().Fetch.Join(); + base.Map((SeguradoraEnderecoDb x) => x.Cep).Column("cep"); + base.Map((SeguradoraEnderecoDb x) => x.Cidade).Column("cidade"); + base.Map((SeguradoraEnderecoDb x) => x.Estado).Column("uf"); + base.Map((SeguradoraEnderecoDb x) => x.Bairro).Column("bairro"); + base.Map((SeguradoraEnderecoDb x) => x.Endereco).Column("endereco"); + base.Map((SeguradoraEnderecoDb x) => x.Numero).Column("numero"); + base.Map((SeguradoraEnderecoDb x) => x.Complemento).Column("complemento"); + base.Map((SeguradoraEnderecoDb x) => (object)x.Tipo).CustomType().Column("idtipoendereco"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/SeguradoraMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/SeguradoraMap.cs new file mode 100644 index 0000000..4c7dbe6 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/SeguradoraMap.cs @@ -0,0 +1,37 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class SeguradoraMap : ClassMap + { + public SeguradoraMap() + { + base.Table("ciaseg"); + base.LazyLoad(); + base.Id((SeguradoraDb x) => (object)x.Id).GeneratedBy.Assigned().Column("idciaseg"); + base.Map((SeguradoraDb x) => x.Nome).Column("nome"); + base.Map((SeguradoraDb x) => x.NomeSocial); + base.Map((SeguradoraDb x) => x.Susep).Column("susep"); + base.Map((SeguradoraDb x) => x.Assistencia).Column("assistencia"); + base.Map((SeguradoraDb x) => x.Documento).Column("cgccpf"); + base.Map((SeguradoraDb x) => (object)x.Ativo).Column("ativo").Not.Nullable().CustomType(); + base.Map((SeguradoraDb x) => (object)x.Tolerancia).Column("tolerancia"); + base.Map((SeguradoraDb x) => x.Observacao).Column("observacao").CustomType("StringClob").CustomSqlType("varchar(MAX)"); + base.Map((SeguradoraDb x) => x.Usuario).Column("usuario"); + base.Map((SeguradoraDb x) => x.Senha).Column("pass"); + base.Map((SeguradoraDb x) => x.Codigo).Column("code"); + base.Map((SeguradoraDb x) => x.CodigoSusep).Column("codesusep"); + base.Map((SeguradoraDb x) => (object)x.IdAggilizador).Column("id"); + base.Map((SeguradoraDb x) => x.CodigoSeguradora).Column("codcia"); + base.Map((SeguradoraDb x) => x.LinkAppAndroid); + base.Map((SeguradoraDb x) => x.LinkAppIos); + base.Map((SeguradoraDb x) => x.CustomId); + base.Map((SeguradoraDb x) => (object)x.ToleranciaPremio).CustomSqlType("numeric(8,2)").Default("2"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/SinistroAutoMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/SinistroAutoMap.cs new file mode 100644 index 0000000..51c5bbc --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/SinistroAutoMap.cs @@ -0,0 +1,35 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class SinistroAutoMap : ClassMap + { + public SinistroAutoMap() + { + base.Table("sinistroauto"); + base.LazyLoad(); + base.Id((SinistroAutoDb x) => (object)x.Id).GeneratedBy.Identity().Column("idsinistroauto"); + base.References((SinistroAutoDb x) => x.Sinistro).Column("idsinistro").Not.Nullable().Fetch.Join(); + base.References((SinistroAutoDb x) => x.ParceiroMecanica).Column("idparceiromecanica").Fetch.Join(); + base.References((SinistroAutoDb x) => x.ParceiroFunilaria).Column("idparceirofunilaria").Fetch.Join(); + base.Map((SinistroAutoDb x) => x.NumeroBo).Column("numbo"); + base.Map((SinistroAutoDb x) => (object)x.TipoPerda).Column("idtipoperda").CustomType(); + base.Map((SinistroAutoDb x) => (object)x.Culpado).Column("culpado").CustomType(); + base.Map((SinistroAutoDb x) => (object)x.UltimoDocEnviado).Column("dataultdoc"); + base.Map((SinistroAutoDb x) => x.Endereco).Column("endereco"); + base.Map((SinistroAutoDb x) => x.Envolvido).Column("envolvido"); + base.Map((SinistroAutoDb x) => x.Motorista).Column("motorista"); + base.Map((SinistroAutoDb x) => x.Ddd).Column("ddd"); + base.Map((SinistroAutoDb x) => x.Telefone).Column("telefone"); + base.Map((SinistroAutoDb x) => x.Email).Column("email"); + base.Map((SinistroAutoDb x) => x.Cnh).Column("cnh"); + base.Map((SinistroAutoDb x) => (object)x.ValorMecanica).Column("valormecanica"); + base.Map((SinistroAutoDb x) => (object)x.ValorFunilaria).Column("valorfunilaria"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/SinistroMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/SinistroMap.cs new file mode 100644 index 0000000..dcad7ad --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/SinistroMap.cs @@ -0,0 +1,42 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class SinistroMap : ClassMap + { + public SinistroMap() + { + base.Table("sinistro"); + base.LazyLoad(); + base.Id((SinistroDb x) => (object)x.Id).GeneratedBy.Identity().Column("idsinistro"); + base.References((SinistroDb x) => x.ControleSinistro).Column("idcontrolesinistro").Not.Nullable().Fetch.Join(); + base.Map((SinistroDb x) => x.Numero).Column("numsinistro"); + base.Map((SinistroDb x) => (object)x.StatusSinistro).Column("idstatussinistro").CustomType(); + base.Map((SinistroDb x) => (object)x.TipoSinistro).Column("tiposinistro").CustomType(); + base.Map((SinistroDb x) => (object)x.DataReclamacao).Column("datareclamacao"); + base.Map((SinistroDb x) => (object)x.DataLiquidacao).Column("dataliquidacao"); + base.Map((SinistroDb x) => x.ItemSinistrado).Column("itemsinistrado"); + base.Map((SinistroDb x) => x.Descricao).Column("descricao").CustomType("StringClob").CustomSqlType("varchar(MAX)"); + base.Map((SinistroDb x) => x.Observacao).Column("observacao").CustomType("StringClob").CustomSqlType("nvarchar(max)"); + base.Map((SinistroDb x) => (object)x.Valor).Column("valor"); + base.Map((SinistroDb x) => x.Motivo).Column("motivo"); + base.Map((SinistroDb x) => (object)x.ValorOrcado).Column("vlrorcado"); + base.Map((SinistroDb x) => (object)x.ValorLiberado).Column("vlrliberado"); + base.Map((SinistroDb x) => (object)x.ValorPago).Column("vlrpago"); + base.Map((SinistroDb x) => (object)x.ValorFranquia).Column("vlrfranquia"); + base.Map((SinistroDb x) => x.Auxiliar).Column("auxiliar"); + base.Map((SinistroDb x) => (object)x.ValorSalvado).Column("vlrsalvado"); + base.Map((SinistroDb x) => x.ObservacaoInterna).Column("observacaoint").Length(4001); + base.Map((SinistroDb x) => x.StatusPersonalizado); + base.Map((SinistroDb x) => (object)x.DataCriacao).Column("datacriacao"); + base.Map((SinistroDb x) => (object)x.IdUsuarioCriacao).Column("usuariocriacao"); + base.Map((SinistroDb x) => (object)x.DataAlteracao).Column("dataalteracao"); + base.Map((SinistroDb x) => (object)x.IdUsuarioAlteracao).Column("usuarioalteracao"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/SinistroVidaMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/SinistroVidaMap.cs new file mode 100644 index 0000000..960164b --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/SinistroVidaMap.cs @@ -0,0 +1,26 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class SinistroVidaMap : ClassMap + { + public SinistroVidaMap() + { + base.Table("sinistrovida"); + base.LazyLoad(); + base.Id((SinistroVidaDb x) => (object)x.Id).GeneratedBy.Identity().Column("idsinistrovida"); + base.References((SinistroVidaDb x) => x.Sinistro).Column("idsinistro").Not.Nullable().Fetch.Join(); + base.Map((SinistroVidaDb x) => (object)x.TipoPerda).Column("tipoperda").CustomType(); + base.Map((SinistroVidaDb x) => (object)x.AuxFuneral).Column("auxfuneral").CustomType(); + base.Map((SinistroVidaDb x) => (object)x.EstadoCivil).CustomType>().Column("estadocivil"); + base.Map((SinistroVidaDb x) => x.CertObito).Column("certobito"); + base.Map((SinistroVidaDb x) => x.Beneficiario).Column("beneficiario"); + base.Map((SinistroVidaDb x) => x.Observacao).Column("observacao").CustomType("StringClob").CustomSqlType("varchar(MAX)"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/StatusMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/StatusMap.cs new file mode 100644 index 0000000..b934254 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/StatusMap.cs @@ -0,0 +1,21 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class StatusMap : ClassMap + { + public StatusMap() + { + base.Table("status"); + base.LazyLoad(); + base.Id((StatusDb x) => (object)x.Id).GeneratedBy.Identity().Column("idstatus"); + base.Map((StatusDb x) => x.Nome).Column("nome"); + base.Map((StatusDb x) => (object)x.Ativo).Column("ativo"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/TipoContaMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/TipoContaMap.cs new file mode 100644 index 0000000..3a80b5a --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/TipoContaMap.cs @@ -0,0 +1,21 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class TipoContaMap : ClassMap + { + public TipoContaMap() + { + base.Table("tipoconta"); + base.LazyLoad(); + base.Id((TipoContaDb x) => (object)x.Id).GeneratedBy.Increment().Column("idtipoconta"); + base.Map((TipoContaDb x) => x.Descricao).Column("descricao"); + base.Map((TipoContaDb x) => (object)x.Ativo).Column("ativo"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/TipoVendedorMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/TipoVendedorMap.cs new file mode 100644 index 0000000..e1a91d9 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/TipoVendedorMap.cs @@ -0,0 +1,21 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class TipoVendedorMap : ClassMap + { + public TipoVendedorMap() + { + base.Table("tipovendedor"); + base.LazyLoad(); + base.Id((TipoVendedorDb x) => (object)x.Id).GeneratedBy.Assigned().Column("idtipovendedor"); + base.Map((TipoVendedorDb x) => x.Descricao).Column("descricao"); + base.Map((TipoVendedorDb x) => (object)x.Ativo).Column("ativo"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/TitularesVidaMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/TitularesVidaMap.cs new file mode 100644 index 0000000..23b56fa --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/TitularesVidaMap.cs @@ -0,0 +1,33 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class TitularesVidaMap : ClassMap + { + public TitularesVidaMap() + { + base.Table("TitularesVida"); + base.LazyLoad(); + base.Id((TitularesVidaDb x) => (object)x.Id).GeneratedBy.Identity(); + base.References((TitularesVidaDb x) => x.Dependente).Fetch.Join().NotFound.Ignore(); + base.Map((TitularesVidaDb x) => (object)x.IdItem); + base.Map((TitularesVidaDb x) => x.Codigo); + base.Map((TitularesVidaDb x) => (object)x.Inicio).Not.Nullable(); + base.Map((TitularesVidaDb x) => (object)x.Fim); + base.Map((TitularesVidaDb x) => x.Fatura); + base.Map((TitularesVidaDb x) => x.Nome).Not.Nullable(); + base.Map((TitularesVidaDb x) => x.Observacao); + base.Map((TitularesVidaDb x) => (object)x.Nascimento); + base.Map((TitularesVidaDb x) => x.Cpf); + base.Map((TitularesVidaDb x) => x.Matricula); + base.Map((TitularesVidaDb x) => (object)x.Premio); + base.Map((TitularesVidaDb x) => (object)x.Capital); + base.Map((TitularesVidaDb x) => (object)x.Tipo).CustomType().Not.Nullable(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/UsuarioMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/UsuarioMap.cs new file mode 100644 index 0000000..e4579f0 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/UsuarioMap.cs @@ -0,0 +1,69 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class UsuarioMap : ClassMap + { + public UsuarioMap() + { + base.Table("usuario"); + base.LazyLoad(); + base.Id((UsuarioDb x) => (object)x.Id).GeneratedBy.Identity().Column("idusuario"); + base.References((UsuarioDb x) => x.Banco).Column("idcodigobanco").Fetch.Join(); + base.Map((UsuarioDb x) => (object)x.IdEmpresa).Column("idempresa"); + base.Map((UsuarioDb x) => x.Nome).Column("nome"); + base.Map((UsuarioDb x) => (object)x.Nascimento).Column("dtnasc"); + base.Map((UsuarioDb x) => x.Login).Column("identif"); + base.Map((UsuarioDb x) => x.Senha).Column("senha"); + base.Map((UsuarioDb x) => (object)x.Sexo).CustomType().Column("sexo"); + base.Map((UsuarioDb x) => x.Cep).Column("cep"); + base.Map((UsuarioDb x) => x.Endereco).Column("endereco"); + base.Map((UsuarioDb x) => x.Numero).Column("numero"); + base.Map((UsuarioDb x) => x.Complemento).Column("complemento"); + base.Map((UsuarioDb x) => x.Bairro).Column("bairro"); + base.Map((UsuarioDb x) => x.Cidade).Column("cidade"); + base.Map((UsuarioDb x) => x.Estado).Column("uf"); + base.Map((UsuarioDb x) => (object)x.TipoTelefone).CustomType(); + base.Map((UsuarioDb x) => x.Prefixo).Column("ddd"); + base.Map((UsuarioDb x) => x.Telefone).Column("telefone"); + base.Map((UsuarioDb x) => (object)x.TipoTelefone2).CustomType(); + base.Map((UsuarioDb x) => x.Prefixo2).Column("ddd2"); + base.Map((UsuarioDb x) => x.Telefone2).Column("telefone2"); + base.Map((UsuarioDb x) => x.Email).Column("email"); + base.Map((UsuarioDb x) => x.Documento).Column("cgccpf"); + base.Map((UsuarioDb x) => x.Identidade).Column("rg"); + base.Map((UsuarioDb x) => x.EstadoEmissor).Column("rguf"); + base.Map((UsuarioDb x) => (object)x.Expedicao).Column("rgexpedicao"); + base.Map((UsuarioDb x) => x.Agencia).Column("agencia"); + base.Map((UsuarioDb x) => x.Conta).Column("conta"); + base.Map((UsuarioDb x) => (object)x.Mobile).Column("mobile").CustomType(); + base.Map((UsuarioDb x) => (object)x.Resultados).Column("acessoresult").CustomType(); + base.Map((UsuarioDb x) => (object)x.Aggilizador).Column("visualizarcalculo"); + base.Map((UsuarioDb x) => (object)x.Excluido).Column("Removido"); + base.Map((UsuarioDb x) => (object)x.PermissaoAggilizador).Column("IdPermissao"); + base.Map((UsuarioDb x) => (object)x.Administrador).Column("AdmGestor"); + base.Map((UsuarioDb x) => (object)x.InicioAcesso).Column("InicioAcesso"); + base.Map((UsuarioDb x) => (object)x.FimAcesso).Column("FimAcesso"); + base.Map((UsuarioDb x) => (object)x.Segunda); + base.Map((UsuarioDb x) => (object)x.Terca); + base.Map((UsuarioDb x) => (object)x.Quarta); + base.Map((UsuarioDb x) => (object)x.Quinta); + base.Map((UsuarioDb x) => (object)x.Sexta); + base.Map((UsuarioDb x) => (object)x.Sabado); + base.Map((UsuarioDb x) => (object)x.Domingo); + base.Map((UsuarioDb x) => (object)x.TelaInicial).CustomType(); + base.Map((UsuarioDb x) => x.Cargo); + base.Map((UsuarioDb x) => x.Visita); + base.Map((UsuarioDb x) => (object)x.FiltroInicial).CustomType(); + base.Map((UsuarioDb x) => (object)x.Dashboard).Default("0"); + base.Map((UsuarioDb x) => (object)x.AdministradorCentralSegurado).Column("AdmCentralSegurado"); + base.Map((UsuarioDb x) => x.SsoId).CustomSqlType("varchar(30)"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/VendedorMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/VendedorMap.cs new file mode 100644 index 0000000..e423351 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/VendedorMap.cs @@ -0,0 +1,34 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class VendedorMap : ClassMap + { + public VendedorMap() + { + base.Table("vendedor"); + base.LazyLoad(); + base.Id((VendedorDb x) => (object)x.Id).GeneratedBy.Identity().Column("idvendedor"); + base.References((VendedorDb x) => x.Banco).Column("idcodigobanco").Fetch.Join(); + base.Map((VendedorDb x) => (object)x.IdEmpresa).Column("idempresa"); + base.Map((VendedorDb x) => x.Nome).Column("nome"); + base.Map((VendedorDb x) => (object)x.TipoIncidenciaDesconto).Column("tipoincidenciadesconto").Default("0"); + base.Map((VendedorDb x) => (object)x.Desconto).Column("desconto"); + base.Map((VendedorDb x) => x.Documento).Column("cpfcnpj"); + base.Map((VendedorDb x) => x.Conta).Column("conta"); + base.Map((VendedorDb x) => x.Agencia).Column("agencia"); + base.Map((VendedorDb x) => (object)x.TipoConta).Column("idtipoconta"); + base.Map((VendedorDb x) => x.TitularConta).Column("titularconta"); + base.Map((VendedorDb x) => x.TitularDocumento).Column("cpfcnpjtitular"); + base.Map((VendedorDb x) => (object)x.Corretora).Column("corretora").CustomType(); + base.Map((VendedorDb x) => (object)x.Ativo).Column("ativo").CustomType(); + base.Map((VendedorDb x) => x.Observacao).Column("obs").CustomType("StringClob").CustomSqlType("varchar(MAX)"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/VendedorParcelaMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/VendedorParcelaMap.cs new file mode 100644 index 0000000..3bf9115 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/VendedorParcelaMap.cs @@ -0,0 +1,34 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class VendedorParcelaMap : ClassMap + { + public VendedorParcelaMap() + { + base.Table("vendedorparcela"); + base.LazyLoad(); + base.Id((VendedorParcelaDb x) => (object)x.Id).GeneratedBy.Identity().Column("idvendedorparcela"); + base.References((VendedorParcelaDb x) => x.Vendedor).Column("idvendedor").Fetch.Join().Not.Nullable(); + base.References((VendedorParcelaDb x) => x.Documento).Column("iddocumento").Fetch.Join().Not.Nullable(); + base.References((VendedorParcelaDb x) => x.Parcela).Column("idparcela").Fetch.Join(); + base.References((VendedorParcelaDb x) => x.Repasse).Column("idrepasse").Fetch.Join().NotFound.Ignore(); + base.References((VendedorParcelaDb x) => x.CondicaoRepasse).Column("idcondicao").Fetch.Join().NotFound.Ignore(); + base.References((VendedorParcelaDb x) => x.TipoVendedor).Column("idtipovendedor").Not.Nullable().Fetch.Join(); + base.Map((VendedorParcelaDb x) => x.VCondRep).Column("vcondrep"); + base.Map((VendedorParcelaDb x) => (object)x.ValorRepasse).Column("vlrrep"); + base.Map((VendedorParcelaDb x) => (object)x.PorcentagemRepasse).Column("vrep"); + base.Map((VendedorParcelaDb x) => (object)x.ValorRepasseB).Column("vlrrepb"); + base.Map((VendedorParcelaDb x) => (object)x.PorcentagemRepasseB).Column("vrepb"); + base.Map((VendedorParcelaDb x) => (object)x.DataPagamento).Column("datapgt"); + base.Map((VendedorParcelaDb x) => (object)x.DataPrePagamento).Column("dataprepagto"); + base.Map((VendedorParcelaDb x) => (object)x.CoCorretagem).Column("cocorretagem"); + base.Map((VendedorParcelaDb x) => (object)x.ValorTotal).Column("valortotal"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/VendedorTelefoneMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/VendedorTelefoneMap.cs new file mode 100644 index 0000000..09f7b2e --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/VendedorTelefoneMap.cs @@ -0,0 +1,25 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class VendedorTelefoneMap : ClassMap + { + public VendedorTelefoneMap() + { + base.Table("vendcontato"); + base.LazyLoad(); + base.Id((VendedorTelefoneDb x) => (object)x.Id).GeneratedBy.Identity().Column("idvendcontato"); + base.References((VendedorTelefoneDb x) => x.Vendedor).Column("IDVENDEDOR").Not.Nullable().Fetch.Join(); + base.Map((VendedorTelefoneDb x) => x.Nome).Column("nome"); + base.Map((VendedorTelefoneDb x) => (object)x.Tipo).CustomType().Column("idfonetipo"); + base.Map((VendedorTelefoneDb x) => x.Prefixo).Column("ddd"); + base.Map((VendedorTelefoneDb x) => x.Numero).Column("fone"); + base.Map((VendedorTelefoneDb x) => x.Email).Column("email"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/VendedorUsuarioMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/VendedorUsuarioMap.cs new file mode 100644 index 0000000..cceda11 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/VendedorUsuarioMap.cs @@ -0,0 +1,21 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class VendedorUsuarioMap : ClassMap + { + public VendedorUsuarioMap() + { + base.Table("vendedorusuario"); + base.LazyLoad(); + base.Id((VendedorUsuarioDb x) => (object)x.Id).GeneratedBy.Identity().Column("idvendedorusuario"); + base.References((VendedorUsuarioDb x) => x.Usuario).Column("idusuario").Not.Nullable().Fetch.Join(); + base.References((VendedorUsuarioDb x) => x.Vendedor).Column("idvendedor").Not.Nullable().Fetch.Join(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/VidaMap.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/VidaMap.cs new file mode 100644 index 0000000..1ef450f --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Mappings.Seguros/VidaMap.cs @@ -0,0 +1,26 @@ +using FluentNHibernate.Mapping; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using System; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Mappings.Seguros +{ + public class VidaMap : ClassMap + { + public VidaMap() + { + base.Table("vida"); + base.LazyLoad(); + base.Id((VidaDb x) => (object)x.Id).GeneratedBy.Identity().Column("idvida"); + base.References((VidaDb x) => x.Item).Column("iditem").Not.Nullable().Fetch.Join(); + base.Map((VidaDb x) => x.Plano).Column("plano"); + base.Map((VidaDb x) => (object)x.Socios).Column("socios"); + base.Map((VidaDb x) => (object)x.Funcionarios).Column("funcionarios"); + base.Map((VidaDb x) => (object)x.CapitalSocios).Column("capitalsocio"); + base.Map((VidaDb x) => (object)x.CapitalFuncionarios).Column("capitalfunc"); + base.Map((VidaDb x) => x.Observacao).Column("obs").Length(4001); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Generic/GenericRepository_T_.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Generic/GenericRepository_T_.cs new file mode 100644 index 0000000..f0c15d7 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Generic/GenericRepository_T_.cs @@ -0,0 +1,90 @@ +using Gestor.Infrastructure.Entities.Generic; +using NHibernate; +using NHibernate.Linq; +using NHibernate.Util; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Generic +{ + public class GenericRepository : IGenericRepository + where T : class + { + private readonly ISession _currentSession; + + public GenericRepository(ISession currentSession) + { + this._currentSession = currentSession; + } + + public virtual void Add(T entity) + { + this._currentSession.Save(entity); + } + + public void AddRange(IEnumerable entities) + { + if (entities != null) + { + entities.ForEach((T entity) => this._currentSession.Save(entity)); + } + } + + public IQueryable All() + { + return this._currentSession.Query(); + } + + public void Delete(T entity) + { + this._currentSession.Delete(entity); + } + + public void DeleteRange(IEnumerable entities) + { + if (entities != null) + { + entities.ForEach((T entity) => this._currentSession.Delete(entity)); + } + } + + public void Evict(TEntity entity) + where TEntity : EntityBase + { + this._currentSession.Evict(entity); + } + + public T FindEntityById(long id) + { + return this._currentSession.Get(id); + } + + protected void Load(TEntity entity) + where TEntity : EntityBase + { + EntityBase entityBase = entity; + if (entityBase == null) + { + return; + } + this._currentSession.Load(entity, entityBase.Id); + } + + public void Merge(T entity) + { + this._currentSession.Merge(entity); + } + + public virtual void SaveOrUpdate(T entity) + { + this._currentSession.SaveOrUpdate(entity); + } + + public void Update(T entity) + { + this._currentSession.Update(entity); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Generic/IGenericRepository_TEntity_.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Generic/IGenericRepository_TEntity_.cs new file mode 100644 index 0000000..3f43a5c --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Generic/IGenericRepository_TEntity_.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Gestor.Infrastructure.Repository.Generic +{ + public interface IGenericRepository + where TEntity : class + { + void Add(TEntity entity); + + void AddRange(IEnumerable entities); + + IQueryable All(); + + void Delete(TEntity entity); + + void DeleteRange(IEnumerable entities); + + void Evict(TE entity) + where TE : EntityBase; + + TEntity FindEntityById(long id); + + void Merge(TEntity entity); + + void SaveOrUpdate(TEntity entity); + + void Update(TEntity entity); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IAdiantamentoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IAdiantamentoRepository.cs new file mode 100644 index 0000000..75da0da --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IAdiantamentoRepository.cs @@ -0,0 +1,31 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IAdiantamentoRepository : IGenericRepository + { + List AddRange(List adiantamentos); + + List BuscarAdiantamentos(long id, bool concluido = false); + + void Delete(long id); + + List Find(bool ativo); + + List Find(long id); + + List Find(string nome); + + List FindByDate(DateTime filtroInicio, DateTime filtroFim, List vendedores = null, bool segundavia = false); + + Adiantamento FindById(long id); + + Adiantamento Merge(Adiantamento adiantamento); + + Adiantamento SaveOrUpdate(Adiantamento adiantamento); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IAeronauticoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IAeronauticoRepository.cs new file mode 100644 index 0000000..f2c1849 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IAeronauticoRepository.cs @@ -0,0 +1,23 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IAeronauticoRepository : IGenericRepository + { + void Delete(long id); + + void DeleteRange(List ids); + + Aeronautico Find(long id); + + Aeronautico FindById(long id); + + Aeronautico Merge(Aeronautico aeronautico); + + Aeronautico SaveOrUpdate(Aeronautico aeronautico); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IAgendaEmailRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IAgendaEmailRepository.cs new file mode 100644 index 0000000..6e4ffa1 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IAgendaEmailRepository.cs @@ -0,0 +1,29 @@ +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Ferramentas; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IAgendaEmailRepository : IGenericRepository + { + void Delete(long id); + + List FindByAgenda(List ids); + + List FindByAgendaId(long id); + + AgendaEmail FindById(long id); + + List FindEmailAgenda(string email); + + List Inserir(List emails, Agenda agenda); + + AgendaEmail Merge(AgendaEmail agendaEmail); + + List Merge(List emails, Agenda agenda); + + AgendaEmail SaveOrUpdate(AgendaEmail agendaEmail); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IAgendaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IAgendaRepository.cs new file mode 100644 index 0000000..f3bface --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IAgendaRepository.cs @@ -0,0 +1,25 @@ +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Ferramentas; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IAgendaRepository : IGenericRepository + { + void Delete(long id); + + List Find(string value); + + List Find(); + + Agenda FindById(long id); + + List FindByName(string filter); + + Agenda Merge(Agenda agenda); + + Agenda SaveOrUpdate(Agenda agenda); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IAgendaTelefoneRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IAgendaTelefoneRepository.cs new file mode 100644 index 0000000..809c6f9 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IAgendaTelefoneRepository.cs @@ -0,0 +1,29 @@ +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Ferramentas; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IAgendaTelefoneRepository : IGenericRepository + { + void Delete(long id); + + List Find(string telefone); + + List FindByAgendaId(long id); + + AgendaTelefone FindById(long id); + + List Inserir(List telefones); + + List Inserir(List telefones, Agenda agenda); + + AgendaTelefone Merge(AgendaTelefone telefone); + + List Merge(List telefones, Agenda agenda); + + AgendaTelefone SaveOrUpdate(AgendaTelefone telefone); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IAtividadeRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IAtividadeRepository.cs new file mode 100644 index 0000000..ea45a75 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IAtividadeRepository.cs @@ -0,0 +1,19 @@ +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Common; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IAtividadeRepository : IGenericRepository + { + List Find(string filter); + + long FindLastId(); + + Atividade Merge(Atividade atividade); + + Atividade SaveOrUpdate(Atividade atividade); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IAtualizacaoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IAtualizacaoRepository.cs new file mode 100644 index 0000000..3d37a87 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IAtualizacaoRepository.cs @@ -0,0 +1,11 @@ +using System; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IAtualizacaoRepository + { + long FindLastUpdate(); + + void Save(long fileId); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IAutoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IAutoRepository.cs new file mode 100644 index 0000000..c77221a --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IAutoRepository.cs @@ -0,0 +1,31 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IAutoRepository : IGenericRepository + { + void Delete(long id); + + void DeleteRange(List ids); + + Auto Find(long id); + + List FindAuto(string pesquisa, FiltroStatusDocumento status, List vendedorVinculado, TipoPesquisa tipo, bool tipobusca = false); + + Documento FindByChassi(string chassi, long id, DateTime vigencia1, DateTime? vigencia2, long idSeguradora); + + Auto FindById(long id); + + string FindChassi(long id); + + Auto Merge(Auto auto); + + Auto SaveOrUpdate(Auto auto); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IBancoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IBancoRepository.cs new file mode 100644 index 0000000..3cc18b7 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IBancoRepository.cs @@ -0,0 +1,23 @@ +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Common; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IBancoRepository : IGenericRepository + { + void Delete(long id); + + List Find(string filter); + + Banco FindById(long id); + + Banco Merge(Banco banco); + + Banco SaveOrUpdate(Banco banco); + + List SelectDefault(); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IBancosContasRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IBancosContasRepository.cs new file mode 100644 index 0000000..4dde7eb --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IBancosContasRepository.cs @@ -0,0 +1,23 @@ +using Gestor.Infrastructure.Entities.Financeiro; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Financeiro; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IBancosContasRepository : IGenericRepository + { + void Delete(long id); + + List Find(string descricao); + + List Find(); + + BancosContas FindById(long id); + + BancosContas Merge(BancosContas bancosContas); + + BancosContas SaveOrUpdate(BancosContas bancosContas); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ICategoriaTarefaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ICategoriaTarefaRepository.cs new file mode 100644 index 0000000..9350ddf --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ICategoriaTarefaRepository.cs @@ -0,0 +1,18 @@ +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Ferramentas; +using System; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface ICategoriaTarefaRepository : IGenericRepository + { + void Delete(long id); + + CategoriaTarefa FindById(long id); + + CategoriaTarefa Merge(CategoriaTarefa categoriaTarefa); + + CategoriaTarefa SaveOrUpdate(CategoriaTarefa categoriaTarefa); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ICentroRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ICentroRepository.cs new file mode 100644 index 0000000..fe55492 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ICentroRepository.cs @@ -0,0 +1,19 @@ +using Gestor.Infrastructure.Entities.Financeiro; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Financeiro; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface ICentroRepository : IGenericRepository + { + List Find(string descricao); + + List Find(); + + Centro Merge(Centro centro); + + Centro SaveOrUpdate(Centro centro); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IClienteEmailRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IClienteEmailRepository.cs new file mode 100644 index 0000000..d14e969 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IClienteEmailRepository.cs @@ -0,0 +1,31 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IClienteEmailRepository : IGenericRepository + { + void Delete(long id); + + List DeleteMail(long clienteId, List emails); + + List FindByCliente(List ids); + + List FindByClienteId(long id); + + ClienteEmail FindById(long id); + + List FindEmailCliente(string email, long idempresa = 0L); + + List Inserir(List emails, Cliente cliente); + + ClienteEmail Merge(ClienteEmail clienteEmail); + + List Merge(List emails, Cliente cliente); + + ClienteEmail SaveOrUpdate(ClienteEmail clienteEmail); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IClienteEnderecoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IClienteEnderecoRepository.cs new file mode 100644 index 0000000..cba09be --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IClienteEnderecoRepository.cs @@ -0,0 +1,29 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IClienteEnderecoRepository : IGenericRepository + { + void Delete(long id); + + List DeleteEndereco(long clienteId, List enderecos); + + List FindByCliente(List clientes); + + List FindByClienteId(long id); + + ClienteEndereco FindById(long id); + + List Inserir(List endereco, Cliente cliente); + + ClienteEndereco Merge(ClienteEndereco clienteEndereco); + + List Merge(List enderecos, Cliente cliente); + + ClienteEndereco SaveOrUpdate(ClienteEndereco clienteEndereco); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IClienteRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IClienteRepository.cs new file mode 100644 index 0000000..e65df00 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IClienteRepository.cs @@ -0,0 +1,72 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Relatorios.Classificacao; +using Gestor.Model.Domain.Relatorios.ClientesAtivosInativos; +using Gestor.Model.Domain.Relatorios.Dashboard; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IClienteRepository : IGenericRepository + { + void AddCentralSegurado(long id, bool update); + + Task> BuscaClientes(bool completo, long idempresa); + + Task> BuscaClientesVinculo(bool completo, List vinculo, long idempresa); + + DateTime? BuscaNascimeto(long id); + + Task> BuscaProspeccoes(Filtros filtro, long idEmpresa = 0L); + + List BuscarAniversariantes(Filtros filtro, long idempresa = 0L); + + List BuscarAniversariantesVinculo(Filtros filtro, List vinculo, long idempresa = 0L); + + Task> BuscarClassificacoes(long id); + + string BuscarLogAntigo(long id, string connection); + + List BuscarOrigem(long id); + + List BuscarVencimentoCnh(Filtros filtro, long idempresa = 0L); + + void Delete(long id); + + void DeleteOrigem(long id); + + List Find(string filter, long idempresa = 0L, bool acessoAgger = false, bool assintatura = false); + + List FindAllClientes(bool completo, long idempresa = 0L); + + Cliente FindById(long id); + + List FindByName(string filter, long idempresa = 0L, bool acessoAgger = false, bool assintatura = false, bool somenteNome = false); + + List FindClienteDocumento(string documento); + + List FindClienteVinculo(string filter, List vinculos, long idempresa = 0L, bool acessoAgger = false, bool assinatura = false, TipoFiltroCliente tipoFiltroCliente = 2); + + List FindObsCliente(string obsCliente, long idempresa = 0L); + + List FindPastaCliente(string pastaCliente, bool busca = false, long idempresa = 0L); + + List FindVinculo(string filter, long id); + + Cliente Merge(Cliente cliente); + + OrigemCliente Merge(OrigemCliente origem); + + Cliente SaveOrUpdate(Cliente cliente); + + OrigemCliente SaveOrUpdate(OrigemCliente origem); + + List Sincronize(List origens, long id); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IClienteTelefoneRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IClienteTelefoneRepository.cs new file mode 100644 index 0000000..4eea2ac --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IClienteTelefoneRepository.cs @@ -0,0 +1,31 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IClienteTelefoneRepository : IGenericRepository + { + void Delete(long id); + + List DeleteFone(long clienteId, List telefones); + + List Find(string telefone, long idempresa = 0L); + + List FindByClienteId(long id); + + ClienteTelefone FindById(long id); + + List Inserir(List telefones); + + List Inserir(List telefones, Cliente cliente); + + ClienteTelefone Merge(ClienteTelefone telefone); + + List Merge(List telefones, Cliente cliente); + + ClienteTelefone SaveOrUpdate(ClienteTelefone telefone); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IClienteVinculoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IClienteVinculoRepository.cs new file mode 100644 index 0000000..a399178 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IClienteVinculoRepository.cs @@ -0,0 +1,25 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IClienteVinculoRepository : IGenericRepository + { + void Delete(long id); + + List DeleteVinculo(long clienteId, List vinculos); + + List FindByCliente(long id); + + ClienteVinculo FindById(long id); + + List Inserir(List vinculos, Cliente cliente); + + List Merge(List contatos, Cliente cliente); + + ClienteVinculo SaveOrUpdate(ClienteVinculo clienteVinculo); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ICoberturaGranizoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ICoberturaGranizoRepository.cs new file mode 100644 index 0000000..620e2af --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ICoberturaGranizoRepository.cs @@ -0,0 +1,21 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface ICoberturaGranizoRepository : IGenericRepository + { + void Delete(long id); + + List Find(long id); + + CoberturaGranizo FindById(long id); + + CoberturaGranizo Merge(CoberturaGranizo cobertura); + + CoberturaGranizo SaveOrUpdate(CoberturaGranizo cobertura); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ICoberturaPadraoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ICoberturaPadraoRepository.cs new file mode 100644 index 0000000..ed82a3d --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ICoberturaPadraoRepository.cs @@ -0,0 +1,23 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface ICoberturaPadraoRepository : IGenericRepository + { + void Delete(long id); + + List Find(); + + CoberturaPadrao FindById(long id); + + List FindByRamoId(long id); + + CoberturaPadrao Merge(CoberturaPadrao coberturaPadrao); + + CoberturaPadrao SaveOrUpdate(CoberturaPadrao coberturaPadrao); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ICoberturaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ICoberturaRepository.cs new file mode 100644 index 0000000..e2f5a01 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ICoberturaRepository.cs @@ -0,0 +1,29 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface ICoberturaRepository : IGenericRepository + { + List AddRange(List coberturas); + + void Delete(long id); + + void DeletebyItem(long id); + + void DeleteRange(List ids); + + Cobertura FindById(long id); + + List FindByItemId(long id); + + Cobertura Merge(Cobertura cobertura); + + List MergeRange(List coberturas); + + Cobertura SaveOrUpdate(Cobertura cobertura); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ICondicaoRepasseRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ICondicaoRepasseRepository.cs new file mode 100644 index 0000000..367005b --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ICondicaoRepasseRepository.cs @@ -0,0 +1,18 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface ICondicaoRepasseRepository : IGenericRepository + { + void Delete(long id); + + CondicaoRepasse FindById(long id); + + CondicaoRepasse Merge(CondicaoRepasse condicaoRepasse); + + CondicaoRepasse SaveOrUpdate(CondicaoRepasse condicaoRepasse); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IConfigExtratoImportRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IConfigExtratoImportRepository.cs new file mode 100644 index 0000000..c1bf651 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IConfigExtratoImportRepository.cs @@ -0,0 +1,27 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IConfigExtratoImportRepository : IGenericRepository + { + void Delete(long id); + + List Find(bool ativo); + + List Find(); + + ConfigExtratoImport FindById(long id); + + List FindBySeguradora(long id); + + Gestor.Model.Domain.Seguros.ConfigExtratoImport Merge(Gestor.Model.Domain.Seguros.ConfigExtratoImport ConfigExtratoImport); + + List MergeRange(List ConfigExtratoImport); + + Gestor.Model.Domain.Seguros.ConfigExtratoImport SaveOrUpdate(Gestor.Model.Domain.Seguros.ConfigExtratoImport ConfigExtratoImport); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IConfiguracaoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IConfiguracaoRepository.cs new file mode 100644 index 0000000..2232774 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IConfiguracaoRepository.cs @@ -0,0 +1,22 @@ +using Gestor.Infrastructure.Entities.Configuracoes; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Configuracoes; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IConfiguracaoRepository : IGenericRepository + { + List BuscarConfiguracoes(); + + void Delete(long id); + + ConfiguracaoSistema Find(Configuracao configuracao); + + ConfiguracaoSistema Merge(ConfiguracaoSistema configuracao); + + ConfiguracaoSistema SaveOrUpdate(ConfiguracaoSistema configuracao); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IConsorcioRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IConsorcioRepository.cs new file mode 100644 index 0000000..db9ce96 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IConsorcioRepository.cs @@ -0,0 +1,23 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IConsorcioRepository : IGenericRepository + { + void Delete(long id); + + void DeleteRange(List ids); + + Consorcio Find(long id); + + Consorcio FindById(long id); + + Consorcio Merge(Consorcio risco); + + Consorcio SaveOrUpdate(Consorcio risco); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IControleFinanceiroRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IControleFinanceiroRepository.cs new file mode 100644 index 0000000..3205e4a --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IControleFinanceiroRepository.cs @@ -0,0 +1,21 @@ +using Gestor.Infrastructure.Entities.Financeiro; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Financeiro; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IControleFinanceiroRepository : IGenericRepository + { + void Delete(long id); + + List FindByFornecedor(long id); + + ControleFinanceiro FindById(long id); + + ControleFinanceiro Merge(ControleFinanceiro controle); + + ControleFinanceiro SaveOrUpdate(ControleFinanceiro controle); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IControleRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IControleRepository.cs new file mode 100644 index 0000000..3d04cd2 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IControleRepository.cs @@ -0,0 +1,23 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IControleRepository : IGenericRepository + { + void Delete(long id); + + IEnumerable FindByCustomerId(long id); + + Controle FindById(long id); + + Controle Merge(Controle controle); + + Controle SaveOrUpdate(Controle controle); + + IEnumerable SelectDocumentIds(long id); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IControleSinistroRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IControleSinistroRepository.cs new file mode 100644 index 0000000..61f5fe1 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IControleSinistroRepository.cs @@ -0,0 +1,27 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IControleSinistroRepository : IGenericRepository + { + void Delete(long id); + + void DeleteByItem(long id); + + void DeleteRange(List ids); + + ControleSinistro FindById(long id); + + List FindByIdItem(long id); + + bool HasSinistro(long id); + + ControleSinistro Merge(ControleSinistro controle); + + ControleSinistro SaveOrUpdate(ControleSinistro controle); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ICredencialRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ICredencialRepository.cs new file mode 100644 index 0000000..67ef505 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ICredencialRepository.cs @@ -0,0 +1,23 @@ +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Ferramentas; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface ICredencialRepository : IGenericRepository + { + void Delete(long id); + + List Find(long idEmpresa); + + List Find(string descricao, long idEmpresa); + + Credencial FindById(long id); + + Credencial Merge(Credencial credencial); + + Credencial SaveOrUpdate(Credencial credencial); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ICriticaApoliceRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ICriticaApoliceRepository.cs new file mode 100644 index 0000000..8766bbf --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ICriticaApoliceRepository.cs @@ -0,0 +1,33 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface ICriticaApoliceRepository : IGenericRepository + { + List BuscarUsuarioCritica(DateTime inicio, DateTime fim, bool criticado = false, long idempresa = 0L); + + void Delete(long id); + + List Find(long usuario, DateTime inicio, DateTime fim, long idCorretora, bool criticado = false, long idempresa = 0L, List vinculos = null, bool vendedorEmBranco = false, bool vinculoVendedorCritica = false); + + List Find(DateTime inicio, DateTime fim, long idempresa = 0L); + + List Find(long id); + + CriticaApolice FindByApolice(long id); + + CriticaApolice FindById(long id); + + List FindDuo(long id, DateTime vigencia); + + List FindImport(long id); + + CriticaApolice Merge(CriticaApolice documento); + + CriticaApolice SaveOrUpdate(CriticaApolice documento); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IDetalheExtratoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IDetalheExtratoRepository.cs new file mode 100644 index 0000000..0ac35c8 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IDetalheExtratoRepository.cs @@ -0,0 +1,25 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IDetalheExtratoRepository : IGenericRepository + { + void Delete(long id); + + List Find(long id); + + DetalheExtrato FindById(long id); + + List FindByLongId(long? id); + + DetalheExtrato FindByParcelaId(long id); + + DetalheExtrato Merge(DetalheExtrato parcela); + + DetalheExtrato SaveOrUpdate(DetalheExtrato parcela); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IDocumentoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IDocumentoRepository.cs new file mode 100644 index 0000000..277a960 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IDocumentoRepository.cs @@ -0,0 +1,68 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Relatorios.Fechamento; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.License; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IDocumentoRepository : IGenericRepository + { + bool AtualizarNumero(long id, string numero, string endosso, int tipoDocumento); + + List Auditoria(Filtros filtro); + + Task> BuscaDocumentosPorVigencia(Filtros filtro, bool buscaAssinaturas = false, bool painelBi = false); + + List BuscarDocumentoPorEstipulante(long id); + + List BuscarDocumentoPorStatus(long id); + + string BuscarLogAntigo(long id, string conn); + + List BuscarPlanilhaCompletaProspeccao(List ids); + + int Cotacoes(Filtros filtro); + + void Delete(long id); + + Task> Fechamento(Filtros filtro); + + List FindApolice(string pesquisa, FiltroStatusDocumento status, List vendedorVinculado, string campo, long idempresa = 0L, bool vendedorembranco = false, bool tipobusca = false); + + List FindApoliceByCustomer(long idCliente, FiltroStatusDocumento status, List vendedorVinculado, List licencas, bool endosso = false, bool acessoAgger = false, bool vendedorembranco = false); + + List FindByControle(long id); + + Documento FindById(long id, bool itens = false, bool sinistrosPorControle = false); + + Documento FindById(long id, List vendedorVinculado); + + List FindByIds(List ids); + + List FindByLicenciamento(Filtros filtro); + + List FindByParcelaIds(List ids); + + List FindByPlaca(Filtros filtro); + + List FindByVigenciaFinal(Filtros filtro, List licencas, bool somarPremios); + + Task> FindEndossoByVigencia(Filtros filtro, bool buscarAssinatura = false); + + List FindPendenciasByVigencia(Filtros filtro); + + Documento Merge(Documento documento); + + void SalvarAssistencia(string id, long idcontrole); + + Documento SaveOrUpdate(Documento documento); + + void TrocarCliente(Controle controle, Cliente cliente); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IEmpresaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IEmpresaRepository.cs new file mode 100644 index 0000000..1b30b68 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IEmpresaRepository.cs @@ -0,0 +1,32 @@ +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IEmpresaRepository : IGenericRepository + { + string BuscarSenhaAdm(long idempresa = 1L); + + double ConsultaEspacoBancoInGb(); + + void Delete(long id); + + List Find(long idempresa = 0L); + + List FindAsCliente(string filter); + + Empresa FindByDocumento(string documento); + + Empresa FindById(long id); + + Empresa FindBySerial(string serial); + + Empresa Merge(Empresa empresa); + + Empresa SaveOrUpdate(Empresa empresa); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IEstipulanteRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IEstipulanteRepository.cs new file mode 100644 index 0000000..c532c4e --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IEstipulanteRepository.cs @@ -0,0 +1,23 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IEstipulanteRepository : IGenericRepository + { + void Delete(long id); + + List Find(string value, long idempresa = 0L); + + List Find(); + + Estipulante FindById(long id); + + Estipulante Merge(Estipulante empresa); + + Estipulante SaveOrUpdate(Estipulante empresa); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IExpedicaoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IExpedicaoRepository.cs new file mode 100644 index 0000000..bd2979d --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IExpedicaoRepository.cs @@ -0,0 +1,19 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IExpedicaoRepository : IGenericRepository + { + void Delete(long id); + + List FindByIdDocumento(long IdDocumento); + + Expedicao Merge(Expedicao expedicao); + + Expedicao SaveOrUpdate(Expedicao expedicao); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IExtratoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IExtratoRepository.cs new file mode 100644 index 0000000..395f10f --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IExtratoRepository.cs @@ -0,0 +1,31 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IExtratoRepository : IGenericRepository + { + void Delete(long id); + + List FindByData(Filtros filtro); + + List FindByEmpresa(long id); + + Extrato FindById(long id); + + List FindBySeguradora(long id, long idusuario, long empresa, DateTime inicio, DateTime fim, StatusExtrato? status = null); + + List FindByStatus(StatusExtrato status); + + List FindSeguradoras(StatusExtrato status); + + Extrato Merge(Extrato extrato); + + Extrato SaveOrUpdate(Extrato extrato); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IFabricanteRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IFabricanteRepository.cs new file mode 100644 index 0000000..af987ed --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IFabricanteRepository.cs @@ -0,0 +1,23 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IFabricanteRepository : IGenericRepository + { + void Delete(long id); + + List Find(string filter); + + Fabricante FindById(long id); + + Fabricante Merge(Fabricante fabricante); + + Fabricante SaveOrUpdate(Fabricante fabricante); + + List Select(); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IFornecedorRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IFornecedorRepository.cs new file mode 100644 index 0000000..5b8f9b6 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IFornecedorRepository.cs @@ -0,0 +1,23 @@ +using Gestor.Infrastructure.Entities.Financeiro; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Financeiro; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IFornecedorRepository : IGenericRepository + { + void Delete(long id); + + List Find(string filter, bool ativo); + + List Find(); + + Fornecedor FindById(long id); + + Fornecedor Merge(Fornecedor fornecedor); + + Fornecedor SaveOrUpdate(Fornecedor fornecedor); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IGranizoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IGranizoRepository.cs new file mode 100644 index 0000000..f8e456d --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IGranizoRepository.cs @@ -0,0 +1,23 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IGranizoRepository : IGenericRepository + { + void Delete(long id); + + void DeleteRange(List ids); + + Granizo Find(long id); + + Granizo FindById(long id); + + Granizo Merge(Granizo granizo); + + Granizo SaveOrUpdate(Granizo granizo); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IImpostoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IImpostoRepository.cs new file mode 100644 index 0000000..9e1a522 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IImpostoRepository.cs @@ -0,0 +1,23 @@ +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Ferramentas; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IImpostoRepository : IGenericRepository + { + List DefaultSelect(bool? ativo); + + Imposto FindById(long id); + + List FindByRamo(long id); + + List FindBySeguradora(long id); + + Imposto Merge(Imposto imposto); + + Imposto SaveOrUpdate(Imposto imposto); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IIndiceArquivoDigitalRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IIndiceArquivoDigitalRepository.cs new file mode 100644 index 0000000..fc3a993 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IIndiceArquivoDigitalRepository.cs @@ -0,0 +1,34 @@ +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IIndiceArquivoDigitalRepository : IGenericRepository + { + ControleArquivoDigital BuscarBanco(); + + List BuscarBancos(); + + ControleArquivoDigital ConsultarBanco(string banco); + + void Delete(long id); + + List Find(TipoArquivoDigital tipo, long id, long usuario, bool buscarAssinaturas = false); + + ArquivoDigital FindAssinatura(long id); + + List FindAssinatura(List id); + + IndiceArquivoDigital FindById(long id); + + IndiceArquivoDigital Merge(IndiceArquivoDigital indice); + + IndiceArquivoDigital SaveOrUpdate(IndiceArquivoDigital indice); + + ControleArquivoDigital SaveOrUpdate(ControleArquivoDigital catalogo); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IItemRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IItemRepository.cs new file mode 100644 index 0000000..04578fa --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IItemRepository.cs @@ -0,0 +1,44 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IItemRepository : IGenericRepository + { + Task> BuscaItensPorObs(string pesquisa, FiltroStatusDocumento status, List vendedorVinculado, TipoPesquisa tipo, bool tipobusca = false); + + Cliente BuscarCliente(long id); + + int ChecarQuantidade(long idDocumento); + + void Delete(long id); + + void DeleteRange(List ids); + + List FindByDocumentsIds(long id, StatusItem status = 0, bool sinistroCompleto = false); + + Item FindById(long id); + + List FindByIds(List ids); + + List FindItens(long id, StatusItem status); + + List FindItens(List documento); + + List FindItens(long id); + + List FindItens(List ids); + + int FindNextItem(long id); + + Item Merge(Item empresa); + + Item SaveOrUpdate(Item empresa); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ILancamentoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ILancamentoRepository.cs new file mode 100644 index 0000000..e91d625 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ILancamentoRepository.cs @@ -0,0 +1,55 @@ +using Gestor.Infrastructure.Entities.Financeiro; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Financeiro.Relatorios; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface ILancamentoRepository : IGenericRepository + { + List AddRange(List lancamento); + + bool BancosContasUtilizado(long id); + + void Delete(long id); + + List Fechamento(FiltroFinanceiro filtro); + + Saldo FecharSaldo(Saldo saldo); + + List Find(DateTime inicio, DateTime fim, StatusLancamento status); + + List FindByBaixa(DateTime inicio, DateTime fim); + + List FindByCodigoBanco(List codigos); + + List FindByConta(DateTime inicio, DateTime fim, long id); + + List FindByControle(long id, StatusLancamento status); + + Lancamento FindByControle(long id, int parcela); + + List FindByFornecedor(long id, StatusLancamento status); + + List FindByFornecedor(long id, DateTime date, Sinal sinal); + + Lancamento FindById(long id); + + List FindByLancamento(DateTime inicio, DateTime fim, StatusLancamento status); + + List FindByPagamento(DateTime inicio, DateTime fim); + + List FindLancamentosByConta(DateTime inicio, DateTime fim, long id); + + List FindPersonalizado(DateTime inicio, DateTime fim, StatusLancamento status, FiltroLancamentoData filtrodata); + + bool HasByFornecedor(long id); + + Lancamento Merge(Lancamento lancamento); + + Lancamento SaveOrUpdate(Lancamento lancamento); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IMaisContatoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IMaisContatoRepository.cs new file mode 100644 index 0000000..0d92bad --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IMaisContatoRepository.cs @@ -0,0 +1,27 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IMaisContatoRepository : IGenericRepository + { + void Delete(long id); + + List DeleteContato(long clienteId, List contatos); + + List FindByCustomerId(long id); + + MaisContato FindById(long id); + + List Inserir(List contatos, Cliente cliente); + + MaisContato Merge(MaisContato maisContato); + + List Merge(List contatos, Cliente cliente); + + MaisContato SaveOrUpdate(MaisContato maisContato); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IMetaSeguradoraRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IMetaSeguradoraRepository.cs new file mode 100644 index 0000000..12b8b10 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IMetaSeguradoraRepository.cs @@ -0,0 +1,24 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IMetaSeguradoraRepository : IGenericRepository + { + void Delete(long id); + + List Find(long id); + + MetaSeguradora FindById(long id); + + List FindByMeta(Filtros filtro); + + MetaSeguradora Merge(MetaSeguradora metaSeguradora); + + MetaSeguradora SaveOrUpdate(MetaSeguradora metaSeguradora); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IMetaVendedorRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IMetaVendedorRepository.cs new file mode 100644 index 0000000..d1f88a6 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IMetaVendedorRepository.cs @@ -0,0 +1,24 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IMetaVendedorRepository : IGenericRepository + { + void Delete(long id); + + List Find(long id); + + MetaVendedor FindById(long id); + + List FindByMeta(Filtros filtro); + + MetaVendedor Merge(MetaVendedor metaVendedor); + + MetaVendedor SaveOrUpdate(MetaVendedor metaVendedor); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IModeloMalaDiretaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IModeloMalaDiretaRepository.cs new file mode 100644 index 0000000..3c39958 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IModeloMalaDiretaRepository.cs @@ -0,0 +1,21 @@ +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.MalaDireta; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IModeloMalaDiretaRepository : IGenericRepository + { + void Delete(long id); + + List Find(); + + ModeloMalaDireta FindById(long id); + + ModeloMalaDireta Merge(ModeloMalaDireta modelo); + + ModeloMalaDireta SaveOrUpdate(ModeloMalaDireta modelo); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/INotaFiscalRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/INotaFiscalRepository.cs new file mode 100644 index 0000000..cba9155 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/INotaFiscalRepository.cs @@ -0,0 +1,24 @@ +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Relatorios; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface INotaFiscalRepository : IGenericRepository + { + void Delete(long id); + + List FindAll(); + + List FindByDatas(Filtros filtro); + + bool FindByExtrato(long id); + + NotaFiscal Merge(NotaFiscal notaFiscal); + + NotaFiscal SaveOrUpdate(NotaFiscal notaFiscal); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IParametrosRelatorioRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IParametrosRelatorioRepository.cs new file mode 100644 index 0000000..555ac56 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IParametrosRelatorioRepository.cs @@ -0,0 +1,20 @@ +using Gestor.Infrastructure.Entities.Relatorios; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Relatorios; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IParametrosRelatorioRepository : IGenericRepository + { + void Delete(long id); + + List Find(long id, Relatorio relatorio); + + ParametrosRelatorio Merge(ParametrosRelatorio parametrosRelatorio); + + ParametrosRelatorio SaveOrUpdate(ParametrosRelatorio parametrosRelatorio); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IParametrosTotalizacaoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IParametrosTotalizacaoRepository.cs new file mode 100644 index 0000000..e1f0bbc --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IParametrosTotalizacaoRepository.cs @@ -0,0 +1,20 @@ +using Gestor.Infrastructure.Entities.Relatorios; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Relatorios; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IParametrosTotalizacaoRepository : IGenericRepository + { + void Delete(long id); + + List Find(long id, Relatorio relatorio); + + ParametrosTotalizacao Merge(ParametrosTotalizacao parametrosTotalizacao); + + ParametrosTotalizacao SaveOrUpdate(ParametrosTotalizacao parametrosTotalizacao); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IParceiroRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IParceiroRepository.cs new file mode 100644 index 0000000..76ae828 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IParceiroRepository.cs @@ -0,0 +1,25 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IParceiroRepository : IGenericRepository + { + void Delete(long id); + + List Find(); + + List Find(string filter); + + Parceiro FindById(long id); + + long FindLastId(); + + Parceiro Merge(Parceiro parceiro); + + Parceiro SaveOrUpdate(Parceiro parceiro); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IParcelaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IParcelaRepository.cs new file mode 100644 index 0000000..46850f7 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IParcelaRepository.cs @@ -0,0 +1,67 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Aggilizador; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Relatorios.PrevisaoPagamentoComissao; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IParcelaRepository : IGenericRepository + { + Task> BuscaDocumentosPorVigencia(Filtros filtro, bool buscaAssinaturas = false, bool painelBi = false); + + Documento BuscarApolice(long id); + + string BuscarLogAntigo(long id, string conn); + + ParcelaPendente BuscarPendencia(long id); + + void Delete(long id); + + void DeleteRange(long id); + + bool ExcluirVinculoParcelaPendenteDocExcluido(Documento doc); + + Task> FaturaPendente(Filtros filtro); + + List FindByDocumentId(long id); + + List FindByDocumentId(List ids); + + List FindByDocumentIds(string ids, List documentos); + + List FindByDocumento(Documento documento); + + Parcela FindById(long id); + + List FindByPagamento(Filtros filtro, bool reciboPagamento, bool segundaViaReciboPagamento, bool datacontrole); + + List FindByPendente(Filtros filtro, bool pendente, bool somenteAtivos); + + Task> FindByRecebimento(Filtros filtro); + + List FindByVencimento(Filtros filtro); + + List FindByVigencia(Filtros filtro); + + List FindDocumentId(List ids); + + List FindNumFatura(string numero); + + Parcela Merge(Parcela parcela); + + List PrevisaoPagamentoComissao(Filtros filtro); + + Parcela SaveOrUpdate(Parcela parcela); + + int[] SincronizarPendencia(DateTime date, List ids = null); + + bool Update(List detalhes, bool desabilitaAproximacao); + + List UpdateRange(List parcelas); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IPatrimonialRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IPatrimonialRepository.cs new file mode 100644 index 0000000..318f5a8 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IPatrimonialRepository.cs @@ -0,0 +1,29 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IPatrimonialRepository : IGenericRepository + { + void Delete(long id); + + void DeleteRange(List ids); + + Patrimonial Find(long id); + + Patrimonial FindById(long id); + + List FindImobiliaria(string imobiliaria, FiltroStatusDocumento status, List vendedorVinculado); + + List Findlocatario(string imobiliaria, FiltroStatusDocumento status, List vendedorVinculado); + + Patrimonial Merge(Patrimonial patrimonial); + + Patrimonial SaveOrUpdate(Patrimonial patrimonial); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IPerfilEmpresaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IPerfilEmpresaRepository.cs new file mode 100644 index 0000000..fe26532 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IPerfilEmpresaRepository.cs @@ -0,0 +1,20 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IPerfilEmpresaRepository : IGenericRepository + { + void Delete(long id); + + PerfilEmpresa Find(long id); + + PerfilEmpresa FindByControleId(long id); + + PerfilEmpresa Merge(PerfilEmpresa perfil); + + PerfilEmpresa SaveOrUpdate(PerfilEmpresa perfil); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IPerfilRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IPerfilRepository.cs new file mode 100644 index 0000000..bc721d4 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IPerfilRepository.cs @@ -0,0 +1,23 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IPerfilRepository : IGenericRepository + { + void Delete(long id); + + Perfil Find(long id); + + List FindByControleId(long id); + + List FindByControleIds(string ids); + + Perfil Merge(Perfil perfil); + + Perfil SaveOrUpdate(Perfil perfil); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IPermissaoArquivoDigitalRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IPermissaoArquivoDigitalRepository.cs new file mode 100644 index 0000000..4a75173 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IPermissaoArquivoDigitalRepository.cs @@ -0,0 +1,18 @@ +using Gestor.Model.Common; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IPermissaoArquivoDigitalRepository + { + PermissaoArquivoDigital FindByPermissao(long id, TipoArquivoDigital tela); + + List FindByUsuario(long id); + + PermissaoArquivoDigital Merge(PermissaoArquivoDigital permissao); + + PermissaoArquivoDigital SaveOrUpdate(PermissaoArquivoDigital permissao); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IPermissaoUsuarioRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IPermissaoUsuarioRepository.cs new file mode 100644 index 0000000..07fd4fe --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IPermissaoUsuarioRepository.cs @@ -0,0 +1,18 @@ +using Gestor.Model.Common; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IPermissaoUsuarioRepository + { + PermissaoUsuario FindByPermissao(long id, TipoTela tela); + + List FindByUsuario(long id); + + PermissaoUsuario Merge(PermissaoUsuario permissao); + + PermissaoUsuario SaveOrUpdate(PermissaoUsuario permissao); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IPlanoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IPlanoRepository.cs new file mode 100644 index 0000000..b5722d8 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IPlanoRepository.cs @@ -0,0 +1,19 @@ +using Gestor.Infrastructure.Entities.Financeiro; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Financeiro; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IPlanoRepository : IGenericRepository + { + List Find(string descricao); + + List Find(); + + Plano Merge(Plano plano); + + Plano SaveOrUpdate(Plano plano); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IPlanosRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IPlanosRepository.cs new file mode 100644 index 0000000..e12b184 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IPlanosRepository.cs @@ -0,0 +1,23 @@ +using Gestor.Infrastructure.Entities.Financeiro; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Financeiro; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IPlanosRepository : IGenericRepository + { + List Find(string descricao); + + List Find(); + + Planos FindById(long id); + + List FindByPlanoId(long id); + + Planos Merge(Planos planos); + + Planos SaveOrUpdate(Planos planos); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IProdutoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IProdutoRepository.cs new file mode 100644 index 0000000..703cc69 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IProdutoRepository.cs @@ -0,0 +1,23 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IProdutoRepository : IGenericRepository + { + void Delete(long id); + + List Find(string value); + + List Find(); + + Produto FindById(long id); + + Produto Merge(Produto produto); + + Produto SaveOrUpdate(Produto produto); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IProfissaoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IProfissaoRepository.cs new file mode 100644 index 0000000..6f32852 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IProfissaoRepository.cs @@ -0,0 +1,19 @@ +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Common; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IProfissaoRepository : IGenericRepository + { + List Find(string filter); + + long FindLastId(); + + Profissao Merge(Profissao profissao); + + Profissao SaveOrUpdate(Profissao profissao); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IProspectRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IProspectRepository.cs new file mode 100644 index 0000000..b15a4ba --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IProspectRepository.cs @@ -0,0 +1,35 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IProspectRepository : IGenericRepository + { + void Delete(long id); + + List Find(long idEmpresa, long id, DateTime inicio, DateTime fim, StatusProspeccao? status); + + List Find(Filtros filtro); + + List FindByData(DateTime inicio, DateTime fim); + + Prospeccao FindById(long id); + + List FindByStatus(StatusProspeccao status); + + List FindByStatusPersonalizado(long statusId); + + Prospeccao FindByTarefa(long id); + + List FindByVendedor(long id); + + Prospeccao Merge(Prospeccao prospeccao); + + Prospeccao SaveOrUpdate(Prospeccao prospeccao); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IQualificacaoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IQualificacaoRepository.cs new file mode 100644 index 0000000..d2d8b2f --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IQualificacaoRepository.cs @@ -0,0 +1,16 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IQualificacaoRepository : IGenericRepository + { + Qualificacao FindById(long id); + + Qualificacao Merge(Qualificacao qualificacao); + + Qualificacao SaveOrUpdate(Qualificacao qualificacao); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IRamoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IRamoRepository.cs new file mode 100644 index 0000000..e0aa433 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IRamoRepository.cs @@ -0,0 +1,25 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IRamoRepository : IGenericRepository + { + void Delete(long id); + + List Find(bool ativo); + + List Find(); + + Ramo FindById(long id); + + Ramo Merge(Ramo ramo); + + List MergeRange(List ramos); + + Ramo SaveOrUpdate(Ramo ramo); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IReciboRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IReciboRepository.cs new file mode 100644 index 0000000..c8abc0a --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IReciboRepository.cs @@ -0,0 +1,23 @@ +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Ferramentas; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IReciboRepository : IGenericRepository + { + List BuscarRecibos(); + + void Delete(long id); + + void DeleteRange(List ids); + + Recibo FindById(long id); + + Recibo Merge(Recibo recibo); + + Recibo SaveOrUpdate(Recibo recibo); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IRegistroAcaoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IRegistroAcaoRepository.cs new file mode 100644 index 0000000..8857ec3 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IRegistroAcaoRepository.cs @@ -0,0 +1,25 @@ +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Relatorios; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IRegistroAcaoRepository : IGenericRepository + { + void Delete(long id); + + List Find(Filtros filtros); + + List FindByEntityId(long id, TipoTela tela); + + RegistroAcao FindById(long id); + + List FindOld(Filtros filtros, string connection); + + RegistroAcao SaveOrUpdate(RegistroAcao log); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IRegistroLogRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IRegistroLogRepository.cs new file mode 100644 index 0000000..6dd9344 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IRegistroLogRepository.cs @@ -0,0 +1,41 @@ +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Relatorios.LogsEnvio; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IRegistroLogRepository : IGenericRepository + { + void AddRange(List registrosLog); + + List BuscaLogParcelas(List EntidadeId); + + void Delete(long id); + + List FindByCredential(long id); + + List FindByEntity(TipoTela tela, long id); + + List FindByEntityId(TipoTela tela, long EntidadeId); + + RegistroLog FindById(long id); + + List FindByIdSingle(long id); + + List FindByUser(TipoTela tela, long IdUsuario); + + List FindByUsuario(long id); + + List LogsEnvio(Filtros filtro); + + RegistroLog SaveOrUpdate(RegistroLog registroLog); + + LogEmail SaveOrUpdate(LogEmail log); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IRepasseRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IRepasseRepository.cs new file mode 100644 index 0000000..24448c8 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IRepasseRepository.cs @@ -0,0 +1,33 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IRepasseRepository : IGenericRepository + { + List DefaultSelect(long idempresa = 0L); + + void Delete(long id); + + void DeleteVinculo(long id); + + Repasse FindById(long id); + + List FindByIdRepasse(long id); + + List FindByIdVendedor(long id); + + List FindByRepasse(long id); + + Repasse Merge(Repasse repasse); + + VinculoRepasse Merge(VinculoRepasse vinculo); + + Repasse SaveOrUpdate(Repasse repasse); + + VinculoRepasse SaveOrUpdate(VinculoRepasse vinculo); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IReportRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IReportRepository.cs new file mode 100644 index 0000000..72d0c90 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IReportRepository.cs @@ -0,0 +1,16 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Relatorios; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IReportRepository : IGenericRepository + { + List PlanilhaCompleta(List ids, bool configFranquia, bool configSomaPremio); + + List PlanilhaCompletaFatura(List ids, Relatorio relatorio, DateTime inicio, DateTime fim, bool configFranquia, bool configSomaPremio); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IRestricaoUsuarioCamposRelatoriosRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IRestricaoUsuarioCamposRelatoriosRepository.cs new file mode 100644 index 0000000..67855b8 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IRestricaoUsuarioCamposRelatoriosRepository.cs @@ -0,0 +1,15 @@ +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IRestricaoUsuarioCamposRelatoriosRepository + { + List FindByUsuario(long id); + + RestricaoUsuarioCamposRelatorios Merge(RestricaoUsuarioCamposRelatorios restricao); + + RestricaoUsuarioCamposRelatorios SaveOrUpdate(RestricaoUsuarioCamposRelatorios restricao); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IRestricaoUsuarioRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IRestricaoUsuarioRepository.cs new file mode 100644 index 0000000..aeb731b --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IRestricaoUsuarioRepository.cs @@ -0,0 +1,18 @@ +using Gestor.Model.Common; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IRestricaoUsuarioRepository + { + List FindByUsuario(long id); + + RestricaoUsuario FindRestricao(long id, TipoRestricao restricao); + + RestricaoUsuario Merge(RestricaoUsuario restricao); + + RestricaoUsuario SaveOrUpdate(RestricaoUsuario restricao); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IRiscosDiversosRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IRiscosDiversosRepository.cs new file mode 100644 index 0000000..5516f1e --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IRiscosDiversosRepository.cs @@ -0,0 +1,23 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IRiscosDiversosRepository : IGenericRepository + { + void Delete(long id); + + void DeleteRange(List ids); + + RiscosDiversos Find(long id); + + RiscosDiversos FindById(long id); + + RiscosDiversos Merge(RiscosDiversos risco); + + RiscosDiversos SaveOrUpdate(RiscosDiversos risco); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ISaldoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ISaldoRepository.cs new file mode 100644 index 0000000..d8b9200 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ISaldoRepository.cs @@ -0,0 +1,27 @@ +using Gestor.Infrastructure.Entities.Financeiro; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Financeiro; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface ISaldoRepository : IGenericRepository + { + Saldo BuscarAberto(long id); + + List BuscarPorConta(long id); + + Saldo BuscarPorData(DateTime inicio, long id); + + Saldo BuscarPorMenorData(long id); + + void Delete(long id); + + Saldo FindById(long id); + + Saldo Merge(Saldo saldo); + + Saldo SaveOrUpdate(Saldo saldo); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ISeguradoraContatoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ISeguradoraContatoRepository.cs new file mode 100644 index 0000000..57425d5 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ISeguradoraContatoRepository.cs @@ -0,0 +1,25 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface ISeguradoraContatoRepository : IGenericRepository + { + void Delete(long id); + + List FindAssistencia(long empresa, long id); + + SeguradoraContato FindById(long id); + + List FindBySeguradora(long empresa, long id); + + SeguradoraContato Merge(SeguradoraContato contato); + + List Merge(List contatos, Seguradora seguradora, long empresa); + + SeguradoraContato SaveOrUpdate(SeguradoraContato contato); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ISeguradoraEnderecoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ISeguradoraEnderecoRepository.cs new file mode 100644 index 0000000..24f2709 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ISeguradoraEnderecoRepository.cs @@ -0,0 +1,23 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface ISeguradoraEnderecoRepository : IGenericRepository + { + void Delete(long id); + + SeguradoraEndereco FindById(long id); + + List FindBySeguradora(long empresa, long id); + + SeguradoraEndereco Merge(SeguradoraEndereco endereco); + + List Merge(List enderecos, Seguradora seguradora, long empresa); + + SeguradoraEndereco SaveOrUpdate(SeguradoraEndereco endereco); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ISeguradoraRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ISeguradoraRepository.cs new file mode 100644 index 0000000..d297481 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ISeguradoraRepository.cs @@ -0,0 +1,25 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface ISeguradoraRepository : IGenericRepository + { + void Delete(long id); + + List Find(string filter); + + List Find(bool ativo); + + List Find(); + + Seguradora FindById(long id); + + Seguradora Merge(Seguradora seguradora); + + Seguradora SaveOrUpdate(Seguradora seguradora); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ISinistroAutoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ISinistroAutoRepository.cs new file mode 100644 index 0000000..0536662 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ISinistroAutoRepository.cs @@ -0,0 +1,22 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface ISinistroAutoRepository : IGenericRepository + { + void Delete(long id); + + SinistroAuto FindById(long id); + + SinistroAuto FindBySinistroId(long id); + + SinistroAuto Merge(SinistroAuto sinistroAuto); + + bool ParceiroUtilizado(long id); + + SinistroAuto SaveOrUpdate(SinistroAuto sinistroAuto); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ISinistroRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ISinistroRepository.cs new file mode 100644 index 0000000..763b7bd --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ISinistroRepository.cs @@ -0,0 +1,30 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface ISinistroRepository : IGenericRepository + { + void Delete(long id); + + List Find(string numero); + + List FindByControleId(long id); + + List FindByData(Filtros filtro, bool pendentes = false); + + Sinistro FindById(long id); + + List FindByItemId(long id); + + List FindNumeroSinistro(string numero); + + Sinistro Merge(Sinistro sinistro); + + Sinistro SaveOrUpdate(Sinistro sinistro); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ISinistroVidaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ISinistroVidaRepository.cs new file mode 100644 index 0000000..322e62e --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ISinistroVidaRepository.cs @@ -0,0 +1,20 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface ISinistroVidaRepository : IGenericRepository + { + void Delete(long id); + + SinistroVida FindById(long id); + + SinistroVida FindBySinistroId(long id); + + SinistroVida Merge(SinistroVida sinistroVida); + + SinistroVida SaveOrUpdate(SinistroVida sinistroVida); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ISocioRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ISocioRepository.cs new file mode 100644 index 0000000..d5c7eda --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ISocioRepository.cs @@ -0,0 +1,23 @@ +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Common; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface ISocioRepository : IGenericRepository + { + void Delete(long id); + + List Find(); + + List FindByEmpresa(long id); + + Socio FindById(long id); + + Socio Merge(Socio socio); + + Socio SaveOrUpdate(Socio socio); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IStatusProspeccaoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IStatusProspeccaoRepository.cs new file mode 100644 index 0000000..f1319dd --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IStatusProspeccaoRepository.cs @@ -0,0 +1,16 @@ +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Ferramentas; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IStatusProspeccaoRepository : IGenericRepository + { + List FindAll(); + + StatusDeProspeccao Merge(StatusDeProspeccao statusProspeccao); + + StatusDeProspeccao SaveOrUpdate(StatusDeProspeccao statusProspeccao); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IStatusRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IStatusRepository.cs new file mode 100644 index 0000000..5899603 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IStatusRepository.cs @@ -0,0 +1,23 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IStatusRepository : IGenericRepository + { + void Delete(long id); + + List Find(string value); + + List Find(); + + Status FindById(long id); + + Status Merge(Status status); + + Status SaveOrUpdate(Status status); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ITarefaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ITarefaRepository.cs new file mode 100644 index 0000000..3d4b0f5 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ITarefaRepository.cs @@ -0,0 +1,69 @@ +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Relatorios.Tarefa; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface ITarefaRepository : IGenericRepository + { + Gestor.Model.Domain.Ferramentas.Tarefa Atualizar(Gestor.Model.Domain.Ferramentas.Tarefa tarefa); + + Trilha Atualizar(Trilha trilha); + + Fase Atualizar(Fase fase); + + List BuscarFases(long id); + + Gestor.Model.Domain.Ferramentas.Tarefa BuscarTarefa(long id); + + List BuscarTarefa(TipoTarefa entidade, long id, bool? concluido = false); + + List BuscarTarefaConcluidaPorUsuario(long id, TipoTarefa tipo); + + List BuscarTarefaPorCliente(long id); + + List BuscarTarefaPorData(DateTime data, long idUsuario, bool? concluido = false); + + List BuscarTarefaPorFiltro(DateTime inicio, DateTime fim); + + List BuscarTarefaPorTrilha(long id); + + List BuscarTarefaPorUsuario(long id, bool? concluido = false); + + List BuscarTarefaPorUsuario(long id, DateTime inicio, DateTime fim, bool? concluido); + + List BuscarTarefaPorUsuario(long id, TipoTarefa tipo); + + List BuscarTarefasPorTipo(long id); + + Trilha BuscarTrilha(long id); + + List BuscarTrilhas(bool ativo = true); + + List BuscarTrilhas(string titulo, bool ativo = true); + + int[] ContarTarefas(long id); + + void Excluir(long id); + + void ExcluirFase(long id); + + void ExcluirTrilha(long id); + + Gestor.Model.Domain.Ferramentas.Tarefa Salvar(Gestor.Model.Domain.Ferramentas.Tarefa tarefa); + + List Salvar(List tarefas); + + Trilha Salvar(Trilha trilha); + + Fase Salvar(Fase fase); + + List Salvar(List fases); + + List Validar(List ids, long trilha); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ITipoContaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ITipoContaRepository.cs new file mode 100644 index 0000000..53b32b7 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ITipoContaRepository.cs @@ -0,0 +1,16 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Financeiro; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface ITipoContaRepository : IGenericRepository + { + List Find(); + + TipoConta Merge(TipoConta planos); + + TipoConta SaveOrUpdate(TipoConta planos); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ITipoTarefaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ITipoTarefaRepository.cs new file mode 100644 index 0000000..fead2c4 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ITipoTarefaRepository.cs @@ -0,0 +1,16 @@ +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Ferramentas; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface ITipoTarefaRepository : IGenericRepository + { + List FindAll(); + + TipoDeTarefa Merge(TipoDeTarefa tipoTarefa); + + TipoDeTarefa SaveOrUpdate(TipoDeTarefa tipoTarefa); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ITipoVendedorRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ITipoVendedorRepository.cs new file mode 100644 index 0000000..767d60a --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ITipoVendedorRepository.cs @@ -0,0 +1,29 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface ITipoVendedorRepository : IGenericRepository + { + List DefaultSelect(); + + void Delete(long id); + + List Find(bool ativo); + + List Find(); + + TipoVendedor FindById(long id); + + long FindLastId(); + + TipoVendedor Merge(TipoVendedor tipoVendedor); + + List MergeRange(List tiposVendedor); + + TipoVendedor SaveOrUpdate(TipoVendedor tipoVendedor); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ITitularesVidaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ITitularesVidaRepository.cs new file mode 100644 index 0000000..504ed2f --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/ITitularesVidaRepository.cs @@ -0,0 +1,23 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface ITitularesVidaRepository : IGenericRepository + { + void Delete(long id); + + void DeleteRange(List ids); + + List Find(long id); + + TitularesVida FindById(long id); + + TitularesVida Merge(TitularesVida vida); + + TitularesVida SaveOrUpdate(TitularesVida vida); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IUsuarioRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IUsuarioRepository.cs new file mode 100644 index 0000000..848c459 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IUsuarioRepository.cs @@ -0,0 +1,41 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.API; +using Gestor.Model.Common; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IUsuarioRepository : IGenericRepository + { + Usuario AddUsuarioFromSso(UserSso userSso); + + void Delete(long id); + + List Find(string filter, long idempresa = 0L); + + List Find(long idempresa = 0L); + + Usuario FindById(long id); + + List FindByLoginInteiro(string filter); + + bool FindDocUsedByDocumento(string filter, long id, long idempresa); + + Usuario FindFromSso(UserSso userSso); + + Usuario FindUsuario(string login); + + Usuario Merge(Usuario usuario); + + List PermissaoAggilizador(); + + Usuario SaveOrUpdate(Usuario usuario); + + Usuario SsoId(AuthSso sso); + + Usuario ValidateLogin(string login, string password); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IVendedorParcelaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IVendedorParcelaRepository.cs new file mode 100644 index 0000000..7b56a7b --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IVendedorParcelaRepository.cs @@ -0,0 +1,45 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IVendedorParcelaRepository : IGenericRepository + { + List AddRange(List repasses); + + Vendedor BuscarVendedorPorControle(long id); + + bool Delete(long id); + + void DeleteRange(long id); + + void DeleteRange(List repasses); + + List FindByDate(Filtros filtro); + + List FindByDocumentId(long documentId); + + VendedorParcela FindById(long id); + + Vendedor FindByMainDocumentId(long documentId); + + List FindByParcela(long id); + + List FindVinculoByIdCliente(long idCliente); + + bool GerarPagamento(List ids, DateTime data); + + VendedorParcela Merge(VendedorParcela vendedorParcela); + + VendedorParcela SaveOrUpdate(VendedorParcela vendedorParcela); + + bool TemPagamentoParcela(long id); + + bool TipoVendedorUtilizado(long id); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IVendedorRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IVendedorRepository.cs new file mode 100644 index 0000000..6adadaf --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IVendedorRepository.cs @@ -0,0 +1,27 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IVendedorRepository : IGenericRepository + { + void Delete(long id); + + List Find(bool ativo, long idempresa = 0L); + + List Find(long idempresa = 0L); + + List Find(string nome, long idempresa = 0L); + + Vendedor FindById(long id); + + Vendedor FindCorretora(); + + Vendedor Merge(Vendedor vendedor); + + Vendedor SaveOrUpdate(Vendedor vendedor); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IVendedorTelefoneRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IVendedorTelefoneRepository.cs new file mode 100644 index 0000000..49e775b --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IVendedorTelefoneRepository.cs @@ -0,0 +1,27 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IVendedorTelefoneRepository : IGenericRepository + { + void Delete(long id); + + VendedorTelefone FindById(long id); + + List FindByVendedorId(long id); + + List Inserir(List telefones); + + List Inserir(List telefones, Vendedor vendedor); + + VendedorTelefone Merge(VendedorTelefone telefone); + + List Merge(List telefones, Vendedor vendedor); + + VendedorTelefone SaveOrUpdate(VendedorTelefone telefone); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IVendedorUsuarioRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IVendedorUsuarioRepository.cs new file mode 100644 index 0000000..350e705 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IVendedorUsuarioRepository.cs @@ -0,0 +1,27 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IVendedorUsuarioRepository : IGenericRepository + { + void Delete(long id); + + bool Exist(long id); + + bool ExistVinculoUsuario(long idUsuario); + + VendedorUsuario FindById(long id); + + IList FindByUsuario(long idUsuario); + + List FindByVinculo(long idUsuario); + + VendedorUsuario Merge(VendedorUsuario vendedorUsuario); + + VendedorUsuario SaveOrUpdate(VendedorUsuario vendedorUsuario); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IVidaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IVidaRepository.cs new file mode 100644 index 0000000..c213cd7 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IVidaRepository.cs @@ -0,0 +1,23 @@ +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IVidaRepository : IGenericRepository + { + void Delete(long id); + + void DeleteRange(List ids); + + Vida Find(long id); + + Vida FindById(long id); + + Vida Merge(Vida vida); + + Vida SaveOrUpdate(Vida vida); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IVinculoDocumentoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IVinculoDocumentoRepository.cs new file mode 100644 index 0000000..e95c0ca --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Interface/IVinculoDocumentoRepository.cs @@ -0,0 +1,25 @@ +using Gestor.Infrastructure.Entities.Aggilizador; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Aggilizador; +using Gestor.Model.Domain.Relatorios; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Interface +{ + public interface IVinculoDocumentoRepository : IGenericRepository + { + List BuscarArquivos(List ids, TipoArquivoVinculo type); + + void Delete(long id); + + VinculoDocumento FindById(long id); + + VinculoDocumento Merge(VinculoDocumento vinculo); + + VinculoDocumento SaveOrUpdate(VinculoDocumento vinculo); + + int Sincronize(DateTime inicio, List dados); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AdiantamentoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AdiantamentoRepository.cs new file mode 100644 index 0000000..aff2bf7 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AdiantamentoRepository.cs @@ -0,0 +1,168 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Helpers; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class AdiantamentoRepository : GenericRepository, IAdiantamentoRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public AdiantamentoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public List AddRange(List adiantamentos) + { + List adiantamentoDbs = ApplicationMapper.Mapper.Map, List>(adiantamentos); + base.AddRange(adiantamentoDbs); + return ApplicationMapper.Mapper.Map, List>(adiantamentoDbs); + } + + public List BuscarAdiantamentos(long id, bool concluido = false) + { + List list = ( + from x in base.All() + where x.Vendedor.Id == id && x.Pago == concluido + select x).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public List Find(bool ativo) + { + return this.Select((new List() + { + new Condicao() + { + Campo = "ativo", + Valores = null + }, + new Condicao() + { + Campo = "pago", + Valores = "1".CriarValor() + } + }).CreateParameters(0)); + } + + public List Find(long id) + { + return this.Select((new List() + { + new Condicao() + { + Campo = "idvendedor", + Valores = id.CriarValor() + } + }).CreateParameters(0)); + } + + public List Find(string nome) + { + return this.Select((new List() + { + new Condicao() + { + Campo = "historico", + Valores = nome.CriarValor() + } + }).CreateParameters(0)); + } + + public List FindByDate(DateTime inicio, DateTime fim, List vendedores = null, bool segundavia = false) + { + List condicaos = new List() + { + new Condicao() + { + Campo = (segundavia ? "CAST(Pagamento AS DATE)" : "CAST(data AS DATE)"), + Valores = inicio.CriarValor(), + Operador = Operador.MaiorEIgual + }, + new Condicao() + { + Campo = (segundavia ? "CAST(Pagamento AS DATE)" : "CAST(data AS DATE)"), + Valores = fim.CriarValor(), + Operador = Operador.MenorEIgual + } + }; + condicaos.AddRange((!segundavia ? new List() + { + new Condicao() + { + Campo = "pago", + Valores = null, + Operacao = Operacao.Or, + Grupo = 1 + }, + new Condicao() + { + Campo = "pago", + Valores = "1".CriarValor(), + Operacao = Operacao.Or, + Grupo = 1, + Operador = Operador.Diferente + } + } : new List() + { + new Condicao() + { + Campo = "pago", + Valores = "1".CriarValor() + } + })); + if (vendedores != null && vendedores.Count > 0) + { + condicaos.Add(new Condicao() + { + Campo = "idvendedor", + Valores = vendedores.CriarValor() + }); + } + return this.Select(condicaos.CreateParameters(0)); + } + + public Adiantamento FindById(long id) + { + AdiantamentoDb adiantamentoDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(adiantamentoDb); + } + + public Adiantamento Merge(Adiantamento adiantamento) + { + AdiantamentoDb adiantamentoDb = ApplicationMapper.Mapper.Map(adiantamento); + base.Merge(adiantamentoDb); + return ApplicationMapper.Mapper.Map(adiantamentoDb); + } + + public Adiantamento SaveOrUpdate(Adiantamento adiantamento) + { + AdiantamentoDb adiantamentoDb = ApplicationMapper.Mapper.Map(adiantamento); + this.SaveOrUpdate(adiantamentoDb); + return ApplicationMapper.Mapper.Map(adiantamentoDb); + } + + private List Select(SqlQueryCondition sqlCondition) + { + return this._unitOfWork.Select(sqlCondition, "SELECT DISTINCT * FROM adiantamento WHERE", "").MapAdiantamento(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AeronauticoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AeronauticoRepository.cs new file mode 100644 index 0000000..b5b4d57 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AeronauticoRepository.cs @@ -0,0 +1,71 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class AeronauticoRepository : GenericRepository, IAeronauticoRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public AeronauticoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + AeronauticoDb aeronauticoDb = base.FindEntityById(id); + if (aeronauticoDb == null) + { + return; + } + base.Delete(aeronauticoDb); + } + + public void DeleteRange(List ids) + { + List list = ( + from x in base.All() + where ids.Contains(x.Item.Id) + select x).ToList(); + base.DeleteRange(list); + } + + public Aeronautico Find(long id) + { + AeronauticoDb aeronauticoDb = base.All().FirstOrDefault((AeronauticoDb x) => x.Item.Id == id) ?? new AeronauticoDb(); + return ApplicationMapper.Mapper.Map(aeronauticoDb); + } + + public Aeronautico FindById(long id) + { + AeronauticoDb aeronauticoDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(aeronauticoDb); + } + + public Aeronautico Merge(Aeronautico aeronautico) + { + AeronauticoDb aeronauticoDb = ApplicationMapper.Mapper.Map(aeronautico); + base.Merge(aeronauticoDb); + return ApplicationMapper.Mapper.Map(aeronauticoDb); + } + + public Aeronautico SaveOrUpdate(Aeronautico aeronautico) + { + AeronauticoDb aeronauticoDb = ApplicationMapper.Mapper.Map(aeronautico); + this.SaveOrUpdate(aeronauticoDb); + return ApplicationMapper.Mapper.Map(aeronauticoDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaEmailRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaEmailRepository.cs new file mode 100644 index 0000000..9131660 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaEmailRepository.cs @@ -0,0 +1,151 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class AgendaEmailRepository : GenericRepository, IAgendaEmailRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public AgendaEmailRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public void DeleteRange(long id) + { + IQueryable agendaEmailDbs = + from x in base.All() + where x.Agenda.Id == id + select x; + if (!agendaEmailDbs.Any()) + { + return; + } + base.DeleteRange(agendaEmailDbs); + } + + private List FindByAgenda(long id) + { + List list = ( + from x in base.All() + where x.Agenda.Id == id + select x).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public List FindByAgenda(List ids) + { + List list = ( + from x in base.All() + where ids.Contains(x.Agenda.Id) + select x).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public List FindByAgendaId(long id) + { + return this.FindByAgenda(id); + } + + public AgendaEmail FindById(long id) + { + AgendaEmailDb agendaEmailDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(agendaEmailDb); + } + + public List FindEmailAgenda(string email) + { + List list = ( + from x in base.All() + where x.Email.Contains(email) + select x).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public List Inserir(List emails, Agenda agenda) + { + emails.ForEach((AgendaEmail x) => x.Agenda = agenda); + List agendaEmailDbs = ApplicationMapper.Mapper.Map, List>(emails); + base.AddRange(agendaEmailDbs); + return ApplicationMapper.Mapper.Map, List>(agendaEmailDbs); + } + + public List Inserir(List emails) + { + List agendaEmailDbs = ApplicationMapper.Mapper.Map, List>(emails); + agendaEmailDbs.ForEach((AgendaEmailDb x) => { + if (x.Id == 0) + { + this.SaveOrUpdate(x); + return; + } + base.Merge(x); + }); + return ApplicationMapper.Mapper.Map, List>(agendaEmailDbs); + } + + public AgendaEmail Merge(AgendaEmail agendaEmail) + { + AgendaEmailDb agendaEmailDb = ApplicationMapper.Mapper.Map(agendaEmail); + base.Merge(agendaEmailDb); + return ApplicationMapper.Mapper.Map(agendaEmailDb); + } + + public List Merge(List emails, Agenda agenda) + { + IQueryable agendaEmailDbs = + from x in base.All() + where x.Agenda.Id == agenda.Id + select x; + AgendaEmailRepository agendaEmailRepository = this; + ( + from x in agendaEmailDbs + select x.Id).ToList().Where((long x) => { + List agendaEmails = emails; + Func u003cu003e9_114 = AgendaEmailRepository.u003cu003ec.u003cu003e9__11_4; + if (u003cu003e9_114 == null) + { + u003cu003e9_114 = (AgendaEmail t) => t.Id; + AgendaEmailRepository.u003cu003ec.u003cu003e9__11_4 = u003cu003e9_114; + } + return !agendaEmails.Select(u003cu003e9_114).Contains(x); + }).ToList().ForEach(new Action(agendaEmailRepository.Delete)); + List agendaEmailDbs1 = ApplicationMapper.Mapper.Map, List>(emails); + agendaEmailDbs1.ForEach((AgendaEmailDb x) => { + if (x.Id != 0) + { + base.Merge(x); + return; + } + x.Agenda = ApplicationMapper.Mapper.Map(agenda); + this.SaveOrUpdate(x); + }); + return ApplicationMapper.Mapper.Map, List>(agendaEmailDbs1); + } + + public AgendaEmail SaveOrUpdate(AgendaEmail agendaEmail) + { + AgendaEmailDb agendaEmailDb = ApplicationMapper.Mapper.Map(agendaEmail); + this.SaveOrUpdate(agendaEmailDb); + return ApplicationMapper.Mapper.Map(agendaEmailDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaRepository.cs new file mode 100644 index 0000000..1ab42b8 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaRepository.cs @@ -0,0 +1,86 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class AgendaRepository : GenericRepository, IAgendaRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public AgendaRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + AgendaDb agendaDb = base.FindEntityById(id); + if (agendaDb == null) + { + return; + } + (new AgendaEmailRepository(this._unitOfWork)).DeleteRange(id); + (new AgendaTelefoneRepository(this._unitOfWork)).DeleteRange(id); + base.Delete(agendaDb); + } + + public List Find(string filter) + { + AgendaRepository.u003cu003ec__DisplayClass3_0 variable = null; + IQueryable agendaDbs = base.All(); + ParameterExpression parameterExpression = Expression.Parameter(typeof(AgendaDb), "x"); + IQueryable agendaDbs1 = agendaDbs.Where(Expression.Lambda>(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(AgendaDb).GetMethod("get_Nome").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(AgendaRepository.u003cu003ec__DisplayClass3_0)), FieldInfo.GetFieldFromHandle(typeof(AgendaRepository.u003cu003ec__DisplayClass3_0).GetField("filter").FieldHandle)) }), new ParameterExpression[] { parameterExpression })); + parameterExpression = Expression.Parameter(typeof(AgendaDb), "x"); + return agendaDbs1.Select(Expression.Lambda>(Expression.MemberInit(Expression.New(typeof(Agenda)), new MemberBinding[] { Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(DomainBase).GetMethod("set_Id", new Type[] { typeof(long) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(EntityBase).GetMethod("get_Id").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Agenda).GetMethod("set_Nome", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(AgendaDb).GetMethod("get_Nome").MethodHandle))) }), new ParameterExpression[] { parameterExpression })).ToList(); + } + + public List Find() + { + List list = base.All().ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public Agenda FindById(long id) + { + AgendaDb agendaDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(agendaDb); + } + + public List FindByName(string name) + { + AgendaRepository.u003cu003ec__DisplayClass4_0 variable = null; + IQueryable agendaDbs = base.All(); + ParameterExpression parameterExpression = Expression.Parameter(typeof(AgendaDb), "x"); + IQueryable agendaDbs1 = agendaDbs.Where(Expression.Lambda>(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(AgendaDb).GetMethod("get_Nome").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(AgendaRepository.u003cu003ec__DisplayClass4_0)), FieldInfo.GetFieldFromHandle(typeof(AgendaRepository.u003cu003ec__DisplayClass4_0).GetField("name").FieldHandle)) }), new ParameterExpression[] { parameterExpression })).Take(150); + parameterExpression = Expression.Parameter(typeof(AgendaDb), "x"); + return agendaDbs1.Select(Expression.Lambda>(Expression.MemberInit(Expression.New(typeof(Agenda)), new MemberBinding[] { Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(DomainBase).GetMethod("set_Id", new Type[] { typeof(long) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(EntityBase).GetMethod("get_Id").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Agenda).GetMethod("set_Nome", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(AgendaDb).GetMethod("get_Nome").MethodHandle))) }), new ParameterExpression[] { parameterExpression })).ToList(); + } + + public Agenda Merge(Agenda agenda) + { + AgendaDb agendaDb = ApplicationMapper.Mapper.Map(agenda); + base.Merge(agendaDb); + return ApplicationMapper.Mapper.Map(agendaDb); + } + + public Agenda SaveOrUpdate(Agenda agenda) + { + AgendaDb agendaDb = ApplicationMapper.Mapper.Map(agenda); + this.SaveOrUpdate(agendaDb); + return ApplicationMapper.Mapper.Map(agendaDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaTelefoneRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaTelefoneRepository.cs new file mode 100644 index 0000000..9c1b0d6 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaTelefoneRepository.cs @@ -0,0 +1,149 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class AgendaTelefoneRepository : GenericRepository, IAgendaTelefoneRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public AgendaTelefoneRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public void DeleteRange(long id) + { + IQueryable agendaTelefoneDbs = + from x in base.All() + where x.Agenda.Id == id + select x; + if (!agendaTelefoneDbs.Any()) + { + return; + } + base.DeleteRange(agendaTelefoneDbs); + } + + public List Find(string telefone) + { + List list = ( + from x in base.All() + where x.Numero.Contains(telefone) + select x).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + private List FindByAgenda(long id) + { + return ( + from x in base.All() + where x.Agenda.Id == id + select new AgendaTelefone() + { + Id = x.Id, + Agenda = ApplicationMapper.Mapper.Map(x.Agenda), + Prefixo = x.Prefixo, + Numero = x.Numero, + Tipo = x.Tipo, + Observacao = x.Observacao + }).ToList(); + } + + public List FindByAgendaId(long id) + { + return this.FindByAgenda(id); + } + + public AgendaTelefone FindById(long id) + { + AgendaTelefoneDb agendaTelefoneDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(agendaTelefoneDb); + } + + public List Inserir(List telefones) + { + List agendaTelefoneDbs = ApplicationMapper.Mapper.Map, List>(telefones); + agendaTelefoneDbs.ForEach((AgendaTelefoneDb x) => { + if (x.Id == 0) + { + this.SaveOrUpdate(x); + return; + } + base.Merge(x); + }); + return ApplicationMapper.Mapper.Map, List>(agendaTelefoneDbs); + } + + public List Inserir(List telefones, Agenda agenda) + { + telefones.ForEach((AgendaTelefone x) => x.Agenda = agenda); + List agendaTelefoneDbs = ApplicationMapper.Mapper.Map, List>(telefones); + base.AddRange(agendaTelefoneDbs); + return ApplicationMapper.Mapper.Map, List>(agendaTelefoneDbs); + } + + public AgendaTelefone Merge(AgendaTelefone telefone) + { + AgendaTelefoneDb agendaTelefoneDb = ApplicationMapper.Mapper.Map(telefone); + base.Merge(agendaTelefoneDb); + return ApplicationMapper.Mapper.Map(agendaTelefoneDb); + } + + public List Merge(List telefones, Agenda agenda) + { + IQueryable agendaTelefoneDbs = + from x in base.All() + where x.Agenda.Id == agenda.Id + select x; + AgendaTelefoneRepository agendaTelefoneRepository = this; + ( + from x in agendaTelefoneDbs + select x.Id).ToList().Where((long x) => { + List agendaTelefones = telefones; + Func u003cu003e9_114 = AgendaTelefoneRepository.u003cu003ec.u003cu003e9__11_4; + if (u003cu003e9_114 == null) + { + u003cu003e9_114 = (AgendaTelefone t) => t.Id; + AgendaTelefoneRepository.u003cu003ec.u003cu003e9__11_4 = u003cu003e9_114; + } + return !agendaTelefones.Select(u003cu003e9_114).Contains(x); + }).ToList().ForEach(new Action(agendaTelefoneRepository.Delete)); + List agendaTelefoneDbs1 = ApplicationMapper.Mapper.Map, List>(telefones); + agendaTelefoneDbs1.ForEach((AgendaTelefoneDb x) => { + if (x.Id != 0) + { + base.Merge(x); + return; + } + x.Agenda = ApplicationMapper.Mapper.Map(agenda); + this.SaveOrUpdate(x); + }); + return ApplicationMapper.Mapper.Map, List>(agendaTelefoneDbs1); + } + + public AgendaTelefone SaveOrUpdate(AgendaTelefone telefone) + { + AgendaTelefoneDb agendaTelefoneDb = ApplicationMapper.Mapper.Map(telefone); + this.SaveOrUpdate(agendaTelefoneDb); + return ApplicationMapper.Mapper.Map(agendaTelefoneDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AtividadeRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AtividadeRepository.cs new file mode 100644 index 0000000..d3261c6 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AtividadeRepository.cs @@ -0,0 +1,92 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class AtividadeRepository : GenericRepository, IAtividadeRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public AtividadeRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public List Find(string filter) + { + AtividadeRepository.u003cu003ec__DisplayClass5_0 variable = null; + IQueryable atividadeDbs = base.All(); + ParameterExpression parameterExpression = Expression.Parameter(typeof(AtividadeDb), "x"); + IQueryable atividadeDbs1 = atividadeDbs.Where(Expression.Lambda>(Expression.OrElse(Expression.Call(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(AtividadeDb).GetMethod("get_Nome").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Trim").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(AtividadeRepository.u003cu003ec__DisplayClass5_0)), FieldInfo.GetFieldFromHandle(typeof(AtividadeRepository.u003cu003ec__DisplayClass5_0).GetField("filter").FieldHandle)) }), Expression.Call(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(AtividadeDb).GetMethod("get_Cnac").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Trim").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(AtividadeRepository.u003cu003ec__DisplayClass5_0)), FieldInfo.GetFieldFromHandle(typeof(AtividadeRepository.u003cu003ec__DisplayClass5_0).GetField("filter").FieldHandle)) })), new ParameterExpression[] { parameterExpression })); + parameterExpression = Expression.Parameter(typeof(AtividadeDb), "x"); + return atividadeDbs1.Select(Expression.Lambda>(Expression.MemberInit(Expression.New(typeof(Atividade)), new MemberBinding[] { Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(DomainBase).GetMethod("set_Id", new Type[] { typeof(long) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(EntityBase).GetMethod("get_Id").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Atividade).GetMethod("set_Nome", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(AtividadeDb).GetMethod("get_Nome").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Atividade).GetMethod("set_Cnac", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(AtividadeDb).GetMethod("get_Cnac").MethodHandle))) }), new ParameterExpression[] { parameterExpression })).ToList(); + } + + public long FindLastId() + { + long num; + object connection; + SqlCommand sqlCommand; + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + if (sqlConnection != null) + { + sqlCommand = sqlConnection.CreateCommand(); + } + else + { + sqlCommand = null; + } + using (SqlCommand sqlCommand1 = sqlCommand) + { + sqlCommand1.CommandText = "SELECT MAX(idatividade) as id FROM atividade"; + SqlDataReader sqlDataReader = sqlCommand1.ExecuteReader(); + sqlDataReader.Read(); + sqlDataReader["id"].ToString(); + num = (sqlDataReader["id"] == null || sqlDataReader["id"].ToString() == "" || sqlDataReader["id"].ToString() == "{}" ? (long)0 : long.Parse(sqlDataReader["id"].ToString())); + } + } + return num; + } + + public Atividade Merge(Atividade atividade) + { + AtividadeDb atividadeDb = ApplicationMapper.Mapper.Map(atividade); + base.Merge(atividadeDb); + return ApplicationMapper.Mapper.Map(atividadeDb); + } + + public Atividade SaveOrUpdate(Atividade atividade) + { + AtividadeDb atividadeDb = ApplicationMapper.Mapper.Map(atividade); + this.SaveOrUpdate(atividadeDb); + return ApplicationMapper.Mapper.Map(atividadeDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AtualizacaoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AtualizacaoRepository.cs new file mode 100644 index 0000000..d4702f8 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AtualizacaoRepository.cs @@ -0,0 +1,44 @@ +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Helpers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using System; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class AtualizacaoRepository : GenericRepository, IAtualizacaoRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public AtualizacaoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public long FindLastUpdate() + { + AtualizacaoDb atualizacaoDb = ( + from x in base.All() + orderby x.IdArquivo descending + select x).FirstOrDefault(); + if (atualizacaoDb != null) + { + return atualizacaoDb.IdArquivo; + } + return (long)0; + } + + public void Save(long fileId) + { + this.Add(new AtualizacaoDb() + { + IdArquivo = fileId, + DataAtualizacao = Funcoes.GetNetworkTime() + }); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AutoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AutoRepository.cs new file mode 100644 index 0000000..7cbb775 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AutoRepository.cs @@ -0,0 +1,607 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Helpers; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class AutoRepository : GenericRepository, IAutoRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public AutoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + AutoDb autoDb = base.FindEntityById(id); + if (autoDb == null) + { + return; + } + base.Delete(autoDb); + } + + public void DeleteRange(List ids) + { + List list = ( + from x in base.All() + where ids.Contains(x.Item.Id) + select x).ToList(); + base.DeleteRange(list); + } + + public Auto Find(long id) + { + AutoDb autoDb = base.All().FirstOrDefault((AutoDb x) => x.Item.Id == id) ?? new AutoDb(); + return ApplicationMapper.Mapper.Map(autoDb); + } + + public List FindAuto(string pesquisa, FiltroStatusDocumento status, List vendedorVinculado, TipoPesquisa tipo, bool tipobusca = false) + { + List pesquisaAvancadas; + object connection; + DataTable dataTable = new DataTable(); + DataTable dataTable1 = new DataTable(); + DataTable dataTable2 = new DataTable(); + DataTable dataTable3 = new DataTable(); + DateTime date = Funcoes.GetNetworkTime().Date; + List condicaos = new List() + { + new Condicao() + { + Campo = "d.excluido", + Valores = null, + Grupo = 1, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "d.excluido", + Valores = "0".CriarValor(), + Grupo = 1, + Operacao = Operacao.Or + } + }; + switch (status) + { + case FiltroStatusDocumento.Vencidos: + { + condicaos.AddRange(new List() + { + new Condicao() + { + Campo = "d.situacao", + Valores = new List() + { + 3, + 7 + }, + Operador = Operador.Diferente + }, + new Condicao() + { + Campo = "d.vigencia2", + Valores = date.AddDays(-5).CriarValor(), + Operador = Operador.Menor + } + }); + goto case FiltroStatusDocumento.Todos; + } + case FiltroStatusDocumento.Cancelados: + { + condicaos.Add(new Condicao() + { + Campo = "d.situacao", + Valores = 3.CriarValor() + }); + goto case FiltroStatusDocumento.Todos; + } + case FiltroStatusDocumento.Recusados: + { + condicaos.Add(new Condicao() + { + Campo = "d.situacao", + Valores = 7.CriarValor() + }); + goto case FiltroStatusDocumento.Todos; + } + case FiltroStatusDocumento.Todos: + { + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + List condicaos1 = new List(); + if (tipo == TipoPesquisa.Chassi) + { + condicaos1.Add(new Condicao() + { + Campo = "a.chassi", + Valores = pesquisa.CriarValor(), + Operador = (tipobusca ? Operador.Igual : Operador.Like) + }); + } + else if (tipo == TipoPesquisa.Item) + { + condicaos1.Add(new Condicao() + { + Campo = "i.descricao", + Valores = pesquisa.CriarValor(), + Operador = (tipobusca ? Operador.Igual : Operador.Like) + }); + } + else if (tipo == TipoPesquisa.Placa) + { + condicaos1.Add(new Condicao() + { + Campo = "REPLACE(a.placa, '-','')", + Valores = pesquisa.Replace("-", "").Replace("?", "%").CriarValor(), + Operador = (tipobusca ? Operador.Igual : Operador.Like) + }); + } + dataTable = sqlCommand.Select(condicaos1.CreateParameters(0), "SELECT TOP 1000 i.iditem as id FROM item i LEFT OUTER JOIN auto a on i.iditem = a.iditem WHERE ", ""); + if (dataTable.Rows.Count != 0) + { + List condicaos2 = new List() + { + new Condicao() + { + Campo = "iditem", + Valores = dataTable.AsEnumerable().Select((DataRow v) => v.Field("id")).ToList().CriarValor() + } + }; + dataTable1 = sqlCommand.Select(condicaos2.CreateParameters(0), "SELECT iddocumento as id, descricao, iditem FROM item WHERE", ""); + condicaos.Add(new Condicao() + { + Campo = "d.iddocumento", + Valores = dataTable1.AsEnumerable().Select((DataRow v) => v.Field("id")).ToList().CriarValor() + }); + dataTable2 = sqlCommand.Select(condicaos.CreateParameters(0), "SELECT DISTINCT cl.nome as cliente, c.idcliente, d.idcontrole, d.iddocumento, situacao, ISNULL(vigencia1, GETDATE()) AS vigencia1, vigencia2, proposta, contrato as apolice, aditamento as endosso, CAST(tipo as INTEGER) as tipo FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE ", ""); + if (dataTable2.Rows.Count != 0) + { + List list = ( + from x in dataTable2.AsEnumerable().ToList() + select x.Field("idcontrole")).ToList(); + List condicaos3 = new List() + { + new Condicao() + { + Campo = "d.idcontrole", + Valores = list.CriarValor() + } + }; + dataTable3 = sqlCommand.Select(condicaos3.CreateParameters(0), "SELECT DISTINCT vp.idvendedor, d.iddocumento, d.idcontrole, vp.idtipovendedor FROM vendedorparcela vp INNER JOIN documento d on d.iddocumento = vp.iddocumento WHERE ", ""); + goto Label1; + } + else + { + pesquisaAvancadas = new List(); + } + } + else + { + pesquisaAvancadas = new List(); + } + } + } + return pesquisaAvancadas; + } + default: + { + condicaos.AddRange(new List() + { + new Condicao() + { + Campo = "d.situacao", + Valores = new List() + { + 1, + 2, + 4 + } + }, + new Condicao() + { + Campo = "d.vigencia2", + Valores = null, + Grupo = 2, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "d.vigencia2", + Valores = date.AddDays(-5).CriarValor(), + Grupo = 2, + Operacao = Operacao.Or, + Operador = Operador.Maior + } + }); + goto case FiltroStatusDocumento.Todos; + } + } + Label1: + List nums = null; + if (vendedorVinculado != null && vendedorVinculado.Count > 0) + { + nums = dataTable3.AsEnumerable().Where((DataRow x) => { + List vendedorUsuarios = vendedorVinculado; + Func u003cu003e9_107 = AutoRepository.u003cu003ec.u003cu003e9__10_7; + if (u003cu003e9_107 == null) + { + u003cu003e9_107 = (VendedorUsuario v) => v.Vendedor.Id; + AutoRepository.u003cu003ec.u003cu003e9__10_7 = u003cu003e9_107; + } + return vendedorUsuarios.Select(u003cu003e9_107).Contains(x.Field("idvendedor")); + }).Select((DataRow x) => x.Field("idcontrole")).ToList(); + } + if (nums != null && nums.Count == 0) + { + return new List(); + } + return dataTable2.AsEnumerable().Where((DataRow x) => { + if (nums == null) + { + return true; + } + return nums.Contains(x.Field("idcontrole")); + }).Select((DataRow x) => new PesquisaAvancada() + { + IdCliente = x.Field("idcliente"), + IdDocumento = x.Field("iddocumento"), + IdItem = dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("iditem"), + Nome = x.Field("cliente"), + Pesquisa = (x.Field("tipo") == 0 ? string.Format("ITEM: {0} - NÚMERO DA APÓLICE: {1} - NÚMERO DA PROPOSTA: {2} - VIGÊNCIA INICIAL: {3:d} ", new object[] { dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("descricao"), x.Field("apolice"), x.Field("proposta"), x.Field("vigencia1") }) : string.Format("ITEM: {0} - NÚMERO DA APÓLICE: {1} - NÚMERO DA PROPOSTA: {2} - NÚMERO DO ENDOSSO: {3} VIGÊNCIA INICIAL: {4:d}", new object[] { dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("descricao"), x.Field("apolice"), x.Field("proposta"), x.Field("endosso"), x.Field("vigencia1") })) + }).ToList(); + } + + public Documento FindByChassi(string chassi, long id, DateTime vigencia1, DateTime? vigencia2, long idSeguradora) + { + DocumentoDb documento; + List tipoSeguros = new List() + { + TipoSeguro.Novo, + TipoSeguro.Renovacao, + TipoSeguro.Reabilitado + }; + DateTime dateTime3 = Convert.ToDateTime(vigencia2); + AutoDb autoDb = ( + from a in base.All() + select new AutoDb() + { + Id = a.Id, + Chassi = a.Chassi, + Item = new ItemDb() + { + Cancelado = a.Item.Cancelado, + Substituido = a.Item.Substituido, + Documento = new DocumentoDb() + { + Vigencia1 = a.Item.Documento.Vigencia1, + Vigencia2 = a.Item.Documento.Vigencia2, + Situacao = a.Item.Documento.Situacao, + Excluido = a.Item.Documento.Excluido, + Controle = new ControleDb() + { + Id = a.Item.Documento.Controle.Id, + Seguradora = new SeguradoraDb() + { + Id = a.Item.Documento.Controle.Seguradora.Id, + Nome = a.Item.Documento.Controle.Seguradora.Nome, + NomeSocial = a.Item.Documento.Controle.Seguradora.NomeSocial + }, + Cliente = new ClienteDb() + { + Id = a.Item.Documento.Controle.Cliente.Id, + Nome = a.Item.Documento.Controle.Cliente.Nome + } + } + } + } + } into x + where x.Id != id && x.Chassi == chassi && tipoSeguros.Contains(x.Item.Documento.Situacao) + select x).ToList().AsEnumerable().ToList().Where((AutoDb x) => { + DateTime dateTime = dateTime3; + DateTime dateTime4 = x.Item.Documento.Vigencia1; + if (dateTime >= dateTime4.AddDays(5)) + { + DateTime dateTime1 = dateTime3; + dateTime4 = Convert.ToDateTime(x.Item.Documento.Vigencia2); + if (dateTime1 <= dateTime4.AddDays(5)) + { + return true; + } + } + DateTime dateTime2 = vigencia1; + dateTime4 = x.Item.Documento.Vigencia1; + if (dateTime2 < dateTime4.AddDays(5)) + { + return false; + } + dateTime4 = vigencia1.AddDays(5); + DateTime? nullable1 = x.Item.Documento.Vigencia2; + if (!nullable1.HasValue) + { + return false; + } + return dateTime4 <= nullable1.GetValueOrDefault(); + }).ToList().FirstOrDefault((AutoDb x) => { + long? nullable; + if (!x.Item.Cancelado) + { + long? substituido = x.Item.Substituido; + if (!substituido.HasValue && !x.Item.Documento.Excluido) + { + long num = idSeguradora; + ControleDb controle = x.Item.Documento.Controle; + if (controle != null) + { + nullable = new long?(controle.Seguradora.Id); + } + else + { + nullable = null; + } + substituido = nullable; + return num == substituido.GetValueOrDefault() & substituido.HasValue; + } + } + return false; + }); + if (autoDb != null) + { + documento = autoDb.Item.Documento; + } + else + { + documento = null; + } + return ApplicationMapper.Mapper.Map(documento); + } + + public Auto FindById(long id) + { + AutoDb autoDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(autoDb); + } + + public string FindChassi(long id) + { + List condicaos = new List() + { + new Condicao() + { + Campo = "iditem", + Valores = id.CriarValor() + } + }; + DataTable dataTable = this._unitOfWork.Select(condicaos.CreateParameters(0), "SELECT chassi FROM auto WHERE ", ""); + if (dataTable == null) + { + return null; + } + DataRow dataRow = dataTable.AsEnumerable().FirstOrDefault(); + if (dataRow == null) + { + return null; + } + return dataRow.Field("chassi"); + } + + public List FindPlaca(string placa, FiltroStatusDocumento status, List vendedorVinculado) + { + List pesquisaAvancadas; + object connection; + string str = placa.Replace("-", ""); + string str1 = str.Insert(3, "-"); + DataTable dataTable = new DataTable(); + DataTable dataTable1 = new DataTable(); + DataTable dataTable2 = new DataTable(); + DataTable dataTable3 = new DataTable(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = string.Concat(new string[] { "SELECT iditem as id FROM auto WHERE placa ='", str, "' OR placa ='", str1, "'" }); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + if (dataTable.Rows.Count != 0) + { + string str2 = string.Concat(" AND iditem IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); + sqlCommand.CommandText = string.Concat("SELECT iddocumento as id, descricao, iditem FROM item WHERE 1=1 ", str2); + using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) + { + sqlDataAdapter1.SelectCommand = sqlCommand; + sqlDataAdapter1.Fill(dataTable1); + } + sqlCommand.CommandText = string.Concat("SELECT DISTINCT cl.nome as cliente, c.idcliente, d.idcontrole, d.iddocumento, situacao, vigencia1, vigencia2, proposta, contrato as apolice, aditamento as endosso, CAST(tipo as INTEGER) as tipo FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE (d.excluido IS NULL OR d.excluido != '1') AND d.iddocumento IN (", string.Join(",", dataTable1.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); + using (SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter()) + { + sqlDataAdapter2.SelectCommand = sqlCommand; + sqlDataAdapter2.Fill(dataTable2); + } + string str3 = string.Concat(" AND d.idcontrole IN (", string.Join(",", ( + from x in dataTable2.AsEnumerable().ToList() + select x.Field("idcontrole")).ToList()), ")"); + sqlCommand.CommandText = string.Concat("SELECT DISTINCT vp.idvendedor, d.iddocumento, d.idcontrole, vp.idtipovendedor FROM vendedorparcela vp INNER JOIN documento d on d.iddocumento = vp.iddocumento WHERE 1=1 ", str3); + using (SqlDataAdapter sqlDataAdapter3 = new SqlDataAdapter()) + { + sqlDataAdapter3.SelectCommand = sqlCommand; + sqlDataAdapter3.Fill(dataTable3); + goto Label0; + } + } + else + { + pesquisaAvancadas = new List(); + } + } + } + return pesquisaAvancadas; + Label0: + List list = null; + if (vendedorVinculado != null && vendedorVinculado.Count > 0) + { + list = dataTable3.AsEnumerable().Where((DataRow x) => { + List vendedorUsuarios = vendedorVinculado; + Func u003cu003e9_915 = AutoRepository.u003cu003ec.u003cu003e9__9_15; + if (u003cu003e9_915 == null) + { + u003cu003e9_915 = (VendedorUsuario v) => v.Vendedor.Id; + AutoRepository.u003cu003ec.u003cu003e9__9_15 = u003cu003e9_915; + } + return vendedorUsuarios.Select(u003cu003e9_915).Contains(x.Field("idvendedor")); + }).Select((DataRow x) => x.Field("idcontrole")).ToList(); + } + if (list != null && list.Count == 0) + { + return new List(); + } + DateTime date = Funcoes.GetNetworkTime().Date; + switch (status) + { + case FiltroStatusDocumento.Vencidos: + { + return dataTable2.AsEnumerable().Where((DataRow x) => { + if ((list == null || list.Contains(x.Field("idcontrole"))) && (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()) == TipoSeguro.Renovado) + { + return true; + } + return x.Field("vigencia2") < date.AddDays(-5); + }).Select((DataRow x) => new PesquisaAvancada() + { + IdCliente = x.Field("idcliente"), + IdDocumento = x.Field("iddocumento"), + IdItem = dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("iditem"), + Nome = x.Field("cliente"), + Pesquisa = (x.Field("tipo") == 0 ? string.Concat(new string[] { "ITEM: ", dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("descricao"), " - NÚMERO DA APÓLICE: ", x.Field("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field("proposta") }) : string.Concat(new string[] { "ITEM: ", dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("descricao"), " - NÚMERO DA APÓLICE: ", x.Field("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field("proposta"), " - NÚMERO DO ENDOSSO: ", x.Field("endosso") })) + }).ToList(); + } + case FiltroStatusDocumento.Cancelados: + { + return dataTable2.AsEnumerable().Where((DataRow x) => { + if (list != null && !list.Contains(x.Field("idcontrole"))) + { + return false; + } + return (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()) == TipoSeguro.Cancelado; + }).Select((DataRow x) => new PesquisaAvancada() + { + IdCliente = x.Field("idcliente"), + IdDocumento = x.Field("iddocumento"), + IdItem = dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("iditem"), + Nome = x.Field("cliente"), + Pesquisa = (x.Field("tipo") == 0 ? string.Concat(new string[] { "ITEM: ", dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("descricao"), " - NÚMERO DA APÓLICE: ", x.Field("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field("proposta") }) : string.Concat(new string[] { "ITEM: ", dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("descricao"), " - NÚMERO DA APÓLICE: ", x.Field("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field("proposta"), " - NÚMERO DO ENDOSSO: ", x.Field("endosso") })) + }).ToList(); + } + case FiltroStatusDocumento.Recusados: + { + return dataTable2.AsEnumerable().Where((DataRow x) => { + if (list != null && !list.Contains(x.Field("idcontrole"))) + { + return false; + } + return (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()) == TipoSeguro.Recusado; + }).Select((DataRow x) => new PesquisaAvancada() + { + IdCliente = x.Field("idcliente"), + IdDocumento = x.Field("iddocumento"), + IdItem = dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("iditem"), + Nome = x.Field("cliente"), + Pesquisa = (x.Field("tipo") == 0 ? string.Concat(new string[] { "ITEM: ", dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("descricao"), " - NÚMERO DA APÓLICE: ", x.Field("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field("proposta") }) : string.Concat(new string[] { "ITEM: ", dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("descricao"), " - NÚMERO DA APÓLICE: ", x.Field("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field("proposta"), " - NÚMERO DO ENDOSSO: ", x.Field("endosso") })) + }).ToList(); + } + case FiltroStatusDocumento.Todos: + { + return dataTable2.AsEnumerable().Where((DataRow x) => { + if (list == null) + { + return true; + } + return list.Contains(x.Field("idcontrole")); + }).Select((DataRow x) => new PesquisaAvancada() + { + IdCliente = x.Field("idcliente"), + IdDocumento = x.Field("iddocumento"), + IdItem = dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("iditem"), + Nome = x.Field("cliente"), + Pesquisa = (x.Field("tipo") == 0 ? string.Concat(new string[] { "ITEM: ", dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("descricao"), " - NÚMERO DA APÓLICE: ", x.Field("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field("proposta") }) : string.Concat(new string[] { "ITEM: ", dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("descricao"), " - NÚMERO DA APÓLICE: ", x.Field("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field("proposta"), " - NÚMERO DO ENDOSSO: ", x.Field("endosso") })) + }).ToList(); + } + default: + { + return dataTable2.AsEnumerable().Where((DataRow x) => { + if (list != null && !list.Contains(x.Field("idcontrole")) || (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()) != TipoSeguro.Novo && (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()) != TipoSeguro.Renovacao) + { + return false; + } + return x.Field("vigencia2") > date.AddDays(-5); + }).Select((DataRow x) => new PesquisaAvancada() + { + IdCliente = x.Field("idcliente"), + IdDocumento = x.Field("iddocumento"), + IdItem = dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("iditem"), + Nome = x.Field("cliente"), + Pesquisa = (x.Field("tipo") == 0 ? string.Concat(new string[] { "ITEM: ", dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("descricao"), " - NÚMERO DA APÓLICE: ", x.Field("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field("proposta") }) : string.Concat(new string[] { "ITEM: ", dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("descricao"), " - NÚMERO DA APÓLICE: ", x.Field("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field("proposta"), " - NÚMERO DO ENDOSSO: ", x.Field("endosso") })) + }).ToList(); + } + } + } + + public Auto Merge(Auto auto) + { + AutoDb autoDb = ApplicationMapper.Mapper.Map(auto); + base.Merge(autoDb); + return ApplicationMapper.Mapper.Map(autoDb); + } + + public Auto SaveOrUpdate(Auto auto) + { + AutoDb autoDb = ApplicationMapper.Mapper.Map(auto); + this.SaveOrUpdate(autoDb); + return ApplicationMapper.Mapper.Map(autoDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/BancoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/BancoRepository.cs new file mode 100644 index 0000000..eaba0c1 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/BancoRepository.cs @@ -0,0 +1,69 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Common; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class BancoRepository : GenericRepository, IBancoRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public BancoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public List Find(string filter) + { + BancoRepository.u003cu003ec__DisplayClass7_0 variable = null; + IQueryable bancoDbs = base.All(); + ParameterExpression parameterExpression = Expression.Parameter(typeof(BancoDb), "x"); + IQueryable bancoDbs1 = bancoDbs.Where(Expression.Lambda>(Expression.OrElse(Expression.Call(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(BancoDb).GetMethod("get_Nome").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Trim").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(BancoRepository.u003cu003ec__DisplayClass7_0)), FieldInfo.GetFieldFromHandle(typeof(BancoRepository.u003cu003ec__DisplayClass7_0).GetField("filter").FieldHandle)) }), Expression.Call(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(BancoDb).GetMethod("get_Codigo").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(int).GetMethod("ToString").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Trim").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(BancoRepository.u003cu003ec__DisplayClass7_0)), FieldInfo.GetFieldFromHandle(typeof(BancoRepository.u003cu003ec__DisplayClass7_0).GetField("filter").FieldHandle)) })), new ParameterExpression[] { parameterExpression })); + parameterExpression = Expression.Parameter(typeof(BancoDb), "x"); + return bancoDbs1.Select(Expression.Lambda>(Expression.MemberInit(Expression.New(typeof(Banco)), new MemberBinding[] { Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Banco).GetMethod("set_Id", new Type[] { typeof(int) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(BancoDb).GetMethod("get_Id").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Banco).GetMethod("set_Nome", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(BancoDb).GetMethod("get_Nome").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Banco).GetMethod("set_Codigo", new Type[] { typeof(int) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(BancoDb).GetMethod("get_Codigo").MethodHandle))) }), new ParameterExpression[] { parameterExpression })).ToList(); + } + + public Banco FindById(long id) + { + BancoDb bancoDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(bancoDb); + } + + public Banco Merge(Banco banco) + { + BancoDb bancoDb = ApplicationMapper.Mapper.Map(banco); + base.Merge(bancoDb); + return ApplicationMapper.Mapper.Map(bancoDb); + } + + public Banco SaveOrUpdate(Banco banco) + { + BancoDb bancoDb = ApplicationMapper.Mapper.Map(banco); + this.SaveOrUpdate(bancoDb); + return ApplicationMapper.Mapper.Map(bancoDb); + } + + public List SelectDefault() + { + return ApplicationMapper.Mapper.Map, List>(( + from x in base.All() + orderby x.Nome + select x).ToList()); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/BancosContasRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/BancosContasRepository.cs new file mode 100644 index 0000000..53fa20c --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/BancosContasRepository.cs @@ -0,0 +1,119 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Financeiro; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Helpers; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Financeiro; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class BancosContasRepository : GenericRepository, IBancosContasRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public BancosContasRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + List list = ( + from x in this._unitOfWork.Query() + where x.Conta.Id == id + select x).ToList(); + if (list.Any()) + { + this._unitOfWork.Repository().DeleteRange(list); + } + BancosContasDb bancosContasDb = base.FindEntityById(id); + if (bancosContasDb == null) + { + return; + } + base.Delete(bancosContasDb); + } + + public List Find(string filter) + { + return this.Select(" AND ISNULL(UPPER(descricao)) LIKE '%filter%'"); + } + + public List Find() + { + return this.Select(""); + } + + public BancosContas FindById(long id) + { + BancosContasDb bancosContasDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(bancosContasDb); + } + + public BancosContas Merge(BancosContas bancosContas) + { + BancosContasDb bancosContasDb = ApplicationMapper.Mapper.Map(bancosContas); + base.Merge(bancosContasDb); + return ApplicationMapper.Mapper.Map(bancosContasDb); + } + + public BancosContas SaveOrUpdate(BancosContas bancosContas) + { + BancosContasDb bancosContasDb = ApplicationMapper.Mapper.Map(bancosContas); + this.SaveOrUpdate(bancosContasDb); + return ApplicationMapper.Mapper.Map(bancosContasDb); + } + + private List Select(string condition) + { + List bancosContas; + object connection; + DataTable dataTable = new DataTable(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + Auxiliar.CriarAuxiliar(sqlCommand, false); + sqlCommand.CommandText = string.Concat("SELECT * FROM conta WHERE 1=1 ", condition); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + if (dataTable.Rows.Count != 0) + { + return CustomMap.MapConta(dataTable); + } + else + { + bancosContas = new List(); + } + } + } + return bancosContas; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CategoriaTarefaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CategoriaTarefaRepository.cs new file mode 100644 index 0000000..e3cbdf9 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CategoriaTarefaRepository.cs @@ -0,0 +1,46 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Ferramentas; +using System; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class CategoriaTarefaRepository : GenericRepository, ICategoriaTarefaRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public CategoriaTarefaRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public CategoriaTarefa FindById(long id) + { + CategoriaTarefaDb categoriaTarefaDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(categoriaTarefaDb); + } + + public CategoriaTarefa Merge(CategoriaTarefa categoriaTarefa) + { + CategoriaTarefaDb categoriaTarefaDb = ApplicationMapper.Mapper.Map(categoriaTarefa); + base.Merge(categoriaTarefaDb); + return ApplicationMapper.Mapper.Map(categoriaTarefaDb); + } + + public CategoriaTarefa SaveOrUpdate(CategoriaTarefa categoriaTarefa) + { + CategoriaTarefaDb categoriaTarefaDb = ApplicationMapper.Mapper.Map(categoriaTarefa); + this.SaveOrUpdate(categoriaTarefaDb); + return ApplicationMapper.Mapper.Map(categoriaTarefaDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CentroRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CentroRepository.cs new file mode 100644 index 0000000..c72986f --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CentroRepository.cs @@ -0,0 +1,96 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Financeiro; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class CentroRepository : GenericRepository, ICentroRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public CentroRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public List Find(string filter) + { + CentroRepository.u003cu003ec__DisplayClass2_0 variable = null; + IQueryable centroDbs = base.All(); + ParameterExpression parameterExpression = Expression.Parameter(typeof(CentroDb), "x"); + IQueryable centroDbs1 = centroDbs.Where(Expression.Lambda>(Expression.AndAlso(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(CentroDb).GetMethod("get_Ativo").MethodHandle)), Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(CentroDb).GetMethod("get_Descricao").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(CentroRepository.u003cu003ec__DisplayClass2_0)), FieldInfo.GetFieldFromHandle(typeof(CentroRepository.u003cu003ec__DisplayClass2_0).GetField("filter").FieldHandle)) })), new ParameterExpression[] { parameterExpression })); + parameterExpression = Expression.Parameter(typeof(CentroDb), "x"); + return centroDbs1.Select(Expression.Lambda>(Expression.MemberInit(Expression.New(typeof(Centro)), new MemberBinding[] { Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(DomainBase).GetMethod("set_Id", new Type[] { typeof(long) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(EntityBase).GetMethod("get_Id").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Centro).GetMethod("set_Descricao", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(CentroDb).GetMethod("get_Descricao").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Centro).GetMethod("set_Ativo", new Type[] { typeof(bool) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(CentroDb).GetMethod("get_Ativo").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Centro).GetMethod("set_IdEmpresa", new Type[] { typeof(long) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(CentroDb).GetMethod("get_IdEmpresa").MethodHandle))) }), new ParameterExpression[] { parameterExpression })).ToList(); + } + + public List Find() + { + object connection; + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + DataTable dataTable = new DataTable(); + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + if (sqlConnection != null) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = "SELECT DISTINCT idcentro as id, descricao as nome, ativo FROM centro;"; + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + } + } + } + return ( + from a in dataTable.AsEnumerable().ToList() + select new Centro() + { + Id = a.Field("id"), + Descricao = a.Field("nome"), + Ativo = (a.Field("ativo") == null ? true : a.Field("ativo").ToString() == "1") + }).ToList(); + } + + public Centro Merge(Centro centro) + { + CentroDb centroDb = ApplicationMapper.Mapper.Map(centro); + base.Merge(centroDb); + return ApplicationMapper.Mapper.Map(centroDb); + } + + public Centro SaveOrUpdate(Centro centro) + { + CentroDb centroDb = ApplicationMapper.Mapper.Map(centro); + this.SaveOrUpdate(centroDb); + return ApplicationMapper.Mapper.Map(centroDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteEmailRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteEmailRepository.cs new file mode 100644 index 0000000..6d40eff --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteEmailRepository.cs @@ -0,0 +1,248 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class ClienteEmailRepository : GenericRepository, IClienteEmailRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public ClienteEmailRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public List DeleteMail(long clienteId, List emails) + { + if (emails == null) + { + return null; + } + List list = ( + from x in base.All() + where x.Cliente.Id == clienteId + select x).ToList().Where((ClienteEmailDb email) => { + List clienteEmails = emails; + Func u003cu003e9_112 = ClienteEmailRepository.u003cu003ec.u003cu003e9__11_2; + if (u003cu003e9_112 == null) + { + u003cu003e9_112 = (ClienteEmail t) => t.Id; + ClienteEmailRepository.u003cu003ec.u003cu003e9__11_2 = u003cu003e9_112; + } + return !clienteEmails.Select(u003cu003e9_112).Contains(email.Id); + }).ToList(); + if (emails.Count == 0 && (list == null || list.Count == 0)) + { + return null; + } + ClienteEmailRepository clienteEmailRepository = this; + list.ForEach(new Action(clienteEmailRepository.Delete)); + return ApplicationMapper.Mapper.Map, List>(list); + } + + private List FindByCliente(long id) + { + return this.Select(string.Format(" AND cm.idcliente = {0}", id)); + } + + public List FindByCliente(List ids) + { + if (ids.Count == 0) + { + return new List(); + } + string str = string.Concat(" AND cm.idcliente IN (", string.Join(",", ids), ")"); + return this.Select(str); + } + + public List FindByClienteId(long id) + { + return this.FindByCliente(id); + } + + public ClienteEmail FindById(long id) + { + ClienteEmailDb clienteEmailDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(clienteEmailDb); + } + + public List FindEmailCliente(string email, long idempresa = 0L) + { + return this.Select((idempresa == 0 ? string.Concat(" AND cm.email LIKE '%", email, "%'") : string.Format(" AND c.idempresa = {0} AND CONTAINS(cm.email, \"%{1}%\")", idempresa, email))); + } + + public List Inserir(List emails, Cliente cliente) + { + emails.ForEach((ClienteEmail x) => { + string str; + x.Cliente = cliente; + ClienteEmail clienteEmail = x; + string observacao = x.Observacao; + if (observacao != null) + { + str = observacao.Trim(); + } + else + { + str = null; + } + clienteEmail.Observacao = str; + }); + List clienteEmailDbs = ApplicationMapper.Mapper.Map, List>(emails); + base.AddRange(clienteEmailDbs); + return ApplicationMapper.Mapper.Map, List>(clienteEmailDbs); + } + + public List Inserir(List emails) + { + List clienteEmailDbs = ApplicationMapper.Mapper.Map, List>(emails); + clienteEmailDbs.ForEach((ClienteEmailDb x) => { + string str; + ClienteEmailDb clienteEmailDb = x; + string observacao = x.Observacao; + if (observacao != null) + { + str = observacao.Trim(); + } + else + { + str = null; + } + clienteEmailDb.Observacao = str; + if (x.Id == 0) + { + this.SaveOrUpdate(x); + return; + } + base.Merge(x); + }); + return ApplicationMapper.Mapper.Map, List>(clienteEmailDbs); + } + + public ClienteEmail Merge(ClienteEmail clienteEmail) + { + string str; + ClienteEmailDb clienteEmailDb = ApplicationMapper.Mapper.Map(clienteEmail); + ClienteEmailDb clienteEmailDb1 = clienteEmailDb; + string observacao = clienteEmailDb.Observacao; + if (observacao != null) + { + str = observacao.Trim(); + } + else + { + str = null; + } + clienteEmailDb1.Observacao = str; + base.Merge(clienteEmailDb); + return ApplicationMapper.Mapper.Map(clienteEmailDb); + } + + public List Merge(List emails, Cliente cliente) + { + List clienteEmailDbs = ApplicationMapper.Mapper.Map, List>(emails); + clienteEmailDbs.ForEach((ClienteEmailDb x) => { + string str; + ClienteEmailDb clienteEmailDb = x; + string observacao = x.Observacao; + if (observacao != null) + { + str = observacao.Trim(); + } + else + { + str = null; + } + clienteEmailDb.Observacao = str; + if (x.Id != 0) + { + base.Merge(x); + return; + } + x.Cliente = ApplicationMapper.Mapper.Map(cliente); + this.SaveOrUpdate(x); + }); + return ApplicationMapper.Mapper.Map, List>(clienteEmailDbs); + } + + public ClienteEmail SaveOrUpdate(ClienteEmail clienteEmail) + { + string str; + ClienteEmailDb clienteEmailDb = ApplicationMapper.Mapper.Map(clienteEmail); + ClienteEmailDb clienteEmailDb1 = clienteEmailDb; + string observacao = clienteEmailDb.Observacao; + if (observacao != null) + { + str = observacao.Trim(); + } + else + { + str = null; + } + clienteEmailDb1.Observacao = str; + this.SaveOrUpdate(clienteEmailDb); + return ApplicationMapper.Mapper.Map(clienteEmailDb); + } + + private List Select(string condition) + { + object connection; + DataTable dataTable = new DataTable(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = string.Concat("SELECT cm.idclimail AS Id, cm.idcliente as IdCliente, cm.email AS Email, cm.obs AS Observacao, cm.ordem AS Ordem, c.nome as NomeCliente FROM climail cm INNER JOIN cliente c ON c.idcliente = cm.idcliente WHERE 1=1 ", condition); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + } + } + List clienteEmails = CustomMap.MapEmail(dataTable); + int? nullable1 = new int?(0); + clienteEmails.ForEach((ClienteEmail x) => { + int? ordem = nullable1; + int? nullable = ordem; + nullable1 = (nullable.HasValue ? new int?(nullable.GetValueOrDefault() + 1) : null); + ClienteEmail clienteEmail = x; + ordem = x.Ordem; + clienteEmail.Ordem = (ordem.HasValue ? ordem : nullable1); + }); + return clienteEmails; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteEnderecoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteEnderecoRepository.cs new file mode 100644 index 0000000..9a2ac8e --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteEnderecoRepository.cs @@ -0,0 +1,223 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class ClienteEnderecoRepository : GenericRepository, IClienteEnderecoRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public ClienteEnderecoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public List DeleteEndereco(long clienteId, List enderecos) + { + if (enderecos == null || enderecos.Count == 0) + { + return null; + } + List list = ( + from cliente in base.All() + where cliente.Cliente.Id == clienteId + select cliente).ToList().Where((ClienteEnderecoDb endereco) => { + List clienteEnderecos = enderecos; + Func u003cu003e9_102 = ClienteEnderecoRepository.u003cu003ec.u003cu003e9__10_2; + if (u003cu003e9_102 == null) + { + u003cu003e9_102 = (ClienteEndereco t) => t.Id; + ClienteEnderecoRepository.u003cu003ec.u003cu003e9__10_2 = u003cu003e9_102; + } + return !clienteEnderecos.Select(u003cu003e9_102).Contains(endereco.Id); + }).ToList(); + ClienteEnderecoRepository clienteEnderecoRepository = this; + list.ForEach(new Action(clienteEnderecoRepository.Delete)); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public List FindByCliente(List clientes) + { + string str = string.Concat(" AND ce.idcliente in (", string.Join(",", ( + from x in clientes + select x.Id).Distinct()), ")"); + List clienteEnderecos = this.Select(str); + ( + from x in clienteEnderecos + orderby x.Ordem + select x).ToList().ForEach((ClienteEndereco x) => x.Selecionado = x.Id == clienteEnderecos.First((ClienteEndereco c) => c.Cliente.Id == x.Cliente.Id).Id); + return clienteEnderecos; + } + + public List FindByClienteId(long id) + { + return this.Select(string.Format(" AND ce.idcliente = {0}", id)); + } + + public ClienteEndereco FindById(long id) + { + ClienteEnderecoDb clienteEnderecoDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(clienteEnderecoDb); + } + + public List Inserir(List endereco, Cliente cliente) + { + endereco.ForEach((ClienteEndereco x) => x.Cliente = cliente); + List clienteEnderecoDbs = ApplicationMapper.Mapper.Map, List>(endereco); + base.AddRange(clienteEnderecoDbs); + return ApplicationMapper.Mapper.Map, List>(clienteEnderecoDbs); + } + + public List Inserir(List endereco) + { + List clienteEnderecoDbs = ApplicationMapper.Mapper.Map, List>(endereco); + clienteEnderecoDbs.ForEach((ClienteEnderecoDb x) => { + string str; + ClienteEnderecoDb clienteEnderecoDb = x; + string observacao = x.Observacao; + if (observacao != null) + { + str = observacao.Trim(); + } + else + { + str = null; + } + clienteEnderecoDb.Observacao = str; + if (x.Id == 0) + { + this.SaveOrUpdate(x); + return; + } + base.Merge(x); + }); + return ApplicationMapper.Mapper.Map, List>(clienteEnderecoDbs); + } + + public ClienteEndereco Merge(ClienteEndereco clienteEndereco) + { + string str; + ClienteEnderecoDb clienteEnderecoDb = ApplicationMapper.Mapper.Map(clienteEndereco); + ClienteEnderecoDb clienteEnderecoDb1 = clienteEnderecoDb; + string observacao = clienteEnderecoDb.Observacao; + if (observacao != null) + { + str = observacao.Trim(); + } + else + { + str = null; + } + clienteEnderecoDb1.Observacao = str; + base.Merge(clienteEnderecoDb); + return ApplicationMapper.Mapper.Map(clienteEnderecoDb); + } + + public List Merge(List enderecos, Cliente cliente) + { + List clienteEnderecoDbs = ApplicationMapper.Mapper.Map, List>(enderecos); + clienteEnderecoDbs.ForEach((ClienteEnderecoDb x) => { + string str; + ClienteEnderecoDb clienteEnderecoDb = x; + string observacao = x.Observacao; + if (observacao != null) + { + str = observacao.Trim(); + } + else + { + str = null; + } + clienteEnderecoDb.Observacao = str; + if (x.Id != 0) + { + base.Merge(x); + return; + } + x.Cliente = ApplicationMapper.Mapper.Map(cliente); + this.SaveOrUpdate(x); + }); + return ApplicationMapper.Mapper.Map, List>(clienteEnderecoDbs); + } + + public ClienteEndereco SaveOrUpdate(ClienteEndereco clienteEndereco) + { + string str; + ClienteEnderecoDb clienteEnderecoDb = ApplicationMapper.Mapper.Map(clienteEndereco); + ClienteEnderecoDb clienteEnderecoDb1 = clienteEnderecoDb; + string observacao = clienteEnderecoDb.Observacao; + if (observacao != null) + { + str = observacao.Trim(); + } + else + { + str = null; + } + clienteEnderecoDb1.Observacao = str; + this.SaveOrUpdate(clienteEnderecoDb); + return ApplicationMapper.Mapper.Map(clienteEnderecoDb); + } + + private List Select(string condition) + { + object connection; + DataTable dataTable = new DataTable(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = string.Concat("SELECT ce.*, c.nome as NomeCliente FROM cliendereco ce INNER JOIN cliente c ON c.idcliente = ce.idcliente WHERE 1=1 ", condition); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + } + } + List clienteEnderecos = dataTable.MapEndereco(); + int? nullable1 = new int?(0); + clienteEnderecos.ForEach((ClienteEndereco x) => { + int? ordem = nullable1; + int? nullable = ordem; + nullable1 = (nullable.HasValue ? new int?(nullable.GetValueOrDefault() + 1) : null); + ClienteEndereco clienteEndereco = x; + ordem = x.Ordem; + clienteEndereco.Ordem = (ordem.HasValue ? ordem : nullable1); + }); + return clienteEnderecos; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteRepository.cs new file mode 100644 index 0000000..f07399f --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteRepository.cs @@ -0,0 +1,3102 @@ +using AutoMapper; +using Gestor.Common.Helpers; +using Gestor.Common.Validation; +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Helpers; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Relatorios.Classificacao; +using Gestor.Model.Domain.Relatorios.ClientesAtivosInativos; +using Gestor.Model.Domain.Relatorios.Dashboard; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Relatorios; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using NHibernate.Util; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Diagnostics; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class ClienteRepository : GenericRepository, IClienteRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + private const string ComandoEndereco = "SELECT DISTINCT idcliend, cep, cidade, uf as estado, idcliente as id, endereco, numero, comp_end as complemento FROM cliendereco WHERE "; + + private const string ComandoTelefone = "SELECT DISTINCT idclitelefone, ddd, fone, idcliente as id FROM clitelefone WHERE "; + + private const string ComandoEmail = "SELECT DISTINCT idclimail, email, idcliente as id FROM climail WHERE "; + + private const string ComandoCliente = "SELECT idcliente as id, idempresa, nome, cgccpf as documento, cei, rne, documentoprincipal, anotacoes, dtnasc as nascimento, idprofissao, VENCHABILI as vencimento, sexo, RendaMensal, pasta, MalaDireta, clidesde, ESTADOCIVI FROM cliente WHERE "; + + private const string ComandoClienteVinculo = "SELECT DISTINCT cl.idcliente as id, cl.idempresa, cl.nome, cl.cgccpf as documento, cl.cei, cl.rne, cl.documentoprincipal, cl.anotacoes, cl.dtnasc as nascimento, cl.idprofissao,cl.VENCHABILI as vencimento, cl.sexo, cl.RendaMensal, cl.pasta, cl.MalaDireta, cl.clidesde, cl.ESTADOCIVI FROM cliente cl inner join controle co on co.idcliente = cl.idcliente inner join documento d on d.idcontrole = co.idcontrole inner join vendedorparcela vp on vp.iddocumento = d.iddocumento inner join vendedorusuario vu on vu.idvendedor = vp.idvendedor WHERE "; + + public ClienteRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void AddCentralSegurado(long id, bool update) + { + try + { + this._unitOfWork.Session.BeginTransaction(); + this._unitOfWork.Session.CreateQuery("update ClienteDb c set c.EstaNaCentralSegurado = :update where c.Id = :updatedid").SetParameter("updatedid", id).SetParameter("update", update).ExecuteUpdate(); + this._unitOfWork.Commit(); + } + catch + { + } + } + + public async Task> BuscaClientes(bool completo, long idempresa = 0L) + { + IEnumerable clientesAtivosInativos; + DateTime? nullable; + object connection; + string str; + bool flag; + DateTime? nullable1; + string str1; + DateTime? nullable2; + string nome; + string str2; + string str3; + decimal num; + DateTime? nullable3; + ClienteRepository.u003cu003ec__DisplayClass34_0 variable; + Func func = null; + Action action2 = null; + List clientesAtivosInativos1 = new List(); + IEnumerable documentos = await this.DocumentosPeriodo(completo); + IEnumerable clienteEnderecos = await this.EnderecoClientes(); + IEnumerable clienteTelefones = await this.TelefonesClientes(); + IEnumerable clienteEmails = await this.EmailsClientes(); + Array values = Enum.GetValues(typeof(EstadoCivil)); + Regex regex = new Regex("[^\\d]"); + IEnumerable estipulanteClientes = await this.EstipulanteCliente(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + if (sqlConnection != null) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + Auxiliar.CriarAuxiliar(sqlCommand, true); + SqlCommand sqlCommand1 = sqlCommand; + str = (idempresa > (long)0 ? "AND idempresa = @empresa" : ""); + sqlCommand1.CommandText = string.Concat("SELECT c.idcliente,c.nome,c.maladireta,c.dtnasc,c.sexo,c.estadocivi,c.venchabili,c.idprofissao,c.pasta,c.cgccpf,c.rendamensal, c.nomesocialrg, c.clidesde, IIF((SELECT TOP 1 idvinculo FROM clivinculo cv WHERE cv.idcliente1 = c.idcliente OR cv.idcliente2 = c.idcliente) IS NOT NULL, 'SIM', 'NÃO') Parentesco FROM cliente c WHERE (excluido IS NULL OR excluido = 0) ", str); + sqlCommand.Parameters.Add("@empresa", SqlDbType.BigInt).Value = idempresa; + sqlCommand.CommandTimeout = 1000; + using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) + { + while (true) + { + if (!await sqlDataReader.ReadAsync()) + { + break; + } + long item = (long)sqlDataReader["idcliente"]; + string str4 = sqlDataReader["nome"].ToString(); + string str5 = sqlDataReader["nomesocialrg"].ToString(); + flag = (sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("maladireta")) ? true : (bool)sqlDataReader["maladireta"]); + bool flag1 = flag; + if (sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("dtnasc"))) + { + nullable = null; + nullable1 = nullable; + } + else + { + nullable1 = new DateTime?((DateTime)sqlDataReader["dtnasc"]); + } + DateTime? nullable4 = nullable1; + str1 = (sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("sexo")) ? "" : sqlDataReader["sexo"].ToString()); + string str6 = str1; + Sexo sexo = Sexo.Masculino; + if (!string.IsNullOrWhiteSpace(str6) && !Enum.TryParse(str6, out sexo)) + { + str6 = ""; + } + IEnumerable id = + from d in documentos + where d.Controle.Cliente.Id == item + select d; + Gestor.Model.Relatorios.ClienteEndereco clienteEndereco = clienteEnderecos.FirstOrDefault((Gestor.Model.Relatorios.ClienteEndereco e) => e.Cliente.Id == item); + if (clienteEndereco == null) + { + clienteEndereco = new Gestor.Model.Relatorios.ClienteEndereco(); + } + Gestor.Model.Relatorios.ClienteEndereco clienteEndereco1 = clienteEndereco; + IEnumerable id1 = + from f in clienteTelefones + where f.Cliente.Id == item + select f; + IEnumerable clienteEmails1 = + from e in clienteEmails + where e.Cliente.Id == item + select e; + string str7 = ""; + string str8 = ""; + string str9 = "NÃO"; + string str10 = ""; + string description = ""; + int? nullable5 = null; + string str11 = ""; + if (nullable4.HasValue) + { + str10 = nullable4.Value.ToString("dd/MM"); + nullable5 = new int?(this.CalculaIdade(nullable4.Value)); + } + List strs = new List(); + id.ForEach((Gestor.Model.Relatorios.Documento d) => { + str9 = "SIM"; + if (completo) + { + int? ordem = d.Ordem; + if (ordem.GetValueOrDefault() > 0 & ordem.HasValue) + { + return; + } + strs.Add(d.Controle.Ramo.Nome ?? ""); + IList vendedores = d.Vendedores; + if (vendedores == null) + { + return; + } + Action u003cu003e9_10 = action2; + if (u003cu003e9_10 == null) + { + Action action = (Gestor.Model.Relatorios.Vendedor v) => { + if (!str7.Contains(v.Nome)) + { + if (str7.Length > 0) + { + str7 = string.Concat(str7, " | "); + } + str7 = string.Concat(str7, v.Nome); + } + }; + Action action1 = action; + action2 = action; + u003cu003e9_10 = action1; + } + vendedores.ForEach(u003cu003e9_10); + } + }); + List clienteTelefones1 = new List(); + id1.ForEach((Gestor.Model.Relatorios.ClienteTelefone f) => clienteTelefones1.Add(new Gestor.Model.Domain.Seguros.ClienteTelefone() + { + Prefixo = f.Prefixo, + Numero = f.Numero + })); + if (!sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("estadocivi"))) + { + foreach (object value in values) + { + if (value.GetOldValue() != sqlDataReader["estadocivi"].ToString()) + { + continue; + } + description = ((EstadoCivil)value).GetDescription(); + break; + } + } + if (completo && strs.Count > 0) + { + List strs1 = strs; + IEnumerable> groupings = + from g in strs1 + group g by g; + str8 = string.Join(" | ", + from r in groupings + select string.Format("{0}: {1}", r.Key, r.Count())); + } + IEnumerable idCliente = + from x in estipulanteClientes + where x.IdCliente == item + select x; + str11 = string.Join(" | ", + from x in idCliente + select x.NomeEstipulante); + ClientesAtivosInativos clientesAtivosInativo = new ClientesAtivosInativos(); + Gestor.Model.Domain.Seguros.Cliente cliente = new Gestor.Model.Domain.Seguros.Cliente() + { + Id = item, + Nome = str4, + NomeSocialRg = str5, + MalaDireta = new bool?(flag1), + Telefones = new ObservableCollection(clienteTelefones1) + }; + clientesAtivosInativo.EntidadeCliente = cliente; + clientesAtivosInativo.Id = item; + clientesAtivosInativo.Nome = str4; + clientesAtivosInativo.Nascimento = nullable4; + clientesAtivosInativo.Aniversario = str10; + clientesAtivosInativo.Idade = nullable5; + clientesAtivosInativo.Documento = sqlDataReader["cgccpf"].ToString(); + if (sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("venchabili"))) + { + nullable = null; + nullable2 = nullable; + } + else + { + nullable2 = new DateTime?((DateTime)sqlDataReader["venchabili"]); + } + clientesAtivosInativo.VencimentoCnh = nullable2; + clientesAtivosInativo.Vendedor = str7; + clientesAtivosInativo.Ramo = str8; + List clienteTelefones2 = clienteTelefones1; + clientesAtivosInativo.Telefone = string.Join(" | ", + from f in clienteTelefones2 + select string.Concat(f.Prefixo, " ", f.Numero)); + IEnumerable clienteEmails2 = clienteEmails1; + clientesAtivosInativo.Email = string.Join(" | ", + from e in clienteEmails2 + select e.Email); + clientesAtivosInativo.Ativo = str9; + if (sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("idprofissao"))) + { + nome = ""; + } + else + { + List profissoes = Auxiliar.Profissoes; + Func func1 = func; + if (func1 == null) + { + Func id2 = (Profissao p) => p.Id == (long)this.rd["idprofissao"]; + Func func2 = id2; + func = id2; + func1 = func2; + } + Profissao profissao = profissoes.FirstOrDefault(func1); + if (profissao != null) + { + nome = profissao.Nome; + } + else + { + nome = null; + } + } + clientesAtivosInativo.Profissao = nome; + clientesAtivosInativo.Cep = clienteEndereco1.Cep; + clientesAtivosInativo.Endereco = clienteEndereco1.Endereco; + clientesAtivosInativo.Numero = clienteEndereco1.Numero; + clientesAtivosInativo.Complemento = clienteEndereco1.Complemento; + clientesAtivosInativo.Cidade = clienteEndereco1.Cidade; + clientesAtivosInativo.Estado = clienteEndereco1.Estado; + clientesAtivosInativo.Bairro = clienteEndereco1.Bairro; + clientesAtivosInativo.PastaCliente = sqlDataReader["pasta"].ToString(); + clientesAtivosInativo.RecebeEmail = (flag1 ? "SIM" : "NÃO"); + if (sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("cgccpf"))) + { + str2 = "FÍSICA"; + } + else + { + str2 = (regex.Replace(sqlDataReader["cgccpf"].ToString(), string.Empty).Length > 11 ? "JURÍDICA" : "FÍSICA"); + } + clientesAtivosInativo.TipoPessoa = str2; + clientesAtivosInativo.EstadoCivil = description; + str3 = (string.IsNullOrWhiteSpace(str6) ? "" : sexo.GetDescription()); + clientesAtivosInativo.Sexo = str3; + num = (sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("rendamensal")) ? decimal.Zero : (decimal)sqlDataReader["rendamensal"]); + clientesAtivosInativo.RendaMensal = num; + if (sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("clidesde"))) + { + nullable = null; + nullable3 = nullable; + } + else + { + nullable3 = new DateTime?((DateTime)sqlDataReader["clidesde"]); + } + clientesAtivosInativo.ClienteDesde = nullable3; + clientesAtivosInativo.Estipulantes = str11; + clientesAtivosInativo.Parentesco = sqlDataReader["Parentesco"].ToString(); + clientesAtivosInativos1.Add(clientesAtivosInativo); + } + } + } + sqlCommand = null; + } + else + { + clientesAtivosInativos = null; + variable = null; + clientesAtivosInativos1 = null; + documentos = null; + clienteEnderecos = null; + clienteTelefones = null; + clienteEmails = null; + values = null; + regex = null; + estipulanteClientes = null; + return clientesAtivosInativos; + } + } + sqlConnection = null; + clientesAtivosInativos = clientesAtivosInativos1; + variable = null; + clientesAtivosInativos1 = null; + documentos = null; + clienteEnderecos = null; + clienteTelefones = null; + clienteEmails = null; + values = null; + regex = null; + estipulanteClientes = null; + return clientesAtivosInativos; + } + + public async Task> BuscaClientesVinculo(bool completo, List vinculo, long idempresa = 0L) + { + IEnumerable clientesAtivosInativos; + DateTime? nullable; + object connection; + string str; + bool flag; + DateTime? nullable1; + string str1; + DateTime? nullable2; + string nome; + string str2; + string str3; + decimal num; + DateTime? nullable3; + ClienteRepository.u003cu003ec__DisplayClass43_0 variable; + Func func = null; + Action action2 = null; + List clientesAtivosInativos1 = new List(); + IEnumerable documentos = await this.DocumentosPeriodo(completo); + IEnumerable clienteEnderecos = await this.EnderecoClientes(); + IEnumerable clienteTelefones = await this.TelefonesClientes(); + IEnumerable clienteEmails = await this.EmailsClientes(); + Array values = Enum.GetValues(typeof(EstadoCivil)); + Regex regex = new Regex("[^\\d]"); + IEnumerable estipulanteClientes = await this.EstipulanteCliente(); + List vendedorUsuarios = vinculo; + List list = ( + from v in vendedorUsuarios + select v.Id).ToList(); + string[] array = ( + from id in list + select id.ToString()).ToArray(); + string str4 = string.Join(",", array); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + if (sqlConnection != null) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + Auxiliar.CriarAuxiliar(sqlCommand, true); + SqlCommand sqlCommand1 = sqlCommand; + string[] strArrays = new string[] { "SELECT DISTINCT c.idcliente,c.nome,c.maladireta,c.dtnasc,c.sexo,c.estadocivi,c.venchabili,c.idprofissao,c.pasta,c.cgccpf,c.rendamensal, c.nomesocialrg, c.clidesde, \r\n IIF((SELECT TOP 1 idvinculo FROM clivinculo cv WHERE cv.idcliente1 = c.idcliente OR cv.idcliente2 = c.idcliente) IS NOT NULL, 'SIM', 'NÃO') Parentesco FROM cliente c \r\n INNER JOIN controle co on co.idcliente = c.idcliente \r\n INNER JOIN documento d on d.idcontrole = co.idcontrole \r\n INNER JOIN vendedorparcela vp on vp.IdDocumento = d.IdDocumento \r\n INNER JOIN vendedorusuario vu on vu.idvendedor = vp.idvendedor \r\n WHERE (c.excluido IS NULL OR c.excluido = 0) ", null, null, null, null }; + str = (idempresa > (long)0 ? " AND c.idempresa = @empresa" : ""); + strArrays[1] = str; + strArrays[2] = " \r\n AND vu.idvendedorusuario in ("; + strArrays[3] = str4; + strArrays[4] = ")"; + sqlCommand1.CommandText = string.Concat(strArrays); + sqlCommand.Parameters.Add("@empresa", SqlDbType.BigInt).Value = idempresa; + sqlCommand.CommandTimeout = 1000; + using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) + { + while (true) + { + if (!await sqlDataReader.ReadAsync()) + { + break; + } + long item = (long)sqlDataReader["idcliente"]; + string str5 = sqlDataReader["nome"].ToString(); + string str6 = sqlDataReader["nomesocialrg"].ToString(); + flag = (sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("maladireta")) ? true : (bool)sqlDataReader["maladireta"]); + bool flag1 = flag; + if (sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("dtnasc"))) + { + nullable = null; + nullable1 = nullable; + } + else + { + nullable1 = new DateTime?((DateTime)sqlDataReader["dtnasc"]); + } + DateTime? nullable4 = nullable1; + str1 = (sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("sexo")) ? "" : sqlDataReader["sexo"].ToString()); + string str7 = str1; + Sexo sexo = Sexo.Masculino; + if (!string.IsNullOrWhiteSpace(str7) && !Enum.TryParse(str7, out sexo)) + { + str7 = ""; + } + IEnumerable documentos1 = + from d in documentos + where d.Controle.Cliente.Id == item + select d; + Gestor.Model.Relatorios.ClienteEndereco clienteEndereco = clienteEnderecos.FirstOrDefault((Gestor.Model.Relatorios.ClienteEndereco e) => e.Cliente.Id == item); + if (clienteEndereco == null) + { + clienteEndereco = new Gestor.Model.Relatorios.ClienteEndereco(); + } + Gestor.Model.Relatorios.ClienteEndereco clienteEndereco1 = clienteEndereco; + IEnumerable clienteTelefones1 = + from f in clienteTelefones + where f.Cliente.Id == item + select f; + IEnumerable clienteEmails1 = + from e in clienteEmails + where e.Cliente.Id == item + select e; + string str8 = ""; + string str9 = ""; + string str10 = "NÃO"; + string str11 = ""; + string description = ""; + int? nullable5 = null; + string str12 = ""; + if (nullable4.HasValue) + { + str11 = nullable4.Value.ToString("dd/MM"); + nullable5 = new int?(this.CalculaIdade(nullable4.Value)); + } + List strs = new List(); + documentos1.ForEach((Gestor.Model.Relatorios.Documento d) => { + str10 = "SIM"; + if (completo) + { + int? ordem = d.Ordem; + if (ordem.GetValueOrDefault() > 0 & ordem.HasValue) + { + return; + } + strs.Add(d.Controle.Ramo.Nome ?? ""); + IList vendedores = d.Vendedores; + if (vendedores == null) + { + return; + } + Action u003cu003e9_12 = action2; + if (u003cu003e9_12 == null) + { + Action action = (Gestor.Model.Relatorios.Vendedor v) => { + if (!str8.Contains(v.Nome)) + { + if (str8.Length > 0) + { + str8 = string.Concat(str8, " | "); + } + str8 = string.Concat(str8, v.Nome); + } + }; + Action action1 = action; + action2 = action; + u003cu003e9_12 = action1; + } + vendedores.ForEach(u003cu003e9_12); + } + }); + List clienteTelefones2 = new List(); + clienteTelefones1.ForEach((Gestor.Model.Relatorios.ClienteTelefone f) => clienteTelefones2.Add(new Gestor.Model.Domain.Seguros.ClienteTelefone() + { + Prefixo = f.Prefixo, + Numero = f.Numero + })); + if (!sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("estadocivi"))) + { + foreach (object value in values) + { + if (value.GetOldValue() != sqlDataReader["estadocivi"].ToString()) + { + continue; + } + description = ((EstadoCivil)value).GetDescription(); + break; + } + } + if (completo && strs.Count > 0) + { + List strs1 = strs; + IEnumerable> groupings = + from g in strs1 + group g by g; + str9 = string.Join(" | ", + from r in groupings + select string.Format("{0}: {1}", r.Key, r.Count())); + } + IEnumerable idCliente = + from x in estipulanteClientes + where x.IdCliente == item + select x; + str12 = string.Join(" | ", + from x in idCliente + select x.NomeEstipulante); + ClientesAtivosInativos clientesAtivosInativo = new ClientesAtivosInativos(); + Gestor.Model.Domain.Seguros.Cliente cliente = new Gestor.Model.Domain.Seguros.Cliente() + { + Id = item, + Nome = str5, + NomeSocialRg = str6, + MalaDireta = new bool?(flag1), + Telefones = new ObservableCollection(clienteTelefones2) + }; + clientesAtivosInativo.EntidadeCliente = cliente; + clientesAtivosInativo.Id = item; + clientesAtivosInativo.Nome = str5; + clientesAtivosInativo.Nascimento = nullable4; + clientesAtivosInativo.Aniversario = str11; + clientesAtivosInativo.Idade = nullable5; + clientesAtivosInativo.Documento = sqlDataReader["cgccpf"].ToString(); + if (sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("venchabili"))) + { + nullable = null; + nullable2 = nullable; + } + else + { + nullable2 = new DateTime?((DateTime)sqlDataReader["venchabili"]); + } + clientesAtivosInativo.VencimentoCnh = nullable2; + clientesAtivosInativo.Vendedor = str8; + clientesAtivosInativo.Ramo = str9; + List clienteTelefones3 = clienteTelefones2; + clientesAtivosInativo.Telefone = string.Join(" | ", + from f in clienteTelefones3 + select string.Concat(f.Prefixo, " ", f.Numero)); + IEnumerable clienteEmails2 = clienteEmails1; + clientesAtivosInativo.Email = string.Join(" | ", + from e in clienteEmails2 + select e.Email); + clientesAtivosInativo.Ativo = str10; + if (sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("idprofissao"))) + { + nome = ""; + } + else + { + List profissoes = Auxiliar.Profissoes; + Func func1 = func; + if (func1 == null) + { + Func func2 = (Profissao p) => p.Id == (long)this.rd["idprofissao"]; + Func func3 = func2; + func = func2; + func1 = func3; + } + Profissao profissao = profissoes.FirstOrDefault(func1); + if (profissao != null) + { + nome = profissao.Nome; + } + else + { + nome = null; + } + } + clientesAtivosInativo.Profissao = nome; + clientesAtivosInativo.Cep = clienteEndereco1.Cep; + clientesAtivosInativo.Endereco = clienteEndereco1.Endereco; + clientesAtivosInativo.Numero = clienteEndereco1.Numero; + clientesAtivosInativo.Complemento = clienteEndereco1.Complemento; + clientesAtivosInativo.Cidade = clienteEndereco1.Cidade; + clientesAtivosInativo.Estado = clienteEndereco1.Estado; + clientesAtivosInativo.Bairro = clienteEndereco1.Bairro; + clientesAtivosInativo.PastaCliente = sqlDataReader["pasta"].ToString(); + clientesAtivosInativo.RecebeEmail = (flag1 ? "SIM" : "NÃO"); + if (sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("cgccpf"))) + { + str2 = "FÍSICA"; + } + else + { + str2 = (regex.Replace(sqlDataReader["cgccpf"].ToString(), string.Empty).Length > 11 ? "JURÍDICA" : "FÍSICA"); + } + clientesAtivosInativo.TipoPessoa = str2; + clientesAtivosInativo.EstadoCivil = description; + str3 = (string.IsNullOrWhiteSpace(str7) ? "" : sexo.GetDescription()); + clientesAtivosInativo.Sexo = str3; + num = (sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("rendamensal")) ? decimal.Zero : (decimal)sqlDataReader["rendamensal"]); + clientesAtivosInativo.RendaMensal = num; + if (sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("clidesde"))) + { + nullable = null; + nullable3 = nullable; + } + else + { + nullable3 = new DateTime?((DateTime)sqlDataReader["clidesde"]); + } + clientesAtivosInativo.ClienteDesde = nullable3; + clientesAtivosInativo.Estipulantes = str12; + clientesAtivosInativo.Parentesco = sqlDataReader["Parentesco"].ToString(); + clientesAtivosInativos1.Add(clientesAtivosInativo); + } + } + } + sqlCommand = null; + } + else + { + clientesAtivosInativos = null; + variable = null; + clientesAtivosInativos1 = null; + documentos = null; + clienteEnderecos = null; + clienteTelefones = null; + clienteEmails = null; + values = null; + regex = null; + estipulanteClientes = null; + return clientesAtivosInativos; + } + } + sqlConnection = null; + clientesAtivosInativos = clientesAtivosInativos1; + variable = null; + clientesAtivosInativos1 = null; + documentos = null; + clienteEnderecos = null; + clienteTelefones = null; + clienteEmails = null; + values = null; + regex = null; + estipulanteClientes = null; + return clientesAtivosInativos; + } + + public DateTime? BuscaNascimeto(long id) + { + DateTime? nullable; + DateTime dateTime; + object connection; + string str; + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + if (sqlConnection != null) + { + List condicaos = new List() + { + new Condicao() + { + Campo = "idcliente", + Valores = id.CriarValor() + } + }; + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandTimeout = 15000; + object obj = sqlCommand.Select(condicaos.CreateParameters(0), "SELECT c.dtnasc FROM cliente c WHERE", "").AsEnumerable().ToList().FirstOrDefault().Field("dtnasc"); + if (obj != null) + { + str = obj.ToString(); + } + else + { + str = null; + } + if (!DateTime.TryParse(str, out dateTime)) + { + return null; + } + else + { + nullable = new DateTime?(dateTime); + } + } + } + else + { + nullable = null; + nullable = nullable; + } + } + return nullable; + } + + public async Task> BuscaProspeccoes(Filtros filtro, long idEmpresa) + { + int? nullable; + int num; + object connection; + int? nullable1; + List prospectars = new List(); + filtro.IdEmpresa = idEmpresa; + num = (filtro.FiltrarDocumento == "AMBOS" ? -1 : (int)(!(filtro.FiltrarDocumento == "CNPJ"))); + int num1 = num; + List condicaos = new List(); + Condicao condicao = new Condicao() + { + Campo = "d.excluido", + Valores = null, + Grupo = 1, + Operacao = Operacao.Or + }; + condicaos.Add(condicao); + Condicao condicao1 = new Condicao() + { + Campo = "d.excluido", + Valores = "0".CriarValor(), + Grupo = 1, + Operacao = Operacao.Or + }; + condicaos.Add(condicao1); + Condicao condicao2 = new Condicao() + { + Campo = "d.situacao" + }; + List objs = new List() + { + 1, + 2, + 4 + }; + condicao2.Valores = objs; + condicaos.Add(condicao2); + List condicaos1 = condicaos; + if (filtro.IdEmpresa > (long)0) + { + Condicao condicao3 = new Condicao() + { + Campo = "cl.idempresa", + Valores = filtro.IdEmpresa.CriarValor() + }; + condicaos1.Add(condicao3); + } + string str = ""; + if (filtro.Vendedores != null && filtro.Vendedores.Count > 0) + { + str = "INNER JOIN vendedorparcela vp ON vp.iddocumento = d.iddocumento"; + Condicao condicao4 = new Condicao() + { + Campo = "vp.idvendedor", + Valores = filtro.Vendedores.CriarValor() + }; + condicaos1.Add(condicao4); + } + string str1 = string.Concat("SELECT cl.idcliente,cl.nome,cl.cgccpf,c.idramo FROM cliente cl INNER JOIN controle c ON c.idcliente = cl.idcliente INNER JOIN documento d ON d.idcontrole = c.idcontrole ", str, " WHERE"); + string referencia = filtro.Referencia; + if (referencia == "VIGÊNCIA INICIAL") + { + Condicao condicao5 = new Condicao() + { + Campo = "CAST(d.vigencia1 AS DATE)", + Valores = filtro.Inicio.CriarValor(), + Operador = Operador.MaiorEIgual + }; + condicaos1.Add(condicao5); + Condicao condicao6 = new Condicao() + { + Campo = "CAST(d.vigencia1 AS DATE)", + Valores = filtro.Fim.CriarValor(), + Operador = Operador.MenorEIgual + }; + condicaos1.Add(condicao6); + } + else if (referencia == "VIGÊNCIA FINAL") + { + Condicao condicao7 = new Condicao() + { + Campo = "d.vigencia2", + Valores = null, + Operador = Operador.Diferente + }; + condicaos1.Add(condicao7); + Condicao condicao8 = new Condicao() + { + Campo = "CAST(d.vigencia2 AS DATE)", + Valores = filtro.Inicio.CriarValor(), + Operador = Operador.MaiorEIgual + }; + condicaos1.Add(condicao8); + Condicao condicao9 = new Condicao() + { + Campo = "CAST(d.vigencia2 AS DATE)", + Valores = filtro.Fim.CriarValor(), + Operador = Operador.MenorEIgual + }; + condicaos1.Add(condicao9); + } + else + { + Condicao condicao10 = new Condicao() + { + Campo = "CAST(p.vencto AS DATE)", + Valores = filtro.Inicio.CriarValor(), + Operador = Operador.MaiorEIgual + }; + condicaos1.Add(condicao10); + Condicao condicao11 = new Condicao() + { + Campo = "CAST(p.vencto AS DATE)", + Valores = filtro.Fim.CriarValor(), + Operador = Operador.MenorEIgual + }; + condicaos1.Add(condicao11); + str1 = string.Concat("SELECT cl.idcliente,cl.nome,cl.cgccpf,c.idramo FROM cliente cl INNER JOIN controle c ON c.idcliente = cl.idcliente INNER JOIN documento d ON d.idcontrole = c.idcontrole INNER JOIN parcela p ON p.iddocumento = d.iddocumento ", str, " WHERE CAST(d.n_parc AS INTEGER) = CAST(p.parcela AS INTEGER) AND"); + } + SqlQueryCondition sqlQueryCondition = condicaos1.CreateParameters(0); + using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) + { + SessionFactoryImpl sessionFactoryImpl = sessionFactory; + if (sessionFactoryImpl != null) + { + connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandTimeout = 1000; + sqlCommand.CommandText = string.Concat(str1, " ", sqlQueryCondition.Condicao); + sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray()); + List nums = new List(); + using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) + { + while (true) + { + if (!await sqlDataReader.ReadAsync()) + { + break; + } + string str2 = sqlDataReader["cgccpf"].ToString(); + long item = (long)sqlDataReader["idcliente"]; + long item1 = (long)sqlDataReader["idramo"]; + if (filtro.Ramos.Any((long r) => r == item1)) + { + nums.Add(item); + Prospectar prospectar = prospectars.FirstOrDefault((Prospectar p) => p.Id == item); + if (prospectar != null) + { + prospectars.Remove(prospectar); + } + } + else if (!nums.Any((long i) => i == item) && !prospectars.Any((Prospectar c) => c.Id == item)) + { + if (num1 > -1) + { + string str3 = str2; + if (str3 != null) + { + string str4 = str3.Clear(); + if (str4 != null) + { + nullable1 = new int?(str4.Length); + } + else + { + nullable = null; + nullable1 = nullable; + } + } + else + { + nullable = null; + nullable1 = nullable; + } + int? nullable2 = nullable1; + if (num1 == 0) + { + nullable = nullable2; + if (nullable.GetValueOrDefault() < 12 & nullable.HasValue) + { + continue; + } + } + if (num1 == 1) + { + nullable = nullable2; + if (nullable.GetValueOrDefault() > 11 & nullable.HasValue) + { + continue; + } + } + } + if (!await this.ExisteClienteRamo(item, filtro.Ramos.FirstOrDefault())) + { + string str5 = sqlDataReader["nome"].ToString(); + List clienteTelefones = await this.BuscaTelefonesCliente(item); + List prospectars1 = prospectars; + Prospectar prospectar1 = new Prospectar(); + Gestor.Model.Domain.Seguros.Cliente cliente = new Gestor.Model.Domain.Seguros.Cliente() + { + Id = item, + Nome = str5, + Telefones = new ObservableCollection(clienteTelefones) + }; + prospectar1.EntidadeCliente = cliente; + prospectar1.Id = item; + prospectar1.Nome = str5; + prospectar1.Documento = str2; + List clienteTelefones1 = clienteTelefones; + prospectar1.Telefone = string.Join(" | ", + from t in clienteTelefones1 + select string.Concat(t.Prefixo, " ", t.Numero)); + prospectars1.Add(prospectar1); + str2 = null; + str5 = null; + } + } + } + } + sqlDataReader = null; + nums = null; + } + sqlCommand = null; + } + sqlConnection = null; + } + sessionFactory = null; + List prospectars2 = prospectars; + List list = ( + from p in prospectars2 + orderby p.Nome + select p).ToList(); + prospectars = null; + return list; + } + + public List BuscarAniversariantes(Filtros filtro, long idempresa = 0L) + { + List condicaos = new List() + { + new Condicao() + { + Campo = "idempresa", + Valores = idempresa.CriarValor() + } + }; + List condicaos1 = new List() + { + new Condicao() + { + Campo = "dtnasc", + Valores = null, + Operador = Operador.Diferente + }, + new Condicao() + { + Campo = "excluido", + Valores = null, + Grupo = 1, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "excluido", + Valores = "0".CriarValor(), + Grupo = 1, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "falecido", + Valores = null, + Grupo = 2, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "falecido", + Valores = "1".CriarValor(), + Operador = Operador.Diferente, + Grupo = 2, + Operacao = Operacao.Or + } + }; + if (idempresa > (long)0) + { + condicaos1.AddRange(condicaos); + } + string str = (filtro.Inicio.Month != 12 || filtro.Fim.Month != 1 ? string.Format("{0} FORMAT(dtnasc,'MMdd') BETWEEN {1:Mdd} AND {2:Mdd} AND", "SELECT idcliente as id, idempresa, nome, cgccpf as documento, cei, rne, documentoprincipal, anotacoes, dtnasc as nascimento, idprofissao, VENCHABILI as vencimento, sexo, RendaMensal, pasta, MalaDireta, clidesde, ESTADOCIVI FROM cliente WHERE ", filtro.Inicio, filtro.Fim) : string.Format("{0} 1 = (FLOOR(DATEDIFF(dd,DTNASC,'{1:yyyy-MM-dd}') / 365.25)) - (FLOOR(DATEDIFF(dd,DTNASC,'{2:yyyy-MM-dd}') / 365.25)) AND", "SELECT idcliente as id, idempresa, nome, cgccpf as documento, cei, rne, documentoprincipal, anotacoes, dtnasc as nascimento, idprofissao, VENCHABILI as vencimento, sexo, RendaMensal, pasta, MalaDireta, clidesde, ESTADOCIVI FROM cliente WHERE ", filtro.Fim, filtro.Inicio)); + return this.Select(condicaos1.CreateParameters(0), str, true); + } + + public List BuscarAniversariantesVinculo(Filtros filtro, List vinculo, long idempresa = 0L) + { + List condicaos = new List() + { + new Condicao() + { + Campo = "cl.idempresa", + Valores = idempresa.CriarValor() + } + }; + List condicaos1 = new List() + { + new Condicao() + { + Campo = "cl.dtnasc", + Valores = null, + Operador = Operador.Diferente + }, + new Condicao() + { + Campo = "cl.excluido", + Valores = null, + Grupo = 1, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "cl.excluido", + Valores = "0".CriarValor(), + Grupo = 1, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "cl.falecido", + Valores = null, + Grupo = 2, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "cl.falecido", + Valores = "1".CriarValor(), + Operador = Operador.Diferente, + Grupo = 2, + Operacao = Operacao.Or + } + }; + if (idempresa > (long)0) + { + condicaos1.AddRange(condicaos); + } + string[] array = ( + from id in ( + from v in vinculo + select v.Id).ToList() + select id.ToString()).ToArray(); + string str = string.Join(",", array); + string str1 = (filtro.Inicio.Month != 12 || filtro.Fim.Month != 1 ? string.Format("{0} vu.idvendedorusuario in ({1}) AND FORMAT(cl.dtnasc,'MMdd') BETWEEN {2:Mdd} AND {3:Mdd} AND", new object[] { "SELECT DISTINCT cl.idcliente as id, cl.idempresa, cl.nome, cl.cgccpf as documento, cl.cei, cl.rne, cl.documentoprincipal, cl.anotacoes, cl.dtnasc as nascimento, cl.idprofissao,cl.VENCHABILI as vencimento, cl.sexo, cl.RendaMensal, cl.pasta, cl.MalaDireta, cl.clidesde, cl.ESTADOCIVI FROM cliente cl inner join controle co on co.idcliente = cl.idcliente inner join documento d on d.idcontrole = co.idcontrole inner join vendedorparcela vp on vp.iddocumento = d.iddocumento inner join vendedorusuario vu on vu.idvendedor = vp.idvendedor WHERE ", str, filtro.Inicio, filtro.Fim }) : string.Format("{0} 1 = (FLOOR(DATEDIFF(dd,cl.DTNASC,'{1:yyyy-MM-dd}') / 365.25)) - (FLOOR(DATEDIFF(dd,cl.DTNASC,'{2:yyyy-MM-dd}') / 365.25)) AND", "SELECT DISTINCT cl.idcliente as id, cl.idempresa, cl.nome, cl.cgccpf as documento, cl.cei, cl.rne, cl.documentoprincipal, cl.anotacoes, cl.dtnasc as nascimento, cl.idprofissao,cl.VENCHABILI as vencimento, cl.sexo, cl.RendaMensal, cl.pasta, cl.MalaDireta, cl.clidesde, cl.ESTADOCIVI FROM cliente cl inner join controle co on co.idcliente = cl.idcliente inner join documento d on d.idcontrole = co.idcontrole inner join vendedorparcela vp on vp.iddocumento = d.iddocumento inner join vendedorusuario vu on vu.idvendedor = vp.idvendedor WHERE ", filtro.Fim, filtro.Inicio)); + return this.Select(condicaos1.CreateParameters(0), str1, true); + } + + public async Task> BuscarClassificacoes(long idEmpresa) + { + List classificacaos; + Func, bool> func; + object connection; + string str; + Func, bool> func1 = null; + Func, bool> func2 = null; + Func, bool> func3 = null; + List classificacaos1 = new List(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + if (sqlConnection != null) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = "WITH classificatorio ( CodigoCliente, NomeCliente, AtivoInativo, SomaPremioLiq, MediaComissao, Resultado ) AS (\r\nSELECT\r\n\tcl.idcliente AS CodigoCliente,\r\n\tcl.Nome AS NomeCliente,\r\n\t IIF(MAX(d.vigencia2) >= GETDATE(), 1, 0) AS AtivoInativo,\r\n\tSUM (d.pr_liq) AS SomaPremioLiq,\r\n\tSUM (d.com01) / (COUNT(d.com01)) AS MediaComissao,\r\n\tSUM ((d.pr_liq + (IIF(d.adinacomis = 1, d.pr_adic, 0))) * (d.com01 * 0.01)) AS Resultado\r\nFROM\r\n\tcliente cl\r\n\tLEFT JOIN controle c ON c.idcliente = cl.idcliente\r\n\tLEFT JOIN documento d ON d.idcontrole = c.idcontrole AND d.excluido != 1 \tAND d.SITUACAO not in (3,7) WHERE CL.EXCLUIDO != 1 \r\nGROUP BY\r\n\tcl.IdCliente,\r\n\tcl.nome \r\n\t) SELECT CodigoCliente,NomeCliente,\r\n\tAtivoInativo,\r\nCASE\r\n\tWHEN SomaPremioLiq >= iif(quali.liquido3 is null, 500, quali.liquido3) THEN\r\n\t3\r\n\tWHEN SomaPremioLiq >= iif(quali.liquido2 is null, 500, quali.liquido2) THEN\r\n\t2 \r\n\tWHEN SomaPremioLiq >= iif(quali.liquido1 is null, 500, quali.liquido1) THEN\r\n\t1 \r\n\tELSE 0 \r\nEND QualiPremioLiquido,\r\nCASE\r\n\tWHEN MediaComissao >= iif(quali.comissao3 is null, 20, quali.comissao3) THEN\r\n\t3\r\n\tWHEN MediaComissao >= iif(quali.comissao2 is null, 15, quali.comissao2) THEN\r\n\t2 \r\n\tWHEN MediaComissao >= iif(quali.comissao1 is null, 10, quali.comissao1) THEN\r\n\t1 \r\n\tELSE 0 \r\nEND QualiComissao,\r\nCASE\r\n\tWHEN Resultado >= iif(quali.resultado3 is null, 300, quali.resultado3) THEN\r\n\t3\r\n\tWHEN Resultado >= iif(quali.resultado2 is null, 200, quali.resultado2) THEN\r\n\t2 \r\n\tWHEN Resultado >= iif(quali.resultado1 is null, 100, quali.resultado1) THEN\r\n\t1 \r\n\tELSE 0 \r\nEND QualiResultado\r\nFROM\r\nclassificatorio OUTER APPLY (SELECT top 1 * FROM qualificacao) AS quali;"; + sqlCommand.CommandTimeout = 1000; + List> tuples = new List>() + { + new Tuple("0", "SEM CLASSIFICAÇÃO"), + new Tuple("1", "BRONZE"), + new Tuple("2", "PRATA"), + new Tuple("3", "OURO") + }; + List> tuples1 = tuples; + using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) + { + while (true) + { + if (!await sqlDataReader.ReadAsync()) + { + break; + } + List> tuples2 = tuples1; + Func, bool> func4 = func1; + if (func4 == null) + { + Func, bool> func5 = (Tuple x) => x.Item1.Equals(sqlDataReader["QualiPremioLiquido"].ToString() ?? "0"); + func = func5; + func1 = func5; + func4 = func; + } + Tuple tuple = tuples2.FirstOrDefault>(func4); + List> tuples3 = tuples1; + Func, bool> func6 = func2; + if (func6 == null) + { + Func, bool> func7 = (Tuple x) => x.Item1.Equals(sqlDataReader["QualiResultado"].ToString() ?? "0"); + func = func7; + func2 = func7; + func6 = func; + } + Tuple tuple1 = tuples3.FirstOrDefault>(func6); + List> tuples4 = tuples1; + Func, bool> func8 = func3; + if (func8 == null) + { + Func, bool> func9 = (Tuple x) => x.Item1.Equals(sqlDataReader["QualiComissao"].ToString() ?? "0"); + func = func9; + func3 = func9; + func8 = func; + } + Tuple tuple2 = tuples4.FirstOrDefault>(func8); + string item2 = tuples1.FirstOrDefault>((Tuple x) => x.Item1.Equals(((int)Math.Round((double.Parse(tuple.Item1) + double.Parse(tuple1.Item1) + double.Parse(tuple2.Item1)) / 3)).ToString())).Item2; + str = (sqlDataReader["AtivoInativo"].ToString().Equals("1") ? "SIM" : "NÃO"); + string str1 = str; + List classificacaos2 = classificacaos1; + Classificacao classificacao = new Classificacao(); + Gestor.Model.Domain.Seguros.Cliente cliente = new Gestor.Model.Domain.Seguros.Cliente() + { + Id = long.Parse(sqlDataReader["codigocliente"].ToString()) + }; + classificacao.EntidadeCliente = cliente; + classificacao.Nome = sqlDataReader["NomeCliente"].ToString(); + classificacao.Premioliquido = tuple.Item2; + classificacao.Resultado = tuple1.Item2; + classificacao.Comissao = tuple2.Item2; + classificacao.Geral = item2; + classificacao.Ativo = str1; + classificacaos2.Add(classificacao); + } + } + tuples1 = null; + } + sqlCommand = null; + } + else + { + classificacaos = null; + classificacaos1 = null; + return classificacaos; + } + } + sqlConnection = null; + classificacaos = classificacaos1; + classificacaos1 = null; + return classificacaos; + } + + public string BuscarLogAntigo(long id, string conn) + { + object connection; + string str = ""; + List condicaos = new List() + { + new Condicao() + { + Campo = "id", + Valores = id.CriarValor() + }, + new Condicao() + { + Campo = "idname", + Valores = "idcliente".CriarValor() + } + }; + this._unitOfWork.CriarAuxiliar(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + string str1 = "oldbacklog"; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = "SELECT TOP 1 * FROM controlelog"; + SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); + sqlDataReader.Read(); + string str2 = sqlDataReader["bdname"].ToString(); + str1 = sqlDataReader["tabela"].ToString(); + sqlDataReader.Close(); + if (sqlConnection.Database != str2) + { + conn = conn.Replace(sqlConnection.Database, str2); + } + } + } + DataTable dataTable = new DataTable(); + using (SqlConnection sqlConnection1 = new SqlConnection(conn)) + { + sqlConnection1.Open(); + using (SqlCommand sqlCommand1 = sqlConnection1.CreateCommand()) + { + sqlCommand1.CommandTimeout = 15000; + dataTable = sqlCommand1.Select(condicaos.CreateParameters(0), string.Concat("SELECT b.* FROM ", str1, " b WHERE"), ""); + } + } + if (dataTable == null || dataTable.Rows.Count == 0) + { + return ""; + } + if (dataTable != null) + { + dataTable.AsEnumerable().OrderBy((DataRow x) => x.Field("idbacklog")).ToList().ForEach((DataRow x) => { + str = string.Concat(new string[] { str, "
(", x.Field("data").ToString(), ") ", Auxiliar.Usuarios.Find((Usuario u) => u.Id == x.Field("idusuario")).Nome, "
" }); + str = string.Concat(str, "", x.Field("historico").ToString().Replace(Environment.NewLine, "
"), ""); + }); + } + return str; + } + + public List BuscarOrigem(long id) + { + List list = ( + from x in this._unitOfWork.Query() + where x.Cliente.Id == id + select x).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public List BuscarVencimentoCnh(Filtros filtro, long idempresa = 0L) + { + List condicaos = new List() + { + new Condicao() + { + Campo = "idempresa", + Valores = idempresa.CriarValor() + } + }; + List condicaos1 = new List() + { + new Condicao() + { + Campo = "venchabili", + Valores = null, + Operador = Operador.Diferente + }, + new Condicao() + { + Campo = "venchabili", + Valores = filtro.Inicio.CriarValor(), + Operador = Operador.MaiorEIgual + }, + new Condicao() + { + Campo = "venchabili", + Valores = filtro.Fim.CriarValor(), + Operador = Operador.MenorEIgual + }, + new Condicao() + { + Campo = "excluido", + Valores = null, + Grupo = 1, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "excluido", + Valores = "0".CriarValor(), + Grupo = 1, + Operacao = Operacao.Or + } + }; + if (idempresa > (long)0) + { + condicaos1.AddRange(condicaos); + } + return this.Select(condicaos1.CreateParameters(0), "SELECT idcliente as id, idempresa, nome, cgccpf as documento, cei, rne, documentoprincipal, anotacoes, dtnasc as nascimento, idprofissao, VENCHABILI as vencimento, sexo, RendaMensal, pasta, MalaDireta, clidesde, ESTADOCIVI FROM cliente WHERE ", true); + } + + private async Task> BuscaTelefonesCliente(long idCliente) + { + object connection; + List clienteTelefones = new List(); + using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) + { + SessionFactoryImpl sessionFactoryImpl = sessionFactory; + if (sessionFactoryImpl != null) + { + connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandTimeout = 1000; + sqlCommand.CommandText = "SELECT ddd,fone FROM clitelefone WHERE idcliente = @cliente"; + sqlCommand.Parameters.Add("@cliente", SqlDbType.BigInt).Value = idCliente; + using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) + { + while (true) + { + if (!await sqlDataReader.ReadAsync()) + { + break; + } + List clienteTelefones1 = clienteTelefones; + Gestor.Model.Domain.Seguros.ClienteTelefone clienteTelefone = new Gestor.Model.Domain.Seguros.ClienteTelefone() + { + Prefixo = sqlDataReader["ddd"].ToString(), + Numero = sqlDataReader["fone"].ToString() + }; + clienteTelefones1.Add(clienteTelefone); + } + } + sqlDataReader = null; + } + sqlCommand = null; + } + sqlConnection = null; + } + sessionFactory = null; + List clienteTelefones2 = clienteTelefones; + clienteTelefones = null; + return clienteTelefones2; + } + + private int CalculaIdade(DateTime nascimento) + { + int year = DateTime.Now.Year - nascimento.Year; + if (DateTime.Now.DayOfYear < nascimento.DayOfYear) + { + year--; + } + return year; + } + + private List CriarFiltro(string filter) + { + return new List() + { + new Condicao() + { + Campo = "UPPER(NOME) COLLATE Latin1_General_CI_AI", + Valores = filter.CriarValor(), + Operacao = Operacao.Or, + Operador = Operador.Like, + Grupo = 2 + }, + new Condicao() + { + Campo = "UPPER(CGCCPF)", + Valores = filter.CriarValor(), + Operacao = Operacao.Or, + Operador = Operador.Like, + Grupo = 2 + }, + new Condicao() + { + Campo = "UPPER(CEI)", + Valores = filter.CriarValor(), + Operacao = Operacao.Or, + Operador = Operador.Like, + Grupo = 2 + }, + new Condicao() + { + Campo = "UPPER(RNE)", + Valores = filter.CriarValor(), + Operacao = Operacao.Or, + Operador = Operador.Like, + Grupo = 2 + }, + new Condicao() + { + Campo = "UPPER(CAEPF)", + Valores = filter.CriarValor(), + Operacao = Operacao.Or, + Operador = Operador.Like, + Grupo = 2 + }, + new Condicao() + { + Campo = "UPPER(nomesocialRg) COLLATE Latin1_General_CI_AI", + Valores = filter.CriarValor(), + Operacao = Operacao.Or, + Operador = Operador.Like, + Grupo = 2 + } + }; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public void DeleteOrigem(long id) + { + OrigemClienteDb origemClienteDb = this._unitOfWork.Repository().FindEntityById(id); + if (origemClienteDb == null) + { + return; + } + this._unitOfWork.Repository().Delete(origemClienteDb); + } + + private async Task> DocumentosPeriodo(bool completo) + { + IEnumerable documentos; + object connection; + Func func = null; + List documentos1 = new List(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + if (sqlConnection != null) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + if (!completo) + { + sqlCommand.CommandText = "SELECT DISTINCT d.iddocumento,d.idcontrole,c.idcliente FROM documento d INNER JOIN controle c ON c.idcontrole = d.idcontrole WHERE c.idcliente IS NOT NULL AND (d.excluido IS NULL OR d.excluido = 0) AND (d.vigencia2 IS NULL OR d.vigencia2 > @vigenciafinal) AND d.situacao IN (1,2,4) ORDER BY d.iddocumento"; + } + else + { + sqlCommand.CommandText = "SELECT DISTINCT d.iddocumento,d.idcontrole,c.idcliente,c.idramo,r.nome nomeramo,vp.idvendedor,v.nome nomevendedor, d.ordem FROM documento d INNER JOIN controle c ON c.idcontrole = d.idcontrole INNER JOIN ramo r ON r.idramo = c.idramo LEFT JOIN vendedorparcela vp ON d.iddocumento = vp.iddocumento LEFT JOIN vendedor v ON vp.idvendedor = v.idvendedor WHERE c.idcliente IS NOT NULL AND (d.excluido IS NULL OR d.excluido = 0) AND (d.vigencia2 IS NULL OR d.vigencia2 > @vigenciafinal) AND d.situacao IN (1,2,4) ORDER BY d.iddocumento"; + } + SqlParameter sqlParameter = sqlCommand.Parameters.Add("@vigenciafinal", SqlDbType.DateTime); + sqlParameter.Value = DateTime.Now.AddDays(-5); + sqlCommand.CommandTimeout = 1000; + using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) + { + long id = (long)0; + while (true) + { + if (!await sqlDataReader.ReadAsync()) + { + break; + } + Gestor.Model.Relatorios.Documento documento = new Gestor.Model.Relatorios.Documento(); + bool flag = true; + if (id == (long)sqlDataReader["iddocumento"]) + { + documento = documentos1.Last(); + flag = false; + } + if (!flag) + { + bool flag1 = completo; + if (flag1) + { + flag1 = !await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idvendedor")); + } + if (flag1) + { + IList vendedores = documento.Vendedores; + Func func1 = func; + if (func1 == null) + { + Func id1 = (Gestor.Model.Relatorios.Vendedor v) => v.Id == (long)sqlDataReader["idvendedor"]; + Func func2 = id1; + func = id1; + func1 = func2; + } + if (vendedores.Where(func1).Count() == 0) + { + IList vendedors = documento.Vendedores; + Gestor.Model.Relatorios.Vendedor vendedor = new Gestor.Model.Relatorios.Vendedor() + { + Id = (long)sqlDataReader["idvendedor"], + Nome = sqlDataReader["nomevendedor"].ToString() + }; + vendedors.Add(vendedor); + } + } + } + else + { + documento.Id = (long)sqlDataReader["iddocumento"]; + Gestor.Model.Relatorios.Documento documento1 = documento; + Gestor.Model.Relatorios.Controle controle = new Gestor.Model.Relatorios.Controle() + { + Id = (long)sqlDataReader["idcontrole"] + }; + Gestor.Model.Relatorios.Cliente cliente = new Gestor.Model.Relatorios.Cliente() + { + Id = (long)sqlDataReader["idcliente"] + }; + controle.Cliente = cliente; + documento1.Controle = controle; + if (completo) + { + documento.Ordem = (int?)sqlDataReader["ordem"]; + Gestor.Model.Relatorios.Controle controle1 = documento.Controle; + Gestor.Model.Relatorios.Ramo ramo = new Gestor.Model.Relatorios.Ramo() + { + Id = (long)sqlDataReader["idramo"], + Nome = sqlDataReader["nomeramo"].ToString() + }; + controle1.Ramo = ramo; + if (!await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idvendedor"))) + { + Gestor.Model.Relatorios.Documento documento2 = documento; + List vendedors1 = new List(); + Gestor.Model.Relatorios.Vendedor vendedor1 = new Gestor.Model.Relatorios.Vendedor() + { + Id = (long)sqlDataReader["idvendedor"], + Nome = sqlDataReader["nomevendedor"].ToString() + }; + vendedors1.Add(vendedor1); + documento2.Vendedores = vendedors1; + } + } + } + id = documento.Id; + if (flag) + { + documentos1.Add(documento); + } + documento = null; + } + } + } + sqlCommand = null; + } + else + { + documentos = null; + documentos1 = null; + return documentos; + } + } + sqlConnection = null; + documentos = documentos1; + documentos1 = null; + return documentos; + } + + private async Task> EmailsClientes() + { + IEnumerable clienteEmails; + object connection; + List clienteEmails1 = new List(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + if (sqlConnection != null) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = "SELECT idcliente,email FROM climail ORDER BY idcliente,ordem"; + sqlCommand.CommandTimeout = 1000; + using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) + { + while (true) + { + if (!await sqlDataReader.ReadAsync()) + { + break; + } + List clienteEmails2 = clienteEmails1; + Gestor.Model.Relatorios.ClienteEmail clienteEmail = new Gestor.Model.Relatorios.ClienteEmail(); + Gestor.Model.Relatorios.Cliente cliente = new Gestor.Model.Relatorios.Cliente() + { + Id = (long)sqlDataReader["idcliente"] + }; + clienteEmail.Cliente = cliente; + clienteEmail.Email = sqlDataReader["email"].ToString(); + clienteEmails2.Add(clienteEmail); + } + } + sqlDataReader = null; + } + sqlCommand = null; + } + else + { + clienteEmails = null; + clienteEmails1 = null; + return clienteEmails; + } + } + sqlConnection = null; + clienteEmails = clienteEmails1; + clienteEmails1 = null; + return clienteEmails; + } + + private async Task> EnderecoClientes() + { + IEnumerable clienteEnderecos; + object connection; + int num; + List clienteEnderecos1 = new List(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + if (sqlConnection != null) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = "SELECT DISTINCT idcliend, idcliente,ordem,endereco,numero,comp_end,cidade,uf,cep,bairro FROM cliendereco ORDER BY idcliente, ordem, idcliend"; + sqlCommand.CommandTimeout = 1000; + using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) + { + while (true) + { + if (!await sqlDataReader.ReadAsync()) + { + break; + } + List clienteEnderecos2 = clienteEnderecos1; + Gestor.Model.Relatorios.ClienteEndereco clienteEndereco = new Gestor.Model.Relatorios.ClienteEndereco() + { + IdCliEnd = (long)sqlDataReader["idcliend"] + }; + Gestor.Model.Relatorios.Cliente cliente = new Gestor.Model.Relatorios.Cliente() + { + Id = (long)sqlDataReader["idcliente"] + }; + clienteEndereco.Cliente = cliente; + clienteEndereco.Endereco = sqlDataReader["endereco"].ToString(); + clienteEndereco.Numero = sqlDataReader["numero"].ToString(); + clienteEndereco.Complemento = sqlDataReader["comp_end"].ToString(); + clienteEndereco.Cidade = sqlDataReader["cidade"].ToString(); + clienteEndereco.Estado = sqlDataReader["uf"].ToString(); + clienteEndereco.Cep = sqlDataReader["cep"].ToString(); + clienteEndereco.Bairro = sqlDataReader["bairro"].ToString(); + num = (sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("ordem")) ? 0 : (int)sqlDataReader["ordem"]); + clienteEndereco.Ordem = num; + clienteEnderecos2.Add(clienteEndereco); + } + } + sqlDataReader = null; + } + sqlCommand = null; + } + else + { + clienteEnderecos = null; + clienteEnderecos1 = null; + return clienteEnderecos; + } + } + sqlConnection = null; + clienteEnderecos = clienteEnderecos1; + clienteEnderecos1 = null; + return clienteEnderecos; + } + + private async Task> EstipulanteCliente() + { + IEnumerable estipulanteClientes; + object connection; + List estipulanteClientes1 = new List(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + if (sqlConnection != null) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = "SELECT DISTINCT c.idcliente, e.idestipulante, e.nome FROM documento d INNER JOIN estipulante e on e.idestipulante = d.idestipulante INNER JOIN controle c on c.idcontrole = d.idcontrole WHERE d.idestipulante IS NOT NULL AND (d.vigencia2 > GETDATE() OR d.vigencia2 IS NULL)"; + sqlCommand.CommandTimeout = 1000; + using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) + { + while (true) + { + if (!await sqlDataReader.ReadAsync()) + { + break; + } + List estipulanteClientes2 = estipulanteClientes1; + EstipulanteCliente estipulanteCliente = new EstipulanteCliente() + { + IdEstiputante = (long)sqlDataReader["idestipulante"], + IdCliente = (long)sqlDataReader["idcliente"], + NomeEstipulante = sqlDataReader["nome"].ToString() + }; + estipulanteClientes2.Add(estipulanteCliente); + } + } + sqlDataReader = null; + } + sqlCommand = null; + } + else + { + estipulanteClientes = null; + estipulanteClientes1 = null; + return estipulanteClientes; + } + } + sqlConnection = null; + estipulanteClientes = estipulanteClientes1; + estipulanteClientes1 = null; + return estipulanteClientes; + } + + private async Task ExisteClienteRamo(long idCliente, long idRamo) + { + bool flag; + object connection; + using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) + { + SessionFactoryImpl sessionFactoryImpl = sessionFactory; + if (sessionFactoryImpl != null) + { + connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = "SELECT COUNT(c.idcontrole) contador FROM controle c INNER JOIN documento d ON d.idcontrole = c.idcontrole WHERE d.situacao IN (1,2,4) AND (d.vigencia2 > DATEADD(day, -5, GETDATE()) OR d.vigencia2 IS NULL) AND c.idcliente = @cliente AND c.idramo = @ramo"; + sqlCommand.Parameters.Add("@cliente", SqlDbType.BigInt).Value = idCliente; + sqlCommand.Parameters.Add("@ramo", SqlDbType.BigInt).Value = idRamo; + flag = (int)await sqlCommand.ExecuteScalarAsync() > 0; + } + } + } + return flag; + } + + public List Find(string filter, long idempresa = 0L, bool acessoAgger = false, bool assintatura = false) + { + List clientes; + object connection; + DataTable dataTable = new DataTable(); + List nums = new List(); + DataTable dataTable1 = new DataTable(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + if (sqlConnection != null) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + List condicaos = new List() + { + new Condicao() + { + Campo = "excluido", + Valores = null, + Grupo = 1, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "excluido", + Valores = "0".CriarValor(), + Grupo = 1, + Operacao = Operacao.Or + } + }; + List condicaos1 = this.CriarFiltro(filter); + List condicaos2 = new List() + { + new Condicao() + { + Campo = "idempresa", + Valores = idempresa.CriarValor() + } + }; + if (!acessoAgger) + { + condicaos1.AddRange(condicaos); + } + if (idempresa > (long)0) + { + condicaos1.AddRange(condicaos2); + } + dataTable = sqlCommand.Select(condicaos1.CreateParameters(0), "SELECT TOP 200 IDEMPRESA, IDCLIENTE, NOME COLLATE Latin1_General_CI_AI AS NOME, CGCCPF, CEI, RNE, ISNULL(DOCUMENTOPRINCIPAL, 0) AS DOCUMENTOPRINCIPAL, CAEPF, EXCLUIDO, MalaDireta, nomesocialRg COLLATE Latin1_General_CI_AI as nomesocialRg FROM cliente WHERE", ""); + if (dataTable.Rows.Count > 0) + { + List condicaos3 = new List() + { + new Condicao() + { + Campo = "c.idcliente", + Valores = dataTable.AsEnumerable().Select((DataRow x) => x.Field("IDCLIENTE")).ToList().CriarValor() + } + }; + List condicaos4 = new List() + { + new Condicao() + { + Campo = "d.excluido", + Valores = null, + Grupo = 1, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "d.excluido", + Valores = "0".CriarValor(), + Grupo = 1, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "d.tipo", + Valores = 0.CriarValor() + }, + new Condicao() + { + Campo = "d.vigencia2", + Valores = null, + Grupo = 2, + Operacao = Operacao.Or + } + }; + Condicao condicao = new Condicao() + { + Campo = "d.vigencia2" + }; + DateTime date = Funcoes.GetNetworkTime().Date; + condicao.Valores = date.AddDays(-5).CriarValor(); + condicao.Grupo = 2; + condicao.Operacao = Operacao.Or; + condicao.Operador = Operador.Maior; + condicaos4.Add(condicao); + condicaos4.Add(new Condicao() + { + Campo = "d.situacao", + Valores = new List() + { + 1, + 2, + 4 + } + }); + List condicaos5 = condicaos4; + condicaos5.AddRange(condicaos3); + DataTable dataTable2 = sqlCommand.Select(condicaos5.CreateParameters(0), "SELECT DISTINCT c.idcliente FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole WHERE", ""); + nums = dataTable2.AsEnumerable().Select((DataRow x) => x.Field("idcliente")).ToList(); + if (assintatura) + { + dataTable1 = sqlCommand.Select(condicaos3.CreateParameters(0), "SELECT * FROM ResponsavelAssinatura c WHERE ", ""); + } + } + goto Label0; + } + } + else + { + clientes = new List(); + } + } + return clientes; + List list = dataTable1.AsEnumerable().Select((DataRow x) => new ResponsavelAssinatura() + { + Id = x.Field("Id"), + IdCliente = x.Field("IdCliente"), + NomeResponsavel = x.Field("NomeResponsavel").RemoverAcentos(), + DocumentoResponsavel = x.Field("DocumentoResponsavel"), + EmailResponsavel = x.Field("EmailResponsavel") + }).ToList(); + return ( + from x in dataTable.AsEnumerable().ToList() + select new Gestor.Model.Domain.Seguros.Cliente() + { + Id = x.Field("IDCLIENTE"), + IdEmpresa = x.Field("IDEMPRESA"), + Nome = x.Field("NOME").RemoverAcentos(), + Documento = x.Field("CGCCPF"), + Cei = x.Field("CEI"), + Rne = x.Field("RNE"), + Caepf = x.Field("CAEPF"), + DocumentoPrincipal = new TipoDocumento?((TipoDocumento)Enum.Parse(typeof(TipoDocumento), x.Field("DOCUMENTOPRINCIPAL").ToString())), + Status = (nums.Any((long d) => d == x.Field("IDCLIENTE")) ? "ATIVO" : "INATIVO"), + ResponsavelAssinatura = list.Find((ResponsavelAssinatura r) => r.IdCliente == x.Field("IDCLIENTE")), + Excluido = (x.Field("EXCLUIDO") == null ? false : x.Field("EXCLUIDO").ToString() == "1"), + MalaDireta = new bool?(x.Field("MalaDireta").GetValueOrDefault(true)), + NomeSocialRg = x.Field("nomesocialRg") + }).ToList(); + } + + public List FindAllClientes(bool completo, long idempresa = 0L) + { + List condicaos = new List() + { + new Condicao() + { + Campo = "idempresa", + Valores = idempresa.CriarValor() + } + }; + List condicaos1 = new List() + { + new Condicao() + { + Campo = "excluido", + Valores = null, + Grupo = 1, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "excluido", + Valores = "0".CriarValor(), + Grupo = 1, + Operacao = Operacao.Or + } + }; + if (idempresa > (long)0) + { + condicaos1.AddRange(condicaos); + } + return this.Select(condicaos1.CreateParameters(0), "SELECT idcliente as id, idempresa, nome, cgccpf as documento, cei, rne, documentoprincipal, anotacoes, dtnasc as nascimento, idprofissao, VENCHABILI as vencimento, sexo, RendaMensal, pasta, MalaDireta, clidesde, ESTADOCIVI FROM cliente WHERE ", completo); + } + + public Gestor.Model.Domain.Seguros.Cliente FindById(long id) + { + ClienteDb clienteDb = base.FindEntityById(id); + ResponsavelAssinaturaDb responsavelAssinaturaDb = this._unitOfWork.Query().FirstOrDefault((ResponsavelAssinaturaDb x) => x.IdCliente == id); + ResponsavelAssinatura responsavelAssinatura = ApplicationMapper.Mapper.Map(responsavelAssinaturaDb); + Gestor.Model.Domain.Seguros.Cliente cliente = ApplicationMapper.Mapper.Map(clienteDb); + cliente.ResponsavelAssinatura = responsavelAssinatura; + return cliente; + } + + public List FindByName(string filter, long idEmpresa = 0L, bool acessoAgger = false, bool assintatura = false, bool somenteNome = false) + { + return this.Find(filter, idEmpresa, acessoAgger, assintatura); + } + + public List FindByNameOld(string filter, long idempresa = 0L, bool acessoAgger = false, bool assintatura = false, bool somenteNome = false) + { + List clientes; + object connection; + DataTable dataTable = new DataTable(); + List nums = new List(); + DataTable dataTable1 = new DataTable(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + if (sqlConnection != null) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + List condicaos = new List() + { + new Condicao() + { + Campo = "excluido", + Valores = null, + Grupo = 1, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "excluido", + Valores = "0".CriarValor(), + Grupo = 1, + Operacao = Operacao.Or + } + }; + List condicaos1 = new List() + { + new Condicao() + { + Campo = "UPPER(NOME) COLLATE Latin1_General_CI_AI", + Valores = filter.CriarValor(), + Operador = (somenteNome ? Operador.ComecaCom : Operador.Like) + } + }; + List condicaos2 = new List() + { + new Condicao() + { + Campo = "idempresa", + Valores = idempresa.CriarValor() + } + }; + if (!acessoAgger) + { + condicaos1.AddRange(condicaos); + } + if (idempresa > (long)0) + { + condicaos1.AddRange(condicaos2); + } + dataTable = sqlCommand.Select(condicaos1.CreateParameters(0), "SELECT TOP 200 IDEMPRESA, IDCLIENTE, NOME COLLATE Latin1_General_CI_AI AS NOME, CGCCPF, CEI, RNE, ISNULL(DOCUMENTOPRINCIPAL, 0) AS DOCUMENTOPRINCIPAL, CAEPF, EXCLUIDO, MalaDireta, nomesocialRg COLLATE Latin1_General_CI_AI as nomesocialRg FROM cliente WHERE", ""); + if (dataTable.Rows.Count > 0) + { + List condicaos3 = new List() + { + new Condicao() + { + Campo = "c.idcliente", + Valores = dataTable.AsEnumerable().Select((DataRow x) => x.Field("IDCLIENTE")).ToList().CriarValor() + } + }; + List condicaos4 = new List() + { + new Condicao() + { + Campo = "d.excluido", + Valores = null, + Grupo = 1, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "d.excluido", + Valores = "0".CriarValor(), + Grupo = 1, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "d.tipo", + Valores = 0.CriarValor() + }, + new Condicao() + { + Campo = "d.vigencia2", + Valores = null, + Grupo = 2, + Operacao = Operacao.Or + } + }; + Condicao condicao = new Condicao() + { + Campo = "d.vigencia2" + }; + DateTime date = Funcoes.GetNetworkTime().Date; + condicao.Valores = date.AddDays(-5).CriarValor(); + condicao.Grupo = 2; + condicao.Operacao = Operacao.Or; + condicao.Operador = Operador.Maior; + condicaos4.Add(condicao); + condicaos4.Add(new Condicao() + { + Campo = "d.situacao", + Valores = new List() + { + 1, + 2, + 4 + } + }); + List condicaos5 = condicaos4; + condicaos5.AddRange(condicaos3); + DataTable dataTable2 = sqlCommand.Select(condicaos5.CreateParameters(0), "SELECT DISTINCT c.idcliente FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole WHERE", ""); + nums = dataTable2.AsEnumerable().Select((DataRow x) => x.Field("idcliente")).ToList(); + if (assintatura) + { + dataTable1 = sqlCommand.Select(condicaos3.CreateParameters(0), "SELECT * FROM ResponsavelAssinatura c WHERE ", ""); + } + } + goto Label0; + } + } + else + { + clientes = new List(); + } + } + return clientes; + List list = dataTable1.AsEnumerable().Select((DataRow x) => new ResponsavelAssinatura() + { + Id = x.Field("Id"), + IdCliente = x.Field("IdCliente"), + NomeResponsavel = x.Field("NomeResponsavel").RemoverAcentos(), + DocumentoResponsavel = x.Field("DocumentoResponsavel"), + EmailResponsavel = x.Field("EmailResponsavel") + }).ToList(); + return ( + from x in dataTable.AsEnumerable().ToList() + select new Gestor.Model.Domain.Seguros.Cliente() + { + Id = x.Field("IDCLIENTE"), + IdEmpresa = x.Field("IDEMPRESA"), + Nome = x.Field("NOME").RemoverAcentos(), + Documento = x.Field("CGCCPF"), + Cei = x.Field("CEI"), + Rne = x.Field("RNE"), + Caepf = x.Field("CAEPF"), + DocumentoPrincipal = new TipoDocumento?((TipoDocumento)Enum.Parse(typeof(TipoDocumento), x.Field("DOCUMENTOPRINCIPAL").ToString())), + Status = (nums.Any((long d) => d == x.Field("IDCLIENTE")) ? "ATIVO" : "INATIVO"), + ResponsavelAssinatura = list.Find((ResponsavelAssinatura r) => r.IdCliente == x.Field("IDCLIENTE")), + Excluido = (x.Field("EXCLUIDO") == null ? false : x.Field("EXCLUIDO").ToString() == "1"), + MalaDireta = new bool?(x.Field("MalaDireta").GetValueOrDefault(true)), + NomeSocialRg = x.Field("nomesocialRg") ?? "" + }).ToList(); + } + + public List FindClienteDocumento(string documento) + { + List clientes; + object connection; + List clientes1 = new List(); + using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) + { + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + if (sqlConnection != null) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = "SELECT c.IDEMPRESA, c.IDCLIENTE, c.NOME COLLATE Latin1_General_CI_AI AS NOME FROM cliente c WHERE (UPPER(c.CGCCPF) = @documento OR UPPER(c.CEI) = @documento OR UPPER(c.RNE) = @documento OR UPPER(c.CAEPF) = @documento) AND c.EXCLUIDO = '0'"; + sqlCommand.Parameters.Add("@documento", SqlDbType.VarChar).Value = documento; + using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader()) + { + while (sqlDataReader.Read()) + { + clientes1.Add(new Gestor.Model.Domain.Seguros.Cliente() + { + Id = sqlDataReader.GetFieldValue("idcliente", true, true), + IdEmpresa = sqlDataReader.GetFieldValue("idempresa", true, true), + Nome = sqlDataReader.GetFieldValue("nome", true, true), + Documento = documento + }); + } + return clientes1; + } + } + } + else + { + clientes = clientes1; + } + } + } + return clientes; + } + + public List FindClienteVinculo(string filter, List vinculos, long idempresa = 0L, bool acessoAgger = false, bool assinatura = false, TipoFiltroCliente tipoFiltroCliente = 2) + { + List clientes; + object connection; + List clientes1 = new List(); + using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) + { + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + if (sqlConnection != null) + { + using (SqlCommand item = sqlConnection.CreateCommand()) + { + StringBuilder stringBuilder = new StringBuilder("SELECT TOP 25 c.IDEMPRESA, c.IDCLIENTE, c.NOME COLLATE Latin1_General_CI_AI AS NOME, c.NOMESOCIALRG COLLATE Latin1_General_CI_AI AS NOMESOCIAL, c.CGCCPF, c.CEI, c.RNE, ISNULL(c.DOCUMENTOPRINCIPAL, 0) AS DOCUMENTOPRINCIPAL, c.CAEPF, c.EXCLUIDO, c.MalaDireta, (CASE WHEN (SELECT COUNT(d.IDDOCUMENTO) FROM DOCUMENTO d INNER JOIN CONTROLE ctrl ON d.IDCONTROLE = ctrl.IDCONTROLE WHERE ctrl.IDCLIENTE = c.IDCLIENTE AND (d.EXCLUIDO IS NULL OR d.EXCLUIDO = '0') AND (d.VIGENCIA2 IS NULL OR d.VIGENCIA2 >= GETDATE() - 5) AND d.TIPO = 0 AND d.SITUACAO NOT IN(3,7)) > 0 THEN 0 ELSE 1 END) AS ATIVO FROM CLIENTE c WHERE "); + if (idempresa > (long)0) + { + stringBuilder.Append(" (c.IDEMPRESA = @empresa) AND "); + item.Parameters.Add("@empresa", SqlDbType.BigInt).Value = idempresa; + } + if (!acessoAgger) + { + stringBuilder.Append(" (c.excluido IS NULL OR c.excluido = @excluido) AND "); + item.Parameters.Add("@excluido", SqlDbType.VarChar, 1).Value = "0"; + } + stringBuilder.Append((tipoFiltroCliente != TipoFiltroCliente.NomeDocumentos ? " (UPPER(c.NOME) COLLATE Latin1_General_CI_AI LIKE @filtro OR UPPER(c.NOMESOCIALRG) COLLATE Latin1_General_CI_AI LIKE @filtro) " : " (UPPER(c.NOME) COLLATE Latin1_General_CI_AI LIKE @filtro OR UPPER(c.NOMESOCIALRG) COLLATE Latin1_General_CI_AI LIKE @filtro OR UPPER(c.CGCCPF) LIKE @filtro OR UPPER(c.CEI) LIKE @filtro OR UPPER(c.RNE) LIKE @filtro OR UPPER(c.CAEPF) LIKE @filtro) ")); + item.Parameters.Add("@filtro", SqlDbType.VarChar, 150).Value = string.Concat((tipoFiltroCliente == TipoFiltroCliente.Nome ? "" : "%"), filter, "%"); + if (vinculos != null && vinculos.Count > 0) + { + stringBuilder.Append("AND ((SELECT COUNT(vp.IDVENDEDOR) FROM vendedorparcela vp INNER JOIN DOCUMENTO d ON vp.IDDOCUMENTO = d.IDDOCUMENTO INNER JOIN CONTROLE ctrl ON d.IDCONTROLE = ctrl.IDCONTROLE WHERE ctrl.IDCLIENTE = c.IDCLIENTE AND (d.EXCLUIDO IS NULL OR d.EXCLUIDO = '0') AND vp.IDVENDEDOR IN ("); + StringBuilder stringBuilder1 = new StringBuilder(); + for (int i = 0; i < vinculos.Count; i++) + { + if (i > 0) + { + stringBuilder1.Append(","); + } + string str = string.Format("@p{0}", i); + stringBuilder1.Append(str); + item.Parameters.Add(str, SqlDbType.BigInt).Value = vinculos[i]; + } + stringBuilder1.Append(")"); + stringBuilder.Append(stringBuilder1); + stringBuilder.Append(") > 0 OR ((SELECT COUNT(vp.IDVENDEDOR) FROM vendedorparcela vp INNER JOIN DOCUMENTO d ON vp.IDDOCUMENTO = d.IDDOCUMENTO INNER JOIN CONTROLE ctrl ON d.IDCONTROLE = ctrl.IDCONTROLE WHERE ctrl.IDCLIENTE = c.IDCLIENTE AND (d.EXCLUIDO IS NULL OR d.EXCLUIDO = '0') AND vp.IDVENDEDOR IN ("); + stringBuilder.Append(stringBuilder1); + stringBuilder.Append(") = 0 AND (SELECT COUNT(d.IDDOCUMENTO) FROM DOCUMENTO d INNER JOIN CONTROLE ctrl ON d.IDCONTROLE = ctrl.IDCONTROLE WHERE ctrl.IDCLIENTE = c.IDCLIENTE AND (d.EXCLUIDO IS NULL OR d.EXCLUIDO = '0')) = 0))"); + } + item.CommandText = stringBuilder.ToString(); + using (SqlDataReader sqlDataReader = item.ExecuteReader()) + { + while (sqlDataReader.Read()) + { + clientes1.Add(new Gestor.Model.Domain.Seguros.Cliente() + { + Id = sqlDataReader.GetFieldValue("idcliente", true, true), + IdEmpresa = sqlDataReader.GetFieldValue("idempresa", true, true), + Nome = sqlDataReader.GetFieldValue("nome", true, true), + Documento = sqlDataReader.GetFieldValue("cgccpf", true, true), + Cei = sqlDataReader.GetFieldValue("cei", true, true), + Rne = sqlDataReader.GetFieldValue("rne", true, true), + Caepf = sqlDataReader.GetFieldValue("caepf", true, true), + DocumentoPrincipal = new TipoDocumento?(sqlDataReader.GetFieldValue("documentoprincipal", true, true)), + Status = (sqlDataReader.GetFieldValue("ativo", true, true) == 0 ? "ATIVO" : "INATIVO"), + Excluido = sqlDataReader.GetFieldValue("excluido", true, true) == 1, + NomeSocialRg = sqlDataReader.GetFieldValue("nomesocial", true, true) + }); + } + return clientes1; + } + } + } + else + { + clientes = clientes1; + } + } + } + return clientes; + } + + public List FindObsCliente(string obsCliente, long idempresa = 0L) + { + List condicaos = new List() + { + new Condicao() + { + Campo = "idempresa", + Valores = idempresa.CriarValor() + } + }; + List condicaos1 = new List() + { + new Condicao() + { + Campo = "anotacoes", + Valores = obsCliente.CriarValor(), + Operador = Operador.Like + }, + new Condicao() + { + Campo = "excluido", + Valores = null, + Grupo = 1, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "excluido", + Valores = "0".CriarValor(), + Grupo = 1, + Operacao = Operacao.Or + } + }; + if (idempresa > (long)0) + { + condicaos1.AddRange(condicaos); + } + return this._unitOfWork.Select(condicaos1.CreateParameters(0), "SELECT idcliente as id, idempresa, nome, cgccpf as documento, cei, rne, documentoprincipal, anotacoes, dtnasc as nascimento, idprofissao, VENCHABILI as vencimento, sexo, RendaMensal, pasta, MalaDireta, clidesde, ESTADOCIVI FROM cliente WHERE ", "").MapCliente(); + } + + public List FindPastaCliente(string pastaCliente, bool busca = false, long idempresa = 0L) + { + List condicaos = new List() + { + new Condicao() + { + Campo = "idempresa", + Valores = idempresa.CriarValor() + } + }; + List condicaos1 = new List() + { + new Condicao() + { + Campo = "pasta", + Valores = pastaCliente.CriarValor(), + Operador = (busca ? Operador.Igual : Operador.Like) + }, + new Condicao() + { + Campo = "excluido", + Valores = null, + Grupo = 1, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "excluido", + Valores = "0".CriarValor(), + Grupo = 1, + Operacao = Operacao.Or + } + }; + if (idempresa > (long)0) + { + condicaos1.AddRange(condicaos); + } + return this._unitOfWork.Select(condicaos1.CreateParameters(0), "SELECT idcliente as id, idempresa, nome, cgccpf as documento, cei, rne, documentoprincipal, anotacoes, dtnasc as nascimento, idprofissao, VENCHABILI as vencimento, sexo, RendaMensal, pasta, MalaDireta, clidesde, ESTADOCIVI FROM cliente WHERE ", "").MapCliente(); + } + + public List FindVinculo(string filter, long id) + { + List condicaos = this.CriarFiltro(filter); + condicaos.AddRange(new List() + { + new Condicao() + { + Campo = "excluido", + Valores = null, + Grupo = 1, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "excluido", + Valores = "0".CriarValor(), + Grupo = 1, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "idcliente", + Valores = id.CriarValor(), + Operador = Operador.Diferente + } + }); + DataTable dataTable = this._unitOfWork.Select(condicaos.CreateParameters(0), "SELECT TOP 200 idcliente as id, idempresa, nome, cgccpf as documento, cei, rne, documentoprincipal, anotacoes, dtnasc as nascimento, idprofissao, VENCHABILI as vencimento, sexo, RendaMensal, pasta, MalaDireta FROM cliente WHERE", ""); + if (dataTable != null && dataTable.Rows.Count == 0) + { + return new List(); + } + return dataTable.MapCliente(); + } + + public Gestor.Model.Domain.Seguros.Cliente Merge(Gestor.Model.Domain.Seguros.Cliente cliente) + { + ResponsavelAssinatura responsavelAssinatura; + ClienteDb clienteDb = ApplicationMapper.Mapper.Map(cliente); + if (cliente.ResponsavelAssinatura == null || string.IsNullOrEmpty(cliente.ResponsavelAssinatura.NomeResponsavel)) + { + responsavelAssinatura = null; + } + else + { + responsavelAssinatura = cliente.ResponsavelAssinatura; + } + ResponsavelAssinatura responsavelAssinatura1 = responsavelAssinatura; + if (responsavelAssinatura1 != null) + { + ResponsavelAssinaturaDb responsavelAssinaturaDb = ApplicationMapper.Mapper.Map(responsavelAssinatura1); + if (responsavelAssinaturaDb.Id != 0) + { + this._unitOfWork.Repository().Merge(responsavelAssinaturaDb); + } + else + { + this._unitOfWork.Repository().SaveOrUpdate(responsavelAssinaturaDb); + } + responsavelAssinatura1 = ApplicationMapper.Mapper.Map(responsavelAssinaturaDb); + } + base.Merge(clienteDb); + Gestor.Model.Domain.Seguros.Cliente cliente1 = ApplicationMapper.Mapper.Map(clienteDb); + cliente1.ResponsavelAssinatura = responsavelAssinatura1; + return cliente1; + } + + public OrigemCliente Merge(OrigemCliente origem) + { + OrigemClienteDb origemClienteDb = ApplicationMapper.Mapper.Map(origem); + this._unitOfWork.Repository().Merge(origemClienteDb); + return ApplicationMapper.Mapper.Map(origemClienteDb); + } + + public Gestor.Model.Domain.Seguros.Cliente SaveOrUpdate(Gestor.Model.Domain.Seguros.Cliente cliente) + { + ResponsavelAssinatura responsavelAssinatura; + ClienteDb clienteDb = ApplicationMapper.Mapper.Map(cliente); + this.SaveOrUpdate(clienteDb); + if (cliente.ResponsavelAssinatura == null || string.IsNullOrEmpty(cliente.ResponsavelAssinatura.NomeResponsavel)) + { + responsavelAssinatura = null; + } + else + { + responsavelAssinatura = cliente.ResponsavelAssinatura; + } + ResponsavelAssinatura id = responsavelAssinatura; + if (id != null) + { + id.IdCliente = clienteDb.Id; + ResponsavelAssinaturaDb responsavelAssinaturaDb = ApplicationMapper.Mapper.Map(id); + this._unitOfWork.Repository().SaveOrUpdate(responsavelAssinaturaDb); + id = ApplicationMapper.Mapper.Map(responsavelAssinaturaDb); + } + Gestor.Model.Domain.Seguros.Cliente cliente1 = ApplicationMapper.Mapper.Map(clienteDb); + cliente1.ResponsavelAssinatura = id; + return cliente1; + } + + public OrigemCliente SaveOrUpdate(OrigemCliente origem) + { + OrigemClienteDb origemClienteDb = ApplicationMapper.Mapper.Map(origem); + this._unitOfWork.Repository().SaveOrUpdate(origemClienteDb); + return ApplicationMapper.Mapper.Map(origemClienteDb); + } + + private List Select(SqlQueryCondition condition, string command, bool completo) + { + List clientesAtivosInativos; + object connection; + List nums3 = null; + List nums4 = null; + DataTable dataTable1 = new DataTable(); + DataTable dataTable2 = new DataTable(); + DataTable dataTable3 = new DataTable(); + DataTable dataTable4 = new DataTable(); + DataTable dataTable5 = new DataTable(); + DataTable dataTable6 = new DataTable(); + DataTable dataTable7 = new DataTable(); + DataTable dataTable8 = new DataTable(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + if (sqlConnection != null) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandTimeout = 15000; + if (completo) + { + Auxiliar.CriarAuxiliar(sqlCommand, false); + } + dataTable1 = sqlCommand.Select(condition, command, ""); + if (dataTable1 == null || dataTable1.Rows.Count != 0) + { + for (List i = dataTable1.AsEnumerable().Select((DataRow x) => x.Field("id")).ToList(); i.Count > 0; i = nums3) + { + List nums5 = i.Take(2000).ToList(); + List condicaos = new List() + { + new Condicao() + { + Campo = "idcliente", + Valores = nums5.CriarValor() + } + }; + List condicaos1 = new List() + { + new Condicao() + { + Campo = "d.excluido", + Valores = null, + Grupo = 1, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "d.excluido", + Valores = "0".CriarValor(), + Grupo = 1, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "d.vigencia2", + Valores = null, + Grupo = 2, + Operacao = Operacao.Or + } + }; + Condicao condicao = new Condicao() + { + Campo = "d.vigencia2" + }; + DateTime date = Funcoes.GetNetworkTime().Date; + condicao.Valores = date.AddDays(-5).CriarValor(); + condicao.Grupo = 2; + condicao.Operacao = Operacao.Or; + condicao.Operador = Operador.Maior; + condicaos1.Add(condicao); + condicaos1.Add(new Condicao() + { + Campo = "d.situacao", + Valores = new List() + { + 1, + 2, + 4 + } + }); + List condicaos2 = condicaos1; + condicaos2.AddRange(condicaos); + DataTable dataTable9 = sqlCommand.Select(condicaos2.CreateParameters(0), "SELECT DISTINCT c.idcliente, r.idramo, r.nome AS ramo, d.iddocumento as id, d.idcontrole FROM documento d INNER JOIN controle c ON c.idcontrole = d.idcontrole INNER JOIN ramo r ON r.idramo = c.idramo WHERE", ""); + List nums6 = dataTable9.AsEnumerable().Select((DataRow x) => x.Field("id")).ToList(); + List nums7 = dataTable9.AsEnumerable().Select((DataRow x) => x.Field("id")).ToList(); + dataTable2.Merge(dataTable9); + List condicaos3 = new List() + { + new Condicao() + { + Campo = "ORDEM", + Valores = "1".CriarValor(), + Grupo = 1, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "PADRAO", + Valores = "1".CriarValor(), + Grupo = 1, + Operacao = Operacao.Or + } + }; + condicaos3.AddRange(condicaos); + dataTable9 = sqlCommand.Select(condicaos3.CreateParameters(0), "SELECT DISTINCT idcliend, cep, cidade, uf as estado, idcliente as id, endereco, numero, comp_end as complemento FROM cliendereco WHERE ", ""); + dataTable3.Merge(dataTable9); + dataTable9 = sqlCommand.Select(condicaos.CreateParameters(0), "SELECT DISTINCT idclitelefone, ddd, fone, idcliente as id FROM clitelefone WHERE ", ""); + dataTable5.Merge(dataTable9); + dataTable9 = sqlCommand.Select(condicaos.CreateParameters(0), "SELECT DISTINCT idclimail, email, idcliente as id FROM climail WHERE ", ""); + dataTable4.Merge(dataTable9); + if (completo) + { + for (List j = nums5; j.Count > 0; j = nums4) + { + List nums8 = j.Take(1000).ToList(); + List condicaos4 = new List() + { + new Condicao() + { + Campo = "idcliente1", + Valores = nums8.CriarValor(), + Grupo = 1, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "idcliente2", + Valores = nums8.CriarValor(), + Grupo = 1, + Operacao = Operacao.Or + } + }; + dataTable9 = sqlCommand.Select(condicaos4.CreateParameters(0), "SELECT * FROM clivinculo c WHERE", ""); + dataTable7.Merge(dataTable9); + nums4 = (nums8.Count < 1000 ? new List() : j.Except(nums8).ToList()); + } + while (nums6.Count > 0) + { + List nums9 = nums6.Take(2000).ToList(); + List condicaos5 = new List() + { + new Condicao() + { + Campo = "vp.iddocumento", + Valores = nums9.CriarValor() + } + }; + dataTable9 = sqlCommand.Select(condicaos5.CreateParameters(0), "SELECT DISTINCT vp.idvendedor, vp.iddocumento FROM vendedorparcela vp WHERE", ""); + dataTable6.Merge(dataTable9); + nums6 = (nums9.Count < 2000 ? new List() : nums6.Except(nums9).ToList()); + } + while (nums7.Count > 0) + { + List nums10 = nums7.Take(2000).ToList(); + List condicaos6 = new List() + { + new Condicao() + { + Campo = "iddocumento", + Valores = nums10.CriarValor() + } + }; + dataTable9 = sqlCommand.Select(condicaos6.CreateParameters(0), "select IDDOCUMENTO, case when(idestipulante is null ) then 0 else idestipulante end as idestipulante from documento where", ""); + dataTable8.Merge(dataTable9); + nums7 = (nums10.Count < 2000 ? new List() : nums6.Except(nums10).ToList()); + } + } + nums3 = (nums5.Count < 2000 ? new List() : i.Except(nums5).ToList()); + } + goto Label0; + } + else + { + clientesAtivosInativos = new List(); + } + } + } + else + { + clientesAtivosInativos = new List(); + } + } + return clientesAtivosInativos; + Label0: + Regex regex = new Regex("[^\\d]"); + DateTime networkTime = Funcoes.GetNetworkTime(); + Array values = Enum.GetValues(typeof(EstadoCivil)); + List clientesAtivosInativos1 = new List(); + dataTable1.AsEnumerable().ToList().ForEach((DataRow x) => { + DateTime? nullable; + DateTime dateTime; + List list; + List nums; + DateTime? nullable1; + string str; + DateTime? nullable2; + string nome; + int year; + int? nullable3; + DateTime? nullable4; + List dataRows = dataTable2.AsEnumerable().Where((DataRow y) => y.Field("idcliente") == x.Field("id")).ToList(); + List dataRows1 = dataRows; + Func u003cu003e9_325 = ClienteRepository.u003cu003ec.u003cu003e9__32_5; + if (u003cu003e9_325 == null) + { + u003cu003e9_325 = (DataRow d) => d.Field("id"); + ClienteRepository.u003cu003ec.u003cu003e9__32_5 = u003cu003e9_325; + } + List list1 = dataRows1.Select(u003cu003e9_325).ToList(); + DataRow dataRow = dataTable3.AsEnumerable().FirstOrDefault((DataRow t) => t.Field("id") == x.Field("id")); + EnumerableRowCollection dataRows2 = dataTable4.AsEnumerable().Where((DataRow t) => t.Field("id") == x.Field("id")); + Func u003cu003e9_328 = ClienteRepository.u003cu003ec.u003cu003e9__32_8; + if (u003cu003e9_328 == null) + { + u003cu003e9_328 = (DataRow t) => t.Field("email"); + ClienteRepository.u003cu003ec.u003cu003e9__32_8 = u003cu003e9_328; + } + EnumerableRowCollection strs = dataRows2.Select(u003cu003e9_328); + if (list1.Count > 0) + { + EnumerableRowCollection dataRows3 = dataTable6.AsEnumerable().Where((DataRow y) => list1.Contains(y.Field("iddocumento"))); + Func u003cu003e9_3210 = ClienteRepository.u003cu003ec.u003cu003e9__32_10; + if (u003cu003e9_3210 == null) + { + u003cu003e9_3210 = (DataRow y) => y.Field("idvendedor"); + ClienteRepository.u003cu003ec.u003cu003e9__32_10 = u003cu003e9_3210; + } + list = dataRows3.Select(u003cu003e9_3210).Distinct().ToList(); + } + else + { + list = null; + } + List nums1 = list; + EnumerableRowCollection dataRows4 = dataTable5.AsEnumerable().Where((DataRow t) => t.Field("id") == x.Field("id")); + Func u003cu003e9_3212 = ClienteRepository.u003cu003ec.u003cu003e9__32_12; + if (u003cu003e9_3212 == null) + { + u003cu003e9_3212 = (DataRow t) => new Gestor.Model.Domain.Seguros.ClienteTelefone() + { + Prefixo = t.Field("ddd"), + Numero = t.Field("fone") + }; + ClienteRepository.u003cu003ec.u003cu003e9__32_12 = u003cu003e9_3212; + } + List clienteTelefones = dataRows4.Select(u003cu003e9_3212).ToList(); + List clienteTelefones1 = clienteTelefones; + Func u003cu003e9_3213 = ClienteRepository.u003cu003ec.u003cu003e9__32_13; + if (u003cu003e9_3213 == null) + { + u003cu003e9_3213 = (Gestor.Model.Domain.Seguros.ClienteTelefone t) => string.Concat(t.Prefixo, " ", t.Numero); + ClienteRepository.u003cu003ec.u003cu003e9__32_13 = u003cu003e9_3213; + } + IEnumerable strs1 = clienteTelefones1.Select(u003cu003e9_3213); + List dataRows5 = dataRows; + Func u003cu003e9_3214 = ClienteRepository.u003cu003ec.u003cu003e9__32_14; + if (u003cu003e9_3214 == null) + { + u003cu003e9_3214 = (DataRow y) => y.Field("ramo"); + ClienteRepository.u003cu003ec.u003cu003e9__32_14 = u003cu003e9_3214; + } + IEnumerable strs2 = dataRows5.Select(u003cu003e9_3214); + Func u003cu003e9_3215 = ClienteRepository.u003cu003ec.u003cu003e9__32_15; + if (u003cu003e9_3215 == null) + { + u003cu003e9_3215 = (string r) => r; + ClienteRepository.u003cu003ec.u003cu003e9__32_15 = u003cu003e9_3215; + } + List list2 = strs2.OrderBy(u003cu003e9_3215).Distinct().ToList(); + DataRow dataRow1 = dataTable7.AsEnumerable().FirstOrDefault((DataRow v) => v.Field("idcliente1") == x.Field("id")) ?? dataTable7.AsEnumerable().FirstOrDefault((DataRow v) => v.Field("idcliente2") == x.Field("id")); + if (list1.Count > 0) + { + DataTable dataTable = dataTable8; + if (dataTable != null) + { + EnumerableRowCollection dataRows6 = dataTable.AsEnumerable().Where((DataRow y) => list1.Contains(y.Field("iddocumento"))); + Func u003cu003e9_3219 = ClienteRepository.u003cu003ec.u003cu003e9__32_19; + if (u003cu003e9_3219 == null) + { + u003cu003e9_3219 = (DataRow y) => y.Field("idestipulante"); + ClienteRepository.u003cu003ec.u003cu003e9__32_19 = u003cu003e9_3219; + } + nums = dataRows6.Select(u003cu003e9_3219).Distinct().ToList(); + } + else + { + nums = null; + } + } + else + { + nums = null; + } + List nums2 = nums; + List vendedors = (nums1 == null || nums1.Count <= 0 ? new List() : ( + from v in Auxiliar.Vendedores + where nums1.Contains(v.Id) + select v).ToList()); + List estipulantes = (nums2 == null || nums2.Count <= 0 ? new List() : ( + from e in Auxiliar.Estipulantes + where nums2.Contains(e.Id) + select e).ToList()); + string description = ""; + foreach (object obj in values) + { + if (obj.GetOldValue() != x.Field("EstadoCivi")) + { + continue; + } + description = ((EstadoCivil)obj).GetDescription(); + } + ClientesAtivosInativos clientesAtivosInativo = new ClientesAtivosInativos() + { + EntidadeCliente = new Gestor.Model.Domain.Seguros.Cliente() + { + Id = x.Field("id"), + Nome = x.Field("nome"), + Telefones = new ObservableCollection(clienteTelefones), + MalaDireta = new bool?(x.Field("MalaDireta").GetValueOrDefault(true)) + }, + Id = x.Field("id"), + Nome = x.Field("nome") + }; + if (x.Field("nascimento") == null) + { + nullable = null; + nullable1 = nullable; + } + else + { + nullable1 = new DateTime?(DateTime.Parse(x.Field("nascimento").ToString())); + } + clientesAtivosInativo.Nascimento = nullable1; + if (x.Field("nascimento") == null) + { + str = ""; + } + else + { + dateTime = x.Field("nascimento"); + str = dateTime.ToString("dd/MM"); + } + clientesAtivosInativo.Aniversario = str; + clientesAtivosInativo.Documento = x.Field("documento"); + if (x.Field("vencimento") == null) + { + nullable = null; + nullable2 = nullable; + } + else + { + nullable2 = x.Field("vencimento"); + } + clientesAtivosInativo.VencimentoCnh = nullable2; + clientesAtivosInativo.Ramo = string.Join(" | ", list2); + clientesAtivosInativo.Ativo = (list2.Any() ? "SIM" : "NÃO"); + if (x.Field("idprofissao") != null) + { + Profissao profissao = Auxiliar.Profissoes.FirstOrDefault((Profissao p) => p.Id == long.Parse(x.Field("idprofissao").ToString())); + if (profissao != null) + { + nome = profissao.Nome; + } + else + { + nome = null; + } + } + else + { + nome = ""; + } + clientesAtivosInativo.Profissao = nome; + clientesAtivosInativo.Telefone = string.Join(" | ", strs1); + clientesAtivosInativo.Cep = (dataRow != null ? dataRow.Field("cep") : null); + clientesAtivosInativo.Endereco = (dataRow != null ? dataRow.Field("endereco") : null); + clientesAtivosInativo.Numero = (dataRow != null ? dataRow.Field("numero") : null); + clientesAtivosInativo.Complemento = (dataRow != null ? dataRow.Field("complemento") : null); + clientesAtivosInativo.Cidade = (dataRow != null ? dataRow.Field("cidade") : null); + clientesAtivosInativo.PastaCliente = x.Field("pasta"); + clientesAtivosInativo.Estado = (dataRow != null ? dataRow.Field("estado") : null); + clientesAtivosInativo.Email = string.Join(" | ", strs); + clientesAtivosInativo.RecebeEmail = (x.Field("maladireta").GetValueOrDefault() ? "SIM" : "NÃO"); + List vendedors1 = vendedors; + Func u003cu003e9_3223 = ClienteRepository.u003cu003ec.u003cu003e9__32_23; + if (u003cu003e9_3223 == null) + { + u003cu003e9_3223 = (Gestor.Model.Domain.Seguros.Vendedor v) => v.Nome; + ClienteRepository.u003cu003ec.u003cu003e9__32_23 = u003cu003e9_3223; + } + clientesAtivosInativo.Vendedor = string.Join(" | ", vendedors1.Select(u003cu003e9_3223)); + clientesAtivosInativo.TipoPessoa = (string.IsNullOrEmpty(x.Field("documento")) ? "FÍSICA" : (regex.Replace(x.Field("documento"), "").Length > 11 ? "JURÍDICA" : "FÍSICA")); + clientesAtivosInativo.Sexo = (x.Field("sexo") == null || !(x.Field("sexo").ToString() != "") || string.IsNullOrWhiteSpace(x.Field("sexo").ToString()) ? "" : ((Sexo)Enum.Parse(typeof(Sexo), x.Field("sexo").ToString())).GetDescription()); + clientesAtivosInativo.RendaMensal = (x.Field("RendaMensal") == null ? decimal.Zero : x.Field("RendaMensal")); + clientesAtivosInativo.Parentesco = (dataRow1 == null ? "NÃO" : "SIM"); + if (x.Field("nascimento") != null) + { + DateTime dateTime1 = DateTime.Parse(x.Field("nascimento").ToString()); + int num = networkTime.Year; + dateTime = DateTime.Parse(x.Field("nascimento").ToString()); + if (dateTime1 > networkTime.AddYears(-(num - dateTime.Year))) + { + int year1 = networkTime.Year; + dateTime = DateTime.Parse(x.Field("nascimento").ToString()); + year = year1 - dateTime.Year - 1; + } + else + { + int num1 = networkTime.Year; + dateTime = DateTime.Parse(x.Field("nascimento").ToString()); + year = num1 - dateTime.Year; + } + nullable3 = new int?(year); + } + else + { + nullable3 = null; + } + clientesAtivosInativo.Idade = nullable3; + nullable = x.Field("clidesde"); + if (!nullable.HasValue) + { + nullable = null; + nullable4 = nullable; + } + else + { + nullable4 = x.Field("clidesde"); + } + clientesAtivosInativo.ClienteDesde = nullable4; + clientesAtivosInativo.EstadoCivil = description; + List estipulantes1 = estipulantes; + Func u003cu003e9_3224 = ClienteRepository.u003cu003ec.u003cu003e9__32_24; + if (u003cu003e9_3224 == null) + { + u003cu003e9_3224 = (Estipulante v) => v.Nome; + ClienteRepository.u003cu003ec.u003cu003e9__32_24 = u003cu003e9_3224; + } + clientesAtivosInativo.Estipulantes = string.Join(" | ", estipulantes1.Select(u003cu003e9_3224)); + clientesAtivosInativos1.Add(clientesAtivosInativo); + }); + return clientesAtivosInativos1; + } + + public List Sincronize(List origens, long id) + { + if (origens == null) + { + return null; + } + IEnumerable origemClienteDbs = ( + from x in this._unitOfWork.Query() + where x.Cliente.Id == id + select x).ToList().Where((OrigemClienteDb x) => { + List origemClientes = origens; + Func u003cu003e9_304 = ClienteRepository.u003cu003ec.u003cu003e9__30_4; + if (u003cu003e9_304 == null) + { + u003cu003e9_304 = (OrigemCliente i) => i.Id; + ClienteRepository.u003cu003ec.u003cu003e9__30_4 = u003cu003e9_304; + } + return !origemClientes.Select(u003cu003e9_304).Contains(x.Id); + }); + if (origemClienteDbs != null) + { + origemClienteDbs.ForEach((OrigemClienteDb x) => this._unitOfWork.Repository().Delete(x)); + } + else + { + } + origens.ForEach((OrigemCliente x) => x = (x.Id > (long)0 ? this.Merge(x) : this.SaveOrUpdate(x))); + return origens; + } + + private async Task> TelefonesClientes() + { + IEnumerable clienteTelefones; + object connection; + List clienteTelefones1 = new List(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + if (sqlConnection != null) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = "SELECT idcliente,ddd,fone FROM clitelefone ORDER BY idcliente,ordem"; + sqlCommand.CommandTimeout = 1000; + using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) + { + while (true) + { + if (!await sqlDataReader.ReadAsync()) + { + break; + } + List clienteTelefones2 = clienteTelefones1; + Gestor.Model.Relatorios.ClienteTelefone clienteTelefone = new Gestor.Model.Relatorios.ClienteTelefone(); + Gestor.Model.Relatorios.Cliente cliente = new Gestor.Model.Relatorios.Cliente() + { + Id = (long)sqlDataReader["idcliente"] + }; + clienteTelefone.Cliente = cliente; + clienteTelefone.Prefixo = sqlDataReader["ddd"].ToString(); + clienteTelefone.Numero = sqlDataReader["fone"].ToString(); + clienteTelefones2.Add(clienteTelefone); + } + } + sqlDataReader = null; + } + sqlCommand = null; + } + else + { + clienteTelefones = null; + clienteTelefones1 = null; + return clienteTelefones; + } + } + sqlConnection = null; + clienteTelefones = clienteTelefones1; + clienteTelefones1 = null; + return clienteTelefones; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteTelefoneRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteTelefoneRepository.cs new file mode 100644 index 0000000..1a5fb3c --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteTelefoneRepository.cs @@ -0,0 +1,220 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Helpers; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class ClienteTelefoneRepository : GenericRepository, IClienteTelefoneRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public ClienteTelefoneRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public List DeleteFone(long clienteId, List telefones) + { + if (telefones == null || telefones.Count == 0) + { + return null; + } + List list = ( + from cliente in base.All() + where cliente.Cliente.Id == clienteId + select cliente).ToList().Where((ClienteTelefoneDb fone) => { + List clienteTelefones = telefones; + Func u003cu003e9_103 = ClienteTelefoneRepository.u003cu003ec.u003cu003e9__10_3; + if (u003cu003e9_103 == null) + { + u003cu003e9_103 = (ClienteTelefone t) => t.Id; + ClienteTelefoneRepository.u003cu003ec.u003cu003e9__10_3 = u003cu003e9_103; + } + return !clienteTelefones.Select(u003cu003e9_103).Contains(fone.Id); + }).ToList(); + list.ForEach((ClienteTelefoneDb fonesExcluido) => base.Delete(fonesExcluido)); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public List Find(string telefone, long idempresa = 0L) + { + List condicaos = new List() + { + new Condicao() + { + Campo = "REPLACE(ISNULL(ct.fone, ''), '-','')", + Valores = telefone.Clear().CriarValor(), + Operador = Operador.Like + } + }; + if (idempresa > (long)0) + { + condicaos.Add(new Condicao() + { + Campo = "c.idempresa", + Valores = idempresa.CriarValor() + }); + } + return this.Select(condicaos.CreateParameters(0)); + } + + private List FindByCliente(long id) + { + return this.Select((new List() + { + new Condicao() + { + Campo = "ct.idcliente", + Valores = id.CriarValor() + } + }).CreateParameters(0)); + } + + public List FindByClienteId(long id) + { + return this.FindByCliente(id); + } + + public ClienteTelefone FindById(long id) + { + ClienteTelefoneDb clienteTelefoneDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(clienteTelefoneDb); + } + + public List Inserir(List telefones) + { + List clienteTelefoneDbs = ApplicationMapper.Mapper.Map, List>(telefones); + clienteTelefoneDbs.ForEach((ClienteTelefoneDb x) => { + string str; + ClienteTelefoneDb clienteTelefoneDb = x; + string observacao = x.Observacao; + if (observacao != null) + { + str = observacao.Trim(); + } + else + { + str = null; + } + clienteTelefoneDb.Observacao = str; + if (x.Id == 0) + { + this.SaveOrUpdate(x); + return; + } + base.Merge(x); + }); + return ApplicationMapper.Mapper.Map, List>(clienteTelefoneDbs); + } + + public List Inserir(List telefones, Cliente cliente) + { + telefones.ForEach((ClienteTelefone x) => { + string str; + x.Cliente = cliente; + ClienteTelefone clienteTelefone = x; + string observacao = x.Observacao; + if (observacao != null) + { + str = observacao.Trim(); + } + else + { + str = null; + } + clienteTelefone.Observacao = str; + }); + List clienteTelefoneDbs = ApplicationMapper.Mapper.Map, List>(telefones); + base.AddRange(clienteTelefoneDbs); + return ApplicationMapper.Mapper.Map, List>(clienteTelefoneDbs); + } + + public ClienteTelefone Merge(ClienteTelefone telefone) + { + ClienteTelefoneDb clienteTelefoneDb = ApplicationMapper.Mapper.Map(telefone); + clienteTelefoneDb.Observacao = clienteTelefoneDb.Observacao.Trim(); + base.Merge(clienteTelefoneDb); + return ApplicationMapper.Mapper.Map(clienteTelefoneDb); + } + + public List Merge(List telefones, Cliente cliente) + { + List clienteTelefoneDbs = ApplicationMapper.Mapper.Map, List>(telefones); + clienteTelefoneDbs.ForEach((ClienteTelefoneDb x) => { + string str; + ClienteTelefoneDb clienteTelefoneDb = x; + string observacao = x.Observacao; + if (observacao != null) + { + str = observacao.Trim(); + } + else + { + str = null; + } + clienteTelefoneDb.Observacao = str; + if (x.Id != 0) + { + base.Merge(x); + return; + } + x.Cliente = ApplicationMapper.Mapper.Map(cliente); + this.SaveOrUpdate(x); + }); + return ApplicationMapper.Mapper.Map, List>(clienteTelefoneDbs); + } + + public ClienteTelefone SaveOrUpdate(ClienteTelefone telefone) + { + string str; + ClienteTelefoneDb clienteTelefoneDb = ApplicationMapper.Mapper.Map(telefone); + ClienteTelefoneDb clienteTelefoneDb1 = clienteTelefoneDb; + string observacao = clienteTelefoneDb.Observacao; + if (observacao != null) + { + str = observacao.Trim(); + } + else + { + str = null; + } + clienteTelefoneDb1.Observacao = str; + this.SaveOrUpdate(clienteTelefoneDb); + return ApplicationMapper.Mapper.Map(clienteTelefoneDb); + } + + private List Select(SqlQueryCondition condition) + { + List clienteTelefones = CustomMap.MapTelefone(this._unitOfWork.Select(condition, "SELECT ct.idclitelefone AS Id, ct.idcliente as IdCliente, ct.ddd AS Prefixo, ct.fone AS Numero, ISNULL(ct.tipo , 0) AS Tipo, ct.obs AS Observacao, ct.ordem AS Ordem, c.nome as NomeCliente FROM clitelefone ct INNER JOIN cliente c ON c.idcliente = ct.idcliente WHERE ", "")); + int? nullable1 = new int?(0); + clienteTelefones.ForEach((ClienteTelefone x) => { + int? ordem = nullable1; + int? nullable = ordem; + nullable1 = (nullable.HasValue ? new int?(nullable.GetValueOrDefault() + 1) : null); + ClienteTelefone clienteTelefone = x; + ordem = x.Ordem; + clienteTelefone.Ordem = (ordem.HasValue ? ordem : nullable1); + }); + return clienteTelefones; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteVinculoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteVinculoRepository.cs new file mode 100644 index 0000000..460e860 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteVinculoRepository.cs @@ -0,0 +1,112 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class ClienteVinculoRepository : GenericRepository, IClienteVinculoRepository, IGenericRepository + { + public ClienteVinculoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public List DeleteVinculo(long clienteId, List vinculos) + { + if (vinculos == null) + { + return null; + } + List list = ( + from x in base.All() + where x.Cliente1.Id == clienteId || x.Cliente2.Id == clienteId + select x).ToList().Where((ClienteVinculoDb vinculo) => { + List clienteVinculos = vinculos; + Func u003cu003e9_32 = ClienteVinculoRepository.u003cu003ec.u003cu003e9__3_2; + if (u003cu003e9_32 == null) + { + u003cu003e9_32 = (ClienteVinculo t) => t.Id; + ClienteVinculoRepository.u003cu003ec.u003cu003e9__3_2 = u003cu003e9_32; + } + return !clienteVinculos.Select(u003cu003e9_32).Contains(vinculo.Id); + }).ToList(); + ClienteVinculoRepository clienteVinculoRepository = this; + list.ForEach(new Action(clienteVinculoRepository.Delete)); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public List FindByCliente(long id) + { + List list = ( + from x in base.All() + where x.Cliente1.Id == id || x.Cliente2.Id == id + select x).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public ClienteVinculo FindById(long id) + { + ClienteVinculoDb clienteVinculoDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(clienteVinculoDb); + } + + public List Inserir(List vinculos, Cliente cliente) + { + foreach (ClienteVinculo vinculo in vinculos) + { + if (vinculo.Cliente1.Id == cliente.Id || vinculo.Cliente1.Id == 0) + { + vinculo.Cliente1 = cliente; + } + else + { + if (vinculo.Cliente2.Id != cliente.Id && vinculo.Cliente2.Id != 0) + { + continue; + } + vinculo.Cliente2 = cliente; + } + } + List clienteVinculoDbs = ApplicationMapper.Mapper.Map, List>(vinculos); + base.AddRange(clienteVinculoDbs); + return ApplicationMapper.Mapper.Map, List>(clienteVinculoDbs); + } + + public List Merge(List vinculos, Cliente cliente) + { + List clienteVinculoDbs = ApplicationMapper.Mapper.Map, List>(vinculos); + clienteVinculoDbs.ForEach((ClienteVinculoDb x) => { + if (x.Id != 0) + { + base.Merge(x); + return; + } + x.Cliente1 = ApplicationMapper.Mapper.Map(cliente); + this.SaveOrUpdate(x); + }); + return ApplicationMapper.Mapper.Map, List>(clienteVinculoDbs); + } + + public ClienteVinculo SaveOrUpdate(ClienteVinculo clienteVinculo) + { + ClienteVinculoDb clienteVinculoDb = ApplicationMapper.Mapper.Map(clienteVinculo); + this.SaveOrUpdate(clienteVinculoDb); + return ApplicationMapper.Mapper.Map(clienteVinculoDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaGranizoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaGranizoRepository.cs new file mode 100644 index 0000000..f4abfdf --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaGranizoRepository.cs @@ -0,0 +1,65 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class CoberturaGranizoRepository : GenericRepository, ICoberturaGranizoRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public CoberturaGranizoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + CoberturaGranizoDb coberturaGranizoDb = base.FindEntityById(id); + if (coberturaGranizoDb == null) + { + return; + } + base.Delete(coberturaGranizoDb); + } + + public List Find(long id) + { + List list = ( + from x in base.All() + where x.Granizo.Id == id + select x).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public CoberturaGranizo FindById(long id) + { + CoberturaGranizoDb coberturaGranizoDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(coberturaGranizoDb); + } + + public CoberturaGranizo Merge(CoberturaGranizo cobertura) + { + CoberturaGranizoDb coberturaGranizoDb = ApplicationMapper.Mapper.Map(cobertura); + base.Merge(coberturaGranizoDb); + return ApplicationMapper.Mapper.Map(coberturaGranizoDb); + } + + public CoberturaGranizo SaveOrUpdate(CoberturaGranizo cobertura) + { + CoberturaGranizoDb coberturaGranizoDb = ApplicationMapper.Mapper.Map(cobertura); + this.SaveOrUpdate(coberturaGranizoDb); + return ApplicationMapper.Mapper.Map(coberturaGranizoDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaPadraoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaPadraoRepository.cs new file mode 100644 index 0000000..e9f916d --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaPadraoRepository.cs @@ -0,0 +1,70 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class CoberturaPadraoRepository : GenericRepository, ICoberturaPadraoRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public CoberturaPadraoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + CoberturaPadraoDb coberturaPadraoDb = base.FindEntityById(id); + if (coberturaPadraoDb == null) + { + return; + } + base.Delete(coberturaPadraoDb); + } + + public List Find() + { + List list = base.All().ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public CoberturaPadrao FindById(long id) + { + CoberturaPadraoDb coberturaPadraoDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(coberturaPadraoDb); + } + + public List FindByRamoId(long id) + { + List list = ( + from x in base.All() + where x.IdRamo == id + select x).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public CoberturaPadrao Merge(CoberturaPadrao coberturaPadrao) + { + CoberturaPadraoDb coberturaPadraoDb = ApplicationMapper.Mapper.Map(coberturaPadrao); + base.Merge(coberturaPadraoDb); + return ApplicationMapper.Mapper.Map(coberturaPadraoDb); + } + + public CoberturaPadrao SaveOrUpdate(CoberturaPadrao coberturaPadrao) + { + CoberturaPadraoDb coberturaPadraoDb = ApplicationMapper.Mapper.Map(coberturaPadrao); + this.SaveOrUpdate(coberturaPadraoDb); + return ApplicationMapper.Mapper.Map(coberturaPadraoDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaRepository.cs new file mode 100644 index 0000000..f50d4ee --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaRepository.cs @@ -0,0 +1,174 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class CoberturaRepository : GenericRepository, ICoberturaRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public CoberturaRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public List AddRange(List coberturas) + { + List coberturaDbs = ApplicationMapper.Mapper.Map, List>(coberturas); + base.AddRange(coberturaDbs); + return ApplicationMapper.Mapper.Map, List>(coberturaDbs); + } + + public void Delete(long id) + { + CoberturaDb coberturaDb = base.FindEntityById(id); + if (coberturaDb == null) + { + return; + } + base.Delete(coberturaDb); + } + + public void DeletebyItem(long id) + { + object connection; + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = string.Format("DELETE FROM cobertura WHERE iditem = {0}", id); + sqlCommand.ExecuteNonQuery(); + } + } + } + + public void DeleteRange(List ids) + { + List list = ( + from x in base.All() + where ids.Contains(x.Item.Id) + select x).ToList(); + if (list.Count == 0) + { + return; + } + base.DeleteRange(list); + } + + public Cobertura FindById(long id) + { + CoberturaDb coberturaDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(coberturaDb); + } + + public List FindByItemId(long id) + { + object connection; + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + DataTable dataTable = new DataTable(); + DataTable dataTable1 = new DataTable(); + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = "SELECT * FROM coberturapadrao;"; + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + sqlCommand.CommandText = string.Format("SELECT * FROM cobertura WHERE iditem = {0}", id); + using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) + { + sqlDataAdapter1.SelectCommand = sqlCommand; + sqlDataAdapter1.Fill(dataTable1); + } + } + } + List list = ( + from x in dataTable.AsEnumerable().ToList() + select new CoberturaPadrao() + { + Id = x.Field("idcoberturapadrao"), + IdRamo = (x.Field("idramo") != null ? x.Field("idramo") : (long)0), + Descricao = x.Field("descricao") + }).ToList(); + return dataTable1.AsEnumerable().ToList().Select((DataRow x) => { + Cobertura cobertura = new Cobertura() + { + Id = x.Field("idcobertura"), + CoberturaPadrao = (x.Field("idcoberturapadrao") == null ? null : list.FirstOrDefault((CoberturaPadrao c) => c.Id == x.Field("idcoberturapadrao"))), + Item = new Item() + { + Id = x.Field("iditem") + } + }; + decimal? nullable = x.Field("franquia"); + cobertura.Franquia = nullable.GetValueOrDefault(); + nullable = x.Field("premio"); + cobertura.Premio = nullable.GetValueOrDefault(); + nullable = x.Field("lmi"); + cobertura.Lmi = nullable.GetValueOrDefault(); + cobertura.Observacao = x.Field("observacao"); + return cobertura; + }).ToList(); + } + + public Cobertura Merge(Cobertura cobertura) + { + CoberturaDb coberturaDb = ApplicationMapper.Mapper.Map(cobertura); + base.Merge(coberturaDb); + return ApplicationMapper.Mapper.Map(coberturaDb); + } + + public List MergeRange(List coberturas) + { + List coberturaDbs = ApplicationMapper.Mapper.Map, List>(coberturas); + CoberturaRepository coberturaRepository = this; + coberturaDbs.ForEach(new Action(coberturaRepository.Merge)); + return ApplicationMapper.Mapper.Map, List>(coberturaDbs); + } + + public Cobertura SaveOrUpdate(Cobertura cobertura) + { + CoberturaDb coberturaDb = ApplicationMapper.Mapper.Map(cobertura); + this.SaveOrUpdate(coberturaDb); + return ApplicationMapper.Mapper.Map(coberturaDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CondicaoRepasseRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CondicaoRepasseRepository.cs new file mode 100644 index 0000000..d06bfaf --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CondicaoRepasseRepository.cs @@ -0,0 +1,46 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Seguros; +using System; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class CondicaoRepasseRepository : GenericRepository, ICondicaoRepasseRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public CondicaoRepasseRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public CondicaoRepasse FindById(long id) + { + CondicaoRepasseDb condicaoRepasseDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(condicaoRepasseDb); + } + + public CondicaoRepasse Merge(CondicaoRepasse condicaoRepasse) + { + CondicaoRepasseDb condicaoRepasseDb = ApplicationMapper.Mapper.Map(condicaoRepasse); + base.Merge(condicaoRepasseDb); + return ApplicationMapper.Mapper.Map(condicaoRepasseDb); + } + + public CondicaoRepasse SaveOrUpdate(CondicaoRepasse condicaoRepasse) + { + CondicaoRepasseDb condicaoRepasseDb = ApplicationMapper.Mapper.Map(condicaoRepasse); + this.SaveOrUpdate(condicaoRepasseDb); + return ApplicationMapper.Mapper.Map(condicaoRepasseDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConfigExtratoImportRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConfigExtratoImportRepository.cs new file mode 100644 index 0000000..2410399 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConfigExtratoImportRepository.cs @@ -0,0 +1,101 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class ConfigExtratoImportRepository : GenericRepository, IConfigExtratoImportRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public ConfigExtratoImportRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public List Find(bool ativo) + { + return ( + from x in this._unitOfWork.Session.CreateQuery("from ConfigExtratoImportDb \r\n where ativo IS NULL OR ativo != '1'").List() + select new ConfigExtratoImport() + { + Id = x.Id, + IdSeguradora = x.IdSeguradora, + Codigo = x.Codigo, + Descricao = x.Descricao, + Ativo = x.Ativo + }).ToList(); + } + + public List Find() + { + return ( + from x in this._unitOfWork.Session.CreateQuery("from ConfigExtratoImportDb").List() + select new ConfigExtratoImport() + { + Id = x.Id, + IdSeguradora = x.IdSeguradora, + Codigo = x.Codigo, + Descricao = x.Descricao, + Ativo = x.Ativo + }).ToList(); + } + + public ConfigExtratoImport FindById(long id) + { + ConfigExtratoImportDb configExtratoImportDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(configExtratoImportDb); + } + + public List FindBySeguradora(long id) + { + return ( + from x in this._unitOfWork.Session.CreateQuery(string.Format("from ConfigExtratoImportDb where IdSeguradora = {0}", id)).List() + select new ConfigExtratoImport() + { + Id = x.Id, + IdSeguradora = x.IdSeguradora, + Codigo = x.Codigo, + Descricao = x.Descricao, + Ativo = x.Ativo + }).ToList(); + } + + public Gestor.Model.Domain.Seguros.ConfigExtratoImport Merge(Gestor.Model.Domain.Seguros.ConfigExtratoImport ConfigExtratoImport) + { + ConfigExtratoImportDb configExtratoImportDb = ApplicationMapper.Mapper.Map(ConfigExtratoImport); + base.Merge(configExtratoImportDb); + return ApplicationMapper.Mapper.Map(configExtratoImportDb); + } + + public List MergeRange(List configExtratoImport) + { + List configExtratoImportDbs = ApplicationMapper.Mapper.Map, List>(configExtratoImport); + ConfigExtratoImportRepository configExtratoImportRepository = this; + configExtratoImportDbs.ForEach(new Action(configExtratoImportRepository.Merge)); + return ApplicationMapper.Mapper.Map, List>(configExtratoImportDbs); + } + + public Gestor.Model.Domain.Seguros.ConfigExtratoImport SaveOrUpdate(Gestor.Model.Domain.Seguros.ConfigExtratoImport ConfigExtratoImport) + { + ConfigExtratoImportDb configExtratoImportDb = ApplicationMapper.Mapper.Map(ConfigExtratoImport); + this.SaveOrUpdate(configExtratoImportDb); + return ApplicationMapper.Mapper.Map(configExtratoImportDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConfiguracaoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConfiguracaoRepository.cs new file mode 100644 index 0000000..5d6f539 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConfiguracaoRepository.cs @@ -0,0 +1,61 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Configuracoes; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Configuracoes; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class ConfiguracaoRepository : GenericRepository, IConfiguracaoRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public ConfiguracaoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public List BuscarConfiguracoes() + { + return ApplicationMapper.Mapper.Map, List>(base.All().ToList()); + } + + public void Delete(long id) + { + ConfiguracaoSistemaDb configuracaoSistemaDb = base.FindEntityById(id); + if (configuracaoSistemaDb == null) + { + return; + } + base.Delete(configuracaoSistemaDb); + } + + public ConfiguracaoSistema Find(Configuracao configuracao) + { + ConfiguracaoSistemaDb configuracaoSistemaDb = base.All().FirstOrDefault((ConfiguracaoSistemaDb x) => (int)x.Configuracao == (int)configuracao); + return ApplicationMapper.Mapper.Map(configuracaoSistemaDb); + } + + public ConfiguracaoSistema Merge(ConfiguracaoSistema configuracao) + { + ConfiguracaoSistemaDb configuracaoSistemaDb = ApplicationMapper.Mapper.Map(configuracao); + base.Merge(configuracaoSistemaDb); + return ApplicationMapper.Mapper.Map(configuracaoSistemaDb); + } + + public ConfiguracaoSistema SaveOrUpdate(ConfiguracaoSistema configuracao) + { + ConfiguracaoSistemaDb configuracaoSistemaDb = ApplicationMapper.Mapper.Map(configuracao); + this.SaveOrUpdate(configuracaoSistemaDb); + return ApplicationMapper.Mapper.Map(configuracaoSistemaDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConsorcioRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConsorcioRepository.cs new file mode 100644 index 0000000..c909e73 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConsorcioRepository.cs @@ -0,0 +1,66 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class ConsorcioRepository : GenericRepository, IConsorcioRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public ConsorcioRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public void DeleteRange(List ids) + { + List list = ( + from x in base.All() + where ids.Contains(x.Item.Id) + select x).ToList(); + base.DeleteRange(list); + } + + public Consorcio Find(long id) + { + ConsorcioDb consorcioDb = base.All().FirstOrDefault((ConsorcioDb x) => x.Item.Id == id) ?? new ConsorcioDb(); + return ApplicationMapper.Mapper.Map(consorcioDb); + } + + public Consorcio FindById(long id) + { + ConsorcioDb consorcioDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(consorcioDb); + } + + public Consorcio Merge(Consorcio consorcio) + { + ConsorcioDb consorcioDb = ApplicationMapper.Mapper.Map(consorcio); + base.Merge(consorcioDb); + return ApplicationMapper.Mapper.Map(consorcioDb); + } + + public Consorcio SaveOrUpdate(Consorcio consorcio) + { + ConsorcioDb consorcioDb = ApplicationMapper.Mapper.Map(consorcio); + this.SaveOrUpdate(consorcioDb); + return ApplicationMapper.Mapper.Map(consorcioDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleFinanceiroRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleFinanceiroRepository.cs new file mode 100644 index 0000000..15ac6ff --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleFinanceiroRepository.cs @@ -0,0 +1,73 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Financeiro; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Financeiro; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class ControleFinanceiroRepository : GenericRepository, IControleFinanceiroRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public ControleFinanceiroRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + ControleFinanceiroDb controleFinanceiroDb = base.FindEntityById(id); + if (controleFinanceiroDb == null) + { + return; + } + IQueryable lancamentoDbs = + from x in this._unitOfWork.Query() + where x.Controle.Id == id + select x; + if (lancamentoDbs.Any()) + { + this._unitOfWork.Repository().DeleteRange(lancamentoDbs); + } + base.Delete(controleFinanceiroDb); + } + + public List FindByFornecedor(long id) + { + List list = ( + from x in base.All() + where x.Fornecedor.Id == id + select x).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public ControleFinanceiro FindById(long id) + { + ControleFinanceiroDb controleFinanceiroDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(controleFinanceiroDb); + } + + public ControleFinanceiro Merge(ControleFinanceiro controle) + { + ControleFinanceiroDb controleFinanceiroDb = ApplicationMapper.Mapper.Map(controle); + base.Merge(controleFinanceiroDb); + return ApplicationMapper.Mapper.Map(controleFinanceiroDb); + } + + public ControleFinanceiro SaveOrUpdate(ControleFinanceiro controle) + { + ControleFinanceiroDb controleFinanceiroDb = ApplicationMapper.Mapper.Map(controle); + this.SaveOrUpdate(controleFinanceiroDb); + return ApplicationMapper.Mapper.Map(controleFinanceiroDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleRepository.cs new file mode 100644 index 0000000..6f06aaf --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleRepository.cs @@ -0,0 +1,68 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class ControleRepository : GenericRepository, IControleRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public ControleRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public IEnumerable FindByCustomerId(long id) + { + return + from c in ( + from c in base.All() + where c.Cliente.Id == id + select c).ToList() + select c.Id; + } + + public Controle FindById(long id) + { + ControleDb controleDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(controleDb); + } + + public Controle Merge(Controle controle) + { + ControleDb controleDb = ApplicationMapper.Mapper.Map(controle); + base.Merge(controleDb); + return ApplicationMapper.Mapper.Map(controleDb); + } + + public Controle SaveOrUpdate(Controle controle) + { + ControleDb controleDb = ApplicationMapper.Mapper.Map(controle); + this.SaveOrUpdate(controleDb); + return ApplicationMapper.Mapper.Map(controleDb); + } + + public IEnumerable SelectDocumentIds(long id) + { + return + from x in base.All().First((ControleDb c) => c.Id == id).Documentos + select x.Id; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleSinistroRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleSinistroRepository.cs new file mode 100644 index 0000000..5d23145 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleSinistroRepository.cs @@ -0,0 +1,161 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Helpers; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class ControleSinistroRepository : GenericRepository, IControleSinistroRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public ControleSinistroRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + ControleSinistroDb controleSinistroDb = base.FindEntityById(id); + if (controleSinistroDb == null) + { + return; + } + base.Delete(controleSinistroDb); + } + + public void DeleteByItem(long id) + { + object connection; + List list = ( + from s in this._unitOfWork.Query() + where s.ControleSinistro.Item.Id == id + select s).ToList(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = string.Format("DELETE FROM controlesinistro WHERE iditem = {0}", id); + sqlCommand.ExecuteNonQuery(); + list.ForEach((SinistroDb x) => { + sqlCommand.CommandText = string.Format("DELETE FROM sinistro WHERE idsinistro = {0}", x.Id); + sqlCommand.ExecuteNonQuery(); + sqlCommand.CommandText = string.Format("DELETE FROM sinistroauto WHERE idsinistro = {0}", x.Id); + sqlCommand.ExecuteNonQuery(); + sqlCommand.CommandText = string.Format("DELETE FROM sinistrovida WHERE idsinistro = {0}", x.Id); + sqlCommand.ExecuteNonQuery(); + }); + } + } + } + + public void DeleteRange(List ids) + { + List list = ( + from x in base.All() + where ids.Contains(x.Item.Id) + select x).ToList(); + if (list == null || list.Count == 0) + { + return; + } + base.DeleteRange(list); + } + + public bool DocumentoHasSinistro(long id) + { + return base.All().Any((ControleSinistroDb x) => x.Item.Documento.Id == id); + } + + public ControleSinistro FindById(long id) + { + ControleSinistroDb controleSinistroDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(controleSinistroDb); + } + + public List FindByIdItem(long id) + { + List list = ( + from c in base.All() + where c.Item.Id == id + select c into x + select new ControleSinistro() + { + Id = x.Id, + DataSinistro = x.DataSinistro, + Item = ApplicationMapper.Mapper.Map(x.Item) + }).ToList(); + list.ForEach((ControleSinistro x) => x.Sinistros = (new SinistroRepository(this._unitOfWork)).FindByControleId(x.Id)); + return list; + } + + public List HasSinistro(List ids) + { + List nums = new List(); + while (ids.Count > 0) + { + List list = ids.Take(1000).ToList(); + List condicaos = new List() + { + new Condicao() + { + Campo = "d.idcontrole", + Valores = list.CriarValor() + } + }; + DataTable dataTable = this._unitOfWork.Select(condicaos.CreateParameters(0), "SELECT DISTINCT d.idcontrole as id FROM controlesinistro c CROSS APPLY (select idcontrole FROM item i INNER JOIN documento d on d.iddocumento = i.iddocumento WHERE i.iditem = c.iditem) d WHERE ", ""); + if (dataTable != null && dataTable.Rows.Count > 0) + { + nums.AddRange(dataTable.AsEnumerable().Select((DataRow x) => x.Field("id")).ToList()); + } + ids = (list.Count < 1000 ? new List() : ids.Except(list).ToList()); + } + return nums; + } + + public bool HasSinistro(long id) + { + return base.All().Any((ControleSinistroDb x) => x.Item.Documento.Controle.Id == id); + } + + public ControleSinistro Merge(ControleSinistro controleSinistro) + { + ControleSinistroDb controleSinistroDb = ApplicationMapper.Mapper.Map(controleSinistro); + base.Merge(controleSinistroDb); + return ApplicationMapper.Mapper.Map(controleSinistroDb); + } + + public ControleSinistro SaveOrUpdate(ControleSinistro controleSinistro) + { + ControleSinistroDb controleSinistroDb = ApplicationMapper.Mapper.Map(controleSinistro); + this.SaveOrUpdate(controleSinistroDb); + return ApplicationMapper.Mapper.Map(controleSinistroDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CredencialRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CredencialRepository.cs new file mode 100644 index 0000000..0e7d668 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CredencialRepository.cs @@ -0,0 +1,75 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Ferramentas; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class CredencialRepository : GenericRepository, ICredencialRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public CredencialRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + CredencialDb credencialDb = base.FindEntityById(id); + if (credencialDb == null) + { + return; + } + credencialDb.Excluido = true; + base.Merge(credencialDb); + } + + public List Find(long idEmpresa) + { + List list = ( + from x in base.All() + where x.IdEmpresa == idEmpresa && !x.Excluido + select x).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public List Find(string filter, long idEmpresa) + { + CredencialRepository.u003cu003ec__DisplayClass7_0 variable = null; + IQueryable credencialDbs = base.All(); + ParameterExpression parameterExpression = Expression.Parameter(typeof(CredencialDb), "x"); + List list = credencialDbs.Where(Expression.Lambda>(Expression.AndAlso(Expression.Equal(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(CredencialDb).GetMethod("get_Excluido").MethodHandle)), Expression.Constant(false, typeof(bool))), Expression.OrElse(Expression.OrElse(Expression.AndAlso(Expression.Equal(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(CredencialDb).GetMethod("get_IdEmpresa").MethodHandle)), Expression.Field(Expression.Constant(variable, typeof(CredencialRepository.u003cu003ec__DisplayClass7_0)), FieldInfo.GetFieldFromHandle(typeof(CredencialRepository.u003cu003ec__DisplayClass7_0).GetField("idEmpresa").FieldHandle))), Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(CredencialDb).GetMethod("get_Descricao").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(CredencialRepository.u003cu003ec__DisplayClass7_0)), FieldInfo.GetFieldFromHandle(typeof(CredencialRepository.u003cu003ec__DisplayClass7_0).GetField("filter").FieldHandle)) })), Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(CredencialDb).GetMethod("get_Email").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(CredencialRepository.u003cu003ec__DisplayClass7_0)), FieldInfo.GetFieldFromHandle(typeof(CredencialRepository.u003cu003ec__DisplayClass7_0).GetField("filter").FieldHandle)) })), Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(CredencialDb).GetMethod("get_Dominio").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(CredencialRepository.u003cu003ec__DisplayClass7_0)), FieldInfo.GetFieldFromHandle(typeof(CredencialRepository.u003cu003ec__DisplayClass7_0).GetField("filter").FieldHandle)) }))), new ParameterExpression[] { parameterExpression })).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public Credencial FindById(long id) + { + CredencialDb credencialDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(credencialDb); + } + + public Credencial Merge(Credencial credencial) + { + CredencialDb credencialDb = ApplicationMapper.Mapper.Map(credencial); + base.Merge(credencialDb); + return ApplicationMapper.Mapper.Map(credencialDb); + } + + public Credencial SaveOrUpdate(Credencial credencial) + { + CredencialDb credencialDb = ApplicationMapper.Mapper.Map(credencial); + this.SaveOrUpdate(credencialDb); + return ApplicationMapper.Mapper.Map(credencialDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CriticaApoliceRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CriticaApoliceRepository.cs new file mode 100644 index 0000000..3e57d4d --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CriticaApoliceRepository.cs @@ -0,0 +1,315 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Helpers; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class CriticaApoliceRepository : GenericRepository, ICriticaApoliceRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + private const string _commandoCritica = "SELECT i.idimportacao as id, i.iddocumento, i.idusuario, i.critica, i.dataimportacao, i.tipo, d.contrato as apolice, d.proposta, c.idcontrole, c.idciaseg, c.idramo, cl.idcliente, cl.nome as cliente, cl.documentoprincipal, cl.cgccpf as documento, cl.rne, cl.cei, d.vigencia1, d.vigencia2, i.critica, i.idusuariocritica, i.datacritica FROM importacao i INNER JOIN documento d on d.iddocumento = i.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE"; + + private const string _commandoCriticaVinculo = "SELECT DISTINCT i.idimportacao as id, i.iddocumento, i.idusuario, i.critica, i.dataimportacao, i.tipo, d.contrato as apolice, d.proposta, c.idcontrole, c.idciaseg, c.idramo, cl.idcliente, cl.nome as cliente, cl.documentoprincipal, cl.cgccpf as documento, cl.rne, cl.cei, d.vigencia1, d.vigencia2, i.critica, i.idusuariocritica, i.datacritica FROM importacao i INNER JOIN documento d on d.iddocumento = i.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente LEFT OUTER JOIN vendedorparcela vp on vp.iddocumento = d.iddocumento WHERE"; + + public CriticaApoliceRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public List BuscarUsuarioCritica(DateTime inicio, DateTime fim, bool criticado = false, long idempresa = 0L) + { + List usuarios; + object connection; + string str = (criticado ? " AND i.critica = '1'" : " AND i.critica = '0'"); + string str1 = (idempresa == 0 ? "" : string.Format(" AND u.idempresa = {0}", idempresa)); + DataTable dataTable = new DataTable(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + Auxiliar.CriarAuxiliarUsuario(sqlCommand); + sqlCommand.CommandText = string.Concat("SELECT DISTINCT i.idusuario FROM importacao i INNER JOIN documento d on d.iddocumento = i.iddocumento INNER JOIN usuario u on u.idusuario = i.idusuario ", string.Format("WHERE CAST(i.dataimportacao AS DATE) >= '{0:yyyy-MM-dd}' AND CAST(i.dataimportacao AS DATE) <= '{1:yyyy-MM-dd}' AND (d.excluido IS NULL OR d.excluido != '1') {2} {3}", new object[] { inicio, fim, str1, str })); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + if (dataTable.Rows.Count != 0) + { + goto Label0; + } + else + { + usuarios = new List(); + } + } + } + return usuarios; + List list = dataTable.AsEnumerable().Select((DataRow x) => x.Field("idusuario")).ToList(); + return ( + from x in Auxiliar.Usuarios + where list.Contains(x.Id) + select x).ToList(); + } + + public void Delete(long id) + { + CriticaApoliceDb criticaApoliceDb = base.All().FirstOrDefault((CriticaApoliceDb x) => x.Id == id); + if (criticaApoliceDb == null) + { + return; + } + base.Delete(criticaApoliceDb); + } + + public List Find(long usuario, DateTime inicio, DateTime fim, long vendedorCorretoraId, bool criticado = false, long idempresa = 0L, List vinculos = null, bool vendedorEmBranco = false, bool vinculoVendedorCritica = false) + { + Condicao condicao = new Condicao() + { + Campo = "i.idusuario", + Valores = usuario.CriarValor() + }; + Condicao condicao1 = new Condicao() + { + Campo = "i.critica", + Valores = (criticado ? "1".CriarValor() : "0".CriarValor()) + }; + Condicao condicao2 = new Condicao() + { + Campo = "c.idempresa", + Valores = idempresa.CriarValor() + }; + List condicaos = new List() + { + new Condicao() + { + Campo = "CAST(i.dataimportacao AS DATE)", + Valores = inicio.CriarValor(), + Operador = Operador.MaiorEIgual + }, + new Condicao() + { + Campo = "CAST(i.dataimportacao AS DATE)", + Valores = fim.CriarValor(), + Operador = Operador.MenorEIgual + }, + new Condicao() + { + Campo = " d.excluido", + Valores = null, + Grupo = 1, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = " d.excluido", + Valores = "1".CriarValor(), + Grupo = 1, + Operador = Operador.Diferente, + Operacao = Operacao.Or + } + }; + string str = (vinculos == null || vinculos.Count <= 0 ? "SELECT i.idimportacao as id, i.iddocumento, i.idusuario, i.critica, i.dataimportacao, i.tipo, d.contrato as apolice, d.proposta, c.idcontrole, c.idciaseg, c.idramo, cl.idcliente, cl.nome as cliente, cl.documentoprincipal, cl.cgccpf as documento, cl.rne, cl.cei, d.vigencia1, d.vigencia2, i.critica, i.idusuariocritica, i.datacritica FROM importacao i INNER JOIN documento d on d.iddocumento = i.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE" : "SELECT DISTINCT i.idimportacao as id, i.iddocumento, i.idusuario, i.critica, i.dataimportacao, i.tipo, d.contrato as apolice, d.proposta, c.idcontrole, c.idciaseg, c.idramo, cl.idcliente, cl.nome as cliente, cl.documentoprincipal, cl.cgccpf as documento, cl.rne, cl.cei, d.vigencia1, d.vigencia2, i.critica, i.idusuariocritica, i.datacritica FROM importacao i INNER JOIN documento d on d.iddocumento = i.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente LEFT OUTER JOIN vendedorparcela vp on vp.iddocumento = d.iddocumento WHERE"); + if (vinculos != null && vinculos.Count > 0) + { + if (vendedorEmBranco) + { + condicaos.Add(new Condicao() + { + Campo = "vp.idvendedor", + Valores = null, + Operacao = Operacao.Or, + Grupo = 3 + }); + } + condicaos.Add(new Condicao() + { + Campo = "vp.idvendedor", + Valores = (vinculoVendedorCritica & vendedorEmBranco ? vendedorCorretoraId.CriarValor() : ( + from x in vinculos + select x.Vendedor.Id).ToList().CriarValor()), + Grupo = 3 + }); + } + if (usuario > (long)0) + { + condicaos.Add(condicao); + } + if (idempresa > (long)0) + { + condicaos.Add(condicao2); + } + condicaos.Add(condicao1); + return this.Select(condicaos.CreateParameters(0), str); + } + + public List Find(DateTime inicio, DateTime fim, long idempresa = 0L) + { + Condicao condicao = new Condicao() + { + Campo = "c.idempresa", + Valores = idempresa.CriarValor() + }; + List condicaos = new List() + { + new Condicao() + { + Campo = "CAST(i.dataimportacao AS DATE)", + Valores = inicio.CriarValor(), + Operador = Operador.MaiorEIgual + }, + new Condicao() + { + Campo = "CAST(i.dataimportacao AS DATE)", + Valores = fim.CriarValor(), + Operador = Operador.MenorEIgual + }, + new Condicao() + { + Campo = " d.excluido", + Valores = null, + Grupo = 1, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = " d.excluido", + Valores = "1".CriarValor(), + Grupo = 1, + Operador = Operador.Diferente, + Operacao = Operacao.Or + } + }; + if (idempresa > (long)0) + { + condicaos.Add(condicao); + } + return this.Select(condicaos.CreateParameters(0), "SELECT i.idimportacao as id, i.iddocumento, i.idusuario, i.critica, i.dataimportacao, i.tipo, d.contrato as apolice, d.proposta, c.idcontrole, c.idciaseg, c.idramo, cl.idcliente, cl.nome as cliente, cl.documentoprincipal, cl.cgccpf as documento, cl.rne, cl.cei, d.vigencia1, d.vigencia2, i.critica, i.idusuariocritica, i.datacritica FROM importacao i INNER JOIN documento d on d.iddocumento = i.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE"); + } + + public List Find(long id) + { + List list = this._unitOfWork.Session.CreateQuery(string.Format("from CriticaApoliceDb WHERE iddocumento = {0} AND (Critica IS NULL OR Critica != '1')", id)).List().ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public CriticaApolice FindByApolice(long id) + { + CriticaApoliceDb criticaApoliceDb = base.All().FirstOrDefault((CriticaApoliceDb x) => x.Documento.Id == id); + return ApplicationMapper.Mapper.Map(criticaApoliceDb); + } + + public CriticaApolice FindById(long id) + { + CriticaApoliceDb criticaApoliceDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(criticaApoliceDb); + } + + public List FindDuo(long id, DateTime vigencia) + { + return this.Select((new List() + { + new Condicao() + { + Campo = " c.idcliente", + Valores = id.CriarValor() + }, + new Condicao() + { + Campo = " CAST(d.vigencia1 AS DATE)", + Valores = vigencia.CriarValor(), + Operador = Operador.Igual + }, + new Condicao() + { + Campo = " i.critica", + Valores = 1.CriarValor(), + Operador = Operador.Diferente + }, + new Condicao() + { + Campo = " d.excluido", + Valores = null, + Grupo = 1, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = " d.excluido", + Valores = "1".CriarValor(), + Grupo = 1, + Operador = Operador.Diferente, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = " c.idramo", + Valores = 5.CriarValor(), + Grupo = 2, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = " c.idramo", + Valores = 1.CriarValor(), + Grupo = 2, + Operacao = Operacao.Or + } + }).CreateParameters(0), "SELECT i.idimportacao as id, i.iddocumento, i.idusuario, i.critica, i.dataimportacao, i.tipo, d.contrato as apolice, d.proposta, c.idcontrole, c.idciaseg, c.idramo, cl.idcliente, cl.nome as cliente, cl.documentoprincipal, cl.cgccpf as documento, cl.rne, cl.cei, d.vigencia1, d.vigencia2, i.critica, i.idusuariocritica, i.datacritica FROM importacao i INNER JOIN documento d on d.iddocumento = i.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE"); + } + + public List FindImport(long id) + { + List list = this._unitOfWork.Session.CreateQuery(string.Format("from CriticaApoliceDb WHERE iddocumento = {0}", id)).List().ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public CriticaApolice Merge(CriticaApolice documento) + { + CriticaApoliceDb criticaApoliceDb = ApplicationMapper.Mapper.Map(documento); + base.Merge(criticaApoliceDb); + return ApplicationMapper.Mapper.Map(criticaApoliceDb); + } + + public CriticaApolice SaveOrUpdate(CriticaApolice documento) + { + CriticaApoliceDb criticaApoliceDb = ApplicationMapper.Mapper.Map(documento); + this.SaveOrUpdate(criticaApoliceDb); + return ApplicationMapper.Mapper.Map(criticaApoliceDb); + } + + private List Select(SqlQueryCondition condition, string command) + { + return this._unitOfWork.Select(condition, command, "").MapImportacao(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/DetalheExtratoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/DetalheExtratoRepository.cs new file mode 100644 index 0000000..54af174 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/DetalheExtratoRepository.cs @@ -0,0 +1,99 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class DetalheExtratoRepository : GenericRepository, IDetalheExtratoRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public DetalheExtratoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public bool Completo(long id) + { + List statusParcelas = new List() + { + StatusParcela.BaixadaCritica, + StatusParcela.Baixada, + StatusParcela.BaixadaDiferencaPercentual, + StatusParcela.BaixadaAnteriormente, + StatusParcela.BaixadaManualmente, + StatusParcela.DesconsideradaUsuario, + StatusParcela.DesconsideradaSistema + }; + return ( + from x in base.All() + where x.Extrato.Id == id + select x).All((DetalheExtratoDb x) => statusParcelas.Contains(x.Status.Value)); + } + + public void Delete(long id) + { + DetalheExtratoDb detalheExtratoDb = base.FindEntityById(id); + if (detalheExtratoDb == null) + { + return; + } + base.Delete(detalheExtratoDb); + } + + public List Find(long id) + { + List list = ( + from x in base.All() + where x.Extrato.Id == id + select x).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public DetalheExtrato FindById(long id) + { + DetalheExtratoDb detalheExtratoDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(detalheExtratoDb); + } + + public List FindByLongId(long? id) + { + List list = ( + from x in base.All() + where (long?)x.Extrato.Id == id + select x).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public DetalheExtrato FindByParcelaId(long id) + { + DetalheExtratoDb detalheExtratoDb = base.All().FirstOrDefault((DetalheExtratoDb x) => x.Parcela == (long?)id); + return ApplicationMapper.Mapper.Map(detalheExtratoDb); + } + + public DetalheExtrato Merge(DetalheExtrato parcela) + { + DetalheExtratoDb detalheExtratoDb = ApplicationMapper.Mapper.Map(parcela); + base.Merge(detalheExtratoDb); + return ApplicationMapper.Mapper.Map(detalheExtratoDb); + } + + public DetalheExtrato SaveOrUpdate(DetalheExtrato parcela) + { + DetalheExtratoDb detalheExtratoDb = ApplicationMapper.Mapper.Map(parcela); + this.SaveOrUpdate(detalheExtratoDb); + return ApplicationMapper.Mapper.Map(detalheExtratoDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/DocumentoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/DocumentoRepository.cs new file mode 100644 index 0000000..7414c45 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/DocumentoRepository.cs @@ -0,0 +1,5095 @@ +using AutoMapper; +using Gestor.Common.Helpers; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Helpers; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Aggilizador; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Relatorios.Fechamento; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.License; +using Gestor.Model.Validation; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Diagnostics; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class DocumentoRepository : GenericRepository, IDocumentoRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + private const string _commandoDocumento = "SELECT DISTINCT c.idcliente, cl.MalaDireta, cl.cgccpf, c.idempresa, c.idcontrole, c.idciaseg, c.idramo, c.idproduto, d.iddocumento, d.adinacomis, d.pr_adic, d.proposta, d.pedadit, d.contrato, d.aditamento, d.com01, d.idnegocio, d.pr_liq, d.pr_total, d.vigencia1, d.vigencia2, d.emissao, d.remessa, d.idestipulante, d.negociocorretora, d.situacao, d.tiporecebimento, CAST(d.tipo AS INTEGER) AS tipo, CAST(d.ordem AS INTEGER) AS ordem, d.n_parc AS numeroParcelas, d.pasta, d.banco, cb.nomebanco, d.agencia, d.conta, d.excluido, c.AssistenciaId, d.numeroCart, d.vencimentoCart, d.nomeProp, d.formapagamento, d.Obs FROM controle c INNER JOIN documento d ON d.idcontrole = c.idcontrole LEFT OUTER JOIN codigobanco cb on cb.idcodigobanco = d.idbanco INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE "; + + private const string _comandoVendedores = "SELECT DISTINCT vp.IDPARCELA, vp.idvendedor, d.iddocumento, d.idcontrole, vp.idtipovendedor, p.idsubtipo FROM documento d LEFT OUTER JOIN vendedorparcela vp on d.iddocumento = vp.iddocumento LEFT OUTER JOIN parcela p on p.idparcela = vp.idparcela WHERE "; + + private const string _comandoArquivo = "SELECT DISTINCT a.idnewarquivodigital, a.descricao, ISNULL(s.Status ,0) as Status, s.assinado, s.DocumentoId, s.id, s.UsuarioId, s.Enviado FROM newarquivodigital a LEFT OUTER JOIN ArquivoParaAssinatura s on s.IndiceId = a.idnewarquivodigital WHERE "; + + private const string ComandoEndereco = "SELECT DISTINCT idcliend, cep, cidade, uf as estado, idcliente FROM cliendereco WHERE (ORDEM = '1' OR PADRAO = '1') "; + + private const string ComandoTelefone = "SELECT DISTINCT idclitelefone, ddd, fone, idcliente FROM clitelefone WHERE 1=1 "; + + private const string ComandoEmail = "SELECT DISTINCT idclimail, email, idcliente FROM climail WHERE (ORDEM = '1' OR PADRAO = '1') "; + + public DocumentoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public bool AtualizarNumero(long id, string numero, string endosso, int tipoDocumento) + { + DocumentoDb documentoDb = base.FindEntityById(id); + if (documentoDb == null) + { + return false; + } + if (!documentoDb.Emissao.HasValue) + { + return true; + } + if (tipoDocumento == 0) + { + documentoDb.Apolice = numero; + } + else if (tipoDocumento == 1) + { + documentoDb.Apolice = numero; + documentoDb.Endosso = endosso; + } + base.Merge(documentoDb); + return true; + } + + public List Auditoria(Filtros filtro) + { + List documentos; + object connection; + string str = (filtro.Status == null || filtro.Status.Count == 0 ? "" : string.Concat(" AND situacao IN (", string.Join(",", + from v in filtro.Status + select v), ")")); + string str1 = (filtro.Negocio == null || filtro.Negocio.Count == 0 ? "" : string.Concat(" AND NegocioCorretora IN (", string.Join(",", + from v in filtro.Negocio + select v), ")")); + string str2 = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND c.idciaseg IN (", string.Join(",", + from v in filtro.Seguradoras + select v), ")")); + string str3 = (filtro.Ramos == null || filtro.Ramos.Count == 0 ? "" : string.Concat(" AND c.idramo IN (", string.Join(",", + from v in filtro.Ramos + select v), ")")); + string str4 = (filtro.Produtos == null || filtro.Produtos.Count == 0 ? "" : string.Concat(" AND c.idproduto IN (", string.Join(",", + from v in filtro.Produtos + select v), ")")); + string str5 = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? "" : string.Concat(" AND vp.idvendedor IN (", string.Join(",", + from v in filtro.Vendedores + select v), ")")); + string str6 = (filtro.TipoVendedor == null || filtro.TipoVendedor.Count == 0 ? "OUTER APPLY (SELECT TOP 1 idvendedor FROM vendedorparcela vp WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor = 1) vp" : string.Concat("INNER JOIN vendedorparcela vp ON vp.iddocumento = d.iddocumento AND vp.idtipovendedor IN (", string.Join(",", + from v in filtro.TipoVendedor + select v), ")")); + string str7 = (filtro.Estipulantes == null || filtro.Estipulantes.Count == 0 ? "" : string.Concat(" AND d.idestipulante IN (", string.Join(",", + from v in filtro.Estipulantes + select v), ")")); + string str8 = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", filtro.IdEmpresa)); + DataTable dataTable = new DataTable(); + DataTable dataTable1 = new DataTable(); + DataTable dataTable2 = new DataTable(); + DataTable dataTable3 = new DataTable(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandTimeout = 15000; + Auxiliar.CriarAuxiliar(sqlCommand, false); + string str9 = string.Concat("SELECT DISTINCT cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome as cliente, d.idcontrole, d.iddocumento as id, d.contrato as apolice, d.aditamento as endosso, d.idnegocio, d.situacao, d.vigencia1 as vigenciainicial, d.vigencia2 as vigenciafinal, d.pr_total as total, d.pr_liq as liquido, d.pr_adic as adicional, ISNULL(d.com01, 0.00) as comissao, ISNULL(d.adinacomis, '0') as adinacomiss, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, vp.idvendedor, d.idestipulante, d.datacontrole, d.idstatus, d.pasta, d.n_parc, cl.pasta as pastacliente, c.AssistenciaId FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente ", str6, " WHERE (d.excluido IS NULL OR d.excluido = 0) "); + string str10 = "SELECT DISTINCT d.idcontrole, idvendedor FROM vendedorparcela vp INNER JOIN documento d on d.iddocumento = vp.iddocumento WHERE 1=1 "; + string str11 = "SELECT DISTINCT iddocumento as id, idvendedor FROM vendedorparcela vp WHERE 1=1 "; + string str12 = "SELECT DISTINCT vp.idparcela, vp.iddocumento as id, ISNULL(vp.vlrcomiss, 0) as recebida, vp.idsubtipo, vp.datarec as recebimento FROM parcela vp WHERE 1=1 "; + string str13 = "SELECT i.iditem, d.iddocumento, d.idcontrole, i.descricao FROM item i INNER JOIN documento d on d.iddocumento = i.iddocumento WHERE (cancelado IS NULL OR cancelado != '1') AND idsubstituido IS NULL "; + sqlCommand.CommandText = string.Format("{0} {1} AND d.vigencia1 >= '{2:yyyy-MM-dd}' AND d.vigencia1 <= '{3:yyyy-MM-dd}' AND d.tiporecebimento = 1 {4} {5} {6} {7} {8} {9} {10}", new object[] { str9, str8, filtro.Inicio, filtro.Fim, str, str1, str2, str3, str4, str7, str5 }); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + if (dataTable.Rows.Count != 0) + { + string str14 = string.Concat(" AND vp.iddocumento IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); + sqlCommand.CommandText = string.Concat(str12, (filtro.ParcelasEspeciais.Any((FiltroTipoParcela x) => x.Selecionado) ? string.Concat(" AND vp.idsubtipo IN (1,", string.Join(",", + from x in filtro.ParcelasEspeciais + where x.Selecionado + select x into v + select (int)v.Tipo), ")") : " AND vp.idsubtipo = 1 "), str14); + using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) + { + sqlDataAdapter1.SelectCommand = sqlCommand; + sqlDataAdapter1.Fill(dataTable1); + } + string str15 = (dataTable.AsEnumerable().Any((DataRow x) => x.Field("idvendedor") == null) ? string.Concat(" AND d.idcontrole IN (", string.Join(",", dataTable.AsEnumerable().Where((DataRow x) => x.Field("idvendedor") == null).Select((DataRow v) => v.Field("idcontrole"))), ")") : ""); + DataTable dataTable4 = new DataTable(); + sqlCommand.CommandText = string.Concat(new string[] { str10, " ", str15, " ", str5 }); + using (SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter()) + { + sqlDataAdapter2.SelectCommand = sqlCommand; + sqlDataAdapter2.Fill(dataTable4); + } + List dataRows3 = new List(); + foreach (DataRow row in dataTable.Rows) + { + string str16 = string.Format("id = {0}", row["id"]); + DataRow[] dataRowArray = dataTable1.Select(str16); + decimal num = Math.Round(((row.Field("liquido") + (row.Field("adinacomiss") == "1" ? row.Field("liquido") : decimal.Zero)) * row.Field("comissao")) * new decimal(1, 0, 0, false, 2), 2); + decimal num1 = ((IEnumerable)dataRowArray).Sum((DataRow x) => x.Field("recebida")); + decimal? tolerancia = Auxiliar.Seguradoras.First((Seguradora p) => p.Id == row.Field("idseguradora")).Tolerancia; + if ((num - num1) > tolerancia.GetValueOrDefault()) + { + if (!string.IsNullOrEmpty(row["idvendedor"].ToString())) + { + continue; + } + string str17 = string.Format("idcontrole = {0}", row["idcontrole"]); + DataRow[] dataRowArray1 = dataTable4.Select(str17); + if (dataRowArray1.Length == 0) + { + continue; + } + row["idvendedor"] = dataRowArray1[0][1]; + } + else + { + dataRows3.Add(row); + } + } + dataRows3.ForEach((DataRow x) => dataTable.Rows.Remove(x)); + if (dataTable.Rows.Count != 0) + { + str14 = string.Concat(" AND vp.iddocumento IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); + sqlCommand.CommandText = string.Concat(str11, " ", str14); + using (SqlDataAdapter sqlDataAdapter3 = new SqlDataAdapter()) + { + sqlDataAdapter3.SelectCommand = sqlCommand; + sqlDataAdapter3.Fill(dataTable2); + } + string str18 = string.Concat(" AND d.idcontrole IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("idcontrole"))), ")"); + sqlCommand.CommandText = string.Concat(str13, " ", str18); + using (SqlDataAdapter sqlDataAdapter4 = new SqlDataAdapter()) + { + sqlDataAdapter4.SelectCommand = sqlCommand; + sqlDataAdapter4.Fill(dataTable3); + goto Label0; + } + } + else + { + documentos = new List(); + } + } + else + { + documentos = new List(); + } + } + } + return documentos; + Label0: + return dataTable.AsEnumerable().ToList().Select((DataRow x) => { + Func func2 = null; + Documento documento = new Documento() + { + Id = x.Field("id"), + Controle = new Controle() + { + IdEmpresa = x.Field("idempresa"), + Cliente = new Cliente() + { + Id = x.Field("idcliente"), + Nome = x.Field("cliente"), + IdEmpresa = x.Field("idempresa"), + Pasta = x.Field("pastacliente"), + MalaDireta = new bool?(x.Field("MalaDireta").GetValueOrDefault(true)) + }, + Seguradora = (x.Field("idseguradora") != null ? Auxiliar.Seguradoras.FirstOrDefault((Seguradora p) => p.Id == x.Field("idseguradora")) : null), + Ramo = (x.Field("idramo") != null ? Auxiliar.Ramos.FirstOrDefault((Ramo p) => p.Id == x.Field("idramo")) : null), + Produto = (x.Field("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault((Gestor.Model.Domain.Seguros.Produto p) => p.Id == x.Field("idproduto")) : null), + AssistenciaId = x.Field("AssistenciaId") + }, + TipoRecebimento = new TipoRecebimento?(TipoRecebimento.Parcela), + AdicionalComiss = x.Field("adinacomiss") == "1", + Apolice = x.Field("apolice"), + Endosso = x.Field("endosso"), + Comissao = x.Field("comissao"), + Negocio = new Negocio?((x.Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field("idnegocio").ToString()))), + PremioLiquido = x.Field("liquido"), + PremioTotal = x.Field("total"), + PremioAdicional = x.Field("adicional"), + Vigencia2 = x.Field("vigenciafinal") + }; + DateTime? nullable = x.Field("vigenciainicial"); + documento.Vigencia1 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue); + documento.VendedorPrincipal = (x.Field("idvendedor") != null ? Auxiliar.Vendedores.FirstOrDefault((Vendedor p) => p.Id == x.Field("idvendedor")) : null); + documento.Estipulante1 = (x.Field("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault((Estipulante p) => p.Id == x.Field("idestipulante")) : null); + documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()); + documento.Vendedores = Auxiliar.Vendedores.Where((Vendedor v) => { + List list = dataTable2.AsEnumerable().ToList(); + Func u003cu003e9_32 = func2; + if (u003cu003e9_32 == null) + { + Func func = (DataRow d) => d.Field("id") == x.Field("id"); + Func func1 = func; + func2 = func; + u003cu003e9_32 = func1; + } + IEnumerable dataRows = list.Where(u003cu003e9_32); + Func u003cu003e9_4033 = DocumentoRepository.u003cu003ec.u003cu003e9__40_33; + if (u003cu003e9_4033 == null) + { + u003cu003e9_4033 = (DataRow d) => d.Field("idvendedor"); + DocumentoRepository.u003cu003ec.u003cu003e9__40_33 = u003cu003e9_4033; + } + return dataRows.Select(u003cu003e9_4033).ToList().Contains(v.Id); + }).ToList(); + documento.Tipo = x.Field("tipo"); + IEnumerable dataRows1 = + from p in dataTable1.AsEnumerable().ToList() + where p.Field("id") == x.Field("id") + select p; + Func u003cu003e9_4025 = DocumentoRepository.u003cu003ec.u003cu003e9__40_25; + if (u003cu003e9_4025 == null) + { + u003cu003e9_4025 = (DataRow p) => new Parcela() + { + Id = p.Field("idparcela"), + ValorComissao = p.Field("recebida"), + DataRecebimento = p.Field("recebimento"), + SubTipo = (p.Field("idsubtipo") == null ? SubTipo.ParcelaNormal : (SubTipo)Enum.Parse(typeof(SubTipo), p.Field("idsubtipo").ToString())) + }; + DocumentoRepository.u003cu003ec.u003cu003e9__40_25 = u003cu003e9_4025; + } + documento.Parcelas = new ObservableCollection(dataRows1.Select(u003cu003e9_4025).ToList()); + documento.DataControle = x.Field("datacontrole"); + documento.Status = (x.Field("idstatus") != null ? Auxiliar.StatusApolice.FirstOrDefault((Status p) => p.Id == x.Field("idstatus")) : null); + IEnumerable dataRows2 = + from i in dataTable3.AsEnumerable().ToList() + where i.Field("idcontrole") == x.Field("idcontrole") + select i; + Func u003cu003e9_4028 = DocumentoRepository.u003cu003ec.u003cu003e9__40_28; + if (u003cu003e9_4028 == null) + { + u003cu003e9_4028 = (DataRow i) => new Item() + { + Id = i.Field("iditem"), + Descricao = i.Field("descricao") + }; + DocumentoRepository.u003cu003ec.u003cu003e9__40_28 = u003cu003e9_4028; + } + documento.ItensAtivo = new List(dataRows2.Select(u003cu003e9_4028).ToList()); + documento.Pasta = x.Field("Pasta"); + documento.NumeroParcelas = (x.Field("n_parc") != null ? decimal.Parse(x.Field("n_parc").ToString()) : decimal.Zero); + return documento; + }).ToList(); + } + + private async Task> BuscaDocumentosPorCondicao(Filtros filtro, List condicao, bool buscaAssinaturas) + { + NegocioCorretora fieldValue; + Predicate predicate; + bool flag; + object connection; + bool count; + string str; + object vendedor; + bool count1; + bool flag1; + List itensAtivo; + object produto; + object obj; + object statu; + object banco; + List statusDocumentoAssinados; + bool flag2; + StatusAssinatura statusAssinatura; + NegocioCorretora negocioCorretora; + bool count2; + bool count3; + Documento vendedorParcelas; + Documento fieldValue1; + Predicate predicate1 = null; + Predicate predicate2 = null; + Predicate predicate3 = null; + Predicate predicate4 = null; + Predicate predicate5 = null; + List documentos = new List(); + SqlQueryCondition sqlQueryCondition = condicao.CreateParameters(0); + Vendedor vendedor1 = Auxiliar.Vendedores.FirstOrDefault((Vendedor v) => { + if (v.IdEmpresa != (filtro.IdEmpresa == 0 ? (long)1 : filtro.IdEmpresa)) + { + return false; + } + return v.Corretora; + }); + using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) + { + SessionFactoryImpl sessionFactoryImpl = sessionFactory; + if (sessionFactoryImpl != null) + { + connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + bool flag3 = await this.ExisteTabelasAssinatura(); + bool flag4 = flag3; + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandTimeout = 1000; + string str1 = "SELECT d.IDDOCUMENTO IdDocumento,c.IDCONTROLE IdControle,c.IDEMPRESA IdEmpresa,c.IDCLIENTE IdCliente,clie.NOME NomeCliente,clie.CGCCPF DocumentoCliente,clie.PASTA PastaCliente,clie.MalaDireta MalaDireta,cm.idclimail IdEmail,cm.email,ct.idclitelefone IdTelefone,ct.ddd Prefixo,ct.fone Numero,c.IDRAMO IdRamo,r.NOME NomeRamo,c.IDCIASEG IdCiaSeg,cia.NOME NomeCia,cia.NomeSocial NomeSocialCia,c.IDPRODUTO IdProduto,pr.NOME NomeProduto,d.idestipulante IdEstipulante, d.idestipulante2 IdEstipulante2, d.idestipulante3 IdEstipulante3, d.idestipulante4 IdEstipulante4, d.idestipulante5 IdEstipulante5, e.nome NomeEstipulante,d.idstatus IdStatus,s.NOME NomeStatus,vp.idtipovendedor IdTipoVendedor,vp.VREP PorcentagemRepasse,vp.idvendedor IdVendedor,v.NOME NomeVendedor,tv.DESCRICAO DescricaoTipovendedor,d.PROPOSTA Proposta,d.CONTRATO Apolice,d.apoconferida ApoliceConferida,d.PEDADIT PropostaEndosso,d.ADITAMENTO Endosso,d.ADINACOMIS AdicionalComissao,d.COM01 Comissao,d.idnegocio Negocio,d.NegocioCorretora NegocioCorretora,d.tiporecebimento TipoRecebimento,d.TIPO Tipo,d.PR_LIQ PremioLiquido,d.PR_TOTAL PremioTotal,d.PR_ADIC PremioAdicional,d.N_PARC NumeroParcelas,d.VIGENCIA1 VigenciaInicial,d.VIGENCIA2 VigenciaFinal,d.EMISSAO Emissao,d.REMESSA Remessa,d.SITUACAO Situacao,d.datacontrole DataControleDocumento,d.propassinada PropostaAssinada,d.PASTA PastaDocumento,d.CRI_DATA DataCriacao,d.idbanco IdBanco,b.NOMEBANCO NomeBanco,d.AGENCIA Agencia,d.conta Conta FROM documento d INNER JOIN controle c ON c.IDCONTROLE = d.IDCONTROLE INNER JOIN cliente clie ON clie.IDCLIENTE = c.IDCLIENTE INNER JOIN ramo r ON r.IDRAMO = c.IDRAMO INNER JOIN ciaseg cia ON cia.IDCIASEG = c.IDCIASEG LEFT JOIN codigobanco b ON b.IDCODIGOBANCO = d.IDBANCO LEFT JOIN produto pr ON pr.IDPRODUTO = c.IDPRODUTO LEFT JOIN estipulante e ON e.idestipulante = d.idestipulante LEFT JOIN status s ON s.idstatus = d.idstatus LEFT JOIN vendedorparcela vp ON vp.IDDOCUMENTO = d.IDDOCUMENTO LEFT JOIN vendedor v ON v.IDVENDEDOR = vp.IDVENDEDOR LEFT JOIN tipovendedor tv on tv.idtipovendedor = vp.idtipovendedor LEFT JOIN clitelefone ct ON ct.IDCLIENTE = c.IDCLIENTE LEFT JOIN parcela p ON p.idparcela = vp.idparcela LEFT JOIN climail cm ON cm.IDCLIENTE = c.IDCLIENTE WHERE "; + sqlCommand.CommandText = string.Concat(str1, " ", sqlQueryCondition.Condicao, " ORDER BY d.IDDOCUMENTO,d.IDCONTROLE,vp.idtipovendedor,vp.IDVENDEDOR"); + sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray()); + using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) + { + while (true) + { + if (!await sqlDataReader.ReadAsync()) + { + break; + } + TipoSeguro tipoSeguro = sqlDataReader.GetFieldValue("Situacao", true, true); + if (!await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "NegocioCorretora")) + { + fieldValue = sqlDataReader.GetFieldValue("NegocioCorretora", true, true); + } + else + { + flag3 = tipoSeguro == TipoSeguro.Renovacao; + if (flag3) + { + flag3 = !await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "Negocio"); + } + negocioCorretora = (!flag3 || !(sqlDataReader.GetFieldValue("Negocio", true, true) == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio); + fieldValue = negocioCorretora; + } + NegocioCorretora negocioCorretora1 = fieldValue; + List negocio = filtro.Negocio; + if (negocio != null) + { + count = negocio.Count > 0; + } + else + { + count = false; + } + if (!count || filtro.Negocio.Any((long n) => (int)n == (int)negocioCorretora1)) + { + List estipulantes = new List(); + sqlDataReader.GetFieldValue("idestipulante", true, true); + if (sqlDataReader.GetFieldValue("idestipulante", true, true) != 0) + { + List estipulantes1 = estipulantes; + Estipulante nome = new Estipulante(); + List estipulantes2 = Auxiliar.Estipulantes; + Predicate predicate6 = predicate1; + if (predicate6 == null) + { + Predicate predicate7 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue("idestipulante", true, true); + predicate = predicate7; + predicate1 = predicate7; + predicate6 = predicate; + } + nome.Nome = estipulantes2.Find(predicate6).Nome; + estipulantes1.Add(nome); + } + sqlDataReader.GetFieldValue("idestipulante2", true, true); + if (sqlDataReader.GetFieldValue("idestipulante2", true, true) != 0) + { + List estipulantes3 = estipulantes; + Estipulante nome1 = new Estipulante(); + List estipulantes4 = Auxiliar.Estipulantes; + Predicate predicate8 = predicate2; + if (predicate8 == null) + { + Predicate predicate9 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue("idestipulante2", true, true); + predicate = predicate9; + predicate2 = predicate9; + predicate8 = predicate; + } + nome1.Nome = estipulantes4.Find(predicate8).Nome; + estipulantes3.Add(nome1); + } + sqlDataReader.GetFieldValue("idestipulante3", true, true); + if (sqlDataReader.GetFieldValue("idestipulante3", true, true) != 0) + { + List estipulantes5 = estipulantes; + Estipulante estipulante1 = new Estipulante(); + List estipulantes6 = Auxiliar.Estipulantes; + Predicate predicate10 = predicate3; + if (predicate10 == null) + { + Predicate predicate11 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue("idestipulante3", true, true); + predicate = predicate11; + predicate3 = predicate11; + predicate10 = predicate; + } + estipulante1.Nome = estipulantes6.Find(predicate10).Nome; + estipulantes5.Add(estipulante1); + } + sqlDataReader.GetFieldValue("idestipulante4", true, true); + if (sqlDataReader.GetFieldValue("idestipulante4", true, true) != 0) + { + List estipulantes7 = estipulantes; + Estipulante nome2 = new Estipulante(); + List estipulantes8 = Auxiliar.Estipulantes; + Predicate predicate12 = predicate4; + if (predicate12 == null) + { + Predicate predicate13 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue("idestipulante4", true, true); + predicate = predicate13; + predicate4 = predicate13; + predicate12 = predicate; + } + nome2.Nome = estipulantes8.Find(predicate12).Nome; + estipulantes7.Add(nome2); + } + sqlDataReader.GetFieldValue("idestipulante5", true, true); + if (sqlDataReader.GetFieldValue("idestipulante5", true, true) != 0) + { + List estipulantes9 = estipulantes; + Estipulante estipulante2 = new Estipulante(); + List estipulantes10 = Auxiliar.Estipulantes; + Predicate predicate14 = predicate5; + if (predicate14 == null) + { + Predicate predicate15 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue("idestipulante5", true, true); + predicate = predicate15; + predicate5 = predicate15; + predicate14 = predicate; + } + estipulante2.Nome = estipulantes10.Find(predicate14).Nome; + estipulantes9.Add(estipulante2); + } + if (estipulantes.Count > 0) + { + List estipulantes11 = estipulantes; + str = string.Join(" | ", + from estipulante in estipulantes11 + select estipulante.Nome); + } + else + { + str = ""; + } + string str2 = str; + long num = sqlDataReader.GetFieldValue("IdDocumento", true, true); + vendedorParcelas = documentos.Find((Documento d) => d.Id == num); + if (vendedorParcelas == null) + { + long num1 = sqlDataReader.GetFieldValue("IdControle", true, true); + long fieldValue2 = sqlDataReader.GetFieldValue("IdEmpresa", true, true); + Documento documento1 = documentos.Find((Documento p) => p.Controle.Id == num1); + if (documento1 != null) + { + itensAtivo = documento1.ItensAtivo; + } + else + { + itensAtivo = null; + } + List items = itensAtivo; + if (items == null) + { + items = await this.BuscaItemsPorIdControle(num1); + } + List items1 = items; + fieldValue1 = new Documento() + { + Id = num + }; + Documento documento2 = fieldValue1; + Controle controle = new Controle() + { + Id = num1, + IdEmpresa = fieldValue2 + }; + Controle controle1 = controle; + Cliente cliente = new Cliente() + { + Id = sqlDataReader.GetFieldValue("IdCliente", true, true), + Nome = sqlDataReader.GetFieldValue("NomeCliente", true, true), + Documento = sqlDataReader.GetFieldValue("DocumentoCliente", true, true), + Pasta = sqlDataReader.GetFieldValue("PastaCliente", true, true) + }; + bool? fieldValue3 = sqlDataReader.GetFieldValue("MalaDireta", true, true); + cliente.MalaDireta = new bool?(fieldValue3.GetValueOrDefault(true)); + ObservableCollection observableCollection = new ObservableCollection(); + ClienteTelefone clienteTelefone = new ClienteTelefone() + { + Id = sqlDataReader.GetFieldValue("IdTelefone", true, true), + Prefixo = sqlDataReader.GetFieldValue("Prefixo", true, true), + Numero = sqlDataReader.GetFieldValue("Numero", true, true) + }; + observableCollection.Add(clienteTelefone); + cliente.Telefones = observableCollection; + ObservableCollection observableCollection1 = new ObservableCollection(); + ClienteEmail clienteEmail = new ClienteEmail() + { + Id = sqlDataReader.GetFieldValue("IdEMail", true, true), + Email = sqlDataReader.GetFieldValue("Email", true, true) + }; + observableCollection1.Add(clienteEmail); + cliente.Emails = observableCollection1; + controle1.Cliente = cliente; + Controle controle2 = controle; + Ramo ramo = new Ramo() + { + Id = sqlDataReader.GetFieldValue("IdRamo", true, true), + Nome = sqlDataReader.GetFieldValue("NomeRamo", true, true) + }; + controle2.Ramo = ramo; + Controle controle3 = controle; + Seguradora seguradora = new Seguradora() + { + Id = sqlDataReader.GetFieldValue("IdCiaSeg", true, true), + Nome = sqlDataReader.GetFieldValue("NomeCia", true, true), + NomeSocial = sqlDataReader.GetFieldValue("NomeSocialCia", true, true) + }; + controle3.Seguradora = seguradora; + Controle controle4 = controle; + flag3 = await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "IdProduto"); + Controle controle5 = controle4; + if (flag3) + { + produto = null; + } + else + { + produto = new Gestor.Model.Domain.Seguros.Produto(); + ((DomainBase)produto).Id = sqlDataReader.GetFieldValue("IdProduto", true, true); + ((Gestor.Model.Domain.Seguros.Produto)produto).Nome = sqlDataReader.GetFieldValue("NomeProduto", true, true); + } + controle5.Produto = (Gestor.Model.Domain.Seguros.Produto)produto; + documento2.Controle = controle; + Documento documento3 = fieldValue1; + bool flag5 = await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "IdEstipulante"); + Documento documento4 = documento3; + if (flag5) + { + obj = null; + } + else + { + obj = new Estipulante(); + ((DomainBase)obj).Id = sqlDataReader.GetFieldValue("IdEstipulante", true, true); + ((Estipulante)obj).Nome = sqlDataReader.GetFieldValue("NomeEstipulante", true, true); + } + documento4.Estipulante1 = (Estipulante)obj; + fieldValue1.Estipulantes = str2; + Documento documento5 = fieldValue1; + bool flag6 = await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "IdStatus"); + Documento documento6 = documento5; + if (flag6) + { + statu = null; + } + else + { + statu = new Status(); + ((DomainBase)statu).Id = sqlDataReader.GetFieldValue("IdStatus", true, true); + ((Status)statu).Nome = sqlDataReader.GetFieldValue("NomeStatus", true, true); + } + documento6.Status = (Status)statu; + fieldValue1.TipoRecebimento = new TipoRecebimento?(sqlDataReader.GetFieldValue("TipoRecebimento", true, true)); + fieldValue1.Tipo = sqlDataReader.GetFieldValue("Tipo", true, true); + fieldValue1.NegocioCorretora = new NegocioCorretora?(negocioCorretora1); + fieldValue1.Situacao = tipoSeguro; + Documento valueOrDefault = fieldValue1; + fieldValue3 = sqlDataReader.GetFieldValue("ApoliceConferida", true, true); + valueOrDefault.ApoliceConferida = fieldValue3.GetValueOrDefault(); + Documento valueOrDefault1 = fieldValue1; + fieldValue3 = sqlDataReader.GetFieldValue("PropostaAssinada", true, true); + valueOrDefault1.PropostaAssinada = fieldValue3.GetValueOrDefault(); + fieldValue1.Proposta = sqlDataReader.GetFieldValue("Proposta", true, true); + fieldValue1.Apolice = sqlDataReader.GetFieldValue("Apolice", true, true); + fieldValue1.PropostaEndosso = sqlDataReader.GetFieldValue("PropostaEndosso", true, true); + fieldValue1.Endosso = sqlDataReader.GetFieldValue("Endosso", true, true); + fieldValue1.Comissao = sqlDataReader.GetFieldValue("Comissao", true, true); + fieldValue1.PremioLiquido = sqlDataReader.GetFieldValue("PremioLiquido", true, true); + Documento valueOrDefault2 = fieldValue1; + fieldValue3 = sqlDataReader.GetFieldValue("AdicionalComissao", true, true); + valueOrDefault2.AdicionalComiss = fieldValue3.GetValueOrDefault(); + fieldValue1.PremioAdicional = sqlDataReader.GetFieldValue("PremioAdicional", true, true); + fieldValue1.PremioTotal = sqlDataReader.GetFieldValue("PremioTotal", true, true); + fieldValue1.NumeroParcelas = sqlDataReader.GetFieldValue("NumeroParcelas", true, true); + fieldValue1.Vigencia1 = sqlDataReader.GetFieldValue("VigenciaInicial", true, true); + fieldValue1.Vigencia2 = sqlDataReader.GetFieldValue("VigenciaFinal", true, true); + fieldValue1.Emissao = sqlDataReader.GetFieldValue("Emissao", true, true); + fieldValue1.Remessa = sqlDataReader.GetFieldValue("Remessa", true, true); + fieldValue1.DataControle = sqlDataReader.GetFieldValue("DataControleDocumento", true, true); + fieldValue1.DataCriacao = sqlDataReader.GetFieldValue("DataCriacao", true, true); + fieldValue1.Pasta = sqlDataReader.GetFieldValue("PastaDocumento", true, true); + Documento documento7 = fieldValue1; + flag = await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "IdBanco"); + Documento documento8 = documento7; + if (flag) + { + banco = null; + } + else + { + banco = new Banco(); + ((Banco)banco).Id = sqlDataReader.GetFieldValue("IdBanco", true, true); + ((Banco)banco).Nome = sqlDataReader.GetFieldValue("NomeBanco", true, true); + } + documento8.Banco = (Banco)banco; + fieldValue1.Agencia = sqlDataReader.GetFieldValue("Agencia", true, true); + fieldValue1.Conta = sqlDataReader.GetFieldValue("Conta", true, true); + fieldValue1.ItensAtivo = items1; + vendedorParcelas = fieldValue1; + documento2 = null; + controle4 = null; + controle = null; + documento3 = null; + documento5 = null; + documento7 = null; + fieldValue1 = null; + if (flag4 & buscaAssinaturas) + { + List statusDocumentoAssinados1 = await this.BuscaStatusAssinadosPorIdDocumento(vendedorParcelas.Id); + string str3 = (vendedorParcelas.Tipo == 0 ? "PROPOSTA" : "PEDIDO DE ENDOSSO"); + statusDocumentoAssinados1.ForEach((StatusDocumentoAssinado a) => { + if (a.Documento.ToUpper() == str3 || a.Documento.ToUpper().Contains(str3)) + { + a.Selecionado = true; + } + }); + List statusDocumentoAssinados2 = statusDocumentoAssinados1; + StatusDocumentoAssinado statusDocumentoAssinado = statusDocumentoAssinados2.FirstOrDefault((StatusDocumentoAssinado a) => a.Selecionado); + Documento documento9 = vendedorParcelas; + if (statusDocumentoAssinados1 == null || statusDocumentoAssinados1.Count <= 0) + { + statusDocumentoAssinados = null; + } + else + { + statusDocumentoAssinados = statusDocumentoAssinados1; + } + documento9.Assinaturas = statusDocumentoAssinados; + Documento documento10 = vendedorParcelas; + flag2 = (statusDocumentoAssinado != null ? statusDocumentoAssinado.Status == StatusAssinatura.Assinado : false); + documento10.AssinadaSiggner = flag2; + Documento documento11 = vendedorParcelas; + statusAssinatura = (statusDocumentoAssinado != null ? statusDocumentoAssinado.Status : StatusAssinatura.NaoEnviado); + documento11.StatusAssinatura = statusAssinatura; + } + documentos.Add(vendedorParcelas); + items1 = null; + } + if (vendedorParcelas.VendedorPrincipal == null || vendedorParcelas.VendedorPrincipal.Id == vendedor1.Id) + { + fieldValue1 = vendedorParcelas; + flag = await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "IdVendedor"); + Documento documento12 = fieldValue1; + if (flag) + { + vendedor = null; + } + else + { + vendedor = new Vendedor(); + ((DomainBase)vendedor).Id = sqlDataReader.GetFieldValue("IdVendedor", true, true); + ((Vendedor)vendedor).Nome = sqlDataReader.GetFieldValue("NomeVendedor", true, true); + } + documento12.VendedorPrincipal = (Vendedor)vendedor; + fieldValue1 = null; + } + if (vendedorParcelas.Controle.Cliente.Telefones != null) + { + long num2 = sqlDataReader.GetFieldValue("IdTelefone", true, true); + if (vendedorParcelas.Controle.Cliente.Telefones.FirstOrDefault((ClienteTelefone t) => t.Id == num2) == null) + { + ObservableCollection telefones = vendedorParcelas.Controle.Cliente.Telefones; + ClienteTelefone clienteTelefone1 = new ClienteTelefone() + { + Id = num2, + Prefixo = sqlDataReader.GetFieldValue("Prefixo", true, true), + Numero = sqlDataReader.GetFieldValue("Numero", true, true) + }; + telefones.Add(clienteTelefone1); + } + } + if (vendedorParcelas.Controle.Cliente.Emails != null) + { + long num3 = sqlDataReader.GetFieldValue("IdEmail", true, true); + if (vendedorParcelas.Controle.Cliente.Emails.FirstOrDefault((ClienteEmail t) => t.Id == num3) == null) + { + ObservableCollection emails = vendedorParcelas.Controle.Cliente.Emails; + ClienteEmail clienteEmail1 = new ClienteEmail() + { + Id = num3, + Email = sqlDataReader.GetFieldValue("Email", true, true) + }; + emails.Add(clienteEmail1); + } + } + List tipoVendedor = filtro.TipoVendedor; + if (tipoVendedor != null) + { + count1 = tipoVendedor.Count > 0; + } + else + { + count1 = false; + } + if (!count1) + { + List vendedores = filtro.Vendedores; + if (vendedores != null) + { + flag1 = vendedores.Count > 0; + } + else + { + flag1 = false; + } + if (!flag1) + { + if (vendedorParcelas.Pagamentos == null) + { + vendedorParcelas.Pagamentos = new List(); + } + long fieldValue4 = sqlDataReader.GetFieldValue("IdTipoVendedor", true, true); + long num4 = sqlDataReader.GetFieldValue("IdVendedor", true, true); + if (vendedorParcelas.Pagamentos.Find((VendedorParcela vps) => { + if (vps.TipoVendedor.Id != fieldValue4) + { + return false; + } + return vps.Vendedor.Id == num4; + }) == null) + { + List pagamentos = vendedorParcelas.Pagamentos; + VendedorParcela vendedorParcela1 = new VendedorParcela() + { + PorcentagemRepasse = new decimal?(sqlDataReader.GetFieldValue("PorcentagemRepasse", true, true)) + }; + TipoVendedor tipoVendedor1 = new TipoVendedor() + { + Id = fieldValue4, + Descricao = sqlDataReader.GetFieldValue("DescricaoTipovendedor", true, true) + }; + vendedorParcela1.TipoVendedor = tipoVendedor1; + Vendedor vendedor2 = new Vendedor() + { + Id = num4, + Nome = sqlDataReader.GetFieldValue("NomeVendedor", true, true) + }; + vendedorParcela1.Vendedor = vendedor2; + pagamentos.Add(vendedorParcela1); + } + } + } + str2 = null; + vendedorParcelas = null; + } + } + } + } + sqlCommand = null; + List nums = filtro.TipoVendedor; + if (nums != null) + { + count2 = nums.Count > 0; + } + else + { + count2 = false; + } + if (!count2) + { + List vendedores1 = filtro.Vendedores; + if (vendedores1 != null) + { + count3 = vendedores1.Count > 0; + } + else + { + count3 = false; + } + if (!count3) + { + goto Label0; + } + } + foreach (Documento documento13 in documentos) + { + vendedorParcelas = documento13; + List vendedorParcelas1 = await this.BuscaVendedoresPorIdDocumento(documento13.Id, documento13.Controle.IdEmpresa); + vendedorParcelas.Pagamentos = vendedorParcelas1; + vendedorParcelas = null; + } + Label0: + List documentos1 = documentos; + documentos1.ForEach((Documento d) => { + decimal? nullable2; + decimal? porcentagemRepasse; + d.Vendedores = ( + from tipo in d.Pagamentos + orderby tipo.TipoVendedor.Id + select tipo into v + select v.Vendedor).ToList(); + Documento documento = d; + VendedorParcela vendedorParcela = d.Pagamentos.FirstOrDefault((VendedorParcela p) => { + long? nullable; + long id = p.Vendedor.Id; + Vendedor vendedorPrincipal = d.VendedorPrincipal; + nullable = (vendedorPrincipal != null ? new long?(vendedorPrincipal.Id) : null); + long? nullable1 = nullable; + return id == nullable1.GetValueOrDefault() & nullable1.HasValue; + }); + if (vendedorParcela != null) + { + porcentagemRepasse = vendedorParcela.PorcentagemRepasse; + } + else + { + nullable2 = null; + porcentagemRepasse = nullable2; + } + nullable2 = porcentagemRepasse; + documento.PercentualRepasse = new decimal?(nullable2.GetValueOrDefault()); + }); + } + sqlConnection = null; + } + sessionFactory = null; + List documentos2 = documentos; + documentos = null; + sqlQueryCondition = null; + vendedor1 = null; + return documentos2; + } + + public async Task> BuscaDocumentosPorVigencia(Filtros filtro, bool buscaAssinaturas = false, bool painelBi = false) + { + string str = "CAST(d.vigencia1 AS DATE)"; + string referencia = filtro.Referencia; + if (referencia == "EMISSÃO") + { + str = "CAST(d.emissao AS DATE)"; + } + else if (referencia == "TRANSMISSÃO PROPOSTA") + { + str = "CAST(d.remessa AS DATE)"; + } + else if (referencia == "DATA CRIAÇÃO" || referencia == "DATA DE CADASTRO") + { + str = "CAST(d.cri_data AS DATE)"; + } + List condicaos = this.CriaCondicaoDocumento(filtro, str); + Condicao condicao = new Condicao() + { + Campo = "d.TipoRecebimento", + Valores = 1.CriarValor() + }; + condicaos.Add(condicao); + List condicaos1 = new List(); + Condicao condicao1 = new Condicao() + { + Campo = "d.Excluido", + Valores = null, + Grupo = 1, + Operacao = Operacao.Or + }; + condicaos1.Add(condicao1); + Condicao condicao2 = new Condicao() + { + Campo = "d.Excluido", + Valores = "0".CriarValor(), + Grupo = 1, + Operacao = Operacao.Or + }; + condicaos1.Add(condicao2); + condicaos.AddRange(condicaos1); + return await this.BuscaDocumentosPorCondicao(filtro, condicaos, buscaAssinaturas); + } + + private async Task> BuscaFechamento(Filtros filtro) + { + NegocioCorretora negocioCorretora; + bool count; + object connection; + long num; + long num1; + decimal num2; + decimal num3; + decimal num4; + decimal num5; + NegocioCorretora negocioCorretora1; + bool flag; + List fechamentos = new List(); + string str2 = "CAST(d.vigencia1 AS DATE)"; + string str3 = "CAST(f.vigenciai AS DATE)"; + if (filtro.Referencia == "EMISSÃO") + { + str2 = "CAST(d.emissao AS DATE)"; + str3 = "CAST(f.emissao AS DATE)"; + } + List condicaos = this.CriaCondicaoDocumento(filtro, str2); + List condicaos1 = this.CriaCondicaoDocumento(filtro, str3); + List condicaos2 = this.CriaCondicaoDocumento(filtro, "CAST(d.vigencia1 AS DATE)"); + Condicao condicao = new Condicao() + { + Campo = "d.TipoRecebimento", + Valores = 1.CriarValor() + }; + condicaos.Add(condicao); + List condicaos3 = new List(); + Condicao condicao1 = new Condicao() + { + Campo = "d.Excluido", + Valores = null, + Grupo = 1, + Operacao = Operacao.Or + }; + condicaos3.Add(condicao1); + Condicao condicao2 = new Condicao() + { + Campo = "d.Excluido", + Valores = "0".CriarValor(), + Grupo = 1, + Operacao = Operacao.Or + }; + condicaos3.Add(condicao2); + List condicaos4 = condicaos3; + condicaos.AddRange(condicaos4); + condicaos1.AddRange(condicaos4); + condicaos2.AddRange(condicaos4); + string str4 = ""; + List tipoVendedor = filtro.TipoVendedor; + if (tipoVendedor != null) + { + count = tipoVendedor.Count > 0; + } + else + { + count = false; + } + if (!count) + { + List vendedores = filtro.Vendedores; + if (vendedores != null) + { + flag = vendedores.Count > 0; + } + else + { + flag = false; + } + if (flag) + { + goto Label1; + } + str4 = "OUTER APPLY (SELECT TOP 1 idvendedor FROM vendedorparcela vp WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor = 1) vp"; + goto Label0; + } + Label1: + str4 = "INNER JOIN vendedorparcela vp ON d.iddocumento = vp.iddocumento"; + Label0: + SqlQueryCondition sqlQueryCondition = condicaos.CreateParameters(0); + SqlQueryCondition sqlQueryCondition1 = condicaos1.CreateParameters(sqlQueryCondition.Parametros.Count); + using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) + { + SessionFactoryImpl sessionFactoryImpl = sessionFactory; + if (sessionFactoryImpl != null) + { + connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + Auxiliar.CriarAuxiliar(sqlCommand, false); + string str5 = string.Concat("SELECT DISTINCT c.IdEmpresa, d.IdControle, d.IdDocumento Id, d.Pr_Total Total, d.Pr_liq Liquido, d.Pr_Adic Adicional, ISNULL(d.com01, 0.00) Comissao, ISNULL(d.adinacomis, '0') AdinaComis, c.IdRamo, c.IdCiaSeg, c.IdProduto, CAST(d.Tipo AS INTEGER) Tipo, d.IdEstipulante, d.IdNegocio, d.Situacao, d.NegocioCorretora, vp.IdVendedor FROM documento d INNER JOIN controle c ON c.IdControle = d.IdControle ", str4, " WHERE "); + string str6 = string.Concat("SELECT DISTINCT c.IdEmpresa, d.IdControle, p.IdParcela Id, p.Valor Total, p.ValorLF Liquido, 0 Adicional, p.Comiss Comissao, '0' AdinaComis, c.IdRamo, c.IdCiaSeg, c.IdProduto, 2 Tipo, d.IdEstipulante, d.IdNegocio, d.Situacao, d.NegocioCorretora, vp.IdVendedor FROM fatura f INNER JOIN parcela p ON p.idparcela = f.idparcela INNER JOIN documento d ON d.iddocumento = p.iddocumento INNER JOIN controle c ON c.idcontrole = d.idcontrole ", str4, " WHERE "); + sqlCommand.CommandTimeout = 1000; + SqlCommand sqlCommand1 = sqlCommand; + string[] strArrays = new string[] { str5, " ", sqlQueryCondition.Condicao, " UNION ", str6, " ", sqlQueryCondition1.Condicao }; + sqlCommand1.CommandText = string.Concat(strArrays); + sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray()); + sqlCommand.Parameters.AddRange(sqlQueryCondition1.Parametros.ToArray()); + using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) + { + List fechamentos1 = new List(); + decimal num6 = new decimal(); + while (true) + { + if (!await sqlDataReader.ReadAsync()) + { + break; + } + bool flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("IdCiaSeg")); + if (!flag1) + { + flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("IdRamo")); + } + if (!flag1) + { + long item = (long)sqlDataReader["IdEmpresa"]; + long item1 = (long)sqlDataReader["IdCiaSeg"]; + long item2 = (long)sqlDataReader["IdRamo"]; + flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("IdEstipulante")); + num = (flag1 ? (long)0 : (long)sqlDataReader["IdEstipulante"]); + long num7 = num; + flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("IdVendedor")); + num1 = (flag1 ? (long)0 : (long)sqlDataReader["IdVendedor"]); + long id = num1; + flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("Total")); + num2 = (flag1 ? decimal.Zero : (decimal)sqlDataReader["Total"]); + decimal num8 = num2; + flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("Liquido")); + num3 = (flag1 ? decimal.Zero : (decimal)sqlDataReader["Liquido"]); + decimal num9 = num3; + flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("Adicional")); + num4 = (flag1 || sqlDataReader["AdinaComis"].ToString() == "0" ? decimal.Zero : (decimal)sqlDataReader["Adicional"]); + decimal num10 = num4; + flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("Comissao")); + num5 = (flag1 ? decimal.Zero : (decimal)sqlDataReader["Comissao"]); + decimal num11 = num5; + int item3 = (int)sqlDataReader["Tipo"]; + if (!await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("negociocorretora"))) + { + negocioCorretora = (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), sqlDataReader["negociocorretora"].ToString()); + } + else + { + flag1 = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), sqlDataReader["situacao"].ToString()) == TipoSeguro.Renovacao; + if (flag1) + { + flag1 = !await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idnegocio")); + } + negocioCorretora1 = (!flag1 || !(sqlDataReader["idnegocio"].ToString() == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio); + negocioCorretora = negocioCorretora1; + } + NegocioCorretora negocioCorretora2 = negocioCorretora; + if (filtro.Negocio == null || filtro.Negocio.Count <= 0 || filtro.Negocio.Any((long n) => (int)n == (int)negocioCorretora2)) + { + if (id == 0) + { + id = Auxiliar.Vendedores.FirstOrDefault((Vendedor v) => { + if (v.IdEmpresa != item) + { + return false; + } + return v.Corretora; + }).Id; + } + decimal num12 = (num9 + num10) * num11 * new decimal(1, 0, 0, false, 2); + num6 += num8; + for (int i = 0; i < 4; i++) + { + long num13 = (long)0; + switch (i) + { + case 0: + { + num13 = item1; + break; + } + case 1: + { + num13 = item2; + break; + } + case 2: + { + num13 = num7; + break; + } + case 3: + { + num13 = id; + break; + } + } + if (num13 != 0) + { + Fechamento fechamento4 = fechamentos1.FirstOrDefault((Fechamento a) => { + if (a.Entidade != i) + { + return false; + } + return a.Id == num13; + }); + if (fechamento4 == null) + { + fechamento4 = new Fechamento(); + } + Fechamento fechamento5 = fechamento4; + Fechamento premioTotal = fechamento5; + premioTotal.PremioTotal = premioTotal.PremioTotal + num8; + Fechamento premioLiquido = fechamento5; + premioLiquido.PremioLiquido = premioLiquido.PremioLiquido + num9; + Fechamento fechamento6 = fechamento5; + fechamento6.Fechada = fechamento6.Fechada + num11; + Fechamento gerada = fechamento5; + gerada.Gerada = gerada.Gerada + num12; + switch (item3) + { + case 0: + { + Fechamento apolice = fechamento5; + apolice.Apolice = apolice.Apolice + 1; + break; + } + case 1: + { + Fechamento endosso = fechamento5; + endosso.Endosso = endosso.Endosso + 1; + break; + } + case 2: + { + Fechamento fatura = fechamento5; + fatura.Fatura = fatura.Fatura + 1; + break; + } + } + if (fechamento5.Id == 0) + { + fechamento5.Entidade = i; + fechamento5.Id = num13; + fechamentos1.Add(fechamento5); + } + } + } + } + } + } + fechamentos1.ForEach((Fechamento f) => { + string nome; + string str; + string nome1; + string str1; + switch (f.Entidade) + { + case 0: + { + Fechamento fechamento = f; + Seguradora seguradora = Auxiliar.Seguradoras.Find((Seguradora s) => s.Id == f.Id); + if (seguradora != null) + { + nome = seguradora.Nome; + } + else + { + nome = null; + } + fechamento.Nome = nome; + break; + } + case 1: + { + Fechamento fechamento1 = f; + Ramo ramo = Auxiliar.Ramos.Find((Ramo r) => r.Id == f.Id); + if (ramo != null) + { + str = ramo.Nome; + } + else + { + str = null; + } + fechamento1.Nome = str; + break; + } + case 2: + { + Fechamento fechamento2 = f; + Estipulante estipulante = Auxiliar.Estipulantes.Find((Estipulante e) => e.Id == f.Id); + if (estipulante != null) + { + nome1 = estipulante.Nome; + } + else + { + nome1 = null; + } + fechamento2.Nome = nome1; + break; + } + case 3: + { + Fechamento fechamento3 = f; + Vendedor vendedor = Auxiliar.Vendedores.Find((Vendedor v) => v.Id == f.Id); + if (vendedor != null) + { + str1 = vendedor.Nome; + } + else + { + str1 = null; + } + fechamento3.Nome = str1; + break; + } + } + Fechamento fechada = f; + fechada.Fechada = fechada.Fechada / f.Apolice + f.Fatura + f.Endosso; + f.Mix = (f.PremioTotal * new decimal(100)) / num6; + }); + List fechamentos2 = fechamentos1; + foreach (IGrouping nums in + from g in fechamentos2 + group g by g.Entidade) + { + await this.ContaRegistros(nums.Key, fechamentos1, filtro, condicaos2); + await this.SomaComissaoPaga(nums.Key, fechamentos1, filtro, condicaos2); + await this.SomaComissaoRecebida(nums.Key, fechamentos1, filtro, condicaos2); + } + fechamentos.AddRange(fechamentos1); + fechamentos1 = null; + } + sqlDataReader = null; + } + sqlCommand = null; + } + sqlConnection = null; + } + sessionFactory = null; + List fechamentos3 = fechamentos; + fechamentos = null; + condicaos2 = null; + return fechamentos3; + } + + private async Task> BuscaItemsPorIdControle(long idControle) + { + object connection; + List items = new List(); + using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) + { + SessionFactoryImpl sessionFactoryImpl = sessionFactory; + if (sessionFactoryImpl != null) + { + connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandTimeout = 1000; + sqlCommand.CommandText = "SELECT i.iditem,i.descricao FROM item i INNER JOIN documento d ON d.iddocumento = i.iddocumento WHERE d.idcontrole = @controle AND i.idsubstituido IS NULL AND (i.cancelado IS NULL OR i.cancelado = 0)"; + sqlCommand.Parameters.Add("@controle", SqlDbType.BigInt).Value = idControle; + using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) + { + while (true) + { + if (!await sqlDataReader.ReadAsync()) + { + break; + } + List items1 = items; + Item item = new Item() + { + Id = (long)sqlDataReader["iditem"], + Descricao = sqlDataReader["descricao"].ToString() + }; + items1.Add(item); + } + } + sqlDataReader = null; + } + sqlCommand = null; + } + sqlConnection = null; + } + sessionFactory = null; + List items2 = items; + items = null; + return items2; + } + + public List BuscarDocumentoPorEstipulante(long id) + { + List list = ( + from x in base.All() + where x.Estipulante1.Id == id || x.Estipulante2.Id == id || x.Estipulante3.Id == id || x.Estipulante4.Id == id || x.Estipulante5.Id == id + select x).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public List BuscarDocumentoPorStatus(long id) + { + List list = ( + from x in base.All() + where x.Status.Id == id + select x).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public string BuscarLogAntigo(long id, string conn) + { + object connection; + string str = ""; + List condicaos = new List() + { + new Condicao() + { + Campo = "id", + Valores = id.CriarValor() + }, + new Condicao() + { + Campo = "idname", + Valores = "iddocumento".CriarValor() + } + }; + this._unitOfWork.CriarAuxiliar(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + string str1 = "oldbacklog"; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = "SELECT TOP 1 * FROM controlelog"; + SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); + sqlDataReader.Read(); + string str2 = sqlDataReader["bdname"].ToString(); + str1 = sqlDataReader["tabela"].ToString(); + sqlDataReader.Close(); + if (sqlConnection.Database != str2) + { + conn = conn.Replace(sqlConnection.Database, str2); + } + } + } + DataTable dataTable = new DataTable(); + using (SqlConnection sqlConnection1 = new SqlConnection(conn)) + { + sqlConnection1.Open(); + using (SqlCommand sqlCommand1 = sqlConnection1.CreateCommand()) + { + sqlCommand1.CommandTimeout = 15000; + dataTable = sqlCommand1.Select(condicaos.CreateParameters(0), string.Concat("SELECT b.* FROM ", str1, " b WHERE"), ""); + } + } + if (dataTable == null || dataTable.Rows.Count == 0) + { + return ""; + } + if (dataTable != null) + { + dataTable.AsEnumerable().OrderBy((DataRow x) => x.Field("idbacklog")).ToList().ForEach((DataRow x) => { + str = string.Concat(new string[] { str, "
(", x.Field("data").ToString(), ") ", Auxiliar.Usuarios.Find((Usuario u) => u.Id == x.Field("idusuario")).Nome, "
" }); + str = string.Concat(str, "", x.Field("historico").ToString().Replace(Environment.NewLine, "
"), ""); + }); + } + return str; + } + + public List BuscarPlanilhaCompletaProspeccao(List ids) + { + object connection; + List nums = null; + if (ids == null || ids.Count == 0) + { + return new List(); + } + DataTable dataTable = new DataTable(); + DataTable dataTable1 = new DataTable(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + Auxiliar.CriarAuxiliar(sqlCommand, false); + for (List i = ids; i.Count > 0; i = nums) + { + List list = i.Take(2100).ToList(); + string str1 = string.Concat(" AND va.idvenctoaleatorio IN (", string.Join(",", list), ")"); + DataTable dataTable2 = new DataTable(); + string str2 = string.Concat("SELECT DISTINCT * FROM venctoaleatorio va LEFT OUTER JOIN tarefa ta on va.idtarefa = ta.id WHERE 1=1 ", str1, ";"); + sqlCommand.CommandText = str2 ?? ""; + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable2); + } + dataTable.Merge(dataTable2); + nums = (list.Count < 2100 ? new List() : i.Except(list).ToList()); + } + } + } + if (dataTable.Rows.Count == 0) + { + return new List(); + } + List planilhaCompletas = new List(); + dataTable.AsEnumerable().ToList().ForEach((DataRow x) => { + DateTime? nullable; + string str; + DateTime? nullable1; + DateTime? nullable2; + PlanilhaCompleta planilhaCompletum = new PlanilhaCompleta() + { + NumeroApolice = "PROSPECÇÃO", + Status = (x.Field("situacao") == null || !(x.Field("situacao").ToString() != "") || string.IsNullOrWhiteSpace(x.Field("situacao").ToString()) ? null : (StatusProspeccao)Enum.Parse(typeof(StatusProspeccao), x.Field("situacao").ToString()).GetDescription()) + }; + DateTime? nullable3 = x.Field("finalcontrato"); + if (nullable3.HasValue) + { + nullable = x.Field("finalcontrato"); + } + else + { + nullable3 = null; + nullable = nullable3; + } + planilhaCompletum.VigenciaFinal = nullable; + DataRow dataRow = dataTable1.AsEnumerable().FirstOrDefault((DataRow e) => e.Field("iddocumento") == x.Field("iddocumento")); + if (dataRow != null) + { + str = dataRow.Field("nome"); + } + else + { + str = null; + } + planilhaCompletum.Estipulante = str; + planilhaCompletum.Vendedor = (x.Field("idvendedor") != null ? Auxiliar.Vendedores.FirstOrDefault((Vendedor p) => p.Id == x.Field("idvendedor")).Nome : null); + planilhaCompletum.NomeCliente = x.Field("nome"); + nullable3 = x.Field("dtnascimento"); + if (nullable3.HasValue) + { + nullable1 = x.Field("dtnascimento"); + } + else + { + nullable3 = null; + nullable1 = nullable3; + } + planilhaCompletum.NascimentoCliente = nullable1; + planilhaCompletum.DocumentoCliente = x.Field("cpfcnpj"); + planilhaCompletum.Prefixo1 = x.Field("ddd"); + planilhaCompletum.Telefone1 = x.Field("fone"); + planilhaCompletum.Prefixo2 = x.Field("ddd2"); + planilhaCompletum.Telefone2 = x.Field("fone2"); + planilhaCompletum.Email1 = x.Field("email"); + planilhaCompletum.DescricaoItem = x.Field("item"); + planilhaCompletum.ObsProspeccao = x.Field("obs"); + planilhaCompletum.TipoProspeccao = x.Field("tipoprospeccao"); + planilhaCompletum.TituloTarefa = x.Field("titulo"); + planilhaCompletum.DescricaoTarefa = x.Field("descricao"); + nullable3 = x.Field("agendamento"); + if (nullable3.HasValue) + { + nullable2 = x.Field("agendamento"); + } + else + { + nullable3 = null; + nullable2 = nullable3; + } + planilhaCompletum.AgendamentoTarefa = nullable2; + planilhaCompletas.Add(planilhaCompletum); + }); + return planilhaCompletas; + } + + private async Task> BuscaStatusAssinadosPorIdDocumento(long idDocumento) + { + object connection; + DateTime? nullable; + Usuario usuario1; + Func func = null; + List statusDocumentoAssinados = new List(); + using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) + { + SessionFactoryImpl sessionFactoryImpl = sessionFactory; + if (sessionFactoryImpl != null) + { + connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandTimeout = 1000; + sqlCommand.CommandText = "SELECT a.idnewarquivodigital,a.descricao,ISNULL(s.Status ,3) status,s.assinado,a.iddocumento,s.id,s.usuarioid,s.enviado FROM newarquivodigital a LEFT JOIN ArquivoParaAssinatura s ON a.idnewarquivodigital = s.indiceid WHERE a.iddocumento = @documento AND (a.excluido = 0 OR a.excluido IS NULL)"; + sqlCommand.Parameters.Add("@documento", SqlDbType.BigInt).Value = idDocumento; + using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) + { + while (true) + { + if (!await sqlDataReader.ReadAsync()) + { + break; + } + List statusDocumentoAssinados1 = statusDocumentoAssinados; + StatusDocumentoAssinado statusDocumentoAssinado = new StatusDocumentoAssinado() + { + Id = (long)sqlDataReader["idnewarquivodigital"], + Documento = sqlDataReader["descricao"].ToString(), + Status = (StatusAssinatura)((int)sqlDataReader["status"]) + }; + StatusDocumentoAssinado statusDocumentoAssinado1 = statusDocumentoAssinado; + bool flag = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("enviado")); + StatusDocumentoAssinado statusDocumentoAssinado2 = statusDocumentoAssinado1; + if (flag) + { + nullable = null; + } + else + { + nullable = new DateTime?((DateTime)sqlDataReader["enviado"]); + } + statusDocumentoAssinado2.Envio = nullable; + StatusDocumentoAssinado statusDocumentoAssinado3 = statusDocumentoAssinado; + bool flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("usuarioid")); + StatusDocumentoAssinado statusDocumentoAssinado4 = statusDocumentoAssinado3; + if (flag1) + { + usuario1 = null; + } + else + { + List usuarios = Auxiliar.Usuarios; + Func func1 = func; + if (func1 == null) + { + Func id = (Usuario usuario) => usuario.Id == (long)sqlDataReader["usuarioid"]; + Func func2 = id; + func = id; + func1 = func2; + } + usuario1 = usuarios.FirstOrDefault(func1); + } + statusDocumentoAssinado4.Usuario = usuario1; + statusDocumentoAssinados1.Add(statusDocumentoAssinado); + statusDocumentoAssinados1 = null; + statusDocumentoAssinado1 = null; + statusDocumentoAssinado3 = null; + statusDocumentoAssinado = null; + } + } + } + sqlCommand = null; + } + sqlConnection = null; + } + sessionFactory = null; + List statusDocumentoAssinados2 = statusDocumentoAssinados; + statusDocumentoAssinados = null; + return statusDocumentoAssinados2; + } + + private async Task> BuscaVendedoresPorIdControle(long idControle, long idEmpresa) + { + object connection; + Func func = null; + List vendedorParcelas = new List(); + using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) + { + SessionFactoryImpl sessionFactoryImpl = sessionFactory; + if (sessionFactoryImpl != null) + { + connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandTimeout = 1000; + sqlCommand.CommandText = "SELECT DISTINCT vp.idvendedor,vp.vrep,vp.idtipovendedor FROM vendedorparcela vp INNER JOIN parcela p ON vp.idparcela = p.idparcela INNER JOIN documento d ON d.iddocumento = vp.iddocumento WHERE d.idcontrole = @controle AND p.idsubtipo = 1"; + sqlCommand.Parameters.Add("@controle", SqlDbType.BigInt).Value = idControle; + using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) + { + while (true) + { + if (!await sqlDataReader.ReadAsync()) + { + break; + } + List vendedorParcelas1 = vendedorParcelas; + VendedorParcela vendedorParcela = new VendedorParcela(); + TipoVendedor tipoVendedor = new TipoVendedor() + { + Id = sqlDataReader.GetFieldValue("idtipovendedor", true, true) + }; + vendedorParcela.TipoVendedor = tipoVendedor; + List vendedores = Auxiliar.Vendedores; + Func func1 = func; + if (func1 == null) + { + Func id = (Vendedor vendedor) => vendedor.Id == sqlDataReader.GetFieldValue("idvendedor", true, true); + Func func2 = id; + func = id; + func1 = func2; + } + vendedorParcela.Vendedor = vendedores.FirstOrDefault(func1); + vendedorParcela.PorcentagemRepasse = sqlDataReader.GetFieldValue("vrep", true, true); + vendedorParcelas1.Add(vendedorParcela); + } + List vendedorParcelas2 = vendedorParcelas; + if (!vendedorParcelas2.Any((VendedorParcela v) => v.TipoVendedor.Id == (long)1)) + { + List vendedorParcelas3 = vendedorParcelas; + VendedorParcela vendedorParcela1 = new VendedorParcela() + { + TipoVendedor = new TipoVendedor() + { + Id = (long)1 + }, + Vendedor = Auxiliar.Vendedores.FirstOrDefault((Vendedor v) => { + if (v.IdEmpresa != idEmpresa) + { + return false; + } + return v.Corretora; + }), + PorcentagemRepasse = new decimal?(new decimal()) + }; + vendedorParcelas3.Add(vendedorParcela1); + } + } + } + sqlCommand = null; + } + sqlConnection = null; + } + sessionFactory = null; + List vendedorParcelas4 = vendedorParcelas; + vendedorParcelas = null; + return vendedorParcelas4; + } + + private async Task> BuscaVendedoresPorIdDocumento(long idDocumento, long idEmpresa) + { + object connection; + decimal? nullable; + Func func = null; + List vendedorParcelas = new List(); + using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) + { + SessionFactoryImpl sessionFactoryImpl = sessionFactory; + if (sessionFactoryImpl != null) + { + connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandTimeout = 1000; + sqlCommand.CommandText = "SELECT DISTINCT vp.idvendedor,vp.vrep,vp.idtipovendedor FROM vendedorparcela vp INNER JOIN parcela p ON vp.idparcela = p.idparcela WHERE vp.iddocumento = @documento AND p.idsubtipo = 1"; + sqlCommand.Parameters.Add("@documento", SqlDbType.BigInt).Value = idDocumento; + using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) + { + while (true) + { + if (!await sqlDataReader.ReadAsync()) + { + break; + } + List vendedorParcelas1 = vendedorParcelas; + VendedorParcela vendedorParcela = new VendedorParcela(); + VendedorParcela vendedorParcela1 = vendedorParcela; + TipoVendedor tipoVendedor = new TipoVendedor() + { + Id = (long)sqlDataReader["idtipovendedor"] + }; + vendedorParcela1.TipoVendedor = tipoVendedor; + VendedorParcela vendedorParcela2 = vendedorParcela; + List vendedores = Auxiliar.Vendedores; + Func func1 = func; + if (func1 == null) + { + Func id = (Vendedor vendedor) => vendedor.Id == (long)sqlDataReader["idvendedor"]; + Func func2 = id; + func = id; + func1 = func2; + } + vendedorParcela2.Vendedor = vendedores.FirstOrDefault(func1); + VendedorParcela vendedorParcela3 = vendedorParcela; + bool flag = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("vrep")); + VendedorParcela vendedorParcela4 = vendedorParcela3; + if (flag) + { + nullable = null; + } + else + { + nullable = new decimal?((decimal)sqlDataReader["vrep"]); + } + vendedorParcela4.PorcentagemRepasse = nullable; + vendedorParcelas1.Add(vendedorParcela); + vendedorParcelas1 = null; + vendedorParcela3 = null; + vendedorParcela = null; + } + List vendedorParcelas2 = vendedorParcelas; + if (!vendedorParcelas2.Any((VendedorParcela v) => v.TipoVendedor.Id == (long)1)) + { + List vendedorParcelas3 = vendedorParcelas; + VendedorParcela vendedorParcela5 = new VendedorParcela() + { + TipoVendedor = new TipoVendedor() + { + Id = (long)1 + }, + Vendedor = Auxiliar.Vendedores.FirstOrDefault((Vendedor v) => { + if (v.IdEmpresa != idEmpresa) + { + return false; + } + return v.Corretora; + }), + PorcentagemRepasse = new decimal?(new decimal()) + }; + vendedorParcelas3.Add(vendedorParcela5); + } + } + } + sqlCommand = null; + } + sqlConnection = null; + } + sessionFactory = null; + List vendedorParcelas4 = vendedorParcelas; + vendedorParcelas = null; + return vendedorParcelas4; + } + + private async Task ContaRegistros(int tipo, List fechamentos, Filtros filtro, List condicaoDocumento) + { + object connection; + long num; + bool count; + bool flag; + using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) + { + SessionFactoryImpl sessionFactoryImpl = sessionFactory; + if (sessionFactoryImpl != null) + { + connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + string str = "c.IdCiaSeg"; + string str1 = "COUNT(d.IdDocumento)"; + string str2 = "FROM item i INNER JOIN documento d ON d.IdDocumento = i.IdDocumento INNER JOIN controle c ON c.IdControle = d.IdControle"; + string str3 = "i.idsubstituido IS NULL AND (i.cancelado IS NULL OR i.cancelado = 0) AND"; + switch (tipo) + { + case 1: + { + str = "c.IdRamo"; + break; + } + case 2: + { + str = "d.IdEstipulante"; + break; + } + case 3: + { + str = "vp.IdVendedor"; + break; + } + } + string str4 = ""; + if (tipo != 3) + { + List tipoVendedor = filtro.TipoVendedor; + if (tipoVendedor != null) + { + count = tipoVendedor.Count > 0; + } + else + { + count = false; + } + if (!count) + { + List vendedores = filtro.Vendedores; + if (vendedores != null) + { + flag = vendedores.Count > 0; + } + else + { + flag = false; + } + if (!flag) + { + goto Label0; + } + } + } + str1 = "COUNT(DISTINCT d.IdDocumento)"; + str4 = "INNER JOIN vendedorparcela vp ON d.iddocumento = vp.iddocumento"; + Label0: + SqlQueryCondition sqlQueryCondition = condicaoDocumento.CreateParameters(0); + sqlCommand.CommandTimeout = 1000; + SqlCommand sqlCommand1 = sqlCommand; + string[] condicao = new string[] { "SELECT ", str, " Id,", str1, " Contador ", str2, " ", str4, " WHERE ", str3, " ", sqlQueryCondition.Condicao, " GROUP BY ", str }; + sqlCommand1.CommandText = string.Concat(condicao); + sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray()); + using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) + { + while (true) + { + if (!await sqlDataReader.ReadAsync()) + { + break; + } + bool flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("Id")); + num = (flag1 ? (long)0 : (long)sqlDataReader["Id"]); + long num1 = num; + int item = (int)sqlDataReader["Contador"]; + if (num1 != 0) + { + Fechamento fechamento = fechamentos.FirstOrDefault((Fechamento f) => { + if (f.Entidade != tipo) + { + return false; + } + return f.Id == num1; + }); + if (fechamento != null) + { + Fechamento itens = fechamento; + itens.Itens = itens.Itens + item; + } + } + } + } + sqlDataReader = null; + } + sqlCommand = null; + } + sqlConnection = null; + } + sessionFactory = null; + } + + public int Cotacoes(Filtros filtro) + { + int num; + object connection; + string str = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND u.idempresa = {0}", filtro.IdEmpresa)); + try + { + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = string.Format("SELECT COUNT(r.id) as quantidade from ResultadoCalculo r INNER JOIN usuario u ON u.idusuario = r.IdUsuario where CAST(DataAtualizacao AS DATE) >= '{0:yyyy-MM-dd}' and CAST(DataAtualizacao AS DATE) <= '{1:yyyy-MM-dd}' AND DataExclusao IS NULL AND Calculado = 1 {2};", filtro.Inicio, filtro.Fim, str); + SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); + sqlDataReader.Read(); + num = (sqlDataReader.HasRows ? int.Parse(sqlDataReader["quantidade"].ToString()) : 0); + } + } + } + catch (Exception exception) + { + num = 0; + } + return num; + } + + private List CriaCondicaoDocumento(Filtros filtro, string referencia) + { + bool count; + bool flag; + bool count1; + bool flag1; + bool count2; + bool flag2; + bool count3; + bool flag3; + List condicaos = new List() + { + new Condicao() + { + Campo = referencia, + Valores = filtro.Inicio.CriarValor(), + Operador = Operador.MaiorEIgual + }, + new Condicao() + { + Campo = referencia, + Valores = filtro.Fim.CriarValor(), + Operador = Operador.MenorEIgual + } + }; + List seguradoras = filtro.Seguradoras; + if (seguradoras != null) + { + count = seguradoras.Count > 0; + } + else + { + count = false; + } + if (count) + { + condicaos.Add(new Condicao() + { + Campo = "c.idciaseg", + Valores = filtro.Seguradoras.CriarValor() + }); + } + List ramos = filtro.Ramos; + if (ramos != null) + { + flag = ramos.Count > 0; + } + else + { + flag = false; + } + if (flag) + { + condicaos.Add(new Condicao() + { + Campo = "c.idramo", + Valores = filtro.Ramos.CriarValor() + }); + } + List status = filtro.Status; + if (status != null) + { + count1 = status.Count > 0; + } + else + { + count1 = false; + } + if (count1) + { + condicaos.Add(new Condicao() + { + Campo = "d.situacao", + Valores = filtro.Status.CriarValor() + }); + } + List tipoVendedor = filtro.TipoVendedor; + if (tipoVendedor != null) + { + flag1 = tipoVendedor.Count > 0; + } + else + { + flag1 = false; + } + if (flag1) + { + condicaos.Add(new Condicao() + { + Campo = "vp.idtipovendedor", + Valores = filtro.TipoVendedor.CriarValor() + }); + } + List vendedores = filtro.Vendedores; + if (vendedores != null) + { + count2 = vendedores.Count > 0; + } + else + { + count2 = false; + } + if (count2) + { + condicaos.Add(new Condicao() + { + Campo = "vp.idvendedor", + Valores = filtro.Vendedores.CriarValor() + }); + } + List estipulantes = filtro.Estipulantes; + if (estipulantes != null) + { + flag2 = estipulantes.Count > 0; + } + else + { + flag2 = false; + } + if (flag2) + { + condicaos.Add(new Condicao() + { + Campo = "d.idestipulante", + Valores = filtro.Estipulantes.CriarValor(), + Operacao = Operacao.Or, + Grupo = 3 + }); + condicaos.Add(new Condicao() + { + Campo = "d.idestipulante2", + Valores = filtro.Estipulantes.CriarValor(), + Operacao = Operacao.Or, + Grupo = 3 + }); + condicaos.Add(new Condicao() + { + Campo = "d.idestipulante3", + Valores = filtro.Estipulantes.CriarValor(), + Operacao = Operacao.Or, + Grupo = 3 + }); + condicaos.Add(new Condicao() + { + Campo = "d.idestipulante4", + Valores = filtro.Estipulantes.CriarValor(), + Operacao = Operacao.Or, + Grupo = 3 + }); + condicaos.Add(new Condicao() + { + Campo = "d.idestipulante5", + Valores = filtro.Estipulantes.CriarValor(), + Operacao = Operacao.Or, + Grupo = 3 + }); + } + List produtos = filtro.Produtos; + if (produtos != null) + { + count3 = produtos.Count > 0; + } + else + { + count3 = false; + } + if (count3) + { + condicaos.Add(new Condicao() + { + Campo = "c.idproduto", + Valores = filtro.Produtos.CriarValor() + }); + } + List negocio = filtro.Negocio; + if (negocio != null) + { + flag3 = negocio.Count > 0; + } + else + { + flag3 = false; + } + if (flag3) + { + condicaos.Add(new Condicao() + { + Campo = "d.NegocioCorretora", + Valores = filtro.Negocio.CriarValor(), + Operacao = Operacao.Or, + Grupo = 6 + }); + condicaos.Add(new Condicao() + { + Campo = "d.NegocioCorretora", + Valores = null, + Operacao = Operacao.Or, + Grupo = 6 + }); + } + if (filtro.IdEmpresa > (long)0) + { + condicaos.Add(new Condicao() + { + Campo = "c.idempresa", + Valores = filtro.IdEmpresa.CriarValor() + }); + } + return condicaos; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + private async Task ExisteTabelasAssinatura() + { + bool flag; + object connection; + using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) + { + SessionFactoryImpl sessionFactoryImpl = sessionFactory; + if (sessionFactoryImpl != null) + { + connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = "SELECT OBJECT_ID('ArquivoParaAssinatura') AS existe"; + flag = await sqlCommand.ExecuteScalarAsync() != DBNull.Value; + } + } + } + return flag; + } + + public async Task> Fechamento(Filtros filtro) + { + List fechamentos = await this.BuscaFechamento(filtro); + Filtros filtro1 = (Filtros)filtro.Clone(); + DateTime inicio = filtro.Inicio; + filtro1.Inicio = inicio.AddYears(-1); + inicio = filtro.Fim; + filtro1.Fim = inicio.AddYears(-1); + List fechamentos1 = await this.BuscaFechamento(filtro1); + List fechamentos2 = new List(); + fechamentos1.ForEach((Fechamento a) => { + Fechamento premioLiquido = fechamentos.Find((Fechamento fec) => { + if (fec.Entidade != a.Entidade) + { + return false; + } + return fec.Id == a.Id; + }) ?? new Fechamento() + { + Entidade = a.Entidade, + Id = a.Id, + Nome = a.Nome, + PremioLiquido = decimal.Zero, + PremioTotal = decimal.Zero, + Fechada = decimal.Zero, + Gerada = decimal.Zero, + Mix = decimal.Zero, + Apolice = 0, + Endosso = 0, + Fatura = 0, + Itens = 0, + Paga = decimal.Zero, + Recebida = decimal.Zero + }; + premioLiquido.PremioLiquidoAnterior = a.PremioLiquido; + premioLiquido.PremioTotalAnterior = a.PremioTotal; + premioLiquido.FechadaAnterior = a.Fechada; + premioLiquido.GeradaAnterior = a.Gerada; + premioLiquido.MixAnterior = a.Mix; + premioLiquido.ApoliceAnterior = a.Apolice; + premioLiquido.EndossoAnterior = a.Endosso; + premioLiquido.FaturaAnterior = a.Fatura; + premioLiquido.ItensAnterior = a.Itens; + premioLiquido.PagaAnterior = a.Paga; + premioLiquido.RecebidaAnterior = a.Recebida; + fechamentos2.Add(premioLiquido); + }); + fechamentos.ForEach((Fechamento a) => { + if (fechamentos2.Find((Fechamento fec) => { + if (fec.Entidade != a.Entidade) + { + return false; + } + return fec.Id == a.Id; + }) == null) + { + Fechamento fechamento = new Fechamento() + { + Entidade = a.Entidade, + Id = a.Id, + Nome = a.Nome, + PremioLiquidoAnterior = decimal.Zero, + PremioTotalAnterior = decimal.Zero, + FechadaAnterior = decimal.Zero, + GeradaAnterior = decimal.Zero, + MixAnterior = decimal.Zero, + ApoliceAnterior = 0, + EndossoAnterior = 0, + FaturaAnterior = 0, + ItensAnterior = 0, + PagaAnterior = decimal.Zero, + RecebidaAnterior = decimal.Zero, + PremioLiquido = a.PremioLiquido, + PremioTotal = a.PremioTotal, + Fechada = a.Fechada, + Gerada = a.Gerada, + Mix = a.Mix, + Apolice = a.Apolice, + Endosso = a.Endosso, + Fatura = a.Fatura, + Itens = a.Itens, + Paga = a.Paga, + Recebida = a.Recebida + }; + fechamentos2.Add(fechamento); + } + }); + List fechamentos3 = fechamentos2; + return fechamentos3; + } + + public List FindApolice(string pesquisa, FiltroStatusDocumento status, List vendedorVinculado, string campo, long idempresa = 0L, bool vendedorembranco = false, bool tipobusca = false) + { + List documentos; + object connection; + DataTable dataTable = new DataTable(); + if (campo == "Proposta") + { + campo = (tipobusca ? string.Concat(" AND d.proposta LIKE '", pesquisa, "'") : string.Concat(" AND d.proposta LIKE '%", pesquisa, "%'")); + } + else if (campo == "Estipulante") + { + campo = (tipobusca ? string.Concat(" AND d.idestipulante IS NOT NULL AND e.nome LIKE '", pesquisa, "'") : string.Concat(" AND d.idestipulante IS NOT NULL AND e.nome LIKE '%", pesquisa, "%'")); + } + else if (campo == "NumeroEndosso") + { + campo = (tipobusca ? string.Concat(" AND d.aditamento LIKE '", pesquisa, "'") : string.Concat(" AND d.aditamento LIKE '%", pesquisa, "%'")); + } + else if (campo == "PedidoEndosso") + { + campo = (tipobusca ? string.Concat(" AND d.pedadit LIKE '", pesquisa, "'") : string.Concat(" AND d.pedadit LIKE '%", pesquisa, "%'")); + } + else + { + campo = (tipobusca ? string.Concat(" AND d.contrato LIKE '", pesquisa, "'") : string.Concat(" AND d.contrato LIKE '%", pesquisa, "%'")); + } + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + DataTable dataTable1 = new DataTable(); + string str = ""; + string str1 = (idempresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", idempresa)); + DateTime date = Gestor.Infrastructure.Helpers.Funcoes.GetNetworkTime().Date; + switch (status) + { + case FiltroStatusDocumento.Vencidos: + { + str = string.Concat(string.Format(" {0} AND (d.vigencia2 IS NULL OR d.vigencia2 < '{1:yyyy-MM-dd}') ", campo, date.AddDays(-5)), "AND d.situacao NOT IN (3, 7)"); + break; + } + case FiltroStatusDocumento.Cancelados: + { + str = string.Concat(" ", campo, " AND d.situacao IN (3)"); + break; + } + case FiltroStatusDocumento.Recusados: + { + str = string.Concat(campo, " AND d.situacao IN (7)"); + break; + } + case FiltroStatusDocumento.Todos: + { + str = string.Concat(" ", campo); + break; + } + default: + { + str = string.Concat(string.Format(" {0} AND (d.vigencia2 IS NULL OR d.vigencia2 > '{1:yyyy-MM-dd}') ", campo, date.AddDays(-5)), "AND d.situacao IN (1, 2, 4)"); + break; + } + } + string str2 = "SELECT DISTINCT c.idcliente,cl.nome,cl.MalaDireta,c.idempresa,c.idcontrole, c.idciaseg, c.idramo, c.idproduto, d.iddocumento, d.adinacomis, d.contrato, d.aditamento, d.com01, d.idnegocio, d.pr_liq, d.pr_total, d.vigencia1, d.vigencia2, d.emissao, d.remessa, d.idestipulante, d.negociocorretora, d.situacao, d.tiporecebimento, d.pasta, c.AssistenciaId, CAST(d.tipo AS INTEGER) AS tipo, CAST(d.ordem AS INTEGER) AS ordem, d.n_parc AS numeroParcelas, e.nome AS estipulante FROM controle c INNER JOIN documento d ON d.idcontrole = c.idcontrole INNER JOIN cliente cl ON cl.idcliente = c.idcliente LEFT OUTER JOIN estipulante e ON e.idestipulante = d.idestipulante WHERE (d.excluido IS NULL OR d.excluido != 1) "; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + Auxiliar.CriarAuxiliar(sqlCommand, false); + sqlCommand.CommandText = string.Concat(str2, str1, str); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable1); + } + List list = ( + from x in dataTable1.AsEnumerable().ToList() + select x.Field("idcontrole")).ToList(); + while (list.Count > 0) + { + List nums = list.Take(2100).ToList(); + if (dataTable1.Rows.Count != 0) + { + string str3 = string.Concat(" d.idcontrole IN (", string.Join(",", nums), ")"); + str3 = (vendedorembranco ? string.Concat(" AND ", str3) : string.Concat(" AND vp.idvendedorparcela IS NOT NULL AND ", str3)); + sqlCommand.CommandText = string.Concat("SELECT DISTINCT vp.idvendedor, d.iddocumento, d.idcontrole, vp.idtipovendedor FROM documento d LEFT OUTER JOIN vendedorparcela vp on d.iddocumento = vp.iddocumento WHERE 1=1 ", str3); + using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) + { + sqlDataAdapter1.SelectCommand = sqlCommand; + sqlDataAdapter1.Fill(dataTable); + } + list = (nums.Count < 2100 ? new List() : list.Except(nums).ToList()); + } + else + { + documentos = new List(); + return documentos; + } + } + goto Label0; + } + } + return documentos; + Label0: + List list1 = null; + if (vendedorVinculado != null && vendedorVinculado.Count > 0) + { + list1 = dataTable.AsEnumerable().Where((DataRow x) => { + if (!vendedorembranco) + { + if (x.Field("idvendedor") == null) + { + return false; + } + List vendedorUsuarios = vendedorVinculado; + Func u003cu003e9_429 = DocumentoRepository.u003cu003ec.u003cu003e9__42_9; + if (u003cu003e9_429 == null) + { + u003cu003e9_429 = (VendedorUsuario v) => v.Vendedor.Id; + DocumentoRepository.u003cu003ec.u003cu003e9__42_9 = u003cu003e9_429; + } + return vendedorUsuarios.Select(u003cu003e9_429).Contains(x.Field("idvendedor")); + } + if (x.Field("idvendedor") == null) + { + return true; + } + List vendedorUsuarios1 = vendedorVinculado; + Func u003cu003e9_428 = DocumentoRepository.u003cu003ec.u003cu003e9__42_8; + if (u003cu003e9_428 == null) + { + u003cu003e9_428 = (VendedorUsuario v) => v.Vendedor.Id; + DocumentoRepository.u003cu003ec.u003cu003e9__42_8 = u003cu003e9_428; + } + return vendedorUsuarios1.Select(u003cu003e9_428).Contains(x.Field("idvendedor")); + }).Select((DataRow x) => x.Field("idcontrole")).ToList(); + } + if (list1 != null && list1.Count == 0) + { + return new List(); + } + List nums1 = dataTable1.AsEnumerable().Select((DataRow x) => x.Field("idcontrole")).Distinct().ToList(); + List nums2 = (new ControleSinistroRepository(this._unitOfWork)).HasSinistro(nums1); + return ( + from x in dataTable1.AsEnumerable().Where((DataRow x) => { + if (list1 == null) + { + return true; + } + return list1.Contains(x.Field("idcontrole")); + }).ToList() + orderby x.Field("idcontrole"), x.Field("tipo") + select x).Select((DataRow x) => { + Documento documento = new Documento() + { + Id = x.Field("iddocumento"), + Controle = new Controle() + { + Id = x.Field("idcontrole"), + IdEmpresa = (x.Field("idempresa") != null ? x.Field("idempresa") : (long)1), + Cliente = new Cliente() + { + Id = x.Field("idcliente"), + Nome = x.Field("nome"), + MalaDireta = new bool?(x.Field("MalaDireta").GetValueOrDefault(true)) + }, + Seguradora = (x.Field("idciaseg") != null ? Auxiliar.Seguradoras.FirstOrDefault((Seguradora p) => p.Id == x.Field("idciaseg")) : null), + Ramo = (x.Field("idramo") != null ? Auxiliar.Ramos.FirstOrDefault((Ramo p) => p.Id == x.Field("idramo")) : null), + Produto = (x.Field("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault((Gestor.Model.Domain.Seguros.Produto p) => p.Id == x.Field("idproduto")) : null), + AssistenciaId = x.Field("AssistenciaId") + }, + Ordem = x.Field("ordem"), + TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), x.Field("tiporecebimento").ToString())), + AdicionalComiss = x.Field("adinacomis") == "1", + Apolice = x.Field("contrato"), + Endosso = x.Field("aditamento"), + Comissao = x.Field("com01"), + Negocio = new Negocio?((x.Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field("idnegocio").ToString()))), + PremioLiquido = x.Field("pr_liq"), + PremioTotal = x.Field("pr_total"), + Vigencia2 = x.Field("vigencia2") + }; + DateTime? nullable = x.Field("vigencia1"); + documento.Vigencia1 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue); + documento.Emissao = x.Field("emissao"); + documento.Remessa = x.Field("remessa"); + documento.Estipulante1 = (x.Field("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault((Estipulante p) => p.Id == x.Field("idestipulante")) : null); + documento.NegocioCorretora = new NegocioCorretora?((x.Field("negociocorretora") == null ? NegocioCorretora.Proprio : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), x.Field("negociocorretora").ToString()))); + documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()); + documento.Tipo = x.Field("tipo"); + documento.VendedorPrincipal = (new VendedorParcelaRepository(this._unitOfWork)).FindByMainDocumentId(x.Field("iddocumento")); + documento.Sinistro = (nums2 == null ? false : nums2.Any((long s) => s == x.Field("idcontrole"))); + documento.NumeroParcelas = int.Parse(x.Field("numeroParcelas").ToString()); + documento.Pasta = x.Field("Pasta"); + return documento; + }).ToList(); + } + + public List FindApoliceByCustomer(long idCliente, FiltroStatusDocumento status, List vendedorVinculado, List licencas, bool endosso = false, bool acessoAgger = false, bool vendedorembranco = false) + { + List documentos1; + object connection; + long num1; + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + bool flag2 = licencas.Any((Licenca x) => { + if (x.Produto != Gestor.Model.License.Produto.AssinaturaEletronica) + { + return false; + } + return x.Status != 3; + }); + DataTable dataTable3 = new DataTable(); + DataTable dataTable4 = new DataTable(); + DataTable dataTable5 = new DataTable(); + DataTable dataTable6 = new DataTable(); + DataTable dataTable7 = null; + List nums = new List(); + List condicaos = new List() + { + new Condicao() + { + Campo = "d.excluido", + Valores = null, + Grupo = 1, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "d.excluido", + Valores = "0".CriarValor(), + Grupo = 1, + Operacao = Operacao.Or + } + }; + DateTime date = Gestor.Infrastructure.Helpers.Funcoes.GetNetworkTime().Date; + List condicaos1 = new List() + { + new Condicao() + { + Campo = "c.idcliente", + Valores = idCliente.CriarValor() + }, + new Condicao() + { + Campo = "d.tipo", + Valores = 0.CriarValor() + } + }; + switch (status) + { + case FiltroStatusDocumento.Vencidos: + { + condicaos1.AddRange(new List() + { + new Condicao() + { + Campo = "d.situacao", + Valores = new List() + { + 3, + 7 + }, + Operador = Operador.Diferente + }, + new Condicao() + { + Campo = "d.vigencia2", + Valores = date.AddDays(-5).CriarValor(), + Operador = Operador.Menor + } + }); + goto case FiltroStatusDocumento.Todos; + } + case FiltroStatusDocumento.Cancelados: + { + condicaos1.Add(new Condicao() + { + Campo = "d.situacao", + Valores = 3.CriarValor() + }); + goto case FiltroStatusDocumento.Todos; + } + case FiltroStatusDocumento.Recusados: + { + condicaos1.Add(new Condicao() + { + Campo = "d.situacao", + Valores = 7.CriarValor() + }); + goto case FiltroStatusDocumento.Todos; + } + case FiltroStatusDocumento.Todos: + { + if (!acessoAgger) + { + condicaos1.AddRange(condicaos); + } + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + dataTable3 = sqlCommand.Select(condicaos1.CreateParameters(0), "SELECT DISTINCT c.idcliente, cl.MalaDireta, cl.cgccpf, c.idempresa, c.idcontrole, c.idciaseg, c.idramo, c.idproduto, d.iddocumento, d.adinacomis, d.pr_adic, d.proposta, d.pedadit, d.contrato, d.aditamento, d.com01, d.idnegocio, d.pr_liq, d.pr_total, d.vigencia1, d.vigencia2, d.emissao, d.remessa, d.idestipulante, d.negociocorretora, d.situacao, d.tiporecebimento, CAST(d.tipo AS INTEGER) AS tipo, CAST(d.ordem AS INTEGER) AS ordem, d.n_parc AS numeroParcelas, d.pasta, d.banco, cb.nomebanco, d.agencia, d.conta, d.excluido, c.AssistenciaId, d.numeroCart, d.vencimentoCart, d.nomeProp, d.formapagamento, d.Obs FROM controle c INNER JOIN documento d ON d.idcontrole = c.idcontrole LEFT OUTER JOIN codigobanco cb on cb.idcodigobanco = d.idbanco INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE ", ""); + if (dataTable3 == null || dataTable3.Rows.Count == 0) + { + documentos1 = new List(); + return documentos1; + } + else + { + Auxiliar.CriarAuxiliar(sqlCommand, false); + nums = ( + from x in dataTable3.AsEnumerable().ToList() + select x.Field("idcontrole")).ToList(); + List condicaos2 = new List() + { + new Condicao() + { + Campo = "c.idcontrole", + Valores = nums.CriarValor() + }, + new Condicao() + { + Campo = "d.tipo", + Valores = 0.CriarValor(), + Operador = Operador.Diferente + } + }; + if (!acessoAgger) + { + condicaos2.AddRange(condicaos); + } + dataTable4 = sqlCommand.Select(condicaos2.CreateParameters(0), "SELECT DISTINCT c.idcliente, cl.MalaDireta, cl.cgccpf, c.idempresa, c.idcontrole, c.idciaseg, c.idramo, c.idproduto, d.iddocumento, d.adinacomis, d.pr_adic, d.proposta, d.pedadit, d.contrato, d.aditamento, d.com01, d.idnegocio, d.pr_liq, d.pr_total, d.vigencia1, d.vigencia2, d.emissao, d.remessa, d.idestipulante, d.negociocorretora, d.situacao, d.tiporecebimento, CAST(d.tipo AS INTEGER) AS tipo, CAST(d.ordem AS INTEGER) AS ordem, d.n_parc AS numeroParcelas, d.pasta, d.banco, cb.nomebanco, d.agencia, d.conta, d.excluido, c.AssistenciaId, d.numeroCart, d.vencimentoCart, d.nomeProp, d.formapagamento, d.Obs FROM controle c INNER JOIN documento d ON d.idcontrole = c.idcontrole LEFT OUTER JOIN codigobanco cb on cb.idcodigobanco = d.idbanco INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE ", ""); + List condicaos3 = (vendedorembranco ? new List() + { + new Condicao() + { + Campo = "d.idcontrole", + Valores = nums.CriarValor() + } + } : new List() + { + new Condicao() + { + Campo = "vp.idvendedorparcela", + Valores = null, + Operador = Operador.Diferente + }, + new Condicao() + { + Campo = "d.idcontrole", + Valores = nums.CriarValor() + } + }); + dataTable5 = sqlCommand.Select(condicaos3.CreateParameters(0), "SELECT DISTINCT vp.IDPARCELA, vp.idvendedor, d.iddocumento, d.idcontrole, vp.idtipovendedor, p.idsubtipo FROM documento d LEFT OUTER JOIN vendedorparcela vp on d.iddocumento = vp.iddocumento LEFT OUTER JOIN parcela p on p.idparcela = vp.idparcela WHERE ", ""); + try + { + if (flag2) + { + List nums1 = ( + from x in dataTable3.AsEnumerable().ToList() + select x.Field("iddocumento")).ToList(); + List nums2 = ( + from x in dataTable4.AsEnumerable().ToList() + select x.Field("iddocumento")).ToList(); + nums1.AddRange(nums2); + List condicaos4 = new List() + { + new Condicao() + { + Campo = "DocumentoId", + Valores = nums1.CriarValor() + }, + new Condicao() + { + Campo = "a.excluido", + Valores = null, + Grupo = 2, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "a.excluido", + Valores = 0.CriarValor(), + Grupo = 2, + Operacao = Operacao.Or + } + }; + dataTable6 = sqlCommand.Select(condicaos4.CreateParameters(0), "SELECT DISTINCT a.idnewarquivodigital, a.descricao, ISNULL(s.Status ,0) as Status, s.assinado, s.DocumentoId, s.id, s.UsuarioId, s.Enviado FROM newarquivodigital a LEFT OUTER JOIN ArquivoParaAssinatura s on s.IndiceId = a.idnewarquivodigital WHERE ", ""); + } + } + catch (Exception exception) + { + dataTable6 = null; + } + } + } + } + List nums3 = null; + if (vendedorVinculado != null && vendedorVinculado.Count > 0) + { + nums3 = dataTable5.AsEnumerable().Where((DataRow x) => { + if (!vendedorembranco) + { + if (x.Field("idvendedor") == null) + { + return false; + } + List vendedorUsuarios = vendedorVinculado; + Func u003cu003e9_1116 = DocumentoRepository.u003cu003ec.u003cu003e9__11_16; + if (u003cu003e9_1116 == null) + { + u003cu003e9_1116 = (VendedorUsuario v) => v.Vendedor.Id; + DocumentoRepository.u003cu003ec.u003cu003e9__11_16 = u003cu003e9_1116; + } + return vendedorUsuarios.Select(u003cu003e9_1116).Contains(x.Field("idvendedor")); + } + if (x.Field("idvendedor") == null) + { + return true; + } + List vendedorUsuarios1 = vendedorVinculado; + Func u003cu003e9_1115 = DocumentoRepository.u003cu003ec.u003cu003e9__11_15; + if (u003cu003e9_1115 == null) + { + u003cu003e9_1115 = (VendedorUsuario v) => v.Vendedor.Id; + DocumentoRepository.u003cu003ec.u003cu003e9__11_15 = u003cu003e9_1115; + } + return vendedorUsuarios1.Select(u003cu003e9_1115).Contains(x.Field("idvendedor")); + }).Select((DataRow x) => x.Field("idcontrole")).ToList(); + } + if (nums3 != null && nums3.Count == 0) + { + return new List(); + } + DataRow dataRow1 = dataTable3.AsEnumerable().FirstOrDefault(); + if (dataRow1 != null) + { + num1 = dataRow1.Field("idempresa"); + } + else + { + num1 = (long)1; + } + long num2 = num1; + Vendedor vendedor1 = Auxiliar.Vendedores.Find((Vendedor p) => { + if (!p.Corretora) + { + return false; + } + return p.IdEmpresa == num2; + }); + if (endosso) + { + dataTable3.Merge(dataTable4); + return ( + from x in dataTable3.AsEnumerable().Where((DataRow x) => { + if (nums3 == null) + { + return true; + } + return nums3.Contains(x.Field("idcontrole")); + }).ToList() + orderby x.Field("idcontrole"), x.Field("tipo") + select x).Select((DataRow x) => { + List list; + Func func2 = null; + Func func3 = null; + Documento documento = new Documento() + { + Id = x.Field("iddocumento"), + Controle = new Controle() + { + Id = x.Field("idcontrole"), + IdEmpresa = (x.Field("idempresa") != null ? x.Field("idempresa") : (long)1), + Cliente = new Cliente() + { + Id = idCliente, + Documento = x.Field("cgccpf"), + MalaDireta = new bool?(x.Field("MalaDireta").GetValueOrDefault(true)) + }, + Seguradora = (x.Field("idciaseg") != null ? Auxiliar.Seguradoras.Find((Seguradora p) => p.Id == x.Field("idciaseg")) : null), + Ramo = (x.Field("idramo") != null ? Auxiliar.Ramos.Find((Ramo p) => p.Id == x.Field("idramo")) : null), + Produto = (x.Field("idproduto") != null ? Auxiliar.Produtos.Find((Gestor.Model.Domain.Seguros.Produto p) => p.Id == x.Field("idproduto")) : null), + AssistenciaId = x.Field("AssistenciaId") + }, + Ordem = x.Field("ordem"), + TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), x.Field("tiporecebimento").ToString())), + AdicionalComiss = x.Field("adinacomis") == "1", + PremioAdicional = x.Field("pr_adic"), + Proposta = x.Field("proposta"), + Apolice = x.Field("contrato"), + PropostaEndosso = x.Field("pedadit"), + Endosso = x.Field("aditamento"), + Comissao = x.Field("com01"), + Negocio = new Negocio?((x.Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field("idnegocio").ToString()))), + PremioLiquido = x.Field("pr_liq"), + PremioTotal = x.Field("pr_total"), + Vigencia2 = x.Field("vigencia2") + }; + DateTime? nullable = x.Field("vigencia1"); + documento.Vigencia1 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue); + documento.Emissao = x.Field("emissao"); + documento.Remessa = x.Field("remessa"); + documento.Estipulante1 = (x.Field("idestipulante") != null ? Auxiliar.Estipulantes.Find((Estipulante p) => p.Id == x.Field("idestipulante")) : null); + documento.NegocioCorretora = new NegocioCorretora?((x.Field("negociocorretora") == null ? NegocioCorretora.Proprio : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), x.Field("negociocorretora").ToString()))); + documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()); + documento.Tipo = x.Field("tipo"); + documento.VendedorPrincipal = (dataTable5.Rows.Count <= 0 || !dataTable5.AsEnumerable().Any((DataRow v1) => { + if (v1.Field("idvendedor") == null || v1.Field("iddocumento") != x.Field("iddocumento")) + { + return false; + } + return v1.Field("idtipovendedor") == (long)1; + }) ? vendedor1 : Auxiliar.Vendedores.Find((Vendedor v) => { + EnumerableRowCollection dataRows = dataTable5.AsEnumerable(); + Func u003cu003e9_26 = func2; + if (u003cu003e9_26 == null) + { + Func func = (DataRow v1) => { + if (v1.Field("iddocumento") != x.Field("iddocumento")) + { + return false; + } + return v1.Field("idtipovendedor") == (long)1; + }; + Func func1 = func; + func2 = func; + u003cu003e9_26 = func1; + } + return dataRows.First(u003cu003e9_26).Field("idvendedor") == v.Id; + })); + documento.Vendedores = Auxiliar.Vendedores.Where((Vendedor v) => { + EnumerableRowCollection dataRows = dataTable5.AsEnumerable(); + Func u003cu003e9_27 = func3; + if (u003cu003e9_27 == null) + { + Func func = (DataRow v1) => { + if (v1.Field("idvendedor") == null) + { + return false; + } + return v1.Field("iddocumento") == x.Field("iddocumento"); + }; + Func func1 = func; + func3 = func; + u003cu003e9_27 = func1; + } + EnumerableRowCollection dataRows1 = dataRows.Where(u003cu003e9_27); + Func u003cu003e9_1128 = DocumentoRepository.u003cu003ec.u003cu003e9__11_28; + if (u003cu003e9_1128 == null) + { + u003cu003e9_1128 = (DataRow v1) => v1.Field("idvendedor"); + DocumentoRepository.u003cu003ec.u003cu003e9__11_28 = u003cu003e9_1128; + } + return dataRows1.Select(u003cu003e9_1128).Contains(v.Id); + }).ToList(); + documento.NumeroParcelas = x.Field("numeroParcelas"); + if (!flag2 || dataTable6 == null) + { + list = null; + } + else + { + EnumerableRowCollection dataRows2 = dataTable6.AsEnumerable().Where((DataRow a) => a.Field("DocumentoId") == x.Field("iddocumento")); + Func u003cu003e9_1122 = DocumentoRepository.u003cu003ec.u003cu003e9__11_22; + if (u003cu003e9_1122 == null) + { + u003cu003e9_1122 = (DataRow a) => new StatusDocumentoAssinado() + { + Id = a.Field("idnewarquivodigital"), + Documento = a.Field("descricao"), + Status = (StatusAssinatura)((a.Field("Status") != null ? a.Field("Status") : StatusAssinatura.Pendente)), + Envio = (a.Field("Enviado") != null ? new DateTime?(a.Field("Enviado")) : null), + Usuario = (a.Field("UsuarioId") != null ? Auxiliar.Usuarios.FirstOrDefault((Usuario u) => u.Id == a.Field("UsuarioId")) : null) + }; + DocumentoRepository.u003cu003ec.u003cu003e9__11_22 = u003cu003e9_1122; + } + list = dataRows2.Select(u003cu003e9_1122).ToList(); + } + documento.Assinaturas = list; + documento.Pasta = x.Field("Pasta"); + documento.Banco = new Banco() + { + Nome = x.Field("nomebanco") + }; + documento.Agencia = x.Field("agencia"); + documento.Conta = x.Field("conta"); + documento.Excluido = (x.Field("excluido") == null ? false : x.Field("excluido").ToString() == "1"); + documento.FormaPagamento = new FormaPagamento?((x.Field("formapagamento") == null || !(x.Field("formapagamento").ToString() != "") || string.IsNullOrWhiteSpace(x.Field("formapagamento").ToString()) ? FormaPagamento.Nenhum : (FormaPagamento)Enum.Parse(typeof(FormaPagamento), x.Field("formapagamento").ToString()))); + return documento; + }).ToList(); + } + List documentos2 = new List(); + List nums4 = (new ControleSinistroRepository(this._unitOfWork)).HasSinistro(nums); + ( + from x in dataTable3.AsEnumerable().Where((DataRow x) => { + if (nums3 == null) + { + return true; + } + return nums3.Contains(x.Field("idcontrole")); + }).ToList() + orderby x.Field("idcontrole") + group x by x.Field("idcontrole")).ToList>().ForEach((IGrouping x) => { + long? nullable1; + bool count; + bool flag; + long? nullable2; + List statusDocumentoAssinados; + if (x == null || x.FirstOrDefault() == null) + { + return; + } + long num = (x.First().Field("idempresa") != null ? x.First().Field("idempresa") : (long)1); + Cliente cliente = new Cliente() + { + Id = idCliente, + Documento = x.First().Field("cgccpf"), + MalaDireta = new bool?(x.First().Field("MalaDireta").GetValueOrDefault(true)) + }; + Seguradora seguradora = (x.First().Field("idciaseg") != null ? Auxiliar.Seguradoras.Find((Seguradora p) => p.Id == x.First().Field("idciaseg")) : null); + Ramo ramo = (x.First().Field("idramo") != null ? Auxiliar.Ramos.Find((Ramo p) => p.Id == x.First().Field("idramo")) : null); + Gestor.Model.Domain.Seguros.Produto produto = (x.First().Field("idproduto") != null ? Auxiliar.Produtos.Find((Gestor.Model.Domain.Seguros.Produto p) => p.Id == x.First().Field("idproduto")) : null); + EnumerableRowCollection dataRows1 = dataTable5.AsEnumerable().Where((DataRow v) => { + if (v.Field("idvendedor") == null) + { + return false; + } + return v.Field("iddocumento") == x.First().Field("iddocumento"); + }); + DataTable dataTable = (!dataRows1.Any() ? null : dataRows1.CopyToDataTable()); + DataTable dataTable1 = dataTable; + count = (dataTable1 != null ? dataTable1.Rows.Count > 0 : false); + List vendedors = (count ? Auxiliar.Vendedores.Where((Vendedor p) => { + EnumerableRowCollection dataRows = dataTable.AsEnumerable(); + Func u003cu003e9_1145 = DocumentoRepository.u003cu003ec.u003cu003e9__11_45; + if (u003cu003e9_1145 == null) + { + u003cu003e9_1145 = (DataRow v) => v.Field("idvendedor"); + DocumentoRepository.u003cu003ec.u003cu003e9__11_45 = u003cu003e9_1145; + } + return dataRows.Select(u003cu003e9_1145).Contains(p.Id); + }).ToList() : null); + DataTable dataTable2 = dataTable; + flag = (dataTable2 != null ? dataTable2.Rows.Count > 0 : false); + if (flag) + { + EnumerableRowCollection dataRows2 = dataTable.AsEnumerable(); + Func u003cu003e9_1135 = DocumentoRepository.u003cu003ec.u003cu003e9__11_35; + if (u003cu003e9_1135 == null) + { + u003cu003e9_1135 = (DataRow v) => v.Field("idsubtipo"); + DocumentoRepository.u003cu003ec.u003cu003e9__11_35 = u003cu003e9_1135; + } + OrderedEnumerableRowCollection orderedEnumerableRowCollection = dataRows2.OrderBy(u003cu003e9_1135); + Func u003cu003e9_1136 = DocumentoRepository.u003cu003ec.u003cu003e9__11_36; + if (u003cu003e9_1136 == null) + { + u003cu003e9_1136 = (DataRow v) => v.Field("IDPARCELA"); + DocumentoRepository.u003cu003ec.u003cu003e9__11_36 = u003cu003e9_1136; + } + List dataRows3 = orderedEnumerableRowCollection.ThenBy(u003cu003e9_1136).ToList(); + Predicate u003cu003e9_1137 = DocumentoRepository.u003cu003ec.u003cu003e9__11_37; + if (u003cu003e9_1137 == null) + { + u003cu003e9_1137 = (DataRow v) => v.Field("idtipovendedor") == (long)1; + DocumentoRepository.u003cu003ec.u003cu003e9__11_37 = u003cu003e9_1137; + } + DataRow dataRow = dataRows3.Find(u003cu003e9_1137); + if (dataRow != null) + { + nullable2 = new long?(dataRow.Field("idvendedor")); + } + else + { + nullable1 = null; + nullable2 = nullable1; + } + } + else + { + nullable1 = null; + nullable2 = nullable1; + } + long? nullable3 = nullable2; + Vendedor vendedor = (!nullable3.HasValue ? vendedor1 : Auxiliar.Vendedores.Find((Vendedor p) => { + long? nullable = nullable3; + long id = p.Id; + return nullable.GetValueOrDefault() == id & nullable.HasValue; + })); + bool flag1 = (nums4 == null ? false : nums4.Any((long s) => s == x.First().Field("idcontrole"))); + IEnumerable dataRows4 = + from e in dataTable4.AsEnumerable().ToList() + where e.Field("idcontrole") == x.Key + select e; + Func u003cu003e9_1141 = DocumentoRepository.u003cu003ec.u003cu003e9__11_41; + if (u003cu003e9_1141 == null) + { + u003cu003e9_1141 = (DataRow e) => e.Field("tipo"); + DocumentoRepository.u003cu003ec.u003cu003e9__11_41 = u003cu003e9_1141; + } + List dataRows5 = dataRows4.OrderBy(u003cu003e9_1141).ToList(); + List calculos1 = null; + if (dataTable7 != null) + { + EnumerableRowCollection dataRows6 = dataTable7.AsEnumerable().Where((DataRow c) => c.Field("IdDocumento") == x.First().Field("iddocumento")); + Func u003cu003e9_1143 = DocumentoRepository.u003cu003ec.u003cu003e9__11_43; + if (u003cu003e9_1143 == null) + { + u003cu003e9_1143 = (DataRow c) => new Calculo() + { + Id = c.Field("Id"), + DocumentId = c.Field("IdDocumento"), + DataAtualizacao = c.Field("DataAtualizacao"), + Status = (StatusCalculo)c.Field("Status"), + Usuario = Auxiliar.Usuarios.Find((Usuario u) => u.Id == c.Field("IdUsuario")) + }; + DocumentoRepository.u003cu003ec.u003cu003e9__11_43 = u003cu003e9_1143; + } + calculos1 = dataRows6.Select(u003cu003e9_1143).ToList(); + if (dataRows5.Count > 0) + { + dataRows5.ForEach((DataRow e) => { + List calculos = calculos1; + EnumerableRowCollection dataRows = dataTable7.AsEnumerable().Where((DataRow c) => c.Field("IdDocumento") == e.Field("iddocumento")); + Func u003cu003e9_1148 = DocumentoRepository.u003cu003ec.u003cu003e9__11_48; + if (u003cu003e9_1148 == null) + { + u003cu003e9_1148 = (DataRow c) => new Calculo() + { + Id = c.Field("Id"), + DocumentId = c.Field("IdDocumento"), + DataAtualizacao = c.Field("DataAtualizacao"), + Status = (StatusCalculo)c.Field("Status"), + Usuario = Auxiliar.Usuarios.Find((Usuario u) => u.Id == c.Field("IdUsuario")) + }; + DocumentoRepository.u003cu003ec.u003cu003e9__11_48 = u003cu003e9_1148; + } + calculos.AddRange(dataRows.Select(u003cu003e9_1148).ToList()); + }); + } + } + Documento banco = new Documento() + { + Id = x.First().Field("iddocumento"), + Controle = new Controle() + { + Id = x.Key, + IdEmpresa = num, + Cliente = cliente, + Seguradora = seguradora, + Ramo = ramo, + Produto = produto, + AssistenciaId = x.First().Field("AssistenciaId") + }, + Ordem = x.First().Field("ordem"), + TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), x.First().Field("tiporecebimento").ToString())), + AdicionalComiss = x.First().Field("adinacomis") == "1", + Proposta = x.First().Field("proposta"), + Apolice = x.First().Field("contrato"), + Endosso = x.First().Field("aditamento"), + Comissao = (x.First().Field("com01") == null ? decimal.Zero : x.First().Field("com01")), + Negocio = new Negocio?((x.First().Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.First().Field("idnegocio").ToString()))), + PremioLiquido = (!x.First().Field("pr_liq").HasValue ? decimal.Zero : x.First().Field("pr_liq")), + PremioAdicional = (!x.First().Field("pr_adic").HasValue ? decimal.Zero : x.First().Field("pr_adic")), + PremioTotal = (!x.First().Field("pr_total").HasValue ? decimal.Zero : x.First().Field("pr_total")), + Vigencia2 = x.First().Field("vigencia2") + }; + DateTime? nullable4 = x.First().Field("vigencia1"); + banco.Vigencia1 = (nullable4.HasValue ? nullable4.GetValueOrDefault() : DateTime.MinValue); + banco.Emissao = x.First().Field("emissao"); + banco.Remessa = x.First().Field("remessa"); + banco.Estipulante1 = (x.First().Field("idestipulante") != null ? Auxiliar.Estipulantes.Find((Estipulante p) => p.Id == x.First().Field("idestipulante")) : null); + banco.NegocioCorretora = new NegocioCorretora?((x.First().Field("negociocorretora") == null ? NegocioCorretora.Proprio : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), x.First().Field("negociocorretora").ToString()))); + banco.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.First().Field("situacao").ToString()); + banco.Tipo = x.First().Field("tipo"); + banco.VendedorPrincipal = vendedor; + banco.Sinistro = flag1; + banco.TemEndosso = dataRows5.Count > 0; + banco.Vendedores = vendedors; + banco.Observacao = x.First().Field("Obs"); + banco.NumeroParcelas = x.First().Field("numeroParcelas"); + if (!flag2 || dataTable6 == null) + { + statusDocumentoAssinados = null; + } + else + { + EnumerableRowCollection dataRows7 = dataTable6.AsEnumerable().Where((DataRow a) => a.Field("DocumentoId") == x.First().Field("iddocumento")); + Func u003cu003e9_1152 = DocumentoRepository.u003cu003ec.u003cu003e9__11_52; + if (u003cu003e9_1152 == null) + { + u003cu003e9_1152 = (DataRow a) => new StatusDocumentoAssinado() + { + Id = a.Field("idnewarquivodigital"), + Documento = a.Field("descricao"), + Status = (StatusAssinatura)((a.Field("Status") != null ? a.Field("Status") : StatusAssinatura.Pendente)), + Envio = (a.Field("Enviado") != null ? new DateTime?(a.Field("Enviado")) : null), + Usuario = (a.Field("UsuarioId") != null ? Auxiliar.Usuarios.Find((Usuario u) => u.Id == a.Field("UsuarioId")) : null) + }; + DocumentoRepository.u003cu003ec.u003cu003e9__11_52 = u003cu003e9_1152; + } + statusDocumentoAssinados = dataRows7.Select(u003cu003e9_1152).ToList(); + } + banco.Assinaturas = statusDocumentoAssinados; + banco.Pasta = x.First().Field("Pasta"); + banco.Banco = new Banco() + { + Nome = x.First().Field("nomebanco") + }; + banco.Agencia = x.First().Field("agencia"); + banco.Conta = x.First().Field("conta"); + banco.Excluido = (x.First().Field("excluido") == null ? false : x.First().Field("excluido").ToString() == "1"); + banco.NumeroCartao = x.First().Field("numeroCart"); + banco.VencimentoCartao = x.First().Field("vencimentoCart"); + banco.NomeProponente = x.First().Field("nomeProp"); + banco.Calculos = calculos1; + banco.FormaPagamento = new FormaPagamento?((x.First().Field("formapagamento") == null || !(x.First().Field("formapagamento").ToString() != "") || string.IsNullOrWhiteSpace(x.First().Field("formapagamento").ToString()) ? FormaPagamento.Nenhum : (FormaPagamento)Enum.Parse(typeof(FormaPagamento), x.First().Field("formapagamento").ToString()))); + Documento documento1 = banco; + List documentos = new List() + { + documento1 + }; + if (dataRows5.Count > 0) + { + List dataRows8 = dataRows5; + Func u003cu003e9_1154 = DocumentoRepository.u003cu003ec.u003cu003e9__11_54; + if (u003cu003e9_1154 == null) + { + u003cu003e9_1154 = (DataRow e) => e.Field("ordem"); + DocumentoRepository.u003cu003ec.u003cu003e9__11_54 = u003cu003e9_1154; + } + documentos.AddRange(dataRows8.OrderBy(u003cu003e9_1154).Select((DataRow e) => { + List list; + Documento documento = new Documento() + { + Id = e.Field("iddocumento"), + Controle = new Controle() + { + Id = x.Key, + IdEmpresa = num, + Cliente = cliente, + Seguradora = seguradora, + Ramo = ramo, + Produto = produto, + AssistenciaId = x.First().Field("AssistenciaId") + }, + Ordem = e.Field("ordem"), + TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), e.Field("tiporecebimento").ToString())), + AdicionalComiss = e.Field("adinacomis") == "1", + Proposta = e.Field("proposta"), + Apolice = e.Field("contrato"), + PropostaEndosso = e.Field("pedadit"), + Endosso = e.Field("aditamento"), + Comissao = (e.Field("com01") == null ? decimal.Zero : e.Field("com01")), + Negocio = new Negocio?((e.Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), e.Field("idnegocio").ToString()))), + PremioLiquido = e.Field("pr_liq"), + PremioAdicional = e.Field("pr_adic"), + PremioTotal = e.Field("pr_total"), + Vigencia2 = e.Field("vigencia2") + }; + DateTime? nullable = e.Field("vigencia1"); + documento.Vigencia1 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue); + documento.Emissao = e.Field("emissao"); + documento.Remessa = e.Field("remessa"); + documento.Estipulante1 = (e.Field("idestipulante") != null ? Auxiliar.Estipulantes.Find((Estipulante p) => p.Id == e.Field("idestipulante")) : null); + documento.NegocioCorretora = new NegocioCorretora?((e.Field("negociocorretora") == null ? NegocioCorretora.Proprio : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), e.Field("negociocorretora").ToString()))); + documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), e.Field("situacao").ToString()); + documento.Tipo = e.Field("tipo"); + documento.Sinistro = flag1; + documento.NumeroParcelas = e.Field("numeroParcelas"); + if (!flag2 || dataTable6 == null) + { + list = null; + } + else + { + EnumerableRowCollection dataRows = dataTable6.AsEnumerable().Where((DataRow a) => a.Field("DocumentoId") == e.Field("iddocumento")); + Func u003cu003e9_1158 = DocumentoRepository.u003cu003ec.u003cu003e9__11_58; + if (u003cu003e9_1158 == null) + { + u003cu003e9_1158 = (DataRow a) => new StatusDocumentoAssinado() + { + Id = a.Field("idnewarquivodigital"), + Documento = a.Field("descricao"), + Status = (StatusAssinatura)((a.Field("Status") != null ? a.Field("Status") : StatusAssinatura.Pendente)), + Envio = (a.Field("Enviado") != null ? new DateTime?(a.Field("Enviado")) : null), + Usuario = (a.Field("UsuarioId") != null ? Auxiliar.Usuarios.Find((Usuario u) => u.Id == a.Field("UsuarioId")) : null) + }; + DocumentoRepository.u003cu003ec.u003cu003e9__11_58 = u003cu003e9_1158; + } + list = dataRows.Select(u003cu003e9_1158).ToList(); + } + documento.Assinaturas = list; + documento.Pasta = e.Field("Pasta"); + documento.Banco = new Banco() + { + Nome = e.Field("nomebanco") + }; + documento.Agencia = e.Field("agencia"); + documento.Conta = e.Field("conta"); + documento.Excluido = (e.Field("excluido") == null ? false : e.Field("excluido").ToString() == "1"); + documento.FormaPagamento = new FormaPagamento?((x.First().Field("formapagamento") == null || !(x.First().Field("formapagamento").ToString() != "") || string.IsNullOrWhiteSpace(x.First().Field("formapagamento").ToString()) ? FormaPagamento.Nenhum : (FormaPagamento)Enum.Parse(typeof(FormaPagamento), x.First().Field("formapagamento").ToString()))); + return documento; + }).ToList()); + } + documento1.Controle.Documentos = documentos; + documentos2.Add(documento1); + }); + return documentos2; + } + default: + { + condicaos1.AddRange(new List() + { + new Condicao() + { + Campo = "d.situacao", + Valores = new List() + { + 1, + 2, + 4 + } + }, + new Condicao() + { + Campo = "d.vigencia2", + Valores = null, + Grupo = 2, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "d.vigencia2", + Valores = date.AddDays(-5).CriarValor(), + Grupo = 2, + Operacao = Operacao.Or, + Operador = Operador.Maior + } + }); + goto case FiltroStatusDocumento.Todos; + } + } + return documentos1; + } + + public List FindByControle(long id) + { + List list = ( + from x in base.All() + where x.Controle.Id == id && !x.Excluido + select x).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public Documento FindById(long id, bool itens = false, bool sinistrosPorControle = false) + { + DocumentoDb documentoDb = base.FindEntityById(id); + Documento documento = ApplicationMapper.Mapper.Map(documentoDb); + if (documento == null) + { + return null; + } + documento.VendedorPrincipal = (new VendedorParcelaRepository(this._unitOfWork)).FindByMainDocumentId(id); + documento.Sinistro = (sinistrosPorControle ? this.HasSinistroPorControle(documento.Controle.Id) : this.HasSinistro(documento.Id)); + if (itens) + { + documento.ItensAtivo = (new ItemRepository(this._unitOfWork)).FindByDocumentsIds(documento.Controle.Id, StatusItem.Ativos, false); + } + return documento; + } + + public Documento FindById(long id, List vendedorVinculado) + { + DocumentoDb documentoDb = base.FindEntityById(id); + Documento documento = ApplicationMapper.Mapper.Map(documentoDb); + if (documento == null) + { + return null; + } + documento.VendedorPrincipal = (new VendedorParcelaRepository(this._unitOfWork)).FindByMainDocumentId(id); + documento.Vendedores = (new VendedorParcelaRepository(this._unitOfWork)).FindVendedoresByDocumentId(id); + documento.Sinistro = this.HasSinistro(documento.Id); + if (vendedorVinculado.Count <= 0) + { + return documento; + } + if (!documento.Vendedores.Any((Vendedor y) => { + List vendedorUsuarios = vendedorVinculado; + Func u003cu003e9_31 = DocumentoRepository.u003cu003ec.u003cu003e9__3_1; + if (u003cu003e9_31 == null) + { + u003cu003e9_31 = (VendedorUsuario x) => x.Vendedor.Id; + DocumentoRepository.u003cu003ec.u003cu003e9__3_1 = u003cu003e9_31; + } + return vendedorUsuarios.Select(u003cu003e9_31).Contains(y.Id); + })) + { + return null; + } + return documento; + } + + public List FindByIds(List ids) + { + if (ids == null || ids.Count == 0) + { + return new List(); + } + return this.Select((new List() + { + new Condicao() + { + Campo = "d.iddocumento", + Valores = ids.CriarValor() + } + }).CreateParameters(0)); + } + + public List FindByLicenciamento(Filtros filtro) + { + List j; + List documentos; + object connection; + List nums = null; + long num; + List nums1 = new List(); + for (int i1 = filtro.ValorInicio; i1 <= filtro.ValorFim; i1++) + { + nums1.Add(i1); + } + string str = string.Concat("AND SUBSTRING(a.placa, len(a.placa), 1) IN ('", string.Join("','", + from v in nums1 + select v), "')"); + string str1 = (filtro.Status == null || filtro.Status.Count == 0 ? "" : string.Concat(" AND situacao IN (", string.Join(",", + from v in filtro.Status + select v), ")")); + string str2 = (filtro.Negocio == null || filtro.Negocio.Count == 0 ? "" : string.Concat(" AND NegocioCorretora IN (", string.Join(",", + from v in filtro.Negocio + select v), ")")); + string str3 = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND c.idciaseg IN (", string.Join(",", + from v in filtro.Seguradoras + select v), ")")); + string str4 = (filtro.Ramos == null || filtro.Ramos.Count == 0 ? "" : string.Concat(" AND c.idramo IN (", string.Join(",", + from v in filtro.Ramos + select v), ")")); + string str5 = (filtro.Produtos == null || filtro.Produtos.Count == 0 ? "" : string.Concat(" AND c.idproduto IN (", string.Join(",", + from v in filtro.Produtos + select v), ")")); + string str6 = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? "" : string.Concat(" AND vp.idvendedor IN (", string.Join(",", + from v in filtro.Vendedores + select v), ")")); + string str7 = (filtro.Estipulantes == null || filtro.Estipulantes.Count == 0 ? "" : string.Concat(" AND d.idestipulante IN (", string.Join(",", + from v in filtro.Estipulantes + select v), ")")); + string str8 = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", filtro.IdEmpresa)); + DataTable dataTable = new DataTable(); + DataTable dataTable1 = new DataTable(); + DataTable dataTable2 = new DataTable(); + DataTable dataTable3 = new DataTable(); + DataTable dataTable4 = new DataTable(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + Auxiliar.CriarAuxiliar(sqlCommand, false); + string str9 = "SELECT i.iditem, d.iddocumento, d.idcontrole, i.descricao, a.placa, a.idcategoria FROM auto a INNER JOIN item i ON a.iditem = i.iditem INNER JOIN documento d on d.iddocumento = i.iddocumento WHERE (d.excluido IS NULL OR d.excluido = '0') AND d.situacao in (1,2,4) AND (cancelado IS NULL OR cancelado != '1') AND idsubstituido IS NULL AND a.placa IS NOT NULL "; + string str10 = "SELECT DISTINCT cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome as cliente, cl.cgccpf as documento, d.idcontrole, d.iddocumento as id, d.contrato as apolice, d.emissao, d.remessa, d.aditamento as endosso, d.idnegocio, d.situacao, d.negociocorretora, d.vigencia1 as vigenciainicial, d.vigencia2 as vigenciafinal, d.pr_total as total, d.pr_liq as liquido, d.pr_adic as adicional, ISNULL(d.com01, 0.00) as comissao, ISNULL(d.adinacomis, '0') as adinacomiss, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, vp.idvendedor, d.idestipulante, d.idnegocio, d.datacontrole, d.idstatus, d.pasta, cl.pasta as pastacliente, c.AssistenciaId FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente OUTER APPLY (SELECT TOP 1 idvendedor FROM vendedorparcela vp WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor = 1) vp WHERE (d.excluido IS NULL OR d.excluido = 0) AND d.vigencia2 >= GETDATE() "; + string str11 = "SELECT DISTINCT d.idcontrole, idvendedor FROM vendedorparcela vp INNER JOIN documento d on d.iddocumento = vp.iddocumento WHERE 1=1 "; + string str12 = "SELECT DISTINCT iddocumento as id, idvendedor FROM vendedorparcela vp WHERE 1=1 "; + sqlCommand.CommandText = string.Concat(str9, " ", str); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable2); + } + if (dataTable2.Rows.Count != 0) + { + for (j = dataTable2.AsEnumerable().Select((DataRow x) => x.Field("iddocumento")).Distinct().ToList(); j.Count > 0; j = nums) + { + List nums2 = j.Take(2000).ToList(); + string str13 = string.Concat(" AND d.iddocumento IN (", string.Join(",", nums2), ")"); + DataTable dataTable5 = new DataTable(); + sqlCommand.CommandText = string.Concat(new string[] { str10, " ", str8, " ", str13, " ", str1, " ", str2, " ", str3, " ", str4, " ", str5, " ", str7, " ", str6 }); + using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) + { + sqlDataAdapter1.SelectCommand = sqlCommand; + sqlDataAdapter1.Fill(dataTable5); + } + dataTable.Merge(dataTable5); + nums = (nums2.Count < 2000 ? new List() : j.Except(nums2).ToList()); + } + if (dataTable.Rows.Count != 0) + { + if (dataTable.AsEnumerable().Any((DataRow x) => x.Field("idvendedor") == null)) + { + string str14 = string.Concat(" AND d.idcontrole IN (", string.Join(",", dataTable.AsEnumerable().Where((DataRow x) => x.Field("idvendedor") == null).Select((DataRow v) => v.Field("idcontrole"))), ")"); + DataTable dataTable6 = new DataTable(); + sqlCommand.CommandText = string.Concat(new string[] { str11, " ", str14, " ", str6 }); + using (SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter()) + { + sqlDataAdapter2.SelectCommand = sqlCommand; + sqlDataAdapter2.Fill(dataTable6); + } + foreach (DataRow row in dataTable.Rows) + { + if (!string.IsNullOrEmpty(row["idvendedor"].ToString())) + { + continue; + } + string str15 = string.Format("idcontrole = {0}", row["idcontrole"]); + DataRow[] dataRowArray = dataTable6.Select(str15); + if (dataRowArray.Length == 0) + { + continue; + } + row["idvendedor"] = dataRowArray[0][1]; + } + } + j = dataTable.AsEnumerable().Select((DataRow x) => x.Field("idcliente")).Distinct().ToList(); + string str16 = string.Concat(" AND vp.iddocumento IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); + sqlCommand.CommandText = string.Concat(str12, " ", str16); + using (SqlDataAdapter sqlDataAdapter3 = new SqlDataAdapter()) + { + sqlDataAdapter3.SelectCommand = sqlCommand; + sqlDataAdapter3.Fill(dataTable1); + } + while (j.Count > 0) + { + List nums3 = j.Take(2100).ToList(); + string str17 = string.Concat(" AND idcliente IN (", string.Join(",", nums3), ")"); + DataTable dataTable7 = new DataTable(); + sqlCommand.CommandText = string.Concat("SELECT DISTINCT idclimail, email, idcliente FROM climail WHERE (ORDEM = '1' OR PADRAO = '1') ", str17); + using (SqlDataAdapter sqlDataAdapter4 = new SqlDataAdapter()) + { + sqlDataAdapter4.SelectCommand = sqlCommand; + sqlDataAdapter4.Fill(dataTable7); + } + dataTable3.Merge(dataTable7); + dataTable7 = new DataTable(); + sqlCommand.CommandText = string.Concat("SELECT DISTINCT idclitelefone, ddd, fone, idcliente FROM clitelefone WHERE 1=1 ", str17); + using (SqlDataAdapter sqlDataAdapter5 = new SqlDataAdapter()) + { + sqlDataAdapter5.SelectCommand = sqlCommand; + sqlDataAdapter5.Fill(dataTable7); + } + dataTable4.Merge(dataTable7); + j = (nums3.Count < 2100 ? new List() : j.Except(nums3).ToList()); + } + goto Label0; + } + else + { + documentos = new List(); + } + } + else + { + documentos = new List(); + } + } + } + return documentos; + Label0: + return dataTable.AsEnumerable().ToList().Select((DataRow x) => { + Func func2 = null; + Documento documento = new Documento() + { + Id = x.Field("id") + }; + Controle controle = new Controle() + { + IdEmpresa = x.Field("idempresa") + }; + Cliente cliente = new Cliente() + { + Id = x.Field("idcliente"), + Nome = x.Field("cliente"), + Documento = x.Field("documento"), + IdEmpresa = x.Field("idempresa") + }; + EnumerableRowCollection dataRows1 = dataTable4.AsEnumerable().Where((DataRow t) => t.Field("idcliente") == x.Field("idcliente")); + Func u003cu003e9_1525 = DocumentoRepository.u003cu003ec.u003cu003e9__15_25; + if (u003cu003e9_1525 == null) + { + u003cu003e9_1525 = (DataRow t) => new ClienteTelefone() + { + Id = t.Field("idclitelefone"), + Prefixo = t.Field("ddd"), + Numero = t.Field("fone") + }; + DocumentoRepository.u003cu003ec.u003cu003e9__15_25 = u003cu003e9_1525; + } + cliente.Telefones = new ObservableCollection(dataRows1.Select(u003cu003e9_1525)); + EnumerableRowCollection dataRows2 = dataTable3.AsEnumerable().Where((DataRow t) => t.Field("idcliente") == x.Field("idcliente")); + Func u003cu003e9_1527 = DocumentoRepository.u003cu003ec.u003cu003e9__15_27; + if (u003cu003e9_1527 == null) + { + u003cu003e9_1527 = (DataRow t) => new ClienteEmail() + { + Id = t.Field("idclimail"), + Email = t.Field("email") + }; + DocumentoRepository.u003cu003ec.u003cu003e9__15_27 = u003cu003e9_1527; + } + cliente.Emails = new ObservableCollection(dataRows2.Select(u003cu003e9_1527)); + cliente.Pasta = x.Field("pastacliente"); + cliente.MalaDireta = new bool?(x.Field("MalaDireta").GetValueOrDefault(true)); + controle.Cliente = cliente; + controle.Seguradora = (x.Field("idseguradora") != null ? Auxiliar.Seguradoras.FirstOrDefault((Seguradora p) => p.Id == x.Field("idseguradora")) : null); + controle.Ramo = (x.Field("idramo") != null ? Auxiliar.Ramos.FirstOrDefault((Ramo p) => p.Id == x.Field("idramo")) : null); + controle.Produto = (x.Field("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault((Gestor.Model.Domain.Seguros.Produto p) => p.Id == x.Field("idproduto")) : null); + controle.AssistenciaId = x.Field("AssistenciaId"); + documento.Controle = controle; + documento.TipoRecebimento = new TipoRecebimento?(TipoRecebimento.Parcela); + documento.AdicionalComiss = x.Field("adinacomiss") == "1"; + documento.Apolice = x.Field("apolice"); + documento.Endosso = (x.Field("tipo") == 0 ? "" : x.Field("endosso") ?? ""); + documento.Comissao = x.Field("comissao"); + documento.Negocio = new Negocio?((x.Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field("idnegocio").ToString()))); + documento.PremioLiquido = x.Field("liquido"); + documento.PremioTotal = x.Field("total"); + documento.Vigencia2 = x.Field("vigenciafinal"); + DateTime? nullable2 = x.Field("vigenciainicial"); + documento.Vigencia1 = (nullable2.HasValue ? nullable2.GetValueOrDefault() : DateTime.MinValue); + documento.Emissao = x.Field("emissao"); + documento.Remessa = x.Field("remessa"); + documento.VendedorPrincipal = (x.Field("idvendedor") != null ? Auxiliar.Vendedores.FirstOrDefault((Vendedor p) => p.Id == x.Field("idvendedor")) : null); + documento.Estipulante1 = (x.Field("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault((Estipulante p) => p.Id == x.Field("idestipulante")) : null); + documento.NegocioCorretora = new NegocioCorretora?((x.Field("negociocorretora") == null ? ((TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()) != TipoSeguro.Renovacao || x.Field("idnegocio") == null || !(x.Field("idnegocio").ToString() == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio) : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), x.Field("negociocorretora").ToString()))); + documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()); + documento.Vendedores = Auxiliar.Vendedores.Where((Vendedor v) => { + List list = dataTable1.AsEnumerable().ToList(); + Func u003cu003e9_28 = func2; + if (u003cu003e9_28 == null) + { + Func func = (DataRow d) => d.Field("id") == x.Field("id"); + Func func1 = func; + func2 = func; + u003cu003e9_28 = func1; + } + IEnumerable dataRows = list.Where(u003cu003e9_28); + Func u003cu003e9_1529 = DocumentoRepository.u003cu003ec.u003cu003e9__15_29; + if (u003cu003e9_1529 == null) + { + u003cu003e9_1529 = (DataRow d) => d.Field("idvendedor"); + DocumentoRepository.u003cu003ec.u003cu003e9__15_29 = u003cu003e9_1529; + } + return dataRows.Select(u003cu003e9_1529).ToList().Contains(v.Id); + }).ToList(); + documento.Tipo = x.Field("tipo"); + documento.DataControle = x.Field("datacontrole"); + documento.Status = (x.Field("idstatus") != null ? Auxiliar.StatusApolice.FirstOrDefault((Status p) => p.Id == x.Field("idstatus")) : null); + documento.ItensAtivo = new List(dataTable2.AsEnumerable().ToList().Where((DataRow i) => { + if (i.Field("idcontrole") == null || !long.TryParse(i.Field("idcontrole").ToString(), out num)) + { + return false; + } + return i.Field("idcontrole") == x.Field("idcontrole"); + }).Select((DataRow i) => { + Categoria? nullable; + Categoria? nullable1; + Item item = new Item() + { + Id = i.Field("iditem"), + Descricao = i.Field("descricao"), + Documento = new Documento() + { + Id = x.Field("id") + } + }; + Auto auto = new Auto(); + if (i.Field("idcategoria") == null) + { + nullable = null; + nullable1 = nullable; + } + else if (i.Field("idcategoria").ToString() == "") + { + nullable = null; + nullable1 = nullable; + } + else + { + nullable1 = (Categoria?)Enum.Parse(typeof(Categoria), i.Field("idcategoria").ToString()); + } + auto.Categoria = nullable1; + auto.Placa = i.Field("placa"); + item.Auto = auto; + return item; + }).ToList()); + documento.Pasta = x.Field("Pasta"); + return documento; + }).ToList(); + } + + public List FindByParcelaIds(List ids) + { + if (ids == null || ids.Count == 0) + { + return new List(); + } + List nums = (new ParcelaRepository(this._unitOfWork)).FindDocumentId(ids); + return this.Select((new List() + { + new Condicao() + { + Campo = "d.iddocumento", + Valores = nums.CriarValor() + } + }).CreateParameters(0)); + } + + public List FindByPlaca(Filtros filtro) + { + List i; + List documentos1; + object connection; + List nums = null; + string str = (filtro.Status == null || filtro.Status.Count == 0 ? "" : string.Concat(" AND situacao IN (", string.Join(",", + from v in filtro.Status + select v), ")")); + string str1 = (filtro.Negocio == null || filtro.Negocio.Count == 0 ? "" : string.Concat(" AND NegocioCorretora IN (", string.Join(",", + from v in filtro.Negocio + select v), ")")); + string str2 = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND c.idciaseg IN (", string.Join(",", + from v in filtro.Seguradoras + select v), ")")); + string str3 = (filtro.Ramos == null || filtro.Ramos.Count == 0 ? "" : string.Concat(" AND c.idramo IN (", string.Join(",", + from v in filtro.Ramos + select v), ")")); + string str4 = (filtro.Produtos == null || filtro.Produtos.Count == 0 ? "" : string.Concat(" AND c.idproduto IN (", string.Join(",", + from v in filtro.Produtos + select v), ")")); + string str5 = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? "" : string.Concat(" AND vp.idvendedor IN (", string.Join(",", + from v in filtro.Vendedores + select v), ")")); + string str6 = (filtro.Estipulantes == null || filtro.Estipulantes.Count == 0 ? "" : string.Concat(" AND d.idestipulante IN (", string.Join(",", + from v in filtro.Estipulantes + select v), ")")); + string str7 = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", filtro.IdEmpresa)); + DataTable dataTable = new DataTable(); + DataTable dataTable1 = new DataTable(); + DataTable dataTable2 = new DataTable(); + DataTable dataTable3 = new DataTable(); + DataTable dataTable4 = new DataTable(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + Auxiliar.CriarAuxiliar(sqlCommand, false); + object date = filtro.Inicio.Date; + DateTime fim = filtro.Fim; + string str8 = string.Format("SELECT i.iditem, d.iddocumento, d.idcontrole, i.descricao, a.placa, a.idcategoria FROM auto a INNER JOIN item i ON a.iditem = i.iditem INNER JOIN documento d on d.iddocumento = i.iddocumento WHERE (d.excluido IS NULL OR d.excluido = '0') {0} AND (cancelado IS NULL OR cancelado != '1') AND idsubstituido IS NULL AND d.vigencia2 >= '{1:yyyy-MM-dd}' AND d.vigencia2 <= '{2:yyyy-MM-dd}'", str, date, fim.Date); + object obj = filtro.Inicio.Date; + fim = filtro.Fim; + string str9 = string.Concat("SELECT DISTINCT cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome as cliente, cl.cgccpf as documento, d.idcontrole, d.iddocumento as id, d.contrato as apolice, d.emissao, d.remessa, d.aditamento as endosso, d.idnegocio, d.situacao, d.negociocorretora, d.vigencia1 as vigenciainicial, d.vigencia2 as vigenciafinal, d.pr_total as total, d.pr_liq as liquido, d.pr_adic as adicional, ISNULL(d.com01, 0.00) as comissao, ISNULL(d.adinacomis, '0') as adinacomiss, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, vp.idvendedor, d.idestipulante, d.idnegocio, d.datacontrole, d.idstatus, d.pasta, cl.pasta as pastacliente, c.AssistenciaId FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente OUTER APPLY (SELECT TOP 1 idvendedor FROM vendedorparcela vp WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor = 1) vp ", string.Format("WHERE (d.excluido IS NULL OR d.excluido = 0) AND d.vigencia2 >= '{0:yyyy-MM-dd}' AND d.vigencia2 <= '{1:yyyy-MM-dd}'", obj, fim.Date)); + string str10 = "SELECT DISTINCT d.idcontrole, idvendedor FROM vendedorparcela vp INNER JOIN documento d on d.iddocumento = vp.iddocumento WHERE 1=1 "; + string str11 = "SELECT DISTINCT iddocumento as id, idvendedor FROM vendedorparcela vp WHERE 1=1 "; + sqlCommand.CommandText = str8 ?? ""; + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable2); + } + if (dataTable2.Rows.Count != 0) + { + for (i = dataTable2.AsEnumerable().Select((DataRow x) => x.Field("iddocumento")).Distinct().ToList(); i.Count > 0; i = nums) + { + List nums1 = i.Take(2000).ToList(); + string str12 = string.Concat(" AND d.iddocumento IN (", string.Join(",", nums1), ")"); + DataTable dataTable5 = new DataTable(); + sqlCommand.CommandText = string.Concat(new string[] { str9, " ", str7, " ", str12, " ", str, " ", str1, " ", str2, " ", str3, " ", str4, " ", str6, " ", str5 }); + using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) + { + sqlDataAdapter1.SelectCommand = sqlCommand; + sqlDataAdapter1.Fill(dataTable5); + } + dataTable.Merge(dataTable5); + nums = (nums1.Count < 2000 ? new List() : i.Except(nums1).ToList()); + } + if (dataTable.Rows.Count != 0) + { + if (dataTable.AsEnumerable().Any((DataRow x) => x.Field("idvendedor") == null)) + { + string str13 = string.Concat(" AND d.idcontrole IN (", string.Join(",", dataTable.AsEnumerable().Where((DataRow x) => x.Field("idvendedor") == null).Select((DataRow v) => v.Field("idcontrole"))), ")"); + DataTable dataTable6 = new DataTable(); + sqlCommand.CommandText = string.Concat(new string[] { str10, " ", str13, " ", str5 }); + using (SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter()) + { + sqlDataAdapter2.SelectCommand = sqlCommand; + sqlDataAdapter2.Fill(dataTable6); + } + foreach (DataRow row in dataTable.Rows) + { + if (!string.IsNullOrEmpty(row["idvendedor"].ToString())) + { + continue; + } + string str14 = string.Format("idcontrole = {0}", row["idcontrole"]); + DataRow[] dataRowArray = dataTable6.Select(str14); + if (dataRowArray.Length == 0) + { + continue; + } + row["idvendedor"] = dataRowArray[0][1]; + } + } + i = dataTable.AsEnumerable().Select((DataRow x) => x.Field("idcliente")).Distinct().ToList(); + string str15 = string.Concat(" AND vp.iddocumento IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); + sqlCommand.CommandText = string.Concat(str11, " ", str15); + using (SqlDataAdapter sqlDataAdapter3 = new SqlDataAdapter()) + { + sqlDataAdapter3.SelectCommand = sqlCommand; + sqlDataAdapter3.Fill(dataTable1); + } + while (i.Count > 0) + { + List nums2 = i.Take(2100).ToList(); + string str16 = string.Concat(" AND idcliente IN (", string.Join(",", nums2), ")"); + DataTable dataTable7 = new DataTable(); + sqlCommand.CommandText = string.Concat("SELECT DISTINCT idclimail, email, idcliente FROM climail WHERE (ORDEM = '1' OR PADRAO = '1') ", str16); + using (SqlDataAdapter sqlDataAdapter4 = new SqlDataAdapter()) + { + sqlDataAdapter4.SelectCommand = sqlCommand; + sqlDataAdapter4.Fill(dataTable7); + } + dataTable3.Merge(dataTable7); + dataTable7 = new DataTable(); + sqlCommand.CommandText = string.Concat("SELECT DISTINCT idclitelefone, ddd, fone, idcliente FROM clitelefone WHERE 1=1 ", str16); + using (SqlDataAdapter sqlDataAdapter5 = new SqlDataAdapter()) + { + sqlDataAdapter5.SelectCommand = sqlCommand; + sqlDataAdapter5.Fill(dataTable7); + } + dataTable4.Merge(dataTable7); + i = (nums2.Count < 2100 ? new List() : i.Except(nums2).ToList()); + } + goto Label0; + } + else + { + documentos1 = new List(); + } + } + else + { + documentos1 = new List(); + } + } + } + return documentos1; + Label0: + List documentos2 = new List(); + dataTable.AsEnumerable().ToList().ForEach((DataRow apolice) => { + Func func2 = null; + List documentos = documentos2; + Documento documento = new Documento() + { + Id = apolice.Field("id") + }; + Controle controle = new Controle() + { + IdEmpresa = apolice.Field("idempresa") + }; + Cliente cliente = new Cliente() + { + Id = apolice.Field("idcliente"), + Nome = apolice.Field("cliente"), + Documento = apolice.Field("documento"), + IdEmpresa = apolice.Field("idempresa") + }; + EnumerableRowCollection dataRows1 = dataTable4.AsEnumerable().Where((DataRow fone) => fone.Field("idcliente") == apolice.Field("idcliente")); + Func u003cu003e9_1624 = DocumentoRepository.u003cu003ec.u003cu003e9__16_24; + if (u003cu003e9_1624 == null) + { + u003cu003e9_1624 = (DataRow fone) => new ClienteTelefone() + { + Id = fone.Field("idclitelefone"), + Prefixo = fone.Field("ddd"), + Numero = fone.Field("fone") + }; + DocumentoRepository.u003cu003ec.u003cu003e9__16_24 = u003cu003e9_1624; + } + cliente.Telefones = new ObservableCollection(dataRows1.Select(u003cu003e9_1624)); + EnumerableRowCollection dataRows2 = dataTable3.AsEnumerable().Where((DataRow mail) => mail.Field("idcliente") == apolice.Field("idcliente")); + Func u003cu003e9_1626 = DocumentoRepository.u003cu003ec.u003cu003e9__16_26; + if (u003cu003e9_1626 == null) + { + u003cu003e9_1626 = (DataRow mail) => new ClienteEmail() + { + Id = mail.Field("idclimail"), + Email = mail.Field("email") + }; + DocumentoRepository.u003cu003ec.u003cu003e9__16_26 = u003cu003e9_1626; + } + cliente.Emails = new ObservableCollection(dataRows2.Select(u003cu003e9_1626)); + cliente.Pasta = apolice.Field("pastacliente"); + cliente.MalaDireta = new bool?(apolice.Field("MalaDireta").GetValueOrDefault(true)); + controle.Cliente = cliente; + controle.Seguradora = (apolice.Field("idseguradora") != null ? Auxiliar.Seguradoras.FirstOrDefault((Seguradora seguradora) => seguradora.Id == apolice.Field("idseguradora")) : null); + controle.Ramo = (apolice.Field("idramo") != null ? Auxiliar.Ramos.FirstOrDefault((Ramo ramo) => ramo.Id == apolice.Field("idramo")) : null); + controle.Produto = (apolice.Field("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault((Gestor.Model.Domain.Seguros.Produto produto) => produto.Id == apolice.Field("idproduto")) : null); + controle.AssistenciaId = apolice.Field("AssistenciaId"); + documento.Controle = controle; + documento.TipoRecebimento = new TipoRecebimento?(TipoRecebimento.Parcela); + documento.AdicionalComiss = apolice.Field("adinacomiss") == "1"; + documento.Apolice = apolice.Field("apolice"); + documento.Endosso = (apolice.Field("tipo") == 0 ? "" : apolice.Field("endosso") ?? ""); + documento.Comissao = apolice.Field("comissao"); + documento.Negocio = new Negocio?((apolice.Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), apolice.Field("idnegocio").ToString()))); + documento.PremioLiquido = apolice.Field("liquido"); + documento.PremioTotal = apolice.Field("total"); + documento.Vigencia2 = apolice.Field("vigenciafinal"); + DateTime? nullable2 = apolice.Field("vigenciainicial"); + documento.Vigencia1 = (nullable2.HasValue ? nullable2.GetValueOrDefault() : DateTime.MinValue); + documento.Emissao = apolice.Field("emissao"); + documento.Remessa = apolice.Field("remessa"); + documento.VendedorPrincipal = (apolice.Field("idvendedor") != null ? Auxiliar.Vendedores.FirstOrDefault((Vendedor vendedor) => vendedor.Id == apolice.Field("idvendedor")) : null); + documento.Estipulante1 = (apolice.Field("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault((Estipulante estipulante) => estipulante.Id == apolice.Field("idestipulante")) : null); + documento.NegocioCorretora = new NegocioCorretora?((apolice.Field("negociocorretora") == null ? ((TipoSeguro)Enum.Parse(typeof(TipoSeguro), apolice.Field("situacao").ToString()) != TipoSeguro.Renovacao || apolice.Field("idnegocio") == null || !(apolice.Field("idnegocio").ToString() == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio) : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), apolice.Field("negociocorretora").ToString()))); + documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), apolice.Field("situacao").ToString()); + documento.Vendedores = Auxiliar.Vendedores.Where((Vendedor vendedor) => { + List list = dataTable1.AsEnumerable().ToList(); + Func u003cu003e9_27 = func2; + if (u003cu003e9_27 == null) + { + Func func = (DataRow d) => d.Field("id") == apolice.Field("id"); + Func func1 = func; + func2 = func; + u003cu003e9_27 = func1; + } + IEnumerable dataRows = list.Where(u003cu003e9_27); + Func u003cu003e9_1628 = DocumentoRepository.u003cu003ec.u003cu003e9__16_28; + if (u003cu003e9_1628 == null) + { + u003cu003e9_1628 = (DataRow d) => d.Field("idvendedor"); + DocumentoRepository.u003cu003ec.u003cu003e9__16_28 = u003cu003e9_1628; + } + return dataRows.Select(u003cu003e9_1628).ToList().Contains(vendedor.Id); + }).ToList(); + documento.Tipo = apolice.Field("tipo"); + documento.DataControle = apolice.Field("datacontrole"); + documento.Status = (apolice.Field("idstatus") != null ? Auxiliar.StatusApolice.FirstOrDefault((Status status) => status.Id == apolice.Field("idstatus")) : null); + documento.ItensAtivo = new List(( + from item in dataTable2.AsEnumerable().ToList() + where item.Field("iddocumento") == apolice.Field("id") + select item).Select((DataRow item) => { + Categoria? nullable; + Categoria? nullable1; + Item item1 = new Item() + { + Id = item.Field("iditem"), + Descricao = item.Field("descricao"), + Documento = new Documento() + { + Id = apolice.Field("id") + } + }; + Auto auto = new Auto(); + if (item.Field("idcategoria") == null) + { + nullable = null; + nullable1 = nullable; + } + else if (item.Field("idcategoria").ToString() == "") + { + nullable = null; + nullable1 = nullable; + } + else + { + nullable1 = (Categoria?)Enum.Parse(typeof(Categoria), item.Field("idcategoria").ToString()); + } + auto.Categoria = nullable1; + auto.Placa = item.Field("placa"); + item1.Auto = auto; + return item1; + }).ToList()); + documento.Pasta = apolice.Field("Pasta"); + documentos.Add(documento); + }); + return documentos2; + } + + public List FindByVigenciaFinal(Filtros filtro, List licencas, bool somarPremios) + { + List j; + List documentos; + object connection; + bool count; + List nums1 = null; + List nums2 = null; + List nums3 = null; + List nums4 = null; + List condicaos = this.CriaCondicaoDocumento(filtro, "CAST(d.vigencia2 AS DATE)"); + condicaos.AddRange(new List() + { + new Condicao() + { + Campo = "d.excluido", + Valores = null, + Grupo = 1, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "d.excluido", + Valores = "0".CriarValor(), + Grupo = 1, + Operacao = Operacao.Or + } + }); + condicaos.Add(new Condicao() + { + Campo = "d.tipo", + Valores = 0.CriarValor() + }); + DataTable dataTable = new DataTable(); + DataTable dataTable1 = new DataTable(); + DataTable dataTable2 = new DataTable(); + DataTable dataTable3 = new DataTable(); + DataTable dataTable4 = new DataTable(); + DataTable dataTable5 = new DataTable(); + DataTable dataTable6 = null; + DataTable dataTable7 = new DataTable(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandTimeout = 15000; + string str = string.Concat("SELECT DISTINCT cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome as cliente, cl.cgccpf, d.idcontrole, d.iddocumento as id, d.contrato as apolice, CASE WHEN d2.aditamento <>'' THEN 'SIM' ELSE 'NÃO' END AS endosso, d.idnegocio, d.situacao, d.negociocorretora, d.vigencia1 as vigenciainicial, d.vigencia2 as vigenciafinal, d.pr_total as total, d.pr_liq as liquido, d.pr_adic as adicional, ISNULL(d.com01, 0.00) as comissao, ISNULL(d.adinacomis, '0') as adinacomiss, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, vp.idvendedor, d.idestipulante, d.apol_antes, d.remessa, d.emissao, d.pr_adic, d.pr_iof, d.pr_custo, d.datacontrole, d.idstatus, d.pasta, d.idbanco, cb.nomebanco, d.agencia, d.conta, cl.pasta as pastacliente, c.AssistenciaId, d.tiporecebimento FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente LEFT OUTER JOIN codigobanco cb on cb.idcodigobanco = d.idbanco OUTER APPLY (SELECT TOP 1 aditamento FROM documento WHERE idcontrole = d.idcontrole AND tipo = '1') d2 ", (filtro.TipoVendedor == null || filtro.TipoVendedor.Count == 0 ? "OUTER APPLY (SELECT TOP 1 vp.idvendedor FROM vendedorparcela vp INNER JOIN parcela parc ON parc.IdParcela = vp.IdParcela WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor = 1 ORDER BY PARC.IDSUBTIPO, CAST(parc.Parcela as int) DESC) vp" : string.Concat("INNER JOIN vendedorparcela vp ON vp.iddocumento = d.iddocumento AND vp.idtipovendedor IN (", string.Join(",", + from v in filtro.TipoVendedor + select v), ")")), " WHERE "); + string str1 = "SELECT DISTINCT d.idcontrole, idvendedor FROM vendedorparcela vp INNER JOIN documento d on d.iddocumento = vp.iddocumento INNER JOIN parcela p ON p.idparcela = vp.idparcela WHERE "; + string str2 = "SELECT DISTINCT iddocumento as id, idvendedor FROM vendedorparcela vp WHERE "; + string str3 = "SELECT DISTINCT idcontrolesinistro, idcontrole as id, cs.iditem FROM controlesinistro cs INNER JOIN item i on i.iditem = cs.iditem INNER JOIN documento d on d.iddocumento = i.iddocumento WHERE "; + string str4 = "SELECT DISTINCT idclitelefone, ddd, fone, idcliente as id FROM clitelefone WHERE "; + string str5 = "SELECT DISTINCT idclimail, email, idcliente as id FROM climail WHERE "; + string str6 = "SELECT i.iditem, d.iddocumento, d.idcontrole, i.descricao FROM item i INNER JOIN documento d on d.iddocumento = i.iddocumento WHERE "; + dataTable = sqlCommand.Select(condicaos.CreateParameters(0), str, ""); + if (dataTable == null || dataTable.Rows.Count == 0) + { + documentos = new List(); + } + else + { + Auxiliar.CriarAuxiliar(sqlCommand, false); + for (List i1 = dataTable.AsEnumerable().Where((DataRow x) => x.Field("idvendedor") == null).Select((DataRow v) => v.Field("idcontrole")).ToList(); i1.Count > 0; i1 = nums1) + { + List nums5 = i1.Take(1000).ToList(); + List condicaos1 = new List() + { + new Condicao() + { + Campo = "d.idcontrole", + Valores = nums5.CriarValor() + }, + new Condicao() + { + Campo = "p.parcela", + Operador = Operador.Diferente, + Valores = "999".CriarValor() + } + }; + List vendedores = filtro.Vendedores; + if (vendedores != null) + { + count = vendedores.Count > 0; + } + else + { + count = false; + } + if (count) + { + condicaos1.Add(new Condicao() + { + Campo = "vp.idvendedor", + Valores = filtro.Vendedores.CriarValor() + }); + } + DataTable dataTable8 = sqlCommand.Select(condicaos1.CreateParameters(0), str1, ""); + foreach (DataRow row in dataTable.Rows) + { + if (!string.IsNullOrEmpty(row["idvendedor"].ToString())) + { + continue; + } + string str7 = string.Format("idcontrole = {0}", row["idcontrole"]); + DataRow[] dataRowArray = dataTable8.Select(str7); + if (dataRowArray.Length == 0) + { + continue; + } + row["idvendedor"] = dataRowArray[0][1]; + } + nums1 = (nums5.Count < 1000 ? new List() : i1.Except(nums5).ToList()); + } + for (j = dataTable.AsEnumerable().Select((DataRow v) => v.Field("idcliente")).Distinct().ToList(); j.Count > 0; j = nums2) + { + List nums6 = j.Take(1000).ToList(); + List condicaos2 = new List() + { + new Condicao() + { + Campo = "idcliente", + Valores = nums6.CriarValor() + } + }; + DataTable dataTable9 = sqlCommand.Select(condicaos2.CreateParameters(0), str4, ""); + dataTable4.Merge(dataTable9); + dataTable9 = sqlCommand.Select(condicaos2.CreateParameters(0), str5, ""); + dataTable3.Merge(dataTable9); + nums2 = (nums6.Count < 1000 ? new List() : j.Except(nums6).ToList()); + } + for (j = dataTable.AsEnumerable().Select((DataRow v) => v.Field("id")).Distinct().ToList(); j.Count > 0; j = nums3) + { + List nums7 = j.Take(1000).ToList(); + List condicaos3 = new List() + { + new Condicao() + { + Campo = "vp.iddocumento", + Valores = nums7.CriarValor() + } + }; + DataTable dataTable10 = sqlCommand.Select(condicaos3.CreateParameters(0), str2, ""); + dataTable1.Merge(dataTable10); + nums3 = (nums7.Count < 1000 ? new List() : j.Except(nums7).ToList()); + } + for (j = dataTable.AsEnumerable().Select((DataRow v) => v.Field("idcontrole")).Distinct().ToList(); j.Count > 0; j = nums4) + { + List nums8 = j.Take(1000).ToList(); + List condicaos4 = new List() + { + new Condicao() + { + Campo = "d.idcontrole", + Valores = nums8.CriarValor() + } + }; + List condicaos5 = new List(); + condicaos5.AddRange(condicaos4); + DataTable dataTable11 = sqlCommand.Select(condicaos5.CreateParameters(0), str3, ""); + dataTable2.Merge(dataTable11); + condicaos5.AddRange(new List() + { + new Condicao() + { + Campo = "idsubstituido", + Valores = null + }, + new Condicao() + { + Campo = "cancelado", + Valores = null, + Operacao = Operacao.Or, + Grupo = 1 + }, + new Condicao() + { + Campo = "cancelado", + Valores = 0.CriarValor(), + Operacao = Operacao.Or, + Grupo = 1 + } + }); + dataTable11 = sqlCommand.Select(condicaos5.CreateParameters(0), str6, ""); + dataTable5.Merge(dataTable11); + licencas.Any((Licenca x) => { + if (x.Produto != Gestor.Model.License.Produto.AggilizadorCalculos && x.Produto != Gestor.Model.License.Produto.AggilizadorCalculosIndependente) + { + return false; + } + return x.Status != 3; + }); + if (somarPremios) + { + condicaos4.AddRange(new List() + { + new Condicao() + { + Campo = "d.excluido", + Valores = null, + Grupo = 1, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "d.excluido", + Valores = "0".CriarValor(), + Grupo = 1, + Operacao = Operacao.Or + } + }); + DataTable dataTable12 = sqlCommand.Select(condicaos4.CreateParameters(0), "SELECT d.iddocumento, d.idcontrole, ISNULL(d.pr_liq ,0) AS pr_liq, ISNULL(d.pr_total ,0) AS pr_total FROM documento d WHERE", ""); + dataTable7.Merge(dataTable12); + } + nums4 = (nums8.Count < 1000 ? new List() : j.Except(nums8).ToList()); + } + goto Label0; + } + } + } + return documentos; + Label0: + List documentos1 = new List(); + dataTable.AsEnumerable().ToList().ForEach((DataRow x) => { + DateTime? nullable; + List list; + decimal num; + decimal num1; + DateTime? nullable1; + DateTime? nullable2; + EnumerableRowCollection dataRows1 = dataTable1.AsEnumerable().Where((DataRow d) => d.Field("id") == x.Field("id")); + Func u003cu003e9_269 = DocumentoRepository.u003cu003ec.u003cu003e9__26_9; + if (u003cu003e9_269 == null) + { + u003cu003e9_269 = (DataRow d) => d.Field("idvendedor"); + DocumentoRepository.u003cu003ec.u003cu003e9__26_9 = u003cu003e9_269; + } + List nums = dataRows1.Select(u003cu003e9_269).ToList(); + IEnumerable list1 = + from t in dataTable4.AsEnumerable().ToList() + where t.Field("id") == x.Field("idcliente") + select t; + Func u003cu003e9_2611 = DocumentoRepository.u003cu003ec.u003cu003e9__26_11; + if (u003cu003e9_2611 == null) + { + u003cu003e9_2611 = (DataRow t) => new ClienteTelefone() + { + Prefixo = t.Field("ddd"), + Numero = t.Field("fone") + }; + DocumentoRepository.u003cu003ec.u003cu003e9__26_11 = u003cu003e9_2611; + } + List clienteTelefones = list1.Select(u003cu003e9_2611).ToList(); + IEnumerable list2 = + from t in dataTable3.AsEnumerable().ToList() + where t.Field("id") == x.Field("idcliente") + select t; + Func u003cu003e9_2613 = DocumentoRepository.u003cu003ec.u003cu003e9__26_13; + if (u003cu003e9_2613 == null) + { + u003cu003e9_2613 = (DataRow t) => new ClienteEmail() + { + Email = t.Field("email") + }; + DocumentoRepository.u003cu003ec.u003cu003e9__26_13 = u003cu003e9_2613; + } + List clienteEmails = list2.Select(u003cu003e9_2613).ToList(); + List items = ( + from i in dataTable5.AsEnumerable().ToList() + where i.Field("idcontrole") == x.Field("idcontrole") + select i).Select((DataRow i) => { + Item item = new Item() + { + Id = i.Field("iditem"), + Descricao = i.Field("descricao") + }; + EnumerableRowCollection dataRows = dataTable2.AsEnumerable().Where((DataRow s) => { + if (s.Field("id") != x.Field("idcontrole")) + { + return false; + } + return i.Field("iditem") == s.Field("iditem"); + }); + Func u003cu003e9_2624 = DocumentoRepository.u003cu003ec.u003cu003e9__26_24; + if (u003cu003e9_2624 == null) + { + u003cu003e9_2624 = (DataRow s) => new ControleSinistro() + { + Id = s.Field("idcontrolesinistro") + }; + DocumentoRepository.u003cu003ec.u003cu003e9__26_24 = u003cu003e9_2624; + } + item.Sinistros = dataRows.Select(u003cu003e9_2624).ToList(); + return item; + }).ToList(); + if (dataTable6 != null) + { + EnumerableRowCollection dataRows2 = dataTable6.AsEnumerable().Where((DataRow c) => c.Field("idcontrole") == x.Field("idcontrole")); + Func u003cu003e9_2617 = DocumentoRepository.u003cu003ec.u003cu003e9__26_17; + if (u003cu003e9_2617 == null) + { + u003cu003e9_2617 = (DataRow c) => new Calculo() + { + Id = c.Field("Id"), + DocumentId = c.Field("IdDocumento"), + DataAtualizacao = c.Field("DataAtualizacao"), + Status = (StatusCalculo)c.Field("Status"), + Usuario = Auxiliar.Usuarios.Find((Usuario u) => u.Id == c.Field("IdUsuario")) + }; + DocumentoRepository.u003cu003ec.u003cu003e9__26_17 = u003cu003e9_2617; + } + list = dataRows2.Select(u003cu003e9_2617).ToList(); + } + else + { + list = new List(); + } + List calculos = list; + List list3 = dataTable7.AsEnumerable().Where((DataRow p) => p.Field("idcontrole") == x.Field("idcontrole")).ToList(); + if (!somarPremios) + { + num = x.Field("total"); + } + else + { + List dataRows3 = list3; + Func u003cu003e9_2619 = DocumentoRepository.u003cu003ec.u003cu003e9__26_19; + if (u003cu003e9_2619 == null) + { + u003cu003e9_2619 = (DataRow p) => p.Field("pr_total"); + DocumentoRepository.u003cu003ec.u003cu003e9__26_19 = u003cu003e9_2619; + } + num = dataRows3.Sum(u003cu003e9_2619); + } + decimal num2 = num; + if (!somarPremios) + { + num1 = x.Field("liquido"); + } + else + { + List dataRows4 = list3; + Func u003cu003e9_2620 = DocumentoRepository.u003cu003ec.u003cu003e9__26_20; + if (u003cu003e9_2620 == null) + { + u003cu003e9_2620 = (DataRow p) => p.Field("pr_liq"); + DocumentoRepository.u003cu003ec.u003cu003e9__26_20 = u003cu003e9_2620; + } + num1 = dataRows4.Sum(u003cu003e9_2620); + } + decimal num3 = num1; + Vendedor vendedor = (x.Field("idvendedor") != null ? Auxiliar.Vendedores.Find((Vendedor p) => p.Id == x.Field("idvendedor")) : null); + NegocioCorretora negocioCorretora = (x.Field("negociocorretora") == null ? ((TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()) != TipoSeguro.Renovacao || x.Field("idnegocio") == null || !(x.Field("idnegocio").ToString() == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio) : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), x.Field("negociocorretora").ToString())); + if (filtro.Negocio != null && filtro.Negocio.Count > 0 && !filtro.Negocio.Any((long n) => (int)n == (int)negocioCorretora)) + { + return; + } + Documento documento = new Documento() + { + Id = x.Field("id"), + Controle = new Controle() + { + Id = x.Field("idcontrole"), + IdEmpresa = x.Field("idempresa"), + Cliente = new Cliente() + { + Id = x.Field("idcliente"), + Nome = x.Field("cliente"), + Documento = x.Field("cgccpf"), + IdEmpresa = x.Field("idempresa"), + Telefones = new ObservableCollection(clienteTelefones), + Emails = new ObservableCollection(clienteEmails), + Pasta = x.Field("pastacliente"), + MalaDireta = new bool?(x.Field("MalaDireta").GetValueOrDefault(true)) + }, + Seguradora = (x.Field("idseguradora") != null ? Auxiliar.Seguradoras.Find((Seguradora p) => p.Id == x.Field("idseguradora")) : null), + Ramo = (x.Field("idramo") != null ? Auxiliar.Ramos.Find((Ramo p) => p.Id == x.Field("idramo")) : null), + Produto = (x.Field("idproduto") != null ? Auxiliar.Produtos.Find((Gestor.Model.Domain.Seguros.Produto p) => p.Id == x.Field("idproduto")) : null), + AssistenciaId = x.Field("AssistenciaId") + }, + TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), x.Field("tiporecebimento").ToString())), + AdicionalComiss = x.Field("adinacomiss") == "1", + Apolice = x.Field("apolice"), + ApoliceAnterior = x.Field("apol_antes") + }; + if (x.Field("remessa") == null) + { + nullable = null; + nullable1 = nullable; + } + else + { + nullable1 = new DateTime?(x.Field("remessa")); + } + documento.Remessa = nullable1; + if (x.Field("emissao") == null) + { + nullable = null; + nullable2 = nullable; + } + else + { + nullable2 = new DateTime?(x.Field("emissao")); + } + documento.Emissao = nullable2; + documento.Endosso = x.Field("endosso"); + documento.Comissao = x.Field("comissao"); + documento.Negocio = new Negocio?((x.Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field("idnegocio").ToString()))); + documento.PremioLiquido = num3; + documento.PremioAdicional = x.Field("pr_adic"); + x.Field("pr_custo"); + documento.Custo = x.Field("pr_custo"); + documento.Iof = x.Field("pr_iof"); + documento.PremioTotal = num2; + documento.Vigencia2 = x.Field("vigenciafinal"); + nullable = x.Field("vigenciainicial"); + documento.Vigencia1 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue); + documento.VendedorPrincipal = vendedor; + documento.Estipulante1 = (x.Field("idestipulante") != null ? Auxiliar.Estipulantes.Find((Estipulante p) => p.Id == x.Field("idestipulante")) : null); + documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()); + documento.NegocioCorretora = new NegocioCorretora?(negocioCorretora); + documento.Vendedores = ( + from v in Auxiliar.Vendedores + where nums.Contains(v.Id) + select v).ToList(); + documento.Sinistro = dataTable2.AsEnumerable().ToList().Any((DataRow s) => s.Field("id") == x.Field("idcontrole")); + documento.Tipo = x.Field("tipo"); + documento.ItensAtivo = items; + documento.DataControle = x.Field("datacontrole"); + documento.Status = (x.Field("idstatus") != null ? Auxiliar.StatusApolice.Find((Status p) => p.Id == x.Field("idstatus")) : null); + documento.Pasta = x.Field("Pasta"); + documento.Banco = new Banco() + { + Nome = x.Field("nomebanco") + }; + documento.Agencia = x.Field("agencia"); + documento.Conta = x.Field("conta"); + documento.Calculos = calculos; + documentos1.Add(documento); + }); + return documentos1; + } + + public async Task> FindEndossoByVigencia(Filtros filtro, bool buscarAssinatura = false) + { + decimal? nullable2; + object list; + bool count; + decimal? porcentagemRepasse; + string str = "CAST(d.vigencia1 AS DATE)"; + string referencia = filtro.Referencia; + if (referencia == "EMISSÃO") + { + str = "CAST(d.emissao AS DATE)"; + } + else if (referencia == "TRANSMISSÃO PROPOSTA") + { + str = "CAST(d.remessa AS DATE)"; + } + else if (referencia == "DATA CRIAÇÃO" || referencia == "DATA DE CADASTRO") + { + str = "CAST(d.cri_data AS DATE)"; + } + List vinculoVendedores = filtro.VinculoVendedores; + if (vinculoVendedores != null) + { + IEnumerable nums = vinculoVendedores.Except(filtro.Vendedores); + if (nums != null) + { + list = nums.ToList(); + } + else + { + list = null; + } + } + else + { + list = null; + } + if (list == null) + { + list = new List(); + } + if (!((IEnumerable)list).Any()) + { + filtro.Vendedores = new List(); + } + List condicaos = this.CriaCondicaoDocumento(filtro, str); + Condicao condicao = new Condicao() + { + Campo = "d.Tipo", + Valores = 1.CriarValor() + }; + condicaos.Add(condicao); + List condicaos1 = new List(); + Condicao condicao1 = new Condicao() + { + Campo = "d.Excluido", + Valores = null, + Grupo = 1, + Operacao = Operacao.Or + }; + condicaos1.Add(condicao1); + Condicao condicao2 = new Condicao() + { + Campo = "d.Excluido", + Valores = "0".CriarValor(), + Grupo = 1, + Operacao = Operacao.Or + }; + condicaos1.Add(condicao2); + condicaos.AddRange(condicaos1); + List documentos = await this.BuscaDocumentosPorCondicao(filtro, condicaos, buscarAssinatura); + List vinculoVendedores1 = filtro.VinculoVendedores; + if (vinculoVendedores1 != null) + { + count = vinculoVendedores1.Count > 0; + } + else + { + count = false; + } + if (count) + { + List documentos1 = new List(); + foreach (Documento documento in documentos) + { + await this.BuscaVendedoresPorIdControle(documento.Controle.Id, documento.Controle.IdEmpresa).ForEach((VendedorParcela v) => { + if (!filtro.VinculoVendedores.Contains(v.Vendedor.Id)) + { + documentos1.Add(documento); + } + }); + } + documentos1.ForEach((Documento d) => this.documentos.Remove(d)); + } + foreach (Documento vendedor in documentos) + { + if (vendedor.Tipo == 1 && vendedor.VendedorPrincipal == null && vendedor.Pagamentos.Count < 2) + { + List vendedorParcelas = await this.BuscaVendedoresPorIdControle(vendedor.Controle.Id, vendedor.Controle.IdEmpresa); + vendedor.Pagamentos = vendedorParcelas; + List vendedorParcelas1 = vendedorParcelas; + VendedorParcela vendedorParcela = vendedorParcelas1.Find((VendedorParcela v) => v.TipoVendedor.Id == (long)1); + if (vendedorParcela != null) + { + vendedor.VendedorPrincipal = vendedorParcela.Vendedor; + } + List pagamentos = vendedor.Pagamentos; + IOrderedEnumerable vendedorParcelas2 = + from tipo in pagamentos + orderby tipo.TipoVendedor.Id + select tipo; + List vendedors = ( + from v in vendedorParcelas2 + select v.Vendedor).ToList(); + vendedor.Vendedores = vendedors; + Documento documento1 = vendedor; + VendedorParcela vendedorParcela1 = vendedor.Pagamentos.FirstOrDefault((VendedorParcela p) => { + long? nullable; + long id = p.Vendedor.Id; + Vendedor vendedorPrincipal = vendedor.VendedorPrincipal; + if (vendedorPrincipal != null) + { + nullable = new long?(vendedorPrincipal.Id); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + return id == nullable1.GetValueOrDefault() & nullable1.HasValue; + }); + if (vendedorParcela1 != null) + { + porcentagemRepasse = vendedorParcela1.PorcentagemRepasse; + } + else + { + nullable2 = null; + porcentagemRepasse = nullable2; + } + nullable2 = porcentagemRepasse; + documento1.PercentualRepasse = new decimal?(nullable2.GetValueOrDefault()); + } + } + List documentos2 = documentos; + return documentos2; + } + + public List FindPendenciasByVigencia(Filtros filtro) + { + object connection; + string str = (filtro.Status == null || filtro.Status.Count == 0 ? "" : string.Concat(" AND situacao IN (", string.Join(",", + from v in filtro.Status + select v), ")")); + string str1 = (filtro.Negocio == null || filtro.Negocio.Count == 0 ? "" : string.Concat(" AND NegocioCorretora IN (", string.Join(",", + from v in filtro.Negocio + select v), ")")); + string str2 = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND c.idciaseg IN (", string.Join(",", + from v in filtro.Seguradoras + select v), ")")); + string str3 = (filtro.Ramos == null || filtro.Ramos.Count == 0 ? "" : string.Concat(" AND c.idramo IN (", string.Join(",", + from v in filtro.Ramos + select v), ")")); + string str4 = (filtro.Produtos == null || filtro.Produtos.Count == 0 ? "" : string.Concat(" AND c.idproduto IN (", string.Join(",", + from v in filtro.Produtos + select v), ")")); + string str5 = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? "" : string.Concat(" AND vp.idvendedor IN (", string.Join(",", + from v in filtro.Vendedores + select v), ")")); + string str6 = (filtro.TipoVendedor == null || filtro.TipoVendedor.Count == 0 ? "OUTER APPLY (SELECT TOP 1 idvendedor FROM vendedorparcela vp WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor = 1) vp" : string.Concat("INNER JOIN vendedorparcela vp ON vp.iddocumento = d.iddocumento AND vp.idtipovendedor IN (", string.Join(",", + from v in filtro.TipoVendedor + select v), ")")); + string str7 = (filtro.Estipulantes == null || filtro.Estipulantes.Count == 0 ? "" : string.Concat(" AND d.idestipulante IN (", string.Join(",", + from v in filtro.Estipulantes + select v), ")")); + string str8 = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", filtro.IdEmpresa)); + DataTable dataTable1 = new DataTable(); + DataTable dataTable2 = new DataTable(); + DataTable dataTable3 = new DataTable(); + DataTable dataTable4 = new DataTable(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandTimeout = 15000; + Auxiliar.CriarAuxiliar(sqlCommand, false); + string str9 = string.Concat("SELECT DISTINCT cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome as cliente, cl.cgccpf, d.idcontrole, d.iddocumento as id, d.proposta, d.pedadit as propostaendosso, d.idnegocio, d.situacao, d.vigencia1 as vigenciainicial, d.vigencia2 as vigenciafinal, d.pr_total as total, d.pr_liq as liquido, d.pr_adic as adicional, ISNULL(d.com01, 0.00) as comissao, ISNULL(d.adinacomis, '0') as adinacomiss, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, vp.idvendedor, d.idestipulante, d.tiporecebimento, d.datacontrole, d.idstatus, d.pasta, d.idbanco, cb.nomebanco, d.conta, d.agencia, cl.pasta as pastacliente, c.AssistenciaId FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente LEFT OUTER JOIN codigobanco cb on cb.idcodigobanco = d.idbanco ", str6, " WHERE (d.excluido IS NULL OR d.excluido = 0) AND (cl.excluido = 0 OR cl.excluido IS NULL) AND CASE \tWHEN ( d.tipo = 0 ) THEN DATALENGTH(ISNULL( d.contrato, '' )) ELSE DATALENGTH(ISNULL( d.aditamento, '' )) END < 1 "); + string str10 = "SELECT DISTINCT d.idcontrole, idvendedor FROM vendedorparcela vp INNER JOIN documento d on d.iddocumento = vp.iddocumento WHERE 1=1 "; + string str11 = "SELECT DISTINCT iddocumento as id, idvendedor FROM vendedorparcela vp WHERE 1=1 "; + string str12 = "SELECT i.iditem, d.iddocumento, d.idcontrole, i.descricao FROM item i INNER JOIN documento d on d.iddocumento = i.iddocumento WHERE (cancelado IS NULL OR cancelado != '1') AND idsubstituido IS NULL "; + string str13 = "SELECT * FROM VinculoDocumento WHERE 1=1 "; + sqlCommand.CommandText = string.Format("{0} {1} AND d.vigencia1 >= '{2:yyyy-MM-dd}' AND d.vigencia1 <= '{3:yyyy-MM-dd}' {4} {5} {6} {7} {8} {9} {10}", new object[] { str9, str8, filtro.Inicio, filtro.Fim, str, str1, str2, str3, str4, str7, str5 }); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable1); + } + if (dataTable1.Rows.Count != 0) + { + if (dataTable1.AsEnumerable().Any((DataRow x) => x.Field("idvendedor") == null)) + { + string str14 = string.Concat(" AND d.idcontrole IN (", string.Join(",", dataTable1.AsEnumerable().Where((DataRow x) => x.Field("idvendedor") == null).Select((DataRow v) => v.Field("idcontrole"))), ")"); + DataTable dataTable5 = new DataTable(); + sqlCommand.CommandText = string.Concat(new string[] { str10, " ", str14, " ", str5 }); + using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) + { + sqlDataAdapter1.SelectCommand = sqlCommand; + sqlDataAdapter1.Fill(dataTable5); + } + foreach (DataRow row in dataTable1.Rows) + { + if (!string.IsNullOrEmpty(row["idvendedor"].ToString())) + { + continue; + } + string str15 = string.Format("idcontrole = {0}", row["idcontrole"]); + DataRow[] dataRowArray = dataTable5.Select(str15); + if (dataRowArray.Length == 0) + { + continue; + } + row["idvendedor"] = dataRowArray[0][1]; + } + } + string str16 = string.Concat(" AND vp.iddocumento IN (", string.Join(",", dataTable1.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); + sqlCommand.CommandText = string.Concat(str11, " ", str16); + using (SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter()) + { + sqlDataAdapter2.SelectCommand = sqlCommand; + sqlDataAdapter2.Fill(dataTable2); + } + string str17 = string.Concat(" AND d.idcontrole IN (", string.Join(",", dataTable1.AsEnumerable().Select((DataRow v) => v.Field("idcontrole"))), ")"); + sqlCommand.CommandText = string.Concat(str12, " ", str17); + using (SqlDataAdapter sqlDataAdapter3 = new SqlDataAdapter()) + { + sqlDataAdapter3.SelectCommand = sqlCommand; + sqlDataAdapter3.Fill(dataTable3); + } + try + { + string str18 = string.Concat(" AND IdDocumento IN (", string.Join(",", ( + from x in dataTable1.AsEnumerable().ToList() + select x.Field("id")).ToList()), ")"); + sqlCommand.CommandText = string.Concat(str13, " ", str18); + using (SqlDataAdapter sqlDataAdapter4 = new SqlDataAdapter()) + { + sqlDataAdapter4.SelectCommand = sqlCommand; + sqlDataAdapter4.Fill(dataTable4); + } + } + catch (Exception exception) + { + dataTable4 = null; + } + } + else + { + return new List(); + } + } + } + return dataTable1.AsEnumerable().ToList().Select((DataRow x) => { + VinculoDocumento vinculoDocumento; + Func func2 = null; + Documento documento = new Documento() + { + Id = x.Field("id"), + Controle = new Controle() + { + IdEmpresa = x.Field("idempresa"), + Cliente = new Cliente() + { + Id = x.Field("idcliente"), + Nome = x.Field("cliente"), + Documento = x.Field("cgccpf"), + IdEmpresa = x.Field("idempresa"), + Pasta = x.Field("pastacliente"), + MalaDireta = new bool?(x.Field("MalaDireta").GetValueOrDefault(true)) + }, + Seguradora = (x.Field("idseguradora") != null ? Auxiliar.Seguradoras.FirstOrDefault((Seguradora p) => p.Id == x.Field("idseguradora")) : null), + Ramo = (x.Field("idramo") != null ? Auxiliar.Ramos.FirstOrDefault((Ramo p) => p.Id == x.Field("idramo")) : null), + Produto = (x.Field("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault((Gestor.Model.Domain.Seguros.Produto p) => p.Id == x.Field("idproduto")) : null), + AssistenciaId = x.Field("AssistenciaId") + }, + TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), x.Field("tiporecebimento").ToString())), + AdicionalComiss = x.Field("adinacomiss") == "1", + Proposta = x.Field("proposta"), + PropostaEndosso = x.Field("propostaendosso"), + Comissao = x.Field("comissao"), + Negocio = new Negocio?((x.Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field("idnegocio").ToString()))), + PremioLiquido = x.Field("liquido"), + PremioTotal = x.Field("total"), + Vigencia2 = x.Field("vigenciafinal") + }; + DateTime? nullable = x.Field("vigenciainicial"); + documento.Vigencia1 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue); + documento.VendedorPrincipal = (x.Field("idvendedor") != null ? Auxiliar.Vendedores.FirstOrDefault((Vendedor p) => p.Id == x.Field("idvendedor")) : null); + documento.Estipulante1 = (x.Field("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault((Estipulante p) => p.Id == x.Field("idestipulante")) : null); + documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()); + documento.Vendedores = Auxiliar.Vendedores.Where((Vendedor v) => { + List list = dataTable2.AsEnumerable().ToList(); + Func u003cu003e9_26 = func2; + if (u003cu003e9_26 == null) + { + Func func = (DataRow d) => d.Field("id") == x.Field("id"); + Func func1 = func; + func2 = func; + u003cu003e9_26 = func1; + } + IEnumerable dataRows = list.Where(u003cu003e9_26); + Func u003cu003e9_3927 = DocumentoRepository.u003cu003ec.u003cu003e9__39_27; + if (u003cu003e9_3927 == null) + { + u003cu003e9_3927 = (DataRow d) => d.Field("idvendedor"); + DocumentoRepository.u003cu003ec.u003cu003e9__39_27 = u003cu003e9_3927; + } + return dataRows.Select(u003cu003e9_3927).ToList().Contains(v.Id); + }).ToList(); + documento.Tipo = x.Field("tipo"); + documento.DataControle = x.Field("datacontrole"); + documento.Status = (x.Field("idstatus") != null ? Auxiliar.StatusApolice.FirstOrDefault((Status p) => p.Id == x.Field("idstatus")) : null); + IEnumerable dataRows1 = + from i in dataTable3.AsEnumerable().ToList() + where i.Field("idcontrole") == x.Field("idcontrole") + select i; + Func u003cu003e9_3920 = DocumentoRepository.u003cu003ec.u003cu003e9__39_20; + if (u003cu003e9_3920 == null) + { + u003cu003e9_3920 = (DataRow i) => new Item() + { + Id = i.Field("iditem"), + Descricao = i.Field("descricao") + }; + DocumentoRepository.u003cu003ec.u003cu003e9__39_20 = u003cu003e9_3920; + } + documento.ItensAtivo = new List(dataRows1.Select(u003cu003e9_3920).ToList()); + DataTable dataTable = dataTable4; + if (dataTable != null) + { + EnumerableRowCollection dataRows2 = dataTable.AsEnumerable().Where((DataRow v) => v.Field("IdDocumento") == x.Field("id")); + Func u003cu003e9_3922 = DocumentoRepository.u003cu003ec.u003cu003e9__39_22; + if (u003cu003e9_3922 == null) + { + u003cu003e9_3922 = (DataRow v) => new VinculoDocumento() + { + Id = v.Field("Id"), + IdDocumento = v.Field("IdDocumento"), + IdPropostaDigital = v.Field("IdPropostaDigital"), + IdApoliceDigital = v.Field("IdApoliceDigital") + }; + DocumentoRepository.u003cu003ec.u003cu003e9__39_22 = u003cu003e9_3922; + } + vinculoDocumento = dataRows2.Select(u003cu003e9_3922).FirstOrDefault(); + } + else + { + vinculoDocumento = null; + } + documento.Vinculo = vinculoDocumento; + documento.Pasta = x.Field("Pasta"); + documento.Banco = new Banco() + { + Nome = x.Field("nomebanco") + }; + documento.Agencia = x.Field("agencia"); + documento.Conta = x.Field("conta"); + return documento; + }).ToList(); + } + + public bool HasSinistro(long id) + { + return (new ControleSinistroRepository(this._unitOfWork)).DocumentoHasSinistro(id); + } + + public bool HasSinistroPorControle(long controleId) + { + return (new ControleSinistroRepository(this._unitOfWork)).HasSinistro(controleId); + } + + public Documento Merge(Documento documento) + { + bool id; + Status status = documento.Status; + if (status != null) + { + id = status.Id == (long)0; + } + else + { + id = false; + } + if (id) + { + documento.Status = null; + } + if (!documento.DataCriacao.HasValue) + { + documento.DataCriacao = new DateTime?(Gestor.Infrastructure.Helpers.Funcoes.GetNetworkTime()); + } + DocumentoDb documentoDb = ApplicationMapper.Mapper.Map(documento); + base.Merge(documentoDb); + documento = ApplicationMapper.Mapper.Map(documentoDb); + documento.VendedorPrincipal = (new VendedorParcelaRepository(this._unitOfWork)).FindByMainDocumentId(documento.Id); + return documento; + } + + public void SalvarAssistencia(string id, long idcontrole) + { + ControleDb controleDb = this._unitOfWork.Query().FirstOrDefault((ControleDb x) => x.Id == idcontrole); + if (controleDb == null) + { + return; + } + controleDb.AssistenciaId = id; + this._unitOfWork.Repository().Merge(controleDb); + } + + public Documento SaveOrUpdate(Documento documento) + { + bool id; + Status status = documento.Status; + if (status != null) + { + id = status.Id == (long)0; + } + else + { + id = false; + } + if (id) + { + documento.Status = null; + } + if (!documento.DataCriacao.HasValue) + { + documento.DataCriacao = new DateTime?(Gestor.Infrastructure.Helpers.Funcoes.GetNetworkTime()); + } + DocumentoDb documentoDb = ApplicationMapper.Mapper.Map(documento); + this.SaveOrUpdate(documentoDb); + documento = ApplicationMapper.Mapper.Map(documentoDb); + documento.VendedorPrincipal = (new VendedorParcelaRepository(this._unitOfWork)).FindByMainDocumentId(documento.Id); + return documento; + } + + private List Select(SqlQueryCondition sqlCondition) + { + DataTable dataTable = this._unitOfWork.Select(sqlCondition, "SELECT DISTINCT c.idcliente, cl.MalaDireta, cl.cgccpf, c.idempresa, c.idcontrole, c.idciaseg, c.idramo, c.idproduto, d.iddocumento, d.adinacomis, d.pr_adic, d.proposta, d.pedadit, d.contrato, d.aditamento, d.com01, d.idnegocio, d.pr_liq, d.pr_total, d.vigencia1, d.vigencia2, d.emissao, d.remessa, d.idestipulante, d.negociocorretora, d.situacao, d.tiporecebimento, CAST(d.tipo AS INTEGER) AS tipo, CAST(d.ordem AS INTEGER) AS ordem, d.n_parc AS numeroParcelas, d.pasta, d.banco, cb.nomebanco, d.agencia, d.conta, d.excluido, c.AssistenciaId, d.numeroCart, d.vencimentoCart, d.nomeProp, d.formapagamento, d.Obs FROM controle c INNER JOIN documento d ON d.idcontrole = c.idcontrole LEFT OUTER JOIN codigobanco cb on cb.idcodigobanco = d.idbanco INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE ", ""); + if (dataTable == null || dataTable.Rows.Count == 0) + { + return new List(); + } + this._unitOfWork.CriarAuxiliar(); + List list = dataTable.AsEnumerable().Select((DataRow x) => x.Field("idcontrole")).Distinct().ToList(); + List nums = (new ControleSinistroRepository(this._unitOfWork)).HasSinistro(list); + return dataTable.MapDocumento(nums); + } + + private async Task SomaComissaoPaga(int tipo, List fechamentos, Filtros filtro, List condicaoDocumento) + { + object connection; + long num; + using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) + { + SessionFactoryImpl sessionFactoryImpl = sessionFactory; + if (sessionFactoryImpl != null) + { + connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + string str = "c.IdCiaSeg"; + string str1 = "SUM(vp.vlrrep)"; + string str2 = "FROM vendedorparcela vp INNER JOIN documento d ON vp.iddocumento = d.iddocumento INNER JOIN controle c ON c.IdControle = d.IdControle"; + string str3 = "vp.DataPgt IS NOT NULL AND"; + switch (tipo) + { + case 1: + { + str = "c.IdRamo"; + break; + } + case 2: + { + str = "d.IdEstipulante"; + break; + } + case 3: + { + str = "vp.IdVendedor"; + break; + } + } + SqlQueryCondition sqlQueryCondition = condicaoDocumento.CreateParameters(0); + sqlCommand.CommandTimeout = 1000; + SqlCommand sqlCommand1 = sqlCommand; + string[] condicao = new string[] { "SELECT ", str, " Id,", str1, " Paga ", str2, " WHERE ", str3, " ", sqlQueryCondition.Condicao, " GROUP BY ", str }; + sqlCommand1.CommandText = string.Concat(condicao); + sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray()); + using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) + { + while (true) + { + if (!await sqlDataReader.ReadAsync()) + { + break; + } + bool flag = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("Id")); + num = (flag ? (long)0 : (long)sqlDataReader["Id"]); + long num1 = num; + decimal item = (decimal)sqlDataReader["Paga"]; + if (num1 != 0) + { + Fechamento fechamento = fechamentos.FirstOrDefault((Fechamento f) => { + if (f.Entidade != tipo) + { + return false; + } + return f.Id == num1; + }); + if (fechamento != null) + { + Fechamento paga = fechamento; + paga.Paga = paga.Paga + item; + } + } + } + } + sqlDataReader = null; + } + sqlCommand = null; + } + sqlConnection = null; + } + sessionFactory = null; + } + + private async Task SomaComissaoRecebida(int tipo, List fechamentos, Filtros filtro, List condicaoDocumento) + { + object connection; + bool flag; + bool count; + string str; + long num; + string empty; + bool count1; + bool flag1; + using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) + { + SessionFactoryImpl sessionFactoryImpl = sessionFactory; + if (sessionFactoryImpl != null) + { + connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + List vendedores = Auxiliar.Vendedores; + long id = vendedores.FirstOrDefault((Vendedor v) => v.Corretora).Id; + string str1 = "c.IdCiaSeg"; + string str2 = "SUM(p.vlrcomiss)"; + string str3 = "FROM parcela p INNER JOIN documento d ON p.iddocumento = d.iddocumento INNER JOIN controle c ON c.IdControle = d.IdControle"; + string str4 = "p.DataRec IS NOT NULL AND"; + switch (tipo) + { + case 1: + { + str1 = "c.IdRamo"; + break; + } + case 2: + { + str1 = "d.IdEstipulante"; + break; + } + case 3: + { + str1 = string.Format("CASE WHEN vp.IdVendedor IS NULL THEN {0} ELSE vp.IdVendedor END", id); + break; + } + } + bool flag2 = filtro.Vendedores.Contains(id); + string str5 = ""; + if (tipo == 3 && !flag2) + { + List tipoVendedor = filtro.TipoVendedor; + if (tipoVendedor != null) + { + count1 = tipoVendedor.Count > 0; + } + else + { + count1 = false; + } + if (!count1) + { + List nums = filtro.Vendedores; + if (nums != null) + { + flag1 = nums.Count > 0; + } + else + { + flag1 = false; + } + if (!flag1) + { + goto Label1; + } + } + str5 = "LEFT JOIN vendedorparcela vp ON p.IDPARCELA = vp.IDPARCELA"; + goto Label0; + } + Label1: + string empty1 = string.Empty; + flag = (filtro.TipoVendedor == null ? false : filtro.TipoVendedor.Count > 0); + bool flag3 = flag; + if (filtro.TipoVendedor != null && filtro.TipoVendedor.Count > 0) + { + if (flag3) + { + List tipoVendedor1 = filtro.TipoVendedor; + empty = string.Join(",", + from t in tipoVendedor1 + select t.Value().ToString() ?? ""); + } + else + { + empty = string.Empty; + } + empty1 = empty; + } + List nums1 = filtro.TipoVendedor; + if (nums1 != null) + { + count = nums1.Count > 0; + } + else + { + count = false; + } + str = (count ? string.Concat("OUTER APPLY ( SELECT TOP 1 idvendedor, idtipovendedor FROM vendedorparcela vp WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor IN (", empty1, ")) vp") : "OUTER APPLY (SELECT TOP 1 idvendedor FROM vendedorparcela vp WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor = 1) vp"); + str5 = str; + Label0: + SqlQueryCondition sqlQueryCondition = condicaoDocumento.CreateParameters(0); + sqlCommand.CommandTimeout = 1000; + SqlCommand sqlCommand1 = sqlCommand; + string[] condicao = new string[] { "SELECT ", str1, " as Id,", str2, " Recebida ", str3, " ", str5, " WHERE ", str4, " ", sqlQueryCondition.Condicao, " GROUP BY ", str1 }; + sqlCommand1.CommandText = string.Concat(condicao); + sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray()); + using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) + { + while (true) + { + if (!await sqlDataReader.ReadAsync()) + { + break; + } + bool flag4 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("Id")); + num = (flag4 ? (long)0 : (long)sqlDataReader["Id"]); + long num1 = num; + decimal item = (decimal)sqlDataReader["Recebida"]; + if (num1 != 0) + { + Fechamento fechamento = fechamentos.FirstOrDefault((Fechamento f) => { + if (f.Entidade != tipo) + { + return false; + } + return f.Id == num1; + }); + if (fechamento != null) + { + Fechamento recebida = fechamento; + recebida.Recebida = recebida.Recebida + item; + } + } + } + } + sqlDataReader = null; + } + sqlCommand = null; + } + sqlConnection = null; + } + sessionFactory = null; + } + + public void TrocarCliente(Controle controle, Cliente cliente) + { + ControleDb controleDb = this._unitOfWork.Repository().FindEntityById(controle.Id); + controleDb.Cliente = ApplicationMapper.Mapper.Map(cliente); + this._unitOfWork.Repository().Merge(controleDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/EmpresaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/EmpresaRepository.cs new file mode 100644 index 0000000..4d51e87 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/EmpresaRepository.cs @@ -0,0 +1,143 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class EmpresaRepository : GenericRepository, IEmpresaRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public EmpresaRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public string BuscarSenhaAdm(long idempresa = 1L) + { + EmpresaDb empresaDb = base.All().FirstOrDefault((EmpresaDb x) => x.Id == idempresa); + if (empresaDb != null) + { + return empresaDb.SenhaAdmin; + } + return null; + } + + public double ConsultaEspacoBancoInGb() + { + double num; + object connection; + using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) + { + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = "EXEC sp_spaceused @oneresultset = '1'"; + SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); + if (!sqlDataReader.HasRows) + { + return 0; + } + else + { + sqlDataReader.Read(); + double num1 = double.Parse(sqlDataReader["reserved"].ToString().Replace("KB", string.Empty).Trim()); + double num2 = double.Parse(sqlDataReader["unallocated space"].ToString().Replace("MB", string.Empty).Replace(".", ",").Trim()); + num = (num1 / 1024 + num2) / 1024; + } + } + } + } + return num; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public List Find(long idempresa = 0L) + { + return ( + from x in (idempresa == 0 ? base.All() : + from x in base.All() + where x.Id == idempresa + select x) + select new Empresa() + { + Id = x.Id, + Nome = x.Nome, + Documento = x.Documento, + Serial = x.Serial + }).ToList(); + } + + public List FindAsCliente(string filter) + { + EmpresaRepository.u003cu003ec__DisplayClass9_0 variable = null; + IQueryable empresaDbs = base.All(); + ParameterExpression parameterExpression = Expression.Parameter(typeof(EmpresaDb), "x"); + IQueryable empresaDbs1 = empresaDbs.Where(Expression.Lambda>(Expression.OrElse(Expression.OrElse(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(EmpresaDb).GetMethod("get_Nome").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(EmpresaRepository.u003cu003ec__DisplayClass9_0)), FieldInfo.GetFieldFromHandle(typeof(EmpresaRepository.u003cu003ec__DisplayClass9_0).GetField("filter").FieldHandle)) }), Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(EmpresaDb).GetMethod("get_Documento").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(EmpresaRepository.u003cu003ec__DisplayClass9_0)), FieldInfo.GetFieldFromHandle(typeof(EmpresaRepository.u003cu003ec__DisplayClass9_0).GetField("filter").FieldHandle)) })), Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(EmpresaDb).GetMethod("get_Serial").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(EmpresaRepository.u003cu003ec__DisplayClass9_0)), FieldInfo.GetFieldFromHandle(typeof(EmpresaRepository.u003cu003ec__DisplayClass9_0).GetField("filter").FieldHandle)) })), new ParameterExpression[] { parameterExpression })); + parameterExpression = Expression.Parameter(typeof(EmpresaDb), "x"); + return empresaDbs1.Select(Expression.Lambda>(Expression.MemberInit(Expression.New(typeof(Cliente)), new MemberBinding[] { Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(DomainBase).GetMethod("set_Id", new Type[] { typeof(long) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(EntityBase).GetMethod("get_Id").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Cliente).GetMethod("set_Nome", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(EmpresaDb).GetMethod("get_Nome").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Cliente).GetMethod("set_Documento", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(EmpresaDb).GetMethod("get_Documento").MethodHandle))) }), new ParameterExpression[] { parameterExpression })).ToList(); + } + + public Empresa FindByDocumento(string documento) + { + EmpresaDb empresaDb = base.All().FirstOrDefault((EmpresaDb e) => e.Documento.Replace(",", string.Empty).Replace(".", string.Empty).Replace("-", string.Empty).Replace("/", string.Empty).Equals(documento)) ?? base.All().First(); + return ApplicationMapper.Mapper.Map(empresaDb); + } + + public Empresa FindById(long id) + { + EmpresaDb empresaDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(empresaDb); + } + + public Empresa FindBySerial(string serial) + { + EmpresaDb empresaDb = base.All().FirstOrDefault((EmpresaDb e) => e.Serial.Equals(serial)) ?? base.All().First(); + return ApplicationMapper.Mapper.Map(empresaDb); + } + + public Empresa Merge(Empresa empresa) + { + EmpresaDb empresaDb = ApplicationMapper.Mapper.Map(empresa); + base.Merge(empresaDb); + return ApplicationMapper.Mapper.Map(empresaDb); + } + + public Empresa SaveOrUpdate(Empresa empresa) + { + EmpresaDb empresaDb = ApplicationMapper.Mapper.Map(empresa); + this.SaveOrUpdate(empresaDb); + return ApplicationMapper.Mapper.Map(empresaDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/EstipulanteRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/EstipulanteRepository.cs new file mode 100644 index 0000000..b0ab6cd --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/EstipulanteRepository.cs @@ -0,0 +1,93 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class EstipulanteRepository : GenericRepository, IEstipulanteRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public EstipulanteRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public List Find(string value, long idempresa = 0L) + { + string str = (idempresa == 0 ? string.Format(" AND idempresa = {0}", idempresa) : ""); + string str1 = string.Concat(new string[] { " AND (UPPER(ISNULL(nome, '')) LIKE '%", value.ToUpper(), "%' OR UPPER(ISNULL(cpfcnpj, '')) LIKE '%", value.ToUpper(), "%') " }); + return this.Select(string.Concat(str, str1)); + } + + public List Find() + { + return this.Select(""); + } + + public Estipulante FindById(long id) + { + EstipulanteDb estipulanteDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(estipulanteDb); + } + + public Estipulante Merge(Estipulante estipulante) + { + EstipulanteDb estipulanteDb = ApplicationMapper.Mapper.Map(estipulante); + base.Merge(estipulanteDb); + return ApplicationMapper.Mapper.Map(estipulanteDb); + } + + public Estipulante SaveOrUpdate(Estipulante estipulante) + { + EstipulanteDb estipulanteDb = ApplicationMapper.Mapper.Map(estipulante); + this.SaveOrUpdate(estipulanteDb); + return ApplicationMapper.Mapper.Map(estipulanteDb); + } + + private List Select(string condition) + { + object connection; + DataTable dataTable = new DataTable(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = string.Concat("SELECT DISTINCT * FROM estipulante WHERE 1=1 ", condition, ";"); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + } + } + return dataTable.MapEstipulante(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ExpedicaoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ExpedicaoRepository.cs new file mode 100644 index 0000000..e568567 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ExpedicaoRepository.cs @@ -0,0 +1,55 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class ExpedicaoRepository : GenericRepository, IExpedicaoRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public ExpedicaoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public List FindByIdDocumento(long IdDocumento) + { + List list = ( + from x in base.All() + where x.Apolice.Id == IdDocumento + orderby x.DataEnvio descending + select x).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public Expedicao Merge(Expedicao expedicao) + { + ExpedicaoDb expedicaoDb = ApplicationMapper.Mapper.Map(expedicao); + base.Merge(expedicaoDb); + return ApplicationMapper.Mapper.Map(expedicaoDb); + } + + public Expedicao SaveOrUpdate(Expedicao expedicao) + { + ExpedicaoDb expedicaoDb = ApplicationMapper.Mapper.Map(expedicao); + this.SaveOrUpdate(expedicaoDb); + return ApplicationMapper.Mapper.Map(expedicaoDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ExtratoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ExtratoRepository.cs new file mode 100644 index 0000000..ff4afc6 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ExtratoRepository.cs @@ -0,0 +1,237 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Helpers; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class ExtratoRepository : GenericRepository, IExtratoRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public ExtratoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + List list = ( + from x in this._unitOfWork.Query() + where x.Extrato.Id == id + select x).ToList(); + if (list.Count > 0) + { + this._unitOfWork.Repository().DeleteRange(list); + } + ExtratoDb extratoDb = base.FindEntityById(id); + if (extratoDb == null) + { + return; + } + base.Delete(extratoDb); + } + + public List FindByData(Filtros filtro) + { + string str = "CAST(datacriacao AS DATE)"; + string referencia = filtro.Referencia; + if (referencia == "DATA DO EXTRATO") + { + str = "CAST(data AS DATE)"; + } + else if (referencia == "DATA DO CRÉDITO") + { + str = "CAST(DataCredito AS DATE)"; + } + List condicaos = new List() + { + new Condicao() + { + Campo = str, + Valores = filtro.Inicio.CriarValor(), + Operador = Operador.MaiorEIgual + }, + new Condicao() + { + Campo = str, + Valores = filtro.Fim.CriarValor(), + Operador = Operador.MenorEIgual + }, + new Condicao() + { + Campo = "idstatusextrato", + Valores = null, + Operador = Operador.Diferente, + Grupo = 1, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "idstatusextrato", + Valores = "1".CriarValor(), + Operador = Operador.Diferente, + Grupo = 1, + Operacao = Operacao.Or + } + }; + return CustomMap.MapExtrato(this._unitOfWork.Select(condicaos.CreateParameters(0), "SELECT * FROM EXTRATO WHERE ", ""), null); + } + + public List FindByEmpresa(long id) + { + List list = ( + from x in base.All() + where x.IdEmpresa == id + select x).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public Extrato FindById(long id) + { + ExtratoDb extratoDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(extratoDb); + } + + public List FindBySeguradora(long id, long idusuario, long empresa, DateTime inicio, DateTime fim, StatusExtrato? status = null) + { + List extratos; + object connection; + DataTable dataTable = new DataTable(); + DataTable dataTable1 = new DataTable(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + Auxiliar.CriarAuxiliar(sqlCommand, false); + string str = ""; + if (empresa > (long)1) + { + str = string.Format("idempresa = {0} AND", empresa); + } + string str1 = string.Format("SELECT * FROM EXTRATO WHERE {0} data >= '{1:yyyy-MM-dd}' AND data <= '{2:yyyy-MM-dd}'", str, inicio, fim); + if (id > (long)0) + { + str1 = string.Concat(str1, string.Format(" AND idciaseg = {0}", id)); + } + if (idusuario > (long)0) + { + str1 = string.Concat(str1, string.Format(" AND usuariocriacao = {0}", idusuario)); + } + if (status.HasValue) + { + StatusExtrato valueOrDefault = status.GetValueOrDefault(); + if (valueOrDefault == StatusExtrato.Pendente) + { + str1 = string.Concat(str1, " AND (idstatusextrato IS NULL OR idstatusextrato = 1)"); + } + else if (valueOrDefault == StatusExtrato.Baixado) + { + str1 = string.Concat(str1, " AND idstatusextrato IS NOT NULL AND idstatusextrato != 1"); + } + } + sqlCommand.CommandText = str1; + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + if (dataTable.Rows.Count != 0) + { + string str2 = string.Concat(" AND idextrato IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("idextrato"))), ")"); + List nums = new List() + { + 13, + 1, + 10, + 5, + 12, + 6, + 8, + 21 + }; + sqlCommand.CommandText = string.Concat("SELECT idextrato, idparcelaextrato FROM parcelaextrato WHERE idstatusparcela NOT IN (", string.Join(",", + from v in nums + select v), ") ", str2); + using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) + { + sqlDataAdapter1.SelectCommand = sqlCommand; + sqlDataAdapter1.Fill(dataTable1); + return CustomMap.MapExtrato(dataTable, dataTable1); + } + } + else + { + extratos = new List(); + } + } + } + return extratos; + } + + public List FindByStatus(StatusExtrato status) + { + List list = ( + from x in base.All() + where (int)x.Status == (int)status + select x).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public List FindSeguradoras(StatusExtrato status) + { + return ( + from x in ( + from x in base.All() + where (int)x.Status == (int)status + select x.Seguradora).ToList() + group x by x.Id into x + select new Seguradora() + { + Id = x.Key, + Nome = x.First().Nome + }).ToList(); + } + + public Extrato Merge(Extrato extrato) + { + ExtratoDb extratoDb = ApplicationMapper.Mapper.Map(extrato); + base.Merge(extratoDb); + return ApplicationMapper.Mapper.Map(extratoDb); + } + + public Extrato SaveOrUpdate(Extrato extrato) + { + ExtratoDb extratoDb = ApplicationMapper.Mapper.Map(extrato); + this.SaveOrUpdate(extratoDb); + return ApplicationMapper.Mapper.Map(extratoDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/FabricanteRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/FabricanteRepository.cs new file mode 100644 index 0000000..609964c --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/FabricanteRepository.cs @@ -0,0 +1,65 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + internal class FabricanteRepository : GenericRepository, IFabricanteRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public FabricanteRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public List Find(string filter) + { + FabricanteRepository.u003cu003ec__DisplayClass7_0 variable = null; + IQueryable fabricanteDbs = base.All(); + ParameterExpression parameterExpression = Expression.Parameter(typeof(FabricanteDb), "x"); + List list = fabricanteDbs.Where(Expression.Lambda>(Expression.Call(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(FabricanteDb).GetMethod("get_Descricao").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Trim").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(FabricanteRepository.u003cu003ec__DisplayClass7_0)), FieldInfo.GetFieldFromHandle(typeof(FabricanteRepository.u003cu003ec__DisplayClass7_0).GetField("filter").FieldHandle)) }), new ParameterExpression[] { parameterExpression })).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public Fabricante FindById(long id) + { + FabricanteDb fabricanteDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(fabricanteDb); + } + + public Fabricante Merge(Fabricante fabricante) + { + FabricanteDb fabricanteDb = ApplicationMapper.Mapper.Map(fabricante); + base.Merge(fabricanteDb); + return ApplicationMapper.Mapper.Map(fabricanteDb); + } + + public Fabricante SaveOrUpdate(Fabricante fabricante) + { + FabricanteDb fabricanteDb = ApplicationMapper.Mapper.Map(fabricante); + this.SaveOrUpdate(fabricanteDb); + return ApplicationMapper.Mapper.Map(fabricanteDb); + } + + public List Select() + { + return ApplicationMapper.Mapper.Map, List>(base.All().ToList()); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/FornecedorRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/FornecedorRepository.cs new file mode 100644 index 0000000..98ce65b --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/FornecedorRepository.cs @@ -0,0 +1,103 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Financeiro; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Financeiro; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class FornecedorRepository : GenericRepository, IFornecedorRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public FornecedorRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + FornecedorDb fornecedorDb = base.FindEntityById(id); + if (fornecedorDb == null) + { + return; + } + base.Delete(fornecedorDb); + } + + public List Find(string filter, bool ativo = false) + { + List fornecedors; + object connection; + DataTable dataTable = new DataTable(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + string str = string.Concat(new string[] { "(UPPER(nome) COLLATE Latin1_General_CI_AI LIKE '%", filter, "%' OR UPPER(cpfcnpj) LIKE '%", filter, "%' OR UPPER(fone1) LIKE '%", filter, "%' OR UPPER(fone2) LIKE '%", filter, "%' OR UPPER(email) LIKE '%", filter, "%')" }); + sqlCommand.CommandText = string.Concat("SELECT top 200 * FROM fornecedor WHERE ", str, " ", (ativo ? "AND Ativo = 1" : string.Empty)); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + if (dataTable.Rows.Count != 0) + { + return CustomMap.MapFornecedor(dataTable); + } + else + { + fornecedors = new List(); + } + } + } + return fornecedors; + } + + public List Find() + { + List list = this._unitOfWork.Session.CreateQuery("from FornecedorDb").List().ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public Fornecedor FindById(long id) + { + FornecedorDb fornecedorDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(fornecedorDb); + } + + public Fornecedor Merge(Fornecedor fornecedor) + { + FornecedorDb fornecedorDb = ApplicationMapper.Mapper.Map(fornecedor); + base.Merge(fornecedorDb); + return ApplicationMapper.Mapper.Map(fornecedorDb); + } + + public Fornecedor SaveOrUpdate(Fornecedor fornecedor) + { + FornecedorDb fornecedorDb = ApplicationMapper.Mapper.Map(fornecedor); + this.SaveOrUpdate(fornecedorDb); + return ApplicationMapper.Mapper.Map(fornecedorDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/GranizoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/GranizoRepository.cs new file mode 100644 index 0000000..ad6cdb6 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/GranizoRepository.cs @@ -0,0 +1,71 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class GranizoRepository : GenericRepository, IGranizoRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public GranizoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + GranizoDb granizoDb = base.FindEntityById(id); + if (granizoDb == null) + { + return; + } + base.Delete(granizoDb); + } + + public void DeleteRange(List ids) + { + List list = ( + from x in base.All() + where ids.Contains(x.Item.Id) + select x).ToList(); + base.DeleteRange(list); + } + + public Granizo Find(long id) + { + GranizoDb granizoDb = base.All().FirstOrDefault((GranizoDb x) => x.Item.Id == id) ?? new GranizoDb(); + return ApplicationMapper.Mapper.Map(granizoDb); + } + + public Granizo FindById(long id) + { + GranizoDb granizoDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(granizoDb); + } + + public Granizo Merge(Granizo granizo) + { + GranizoDb granizoDb = ApplicationMapper.Mapper.Map(granizo); + base.Merge(granizoDb); + return ApplicationMapper.Mapper.Map(granizoDb); + } + + public Granizo SaveOrUpdate(Granizo granizo) + { + GranizoDb granizoDb = ApplicationMapper.Mapper.Map(granizo); + this.SaveOrUpdate(granizoDb); + return ApplicationMapper.Mapper.Map(granizoDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ImpostoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ImpostoRepository.cs new file mode 100644 index 0000000..004432a --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ImpostoRepository.cs @@ -0,0 +1,102 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Helpers; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Ferramentas; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class ImpostoRepository : GenericRepository, IImpostoRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public ImpostoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public List DefaultSelect(bool? ativo) + { + string str; + if (!ativo.HasValue) + { + str = ""; + } + else + { + str = (ativo.Value ? " AND Ativo = 1" : " AND Ativo = 0"); + } + return this.Select(str); + } + + public Imposto FindById(long id) + { + ImpostoDb impostoDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(impostoDb); + } + + public List FindByRamo(long id) + { + return this.Select(string.Format(" AND idramo = {0}", id)); + } + + public List FindBySeguradora(long id) + { + return this.Select(string.Format(" AND idciaseg = {0}", id)); + } + + public Imposto Merge(Imposto imposto) + { + ImpostoDb impostoDb = ApplicationMapper.Mapper.Map(imposto); + base.Merge(impostoDb); + return ApplicationMapper.Mapper.Map(impostoDb); + } + + public Imposto SaveOrUpdate(Imposto imposto) + { + ImpostoDb impostoDb = ApplicationMapper.Mapper.Map(imposto); + this.SaveOrUpdate(impostoDb); + return ApplicationMapper.Mapper.Map(impostoDb); + } + + private List Select(string condition) + { + object connection; + DataTable dataTable = new DataTable(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + Auxiliar.CriarAuxiliar(sqlCommand, false); + sqlCommand.CommandText = string.Concat("SELECT * FROM Imposto WHERE 1=1 ", condition); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + } + } + return CustomMap.MapImposto(dataTable); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/IndiceArquivoDigitalRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/IndiceArquivoDigitalRepository.cs new file mode 100644 index 0000000..5d50ddf --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/IndiceArquivoDigitalRepository.cs @@ -0,0 +1,402 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Helpers; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class IndiceArquivoDigitalRepository : GenericRepository, IIndiceArquivoDigitalRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public IndiceArquivoDigitalRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public ControleArquivoDigital BuscarBanco() + { + ControleArquivoDigitalDb controleArquivoDigitalDb = ( + from x in this._unitOfWork.Query() + orderby x.Id descending + select x).First(); + return ApplicationMapper.Mapper.Map(controleArquivoDigitalDb); + } + + public List BuscarBancos() + { + List list = ( + from x in this._unitOfWork.Query() + orderby x.Id descending + select x).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public ControleArquivoDigital ConsultarBanco(string banco) + { + ControleArquivoDigitalDb controleArquivoDigitalDb = this._unitOfWork.Query().First((ControleArquivoDigitalDb x) => x.Catalogo == banco); + return ApplicationMapper.Mapper.Map(controleArquivoDigitalDb); + } + + public void Delete(long id) + { + IndiceArquivoDigitalDb indiceArquivoDigitalDb = base.FindEntityById(id); + if (indiceArquivoDigitalDb == null) + { + return; + } + base.Delete(indiceArquivoDigitalDb); + } + + public List Find(TipoArquivoDigital tipo, long id, long usuario, bool buscarAssinaturas = false) + { + object connection; + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + DataTable dataTable = new DataTable(); + DataTable dataTable1 = new DataTable(); + string str1 = ""; + switch (tipo) + { + case TipoArquivoDigital.Todos: + { + str1 = "idcliente = @id "; + break; + } + case TipoArquivoDigital.Cliente: + { + str1 = "idcliente = @id AND ISNULL(iddocumento, 0) = 0 AND ISNULL(iditem, 0) = 0 AND ISNULL(idvenctoaleatorio, 0) = 0 AND ISNULL(idparcela, 0) = 0 AND ISNULL(idsinistro, 0) = 0 "; + break; + } + case TipoArquivoDigital.Apolice: + { + str1 = "iddocumento = @id AND ISNULL(iditem, 0) = 0 AND ISNULL(idvenctoaleatorio, 0) = 0 AND ISNULL(idparcela, 0) = 0 AND ISNULL(idsinistro, 0) = 0 "; + break; + } + case TipoArquivoDigital.Parcela: + { + str1 = "idparcela = @id AND ISNULL(iditem, 0) = 0 AND ISNULL(idvenctoaleatorio, 0) = 0 AND ISNULL(idsinistro, 0) = 0 "; + break; + } + case TipoArquivoDigital.Item: + { + str1 = "iditem = @id AND ISNULL(idvenctoaleatorio, 0) = 0 AND ISNULL(idparcela, 0) = 0 AND ISNULL(idsinistro, 0) = 0 "; + break; + } + case TipoArquivoDigital.Sinistro: + { + str1 = "idsinistro = @id AND ISNULL(idvenctoaleatorio, 0) = 0 AND ISNULL(idparcela, 0) = 0 "; + break; + } + case TipoArquivoDigital.Vendedor: + { + str1 = "idvendedor = @id "; + break; + } + case TipoArquivoDigital.Extrato: + { + str1 = "idextrato = @id "; + break; + } + case TipoArquivoDigital.Seguradora: + { + str1 = "idciaseg = @id "; + break; + } + case TipoArquivoDigital.Lancamento: + { + str1 = "idlancamen = @id "; + break; + } + case TipoArquivoDigital.Fornecedor: + { + str1 = "idfornecedor = @id AND ISNULL(idlancamen, 0) = 0 "; + break; + } + case TipoArquivoDigital.Prospeccao: + { + str1 = "idvenctoaleatorio = @id "; + break; + } + case TipoArquivoDigital.Usuario: + { + str1 = "idusuarioarquivo = @id "; + break; + } + case TipoArquivoDigital.Empresa: + { + str1 = "idempresa = @id AND ISNULL(idcliente, 0) = 0 AND ISNULL(iddocumento, 0) = 0 AND ISNULL(iditem, 0) = 0 AND ISNULL(idvenctoaleatorio, 0) = 0 AND ISNULL(idparcela, 0) = 0 AND ISNULL(idsinistro, 0) = 0 AND ISNULL(idlancamen, 0) = 0 AND ISNULL(idfornecedor, 0) = 0 AND ISNULL(idextrato, 0) = 0 AND ISNULL(idciaseg, 0) = 0 AND ISNULL(idvendedor, 0) = 0 AND ISNULL(idusuarioarquivo, 0) = 0 AND ISNULL(idtarefa, 0) = 0 AND ISNULL(idsocio, 0) = 0 "; + break; + } + case TipoArquivoDigital.Socio: + { + str1 = "idsocio = @id "; + break; + } + case TipoArquivoDigital.Tarefa: + { + str1 = "IdTarefa = @id "; + break; + } + case TipoArquivoDigital.NotaFiscal: + { + str1 = "IdNotaFiscal = @id "; + break; + } + case TipoArquivoDigital.Estipulante: + { + str1 = "IdEstipulante = @id "; + break; + } + } + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = string.Concat("SELECT * FROM newarquivodigital WHERE ", (usuario == 0 ? "" : "(excluido IS NULL OR excluido != '1') AND"), " ", str1); + sqlCommand.Parameters.AddWithValue("@id", id); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + if (dataTable.Rows.Count != 0) + { + try + { + if (buscarAssinaturas) + { + List condicaos = new List() + { + new Condicao() + { + Campo = "IndiceId", + Valores = ( + from x in dataTable.AsEnumerable().ToList() + select x.Field("idnewarquivodigital")).ToList().CriarValor() + }, + new Condicao() + { + Campo = "excluido", + Valores = null, + Grupo = 2, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "excluido", + Valores = "1".CriarValor(), + Operador = Operador.Diferente, + Grupo = 2, + Operacao = Operacao.Or + } + }; + dataTable1 = sqlCommand.Select(condicaos.CreateParameters(0), "SELECT assinado, IndiceId, UrlAssinatura FROM ArquivoParaAssinatura WHERE ", ""); + } + } + catch (Exception exception) + { + dataTable1 = null; + } + } + else + { + return new List(); + } + } + } + return dataTable.AsEnumerable().ToList().Select((DataRow x) => { + string str; + IndiceArquivoDigital indiceArquivoDigital = new IndiceArquivoDigital() + { + Id = x.Field("idnewarquivodigital"), + IdArquivoDigital = x.Field("idarquivodigital"), + Bd = x.Field("banco"), + Descricao = x.Field("descricao"), + Extensao = x.Field("extension") + }; + long? nullable = x.Field("idcliente"); + indiceArquivoDigital.IdCliente = nullable.GetValueOrDefault(); + nullable = x.Field("iddocumento"); + indiceArquivoDigital.IdDocumento = nullable.GetValueOrDefault(); + nullable = x.Field("iditem"); + indiceArquivoDigital.IdItem = nullable.GetValueOrDefault(); + nullable = x.Field("idparcela"); + indiceArquivoDigital.IdParcela = nullable.GetValueOrDefault(); + nullable = x.Field("idsinistro"); + indiceArquivoDigital.IdSinistro = nullable.GetValueOrDefault(); + nullable = x.Field("idciaseg"); + indiceArquivoDigital.IdSeguradora = nullable.GetValueOrDefault(); + nullable = x.Field("idvendedor"); + indiceArquivoDigital.IdVendedor = nullable.GetValueOrDefault(); + nullable = x.Field("idextrato"); + indiceArquivoDigital.IdExtrato = nullable.GetValueOrDefault(); + nullable = x.Field("idempresa"); + indiceArquivoDigital.IdEmpresa = nullable.GetValueOrDefault(); + nullable = x.Field("idlancamen"); + indiceArquivoDigital.IdLancamento = nullable.GetValueOrDefault(); + nullable = x.Field("idfornecedor"); + indiceArquivoDigital.IdFornecedor = nullable.GetValueOrDefault(); + nullable = x.Field("idvenctoaleatorio"); + indiceArquivoDigital.IdProspeccao = nullable.GetValueOrDefault(); + nullable = x.Field("idsocio"); + indiceArquivoDigital.IdSocio = nullable.GetValueOrDefault(); + indiceArquivoDigital.Excluido = (x.Field("excluido") == null ? true : x.Field("excluido").ToString() != "1"); + nullable = x.Field("idusuarioarquivo"); + indiceArquivoDigital.IdUsuario = nullable.GetValueOrDefault(); + nullable = x.Field("IdTarefa"); + indiceArquivoDigital.IdTarefa = nullable.GetValueOrDefault(); + nullable = x.Field("IdNotaFiscal"); + indiceArquivoDigital.IdNotaFiscal = nullable.GetValueOrDefault(); + nullable = x.Field("IdEstipulante"); + indiceArquivoDigital.IdEstipulante = nullable.GetValueOrDefault(); + nullable = x.Field("usuariocriacao"); + indiceArquivoDigital.UsuarioCriacao = nullable.GetValueOrDefault(); + nullable = x.Field("usuarioalteracao"); + indiceArquivoDigital.UsuarioAtualizacao = nullable.GetValueOrDefault(); + DateTime? nullable1 = x.Field("datacriacao"); + indiceArquivoDigital.DataCriacao = new DateTime?((nullable1.HasValue ? nullable1.GetValueOrDefault() : DateTime.MinValue)); + nullable1 = x.Field("dataalteracao"); + indiceArquivoDigital.DataAtualizacao = new DateTime?((nullable1.HasValue ? nullable1.GetValueOrDefault() : DateTime.MinValue)); + indiceArquivoDigital.Assinado = (!buscarAssinaturas || dataTable1 == null ? false : dataTable1.AsEnumerable().ToList().Any((DataRow a) => { + if (a.Field("IndiceId") != x.Field("idnewarquivodigital")) + { + return false; + } + return a.Field("assinado"); + })); + indiceArquivoDigital.EnviadoAssinatura = (!buscarAssinaturas || dataTable1 == null ? false : dataTable1.AsEnumerable().ToList().Any((DataRow a) => a.Field("IndiceId") == x.Field("idnewarquivodigital"))); + if (!buscarAssinaturas || dataTable1 == null) + { + str = ""; + } + else + { + DataRow dataRow = dataTable1.AsEnumerable().ToList().FirstOrDefault((DataRow a) => a.Field("IndiceId") == x.Field("idnewarquivodigital")); + if (dataRow != null) + { + str = dataRow.Field("UrlAssinatura"); + } + else + { + str = null; + } + } + indiceArquivoDigital.UrlAssinatura = str; + indiceArquivoDigital.AzureGuid = x.Field("AzureGuid"); + indiceArquivoDigital.AzureStorage = x.Field("AzureStorage"); + return indiceArquivoDigital; + }).ToList(); + } + + public List Find(string condicao) + { + List list; + object connection; + DataTable dataTable = new DataTable(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + try + { + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = string.Concat("SELECT * FROM AssinaturaRecebida WHERE tipo = 'MANIFEST' ", condicao, " "); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + } + } + list = ( + from x in dataTable.AsEnumerable().ToList() + select new ArquivoDigital() + { + Id = x.Field("Id"), + Arquivo = x.Field("Bytes"), + Descricao = x.Field("Nome"), + Extensao = x.Field("Mime"), + DataCriacao = x.Field("DataCriacao"), + AzureGuid = x.Field("AzureGuid") + }).ToList(); + } + catch (Exception exception) + { + list = new List(); + } + return list; + } + + public ArquivoDigital FindAssinatura(long id) + { + string str = string.Format(" AND IndiceId = {0}", id); + return this.Find(str).FirstOrDefault(); + } + + public List FindAssinatura(List id) + { + string str = string.Concat(" AND IndiceId IN (", string.Join(",", id), ")"); + return this.Find(str); + } + + public IndiceArquivoDigital FindById(long id) + { + IndiceArquivoDigitalDb indiceArquivoDigitalDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(indiceArquivoDigitalDb); + } + + public IndiceArquivoDigital Merge(IndiceArquivoDigital indice) + { + IndiceArquivoDigitalDb indiceArquivoDigitalDb = ApplicationMapper.Mapper.Map(indice); + base.Merge(indiceArquivoDigitalDb); + return ApplicationMapper.Mapper.Map(indiceArquivoDigitalDb); + } + + public IndiceArquivoDigital SaveOrUpdate(IndiceArquivoDigital indice) + { + IndiceArquivoDigitalDb indiceArquivoDigitalDb = ApplicationMapper.Mapper.Map(indice); + this.SaveOrUpdate(indiceArquivoDigitalDb); + return ApplicationMapper.Mapper.Map(indiceArquivoDigitalDb); + } + + public ControleArquivoDigital SaveOrUpdate(ControleArquivoDigital catalogo) + { + ControleArquivoDigitalDb controleArquivoDigitalDb = ApplicationMapper.Mapper.Map(catalogo); + this._unitOfWork.Repository().SaveOrUpdate(controleArquivoDigitalDb); + return ApplicationMapper.Mapper.Map(controleArquivoDigitalDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ItemRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ItemRepository.cs new file mode 100644 index 0000000..0d8590f --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ItemRepository.cs @@ -0,0 +1,1450 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Helpers; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using NHibernate.Util; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Diagnostics; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class ItemRepository : GenericRepository, IItemRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public ItemRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public async Task> BuscaItensPorObs(string pesquisa, FiltroStatusDocumento status, List vendedorVinculado, TipoPesquisa tipo, bool tipobusca = false) + { + List pesquisaAvancadas; + object connection; + object obj; + DateTime dateTime; + List pesquisaAvancadas1 = new List(); + DateTime date = Funcoes.GetNetworkTime().Date; + List condicaos = new List(); + Condicao condicao = new Condicao() + { + Campo = "d.excluido", + Valores = null, + Grupo = 1, + Operacao = Operacao.Or + }; + condicaos.Add(condicao); + Condicao condicao1 = new Condicao() + { + Campo = "d.excluido", + Valores = "0".CriarValor(), + Grupo = 1, + Operacao = Operacao.Or + }; + condicaos.Add(condicao1); + List condicaos1 = condicaos; + if (vendedorVinculado.Count > 0) + { + Condicao condicao2 = new Condicao() + { + Campo = "vp.IdVendedor", + Valores = vendedorVinculado.CriarValor() + }; + condicaos1.Add(condicao2); + } + switch (status) + { + case FiltroStatusDocumento.Vencidos: + { + List condicaos2 = new List(); + Condicao condicao3 = new Condicao() + { + Campo = "d.situacao", + Valores = new List() + { + 3, + 7 + }, + Operador = Operador.Diferente + }; + condicaos2.Add(condicao3); + Condicao condicao4 = new Condicao() + { + Campo = "d.vigencia2", + Valores = date.AddDays(-5).CriarValor(), + Operador = Operador.Menor + }; + condicaos2.Add(condicao4); + condicaos1.AddRange(condicaos2); + goto Label0; + } + case FiltroStatusDocumento.Cancelados: + { + Condicao condicao5 = new Condicao() + { + Campo = "d.situacao", + Valores = 3.CriarValor() + }; + condicaos1.Add(condicao5); + goto Label0; + } + case FiltroStatusDocumento.Recusados: + { + Condicao condicao6 = new Condicao() + { + Campo = "d.situacao", + Valores = 7.CriarValor() + }; + condicaos1.Add(condicao6); + goto Label0; + } + case FiltroStatusDocumento.Todos: + { + using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) + { + SessionFactoryImpl sessionFactoryImpl = sessionFactory; + if (sessionFactoryImpl != null) + { + connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + List condicaos3 = condicaos1; + Condicao condicao7 = new Condicao() + { + Campo = "a.obs", + Valores = pesquisa.CriarValor(), + Grupo = 3, + Operacao = Operacao.Or, + Operador = (tipobusca ? Operador.Igual : Operador.Like) + }; + condicaos3.Add(condicao7); + List condicaos4 = condicaos1; + Condicao condicao8 = new Condicao() + { + Campo = "r.obs", + Valores = pesquisa.CriarValor(), + Grupo = 3, + Operacao = Operacao.Or, + Operador = (tipobusca ? Operador.Igual : Operador.Like) + }; + condicaos4.Add(condicao8); + List condicaos5 = condicaos1; + Condicao condicao9 = new Condicao() + { + Campo = "aero.obs", + Valores = pesquisa.CriarValor(), + Grupo = 3, + Operacao = Operacao.Or, + Operador = (tipobusca ? Operador.Igual : Operador.Like) + }; + condicaos5.Add(condicao9); + List condicaos6 = condicaos1; + Condicao condicao10 = new Condicao() + { + Campo = "g.obs", + Valores = pesquisa.CriarValor(), + Grupo = 3, + Operacao = Operacao.Or, + Operador = (tipobusca ? Operador.Igual : Operador.Like) + }; + condicaos6.Add(condicao10); + List condicaos7 = condicaos1; + Condicao condicao11 = new Condicao() + { + Campo = "v.obs", + Valores = pesquisa.CriarValor(), + Grupo = 3, + Operacao = Operacao.Or, + Operador = (tipobusca ? Operador.Igual : Operador.Like) + }; + condicaos7.Add(condicao11); + List condicaos8 = condicaos1; + Condicao condicao12 = new Condicao() + { + Campo = "rd.obs", + Valores = pesquisa.CriarValor(), + Grupo = 3, + Operacao = Operacao.Or, + Operador = (tipobusca ? Operador.Igual : Operador.Like) + }; + condicaos8.Add(condicao12); + List condicaos9 = condicaos1; + Condicao condicao13 = new Condicao() + { + Campo = "re.bens", + Valores = pesquisa.CriarValor(), + Grupo = 3, + Operacao = Operacao.Or, + Operador = (tipobusca ? Operador.Igual : Operador.Like) + }; + condicaos9.Add(condicao13); + SqlQueryCondition sqlQueryCondition = condicaos1.CreateParameters(0); + sqlCommand.CommandText = string.Concat("SELECT DISTINCT TOP 1000 c.IdControle,d.IdDocumento,d.Proposta,d.Contrato Apolice,d.Aditamento Endosso,d.Vigencia1 VigenciaInicial,c.IdCliente,d.Tipo Tipo,i.IdItem,i.Descricao,cli.Nome,vp.IdVendedor FROM documento d INNER JOIN controle c ON d.IdControle = c.idControle INNER JOIN cliente cli ON cli.IdCliente = c.IdCliente INNER JOIN item i ON d.IdDocumento = i.IdDocumento LEFT JOIN auto a ON i.IdItem = a.IdItem LEFT JOIN resempco r ON i.IdItem = r.IdItem LEFT JOIN aeronautico aero ON i.IdItem = aero.IdItem LEFT JOIN granizo g ON i.IdItem = g.IdItem LEFT JOIN vida v ON i.IdItem = v.IdItem LEFT JOIN riscosdiversos rd ON i.IdItem = rd.IdItem LEFT JOIN vendedorparcela vp ON d.IdDocumento = vp.IdDocumento LEFT JOIN resempco re ON i.IdItem = re.IdItem WHERE ", sqlQueryCondition.Condicao); + sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray()); + using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) + { + while (true) + { + if (!await sqlDataReader.ReadAsync()) + { + break; + } + object[] fieldValue = new object[] { sqlDataReader.GetFieldValue("Descricao", true, true), sqlDataReader.GetFieldValue("Apolice", true, true), null, null, null }; + obj = (sqlDataReader.GetFieldValue("Tipo", true, true) == 0 ? "" : string.Concat(" - ENDOSSO: ", sqlDataReader.GetFieldValue("Endosso", true, true))); + fieldValue[2] = obj; + fieldValue[3] = sqlDataReader.GetFieldValue("Proposta", true, true); + DateTime? nullable = sqlDataReader.GetFieldValue("VigenciaInicial", true, true); + dateTime = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.Now); + fieldValue[4] = dateTime; + string str = string.Format("ITEM: {0} - APÓLICE: {1}{2} - PROPOSTA: {3} - VIGÊNCIA INICIAL: {4:d}", fieldValue); + PesquisaAvancada pesquisaAvancada = new PesquisaAvancada() + { + IdCliente = sqlDataReader.GetFieldValue("IdCliente", true, true), + IdDocumento = sqlDataReader.GetFieldValue("IdDocumento", true, true), + IdItem = sqlDataReader.GetFieldValue("IdItem", true, true), + Nome = sqlDataReader.GetFieldValue("Nome", true, true).ToUpper(), + Pesquisa = str.ToUpper() + }; + pesquisaAvancadas1.Add(pesquisaAvancada); + } + } + sqlDataReader = null; + } + sqlCommand = null; + } + sqlConnection = null; + } + sessionFactory = null; + pesquisaAvancadas = pesquisaAvancadas1; + break; + } + default: + { + List condicaos10 = new List(); + Condicao condicao14 = new Condicao() + { + Campo = "d.situacao" + }; + List objs = new List() + { + 1, + 2, + 4 + }; + condicao14.Valores = objs; + condicaos10.Add(condicao14); + Condicao condicao15 = new Condicao() + { + Campo = "d.vigencia2", + Valores = null, + Grupo = 2, + Operacao = Operacao.Or + }; + condicaos10.Add(condicao15); + Condicao condicao16 = new Condicao() + { + Campo = "d.vigencia2", + Valores = date.AddDays(-5).CriarValor(), + Grupo = 2, + Operacao = Operacao.Or, + Operador = Operador.Maior + }; + condicaos10.Add(condicao16); + condicaos1.AddRange(condicaos10); + goto Label0; + } + } + pesquisaAvancadas1 = null; + return pesquisaAvancadas; + } + + public Cliente BuscarCliente(long id) + { + return this.FindById(id).Documento.Controle.Cliente; + } + + public int ChecarQuantidade(long idDocumento) + { + return base.All().Count((ItemDb x) => x.Documento.Id == idDocumento); + } + + public void Delete(long id) + { + ItemDb itemDb = base.FindEntityById(id); + if (itemDb == null) + { + return; + } + base.Delete(itemDb); + } + + public void DeleteRange(List ids) + { + List list = ( + from x in base.All() + where ids.Contains(x.Id) + select x).ToList(); + base.DeleteRange(list); + } + + public List FindByDocumentsIds(long id, StatusItem status = 0, bool sinistroCompleto = false) + { + List condicaos; + DataTable dataTable1; + int length; + Item granizo; + long? nullable; + long? nullable1; + long? nullable2; + string str; + string str1; + string str2; + string str3; + string str4; + string str5; + string str6; + string str7; + object fabricante; + string str8; + string str9; + string str10; + string str11; + string str12; + string str13; + string str14; + string str15; + string str16; + int? nullable3; + TabelaReferencia tabelaReferencium; + string str17; + string str18; + Cor cor; + string str19; + string str20; + Action action = null; + List condicaos1 = new List() + { + new Condicao() + { + Campo = "d.idcontrole", + Valores = id.CriarValor() + } + }; + switch (status) + { + case StatusItem.Ativos: + { + condicaos1.AddRange(new List() + { + new Condicao() + { + Campo = "idsubstituido", + Valores = null + }, + new Condicao() + { + Campo = "cancelado", + Valores = null, + Grupo = 1, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "cancelado", + Valores = "1".CriarValor(), + Grupo = 1, + Operacao = Operacao.Or, + Operador = Operador.Diferente + } + }); + break; + } + case StatusItem.Inativos: + { + condicaos1.AddRange(new List() + { + new Condicao() + { + Campo = "idsubstituido", + Valores = null, + Grupo = 1, + Operacao = Operacao.Or, + Operador = Operador.Diferente + }, + new Condicao() + { + Campo = "cancelado", + Valores = "1".CriarValor(), + Grupo = 1 + } + }); + break; + } + case StatusItem.Documento: + { + condicaos1 = new List() + { + new Condicao() + { + Campo = "d.iddocumento", + Valores = id.CriarValor() + } + }; + break; + } + } + DataTable dataTable2 = this._unitOfWork.Select(condicaos1.CreateParameters(0), "SELECT i.iditem, c.idramo, i.iddocumento, i.descricao, i.sinistrado, i.status, i.statusinc, i.idsubstituido, i.iddocumentocancelado, i.ordem FROM item i INNER JOIN documento d on d.iddocumento = i.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole WHERE ", "ORDER BY i.ordem"); + if (dataTable2.Rows.Count == 0) + { + return new List(); + } + string str21 = dataTable2.AsEnumerable().First().Field("idramo").ToString(); + List list = dataTable2.AsEnumerable().Select((DataRow x) => x.Field("iditem")).ToList(); + DataTable dataTable3 = new DataTable(); + DataTable dataTable4 = new DataTable(); + DataTable dataTable5 = new DataTable(); + DataTable dataTable6 = new DataTable(); + DataTable dataTable7 = new DataTable(); + DataTable dataTable8 = new DataTable(); + DataTable dataTable9 = new DataTable(); + DataTable dataTable10 = new DataTable(); + DataTable dataTable11 = new DataTable(); + DataTable dataTable12 = new DataTable(); + while (list.Count > 0) + { + List nums = list.Take(1500).ToList(); + condicaos = new List() + { + new Condicao() + { + Campo = "iditem", + Valores = nums.CriarValor() + } + }; + dataTable1 = this._unitOfWork.Select(condicaos.CreateParameters(0), "SELECT idcobertura, iditem, observacao, franquia, premio, lmi FROM cobertura WHERE ", ""); + dataTable12.Merge(dataTable1); + if (str21 != null) + { + length = str21.Length; + if (length == 1) + { + switch (str21[0]) + { + case '1': + case '2': + case '3': + { + goto Label1; + } + case '4': + case '8': + { + break; + } + case '5': + { + dataTable1 = this._unitOfWork.Select(condicaos.CreateParameters(0), "SELECT a.*, f.descricao AS fabricante FROM auto a LEFT OUTER JOIN fabricante f ON f.idfabricante = a.IDFABRICANTE WHERE ", ""); + dataTable3.Merge(dataTable1); + goto Label0; + } + default: + { + goto Label0; + } + } + } + else if (length == 2) + { + switch (str21[1]) + { + case '0': + { + if (str21 == "10") + { + goto Label0; + } + if (str21 == "20") + { + dataTable1 = this._unitOfWork.Select(condicaos.CreateParameters(0), "SELECT iditem, obs FROM granizo WHERE ", ""); + dataTable11.Merge(dataTable1); + goto Label0; + } + else + { + goto Label0; + } + } + case '1': + { + if (str21 == "31" || str21 == "41") + { + break; + } + goto Label0; + } + case '3': + { + if (str21 == "23" || str21 == "33") + { + break; + } + if (str21 == "13") + { + dataTable1 = this._unitOfWork.Select(condicaos.CreateParameters(0), "SELECT iditem, obs FROM aeronautico WHERE ", ""); + dataTable10.Merge(dataTable1); + goto Label0; + } + else + { + if (str21 == "53") + { + goto Label0; + } + goto Label0; + } + } + case '5': + { + if (str21 == "15") + { + goto Label1; + } + goto Label0; + } + case '6': + { + if (str21 == "16" || str21 == "26") + { + break; + } + goto Label0; + } + case '7': + { + if (str21 == "17") + { + break; + } + goto Label0; + } + case '8': + { + if (str21 == "18") + { + goto Label1; + } + if (str21 == "28") + { + break; + } + goto Label0; + } + case '9': + { + if (str21 == "19" || str21 == "39" || str21 == "59") + { + break; + } + goto Label0; + } + default: + { + goto Label0; + } + } + } + else + { + goto Label0; + } + dataTable1 = this._unitOfWork.Select(condicaos.CreateParameters(0), "SELECT iditem, obs FROM riscosdiversos WHERE ", ""); + dataTable9.Merge(dataTable1); + } + Label0: + dataTable1 = this._unitOfWork.Select(condicaos.CreateParameters(0), "SELECT * FROM controlesinistro WHERE ", ""); + dataTable5.Merge(dataTable1); + if (dataTable1.Rows.Count > 0) + { + List condicaos2 = new List() + { + new Condicao() + { + Campo = "idcontrolesinistro", + Valores = dataTable5.AsEnumerable().Select((DataRow x) => x.Field("idcontrolesinistro")).ToList().CriarValor() + } + }; + dataTable1 = this._unitOfWork.Select(condicaos2.CreateParameters(0), "SELECT * FROM sinistro WHERE ", ""); + dataTable6.Merge(dataTable1); + List condicaos3 = new List() + { + new Condicao() + { + Campo = "idsinistro", + Valores = dataTable6.AsEnumerable().Select((DataRow x) => x.Field("idsinistro")).ToList().CriarValor() + } + }; + dataTable1 = this._unitOfWork.Select(condicaos3.CreateParameters(0), "SELECT * FROM sinistrovida WHERE ", ""); + dataTable8.Merge(dataTable1); + dataTable1 = this._unitOfWork.Select(condicaos3.CreateParameters(0), "SELECT * FROM sinistroauto WHERE ", ""); + dataTable7.Merge(dataTable1); + } + list = (nums.Count < 1500 ? new List() : list.Except(nums).ToList()); + } + List items = new List(); + Label4: + foreach (DataRow row in dataTable2.Rows) + { + Item item = new Item() + { + Id = long.Parse(row["iditem"].ToString()), + Documento = new Documento() + { + Id = long.Parse(row["iddocumento"].ToString()) + }, + Sinistrado = row["sinistrado"].ToString() == "1", + Descricao = row["descricao"].ToString(), + Status = row["status"].ToString(), + Ordem = new int?(int.Parse(row["ordem"].ToString())), + StatusInclusao = row["statusinc"].ToString() + }; + if (string.IsNullOrEmpty(row["iddocumentocancelado"].ToString())) + { + nullable = null; + nullable1 = nullable; + } + else + { + nullable1 = new long?(long.Parse(row["iddocumentocancelado"].ToString())); + } + item.IdDocumentoCancelado = nullable1; + if (string.IsNullOrEmpty(row["idsubstituido"].ToString())) + { + nullable = null; + nullable2 = nullable; + } + else + { + nullable2 = new long?(long.Parse(row["idsubstituido"].ToString())); + } + item.Substituido = nullable2; + item.Coberturas = ( + from x in dataTable12.AsEnumerable().Where((DataRow x) => x.Field("iditem") == long.Parse(this.i["iditem"].ToString())).ToList() + select new Cobertura() + { + Id = x.Field("idcobertura"), + Observacao = x.Field("observacao"), + Franquia = (x.Field("franquia") == null ? decimal.Zero : x.Field("franquia")), + Lmi = (x.Field("lmi") == null ? decimal.Zero : x.Field("lmi")), + Premio = (x.Field("premio") == null ? decimal.Zero : x.Field("premio")) + }).ToList(); + granizo = item; + string str22 = row["idramo"].ToString(); + if (str22 != null) + { + length = str22.Length; + if (length == 1) + { + switch (str22[0]) + { + case '1': + case '2': + case '3': + { + goto Label3; + } + case '4': + case '8': + { + break; + } + case '5': + { + if (dataTable3.AsEnumerable().Where((DataRow x) => x.Field("iditem") == long.Parse(this.i["iditem"].ToString())).ToList().Count == 0) + { + continue; + } + DataRow dataRow4 = dataTable3.AsEnumerable().FirstOrDefault((DataRow x) => x.Field("iditem") == long.Parse(this.i["iditem"].ToString())); + Item item1 = granizo; + Auto auto = new Auto(); + if (dataRow4 != null) + { + str7 = dataRow4["IDFABRICANTE"].ToString(); + } + else + { + str7 = null; + } + if (string.IsNullOrEmpty(str7)) + { + fabricante = null; + } + else + { + fabricante = new Fabricante(); + if (dataRow4 != null) + { + str19 = dataRow4["IDFABRICANTE"].ToString(); + } + else + { + str19 = null; + } + ((Fabricante)fabricante).Id = int.Parse(str19); + if (dataRow4 != null) + { + str20 = dataRow4["fabricante"].ToString(); + } + else + { + str20 = null; + } + ((Fabricante)fabricante).Descricao = str20; + } + auto.Fabricante = (Fabricante)fabricante; + if (dataRow4 != null) + { + str8 = dataRow4["modelo"].ToString(); + } + else + { + str8 = null; + } + auto.Modelo = str8; + if (dataRow4 != null) + { + str9 = dataRow4["anofab"].ToString(); + } + else + { + str9 = null; + } + auto.AnoFabricacao = str9; + if (dataRow4 != null) + { + str10 = dataRow4["anomod"].ToString(); + } + else + { + str10 = null; + } + auto.AnoModelo = str10; + if (dataRow4 != null) + { + str11 = dataRow4["placa"].ToString(); + } + else + { + str11 = null; + } + auto.Placa = str11; + if (dataRow4 != null) + { + str12 = dataRow4["chassi"].ToString(); + } + else + { + str12 = null; + } + auto.Chassi = str12; + if (dataRow4 != null) + { + str13 = dataRow4["ci"].ToString(); + } + else + { + str13 = null; + } + auto.Ci = str13; + if (dataRow4 != null) + { + str14 = dataRow4["renavam"].ToString(); + } + else + { + str14 = null; + } + auto.Renavam = str14; + if (dataRow4 != null) + { + str15 = dataRow4["CEPpernoite"].ToString(); + } + else + { + str15 = null; + } + auto.CepPernoite = str15; + if (dataRow4 != null) + { + str16 = dataRow4["financiado"].ToString(); + } + else + { + str16 = null; + } + auto.Financiado = new bool?(str16 == "1"); + auto.TipoCobertura = (!string.IsNullOrEmpty(dataRow4["idtipocobertura"].ToString()) ? new TipoCobertura?((TipoCobertura)int.Parse(dataRow4["idtipocobertura"].ToString())) : new TipoCobertura?(0)); + if (string.IsNullOrEmpty(dataRow4["bonus"].ToString())) + { + nullable3 = null; + } + else + { + nullable3 = new int?(int.Parse(dataRow4["bonus"].ToString())); + } + auto.Bonus = nullable3; + auto.RegiaoCirculacao = dataRow4["regiaocirculacao"].ToString(); + if (!string.IsNullOrEmpty(dataRow4["idtabelareferencia"].ToString())) + { + tabelaReferencium = (TabelaReferencia)int.Parse(dataRow4["idtabelareferencia"].ToString()); + } + else + { + tabelaReferencium = TabelaReferencia.Molicar; + } + auto.TabelaReferencia = new TabelaReferencia?(tabelaReferencium); + auto.PorcentagemReferencia = (string.IsNullOrEmpty(dataRow4["porcentagemreferencia"].ToString()) ? decimal.Zero : decimal.Parse(dataRow4["porcentagemreferencia"].ToString())); + auto.Fipe = dataRow4["CODFIPE"].ToString(); + if (dataRow4 != null) + { + str17 = dataRow4["idcor"].ToString(); + } + else + { + str17 = null; + } + if (!string.IsNullOrEmpty(str17)) + { + if (dataRow4 != null) + { + str18 = dataRow4["idcor"].ToString(); + } + else + { + str18 = null; + } + cor = (Cor)int.Parse(str18); + } + else + { + cor = Cor.OutrosNull; + } + auto.Cor = new Cor?(cor); + item1.Auto = auto; + goto Label2; + } + default: + { + goto Label2; + } + } + } + else if (length == 2) + { + switch (str22[1]) + { + case '0': + { + if (str22 == "10") + { + goto Label2; + } + if (str22 == "20") + { + if (dataTable11.AsEnumerable().Where((DataRow x) => x.Field("iditem") == long.Parse(this.i["iditem"].ToString())).ToList().Count <= 0) + { + goto Label2; + } + granizo.Granizo = new Granizo() + { + Observacao = dataTable11.AsEnumerable().FirstOrDefault((DataRow x) => x.Field("iditem") == long.Parse(this.i["iditem"].ToString()))["obs"].ToString() + }; + goto Label2; + } + else + { + goto Label2; + } + } + case '1': + { + if (str22 == "31" || str22 == "41") + { + break; + } + goto Label2; + } + case '3': + { + if (str22 == "53") + { + goto Label2; + } + if (str22 == "23" || str22 == "33") + { + break; + } + if (str22 == "13") + { + if (dataTable10.AsEnumerable().Where((DataRow x) => x.Field("iditem") == long.Parse(this.i["iditem"].ToString())).ToList().Count <= 0) + { + goto Label2; + } + granizo.Aeronautico = new Aeronautico() + { + Observacao = dataTable10.AsEnumerable().FirstOrDefault((DataRow x) => x.Field("iditem") == long.Parse(this.i["iditem"].ToString()))["obs"].ToString() + }; + goto Label2; + } + else + { + goto Label2; + } + } + case '5': + { + if (str22 == "15") + { + goto Label3; + } + goto Label2; + } + case '6': + { + if (str22 == "16" || str22 == "26") + { + break; + } + goto Label2; + } + case '7': + { + if (str22 == "17") + { + break; + } + goto Label2; + } + case '8': + { + if (str22 == "18") + { + goto Label3; + } + if (str22 == "28") + { + break; + } + goto Label2; + } + case '9': + { + if (str22 == "19" || str22 == "39" || str22 == "59") + { + break; + } + goto Label2; + } + default: + { + goto Label2; + } + } + } + else + { + goto Label2; + } + if (dataTable9.AsEnumerable().Where((DataRow x) => x.Field("iditem") == long.Parse(this.i["iditem"].ToString())).ToList().Count > 0) + { + granizo.RiscosDiversos = new RiscosDiversos() + { + Observacao = dataTable9.AsEnumerable().FirstOrDefault((DataRow x) => x.Field("iditem") == long.Parse(this.i["iditem"].ToString()))["obs"].ToString() + }; + } + } + Label2: + List sinistros = new List(); + granizo.Sinistros = new List(); + foreach (DataRow row1 in dataTable5.Rows) + { + if (row1["iditem"].ToString() != row["iditem"].ToString()) + { + continue; + } + long num = long.Parse(row1["idcontrolesinistro"].ToString()); + EnumerableRowCollection dataRows = dataTable6.AsEnumerable().Where((DataRow x) => x.Field("idcontrolesinistro") == num); + Action action1 = action; + if (action1 == null) + { + Action action2 = (DataRow x) => { + DataRow dataRow; + DataRow dataRow1; + object sinistroVida; + object sinistroAuto; + DataTable cSu0024u003cu003e8_locals1 = dataTable8; + if (cSu0024u003cu003e8_locals1 != null) + { + dataRow = cSu0024u003cu003e8_locals1.AsEnumerable().FirstOrDefault((DataRow s) => s.Field("idsinistro") == x.Field("idsinistro")); + } + else + { + dataRow = null; + } + DataRow dataRow2 = dataRow; + DataTable dataTable = dataTable7; + if (dataTable != null) + { + dataRow1 = dataTable.AsEnumerable().FirstOrDefault((DataRow s) => s.Field("idsinistro") == x.Field("idsinistro")); + } + else + { + dataRow1 = null; + } + DataRow dataRow3 = dataRow1; + if (dataRow2 == null) + { + sinistroVida = null; + } + else + { + sinistroVida = new SinistroVida(); + ((DomainBase)sinistroVida).Id = dataRow2.Field("idsinistrovida"); + ((SinistroVida)sinistroVida).Beneficiario = dataRow2.Field("beneficiario"); + } + SinistroVida sinistroVida1 = (SinistroVida)sinistroVida; + if (dataRow3 == null) + { + sinistroAuto = null; + } + else + { + sinistroAuto = new SinistroAuto(); + ((DomainBase)sinistroAuto).Id = dataRow3.Field("idsinistroauto"); + } + SinistroAuto sinistroAuto1 = (SinistroAuto)sinistroAuto; + sinistros.Add(new Sinistro() + { + Id = x.Field("idsinistro"), + Numero = x.Field("numsinistro"), + DataReclamacao = x.Field("datareclamacao"), + StatusSinistro = (x.Field("idstatussinistro") != null ? new StatusSinistro?((StatusSinistro)int.Parse(x.Field("idstatussinistro").ToString())) : null), + DataLiquidacao = x.Field("dataliquidacao"), + ItemSinistrado = x.Field("itemsinistrado"), + Motivo = x.Field("motivo"), + Valor = x.Field("valor").GetValueOrDefault(), + SinistroVida = sinistroVida1, + SinistroAuto = sinistroAuto1 + }); + }; + Action action3 = action2; + action = action2; + action1 = action3; + } + dataRows.ForEach(action1); + granizo.Sinistros.Add(new ControleSinistro() + { + Id = num, + DataSinistro = row1.Field("datasinistro"), + Item = new Item() + { + Id = long.Parse(row["iditem"].ToString()) + }, + Sinistros = sinistros + }); + } + items.Add(granizo); + } + return items; + Label1: + dataTable1 = this._unitOfWork.Select(condicaos.CreateParameters(0), "SELECT * FROM resempco WHERE ", ""); + dataTable4.Merge(dataTable1); + goto Label0; + Label3: + if (dataTable4.AsEnumerable().Where((DataRow x) => x.Field("iditem") == long.Parse(this.i["iditem"].ToString())).ToList().Count == 0) + { + goto Label4; + } + DataRow dataRow5 = dataTable4.AsEnumerable().FirstOrDefault((DataRow x) => x.Field("iditem") == long.Parse(this.i["iditem"].ToString())); + Item item2 = granizo; + Patrimonial patrimonial = new Patrimonial(); + if (dataRow5 != null) + { + str = dataRow5["endereco"].ToString(); + } + else + { + str = null; + } + patrimonial.Endereco = str; + if (dataRow5 != null) + { + str1 = dataRow5["numero"].ToString(); + } + else + { + str1 = null; + } + patrimonial.Numero = str1; + if (dataRow5 != null) + { + str2 = dataRow5["complemento"].ToString(); + } + else + { + str2 = null; + } + patrimonial.Complemento = str2; + if (dataRow5 != null) + { + str3 = dataRow5["bairro"].ToString(); + } + else + { + str3 = null; + } + patrimonial.Bairro = str3; + if (dataRow5 != null) + { + str4 = dataRow5["cidade"].ToString(); + } + else + { + str4 = null; + } + patrimonial.Cidade = str4; + if (dataRow5 != null) + { + str5 = dataRow5["uf"].ToString(); + } + else + { + str5 = null; + } + patrimonial.Estado = str5; + if (dataRow5 != null) + { + str6 = dataRow5["cep"].ToString(); + } + else + { + str6 = null; + } + patrimonial.Cep = str6; + item2.Patrimonial = patrimonial; + goto Label2; + } + + public Item FindById(long id) + { + ItemDb itemDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(itemDb); + } + + public List FindByIds(List ids) + { + List list = ( + from x in base.All() + where ids.Contains(x.Id) + select x).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public List FindItens(List ids) + { + List list = ( + from x in base.All() + where ids.Contains(x.Id) + select x).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public List FindItens(long id, StatusItem status) + { + List items; + object connection; + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + string str = ""; + switch (status) + { + case StatusItem.Ativos: + { + str = string.Format("AND d.idcontrole = {0} AND (cancelado IS NULL OR cancelado != '1') AND idsubstituido IS NULL", id); + break; + } + case StatusItem.Inativos: + { + str = string.Format("AND d.idcontrole = {0} AND (cancelado IS NOT NULL AND cancelado = '1' OR idsubstituido IS NOT NULL)", id); + break; + } + case StatusItem.Documento: + { + str = string.Format("AND d.iddocumento = {0}", id); + break; + } + case StatusItem.Controle: + { + str = string.Format("AND d.idcontrole = {0}", id); + break; + } + } + DataTable dataTable = new DataTable(); + DataTable dataTable1 = new DataTable(); + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = string.Concat("SELECT i.* FROM item i INNER JOIN documento d on d.iddocumento = i.iddocumento WHERE 1=1 ", str); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + if (dataTable.Rows.Count != 0) + { + string str1 = string.Concat(" AND iditem IN (", string.Join(",", ( + from x in dataTable.AsEnumerable().ToList() + select x.Field("iditem")).ToList()), ")"); + sqlCommand.CommandText = string.Concat("SELECT iditem, idcontrolesinistro, datasinistro FROM controlesinistro WHERE 1=1 ", str1); + using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) + { + sqlDataAdapter1.SelectCommand = sqlCommand; + sqlDataAdapter1.Fill(dataTable1); + return dataTable.AsEnumerable().ToList().Select((DataRow x) => { + Item item = new Item() + { + Id = x.Field("iditem"), + Descricao = x.Field("descricao"), + Ordem = x.Field("ordem"), + Sinistrado = (x.Field("sinistrado") == null ? false : x.Field("sinistrado") == "1"), + Cancelado = (x.Field("cancelado") == null ? false : x.Field("cancelado") == "1"), + Substituicao = x.Field("idsubstituicao"), + Substituido = x.Field("idsubstituido"), + Status = x.Field("status"), + StatusInclusao = x.Field("statusinc") + }; + IEnumerable list = + from s in dataTable1.AsEnumerable().ToList() + where s.Field("iditem") == x.Field("iditem") + select s; + Func u003cu003e9_104 = ItemRepository.u003cu003ec.u003cu003e9__10_4; + if (u003cu003e9_104 == null) + { + u003cu003e9_104 = (DataRow s) => { + ControleSinistro controleSinistro = new ControleSinistro() + { + Id = s.Field("idcontrolesinistro") + }; + DateTime? nullable = s.Field("datasinistro"); + controleSinistro.DataSinistro = new DateTime?((nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue)); + return controleSinistro; + }; + ItemRepository.u003cu003ec.u003cu003e9__10_4 = u003cu003e9_104; + } + item.Sinistros = list.Select(u003cu003e9_104).ToList(); + return item; + }).OrderBy((Item x) => x.Ordem).ToList(); + } + } + else + { + items = new List(); + } + } + } + return items; + } + + public List FindItens(List documento) + { + List items; + object connection; + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + DataTable dataTable = new DataTable(); + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = string.Concat("SELECT * FROM item WHERE iddocumento IN (", string.Join(",", + from x in documento + select x.Id), ")"); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + if (dataTable.Rows.Count != 0) + { + return ( + from x in dataTable.AsEnumerable().ToList() + select new Item() + { + Id = x.Field("iditem"), + Descricao = x.Field("descricao"), + Ordem = x.Field("ordem"), + Documento = new Documento() + { + Id = x.Field("iddocumento") + } + } into x + orderby x.Ordem + select x).ToList(); + } + else + { + items = new List(); + } + } + } + return items; + } + + public List FindItens(long id) + { + List list = ( + from x in base.All() + where x.Documento.Id == id + select x).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public int FindNextItem(long id) + { + int? nullable; + int? nullable1; + int? ordem; + int? nullable2; + List items = this.FindItens(id, StatusItem.Ativos); + if (items != null) + { + Item item = items.LastOrDefault(); + if (item != null) + { + ordem = item.Ordem; + } + else + { + nullable1 = null; + ordem = nullable1; + } + nullable = ordem; + if (nullable.HasValue) + { + nullable2 = new int?(nullable.GetValueOrDefault() + 1); + } + else + { + nullable1 = null; + nullable2 = nullable1; + } + } + else + { + nullable = null; + nullable2 = nullable; + } + nullable = nullable2; + return nullable.GetValueOrDefault(1); + } + + public Item Merge(Item item) + { + bool count; + List list; + ItemDb itemDb = ApplicationMapper.Mapper.Map(item); + IList coberturaDbs = itemDb.Coberturas; + if (coberturaDbs != null) + { + count = coberturaDbs.Count == 0; + } + else + { + count = false; + } + bool flag = count; + List list1 = ( + from x in this._unitOfWork.Query() + where x.Item.Id == itemDb.Id + select x).ToList(); + if (list1 != null) + { + list = list1.Where((CoberturaDb x) => { + IList coberturas = itemDb.Coberturas; + Func u003cu003e9_42 = ItemRepository.u003cu003ec.u003cu003e9__4_2; + if (u003cu003e9_42 == null) + { + u003cu003e9_42 = (CoberturaDb c) => c.Id; + ItemRepository.u003cu003ec.u003cu003e9__4_2 = u003cu003e9_42; + } + return !coberturas.Select(u003cu003e9_42).ToList().Contains(x.Id); + }).ToList(); + } + else + { + list = null; + } + List coberturaDbs1 = list; + itemDb.Coberturas = list1; + base.Merge(itemDb); + if (coberturaDbs1 != null && coberturaDbs1.Count > 0) + { + this._unitOfWork.Repository().DeleteRange(coberturaDbs1); + } + if (flag) + { + this._unitOfWork.Repository().DeleteRange(itemDb.Coberturas); + } + itemDb.Coberturas = null; + return ApplicationMapper.Mapper.Map(itemDb); + } + + public Item SaveOrUpdate(Item item) + { + ItemDb itemDb = ApplicationMapper.Mapper.Map(item); + this.SaveOrUpdate(itemDb); + return ApplicationMapper.Mapper.Map(itemDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/LancamentoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/LancamentoRepository.cs new file mode 100644 index 0000000..82f67fc --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/LancamentoRepository.cs @@ -0,0 +1,345 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Financeiro; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Helpers; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Financeiro.Relatorios; +using Gestor.Model.Domain.Generic; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class LancamentoRepository : GenericRepository, ILancamentoRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public LancamentoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public List AddRange(List lancamento) + { + List lancamentoDbs = ApplicationMapper.Mapper.Map, List>(lancamento); + base.AddRange(lancamentoDbs); + return ApplicationMapper.Mapper.Map, List>(lancamentoDbs); + } + + public bool BancosContasUtilizado(long id) + { + return base.All().Any((LancamentoDb x) => x.Conta.Id == id); + } + + public void Delete(long id) + { + LancamentoDb lancamentoDb = base.FindEntityById(id); + if (lancamentoDb == null) + { + return; + } + base.Delete(lancamentoDb); + } + + public List Fechamento(FiltroFinanceiro filtro) + { + string str = (filtro.Centro == null || filtro.Centro.Count == 0 ? "" : string.Concat(" AND c.idcentro IN (", string.Join(",", filtro.Centro), ")")); + string str1 = (filtro.Plano == null || filtro.Plano.Count == 0 ? "" : string.Concat(" AND cp.idcplano IN (", string.Join(",", filtro.Plano), ")")); + string str2 = (filtro.Planos == null || filtro.Planos.Count == 0 ? "" : string.Concat(" AND c.idcplanos IN (", string.Join(",", filtro.Planos), ")")); + string str3 = (filtro.Conta == null || filtro.Conta.Count == 0 ? "" : string.Concat(" AND l.idconta IN (", string.Join(",", filtro.Conta), ")")); + return this.Select(string.Format(" AND {0} >= '{1:yyyy-MM-dd}' AND {2} <= '{3:yyyy-MM-dd}' {4} {5} {6} {7}", new object[] { filtro.Referencia, filtro.Inicio, filtro.Referencia, filtro.Fim, str, str1, str2, str3 })); + } + + public Saldo FecharSaldo(Saldo saldo) + { + object connection; + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + decimal num = new decimal(); + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + if (sqlConnection != null) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = string.Format("SELECT sinal, vlrbaixa FROM lancamen WHERE idconta = {0} AND dtbaixa IS NOT NULL AND dtbaixa >= '{1:yyyy-MM-dd}' AND dtbaixa < '{2:yyyy-MM-dd}' ", saldo.Conta.Id, saldo.DataInicio, saldo.DataFinal); + DataTable dataTable = new DataTable(); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + num = (dataTable.Rows.Count == 0 ? decimal.Zero : dataTable.AsEnumerable().ToList().Sum((DataRow x) => { + decimal? nullable; + decimal? nullable1; + if (x.Field("sinal") == "0") + { + nullable = x.Field("vlrbaixa"); + return nullable.GetValueOrDefault(); + } + decimal? nullable2 = x.Field("vlrbaixa"); + if (nullable2.HasValue) + { + nullable1 = new decimal?(-nullable2.GetValueOrDefault()); + } + else + { + nullable = null; + nullable1 = nullable; + } + nullable = nullable1; + return nullable.GetValueOrDefault(); + })); + } + } + } + saldo.ValorFinal = new decimal?(saldo.ValorInicio + num); + return saldo; + } + + public List Find(DateTime inicio, DateTime fim, StatusLancamento status) + { + if (status == StatusLancamento.Baixados) + { + return this.Select(string.Format(" AND CAST(l.dtpre AS DATE) >= '{0:yyyy-MM-dd}' AND CAST(l.dtpre AS DATE) <= '{1:yyyy-MM-dd}' AND l.dtbaixa IS NOT NULL", inicio, fim)); + } + if (status != StatusLancamento.Todos) + { + return this.Select(string.Format(" AND CAST(l.dtpre AS DATE) >= '{0:yyyy-MM-dd}' AND CAST(l.dtpre AS DATE) <= '{1:yyyy-MM-dd}' AND l.dtbaixa IS NULL", inicio, fim)); + } + return this.Select(string.Format(" AND CAST(l.dtpre AS DATE) >= '{0:yyyy-MM-dd}' AND CAST(l.dtpre AS DATE) <= '{1:yyyy-MM-dd}'", inicio, fim)); + } + + public List FindByBaixa(DateTime inicio, DateTime fim) + { + return this.Select(string.Format(" AND CAST(l.dtbaixa AS DATE) >= '{0:yyyy-MM-dd}' AND CAST(l.dtbaixa AS DATE) <= '{1:yyyy-MM-dd}'", inicio, fim)); + } + + public List FindByCodigoBanco(List codigos) + { + List strs = codigos; + List lancamentos = new List(); + while (strs.Count > 0) + { + List list = strs.Take(2100).ToList(); + string str = string.Concat(" AND l.CodigoBanco IN ('", string.Join(",", list), "')"); + lancamentos.AddRange(this.Select(str)); + strs = (list.Count < 2100 ? new List() : strs.Except(list).ToList()); + } + return lancamentos; + } + + public List FindByConta(DateTime inicio, DateTime fim, long id) + { + return this.Select(string.Format(" AND l.idconta = {0} AND CAST(l.dtbaixa AS DATE) >= '{1:yyyy-MM-dd}' AND CAST(l.dtbaixa AS DATE) <= '{2:yyyy-MM-dd}'", id, inicio, fim)).Select((Lancamento x) => { + decimal? valorPago; + string nome; + decimal zero; + ExtratoConta extratoContum = new ExtratoConta() + { + IdLancamento = x.Id + }; + DateTime? baixa = x.Baixa; + extratoContum.Baixa = new DateTime?((baixa.HasValue ? baixa.GetValueOrDefault() : DateTime.MinValue)); + ControleFinanceiro controle = x.Controle; + if (controle != null) + { + Fornecedor fornecedor = controle.Fornecedor; + if (fornecedor != null) + { + nome = fornecedor.Nome; + } + else + { + nome = null; + } + } + else + { + nome = null; + } + extratoContum.Fornecedor = nome; + extratoContum.Historico = x.Historico; + extratoContum.TipoPagamento = new TipoPagamento?(x.TipoPagamento); + if (!x.ValorPago.HasValue) + { + zero = decimal.Zero; + } + else if (x.Sinal == Sinal.Credito) + { + valorPago = x.ValorPago; + zero = Math.Abs(valorPago.Value); + } + else + { + valorPago = x.ValorPago; + zero = -Math.Abs(valorPago.Value); + } + extratoContum.Valor = new decimal?(zero); + extratoContum.Sinal = x.Sinal; + return extratoContum; + }).ToList(); + } + + public List FindByControle(long id, StatusLancamento status) + { + if (status == StatusLancamento.Baixados) + { + return this.Select(string.Format(" AND l.idcfinan = {0} AND l.dtbaixa IS NOT NULL", id)); + } + if (status != StatusLancamento.Todos) + { + return this.Select(string.Format(" AND l.idcfinan = {0} AND l.dtbaixa IS NULL", id)); + } + return this.Select(string.Format(" AND l.idcfinan = {0}", id)); + } + + public Lancamento FindByControle(long id, int parcela) + { + return this.Select(string.Format(" AND l.idcfinan = {0} AND l.parcela = {1}", id, parcela)).FirstOrDefault(); + } + + public List FindByFornecedor(long id, StatusLancamento status) + { + if (status == StatusLancamento.Baixados) + { + return this.Select(string.Format(" AND c.idfornecedor = {0} AND l.dtbaixa IS NOT NULL", id)); + } + if (status != StatusLancamento.Todos) + { + return this.Select(string.Format(" AND c.idfornecedor = {0} AND l.dtbaixa IS NULL", id)); + } + return this.Select(string.Format(" AND c.idfornecedor = {0}", id)); + } + + public List FindByFornecedor(long id, DateTime date, Sinal sinal) + { + return this.Select(string.Format(" AND c.idfornecedor = {0} AND l.dtpre >= '{1:yyyy-MM-dd}' AND l.dtpre <= '{2:yyyy-MM-dd}' AND l.sinal = {3}", new object[] { id, date, date.AddMonths(1), (int)sinal })); + } + + public Lancamento FindById(long id) + { + LancamentoDb lancamentoDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(lancamentoDb); + } + + public List FindByLancamento(DateTime inicio, DateTime fim, StatusLancamento status) + { + if (status == StatusLancamento.Baixados) + { + return this.Select(string.Format(" AND CAST(l.datacriacao AS DATE) >= '{0:yyyy-MM-dd}' AND CAST(l.datacriacao AS DATE) <= '{1:yyyy-MM-dd}' AND l.dtbaixa IS NOT NULL", inicio, fim)); + } + if (status != StatusLancamento.Todos) + { + return this.Select(string.Format(" AND CAST(l.datacriacao AS DATE) >= '{0:yyyy-MM-dd}' AND CAST(l.datacriacao AS DATE) <= '{1:yyyy-MM-dd}' AND l.dtbaixa IS NULL", inicio, fim)); + } + return this.Select(string.Format(" AND CAST(l.datacriacao AS DATE) >= '{0:yyyy-MM-dd}' AND CAST(l.datacriacao AS DATE) <= '{1:yyyy-MM-dd}'", inicio, fim)); + } + + public List FindByPagamento(DateTime inicio, DateTime fim) + { + return this.Select(string.Format(" AND CAST(l.dtpagto AS DATE) >= '{0:yyyy-MM-dd}' AND CAST(l.dtpagto AS DATE) <= '{1:yyyy-MM-dd}'", inicio, fim)); + } + + public List FindLancamentosByConta(DateTime inicio, DateTime fim, long id) + { + return this.Select(string.Format(" AND CAST(l.dtpre AS DATE) >= '{0:yyyy-MM-dd}' AND CAST(l.dtpre AS DATE) <= '{1:yyyy-MM-dd}' AND l.idconta = {2}", inicio, fim, id)); + } + + public List FindPersonalizado(DateTime inicio, DateTime fim, StatusLancamento status, FiltroLancamentoData filtrodata) + { + string referencia = this.GetReferencia(filtrodata); + if (status == StatusLancamento.Baixados) + { + return this.Select(string.Format(" AND {0} >= '{1:yyyy-MM-dd}' AND {2} <= '{3:yyyy-MM-dd}' AND l.dtbaixa IS NOT NULL", new object[] { referencia, inicio, referencia, fim })); + } + if (status != StatusLancamento.Todos) + { + return this.Select(string.Format(" AND {0} >= '{1:yyyy-MM-dd}' AND {2} <= '{3:yyyy-MM-dd}' AND l.dtbaixa IS NULL", new object[] { referencia, inicio, referencia, fim })); + } + return this.Select(string.Format(" AND {0} >= '{1:yyyy-MM-dd}' AND {2} <= '{3:yyyy-MM-dd}'", new object[] { referencia, inicio, referencia, fim })); + } + + private string GetReferencia(FiltroLancamentoData filtro) + { + if (filtro == FiltroLancamentoData.Baixa) + { + return "CAST(l.dtbaixa AS DATE)"; + } + if (filtro != FiltroLancamentoData.Pagamento) + { + return "CAST(l.dtpre AS DATE)"; + } + return "CAST(l.dtpagto AS DATE)"; + } + + public bool HasByFornecedor(long id) + { + return base.All().Any((LancamentoDb x) => x.Controle.Fornecedor.Id == id); + } + + public Lancamento Merge(Lancamento lancamento) + { + LancamentoDb lancamentoDb = ApplicationMapper.Mapper.Map(lancamento); + base.Merge(lancamentoDb); + return ApplicationMapper.Mapper.Map(lancamentoDb); + } + + public Lancamento SaveOrUpdate(Lancamento lancamento) + { + LancamentoDb lancamentoDb = ApplicationMapper.Mapper.Map(lancamento); + this.SaveOrUpdate(lancamentoDb); + return ApplicationMapper.Mapper.Map(lancamentoDb); + } + + private List Select(string condition) + { + object connection; + DataTable dataTable = new DataTable(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + AuxiliarFinanceiro.Criar(sqlCommand); + sqlCommand.CommandText = string.Concat("SELECT DISTINCT c.idfornecedor, f.nome, f.Ativo, c.idfornecedor, c.idcplanos, c.idcentro, c.historico as historicocfinan, c.parcela as parcelas, cp.idcplano, l.* FROM lancamen l INNER JOIN cfinan c on c.idcfinan = l.idcfinan LEFT OUTER JOIN cplanos cp on c.idcplanos = cp.idcplanos LEFT OUTER JOIN fornecedor f on f.idfornecedor = c.idfornecedor WHERE 1=1 ", condition); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + } + } + return CustomMap.MapLancamento(dataTable); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MaisContatoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MaisContatoRepository.cs new file mode 100644 index 0000000..3dccaa4 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MaisContatoRepository.cs @@ -0,0 +1,158 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Helpers; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class MaisContatoRepository : GenericRepository, IMaisContatoRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public MaisContatoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public List DeleteContato(long clienteId, List contatos) + { + if (contatos == null) + { + return null; + } + List list = ( + from cliente in base.All() + where cliente.Cliente.Id == clienteId + select cliente).ToList().Where((MaisContatoDb contato) => { + List maisContatos = contatos; + Func u003cu003e9_83 = MaisContatoRepository.u003cu003ec.u003cu003e9__8_3; + if (u003cu003e9_83 == null) + { + u003cu003e9_83 = (MaisContato t) => t.Id; + MaisContatoRepository.u003cu003ec.u003cu003e9__8_3 = u003cu003e9_83; + } + if (maisContatos.Select(u003cu003e9_83).Contains(contato.Id)) + { + return false; + } + return !contato.Excluido; + }).ToList(); + if (contatos.Count == 0 && (list == null || list.Count == 0)) + { + return null; + } + list.ForEach((MaisContatoDb contato) => { + contato.Excluido = true; + base.Merge(contato); + }); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public List FindByCustomerId(long id) + { + ClienteDb clienteDb = this._unitOfWork.Query().FirstOrDefault((ClienteDb x) => x.Id == id); + if (clienteDb == null) + { + return new List(); + } + Cliente cliente = ApplicationMapper.Mapper.Map(clienteDb); + List condicaos = new List() + { + new Condicao() + { + Campo = "idcliente", + Valores = id.CriarValor() + }, + new Condicao() + { + Campo = "excluido", + Valores = null, + Operacao = Operacao.Or, + Grupo = 1 + }, + new Condicao() + { + Campo = "excluido", + Valores = "0".CriarValor(), + Operacao = Operacao.Or, + Grupo = 1 + } + }; + return this._unitOfWork.Select(condicaos.CreateParameters(0), "SELECT * FROM clicontato WHERE", "").MapMaisContatos(cliente); + } + + public MaisContato FindById(long id) + { + MaisContatoDb maisContatoDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(maisContatoDb); + } + + public List Inserir(List contatos, Cliente cliente) + { + contatos.ForEach((MaisContato x) => x.Cliente = cliente); + List maisContatoDbs = ApplicationMapper.Mapper.Map, List>(contatos); + base.AddRange(maisContatoDbs); + return ApplicationMapper.Mapper.Map, List>(maisContatoDbs); + } + + public List Inserir(List contatos) + { + List maisContatoDbs = ApplicationMapper.Mapper.Map, List>(contatos); + maisContatoDbs.ForEach((MaisContatoDb x) => { + if (x.Id == 0) + { + this.SaveOrUpdate(x); + return; + } + base.Merge(x); + }); + return ApplicationMapper.Mapper.Map, List>(maisContatoDbs); + } + + public MaisContato Merge(MaisContato maisContato) + { + MaisContatoDb maisContatoDb = ApplicationMapper.Mapper.Map(maisContato); + base.Merge(maisContatoDb); + return ApplicationMapper.Mapper.Map(maisContatoDb); + } + + public List Merge(List contatos, Cliente cliente) + { + List maisContatoDbs = ApplicationMapper.Mapper.Map, List>(contatos); + maisContatoDbs.ForEach((MaisContatoDb x) => { + if (x.Id != 0) + { + base.Merge(x); + return; + } + x.Cliente = ApplicationMapper.Mapper.Map(cliente); + this.SaveOrUpdate(x); + }); + return ApplicationMapper.Mapper.Map, List>(maisContatoDbs); + } + + public MaisContato SaveOrUpdate(MaisContato maisContato) + { + MaisContatoDb maisContatoDb = ApplicationMapper.Mapper.Map(maisContato); + this.SaveOrUpdate(maisContatoDb); + return ApplicationMapper.Mapper.Map(maisContatoDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MetaSeguradoraRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MetaSeguradoraRepository.cs new file mode 100644 index 0000000..639e281 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MetaSeguradoraRepository.cs @@ -0,0 +1,127 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Helpers; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class MetaSeguradoraRepository : GenericRepository, IMetaSeguradoraRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public MetaSeguradoraRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public List Find(long id) + { + return ( + from x in this._unitOfWork.Session.CreateQuery(string.Format("from MetaSeguradoraDb WHERE idciaseg = {0}", id)).List() + select new MetaSeguradora() + { + Id = x.Id, + Mes = x.Mes, + Ano = x.Ano, + Valor = x.Valor + }).ToList(); + } + + public MetaSeguradora FindById(long id) + { + MetaSeguradoraDb metaSeguradoraDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(metaSeguradoraDb); + } + + public List FindByMeta(Filtros filtro) + { + List metaSeguradoras; + object connection; + string str = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND idciaseg IN (", string.Join(",", + from v in filtro.Seguradoras + select v), ")")); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + DataTable dataTable = new DataTable(); + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + Auxiliar.CriarAuxiliar(sqlCommand, false); + object month = filtro.Fim.Month; + DateTime fim = filtro.Fim; + sqlCommand.CommandText = string.Format("SELECT IdMeta, IdCiaSeg, Mes, Ano, Valor\r\n FROM Meta\r\n WHERE (IdCiaSeg IS NOT NULL OR IdCiaSeg != '') AND Mes = {0} AND Ano = {1} {2};", month, fim.Year, str); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + if (dataTable.Rows.Count != 0) + { + return ( + from x in dataTable.AsEnumerable().ToList() + select new MetaSeguradora() + { + Id = x.Field("IdMeta"), + Mes = (Mes)x.Field("Mes"), + Ano = long.Parse(x.Field("Ano").ToString()), + Valor = x.Field("Valor"), + Seguradora = Auxiliar.Seguradoras.FirstOrDefault((Seguradora s) => s.Id == x.Field("IdCiaseg")) + }).ToList(); + } + else + { + metaSeguradoras = new List(); + } + } + } + return metaSeguradoras; + } + + public MetaSeguradora Merge(MetaSeguradora metaSeguradora) + { + MetaSeguradoraDb idAggilizador = ApplicationMapper.Mapper.Map(metaSeguradora); + idAggilizador.IdAggilizador = idAggilizador.Seguradora.IdAggilizador; + base.Merge(idAggilizador); + return ApplicationMapper.Mapper.Map(idAggilizador); + } + + public MetaSeguradora SaveOrUpdate(MetaSeguradora metaSeguradora) + { + MetaSeguradoraDb idAggilizador = ApplicationMapper.Mapper.Map(metaSeguradora); + idAggilizador.IdAggilizador = idAggilizador.Seguradora.IdAggilizador; + this.SaveOrUpdate(idAggilizador); + return ApplicationMapper.Mapper.Map(idAggilizador); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MetaVendedorRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MetaVendedorRepository.cs new file mode 100644 index 0000000..04be6b1 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MetaVendedorRepository.cs @@ -0,0 +1,125 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Helpers; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class MetaVendedorRepository : GenericRepository, IMetaVendedorRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public MetaVendedorRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public List Find(long id) + { + return ( + from x in this._unitOfWork.Session.CreateQuery(string.Format("from MetaVendedorDb WHERE idvendedor = {0}", id)).List() + select new MetaVendedor() + { + Id = x.Id, + Mes = x.Mes, + Ano = x.Ano, + Valor = x.Valor + }).ToList(); + } + + public MetaVendedor FindById(long id) + { + MetaVendedorDb metaVendedorDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(metaVendedorDb); + } + + public List FindByMeta(Filtros filtro) + { + List metaVendedors; + object connection; + string str = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? "" : string.Concat(" AND idvendedor IN (", string.Join(",", + from v in filtro.Vendedores + select v), ")")); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + DataTable dataTable = new DataTable(); + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + Auxiliar.CriarAuxiliar(sqlCommand, false); + object month = filtro.Fim.Month; + DateTime fim = filtro.Fim; + sqlCommand.CommandText = string.Format("SELECT IdMetaVendedor, IdVendedor, Mes, Ano, Valor\r\n FROM MetaVendedor\r\n WHERE Mes = {0} AND Ano = {1} {2};", month, fim.Year, str); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + if (dataTable.Rows.Count != 0) + { + return ( + from x in dataTable.AsEnumerable().ToList() + select new MetaVendedor() + { + Id = x.Field("IdMetaVendedor"), + Mes = (Mes)x.Field("Mes"), + Ano = long.Parse(x.Field("Ano").ToString()), + Valor = x.Field("Valor"), + Vendedor = Auxiliar.Vendedores.FirstOrDefault((Vendedor v) => v.Id == x.Field("idvendedor")) + }).ToList(); + } + else + { + metaVendedors = new List(); + } + } + } + return metaVendedors; + } + + public MetaVendedor Merge(MetaVendedor metaVendedor) + { + MetaVendedorDb metaVendedorDb = ApplicationMapper.Mapper.Map(metaVendedor); + base.Merge(metaVendedorDb); + return ApplicationMapper.Mapper.Map(metaVendedorDb); + } + + public MetaVendedor SaveOrUpdate(MetaVendedor metaVendedor) + { + MetaVendedorDb metaVendedorDb = ApplicationMapper.Mapper.Map(metaVendedor); + this.SaveOrUpdate(metaVendedorDb); + return ApplicationMapper.Mapper.Map(metaVendedorDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ModeloMalaDiretaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ModeloMalaDiretaRepository.cs new file mode 100644 index 0000000..799cb19 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ModeloMalaDiretaRepository.cs @@ -0,0 +1,59 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.MalaDireta; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class ModeloMalaDiretaRepository : GenericRepository, IModeloMalaDiretaRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public ModeloMalaDiretaRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + ModeloMalaDiretaDb modeloMalaDiretaDb = base.FindEntityById(id); + if (modeloMalaDiretaDb == null) + { + return; + } + base.Delete(modeloMalaDiretaDb); + } + + public List Find() + { + List list = base.All().ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public ModeloMalaDireta FindById(long id) + { + ModeloMalaDiretaDb modeloMalaDiretaDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(modeloMalaDiretaDb); + } + + public ModeloMalaDireta Merge(ModeloMalaDireta modelo) + { + ModeloMalaDiretaDb modeloMalaDiretaDb = ApplicationMapper.Mapper.Map(modelo); + base.Merge(modeloMalaDiretaDb); + return ApplicationMapper.Mapper.Map(modeloMalaDiretaDb); + } + + public ModeloMalaDireta SaveOrUpdate(ModeloMalaDireta modelo) + { + ModeloMalaDiretaDb modeloMalaDiretaDb = ApplicationMapper.Mapper.Map(modelo); + this.SaveOrUpdate(modeloMalaDiretaDb); + return ApplicationMapper.Mapper.Map(modeloMalaDiretaDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/NotaFiscalRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/NotaFiscalRepository.cs new file mode 100644 index 0000000..f35835a --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/NotaFiscalRepository.cs @@ -0,0 +1,131 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Helpers; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class NotaFiscalRepository : GenericRepository, INotaFiscalRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public NotaFiscalRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + NotaFiscalDb notaFiscalDb = base.FindEntityById(id); + if (notaFiscalDb == null) + { + return; + } + base.Delete(notaFiscalDb); + } + + public List FindAll() + { + return this.Select(""); + } + + public List FindByDatas(Filtros filtro) + { + string str = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND IdSeguradora IN (", string.Join(",", + from v in filtro.Seguradoras + select v), ")")); + return this.Select(string.Format(" AND Data >= '{0:yyyy-MM-dd}' AND Data <= '{1:yyyy-MM-dd}' {2}", filtro.Inicio, filtro.Fim, str)); + } + + public bool FindByExtrato(long id) + { + return base.All().FirstOrDefault((NotaFiscalDb x) => x.IdExtrato == (long?)id) != null; + } + + public NotaFiscal Merge(NotaFiscal notaFiscal) + { + NotaFiscalDb notaFiscalDb = ApplicationMapper.Mapper.Map(notaFiscal); + base.Merge(notaFiscalDb); + return ApplicationMapper.Mapper.Map(notaFiscalDb); + } + + public NotaFiscal SaveOrUpdate(NotaFiscal notaFiscal) + { + NotaFiscalDb notaFiscalDb = ApplicationMapper.Mapper.Map(notaFiscal); + this.SaveOrUpdate(notaFiscalDb); + return ApplicationMapper.Mapper.Map(notaFiscalDb); + } + + private List Select(string condition) + { + List notaFiscals; + object connection; + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + DataTable dataTable = new DataTable(); + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandTimeout = 15000; + Auxiliar.CriarAuxiliar(sqlCommand, false); + sqlCommand.CommandText = string.Concat("SELECT * FROM NotaFiscal WHERE 1=1 ", condition, ";"); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + if (dataTable.Rows.Count != 0) + { + return ( + from x in dataTable.AsEnumerable().ToList() + select new NotaFiscal() + { + Id = x.Field("Id"), + ValorLiquido = x.Field("ValorLiquido"), + Obs = x.Field("obs"), + IdExtrato = x.Field("IdExtrato"), + Iss = x.Field("Iss"), + ValorBruto = x.Field("ValorBruto"), + Data = x.Field("Data"), + Seguradora = Auxiliar.Seguradoras.FirstOrDefault((Seguradora v) => v.Id == x.Field("IdSeguradora")), + Estipulante = (!x.Field("IdEstipulante").HasValue ? null : Auxiliar.Estipulantes.FirstOrDefault((Estipulante e) => e.Id == x.Field("IdEstipulante"))), + Extrato = x.Field("Extrato"), + Ir = (x.Field("Ir") != null ? x.Field("Ir") : decimal.Zero) + }).ToList(); + } + else + { + notaFiscals = new List(); + } + } + } + return notaFiscals; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParametrosRelatorioRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParametrosRelatorioRepository.cs new file mode 100644 index 0000000..d547f22 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParametrosRelatorioRepository.cs @@ -0,0 +1,111 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Relatorios; +using Gestor.Infrastructure.Helpers; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Relatorios; +using System; +using System.Collections.Generic; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class ParametrosRelatorioRepository : GenericRepository, IParametrosRelatorioRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public ParametrosRelatorioRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + ParametrosRelatorioDb parametrosRelatorioDb = base.FindEntityById(id); + if (parametrosRelatorioDb == null) + { + return; + } + base.Delete(parametrosRelatorioDb); + } + + public List Find(long id, Relatorio relatorio) + { + List parametrosRelatorios = this.Select(new List() + { + new Condicao() + { + Campo = "IdUsuario", + Valores = id.CriarValor() + }, + new Condicao() + { + Campo = "Relatorio", + Valores = relatorio.CriarValor() + }, + new Condicao() + { + Campo = "Header", + Valores = null, + Operador = Operador.Diferente + }, + new Condicao() + { + Campo = "Header", + Valores = "".CriarValor(), + Operador = Operador.Diferente + } + }); + if (parametrosRelatorios.Count == 0) + { + parametrosRelatorios = this.Select(new List() + { + new Condicao() + { + Campo = "IdUsuario", + Valores = 0.CriarValor() + }, + new Condicao() + { + Campo = "Relatorio", + Valores = relatorio.CriarValor() + }, + new Condicao() + { + Campo = "Header", + Valores = null, + Operador = Operador.Diferente + }, + new Condicao() + { + Campo = "Header", + Valores = "".CriarValor(), + Operador = Operador.Diferente + } + }); + } + return parametrosRelatorios; + } + + public ParametrosRelatorio Merge(ParametrosRelatorio parametrosRelatorio) + { + ParametrosRelatorioDb parametrosRelatorioDb = ApplicationMapper.Mapper.Map(parametrosRelatorio); + base.Merge(parametrosRelatorioDb); + return ApplicationMapper.Mapper.Map(parametrosRelatorioDb); + } + + public ParametrosRelatorio SaveOrUpdate(ParametrosRelatorio parametrosRelatorio) + { + ParametrosRelatorioDb parametrosRelatorioDb = ApplicationMapper.Mapper.Map(parametrosRelatorio); + this.SaveOrUpdate(parametrosRelatorioDb); + return ApplicationMapper.Mapper.Map(parametrosRelatorioDb); + } + + public List Select(List condicao) + { + return this._unitOfWork.Select(condicao.CreateParameters(0), "SELECT * FROM CamposRelatorios WHERE ", "").MapCamposRelatorio(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParametrosTotalizacaoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParametrosTotalizacaoRepository.cs new file mode 100644 index 0000000..19ce696 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParametrosTotalizacaoRepository.cs @@ -0,0 +1,59 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Relatorios; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Relatorios; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class ParametrosTotalizacaoRepository : GenericRepository, IParametrosTotalizacaoRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public ParametrosTotalizacaoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + ParametrosTotalizacaoDb parametrosTotalizacaoDb = base.FindEntityById(id); + if (parametrosTotalizacaoDb == null) + { + return; + } + base.Delete(parametrosTotalizacaoDb); + } + + public List Find(long id, Relatorio relatorio) + { + List list = ( + from x in base.All() + where x.IdUsuario == id && (int)x.Relatorio == (int)relatorio && x.Header != "AGRUPAMENTO" + select x).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public ParametrosTotalizacao Merge(ParametrosTotalizacao parametrosTotalizacao) + { + ParametrosTotalizacaoDb parametrosTotalizacaoDb = ApplicationMapper.Mapper.Map(parametrosTotalizacao); + base.Merge(parametrosTotalizacaoDb); + return ApplicationMapper.Mapper.Map(parametrosTotalizacaoDb); + } + + public ParametrosTotalizacao SaveOrUpdate(ParametrosTotalizacao parametrosTotalizacao) + { + ParametrosTotalizacaoDb parametrosTotalizacaoDb = ApplicationMapper.Mapper.Map(parametrosTotalizacao); + this.SaveOrUpdate(parametrosTotalizacaoDb); + return ApplicationMapper.Mapper.Map(parametrosTotalizacaoDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParceiroRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParceiroRepository.cs new file mode 100644 index 0000000..476ec1a --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParceiroRepository.cs @@ -0,0 +1,108 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class ParceiroRepository : GenericRepository, IParceiroRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public ParceiroRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public List Find() + { + List list = base.All().ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public List Find(string filter) + { + ParceiroRepository.u003cu003ec__DisplayClass7_0 variable = null; + IQueryable parceiroDbs = base.All(); + ParameterExpression parameterExpression = Expression.Parameter(typeof(ParceiroDb), "x"); + IQueryable parceiroDbs1 = parceiroDbs.Where(Expression.Lambda>(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(ParceiroDb).GetMethod("get_Nome").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(ParceiroRepository.u003cu003ec__DisplayClass7_0)), FieldInfo.GetFieldFromHandle(typeof(ParceiroRepository.u003cu003ec__DisplayClass7_0).GetField("filter").FieldHandle)) }), new ParameterExpression[] { parameterExpression })); + parameterExpression = Expression.Parameter(typeof(ParceiroDb), "x"); + return parceiroDbs1.Select(Expression.Lambda>(Expression.MemberInit(Expression.New(typeof(Parceiro)), new MemberBinding[] { Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(DomainBase).GetMethod("set_Id", new Type[] { typeof(long) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(EntityBase).GetMethod("get_Id").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Parceiro).GetMethod("set_Nome", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(ParceiroDb).GetMethod("get_Nome").MethodHandle))) }), new ParameterExpression[] { parameterExpression })).ToList(); + } + + public Parceiro FindById(long id) + { + ParceiroDb parceiroDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(parceiroDb); + } + + public long FindLastId() + { + long num; + object connection; + SqlCommand sqlCommand; + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + if (sqlConnection != null) + { + sqlCommand = sqlConnection.CreateCommand(); + } + else + { + sqlCommand = null; + } + using (SqlCommand sqlCommand1 = sqlCommand) + { + sqlCommand1.CommandText = "SELECT MAX(IDPARCEIRO) as id FROM parceiro"; + SqlDataReader sqlDataReader = sqlCommand1.ExecuteReader(); + sqlDataReader.Read(); + num = (sqlDataReader["id"] == null ? (long)0 : long.Parse(sqlDataReader["id"].ToString())); + } + } + return num; + } + + public Parceiro Merge(Parceiro parceiro) + { + ParceiroDb parceiroDb = ApplicationMapper.Mapper.Map(parceiro); + base.Merge(parceiroDb); + return ApplicationMapper.Mapper.Map(parceiroDb); + } + + public Parceiro SaveOrUpdate(Parceiro parceiro) + { + ParceiroDb parceiroDb = ApplicationMapper.Mapper.Map(parceiro); + this.SaveOrUpdate(parceiroDb); + return ApplicationMapper.Mapper.Map(parceiroDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParcelaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParcelaRepository.cs new file mode 100644 index 0000000..f6e2cdf --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParcelaRepository.cs @@ -0,0 +1,4562 @@ +using AutoMapper; +using Gestor.Common.Helpers; +using Gestor.Common.Validation; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Helpers; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Aggilizador; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Relatorios.PrevisaoPagamentoComissao; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using NHibernate.Util; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Diagnostics; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class ParcelaRepository : GenericRepository, IParcelaRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public ParcelaRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public async Task> BuscaDocumentosPorVigencia(Filtros filtro, bool buscaAssinaturas = false, bool painelBi = false) + { + List documentos = new List(); + return await this.BuscaDocumentosPorVigenciaNew(filtro, buscaAssinaturas, painelBi); + } + + private async Task> BuscaDocumentosPorVigenciaNew(Filtros filtro, bool buscaAssinaturas = false, bool painelBi = false) + { + NegocioCorretora fieldValue; + Predicate predicate; + object connection; + bool count; + string str; + bool flag; + object vendedor; + bool count1; + Documento documento1; + List itensAtivo; + object produto; + object obj; + object statu; + object banco; + List statusDocumentoAssinados; + bool flag1; + StatusAssinatura statusAssinatura; + NegocioCorretora negocioCorretora; + bool count2; + bool flag2; + Predicate predicate1 = null; + Predicate predicate2 = null; + Predicate predicate3 = null; + Predicate predicate4 = null; + Predicate predicate5 = null; + List documentos = new List(); + string str1 = "CAST(f.vigenciai AS DATE)"; + string referencia = filtro.Referencia; + if (referencia == "EMISSÃO") + { + str1 = "CAST(f.emissao AS DATE)"; + } + else if (referencia == "TRANSMISSÃO PROPOSTA") + { + str1 = "CAST(d.remessa AS DATE)"; + } + else if (referencia == "DATA CRIAÇÃO" || referencia == "DATA DE CADASTRO") + { + str1 = "CAST(p.cri_data AS DATE)"; + } + List condicaos = this.CriaCondicaoDocumento(filtro, str1); + List condicaos1 = new List(); + Condicao condicao = new Condicao() + { + Campo = "d.Excluido", + Valores = null, + Grupo = 1, + Operacao = Operacao.Or + }; + condicaos1.Add(condicao); + Condicao condicao1 = new Condicao() + { + Campo = "d.Excluido", + Valores = "0".CriarValor(), + Grupo = 1, + Operacao = Operacao.Or + }; + condicaos1.Add(condicao1); + condicaos.AddRange(condicaos1); + SqlQueryCondition sqlQueryCondition = condicaos.CreateParameters(0); + using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) + { + SessionFactoryImpl sessionFactoryImpl = sessionFactory; + if (sessionFactoryImpl != null) + { + connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + bool flag3 = await this.ExisteTabelasAssinatura(); + bool flag4 = flag3; + List parcelas = new List(); + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandTimeout = 1000; + string str2 = "SELECT f.IDFATURA IdFatura, p.IDPARCELA IdParcela, d.IDDOCUMENTO IdDocumento, c.IDEMPRESA IdEmpresa, c.IDCLIENTE IdCliente, clie.CGCCPF DocumentoCliente, clie.MalaDireta MalaDireta, clie.NOME NomeCliente, clie.pasta PastaCliente, c.IDCONTROLE IdControle, cm.idclimail IdEmail, cm.email, ct.idclitelefone IdTelefone, ct.ddd Prefixo, ct.fone Numero, d.CONTRATO Apolice, d.PROPOSTA Proposta, d.PEDADIT PropostaEndosso, f.NumFatura NumeroFatura, f.Emissao EmissaoFatura, d.idnegocio Negocio, d.SITUACAO Situacao, f.VIGENCIAI VigenciaInicial, f.VIGENCIAF VigenciaFinal, p.VALOR PremioTotal, p.VALORLF PremioLiquido, p.comiss Comissao, c.IDRAMO IdRamo, r.NOME NomeRamo, c.IDCIASEG IdCiaSeg, cia.NOME NomeCia, cia.NomeSocial NomeSocialCia, c.IDPRODUTO IdProduto, pr.NOME NomeProduto, d.idestipulante IdEstipulante,d.idestipulante2 IdEstipulante2,d.idestipulante3 IdEstipulante3,d.idestipulante4 IdEstipulante4,d.idestipulante5 IdEstipulante5, e.nome NomeEstipulante, d.NegocioCorretora NegocioCorretora, p.datacontrole DataControleParcela, d.idstatus IdStatus, s.nome NomeStatus, p.CRI_DATA DataCriacaoParcela, d.TIPO Tipo, d.REMESSA Remessa, d.idbanco IdBanco, b.NOMEBANCO NomeBanco, d.AGENCIA Agencia, d.CONTA Conta, d.PASTA PastaDocumento, d.apoconferida ApoliceConferida, d.propassinada PropostaAssinada, vp.IDVENDEDORPARCELA IdVendedorParcela, vp.idtipovendedor IdTipoVendedor, vp.IDVENDEDOR IdVendedor, vp.VREP PorcentagemRepasse, v.NOME NomeVendedor FROM fatura f INNER JOIN parcela p ON p.IDPARCELA = f.IDPARCELA INNER JOIN documento d ON d.IDDOCUMENTO = p.IDDOCUMENTO INNER JOIN controle c ON c.IDCONTROLE = d.IDCONTROLE INNER JOIN cliente clie ON clie.IDCLIENTE = c.IDCLIENTE INNER JOIN ramo r ON r.IDRAMO = c.IDRAMO INNER JOIN ciaseg cia ON cia.IDCIASEG = c.IDCIASEG LEFT JOIN codigobanco b ON b.IDCODIGOBANCO = d.IDBANCO LEFT JOIN produto pr ON pr.IDPRODUTO = c.IDPRODUTO LEFT JOIN estipulante e ON e.idestipulante = d.idestipulante LEFT JOIN status s ON s.idstatus = d.idstatus LEFT JOIN vendedorparcela vp ON vp.IDPARCELA = f.IDPARCELA LEFT JOIN vendedor v ON v.IDVENDEDOR = vp.IDVENDEDOR LEFT JOIN clitelefone ct ON ct.IDCLIENTE = c.IDCLIENTE LEFT JOIN climail cm ON cm.IDCLIENTE = c.IDCLIENTE WHERE "; + sqlCommand.CommandText = string.Concat(str2, " ", sqlQueryCondition.Condicao, " ORDER BY f.IDPARCELA, d.IDDOCUMENTO, d.IDCONTROLE, vp.idtipovendedor, vp.IDVENDEDOR"); + sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray()); + using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) + { + while (true) + { + if (!await sqlDataReader.ReadAsync()) + { + break; + } + TipoSeguro tipoSeguro = sqlDataReader.GetFieldValue("Situacao", true, true); + if (!await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "NegocioCorretora")) + { + fieldValue = sqlDataReader.GetFieldValue("NegocioCorretora", true, true); + } + else + { + flag3 = tipoSeguro == TipoSeguro.Renovacao; + if (flag3) + { + flag3 = !await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "Negocio"); + } + negocioCorretora = (!flag3 || !(sqlDataReader.GetFieldValue("Negocio", true, true) == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio); + fieldValue = negocioCorretora; + } + NegocioCorretora negocioCorretora1 = fieldValue; + List negocio = filtro.Negocio; + if (negocio != null) + { + count = negocio.Count > 0; + } + else + { + count = false; + } + if (!count || filtro.Negocio.Any((long n) => (int)n == (int)negocioCorretora1)) + { + List estipulantes = new List(); + sqlDataReader.GetFieldValue("idestipulante", true, true); + if (sqlDataReader.GetFieldValue("idestipulante", true, true) != 0) + { + List estipulantes1 = estipulantes; + Estipulante nome = new Estipulante(); + List estipulantes2 = Auxiliar.Estipulantes; + Predicate predicate6 = predicate1; + if (predicate6 == null) + { + Predicate predicate7 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue("idestipulante", true, true); + predicate = predicate7; + predicate1 = predicate7; + predicate6 = predicate; + } + nome.Nome = estipulantes2.Find(predicate6).Nome; + estipulantes1.Add(nome); + } + sqlDataReader.GetFieldValue("idestipulante2", true, true); + if (sqlDataReader.GetFieldValue("idestipulante2", true, true) != 0) + { + List estipulantes3 = estipulantes; + Estipulante nome1 = new Estipulante(); + List estipulantes4 = Auxiliar.Estipulantes; + Predicate predicate8 = predicate2; + if (predicate8 == null) + { + Predicate predicate9 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue("idestipulante2", true, true); + predicate = predicate9; + predicate2 = predicate9; + predicate8 = predicate; + } + nome1.Nome = estipulantes4.Find(predicate8).Nome; + estipulantes3.Add(nome1); + } + sqlDataReader.GetFieldValue("idestipulante3", true, true); + if (sqlDataReader.GetFieldValue("idestipulante3", true, true) != 0) + { + List estipulantes5 = estipulantes; + Estipulante estipulante1 = new Estipulante(); + List estipulantes6 = Auxiliar.Estipulantes; + Predicate predicate10 = predicate3; + if (predicate10 == null) + { + Predicate predicate11 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue("idestipulante3", true, true); + predicate = predicate11; + predicate3 = predicate11; + predicate10 = predicate; + } + estipulante1.Nome = estipulantes6.Find(predicate10).Nome; + estipulantes5.Add(estipulante1); + } + sqlDataReader.GetFieldValue("idestipulante4", true, true); + if (sqlDataReader.GetFieldValue("idestipulante4", true, true) != 0) + { + List estipulantes7 = estipulantes; + Estipulante nome2 = new Estipulante(); + List estipulantes8 = Auxiliar.Estipulantes; + Predicate predicate12 = predicate4; + if (predicate12 == null) + { + Predicate predicate13 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue("idestipulante4", true, true); + predicate = predicate13; + predicate4 = predicate13; + predicate12 = predicate; + } + nome2.Nome = estipulantes8.Find(predicate12).Nome; + estipulantes7.Add(nome2); + } + sqlDataReader.GetFieldValue("idestipulante5", true, true); + if (sqlDataReader.GetFieldValue("idestipulante5", true, true) != 0) + { + List estipulantes9 = estipulantes; + Estipulante estipulante2 = new Estipulante(); + List estipulantes10 = Auxiliar.Estipulantes; + Predicate predicate14 = predicate5; + if (predicate14 == null) + { + Predicate predicate15 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue("idestipulante5", true, true); + predicate = predicate15; + predicate5 = predicate15; + predicate14 = predicate; + } + estipulante2.Nome = estipulantes10.Find(predicate14).Nome; + estipulantes9.Add(estipulante2); + } + if (estipulantes.Count > 0) + { + List estipulantes11 = estipulantes; + str = string.Join(" | ", + from estipulante in estipulantes11 + select estipulante.Nome); + } + else + { + str = ""; + } + string str3 = str; + long num = sqlDataReader.GetFieldValue("IdDocumento", true, true); + long fieldValue1 = sqlDataReader.GetFieldValue("IdParcela", true, true); + Parcela observableCollection = parcelas.Find((Parcela p) => p.Id == fieldValue1); + if (observableCollection == null) + { + Parcela parcela = parcelas.Find((Parcela d) => d.Documento.Id == num); + if (parcela != null) + { + documento1 = parcela.Documento; + } + else + { + documento1 = null; + } + Documento zero = documento1; + if (zero != null) + { + zero = zero.DeepCopy(); + } + else + { + long num1 = sqlDataReader.GetFieldValue("IdControle", true, true); + long fieldValue2 = sqlDataReader.GetFieldValue("IdEmpresa", true, true); + Documento documento2 = documentos.Find((Documento p) => p.Controle.Id == num1); + if (documento2 != null) + { + itensAtivo = documento2.ItensAtivo; + } + else + { + itensAtivo = null; + } + List items = itensAtivo; + if (items == null) + { + items = await this.BuscaItemsPorIdControle(num1); + } + Documento valueOrDefault = new Documento() + { + Id = num + }; + Controle controle = new Controle() + { + Id = num1, + IdEmpresa = fieldValue2 + }; + Cliente cliente = new Cliente() + { + Id = sqlDataReader.GetFieldValue("IdCliente", true, true), + Nome = sqlDataReader.GetFieldValue("NomeCliente", true, true), + Documento = sqlDataReader.GetFieldValue("DocumentoCliente", true, true), + Pasta = sqlDataReader.GetFieldValue("PastaCliente", true, true) + }; + bool? fieldValue3 = sqlDataReader.GetFieldValue("MalaDireta", true, true); + cliente.MalaDireta = new bool?(fieldValue3.GetValueOrDefault(true)); + ObservableCollection observableCollection1 = new ObservableCollection(); + ClienteTelefone clienteTelefone = new ClienteTelefone() + { + Id = sqlDataReader.GetFieldValue("IdTelefone", true, true), + Prefixo = sqlDataReader.GetFieldValue("Prefixo", true, true), + Numero = sqlDataReader.GetFieldValue("Numero", true, true) + }; + observableCollection1.Add(clienteTelefone); + cliente.Telefones = observableCollection1; + ObservableCollection observableCollection2 = new ObservableCollection(); + ClienteEmail clienteEmail = new ClienteEmail() + { + Id = sqlDataReader.GetFieldValue("IdEmail", true, true), + Email = sqlDataReader.GetFieldValue("Email", true, true) + }; + observableCollection2.Add(clienteEmail); + cliente.Emails = observableCollection2; + controle.Cliente = cliente; + Ramo ramo = new Ramo() + { + Id = sqlDataReader.GetFieldValue("IdRamo", true, true), + Nome = sqlDataReader.GetFieldValue("NomeRamo", true, true) + }; + controle.Ramo = ramo; + Seguradora seguradora = new Seguradora() + { + Id = sqlDataReader.GetFieldValue("IdCiaSeg", true, true), + Nome = sqlDataReader.GetFieldValue("NomeCia", true, true), + NomeSocial = sqlDataReader.GetFieldValue("NomeSocialCia", true, true) + }; + controle.Seguradora = seguradora; + if (sqlDataReader.FieldIsNull("IdProduto")) + { + produto = null; + } + else + { + produto = new Produto(); + ((DomainBase)produto).Id = sqlDataReader.GetFieldValue("IdProduto", true, true); + ((Produto)produto).Nome = sqlDataReader.GetFieldValue("NomeProduto", true, true); + } + controle.Produto = (Produto)produto; + valueOrDefault.Controle = controle; + if (sqlDataReader.FieldIsNull("IdEstipulante")) + { + obj = null; + } + else + { + obj = new Estipulante(); + ((DomainBase)obj).Id = sqlDataReader.GetFieldValue("IdEstipulante", true, true); + ((Estipulante)obj).Nome = sqlDataReader.GetFieldValue("NomeEstipulante", true, true); + } + valueOrDefault.Estipulante1 = (Estipulante)obj; + valueOrDefault.Estipulantes = str3; + if (sqlDataReader.FieldIsNull("IdStatus")) + { + statu = null; + } + else + { + statu = new Status(); + ((DomainBase)statu).Id = sqlDataReader.GetFieldValue("IdStatus", true, true); + ((Status)statu).Nome = sqlDataReader.GetFieldValue("NomeStatus", true, true); + } + valueOrDefault.Status = (Status)statu; + valueOrDefault.TipoRecebimento = new TipoRecebimento?(TipoRecebimento.Fatura); + valueOrDefault.Tipo = sqlDataReader.GetFieldValue("Tipo", true, true); + valueOrDefault.NegocioCorretora = new NegocioCorretora?(negocioCorretora1); + valueOrDefault.Situacao = tipoSeguro; + fieldValue3 = sqlDataReader.GetFieldValue("ApoliceConferida", true, true); + valueOrDefault.ApoliceConferida = fieldValue3.GetValueOrDefault(); + fieldValue3 = sqlDataReader.GetFieldValue("PropostaAssinada", true, true); + valueOrDefault.PropostaAssinada = fieldValue3.GetValueOrDefault(); + valueOrDefault.Proposta = sqlDataReader.GetFieldValue("Proposta", true, true); + valueOrDefault.Apolice = sqlDataReader.GetFieldValue("Apolice", true, true); + valueOrDefault.PropostaEndosso = sqlDataReader.GetFieldValue("PropostaEndosso", true, true); + valueOrDefault.Remessa = sqlDataReader.GetFieldValue("Remessa", true, true); + valueOrDefault.DataControle = sqlDataReader.GetFieldValue("DataControleParcela", true, true); + valueOrDefault.DataCriacao = sqlDataReader.GetFieldValue("DataCriacaoParcela", true, true); + valueOrDefault.Pasta = sqlDataReader.GetFieldValue("PastaDocumento", true, true); + if (sqlDataReader.FieldIsNull("IdBanco")) + { + banco = null; + } + else + { + banco = new Banco(); + ((Banco)banco).Id = sqlDataReader.GetFieldValue("IdBanco", true, true); + ((Banco)banco).Nome = sqlDataReader.GetFieldValue("NomeBanco", true, true); + } + valueOrDefault.Banco = (Banco)banco; + valueOrDefault.Agencia = sqlDataReader.GetFieldValue("Agencia", true, true); + valueOrDefault.Conta = sqlDataReader.GetFieldValue("Conta", true, true); + valueOrDefault.ItensAtivo = items; + zero = valueOrDefault; + if (flag4 & buscaAssinaturas) + { + List statusDocumentoAssinados1 = await this.BuscaStatusAssinadosPorIdDocumento(zero.Id); + string str4 = (zero.Tipo == 0 ? "PROPOSTA" : "PEDIDO DE ENDOSSO"); + statusDocumentoAssinados1.ForEach((StatusDocumentoAssinado a) => { + if (a.Documento.ToUpper() == str4 || a.Documento.ToUpper().Contains(str4)) + { + a.Selecionado = true; + } + }); + List statusDocumentoAssinados2 = statusDocumentoAssinados1; + StatusDocumentoAssinado statusDocumentoAssinado = statusDocumentoAssinados2.FirstOrDefault((StatusDocumentoAssinado a) => a.Selecionado); + Documento documento3 = zero; + if (statusDocumentoAssinados1 == null || statusDocumentoAssinados1.Count <= 0) + { + statusDocumentoAssinados = null; + } + else + { + statusDocumentoAssinados = statusDocumentoAssinados1; + } + documento3.Assinaturas = statusDocumentoAssinados; + Documento documento4 = zero; + flag1 = (statusDocumentoAssinado != null ? statusDocumentoAssinado.Status == StatusAssinatura.Assinado : false); + documento4.AssinadaSiggner = flag1; + Documento documento5 = zero; + statusAssinatura = (statusDocumentoAssinado != null ? statusDocumentoAssinado.Status : StatusAssinatura.NaoEnviado); + documento5.StatusAssinatura = statusAssinatura; + } + } + zero.Tipo = 2; + zero.AdicionalComiss = false; + zero.PremioAdicional = decimal.Zero; + zero.NumeroParcelas = decimal.One; + zero.Endosso = string.Concat("F ", sqlDataReader.GetFieldValue("NumeroFatura", true, true)); + zero.Comissao = sqlDataReader.GetFieldValue("Comissao", true, true); + zero.PremioLiquido = sqlDataReader.GetFieldValue("PremioLiquido", true, true); + zero.PremioTotal = sqlDataReader.GetFieldValue("PremioTotal", true, true); + zero.Vigencia1 = sqlDataReader.GetFieldValue("VigenciaInicial", true, true); + zero.Vigencia2 = sqlDataReader.GetFieldValue("VigenciaFinal", true, true); + zero.Emissao = sqlDataReader.GetFieldValue("EmissaoFatura", true, true); + zero.DataControle = sqlDataReader.GetFieldValue("DataControleParcela", true, true); + if (zero.Controle.Cliente.Telefones != null) + { + long num2 = sqlDataReader.GetFieldValue("IdTelefone", true, true); + if (zero.Controle.Cliente.Telefones.FirstOrDefault((ClienteTelefone t) => t.Id == num2) == null) + { + ObservableCollection telefones = zero.Controle.Cliente.Telefones; + ClienteTelefone clienteTelefone1 = new ClienteTelefone() + { + Id = num2, + Prefixo = sqlDataReader.GetFieldValue("Prefixo", true, true), + Numero = sqlDataReader.GetFieldValue("Numero", true, true) + }; + telefones.Add(clienteTelefone1); + } + } + if (zero.Controle.Cliente.Emails != null) + { + long num3 = sqlDataReader.GetFieldValue("IdEmail", true, true); + if (zero.Controle.Cliente.Emails.FirstOrDefault((ClienteEmail t) => t.Id == num3) == null) + { + ObservableCollection emails = zero.Controle.Cliente.Emails; + ClienteEmail clienteEmail1 = new ClienteEmail() + { + Id = num3, + Email = sqlDataReader.GetFieldValue("Email", true, true) + }; + emails.Add(clienteEmail1); + } + } + Parcela parcela1 = new Parcela() + { + Id = fieldValue1, + Documento = zero + }; + observableCollection = parcela1; + parcelas.Add(observableCollection); + zero = null; + } + List tipoVendedor = filtro.TipoVendedor; + if (tipoVendedor != null) + { + flag = tipoVendedor.Count > 0; + } + else + { + flag = false; + } + if (!flag) + { + List nums = filtro.Vendedores; + if (nums != null) + { + count1 = nums.Count > 0; + } + else + { + count1 = false; + } + if (!count1) + { + if (observableCollection.Vendedores == null) + { + observableCollection.Vendedores = new ObservableCollection(); + } + long fieldValue4 = sqlDataReader.GetFieldValue("IdTipoVendedor", true, true); + long num4 = sqlDataReader.GetFieldValue("IdVendedor", true, true); + if (observableCollection.Vendedores.ToList().Find((VendedorParcela vps) => { + if (vps.TipoVendedor.Id != fieldValue4) + { + return false; + } + return vps.Vendedor.Id == num4; + }) == null) + { + ObservableCollection observableCollection3 = observableCollection.Vendedores; + VendedorParcela vendedorParcela1 = new VendedorParcela() + { + PorcentagemRepasse = new decimal?(sqlDataReader.GetFieldValue("PorcentagemRepasse", true, true)), + TipoVendedor = new TipoVendedor() + { + Id = fieldValue4 + } + }; + Vendedor vendedor1 = new Vendedor() + { + Id = num4, + Nome = sqlDataReader.GetFieldValue("NomeVendedor", true, true) + }; + vendedorParcela1.Vendedor = vendedor1; + observableCollection3.Add(vendedorParcela1); + } + } + } + if (observableCollection.Documento.VendedorPrincipal == null) + { + Documento documento6 = observableCollection.Documento; + if (sqlDataReader.FieldIsNull("IdVendedor")) + { + vendedor = null; + } + else + { + vendedor = new Vendedor(); + ((DomainBase)vendedor).Id = sqlDataReader.GetFieldValue("IdVendedor", true, true); + ((Vendedor)vendedor).Nome = sqlDataReader.GetFieldValue("NomeVendedor", true, true); + } + documento6.VendedorPrincipal = (Vendedor)vendedor; + } + str3 = null; + } + } + } + } + sqlCommand = null; + List tipoVendedor1 = filtro.TipoVendedor; + if (tipoVendedor1 != null) + { + count2 = tipoVendedor1.Count > 0; + } + else + { + count2 = false; + } + if (!count2) + { + List nums1 = filtro.Vendedores; + if (nums1 != null) + { + flag2 = nums1.Count > 0; + } + else + { + flag2 = false; + } + if (!flag2) + { + goto Label0; + } + } + foreach (Parcela parcela2 in parcelas) + { + Parcela parcela3 = parcela2; + List vendedorParcelas1 = await this.BuscaVendedoresPorIdParcela(parcela2.Id, parcela2.Documento.Controle.IdEmpresa, (long)1); + parcela3.Vendedores = new ObservableCollection(vendedorParcelas1); + parcela3 = null; + } + Label0: + parcelas.ForEach((Parcela p) => { + decimal? nullable2; + decimal? porcentagemRepasse; + ObservableCollection vendedores = p.Vendedores; + Func u003cu003e9_1516 = ParcelaRepository.u003cu003ec.u003cu003e9__15_16; + if (u003cu003e9_1516 == null) + { + u003cu003e9_1516 = (VendedorParcela tipo) => tipo.TipoVendedor.Id; + ParcelaRepository.u003cu003ec.u003cu003e9__15_16 = u003cu003e9_1516; + } + IOrderedEnumerable vendedorParcelas = vendedores.OrderBy(u003cu003e9_1516); + Func u003cu003e9_1517 = ParcelaRepository.u003cu003ec.u003cu003e9__15_17; + if (u003cu003e9_1517 == null) + { + u003cu003e9_1517 = (VendedorParcela v) => v.Vendedor; + ParcelaRepository.u003cu003ec.u003cu003e9__15_17 = u003cu003e9_1517; + } + List list = vendedorParcelas.Select(u003cu003e9_1517).ToList(); + p.Documento.Vendedores = list; + Documento documento = p.Documento; + VendedorParcela vendedorParcela = p.Vendedores.FirstOrDefault((VendedorParcela v) => { + long? nullable; + long id = v.Vendedor.Id; + Vendedor vendedorPrincipal = p.Documento.VendedorPrincipal; + nullable = (vendedorPrincipal != null ? new long?(vendedorPrincipal.Id) : null); + long? nullable1 = nullable; + return id == nullable1.GetValueOrDefault() & nullable1.HasValue; + }); + if (vendedorParcela != null) + { + porcentagemRepasse = vendedorParcela.PorcentagemRepasse; + } + else + { + nullable2 = null; + porcentagemRepasse = nullable2; + } + nullable2 = porcentagemRepasse; + documento.PercentualRepasse = new decimal?(nullable2.GetValueOrDefault()); + documentos.Add(p.Documento); + }); + parcelas = null; + } + sqlConnection = null; + } + sessionFactory = null; + List documentos1 = documentos; + sqlQueryCondition = null; + return documentos1; + } + + private async Task> BuscaDocumentosPorVigenciaPrivate(Filtros filtro, bool buscaAssinaturas = false, bool painelBi = false) + { + NegocioCorretora negocioCorretora; + List.Enumerator enumerator; + decimal? nullable; + DateTime? nullable1; + object connection; + bool count; + string str; + bool flag; + Seguradora seguradora; + Ramo ramo1; + Produto produto1; + bool flag1; + Negocio negocio; + DateTime? nullable2; + DateTime dateTime; + DateTime? nullable3; + DateTime? nullable4; + Estipulante estipulante1; + DateTime? nullable5; + Status statu; + bool flag2; + List statusDocumentoAssinados; + bool flag3; + StatusAssinatura statusAssinatura; + DateTime? nullable6; + decimal? porcentagemRepasse; + List list; + List nums; + NegocioCorretora negocioCorretora1; + bool count1; + Func func = null; + Func func1 = null; + Func func2 = null; + Func func3 = null; + Func func4 = null; + Func func5 = null; + List documentos = new List(); + string str1 = "CAST(f.vigenciai AS DATE)"; + string referencia = filtro.Referencia; + if (referencia == "EMISSÃO") + { + str1 = "CAST(f.emissao AS DATE)"; + } + else if (referencia == "TRANSMISSÃO PROPOSTA") + { + str1 = "CAST(d.remessa AS DATE)"; + } + else if (referencia == "DATA CRIAÇÃO" || referencia == "DATA DE CADASTRO") + { + str1 = "CAST(p.cri_data AS DATE)"; + } + List condicaos = this.CriaCondicaoDocumento(filtro, str1); + List condicaos1 = new List(); + Condicao condicao = new Condicao() + { + Campo = "d.Excluido", + Valores = null, + Grupo = 1, + Operacao = Operacao.Or + }; + condicaos1.Add(condicao); + Condicao condicao1 = new Condicao() + { + Campo = "d.Excluido", + Valores = "0".CriarValor(), + Grupo = 1, + Operacao = Operacao.Or + }; + condicaos1.Add(condicao1); + condicaos.AddRange(condicaos1); + SqlQueryCondition sqlQueryCondition = condicaos.CreateParameters(0); + using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) + { + SessionFactoryImpl sessionFactoryImpl = sessionFactory; + if (sessionFactoryImpl != null) + { + connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandTimeout = 0; + Auxiliar.CriarAuxiliar(sqlCommand, false); + bool flag4 = await this.ExisteTabelasAssinatura(); + bool flag5 = flag4; + List tipoVendedor = filtro.TipoVendedor; + if (tipoVendedor != null) + { + count = tipoVendedor.Count > 0; + } + else + { + count = false; + } + if (!count) + { + List vendedores = filtro.Vendedores; + if (vendedores != null) + { + count1 = vendedores.Count > 0; + } + else + { + count1 = false; + } + if (count1) + { + goto Label1; + } + str = ""; + goto Label0; + } + Label1: + str = "INNER JOIN vendedorparcela vp ON p.idparcela = vp.idparcela"; + Label0: + string str2 = string.Concat("SELECT DISTINCT c.IdEmpresa,c.IdCliente,cli.CGCCPF,cli.MalaDireta,cli.Nome,d.IdControle,p.IdParcela,d.IdDocumento,d.Contrato,f.NumFatura,f.Emissao,d.IdNegocio,d.Situacao,f.VigenciaI,f.VigenciaF,ISNULL(p.Valor, 0.00) Total,ISNULL(p.ValorLF, 0.00) Liquido,ISNULL(p.comiss, 0.00) Comissao,c.IdRamo,c.IdCiaSeg,c.IdProduto,d.IdEstipulante,d.NegocioCorretora,p.DataControle,d.IdStatus,p.Cri_Data,d.Remessa,d.IdBanco,cb.NomeBanco,d.Agencia,d.Conta,d.Pasta,d.ApoConferida,d.PropAssinada,cli.pasta PastaCliente FROM fatura f INNER JOIN parcela p ON p.IdParcela = f.IdParcela ", str, " INNER JOIN documento d ON d.IdDocumento = p.IdDocumento INNER JOIN controle c ON c.IdControle = d.IdControle INNER JOIN cliente cli ON cli.IdCliente = c.IdCliente LEFT JOIN codigobanco cb ON d.idbanco = cb.idcodigobanco WHERE "); + sqlCommand.CommandText = string.Concat(str2, " ", sqlQueryCondition.Condicao); + sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray()); + using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) + { + while (true) + { + if (!await sqlDataReader.ReadAsync()) + { + break; + } + long item = (long)sqlDataReader["idparcela"]; + long num = (long)sqlDataReader["iddocumento"]; + long item1 = (long)sqlDataReader["idcontrole"]; + long num1 = (long)sqlDataReader["idempresa"]; + string str3 = "PEDIDO DE ENDOSSO"; + if (!await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("negociocorretora"))) + { + negocioCorretora = (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), sqlDataReader["negociocorretora"].ToString()); + } + else + { + flag4 = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), sqlDataReader["situacao"].ToString()) == TipoSeguro.Renovacao; + if (flag4) + { + flag4 = !await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idnegocio")); + } + negocioCorretora1 = (!flag4 || !(sqlDataReader["idnegocio"].ToString() == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio); + negocioCorretora = negocioCorretora1; + } + NegocioCorretora negocioCorretora2 = negocioCorretora; + Vendedor vendedor = new Vendedor(); + List vendedors = new List(); + List items = new List(); + List statusDocumentoAssinados1 = new List(); + StatusDocumentoAssinado statusDocumentoAssinado = null; + decimal valueOrDefault = new decimal(); + if (filtro.Negocio == null || filtro.Negocio.Count <= 0 || filtro.Negocio.Any((long n) => (int)n == (int)negocioCorretora2)) + { + if (!painelBi) + { + List vendedorParcelas = await this.BuscaVendedoresPorIdParcela(item, num1, (long)1); + if (filtro.Vendedores != null && filtro.Vendedores.Count > 0) + { + bool flag6 = true; + foreach (long list1 in filtro.Vendedores.ToList()) + { + if (!vendedorParcelas.Any((VendedorParcela v) => v.Vendedor.Id == list1)) + { + continue; + } + flag6 = false; + } + if (flag6) + { + continue; + } + } + List vendedorParcelas1 = vendedorParcelas; + IOrderedEnumerable id = + from tipo in vendedorParcelas1 + orderby tipo.TipoVendedor.Id + select tipo; + vendedors = ( + from v in id + select v.Vendedor).ToList(); + if (filtro.TipoVendedor != null && filtro.TipoVendedor.Count != 0) + { + if (filtro.TipoVendedor != null) + { + List tipoVendedor1 = filtro.TipoVendedor; + if (tipoVendedor1.Any((long v) => v == (long)1)) + { + goto Label3; + } + } + Vendedor vendedor1 = null; + Filtros filtro1 = filtro; + if (filtro1 != null) + { + List nums1 = filtro1.TipoVendedor; + if (nums1 != null) + { + list = ( + from t in nums1 + orderby t + select t).ToList(); + } + else + { + list = null; + } + } + else + { + list = null; + } + enumerator = list.GetEnumerator(); + try + { + do + { + if (!enumerator.MoveNext()) + { + break; + } + long current = enumerator.Current; + Filtros filtro2 = filtro; + if (filtro2 != null) + { + List vendedores1 = filtro2.Vendedores; + if (vendedores1 != null) + { + nums = vendedores1.ToList(); + } + else + { + nums = null; + } + } + else + { + nums = null; + } + List.Enumerator enumerator1 = nums.GetEnumerator(); + try + { + do + { + if (!enumerator1.MoveNext()) + { + break; + } + long current1 = enumerator1.Current; + IEnumerable vendedorParcelas2 = vendedorParcelas.Where((VendedorParcela v) => { + if (v.TipoVendedor.Id != current) + { + return false; + } + return v.Vendedor.Id == current1; + }); + vendedor1 = ( + from v in vendedorParcelas2 + select v.Vendedor).FirstOrDefault(); + } + while (vendedor1 == null); + } + finally + { + ((IDisposable)enumerator1).Dispose(); + } + } + while (vendedor1 == null); + } + finally + { + ((IDisposable)enumerator).Dispose(); + } + if ((filtro.Vendedores == null || filtro.Vendedores.Count == 0) && vendedor1 == null) + { + List vendedorParcelas3 = vendedorParcelas; + Func func6 = func; + if (func6 == null) + { + Func id1 = (VendedorParcela v) => v.TipoVendedor.Id == filtro.TipoVendedor.FirstOrDefault(); + Func func7 = id1; + func = id1; + func6 = func7; + } + IEnumerable vendedorParcelas4 = vendedorParcelas3.Where(func6); + vendedor1 = ( + from v in vendedorParcelas4 + select v.Vendedor).FirstOrDefault(); + } + Vendedor vendedor2 = vendedor1; + if (vendedor2 == null) + { + vendedor2 = vendedors.FirstOrDefault(); + } + vendedor = vendedor2; + goto Label2; + } + List vendedorParcelas5 = vendedorParcelas; + IEnumerable id2 = + from v in vendedorParcelas5 + where v.TipoVendedor.Id == (long)1 + select v; + vendedor = ( + from v in id2 + select v.Vendedor).FirstOrDefault(); + Label2: + VendedorParcela vendedorParcela = vendedorParcelas.FirstOrDefault((VendedorParcela v) => v.Vendedor.Id == vendedor.Id); + if (vendedorParcela != null) + { + porcentagemRepasse = vendedorParcela.PorcentagemRepasse; + } + else + { + nullable = null; + porcentagemRepasse = nullable; + } + nullable = porcentagemRepasse; + valueOrDefault = nullable.GetValueOrDefault(); + if (flag5 & buscaAssinaturas) + { + statusDocumentoAssinados1 = await this.BuscaStatusAssinadosPorIdDocumento(num); + statusDocumentoAssinados1.ForEach((StatusDocumentoAssinado a) => { + if (a.Documento.ToUpper() == str3 || a.Documento.ToUpper().Contains(str3)) + { + a.Selecionado = true; + } + }); + List statusDocumentoAssinados2 = statusDocumentoAssinados1; + statusDocumentoAssinado = statusDocumentoAssinados2.FirstOrDefault((StatusDocumentoAssinado a) => a.Selecionado); + } + items = await this.BuscaItemsPorIdControle(item1); + } + List documentos1 = documentos; + Documento documento = new Documento() + { + Id = num + }; + Documento documento1 = documento; + Controle controle = new Controle() + { + Id = item1, + IdEmpresa = num1 + }; + Controle controle1 = controle; + Cliente cliente = new Cliente() + { + Id = (long)sqlDataReader["idcliente"], + Nome = sqlDataReader["nome"].ToString(), + Documento = sqlDataReader["cgccpf"].ToString(), + IdEmpresa = num1, + Pasta = sqlDataReader["pastacliente"].ToString() + }; + Cliente cliente1 = cliente; + flag4 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("maladireta")); + Cliente cliente2 = cliente1; + flag = (flag4 ? true : (bool)sqlDataReader["maladireta"]); + cliente2.MalaDireta = new bool?(flag); + controle1.Cliente = cliente; + Controle controle2 = controle; + bool flag7 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idciaseg")); + Controle controle3 = controle2; + if (flag7) + { + seguradora = null; + } + else + { + List seguradoras = Auxiliar.Seguradoras; + Func func8 = func1; + if (func8 == null) + { + Func id3 = (Seguradora seg) => seg.Id == (long)sqlDataReader["idciaseg"]; + Func func9 = id3; + func1 = id3; + func8 = func9; + } + seguradora = seguradoras.FirstOrDefault(func8); + } + controle3.Seguradora = seguradora; + Controle controle4 = controle; + bool flag8 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idramo")); + Controle controle5 = controle4; + if (flag8) + { + ramo1 = null; + } + else + { + List ramos = Auxiliar.Ramos; + Func func10 = func2; + if (func10 == null) + { + Func id4 = (Ramo ramo) => ramo.Id == (long)sqlDataReader["idramo"]; + Func func11 = id4; + func2 = id4; + func10 = func11; + } + ramo1 = ramos.FirstOrDefault(func10); + } + controle5.Ramo = ramo1; + Controle controle6 = controle; + bool flag9 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idproduto")); + Controle controle7 = controle6; + if (flag9) + { + produto1 = null; + } + else + { + List produtos = Auxiliar.Produtos; + Func func12 = func3; + if (func12 == null) + { + Func id5 = (Produto produto) => produto.Id == (long)sqlDataReader["idproduto"]; + Func func13 = id5; + func3 = id5; + func12 = func13; + } + produto1 = produtos.FirstOrDefault(func12); + } + controle7.Produto = produto1; + documento1.Controle = controle; + documento.TipoRecebimento = new TipoRecebimento?(TipoRecebimento.Fatura); + documento.AdicionalComiss = false; + documento.Apolice = sqlDataReader["contrato"].ToString(); + Documento documento2 = documento; + bool flag10 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("apoconferida")); + Documento documento3 = documento2; + flag1 = (flag10 ? false : sqlDataReader["apoconferida"].ToString() == "1"); + documento3.ApoliceConferida = flag1; + documento.Endosso = string.Format("F {0}", sqlDataReader["numfatura"]); + documento.Comissao = (decimal)sqlDataReader["comissao"]; + Documento documento4 = documento; + bool flag11 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idnegocio")); + Documento documento5 = documento4; + negocio = (flag11 ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), sqlDataReader["idnegocio"].ToString())); + documento5.Negocio = new Negocio?(negocio); + documento.PremioLiquido = (decimal)sqlDataReader["liquido"]; + documento.PremioTotal = (decimal)sqlDataReader["total"]; + documento.NumeroParcelas = decimal.One; + Documento documento6 = documento; + bool flag12 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("vigenciaf")); + Documento documento7 = documento6; + if (flag12) + { + nullable1 = null; + nullable2 = nullable1; + } + else + { + nullable2 = new DateTime?((DateTime)sqlDataReader["vigenciaf"]); + } + documento7.Vigencia2 = nullable2; + Documento documento8 = documento; + bool flag13 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("vigenciai")); + Documento documento9 = documento8; + dateTime = (flag13 ? DateTime.MinValue : (DateTime)sqlDataReader["vigenciai"]); + documento9.Vigencia1 = dateTime; + Documento documento10 = documento; + bool flag14 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("emissao")); + Documento documento11 = documento10; + if (flag14) + { + nullable1 = null; + nullable3 = nullable1; + } + else + { + nullable3 = new DateTime?((DateTime)sqlDataReader["emissao"]); + } + documento11.Emissao = nullable3; + Documento documento12 = documento; + bool flag15 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("remessa")); + Documento documento13 = documento12; + if (flag15) + { + nullable1 = null; + nullable4 = nullable1; + } + else + { + nullable4 = new DateTime?((DateTime)sqlDataReader["remessa"]); + } + documento13.Remessa = nullable4; + documento.PercentualRepasse = new decimal?(valueOrDefault); + Documento documento14 = documento; + bool flag16 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idestipulante")); + Documento documento15 = documento14; + if (flag16) + { + estipulante1 = null; + } + else + { + List estipulantes = Auxiliar.Estipulantes; + Func func14 = func4; + if (func14 == null) + { + Func id6 = (Estipulante estipulante) => estipulante.Id == (long)sqlDataReader["idestipulante"]; + Func func15 = id6; + func4 = id6; + func14 = func15; + } + estipulante1 = estipulantes.FirstOrDefault(func14); + } + documento15.Estipulante1 = estipulante1; + documento.NegocioCorretora = new NegocioCorretora?(negocioCorretora2); + documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), sqlDataReader["situacao"].ToString()); + documento.Tipo = 2; + Documento documento16 = documento; + bool flag17 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("datacontrole")); + Documento documento17 = documento16; + if (flag17) + { + nullable1 = null; + nullable5 = nullable1; + } + else + { + nullable5 = new DateTime?((DateTime)sqlDataReader["datacontrole"]); + } + documento17.DataControle = nullable5; + Documento documento18 = documento; + bool flag18 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idstatus")); + Documento documento19 = documento18; + if (flag18) + { + statu = null; + } + else + { + List statusApolice = Auxiliar.StatusApolice; + Func func16 = func5; + if (func16 == null) + { + Func id7 = (Status status) => status.Id == (long)sqlDataReader["idstatus"]; + Func func17 = id7; + func5 = id7; + func16 = func17; + } + statu = statusApolice.FirstOrDefault(func16); + } + documento19.Status = statu; + documento.ItensAtivo = items; + Documento documento20 = documento; + bool flag19 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("propassinada")); + Documento documento21 = documento20; + flag2 = (flag19 ? false : sqlDataReader["propassinada"].ToString() == "1"); + documento21.PropostaAssinada = flag2; + documento.VendedorPrincipal = vendedor; + documento.Vendedores = vendedors; + Documento documento22 = documento; + if (statusDocumentoAssinados1.Count == 0) + { + statusDocumentoAssinados = null; + } + else + { + statusDocumentoAssinados = statusDocumentoAssinados1; + } + documento22.Assinaturas = statusDocumentoAssinados; + Documento documento23 = documento; + StatusDocumentoAssinado statusDocumentoAssinado1 = statusDocumentoAssinado; + if (statusDocumentoAssinado1 != null) + { + flag3 = statusDocumentoAssinado1.Status == StatusAssinatura.Assinado; + } + else + { + flag3 = false; + } + documento23.AssinadaSiggner = flag3; + Documento documento24 = documento; + StatusDocumentoAssinado statusDocumentoAssinado2 = statusDocumentoAssinado; + if (statusDocumentoAssinado2 != null) + { + statusAssinatura = statusDocumentoAssinado2.Status; + } + else + { + statusAssinatura = StatusAssinatura.NaoEnviado; + } + documento24.StatusAssinatura = statusAssinatura; + documento.Pasta = sqlDataReader["pasta"].ToString(); + Documento documento25 = documento; + bool flag20 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("cri_data")); + Documento documento26 = documento25; + if (flag20) + { + nullable1 = null; + nullable6 = nullable1; + } + else + { + nullable6 = new DateTime?((DateTime)sqlDataReader["cri_data"]); + } + documento26.DataCriacao = nullable6; + Documento documento27 = documento; + Banco banco = new Banco() + { + Nome = sqlDataReader["nomebanco"].ToString() + }; + documento27.Banco = banco; + documento.Agencia = sqlDataReader["agencia"].ToString(); + documento.Conta = sqlDataReader["conta"].ToString(); + documentos1.Add(documento); + documentos1 = null; + documento1 = null; + controle1 = null; + cliente1 = null; + cliente = null; + controle2 = null; + controle4 = null; + controle6 = null; + controle = null; + documento2 = null; + documento4 = null; + documento6 = null; + documento8 = null; + documento10 = null; + documento12 = null; + documento14 = null; + documento16 = null; + documento18 = null; + documento20 = null; + documento25 = null; + documento = null; + vendedors = null; + items = null; + statusDocumentoAssinados1 = null; + statusDocumentoAssinado = null; + } + } + } + } + sqlCommand = null; + } + sqlConnection = null; + } + sessionFactory = null; + List documentos2 = documentos; + documentos = null; + sqlQueryCondition = null; + return documentos2; + } + + private async Task> BuscaItemsPorIdControle(long idControle) + { + object connection; + List items = new List(); + using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) + { + SessionFactoryImpl sessionFactoryImpl = sessionFactory; + if (sessionFactoryImpl != null) + { + connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandTimeout = 1000; + sqlCommand.CommandText = "SELECT i.iditem,i.descricao FROM item i INNER JOIN documento d ON d.iddocumento = i.iddocumento WHERE d.idcontrole = @controle AND i.idsubstituido IS NULL AND (i.cancelado IS NULL OR i.cancelado = 0)"; + sqlCommand.Parameters.Add("@controle", SqlDbType.BigInt).Value = idControle; + using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) + { + while (true) + { + if (!await sqlDataReader.ReadAsync()) + { + break; + } + List items1 = items; + Item item = new Item() + { + Id = sqlDataReader.GetFieldValue("iditem", true, true), + Descricao = sqlDataReader.GetFieldValue("descricao", true, true) + }; + items1.Add(item); + } + } + sqlDataReader = null; + } + sqlCommand = null; + } + sqlConnection = null; + } + sessionFactory = null; + List items2 = items; + items = null; + return items2; + } + + private async Task> BuscaItemsPorIdControle(SqlConnection connection, long idControle) + { + List items = new List(); + using (SqlCommand sqlCommand = connection.CreateCommand()) + { + sqlCommand.CommandTimeout = 1000; + sqlCommand.CommandText = "SELECT i.iditem,i.descricao FROM item i INNER JOIN documento d ON d.iddocumento = i.iddocumento WHERE d.idcontrole = @controle AND i.idsubstituido IS NULL AND (i.cancelado IS NULL OR i.cancelado = 0)"; + sqlCommand.Parameters.Add("@controle", SqlDbType.BigInt).Value = idControle; + using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) + { + while (true) + { + if (!await sqlDataReader.ReadAsync()) + { + break; + } + List items1 = items; + Item item = new Item() + { + Id = (long)sqlDataReader["iditem"], + Descricao = sqlDataReader["descricao"].ToString() + }; + items1.Add(item); + } + } + sqlDataReader = null; + } + sqlCommand = null; + List items2 = items; + items = null; + return items2; + } + + public Documento BuscarApolice(long id) + { + DocumentoDb documento; + ParcelaDb parcelaDb = base.All().FirstOrDefault((ParcelaDb x) => x.Id == id); + if (parcelaDb != null) + { + documento = parcelaDb.Documento; + } + else + { + documento = null; + } + return ApplicationMapper.Mapper.Map(documento); + } + + public string BuscarLogAntigo(long id, string conn) + { + object connection; + string str = ""; + List condicaos = new List() + { + new Condicao() + { + Campo = "id", + Valores = id.CriarValor() + }, + new Condicao() + { + Campo = "idname", + Valores = "IDParcela".CriarValor() + } + }; + this._unitOfWork.CriarAuxiliar(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + string str1 = "oldbacklog"; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = "SELECT TOP 1 * FROM controlelog"; + SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); + sqlDataReader.Read(); + string str2 = sqlDataReader["bdname"].ToString(); + str1 = sqlDataReader["tabela"].ToString(); + sqlDataReader.Close(); + if (sqlConnection.Database != str2) + { + conn = conn.Replace(sqlConnection.Database, str2); + } + } + } + DataTable dataTable = new DataTable(); + using (SqlConnection sqlConnection1 = new SqlConnection(conn)) + { + sqlConnection1.Open(); + using (SqlCommand sqlCommand1 = sqlConnection1.CreateCommand()) + { + sqlCommand1.CommandTimeout = 15000; + dataTable = sqlCommand1.Select(condicaos.CreateParameters(0), string.Concat("SELECT b.* FROM ", str1, " b WHERE"), ""); + } + } + if (dataTable == null || dataTable.Rows.Count == 0) + { + return ""; + } + if (dataTable != null) + { + dataTable.AsEnumerable().OrderBy((DataRow x) => x.Field("idbacklog")).ToList().ForEach((DataRow x) => { + str = string.Concat(new string[] { str, "
(", x.Field("data").ToString(), ") ", Auxiliar.Usuarios.Find((Usuario u) => u.Id == x.Field("idusuario")).Nome, "
" }); + str = string.Concat(str, "", x.Field("historico").ToString().Replace(Environment.NewLine, "
"), ""); + }); + } + return str; + } + + public ParcelaPendente BuscarPendencia(long id) + { + ParcelaPendente parcelaPendente; + object connection; + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + try + { + sqlCommand.CommandText = string.Format("SELECT * FROM parcelapendente WHERE idparcelapendente = {0}", id); + SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); + if (sqlDataReader.HasRows) + { + sqlDataReader.Read(); + parcelaPendente = new ParcelaPendente() + { + Id = (long)sqlDataReader["idparcelapendente"], + IdParcela = (long)sqlDataReader["idparcela"], + Seguradora = (string)sqlDataReader["seguradora"], + Cliente = (string)sqlDataReader["cliente"], + Apolice = (string)sqlDataReader["apolice"], + Parcela = (int)sqlDataReader["parcela"], + Valor = decimal.Parse(sqlDataReader["valor"].ToString()), + Vencimento = DateTime.Parse(sqlDataReader["vencto"].ToString()) + }; + } + else + { + parcelaPendente = null; + } + } + catch (Exception exception) + { + parcelaPendente = null; + } + } + } + return parcelaPendente; + } + + private async Task> BuscaStatusAssinadosPorIdDocumento(long idDocumento) + { + object connection; + DateTime? nullable; + Usuario usuario1; + Func func = null; + List statusDocumentoAssinados = new List(); + using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) + { + SessionFactoryImpl sessionFactoryImpl = sessionFactory; + if (sessionFactoryImpl != null) + { + connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandTimeout = 1000; + sqlCommand.CommandText = "SELECT a.idnewarquivodigital,a.descricao,ISNULL(s.Status ,3) status,s.assinado,a.iddocumento,s.id,s.usuarioid,s.enviado FROM newarquivodigital a LEFT JOIN ArquivoParaAssinatura s ON a.idnewarquivodigital = s.indiceid WHERE a.iddocumento = @documento AND (a.excluido = 0 OR a.excluido IS NULL)"; + sqlCommand.Parameters.Add("@documento", SqlDbType.BigInt).Value = idDocumento; + using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) + { + while (true) + { + if (!await sqlDataReader.ReadAsync()) + { + break; + } + List statusDocumentoAssinados1 = statusDocumentoAssinados; + StatusDocumentoAssinado statusDocumentoAssinado = new StatusDocumentoAssinado() + { + Id = (long)sqlDataReader["idnewarquivodigital"], + Documento = sqlDataReader["descricao"].ToString(), + Status = (StatusAssinatura)((int)sqlDataReader["status"]) + }; + StatusDocumentoAssinado statusDocumentoAssinado1 = statusDocumentoAssinado; + bool flag = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("enviado")); + StatusDocumentoAssinado statusDocumentoAssinado2 = statusDocumentoAssinado1; + if (flag) + { + nullable = null; + } + else + { + nullable = new DateTime?((DateTime)sqlDataReader["enviado"]); + } + statusDocumentoAssinado2.Envio = nullable; + StatusDocumentoAssinado statusDocumentoAssinado3 = statusDocumentoAssinado; + bool flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("usuarioid")); + StatusDocumentoAssinado statusDocumentoAssinado4 = statusDocumentoAssinado3; + if (flag1) + { + usuario1 = null; + } + else + { + List usuarios = Auxiliar.Usuarios; + Func func1 = func; + if (func1 == null) + { + Func id = (Usuario usuario) => usuario.Id == (long)sqlDataReader["usuarioid"]; + Func func2 = id; + func = id; + func1 = func2; + } + usuario1 = usuarios.FirstOrDefault(func1); + } + statusDocumentoAssinado4.Usuario = usuario1; + statusDocumentoAssinados1.Add(statusDocumentoAssinado); + statusDocumentoAssinados1 = null; + statusDocumentoAssinado1 = null; + statusDocumentoAssinado3 = null; + statusDocumentoAssinado = null; + } + } + } + sqlCommand = null; + } + sqlConnection = null; + } + sessionFactory = null; + List statusDocumentoAssinados2 = statusDocumentoAssinados; + statusDocumentoAssinados = null; + return statusDocumentoAssinados2; + } + + private async Task> BuscaVendedoresPorIdParcela(long idParcela, long idEmpresa = 0L, long idSubTipo = 0L) + { + object connection; + string str; + string str1; + List vendedorParcelas = new List(); + using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) + { + SessionFactoryImpl sessionFactoryImpl = sessionFactory; + if (sessionFactoryImpl != null) + { + connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + str = (idSubTipo > (long)0 ? " INNER JOIN parcela p ON p.idparcela = vp.idparcela " : string.Empty); + string str2 = str; + str1 = (idSubTipo > (long)0 ? " AND p.idsubtipo = @subtipo " : string.Empty); + string str3 = string.Concat("SELECT DISTINCT vp.idvendedor,v.nome nomevendedor,vp.vrep,vp.vlrrep,vp.dataprepagto,vp.datapgt,vp.idtipovendedor FROM vendedorparcela vp INNER JOIN vendedor v ON v.idvendedor = vp.idvendedor ", str2, " WHERE vp.idparcela = @parcela ", str1); + sqlCommand.CommandTimeout = 1000; + sqlCommand.CommandText = str3; + sqlCommand.Parameters.Add("@parcela", SqlDbType.BigInt).Value = idParcela; + sqlCommand.Parameters.Add("@subtipo", SqlDbType.BigInt).Value = idSubTipo; + using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) + { + while (true) + { + if (!await sqlDataReader.ReadAsync()) + { + break; + } + List vendedorParcelas1 = vendedorParcelas; + VendedorParcela vendedorParcela = new VendedorParcela(); + TipoVendedor tipoVendedor = new TipoVendedor() + { + Id = sqlDataReader.GetFieldValue("idtipovendedor", true, true) + }; + vendedorParcela.TipoVendedor = tipoVendedor; + Vendedor vendedor = new Vendedor() + { + Id = sqlDataReader.GetFieldValue("idvendedor", true, true), + Nome = sqlDataReader.GetFieldValue("nomevendedor", true, true) + }; + vendedorParcela.Vendedor = vendedor; + vendedorParcela.PorcentagemRepasse = sqlDataReader.GetFieldValue("vrep", true, true); + vendedorParcela.ValorRepasse = sqlDataReader.GetFieldValue("vlrrep", true, true); + vendedorParcela.DataPagamento = sqlDataReader.GetFieldValue("datapgt", true, true); + vendedorParcela.DataPrePagamento = sqlDataReader.GetFieldValue("dataprepagto", true, true); + vendedorParcelas1.Add(vendedorParcela); + } + if (idEmpresa > (long)0) + { + List vendedorParcelas2 = vendedorParcelas; + if (!vendedorParcelas2.Any((VendedorParcela v) => v.TipoVendedor.Id == (long)1)) + { + List vendedorParcelas3 = vendedorParcelas; + VendedorParcela vendedorParcela1 = new VendedorParcela() + { + TipoVendedor = new TipoVendedor() + { + Id = (long)1 + }, + Vendedor = Auxiliar.Vendedores.FirstOrDefault((Vendedor v) => { + if (v.IdEmpresa != idEmpresa) + { + return false; + } + return v.Corretora; + }), + PorcentagemRepasse = new decimal?(new decimal()) + }; + vendedorParcelas3.Add(vendedorParcela1); + } + } + } + sqlDataReader = null; + } + sqlCommand = null; + } + sqlConnection = null; + } + sessionFactory = null; + List vendedorParcelas4 = vendedorParcelas; + List list = ( + from v in vendedorParcelas4 + orderby v.TipoVendedor.Id + select v).ToList(); + vendedorParcelas = null; + return list; + } + + private List CriaCondicaoDocumento(Filtros filtro, string referencia) + { + bool count; + bool flag; + bool count1; + bool flag1; + bool count2; + bool flag2; + bool count3; + bool flag3; + List condicaos = new List() + { + new Condicao() + { + Campo = referencia, + Valores = filtro.Inicio.CriarValor(), + Operador = Operador.MaiorEIgual + }, + new Condicao() + { + Campo = referencia, + Valores = filtro.Fim.CriarValor(), + Operador = Operador.MenorEIgual + } + }; + List seguradoras = filtro.Seguradoras; + if (seguradoras != null) + { + count = seguradoras.Count > 0; + } + else + { + count = false; + } + if (count) + { + condicaos.Add(new Condicao() + { + Campo = "c.idciaseg", + Valores = filtro.Seguradoras.CriarValor(), + Grupo = 5 + }); + } + List ramos = filtro.Ramos; + if (ramos != null) + { + flag = ramos.Count > 0; + } + else + { + flag = false; + } + if (flag) + { + condicaos.Add(new Condicao() + { + Campo = "c.idramo", + Valores = filtro.Ramos.CriarValor(), + Grupo = 5 + }); + } + List status = filtro.Status; + if (status != null) + { + count1 = status.Count > 0; + } + else + { + count1 = false; + } + if (count1) + { + condicaos.Add(new Condicao() + { + Campo = "d.situacao", + Valores = filtro.Status.CriarValor(), + Grupo = 5 + }); + } + List tipoVendedor = filtro.TipoVendedor; + if (tipoVendedor != null) + { + flag1 = tipoVendedor.Count > 0; + } + else + { + flag1 = false; + } + if (flag1) + { + condicaos.Add(new Condicao() + { + Campo = "vp.idtipovendedor", + Valores = filtro.TipoVendedor.CriarValor(), + Grupo = 5 + }); + } + List vendedores = filtro.Vendedores; + if (vendedores != null) + { + count2 = vendedores.Count > 0; + } + else + { + count2 = false; + } + if (count2) + { + condicaos.Add(new Condicao() + { + Campo = "vp.idvendedor", + Valores = filtro.Vendedores.CriarValor(), + Grupo = 5, + Operacao = Operacao.Or + }); + } + List estipulantes = filtro.Estipulantes; + if (estipulantes != null) + { + flag2 = estipulantes.Count > 0; + } + else + { + flag2 = false; + } + if (flag2) + { + condicaos.Add(new Condicao() + { + Campo = "d.idestipulante", + Valores = filtro.Estipulantes.CriarValor(), + Grupo = 5 + }); + } + List produtos = filtro.Produtos; + if (produtos != null) + { + count3 = produtos.Count > 0; + } + else + { + count3 = false; + } + if (count3) + { + condicaos.Add(new Condicao() + { + Campo = "c.idproduto", + Valores = filtro.Produtos.CriarValor(), + Grupo = 5 + }); + } + List negocio = filtro.Negocio; + if (negocio != null) + { + flag3 = negocio.Count > 0; + } + else + { + flag3 = false; + } + if (flag3) + { + condicaos.Add(new Condicao() + { + Campo = "d.NegocioCorretora", + Valores = filtro.Negocio.CriarValor(), + Operacao = Operacao.Or, + Grupo = 6 + }); + condicaos.Add(new Condicao() + { + Campo = "d.NegocioCorretora", + Valores = null, + Operacao = Operacao.Or, + Grupo = 6 + }); + } + if (filtro.IdEmpresa > (long)0) + { + condicaos.Add(new Condicao() + { + Campo = "c.idempresa", + Valores = filtro.IdEmpresa.CriarValor(), + Grupo = 5 + }); + } + return condicaos; + } + + private List CriaCondicaoFaturaPendente(Filtros filtro, string referencia) + { + return new List() + { + new Condicao() + { + Campo = referencia, + Valores = filtro.Inicio.CriarValor(), + Operador = Operador.MenorEIgual + }, + new Condicao() + { + Campo = referencia, + Valores = filtro.Fim.CriarValor(), + Operador = Operador.MaiorEIgual + } + }; + } + + private List CriaCondicaoFaturaPendenteVigencia(Filtros filtro, string referencia, string referencia2) + { + bool count; + bool flag; + bool count1; + bool flag1; + bool count2; + bool flag2; + bool count3; + bool flag3; + List condicaos = new List() + { + new Condicao() + { + Campo = referencia, + Valores = filtro.Fim.CriarValor(), + Operador = Operador.MenorEIgual + }, + new Condicao() + { + Campo = referencia2, + Valores = filtro.Inicio.CriarValor(), + Grupo = 1, + Operador = Operador.MaiorEIgual, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = referencia2, + Valores = null, + Grupo = 1 + } + }; + List seguradoras = filtro.Seguradoras; + if (seguradoras != null) + { + count = seguradoras.Count > 0; + } + else + { + count = false; + } + if (count) + { + condicaos.Add(new Condicao() + { + Campo = "c.idciaseg", + Valores = filtro.Seguradoras.CriarValor(), + Grupo = 5 + }); + } + List ramos = filtro.Ramos; + if (ramos != null) + { + flag = ramos.Count > 0; + } + else + { + flag = false; + } + if (flag) + { + condicaos.Add(new Condicao() + { + Campo = "c.idramo", + Valores = filtro.Ramos.CriarValor(), + Grupo = 5 + }); + } + List status = filtro.Status; + if (status != null) + { + count1 = status.Count > 0; + } + else + { + count1 = false; + } + if (count1) + { + condicaos.Add(new Condicao() + { + Campo = "d.situacao", + Valores = filtro.Status.CriarValor(), + Grupo = 5 + }); + } + List tipoVendedor = filtro.TipoVendedor; + if (tipoVendedor != null) + { + flag1 = tipoVendedor.Count > 0; + } + else + { + flag1 = false; + } + if (flag1) + { + condicaos.Add(new Condicao() + { + Campo = "vp.idtipovendedor", + Valores = filtro.TipoVendedor.CriarValor(), + Grupo = 5 + }); + } + List vendedores = filtro.Vendedores; + if (vendedores != null) + { + count2 = vendedores.Count > 0; + } + else + { + count2 = false; + } + if (count2) + { + condicaos.Add(new Condicao() + { + Campo = "vp.idvendedor", + Valores = filtro.Vendedores.CriarValor(), + Grupo = 5, + Operacao = Operacao.Or + }); + } + List estipulantes = filtro.Estipulantes; + if (estipulantes != null) + { + flag2 = estipulantes.Count > 0; + } + else + { + flag2 = false; + } + if (flag2) + { + condicaos.Add(new Condicao() + { + Campo = "d.idestipulante", + Valores = filtro.Estipulantes.CriarValor(), + Grupo = 5 + }); + } + List produtos = filtro.Produtos; + if (produtos != null) + { + count3 = produtos.Count > 0; + } + else + { + count3 = false; + } + if (count3) + { + condicaos.Add(new Condicao() + { + Campo = "c.idproduto", + Valores = filtro.Produtos.CriarValor(), + Grupo = 5 + }); + } + List negocio = filtro.Negocio; + if (negocio != null) + { + flag3 = negocio.Count > 0; + } + else + { + flag3 = false; + } + if (flag3) + { + condicaos.Add(new Condicao() + { + Campo = "d.NegocioCorretora", + Valores = filtro.Negocio.CriarValor(), + Operacao = Operacao.Or, + Grupo = 5 + }); + condicaos.Add(new Condicao() + { + Campo = "d.NegocioCorretora", + Valores = null, + Operacao = Operacao.Or, + Grupo = 5 + }); + } + if (filtro.IdEmpresa > (long)0) + { + condicaos.Add(new Condicao() + { + Campo = "c.idempresa", + Valores = filtro.IdEmpresa.CriarValor(), + Grupo = 5 + }); + } + return condicaos; + } + + private List CriarCondicaoFatura(Filtros filtro, string referencia) + { + bool count; + List condicaos = new List() + { + new Condicao() + { + Campo = "d.Excluido", + Valores = null, + Grupo = 1, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "d.Excluido", + Valores = "0".CriarValor(), + Grupo = 1, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "d.tiporecebimento", + Valores = 2.CriarValor() + } + }; + Condicao condicao = new Condicao() + { + Campo = referencia + }; + DateTime inicio = filtro.Inicio; + condicao.Valores = inicio.ToString("yyyy-MM-dd").CriarValor(); + condicao.Operador = Operador.MaiorEIgual; + condicaos.Add(condicao); + Condicao condicao1 = new Condicao() + { + Campo = referencia + }; + inicio = filtro.Fim; + condicao1.Valores = inicio.ToString("yyyy-MM-dd").CriarValor(); + condicao1.Operador = Operador.MenorEIgual; + condicaos.Add(condicao1); + condicaos.Add(new Condicao() + { + Campo = "p.valorr", + Valores = 0.CriarValor() + }); + condicaos.Add(new Condicao() + { + Campo = "p.datarec", + Valores = null + }); + List condicaos1 = condicaos; + if (filtro.Status.Count > 0) + { + condicaos1.Add(new Condicao() + { + Campo = "situacao", + Valores = filtro.Status.CriarValor() + }); + } + if (filtro.Negocio.Count > 0) + { + condicaos1.Add(new Condicao() + { + Campo = "negociocorretora", + Valores = filtro.Negocio.CriarValor() + }); + } + if (filtro.Seguradoras.Count > 0) + { + condicaos1.Add(new Condicao() + { + Campo = "c.idciaseg", + Valores = filtro.Seguradoras.CriarValor() + }); + } + if (filtro.Ramos.Count > 0) + { + condicaos1.Add(new Condicao() + { + Campo = "c.idramo", + Valores = filtro.Ramos.CriarValor() + }); + } + if (filtro.Produtos.Count > 0) + { + condicaos1.Add(new Condicao() + { + Campo = "c.idproduto", + Valores = filtro.Produtos.CriarValor() + }); + } + if (filtro.Vendedores.Count > 0) + { + condicaos1.Add(new Condicao() + { + Campo = "vp.idvendedor", + Valores = filtro.Vendedores.CriarValor(), + Grupo = 2, + Operacao = Operacao.Or + }); + condicaos1.Add(new Condicao() + { + Campo = "vp.idvendedor", + Valores = null, + Operacao = Operacao.Or, + Grupo = 2 + }); + } + if (filtro.Estipulantes.Count > 0) + { + condicaos1.Add(new Condicao() + { + Campo = "d.idestipulante", + Valores = filtro.Estipulantes.CriarValor() + }); + } + if (filtro.IdEmpresa > (long)0) + { + condicaos1.Add(new Condicao() + { + Campo = "c.idempresa", + Valores = filtro.IdEmpresa.CriarValor() + }); + } + List tipoVendedor = filtro.TipoVendedor; + if (tipoVendedor != null) + { + count = tipoVendedor.Count > 0; + } + else + { + count = false; + } + if (count) + { + condicaos1.Add(new Condicao() + { + Campo = "vp.idtipovendedor", + Valores = filtro.TipoVendedor.CriarValor() + }); + } + return condicaos1; + } + + public void Delete(long id) + { + List list = ( + from x in this._unitOfWork.Query() + where x.Parcela.Id == id + select x).ToList(); + if (list.Any()) + { + this._unitOfWork.Repository().DeleteRange(list); + } + ParcelaDb parcelaDb = base.FindEntityById(id); + if (parcelaDb == null) + { + return; + } + base.Delete(parcelaDb); + } + + public void DeleteRange(long id) + { + List list = ( + from x in this._unitOfWork.Query() + where x.Parcela.Documento.Id == id + select x).ToList(); + if (list.Any()) + { + this._unitOfWork.Repository().DeleteRange(list); + } + List parcelaDbs = ( + from i in base.All() + where i.Documento.Id == id && (int)i.SubTipo == 1 + select i).ToList(); + base.DeleteRange(parcelaDbs); + } + + public bool ExcluirVinculoParcelaPendenteDocExcluido(Documento doc) + { + object connection; + try + { + List parcelas = this.FindByDocumento(doc); + if (parcelas != null && parcelas.Count > 0) + { + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + parcelas.ForEach((Parcela p) => { + using (SqlCommand id = sqlConnection.CreateCommand()) + { + id.CommandText = "UPDATE ParcelaPendente SET IdParcela = NULL WHERE IdParcela = @parcela"; + id.Parameters.Add("@parcela", SqlDbType.BigInt).Value = p.Id; + id.ExecuteNonQuery(); + } + }); + } + return true; + } + } + catch + { + } + return false; + } + + private async Task ExisteTabelasAssinatura() + { + bool flag; + object connection; + using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) + { + SessionFactoryImpl sessionFactoryImpl = sessionFactory; + if (sessionFactoryImpl != null) + { + connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = "SELECT OBJECT_ID('ArquivoParaAssinatura') AS existe"; + flag = await sqlCommand.ExecuteScalarAsync() != DBNull.Value; + } + } + } + return flag; + } + + public async Task> FaturaPendente(Filtros filtro) + { + List documentos; + NegocioCorretora fieldValue; + object connection; + bool count; + List itensAtivo; + DateTime dateTime; + DateTime dateTime1; + DateTime dateTime2; + DateTime dateTime3; + object produto; + string str; + Vendedor vendedor; + Estipulante estipulante; + object statu; + NegocioCorretora negocioCorretora; + Func func = null; + Func func1 = null; + string str1 = "f.vigenciai"; + string str2 = "d.vigencia1"; + string str3 = "d.vigencia2"; + if (filtro.Referencia == "VENCIMENTO") + { + str1 = "p.vencto"; + } + List condicaos = this.CriaCondicaoFaturaPendenteVigencia(filtro, str2, str3); + List condicaos1 = this.CriaCondicaoFaturaPendente(filtro, str1); + List condicaos2 = new List(); + Condicao condicao = new Condicao() + { + Campo = "d.tiporecebimento", + Valores = 2.CriarValor(), + Grupo = 2 + }; + condicaos2.Add(condicao); + List condicaos3 = condicaos2; + List condicaos4 = new List(); + Condicao condicao1 = new Condicao() + { + Campo = "d.Excluido", + Valores = null, + Grupo = 4, + Operacao = Operacao.Or + }; + condicaos4.Add(condicao1); + Condicao condicao2 = new Condicao() + { + Campo = "d.Excluido", + Valores = "0".CriarValor(), + Grupo = 4 + }; + condicaos4.Add(condicao2); + List condicaos5 = condicaos4; + List condicaos6 = new List(); + Condicao condicao3 = new Condicao() + { + Campo = "d.situacao", + Valores = 1.CriarValor(), + Grupo = 3, + Operacao = Operacao.Or + }; + condicaos6.Add(condicao3); + Condicao condicao4 = new Condicao() + { + Campo = "d.situacao", + Valores = 2.CriarValor(), + Grupo = 3 + }; + condicaos6.Add(condicao4); + List condicaos7 = condicaos6; + condicaos.AddRange(condicaos3); + condicaos.AddRange(condicaos7); + condicaos.AddRange(condicaos5); + SqlQueryCondition sqlQueryCondition = condicaos.CreateParameters(0); + SqlQueryCondition sqlQueryCondition1 = condicaos1.CreateParameters(0); + List documentos1 = new List(); + using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) + { + SessionFactoryImpl sessionFactoryImpl = sessionFactory; + if (sessionFactoryImpl != null) + { + connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandTimeout = 1000; + string str4 = "WITH tabfatura AS ( SELECT MAX ( f.vigenciaf ) AS vigenciaf, MAX ( f.vigenciai ) AS vigenciai, MAX ( p.idparcela ) AS idparcela, MAX ( p.vencto ) AS Vencimento, MAX (f.idfatura) as idfatura, d.iddocumento FROM documento d LEFT JOIN parcela p ON p.iddocumento = d.iddocumento LEFT JOIN fatura f ON p.idparcela = f.idparcela GROUP BY d.iddocumento ) SELECT DISTINCT d.iddocumento, d.idcontrole, IIF ( d.vigencia2 IS NULL, GETDATE(), d.vigencia2 ) AS vigenciafinalfatura, tabfatura.idparcela,tabfatura.vigenciai AS vigenciaIultimafatura, tabfatura.vigenciaf AS vigenciafultimafatura, f.numfatura,tabfatura.Vencimento, cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome AS cliente, d.contrato AS apolice, d.emissao, d.remessa, d.aditamento AS endosso, d.idnegocio, d.situacao, d.negociocorretora, d.vigencia1 AS vigenciainicial, d.vigencia2 AS vigenciafinal, c.idramo, r.nome AS nomeramo, c.idciaseg AS idseguradora, cs.nome AS nomeseguradora, c.idproduto, pr.nome AS nomeproduto, CAST ( d.tipo AS INTEGER ) AS tipo, vp.idvendedor, d.idestipulante, d.datacontrole, d.idstatus, st.nome AS nomestatus, d.pasta, cl.pasta AS pastacliente FROM documento d INNER JOIN controle c ON c.idcontrole = d.idcontrole INNER JOIN ciaseg cs ON cs.idciaseg = c.idciaseg INNER JOIN ramo r ON r.idramo = c.idramo INNER JOIN cliente cl ON cl.idcliente = c.idcliente LEFT JOIN produto pr ON pr.idproduto = c.idproduto LEFT JOIN status st ON st.idstatus = d.idstatus LEFT JOIN parcela p ON p.iddocumento = d.iddocumento \tLEFT JOIN vendedorparcela vp ON vp.idparcela = p.idparcela LEFT JOIN tabfatura ON tabfatura.iddocumento = d.iddocumento LEFT JOIN fatura f on tabfatura.idfatura = f.idfatura WHERE"; + string str5 = " AND NOT EXISTS ( SELECT 1 FROM parcela p INNER JOIN fatura f ON f.idparcela = p.idparcela WHERE p.iddocumento = d.iddocumento AND "; + SqlCommand sqlCommand1 = sqlCommand; + string[] strArrays = new string[] { str4, " ", sqlQueryCondition.Condicao, " ", str5, " ", sqlQueryCondition1.Condicao, " ) ORDER BY d.IDDOCUMENTO" }; + sqlCommand1.CommandText = string.Concat(strArrays); + foreach (SqlParameter parametro in sqlQueryCondition.Parametros) + { + if (sqlCommand.Parameters.Contains(parametro.ParameterName)) + { + continue; + } + sqlCommand.Parameters.Add(parametro); + } + foreach (SqlParameter sqlParameter in sqlQueryCondition1.Parametros) + { + if (sqlCommand.Parameters.Contains(sqlParameter.ParameterName)) + { + continue; + } + sqlCommand.Parameters.Add(sqlParameter); + } + using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) + { + while (true) + { + if (!await sqlDataReader.ReadAsync()) + { + break; + } + TipoSeguro tipoSeguro = sqlDataReader.GetFieldValue("situacao", true, true); + if (!await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "negociocorretora")) + { + fieldValue = sqlDataReader.GetFieldValue("negociocorretora", true, true); + } + else + { + bool flag = tipoSeguro == TipoSeguro.Renovacao; + if (flag) + { + flag = !await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "idnegocio"); + } + negocioCorretora = (!flag || !(sqlDataReader.GetFieldValue("idnegocio", true, true) == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio); + fieldValue = negocioCorretora; + } + NegocioCorretora negocioCorretora1 = fieldValue; + List negocio = filtro.Negocio; + if (negocio != null) + { + count = negocio.Count > 0; + } + else + { + count = false; + } + if (!count || filtro.Negocio.Any((long n) => (int)n == (int)negocioCorretora1)) + { + long num = sqlDataReader.GetFieldValue("IdControle", true, true); + long fieldValue1 = sqlDataReader.GetFieldValue("IdEmpresa", true, true); + Documento documento = documentos1.Find((Documento p) => p.Controle.Id == num); + if (documento != null) + { + itensAtivo = documento.ItensAtivo; + } + else + { + itensAtivo = null; + } + List items = itensAtivo; + if (items == null) + { + items = await this.BuscaItemsPorIdControle(num); + } + List items1 = items; + DateTime? nullable = sqlDataReader.GetFieldValue("vigenciafultimafatura", true, true); + dateTime = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue); + DateTime dateTime4 = dateTime; + nullable = sqlDataReader.GetFieldValue("vigenciaIultimafatura", true, true); + dateTime1 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue); + DateTime dateTime5 = dateTime1; + nullable = sqlDataReader.GetFieldValue("vigenciainicial", true, true); + dateTime2 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue); + DateTime dateTime6 = dateTime2; + nullable = sqlDataReader.GetFieldValue("vigenciafinalfatura", true, true); + dateTime3 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue); + if (dateTime4 < dateTime3) + { + Documento observableCollection = new Documento() + { + Id = sqlDataReader.GetFieldValue("iddocumento", true, true) + }; + Controle controle = new Controle() + { + IdEmpresa = fieldValue1 + }; + Cliente cliente = new Cliente() + { + Id = sqlDataReader.GetFieldValue("idcliente", true, true), + Nome = sqlDataReader.GetFieldValue("cliente", true, true), + IdEmpresa = fieldValue1, + Pasta = sqlDataReader.GetFieldValue("pastaCliente", true, true) + }; + bool? nullable1 = sqlDataReader.GetFieldValue("MalaDireta", true, true); + cliente.MalaDireta = new bool?(nullable1.GetValueOrDefault(true)); + controle.Cliente = cliente; + Seguradora seguradora = new Seguradora() + { + Id = sqlDataReader.GetFieldValue("idseguradora", true, true), + Nome = sqlDataReader.GetFieldValue("nomeseguradora", true, true) + }; + controle.Seguradora = seguradora; + Ramo ramo = new Ramo() + { + Id = sqlDataReader.GetFieldValue("idramo", true, true), + Nome = sqlDataReader.GetFieldValue("nomeramo", true, true) + }; + controle.Ramo = ramo; + if (sqlDataReader.FieldIsNull("idproduto")) + { + produto = null; + } + else + { + produto = new Produto(); + ((DomainBase)produto).Id = sqlDataReader.GetFieldValue("idproduto", true, true); + ((Produto)produto).Nome = sqlDataReader.GetFieldValue("nomeproduto", true, true); + } + controle.Produto = (Produto)produto; + observableCollection.Controle = controle; + observableCollection.TipoRecebimento = new TipoRecebimento?(TipoRecebimento.Fatura); + observableCollection.Apolice = sqlDataReader.GetFieldValue("apolice", true, true); + observableCollection.Pasta = sqlDataReader.GetFieldValue("Pasta", true, true); + str = (sqlDataReader.GetFieldValue("tipo", true, true) == 0 ? "" : string.Concat("E ", sqlDataReader.GetFieldValue("endosso", true, true))); + observableCollection.Endosso = str; + observableCollection.Vigencia2 = sqlDataReader.GetFieldValue("vigenciafinal", true, true); + observableCollection.Vigencia1 = dateTime6; + observableCollection.Emissao = sqlDataReader.GetFieldValue("emissao", true, true); + observableCollection.Remessa = sqlDataReader.GetFieldValue("remessa", true, true); + if (sqlDataReader.GetFieldValue("idvendedor", true, true) != null) + { + List vendedores = Auxiliar.Vendedores; + Func func2 = func; + if (func2 == null) + { + Func id = (Vendedor p) => p.Id == sqlDataReader.GetFieldValue("idvendedor", true, true); + Func func3 = id; + func = id; + func2 = func3; + } + vendedor = vendedores.FirstOrDefault(func2); + } + else + { + vendedor = null; + } + observableCollection.VendedorPrincipal = vendedor; + if (sqlDataReader.GetFieldValue("idestipulante", true, true) != null) + { + List estipulantes = Auxiliar.Estipulantes; + Func func4 = func1; + if (func4 == null) + { + Func id1 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue("idestipulante", true, true); + Func func5 = id1; + func1 = id1; + func4 = func5; + } + estipulante = estipulantes.FirstOrDefault(func4); + } + else + { + estipulante = null; + } + observableCollection.Estipulante1 = estipulante; + observableCollection.NegocioCorretora = new NegocioCorretora?(negocioCorretora1); + observableCollection.Situacao = tipoSeguro; + List parcelas = new List(); + Parcela parcela = new Parcela() + { + Id = sqlDataReader.GetFieldValue("idparcela", true, true), + VigenciaFinal = new DateTime?(dateTime4), + Fatura = sqlDataReader.GetFieldValue("numfatura", true, true), + Vencimento = sqlDataReader.GetFieldValue("Vencimento", true, true), + VigenciaIncial = new DateTime?(dateTime5) + }; + parcelas.Add(parcela); + observableCollection.Parcelas = new ObservableCollection(parcelas); + observableCollection.Tipo = sqlDataReader.GetFieldValue("tipo", true, true); + observableCollection.DataControle = sqlDataReader.GetFieldValue("datacontrole", true, true); + if (sqlDataReader.FieldIsNull("idstatus")) + { + statu = null; + } + else + { + statu = new Status(); + ((DomainBase)statu).Id = sqlDataReader.GetFieldValue("idstatus", true, true); + ((Status)statu).Nome = sqlDataReader.GetFieldValue("nomestatus", true, true); + } + observableCollection.Status = (Status)statu; + observableCollection.ItensAtivo = items1; + documentos1.Add(observableCollection); + } + } + } + } + } + sqlCommand = null; + } + sqlConnection = null; + documentos = documentos1; + } + documentos1 = null; + return documentos; + } + + public List FindByDocumentId(List ids) + { + List parcelas; + object connection; + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + DataTable dataTable = new DataTable(); + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + Auxiliar.CriarAuxiliar(sqlCommand, false); + string str = string.Concat(" p.iddocumento IN (", string.Join(",", ids), ")"); + sqlCommand.CommandText = string.Concat("SELECT p.iddocumento, ISNULL(p.idempresa, 1) AS idempresa, p.idparcela, p.parcela, p.vencto, p.datarec, p.dataquit, p.datacontrole, p.datacred, p.valor, p.valorr, p.comiss,p.obs, p.vlrcomiss, p.vlrcomdesc, p.idsubtipo, p.idtipopagto, p.valorlf, p.extrato, ISNULL(p.StatusPagamento, 0) AS StatusPagamento, ISNULL(p.IdParcelaPendente, 0) AS IdParcelaPendente, p.irr, p.iss, p.outros, p.desconto, f.* FROM parcela p OUTER APPLY (SELECT numfatura, vigenciai, vigenciaf, emissao FROM fatura WHERE idparcela = p.idparcela) f WHERE ", str); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + if (dataTable.Rows.Count != 0) + { + goto Label0; + } + else + { + parcelas = new List(); + } + } + } + return parcelas; + Label0: + List list = dataTable.AsEnumerable().ToList(); + return list.Select((DataRow x) => { + Parcela parcela = new Parcela() + { + Id = x.Field("idparcela"), + IdEmpresa = x.Field("idempresa"), + Documento = new Documento() + { + Id = x.Field("iddocumento") + }, + NumeroParcela = int.Parse(x.Field("parcela").ToString()) + }; + DateTime? nullable = x.Field("vencto"); + parcela.Vencimento = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.Today); + parcela.DataRecebimento = x.Field("datarec"); + parcela.DataQuitacao = x.Field("dataquit"); + parcela.DataControle = x.Field("datacontrole"); + parcela.DataCredito = x.Field("datacred"); + decimal? nullable1 = x.Field("valor"); + parcela.Valor = nullable1.GetValueOrDefault(); + nullable1 = x.Field("valorr"); + parcela.ValorRealizado = nullable1.GetValueOrDefault(); + nullable1 = x.Field("comiss"); + parcela.Comissao = nullable1.GetValueOrDefault(); + nullable1 = x.Field("vlrcomiss"); + parcela.ValorComissao = nullable1.GetValueOrDefault(); + nullable1 = x.Field("vlrcomdesc"); + parcela.ValorComDesconto = nullable1.GetValueOrDefault(); + parcela.Observacao = x.Field("obs"); + parcela.SubTipo = (SubTipo)Enum.Parse(typeof(SubTipo), x.Field("idsubtipo").ToString()); + parcela.TipoPagamento = (x.Field("idtipopagto") == null ? TipoPagamento.Nenhum : (TipoPagamento)Enum.Parse(typeof(TipoPagamento), x.Field("idtipopagto").ToString())); + nullable1 = x.Field("valorlf"); + parcela.ValorLiquidoFatura = nullable1.GetValueOrDefault(); + parcela.Fatura = x.Field("numfatura"); + parcela.VigenciaIncial = x.Field("vigenciai"); + parcela.VigenciaFinal = x.Field("vigenciaf"); + parcela.Emissao = x.Field("emissao"); + parcela.Extrato = x.Field("extrato"); + parcela.StatusPagamento = new StatusPagamento?((x.Field("StatusPagamento") == null ? StatusPagamento.All : (StatusPagamento)Enum.Parse(typeof(StatusPagamento), x.Field("StatusPagamento").ToString()))); + parcela.IdParcelaPendente = x.Field("IdParcelaPendente").GetValueOrDefault(); + nullable1 = x.Field("irr"); + parcela.Irr = nullable1.GetValueOrDefault(); + nullable1 = x.Field("iss"); + parcela.Iss = nullable1.GetValueOrDefault(); + nullable1 = x.Field("desconto"); + parcela.Desconto = nullable1.GetValueOrDefault(); + nullable1 = x.Field("outros"); + parcela.Outros = nullable1.GetValueOrDefault(); + return parcela; + }).ToList(); + } + + public List FindByDocumentId(long id) + { + List parcelas; + object connection; + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + DataTable dataTable = new DataTable(); + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + Auxiliar.CriarAuxiliar(sqlCommand, false); + sqlCommand.CommandText = string.Concat("SELECT ISNULL(p.idempresa, 1) AS idempresa, p.idparcela, p.parcela, p.vencto, p.datarec, p.dataquit, p.datacontrole, p.datacred, p.valor, p.valorr, p.comiss, p.vlrcomiss,p.obs, p.vlrcomdesc, p.idsubtipo, p.idtipopagto, p.valorlf, p.extrato, ISNULL(p.StatusPagamento, 0) AS StatusPagamento, ISNULL(p.IdParcelaPendente, 0) AS IdParcelaPendente, p.irr, p.iss, p.outros, p.desconto, p.valorp, p.obs, p.vlrextrato, p.cri_data, p.usuariocriacao, f.* ", string.Format("FROM parcela p OUTER APPLY (SELECT idfatura, numfatura as fatura, vigenciai as vigenciainicial, vigenciaf as vigenciafinal, emissao FROM fatura WHERE idparcela = p.idparcela) f WHERE p.iddocumento = {0}", id)); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + if (dataTable.Rows.Count != 0) + { + Documento documento = (new DocumentoRepository(this._unitOfWork)).FindById(id, false, false); + return dataTable.MapParcela(documento); + } + else + { + parcelas = new List(); + } + } + } + return parcelas; + } + + public List FindByDocumentIds(string ids, List documentos) + { + object connection; + DataTable dataTable = new DataTable(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = string.Concat("SELECT iddocumento, idempresa, idparcela, parcela, vencto, valor, idtipopagto, StatusPagamento, IdParcelaPendente FROM parcela WHERE iddocumento IN (", ids, ");"); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + } + } + documentos.ForEach((Documento x) => { + List parcelas = new List(); + dataTable.AsEnumerable().Where((DataRow y) => y.Field("iddocumento") == x.Id).ToList().ForEach((DataRow y) => { + Parcela parcela = new Parcela() + { + Id = y.Field("idparcela"), + IdEmpresa = (!y.Field("idempresa").HasValue ? (long)0 : y.Field("idempresa")), + NumeroParcela = int.Parse(y.Field("parcela").ToString()), + Vencimento = (y.Field("vencto") == null ? new DateTime() : y.Field("vencto")), + Valor = y.Field("valor"), + TipoPagamento = (y.Field("idtipopagto") == null ? TipoPagamento.Nenhum : (int)y.Field("idtipopagto")), + StatusPagamento = new StatusPagamento?((y.Field("StatusPagamento") == null ? StatusPagamento.All : (StatusPagamento)Enum.Parse(typeof(StatusPagamento), y.Field("StatusPagamento").ToString()))), + IdParcelaPendente = y.Field("IdParcelaPendente").GetValueOrDefault() + }; + parcelas.Add(parcela); + }); + x.Parcelas = new ObservableCollection(parcelas); + }); + return documentos; + } + + public List FindByDocumento(Documento documento) + { + List parcelas; + object connection; + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + DataTable dataTable = new DataTable(); + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + Auxiliar.CriarAuxiliar(sqlCommand, false); + sqlCommand.CommandText = string.Concat("SELECT ISNULL(p.idempresa, 1) AS idempresa, p.idparcela, p.parcela, p.vencto, p.datarec, p.dataquit, p.datacontrole, p.datacred, p.valor, p.valorr, p.comiss, p.vlrcomiss,p.obs, p.vlrcomdesc, p.idsubtipo, p.idtipopagto, p.valorlf, p.extrato, ISNULL(p.StatusPagamento, 0) AS StatusPagamento, ISNULL(p.IdParcelaPendente, 0) AS IdParcelaPendente, p.irr, p.iss, p.outros, p.desconto, p.valorp, p.obs, p.vlrextrato, p.cri_data, p.usuariocriacao, f.* ", string.Format("FROM parcela p OUTER APPLY (SELECT idfatura, numfatura as fatura, vigenciai as vigenciainicial, vigenciaf as vigenciafinal, emissao FROM fatura WHERE idparcela = p.idparcela) f WHERE p.iddocumento = {0}", documento.Id)); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + if (dataTable.Rows.Count != 0) + { + return dataTable.MapParcela(documento); + } + else + { + parcelas = new List(); + } + } + } + return parcelas; + } + + public Parcela FindById(long id) + { + DateTime? nullable; + string fatura; + DateTime? vigenciaInicial; + DateTime? vigenciaFinal; + DateTime? emissao; + ParcelaDb parcelaDb = base.FindEntityById(id); + if (parcelaDb == null) + { + return null; + } + if (parcelaDb.Documento.TipoRecebimento.GetValueOrDefault() == TipoRecebimento.Parcela || !string.IsNullOrEmpty(parcelaDb.Fatura)) + { + return ApplicationMapper.Mapper.Map(parcelaDb); + } + FaturaDb faturaDb = this._unitOfWork.Query().FirstOrDefault((FaturaDb x) => x.Parcela.Id == id); + ParcelaDb parcelaDb1 = parcelaDb; + if (faturaDb != null) + { + fatura = faturaDb.Fatura; + } + else + { + fatura = null; + } + parcelaDb1.Fatura = fatura; + ParcelaDb parcelaDb2 = parcelaDb; + if (faturaDb != null) + { + vigenciaInicial = faturaDb.VigenciaInicial; + } + else + { + nullable = null; + vigenciaInicial = nullable; + } + parcelaDb2.VigenciaIncial = vigenciaInicial; + ParcelaDb parcelaDb3 = parcelaDb; + if (faturaDb != null) + { + vigenciaFinal = faturaDb.VigenciaFinal; + } + else + { + nullable = null; + vigenciaFinal = nullable; + } + parcelaDb3.VigenciaFinal = vigenciaFinal; + ParcelaDb parcelaDb4 = parcelaDb; + if (faturaDb != null) + { + emissao = faturaDb.Emissao; + } + else + { + nullable = null; + emissao = nullable; + } + parcelaDb4.Emissao = emissao; + return ApplicationMapper.Mapper.Map(parcelaDb); + } + + public List FindByPagamento(Filtros filtro, bool reciboPagamento, bool segundaViaReciboPagamento, bool datacontrole) + { + List vendedorParcelas; + string str; + object connection; + string str1 = (filtro.Status == null || filtro.Status.Count == 0 ? "" : string.Concat(" AND situacao IN (", string.Join(",", + from v in filtro.Status + select v), ")")); + string str2 = (filtro.Negocio == null || filtro.Negocio.Count == 0 ? "" : string.Concat(" AND (NegocioCorretora IN (", string.Join(",", + from v in filtro.Negocio + select v), ") OR NegocioCorretora IS NULL)")); + string str3 = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND c.idciaseg IN (", string.Join(",", + from v in filtro.Seguradoras + select v), ")")); + string str4 = (filtro.Ramos == null || filtro.Ramos.Count == 0 ? "" : string.Concat(" AND c.idramo IN (", string.Join(",", + from v in filtro.Ramos + select v), ")")); + string str5 = (filtro.Produtos == null || filtro.Produtos.Count == 0 ? "" : string.Concat(" AND c.idproduto IN (", string.Join(",", + from v in filtro.Produtos + select v), ")")); + string str6 = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? "" : string.Concat(" AND vp.idvendedor IN (", string.Join(",", + from v in filtro.Vendedores + select v), ")")); + string str7 = (filtro.TipoVendedor == null || filtro.TipoVendedor.Count == 0 ? "" : string.Concat(" AND vp.idtipovendedor IN (", string.Join(",", + from v in filtro.TipoVendedor + select v), ")")); + string str8 = (filtro.Estipulantes == null || filtro.Estipulantes.Count == 0 ? "" : string.Concat(" AND d.idestipulante IN (", string.Join(",", + from v in filtro.Estipulantes + select v), ")")); + string str9 = (!reciboPagamento || segundaViaReciboPagamento ? "" : "AND vp.datapgt IS NULL "); + if (segundaViaReciboPagamento) + { + str = "CAST(vp.datapgt AS DATE)"; + } + else + { + str = (datacontrole ? "CAST(d.datacontrole AS DATE)" : "CAST(vp.dataprepagto AS DATE)"); + } + string str10 = str; + string str11 = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", filtro.IdEmpresa)); + string str12 = (filtro.ParcelasEspeciais.Any((FiltroTipoParcela x) => x.Selecionado) ? string.Concat(" AND p.idsubtipo IN (", string.Join(",", + from x in filtro.ParcelasEspeciais + where x.Selecionado + select x into v + select (int)v.Tipo), ")") : ""); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + DataTable dataTable = new DataTable(); + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandTimeout = 15000; + Auxiliar.CriarAuxiliar(sqlCommand, false); + string str13 = "SELECT DISTINCT cl.idempresa, vp.idvendedorparcela, cl.idcliente, cl.MalaDireta, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, vp.idvendedor, d.idestipulante, p.idparcela, d.iddocumento, d.N_PARC as numeroparcelas, d.datacontrole, cl.nome as cliente, d.contrato as apolice, d.aditamento as endosso, d.situacao, d.idnegocio, d.vigencia1 as vigenciainicial, d.proposta, d.vigencia2 as vigenciafinal, f.vigenciaf as vigenciaf, ISNULL(d.com01, 0) as comissao, ISNULL(p.comiss, 0.00) as comiss, p.parcela, d.tiporecebimento, ISNULL(d.pr_liq, 0.00) as liquido, ISNULL(d.pr_total, 0.00) as total, ISNULL(p.valor, 0.00) as valor, ISNULL(p.valorlf, 0.00) as liquidofatura, f.vigenciai, f.numfatura as fatura, vp.dataprepagto as recebimento, ISNULL(vp.vlrrep,0) as repasse, ISNULL(vp.vrep, 0) as percentual, p.idsubtipo, vp.datapgt, vp.idrepasse as idrepasse, rep.tipo as tiporepasse, d.cri_data, d.emissao, p.datarec, p.vlrcomdesc, d.NegocioCorretora, CASE WHEN ((Round(ISNULL( d.pr_liq, 0.00 ) * (ISNULL( d.com01, 0 ) / 100 ),2) * ( vp.vrep/ 100 )) - ROUND(vp.valortotal,2) - ROUND(cia.tolerancia,2)) > 0 THEN 'SIM' ELSE 'NÃO'END AS RecebidoPorCompleto FROM vendedorparcela vp INNER JOIN parcela p on p.idparcela = vp.idparcela INNER JOIN documento d on d.iddocumento = p.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente LEFT OUTER JOIN fatura f on f.idparcela = p.idparcela INNER JOIN repasse rep on rep.idrepasse = vp.idrepasse INNER JOIN ciaseg cia on cia.idciaseg = c.idciaseg WHERE (d.excluido IS NULL OR d.excluido = 0)"; + sqlCommand.CommandText = string.Format("{0} {1} AND vp.idvendedor != {2} AND {3} >= '{4:yyyy-MM-dd}' AND {5} <= '{6:yyyy-MM-dd}' {7} {8} {9} {10} {11} {12} {13} {14} {15}{16}", new object[] { str13, str11, Auxiliar.Vendedores.First((Vendedor x) => x.Corretora).Id, str10, filtro.Inicio, str10, filtro.Fim, str9, str1, str2, str3, str4, str5, str8, str6, str7, str12 }); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + if (dataTable.Rows.Count != 0) + { + Action action = (DataRow x) => x.SetField("NegocioCorretora", (!(x.Field("situacao").ToString() == "2") || x.Field("idnegocio") == null || !(x.Field("idnegocio").ToString() == "1") ? "0" : "1")); + ( + from x in dataTable.AsEnumerable().ToList() + where x.Field("NegocioCorretora") == null + select x).ForEach(action); + if (!str2.IsNullOrEmpty()) + { + Func func = (DataRow p) => filtro.Negocio.Any((long filter) => filter.ToString() == p.Field("NegocioCorretora").ToString()); + dataTable = dataTable.AsEnumerable().Where(func).CopyToDataTable(); + } + goto Label0; + } + else + { + vendedorParcelas = new List(); + } + } + } + return vendedorParcelas; + Label0: + List list = dataTable.AsEnumerable().ToList(); + return list.Select((DataRow x) => { + decimal? nullable; + decimal valueOrDefault; + decimal num; + VendedorParcela vendedorParcela = new VendedorParcela() + { + Id = x.Field("idvendedorparcela"), + Vendedor = Auxiliar.Vendedores.FirstOrDefault((Vendedor p) => p.Id == x.Field("idvendedor")), + Repasse = new Repasse() + { + Id = x.Field("idrepasse"), + Tipo = new TipoRepasse?((TipoRepasse)Enum.Parse(typeof(TipoRepasse), x.Field("tiporepasse").ToString())) + } + }; + Documento documento = new Documento() + { + Id = x.Field("iddocumento"), + Controle = new Controle() + { + IdEmpresa = x.Field("idempresa"), + Cliente = new Cliente() + { + Id = x.Field("idcliente"), + Nome = x.Field("cliente"), + IdEmpresa = x.Field("idempresa"), + MalaDireta = new bool?(x.Field("MalaDireta").GetValueOrDefault(true)) + }, + Seguradora = (x.Field("idseguradora") != null ? Auxiliar.Seguradoras.FirstOrDefault((Seguradora p) => p.Id == x.Field("idseguradora")) : null), + Ramo = (x.Field("idramo") != null ? Auxiliar.Ramos.FirstOrDefault((Ramo p) => p.Id == x.Field("idramo")) : null), + Produto = (x.Field("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault((Produto p) => p.Id == x.Field("idproduto")) : null) + }, + Apolice = x.Field("apolice"), + Endosso = (x.Field("tiporecebimento").ToString() == "1" ? x.Field("endosso") : string.Concat("F ", x.Field("fatura"))), + Comissao = (x.Field("tiporecebimento").ToString() == "1" ? x.Field("comissao") : x.Field("comiss")) + }; + if (x.Field("tiporecebimento").ToString() == "1") + { + nullable = x.Field("liquido"); + valueOrDefault = nullable.GetValueOrDefault(); + } + else + { + nullable = x.Field("liquidofatura"); + valueOrDefault = nullable.GetValueOrDefault(); + } + documento.PremioLiquido = valueOrDefault; + if (x.Field("tiporecebimento").ToString() == "1") + { + nullable = x.Field("total"); + num = nullable.GetValueOrDefault(); + } + else + { + nullable = x.Field("valor"); + num = nullable.GetValueOrDefault(); + } + documento.PremioTotal = num; + documento.Vigencia1 = (x.Field("tiporecebimento").ToString() == "1" ? x.Field("vigenciainicial") : (x.Field("vigenciai") != null ? x.Field("vigenciai") : new DateTime())); + documento.Vigencia2 = (x.Field("tiporecebimento").ToString() == "1" ? x.Field("vigenciafinal") : x.Field("vigenciaf")); + documento.Proposta = x.Field("proposta"); + documento.NegocioCorretora = new NegocioCorretora?((NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), x.Field("NegocioCorretora").ToString())); + documento.Estipulante1 = (x.Field("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault((Estipulante p) => p.Id == x.Field("idestipulante")) : null); + documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()); + documento.TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), x.Field("tiporecebimento").ToString())); + documento.NumeroParcelas = x.Field("numeroparcelas"); + documento.DataCriacao = x.Field("cri_data"); + documento.DataControle = x.Field("datacontrole"); + documento.Emissao = x.Field("emissao"); + vendedorParcela.Documento = documento; + Parcela parcela = new Parcela() + { + NumeroParcela = int.Parse(x.Field("parcela").ToString()), + Id = x.Field("idparcela"), + SubTipo = (SubTipo)Enum.Parse(typeof(SubTipo), x.Field("idsubtipo").ToString()), + IdEmpresa = x.Field("idempresa"), + Valor = x.Field("valor") + }; + nullable = x.Field("vlrcomdesc"); + parcela.ValorComDesconto = nullable.GetValueOrDefault(); + parcela.DataRecebimento = x.Field("datarec"); + vendedorParcela.Parcela = parcela; + vendedorParcela.ValorRepasse = new decimal?(x.Field("repasse")); + DateTime? nullable1 = x.Field("recebimento"); + vendedorParcela.DataPrePagamento = new DateTime?((nullable1.HasValue ? nullable1.GetValueOrDefault() : DateTime.MinValue)); + vendedorParcela.PorcentagemRepasse = new decimal?(x.Field("percentual")); + vendedorParcela.DataPagamento = x.Field("datapgt"); + vendedorParcela.RecebidoPorCompleto = x.Field("RecebidoPorCompleto"); + return vendedorParcela; + }).ToList(); + } + + public List FindByPendente(Filtros filtro, bool pendente, bool somenteAtivos) + { + List parcelas; + object connection; + List nums = null; + string str = (filtro.Status == null || filtro.Status.Count == 0 ? "" : string.Concat(" AND situacao IN (", string.Join(",", + from v in filtro.Status + select v), ")")); + string str1 = (filtro.Negocio == null || filtro.Negocio.Count == 0 ? "" : string.Concat(" AND NegocioCorretora IN (", string.Join(",", + from v in filtro.Negocio + select v), ")")); + string str2 = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND c.idciaseg IN (", string.Join(",", + from v in filtro.Seguradoras + select v), ")")); + string str3 = (filtro.Ramos == null || filtro.Ramos.Count == 0 ? "" : string.Concat(" AND c.idramo IN (", string.Join(",", + from v in filtro.Ramos + select v), ")")); + string str4 = (filtro.Produtos == null || filtro.Produtos.Count == 0 ? "" : string.Concat(" AND c.idproduto IN (", string.Join(",", + from v in filtro.Produtos + select v), ")")); + string str5 = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? "" : string.Concat(" AND vp.idvendedor IN (", string.Join(",", + from v in filtro.Vendedores + select v), ")")); + string str6 = (filtro.TipoVendedor == null || filtro.TipoVendedor.Count == 0 ? "OUTER APPLY (SELECT TOP 1 vp2.idvendedor FROM vendedorparcela vp2 WHERE (d.tiporecebimento = 2 AND vp2.IDPARCELA = p.IDPARCELA) OR (d.tiporecebimento = 1 AND vp2.iddocumento = p.iddocumento)) vp" : string.Concat("INNER JOIN vendedorparcela vp ON vp.iddocumento = d.iddocumento AND vp.idtipovendedor IN (", string.Join(",", + from v in filtro.TipoVendedor + select v), ")")); + string str7 = (filtro.Estipulantes == null || filtro.Estipulantes.Count == 0 ? "" : string.Concat(" AND d.idestipulante IN (", string.Join(",", + from v in filtro.Estipulantes + select v), ")")); + string str8 = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", filtro.IdEmpresa)); + string str9 = (somenteAtivos ? " AND i.idsubstituido IS NULL" : ""); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + DataTable dataTable = new DataTable(); + DataTable dataTable1 = new DataTable(); + DataTable dataTable2 = new DataTable(); + DataTable dataTable3 = new DataTable(); + DataTable dataTable4 = new DataTable(); + string str10 = (pendente ? "AND p.datarec IS NULL" : ""); + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandTimeout = 15000; + Auxiliar.CriarAuxiliar(sqlCommand, false); + string str11 = string.Concat("SELECT DISTINCT cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome as cliente, d.idcontrole, p.idparcela as id, f.numfatura as fatura, f.vigenciai as vigenciai, f.vigenciaf as vigenciaf, p.parcela, p.datarec as recebimento, p.dataquit as quitacao, p.datacontrole as dataparcelacontrole, p.vencto as vencimento, ISNULL(p.vlrcomdesc, 0.00) as valorcomdesconto, ISNULL(p.vlrcomiss, 0) as valorcomissao, p.iddocumento, ISNULL(p.StatusPagamento, 0) AS StatusPagamento, ISNULL(p.IdParcelaPendente, 0) AS IdParcelaPendente, d.contrato as apolice, d.aditamento as endosso, d.idnegocio, d.situacao, d.vigencia1 as vigenciainicial, d.vigencia2 as vigenciafinal, d.proposta, ISNULL(p.valor, 0.00) as valor, ISNULL(p.valorr, 0.00) as valorr, ISNULL(p.valorlf, 0.00) as valorliquidofatura, ISNULL(d.pr_total, 0.00) as total, ISNULL(d.pr_liq, 0.00) as liquido, d.pr_adic as adicional, d.adinacomis as adinacomiss, ISNULL(d.com01,0) as comissao, ISNULL(p.comiss, 0.00) as comiss, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, vp.idvendedor, d.idestipulante, d.tiporecebimento, d.N_PARC as numeroparcelas, d.datacontrole, d.idstatus, p.idsubtipo, cl.cgccpf, d.formapagamento, d.propassinada, d.pasta, cl.pasta as pastacliente FROM parcela p INNER JOIN documento d on d.iddocumento = p.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente ", (somenteAtivos ? "INNER JOIN item i on d.iddocumento = i.iddocumento " : ""), str6, " LEFT OUTER JOIN fatura f on f.idparcela = p.idparcela WHERE (d.excluido IS NULL OR d.excluido = 0)"); + string str12 = "SELECT DISTINCT idparcela as id, idvendedor, vlrrep as valorrepasse, vrep as porcentagemrepasse, datapgt as datapagamento, dataprepagto as dataprepagamento FROM vendedorparcela vp WHERE 1=1 "; + string str13 = "SELECT iddocumento, idparcela as id, parcela, datarec as recebimento, vencto as vencimento, vlrcomdesc as valorcomdesconto, ISNULL(vlrcomiss, 0.00) as valorcomissao, ISNULL(valor, 0.00) as valor, ISNULL(comiss, 0.00) as comiss, ISNULL(StatusPagamento, 0) AS StatusPagamento, ISNULL(IdParcelaPendente, 0) AS IdParcelaPendente FROM parcela where datarec IS NOT NULL "; + string str14 = "SELECT i.iditem, d.iddocumento, d.idcontrole, i.descricao FROM item i INNER JOIN documento d on d.iddocumento = i.iddocumento WHERE (cancelado IS NULL OR cancelado != '1') AND idsubstituido IS NULL "; + string str15 = "SELECT DISTINCT idcliente, idclitelefone, ddd, fone, idcliente as id FROM clitelefone WHERE "; + sqlCommand.CommandText = string.Format("{0} {1} {2} AND p.vencto >= '{3:yyyy-MM-dd}' AND p.vencto <= '{4:yyyy-MM-dd}' {5} {6} {7} {8} {9} {10} {11} {12}", new object[] { str11, str8, str10, filtro.Inicio, filtro.Fim, str, str1, str2, str3, str4, str7, str5, str9 }); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + if (dataTable.Rows.Count != 0) + { + string str16 = string.Concat(" AND vp.idparcela IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); + sqlCommand.CommandText = string.Concat(str12, " ", str16); + using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) + { + sqlDataAdapter1.SelectCommand = sqlCommand; + sqlDataAdapter1.Fill(dataTable1); + } + string str17 = string.Concat(" AND iddocumento IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("iddocumento"))), ")"); + sqlCommand.CommandText = string.Concat(str13, " ", str17); + using (SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter()) + { + sqlDataAdapter2.SelectCommand = sqlCommand; + sqlDataAdapter2.Fill(dataTable2); + } + string str18 = string.Concat(" AND d.idcontrole IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("idcontrole"))), ")"); + sqlCommand.CommandText = string.Concat(str14, " ", str18); + using (SqlDataAdapter sqlDataAdapter3 = new SqlDataAdapter()) + { + sqlDataAdapter3.SelectCommand = sqlCommand; + sqlDataAdapter3.Fill(dataTable3); + } + for (List i1 = dataTable.AsEnumerable().Select((DataRow x) => x.Field("idcliente")).Distinct().ToList(); i1.Count > 0; i1 = nums) + { + List nums1 = i1.Take(1000).ToList(); + List condicaos = new List() + { + new Condicao() + { + Campo = "idcliente", + Valores = nums1.CriarValor() + } + }; + DataTable dataTable5 = sqlCommand.Select(condicaos.CreateParameters(0), str15, ""); + dataTable4.Merge(dataTable5); + nums = (nums1.Count < 1000 ? new List() : i1.Except(nums1).ToList()); + } + goto Label0; + } + else + { + parcelas = new List(); + } + } + } + return parcelas; + Label0: + return dataTable.AsEnumerable().ToList().Select((DataRow x) => { + decimal? nullable3; + decimal valueOrDefault; + decimal num; + Parcela observableCollection = new Parcela() + { + Id = x.Field("id"), + IdEmpresa = x.Field("idempresa"), + NumeroParcela = int.Parse(x.Field("parcela").ToString()) + }; + DateTime? nullable4 = x.Field("vencimento"); + observableCollection.Vencimento = (nullable4.HasValue ? nullable4.GetValueOrDefault() : DateTime.MinValue); + observableCollection.Comissao = x.Field("comiss"); + observableCollection.DataQuitacao = x.Field("quitacao"); + observableCollection.DataControle = x.Field("dataparcelacontrole"); + observableCollection.Valor = x.Field("valor"); + observableCollection.SubTipo = (SubTipo)Enum.Parse(typeof(SubTipo), x.Field("idsubtipo").ToString()); + observableCollection.StatusPagamento = new StatusPagamento?((x.Field("StatusPagamento") == null ? StatusPagamento.All : (StatusPagamento)Enum.Parse(typeof(StatusPagamento), x.Field("StatusPagamento").ToString()))); + observableCollection.IdParcelaPendente = x.Field("IdParcelaPendente").GetValueOrDefault(); + IEnumerable list = + from v in dataTable1.AsEnumerable().ToList() + where v.Field("id") == x.Field("id") + select v; + Func u003cu003e9_2614 = ParcelaRepository.u003cu003ec.u003cu003e9__26_14; + if (u003cu003e9_2614 == null) + { + u003cu003e9_2614 = (DataRow v) => { + DateTime? nullable; + DateTime? nullable1; + DateTime? nullable2; + VendedorParcela vendedorParcela = new VendedorParcela() + { + Vendedor = Auxiliar.Vendedores.FirstOrDefault((Vendedor p) => p.Id == v.Field("idvendedor")), + ValorRepasse = new decimal?((v.Field("valorrepasse") == null ? decimal.Zero : v.Field("valorrepasse"))), + PorcentagemRepasse = new decimal?((v.Field("porcentagemrepasse") == null ? decimal.Zero : v.Field("porcentagemrepasse"))) + }; + if (v.Field("datapagamento") == null) + { + nullable = null; + nullable1 = nullable; + } + else + { + nullable1 = v.Field("datapagamento"); + } + vendedorParcela.DataPagamento = nullable1; + if (v.Field("dataprepagamento") == null) + { + nullable = null; + nullable2 = nullable; + } + else + { + nullable2 = v.Field("dataprepagamento"); + } + vendedorParcela.DataPrePagamento = nullable2; + return vendedorParcela; + }; + ParcelaRepository.u003cu003ec.u003cu003e9__26_14 = u003cu003e9_2614; + } + observableCollection.Vendedores = new ObservableCollection(list.Select(u003cu003e9_2614).ToList()); + Documento documento = new Documento() + { + Id = x.Field("iddocumento"), + FormaPagamento = new FormaPagamento?((x.Field("formapagamento") == null || !(x.Field("formapagamento").ToString() != "") || string.IsNullOrWhiteSpace(x.Field("formapagamento").ToString()) ? FormaPagamento.Nenhum : (FormaPagamento)Enum.Parse(typeof(FormaPagamento), x.Field("formapagamento").ToString()))) + }; + Controle controle = new Controle() + { + Id = x.Field("idcontrole"), + IdEmpresa = x.Field("idempresa") + }; + Cliente cliente = new Cliente() + { + Id = x.Field("idcliente"), + Nome = x.Field("cliente"), + Documento = x.Field("cgccpf"), + IdEmpresa = x.Field("idempresa"), + Pasta = x.Field("pastacliente") + }; + EnumerableRowCollection dataRows = dataTable4.AsEnumerable().Where((DataRow t) => t.Field("idcliente") == x.Field("idcliente")); + Func u003cu003e9_2627 = ParcelaRepository.u003cu003ec.u003cu003e9__26_27; + if (u003cu003e9_2627 == null) + { + u003cu003e9_2627 = (DataRow t) => new ClienteTelefone() + { + Id = t.Field("idclitelefone"), + Prefixo = t.Field("ddd"), + Numero = t.Field("fone") + }; + ParcelaRepository.u003cu003ec.u003cu003e9__26_27 = u003cu003e9_2627; + } + cliente.Telefones = new ObservableCollection(dataRows.Select(u003cu003e9_2627)); + cliente.MalaDireta = new bool?(x.Field("MalaDireta").GetValueOrDefault(true)); + controle.Cliente = cliente; + controle.Seguradora = (x.Field("idseguradora") != null ? Auxiliar.Seguradoras.FirstOrDefault((Seguradora p) => p.Id == x.Field("idseguradora")) : null); + controle.Ramo = (x.Field("idramo") != null ? Auxiliar.Ramos.FirstOrDefault((Ramo p) => p.Id == x.Field("idramo")) : null); + controle.Produto = (x.Field("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault((Produto p) => p.Id == x.Field("idproduto")) : null); + documento.Controle = controle; + documento.Pasta = x.Field("Pasta"); + documento.NumeroParcelas = x.Field("numeroparcelas"); + documento.AdicionalComiss = x.Field("adinacomiss") == "1"; + documento.Apolice = x.Field("apolice"); + documento.Endosso = (x.Field("tiporecebimento").ToString() == "1" ? x.Field("endosso") : string.Concat("F ", x.Field("fatura"))); + documento.Comissao = x.Field("comiss"); + documento.Negocio = new Negocio?((x.Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field("idnegocio").ToString()))); + if (x.Field("tiporecebimento").ToString() == "1") + { + nullable3 = x.Field("liquido"); + valueOrDefault = nullable3.GetValueOrDefault(); + } + else + { + nullable3 = x.Field("valorliquidofatura"); + valueOrDefault = nullable3.GetValueOrDefault(); + } + documento.PremioLiquido = valueOrDefault; + if (x.Field("tiporecebimento").ToString() == "1") + { + nullable3 = x.Field("total"); + num = nullable3.GetValueOrDefault(); + } + else + { + nullable3 = x.Field("valor"); + num = nullable3.GetValueOrDefault(); + } + documento.PremioTotal = num; + nullable3 = x.Field("adicional"); + documento.PremioAdicional = nullable3.GetValueOrDefault(); + documento.Vigencia1 = (x.Field("tiporecebimento").ToString() == "1" ? (x.Field("vigenciainicial") == null ? DateTime.MinValue : x.Field("vigenciainicial")) : (x.Field("vigenciai") != null ? x.Field("vigenciai") : (x.Field("vigenciainicial") == null ? DateTime.MinValue : x.Field("vigenciainicial")))); + documento.Vigencia2 = (x.Field("tiporecebimento").ToString() == "1" ? (x.Field("vigenciafinal") == null ? new DateTime?(DateTime.MinValue) : x.Field("vigenciafinal")) : new DateTime?((x.Field("vigenciaf") != null ? x.Field("vigenciaf") : (x.Field("vigenciafinal") == null ? DateTime.MinValue : x.Field("vigenciafinal"))))); + documento.VendedorPrincipal = (x.Field("idvendedor") != null ? Auxiliar.Vendedores.FirstOrDefault((Vendedor p) => p.Id == x.Field("idvendedor")) : null); + documento.Proposta = x.Field("proposta"); + documento.Estipulante1 = (x.Field("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault((Estipulante p) => p.Id == x.Field("idestipulante")) : null); + documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()); + documento.TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), x.Field("tiporecebimento").ToString())); + documento.PropostaAssinada = (x.Field("propassinada") == null ? false : x.Field("propassinada") == "1"); + documento.Parcelas = new ObservableCollection(dataTable2.AsEnumerable().Where((DataRow p) => p.Field("iddocumento") == x.Field("iddocumento")).Select((DataRow p) => { + Parcela parcela = new Parcela() + { + Id = p.Field("id"), + NumeroParcela = int.Parse(p.Field("parcela").ToString()), + DataRecebimento = p.Field("recebimento") + }; + DateTime? nullable = p.Field("vencimento"); + parcela.Vencimento = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue); + parcela.ValorComissao = (x.Field("valorcomissao") == null ? decimal.Zero : p.Field("valorcomissao")); + parcela.ValorComDesconto = (p.Field("valorcomdesconto") == null || p.Field("valorcomdesconto") == decimal.Zero ? (x.Field("valorcomissao") == null ? decimal.Zero : p.Field("valorcomissao")) : p.Field("valorcomdesconto")); + parcela.Comissao = p.Field("comiss"); + parcela.Valor = p.Field("valor"); + parcela.StatusPagamento = new StatusPagamento?((p.Field("StatusPagamento") == null ? StatusPagamento.All : (StatusPagamento)Enum.Parse(typeof(StatusPagamento), p.Field("StatusPagamento").ToString()))); + parcela.IdParcelaPendente = p.Field("IdParcelaPendente").GetValueOrDefault(); + return parcela; + }).ToList()); + documento.Tipo = x.Field("tipo"); + documento.DataControle = x.Field("datacontrole"); + documento.Status = (x.Field("idstatus") != null ? Auxiliar.StatusApolice.FirstOrDefault((Status p) => p.Id == x.Field("idstatus")) : null); + IEnumerable list1 = + from i in dataTable3.AsEnumerable().ToList() + where i.Field("idcontrole") == x.Field("idcontrole") + select i; + Func u003cu003e9_2622 = ParcelaRepository.u003cu003ec.u003cu003e9__26_22; + if (u003cu003e9_2622 == null) + { + u003cu003e9_2622 = (DataRow i) => new Item() + { + Id = i.Field("iditem"), + Descricao = i.Field("descricao") + }; + ParcelaRepository.u003cu003ec.u003cu003e9__26_22 = u003cu003e9_2622; + } + documento.ItensAtivo = new List(list1.Select(u003cu003e9_2622).ToList()); + observableCollection.Documento = documento; + return observableCollection; + }).ToList(); + } + + public async Task> FindByRecebimento(Filtros filtro) + { + NegocioCorretora fieldValue; + bool flag; + bool count; + object connection; + bool count1; + bool flag1; + List itensAtivo; + decimal num; + object produto; + object estipulante; + object statu; + string str; + decimal num1; + decimal num2; + decimal num3; + DateTime dateTime; + DateTime? nullable; + NegocioCorretora negocioCorretora; + bool count2; + bool flag2; + Parcela parcela; + List parcelas = new List(); + List condicaos = this.CriaCondicaoDocumento(filtro, "CAST(p.DATAREC AS DATE)"); + List condicaos1 = new List(); + Condicao condicao = new Condicao() + { + Campo = "d.Excluido", + Valores = null, + Grupo = 1, + Operacao = Operacao.Or + }; + condicaos1.Add(condicao); + Condicao condicao1 = new Condicao() + { + Campo = "d.Excluido", + Valores = "0".CriarValor(), + Grupo = 1, + Operacao = Operacao.Or + }; + condicaos1.Add(condicao1); + condicaos.AddRange(condicaos1); + List vendedores = filtro.Vendedores; + if (vendedores != null) + { + count = vendedores.Count > 0; + } + else + { + count = false; + } + if (count) + { + if (await this.VerificaVendedorPropriaCorretora(filtro.Vendedores)) + { + List condicaos2 = condicaos; + Condicao condicao2 = new Condicao() + { + Campo = "vp.idvendedor", + Valores = null, + Grupo = 5, + Operacao = Operacao.Or + }; + condicaos2.Add(condicao2); + } + } + SqlQueryCondition sqlQueryCondition = condicaos.CreateParameters(0); + using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) + { + SessionFactoryImpl sessionFactoryImpl = sessionFactory; + if (sessionFactoryImpl != null) + { + connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandTimeout = 1500; + string str1 = "SELECT p.IDPARCELA IdParcela,p.PARCELA NumeroParcela,p.DATAREC DataRecebimento,p.dataquit DataQuitacao,p.datacontrole DataControleParcela,p.VENCTO Vencimento,p.VLRCOMISS ValorComissao,p.IRR Irr,p.ISS Iss,p.DESCONTO Desconto,p.OUTROS Outros,p.VLRCOMDESC ValorComDesconto,p.COMISS ComissaoParcela,p.VALORR ValorRealizado,p.VALORLF PremioLiquidoFatura,p.VALOR PremioTotalFatura,p.IDSUBTIPO SubTipo,d.IDDOCUMENTO IdDocumento,c.IDCONTROLE IdControle,c.IDEMPRESA IdEmpresa,c.idcliente IdCliente,clie.NOME NomeCliente,clie.PASTA PastaCliente,clie.MalaDireta MalaDireta,r.idramo IdRamo,r.NOME NomeRamo,cia.IDCIASEG IdCiaSeg,cia.NOME NomeCia,cia.NomeSocial NomeSocial,pr.idproduto IdProduto,pr.NOME NomeProduto,e.idestipulante IdEstipulante,e.nome NomeEstipulante,s.idstatus IdStatus,s.nome NomeStatus,d.ADINACOMIS AdicionalComiss,d.contrato Apolice,d.ADITAMENTO Endosso,d.COM01 ComissaoDocumento,d.NegocioCorretora,d.idnegocio Negocio,d.PR_LIQ PremioLiquido,d.PR_TOTAL PremioTotal,d.PR_ADIC PremioAdicional,d.vigencia1 VigenciaInicial,d.vigencia2 VigenciaFinal,d.SITUACAO Situacao,d.TIPO Tipo,d.tiporecebimento TipoRecebimento,d.datacontrole DataControleDocumento,d.PASTA PastaDocumento,vp.IDVENDEDORPARCELA IdVendedorParcela,vp.VLRREP ValorRepasse,vp.VREP PorcentagemRepasse,vp.DATAPGT DataPagamento,vp.DATAPREPAGTO DataPrePagamento,vp.idtipovendedor IdTipoVendedor,vp.IDVENDEDOR IdVendedor,v.NOME NomeVendedor,f.vigenciai VigenciaInicialFatura,f.vigenciaf VigenciaFinalFatura,f.NUMFATURA Fatura FROM parcela p INNER JOIN documento d ON d.IDDOCUMENTO = p.IDDOCUMENTO INNER JOIN controle c ON c.IDCONTROLE = d.IDCONTROLE INNER JOIN cliente clie ON clie.IDCLIENTE = c.IDCLIENTE INNER JOIN ramo r ON r.IDRAMO = c.IDRAMO INNER JOIN ciaseg cia ON cia.IDCIASEG = c.IDCIASEG LEFT JOIN produto pr ON pr.IDPRODUTO = c.IDPRODUTO LEFT JOIN estipulante e ON e.idestipulante = d.idestipulante LEFT JOIN status s ON s.idstatus = d.idstatus LEFT JOIN vendedorparcela vp ON vp.IDPARCELA = p.IDPARCELA LEFT JOIN vendedor v ON v.IDVENDEDOR = vp.IDVENDEDOR LEFT JOIN fatura f ON f.IDPARCELA = p.IDPARCELA WHERE "; + sqlCommand.CommandText = string.Concat(str1, " ", sqlQueryCondition.Condicao); + sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray()); + using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) + { + while (true) + { + if (!await sqlDataReader.ReadAsync()) + { + break; + } + if (!await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "NegocioCorretora")) + { + fieldValue = sqlDataReader.GetFieldValue("NegocioCorretora", true, true); + } + else + { + flag = sqlDataReader.GetFieldValue("Situacao", true, true) == TipoSeguro.Renovacao; + if (flag) + { + flag = !await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "Negocio"); + } + negocioCorretora = (!flag || !(sqlDataReader.GetFieldValue("Negocio", true, true) == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio); + fieldValue = negocioCorretora; + } + NegocioCorretora negocioCorretora1 = fieldValue; + if (filtro.Negocio == null || filtro.Negocio.Count <= 0 || filtro.Negocio.Any((long n) => (int)n == (int)negocioCorretora1)) + { + long fieldValue1 = sqlDataReader.GetFieldValue("IdParcela", true, true); + Parcela observableCollection = parcelas.Find((Parcela p) => p.Id == fieldValue1); + if (observableCollection == null) + { + long fieldValue2 = sqlDataReader.GetFieldValue("IdControle", true, true); + Parcela parcela1 = parcelas.Find((Parcela p) => p.Documento.Controle.Id == fieldValue2); + if (parcela1 != null) + { + itensAtivo = parcela1.Documento.ItensAtivo; + } + else + { + itensAtivo = null; + } + List items = itensAtivo; + if (items == null) + { + items = await this.BuscaItemsPorIdControle(fieldValue2); + } + TipoRecebimento tipoRecebimento = sqlDataReader.GetFieldValue("TipoRecebimento", true, true); + decimal fieldValue3 = sqlDataReader.GetFieldValue("ValorComissao", true, true); + decimal fieldValue4 = sqlDataReader.GetFieldValue("ValorComDesconto", true, true); + long num4 = sqlDataReader.GetFieldValue("IdEmpresa", true, true); + parcela = new Parcela() + { + Id = fieldValue1, + NumeroParcela = sqlDataReader.GetFieldValue("NumeroParcela", true, true), + DataRecebimento = sqlDataReader.GetFieldValue("DataRecebimento", true, true), + DataQuitacao = sqlDataReader.GetFieldValue("DataQuitacao", true, true), + DataControle = sqlDataReader.GetFieldValue("DataControleParcela", true, true), + Vencimento = sqlDataReader.GetFieldValue("Vencimento", true, true), + ValorComissao = fieldValue3, + Irr = sqlDataReader.GetFieldValue("Irr", true, true), + Iss = sqlDataReader.GetFieldValue("Iss", true, true), + Desconto = sqlDataReader.GetFieldValue("Desconto", true, true), + Outros = sqlDataReader.GetFieldValue("Outros", true, true) + }; + Parcela parcela2 = parcela; + num = (fieldValue4 == decimal.Zero ? fieldValue3 : fieldValue4); + parcela2.ValorComDesconto = num; + parcela.Comissao = sqlDataReader.GetFieldValue("ComissaoParcela", true, true); + parcela.ValorRealizado = sqlDataReader.GetFieldValue("ValorRealizado", true, true); + parcela.SubTipo = sqlDataReader.GetFieldValue("SubTipo", true, true); + parcela.IdEmpresa = num4; + Parcela parcela3 = parcela; + Documento documento = new Documento() + { + Id = sqlDataReader.GetFieldValue("IdDocumento", true, true) + }; + Documento documento1 = documento; + Controle controle = new Controle() + { + Id = fieldValue2, + IdEmpresa = num4 + }; + Controle controle1 = controle; + Cliente cliente = new Cliente() + { + Id = sqlDataReader.GetFieldValue("IdCliente", true, true), + Nome = sqlDataReader.GetFieldValue("NomeCliente", true, true), + Pasta = sqlDataReader.GetFieldValue("PastaCliente", true, true) + }; + bool? nullable1 = sqlDataReader.GetFieldValue("MalaDireta", true, true); + cliente.MalaDireta = new bool?(nullable1.GetValueOrDefault(true)); + controle1.Cliente = cliente; + Controle controle2 = controle; + Ramo ramo = new Ramo() + { + Id = sqlDataReader.GetFieldValue("IdRamo", true, true), + Nome = sqlDataReader.GetFieldValue("NomeRamo", true, true) + }; + controle2.Ramo = ramo; + Controle controle3 = controle; + Seguradora seguradora = new Seguradora() + { + Id = sqlDataReader.GetFieldValue("IdCiaSeg", true, true), + Nome = sqlDataReader.GetFieldValue("NomeCia", true, true), + NomeSocial = sqlDataReader.GetFieldValue("NomeSocial", true, true) + }; + controle3.Seguradora = seguradora; + Controle controle4 = controle; + flag = await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "IdProduto"); + Controle controle5 = controle4; + if (flag) + { + produto = null; + } + else + { + produto = new Produto(); + ((DomainBase)produto).Id = sqlDataReader.GetFieldValue("IdProduto", true, true); + ((Produto)produto).Nome = sqlDataReader.GetFieldValue("NomeProduto", true, true); + } + controle5.Produto = (Produto)produto; + documento1.Controle = controle; + Documento documento2 = documento; + bool flag3 = await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "IdEstipulante"); + Documento documento3 = documento2; + if (flag3) + { + estipulante = null; + } + else + { + estipulante = new Estipulante(); + ((DomainBase)estipulante).Id = sqlDataReader.GetFieldValue("IdEstipulante", true, true); + ((Estipulante)estipulante).Nome = sqlDataReader.GetFieldValue("NomeEstipulante", true, true); + } + documento3.Estipulante1 = (Estipulante)estipulante; + Documento documento4 = documento; + bool flag4 = await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "IdStatus"); + Documento documento5 = documento4; + if (flag4) + { + statu = null; + } + else + { + statu = new Status(); + ((DomainBase)statu).Id = sqlDataReader.GetFieldValue("IdStatus", true, true); + ((Status)statu).Nome = sqlDataReader.GetFieldValue("NomeStatus", true, true); + } + documento5.Status = (Status)statu; + documento.AdicionalComiss = sqlDataReader["AdicionalComiss"].ToString() == "1"; + documento.Apolice = sqlDataReader.GetFieldValue("Apolice", true, true); + Documento documento6 = documento; + str = (tipoRecebimento == TipoRecebimento.Parcela ? sqlDataReader.GetFieldValue("Endosso", true, true) : string.Concat("F ", sqlDataReader.GetFieldValue("Fatura", true, true))); + documento6.Endosso = str; + Documento documento7 = documento; + num1 = (tipoRecebimento == TipoRecebimento.Parcela ? sqlDataReader.GetFieldValue("ComissaoDocumento", true, true) : sqlDataReader.GetFieldValue("ComissaoParcela", true, true)); + documento7.Comissao = num1; + documento.NegocioCorretora = new NegocioCorretora?(negocioCorretora1); + Documento nullable2 = documento; + Negocio? nullable3 = sqlDataReader.GetFieldValue("Negocio", true, true); + nullable2.Negocio = new Negocio?(nullable3.GetValueOrDefault(Negocio.Proprio)); + Documento documento8 = documento; + num2 = (tipoRecebimento == TipoRecebimento.Parcela ? sqlDataReader.GetFieldValue("PremioLiquido", true, true) : sqlDataReader.GetFieldValue("PremioLiquidoFatura", true, true)); + documento8.PremioLiquido = num2; + Documento documento9 = documento; + num3 = (tipoRecebimento == TipoRecebimento.Parcela ? sqlDataReader.GetFieldValue("PremioTotal", true, true) : sqlDataReader.GetFieldValue("PremioTotalFatura", true, true)); + documento9.PremioTotal = num3; + documento.PremioAdicional = sqlDataReader.GetFieldValue("PremioAdicional", true, true); + Documento documento10 = documento; + if (tipoRecebimento == TipoRecebimento.Parcela) + { + dateTime = sqlDataReader.GetFieldValue("VigenciaInicial", true, true); + } + else + { + DateTime? nullable4 = sqlDataReader.GetFieldValue("VigenciaInicialFatura", true, true); + dateTime = (nullable4.HasValue ? nullable4.GetValueOrDefault() : sqlDataReader.GetFieldValue("Vencimento", true, true)); + } + documento10.Vigencia1 = dateTime; + Documento documento11 = documento; + nullable = (tipoRecebimento == TipoRecebimento.Parcela ? sqlDataReader.GetFieldValue("VigenciaFinal", true, true) : sqlDataReader.GetFieldValue("VigenciaFinalFatura", true, true)); + documento11.Vigencia2 = nullable; + documento.Situacao = sqlDataReader.GetFieldValue("Situacao", true, true); + documento.Tipo = sqlDataReader.GetFieldValue("Tipo", true, true); + documento.TipoRecebimento = new TipoRecebimento?(tipoRecebimento); + documento.DataControle = sqlDataReader.GetFieldValue("DataControleDocumento", true, true); + documento.Pasta = sqlDataReader.GetFieldValue("PastaDocumento", true, true); + documento.ItensAtivo = items; + parcela3.Documento = documento; + observableCollection = parcela; + parcela3 = null; + documento1 = null; + controle4 = null; + controle = null; + documento2 = null; + documento4 = null; + documento = null; + parcela = null; + if (observableCollection.Vendedores == null) + { + observableCollection.Vendedores = new ObservableCollection(); + } + parcelas.Add(observableCollection); + items = null; + } + List tipoVendedor = filtro.TipoVendedor; + if (tipoVendedor != null) + { + count1 = tipoVendedor.Count > 0; + } + else + { + count1 = false; + } + if (!count1) + { + List nums = filtro.Vendedores; + if (nums != null) + { + flag1 = nums.Count > 0; + } + else + { + flag1 = false; + } + if (!flag1) + { + long fieldValue5 = sqlDataReader.GetFieldValue("IdVendedorParcela", true, true); + if (fieldValue5 > (long)0) + { + ObservableCollection vendedores1 = observableCollection.Vendedores; + VendedorParcela vendedorParcela = new VendedorParcela() + { + Id = fieldValue5, + ValorRepasse = new decimal?(sqlDataReader.GetFieldValue("ValorRepasse", true, true)), + PorcentagemRepasse = new decimal?(sqlDataReader.GetFieldValue("PorcentagemRepasse", true, true)), + DataPagamento = sqlDataReader.GetFieldValue("DataPagamento", true, true), + DataPrePagamento = sqlDataReader.GetFieldValue("DataPrePagamento", true, true) + }; + TipoVendedor tipoVendedor1 = new TipoVendedor() + { + Id = sqlDataReader.GetFieldValue("IdTipoVendedor", true, true) + }; + vendedorParcela.TipoVendedor = tipoVendedor1; + Vendedor vendedor = new Vendedor() + { + Id = sqlDataReader.GetFieldValue("IdVendedor", true, true), + Nome = sqlDataReader.GetFieldValue("NomeVendedor", true, true) + }; + vendedorParcela.Vendedor = vendedor; + vendedores1.Add(vendedorParcela); + } + } + } + } + } + } + sqlDataReader = null; + List nums1 = filtro.TipoVendedor; + if (nums1 != null) + { + count2 = nums1.Count > 0; + } + else + { + count2 = false; + } + if (!count2) + { + List vendedores2 = filtro.Vendedores; + if (vendedores2 != null) + { + flag2 = vendedores2.Count > 0; + } + else + { + flag2 = false; + } + if (!flag2) + { + goto Label0; + } + } + foreach (Parcela parcela4 in parcelas) + { + parcela = parcela4; + List vendedorParcelas = await this.BuscaVendedoresPorIdParcela(parcela4.Id, parcela4.IdEmpresa, (long)0); + parcela.Vendedores = new ObservableCollection(vendedorParcelas); + parcela = null; + } + Label0: + } + sqlCommand = null; + } + sqlConnection = null; + } + sessionFactory = null; + List parcelas1 = parcelas; + parcelas = null; + condicaos = null; + return parcelas1; + } + + public List FindByVencimento(Filtros filtro) + { + List parcelas; + object connection; + string str = (filtro.Status == null || filtro.Status.Count == 0 ? "" : string.Concat(" AND situacao IN (", string.Join(",", + from v in filtro.Status + select v), ")")); + string str1 = (filtro.Negocio == null || filtro.Negocio.Count == 0 ? "" : string.Concat(" AND NegocioCorretora IN (", string.Join(",", + from v in filtro.Negocio + select v), ")")); + string str2 = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND c.idciaseg IN (", string.Join(",", + from v in filtro.Seguradoras + select v), ")")); + string str3 = (filtro.Ramos == null || filtro.Ramos.Count == 0 ? "" : string.Concat(" AND c.idramo IN (", string.Join(",", + from v in filtro.Ramos + select v), ")")); + string str4 = (filtro.Produtos == null || filtro.Produtos.Count == 0 ? "" : string.Concat(" AND c.idproduto IN (", string.Join(",", + from v in filtro.Produtos + select v), ")")); + string str5 = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? "" : string.Concat(" AND vp.idvendedor IN (", string.Join(",", + from v in filtro.Vendedores + select v), ")")); + string str6 = (filtro.Estipulantes == null || filtro.Estipulantes.Count == 0 ? "" : string.Concat(" AND d.idestipulante IN (", string.Join(",", + from v in filtro.Estipulantes + select v), ")")); + string str7 = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", filtro.IdEmpresa)); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + DataTable dataTable = new DataTable(); + DataTable dataTable1 = new DataTable(); + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + Auxiliar.CriarAuxiliar(sqlCommand, false); + string str8 = "SELECT DISTINCT cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome as cliente, d.idcontrole, p.idparcela as id, f.numfatura as fatura, f.vigenciai as vigenciai, f.vigenciaf as vigenciaf, p.parcela, p.datarec as recebimento, p.vencto as vencimento, ISNULL(p.vlrcomdesc, 0.00) as valorcomdesconto, ISNULL(p.vlrcomiss, 0.00) as valorcomissao, p.iddocumento, d.contrato as apolice, d.aditamento as endosso, d.idnegocio, d.situacao, d.vigencia1 as vigenciainicial, d.vigencia2 as vigenciafinal, ISNULL(p.valor, 0.00) as valor, ISNULL(p.valorlf, 0.00) as valorliquidofatura, ISNULL(p.StatusPagamento, 0) AS StatusPagamento, ISNULL(p.IdParcelaPendente, 0) AS IdParcelaPendente, ISNULL(d.pr_total, 0.00) as total, ISNULL(d.pr_liq, 0.00) as liquido, d.pr_adic as adicional, d.adinacomis as adinacomiss, ISNULL(d.com01, 0.00) as comissao, ISNULL(p.comiss, 0.00) as comiss, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, vp.idvendedor, d.idestipulante, d.tiporecebimento FROM parcela p INNER JOIN documento d on d.iddocumento = p.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente OUTER APPLY (SELECT TOP 1 idvendedor FROM vendedorparcela vp WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor = 1) vp LEFT OUTER JOIN fatura f on f.idparcela = p.idparcela WHERE (d.excluido IS NULL OR d.excluido = 0)"; + string str9 = "SELECT DISTINCT idparcela as id, idvendedor, vlrrep as valorrepasse, vrep as porcentagemrepasse, datapgt as datapagamento, dataprepagto as dataprepagamento FROM vendedorparcela vp WHERE 1=1 "; + sqlCommand.CommandText = string.Format("{0} {1} AND p.vencto >= '{2:yyyy-MM-dd}' AND p.vencto <= '{3:yyyy-MM-dd}' {4} {5} {6} {7} {8} {9} {10}", new object[] { str8, str7, filtro.Inicio, filtro.Fim, str, str1, str2, str3, str4, str6, str5 }); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + if (dataTable.Rows.Count != 0) + { + string str10 = string.Concat(" AND vp.idparcela IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); + sqlCommand.CommandText = string.Concat(str9, " ", str10); + using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) + { + sqlDataAdapter1.SelectCommand = sqlCommand; + sqlDataAdapter1.Fill(dataTable1); + goto Label0; + } + } + else + { + parcelas = new List(); + } + } + } + return parcelas; + Label0: + return dataTable.AsEnumerable().ToList().Select((DataRow x) => { + decimal? nullable3; + decimal valueOrDefault; + decimal num; + Parcela parcela = new Parcela() + { + Id = x.Field("id"), + IdEmpresa = x.Field("idempresa"), + NumeroParcela = int.Parse(x.Field("parcela").ToString()), + DataRecebimento = x.Field("recebimento") + }; + DateTime? nullable4 = x.Field("vencimento"); + parcela.Vencimento = (nullable4.HasValue ? nullable4.GetValueOrDefault() : DateTime.MinValue); + parcela.ValorComDesconto = (x.Field("valorcomdesconto") == null || x.Field("valorcomdesconto") == decimal.Zero ? (x.Field("valorcomissao") == null ? decimal.Zero : x.Field("valorcomissao")) : x.Field("valorcomdesconto")); + parcela.Comissao = x.Field("comiss"); + parcela.Valor = x.Field("valor"); + parcela.StatusPagamento = new StatusPagamento?((x.Field("StatusPagamento") == null ? StatusPagamento.All : (StatusPagamento)Enum.Parse(typeof(StatusPagamento), x.Field("StatusPagamento").ToString()))); + parcela.IdParcelaPendente = x.Field("IdParcelaPendente").GetValueOrDefault(); + IEnumerable list = + from v in dataTable1.AsEnumerable().ToList() + where v.Field("id") == x.Field("id") + select v; + Func u003cu003e9_2810 = ParcelaRepository.u003cu003ec.u003cu003e9__28_10; + if (u003cu003e9_2810 == null) + { + u003cu003e9_2810 = (DataRow v) => { + DateTime? nullable; + DateTime? nullable1; + DateTime? nullable2; + VendedorParcela vendedorParcela = new VendedorParcela() + { + Vendedor = Auxiliar.Vendedores.FirstOrDefault((Vendedor p) => p.Id == v.Field("idvendedor")), + ValorRepasse = new decimal?((v.Field("valorrepasse") == null ? decimal.Zero : v.Field("valorrepasse"))), + PorcentagemRepasse = new decimal?((v.Field("porcentagemrepasse") == null ? decimal.Zero : v.Field("porcentagemrepasse"))) + }; + if (v.Field("datapagamento") == null) + { + nullable = null; + nullable1 = nullable; + } + else + { + nullable1 = v.Field("datapagamento"); + } + vendedorParcela.DataPagamento = nullable1; + if (v.Field("dataprepagamento") == null) + { + nullable = null; + nullable2 = nullable; + } + else + { + nullable2 = v.Field("dataprepagamento"); + } + vendedorParcela.DataPrePagamento = nullable2; + return vendedorParcela; + }; + ParcelaRepository.u003cu003ec.u003cu003e9__28_10 = u003cu003e9_2810; + } + parcela.Vendedores = new ObservableCollection(list.Select(u003cu003e9_2810).ToList()); + Documento documento = new Documento() + { + Controle = new Controle() + { + IdEmpresa = x.Field("idempresa"), + Cliente = new Cliente() + { + Id = x.Field("idcliente"), + Nome = x.Field("cliente"), + IdEmpresa = x.Field("idempresa"), + MalaDireta = new bool?(x.Field("MalaDireta").GetValueOrDefault(true)) + }, + Seguradora = (x.Field("idseguradora") != null ? Auxiliar.Seguradoras.FirstOrDefault((Seguradora p) => p.Id == x.Field("idseguradora")) : null), + Ramo = (x.Field("idramo") != null ? Auxiliar.Ramos.FirstOrDefault((Ramo p) => p.Id == x.Field("idramo")) : null), + Produto = (x.Field("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault((Produto p) => p.Id == x.Field("idproduto")) : null) + }, + AdicionalComiss = x.Field("adinacomiss") == "1", + Apolice = x.Field("apolice"), + Endosso = (x.Field("tiporecebimento").ToString() == "1" ? x.Field("endosso") : string.Concat("F ", x.Field("fatura"))), + Comissao = (x.Field("tiporecebimento").ToString() == "1" ? x.Field("comissao") : x.Field("comiss")), + Negocio = new Negocio?((x.Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field("idnegocio").ToString()))) + }; + if (x.Field("tiporecebimento").ToString() == "1") + { + nullable3 = x.Field("liquido"); + valueOrDefault = nullable3.GetValueOrDefault(); + } + else + { + nullable3 = x.Field("valorliquidofatura"); + valueOrDefault = nullable3.GetValueOrDefault(); + } + documento.PremioLiquido = valueOrDefault; + if (x.Field("tiporecebimento").ToString() == "1") + { + nullable3 = x.Field("total"); + num = nullable3.GetValueOrDefault(); + } + else + { + nullable3 = x.Field("valor"); + num = nullable3.GetValueOrDefault(); + } + documento.PremioTotal = num; + nullable3 = x.Field("adicional"); + documento.PremioAdicional = nullable3.GetValueOrDefault(); + documento.Vigencia1 = (x.Field("tiporecebimento").ToString() == "1" ? x.Field("vigenciainicial") : x.Field("vigenciai")); + documento.Vigencia2 = (x.Field("tiporecebimento").ToString() == "1" ? x.Field("vigenciafinal") : x.Field("vigenciaf")); + documento.VendedorPrincipal = (x.Field("idvendedor") != null ? Auxiliar.Vendedores.FirstOrDefault((Vendedor p) => p.Id == x.Field("idvendedor")) : null); + documento.Estipulante1 = (x.Field("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault((Estipulante p) => p.Id == x.Field("idestipulante")) : null); + documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()); + documento.Tipo = x.Field("tipo"); + parcela.Documento = documento; + return parcela; + }).ToList(); + } + + public List FindByVigencia(Filtros filtro) + { + return new List(); + } + + public List FindDocumentId(List ids) + { + List nums; + object connection; + if (ids == null || ids.Count == 0) + { + return ids; + } + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + DataTable dataTable = new DataTable(); + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + string str = string.Concat(" idparcela IN (", string.Join(",", ids), ")"); + sqlCommand.CommandText = string.Concat("SELECT iddocumento FROM parcela p WHERE ", str); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + if (dataTable.Rows.Count != 0) + { + return dataTable.AsEnumerable().Select((DataRow x) => x.Field("iddocumento")).ToList(); + } + else + { + nums = new List(); + } + } + } + return nums; + } + + public List FindNumFatura(string numero) + { + List documentos; + object connection; + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + DataTable dataTable = new DataTable(); + DataTable dataTable1 = new DataTable(); + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandTimeout = 15000; + Auxiliar.CriarAuxiliar(sqlCommand, false); + string str = string.Concat("SELECT DISTINCT cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome as cliente, d.idcontrole, p.idparcela as id, p.iddocumento, d.contrato as apolice, f.numfatura as fatura, f.emissao, d.idnegocio, d.situacao, f.vigenciai as vigenciainicial, f.vigenciaf as vigenciafinal, ISNULL(p.valor, 0.00) as total, ISNULL(p.valorlf, 0.00) as liquido, 0.00 as adicional, '0' as adinacomiss, ISNULL(p.comiss, 0.00) as comissao, c.idramo, c.idciaseg as idseguradora, c.idproduto, 2 as tipo, vp.idvendedor, d.idestipulante, d.idnegocio, d.negociocorretora, d.datacontrole, d.idstatus, p.datacontrole as dataparcelacontrole, p.cri_data, d.banco, d.agencia, d.conta, d.pasta, d.propassinada FROM fatura f INNER JOIN parcela p on p.idparcela = f.idparcela INNER JOIN documento d on d.iddocumento = p.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente INNER JOIN vendedorparcela vp on vp.idparcela = p.idparcela WHERE (d.excluido IS NULL OR d.excluido = 0) AND NUMFATURA ='", numero, "'"); + string str1 = "SELECT DISTINCT idparcela as id, idvendedor FROM vendedorparcela vp WHERE 1=1 "; + sqlCommand.CommandText = str ?? ""; + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + if (dataTable.Rows.Count != 0) + { + string str2 = string.Concat(" AND vp.idparcela IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); + sqlCommand.CommandText = string.Concat(str1, " ", str2); + using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) + { + sqlDataAdapter1.SelectCommand = sqlCommand; + sqlDataAdapter1.Fill(dataTable1); + goto Label0; + } + } + else + { + documentos = new List(); + } + } + } + return documentos; + Label0: + return dataTable.AsEnumerable().ToList().Select((DataRow x) => { + Func func2 = null; + Documento documento = new Documento() + { + Id = x.Field("iddocumento"), + Controle = new Controle() + { + Id = x.Field("idcontrole"), + IdEmpresa = x.Field("idempresa"), + Cliente = new Cliente() + { + Nome = x.Field("cliente"), + Id = x.Field("idcliente"), + IdEmpresa = x.Field("idempresa"), + MalaDireta = new bool?(x.Field("MalaDireta").GetValueOrDefault(true)) + }, + Seguradora = (x.Field("idseguradora") != null ? Auxiliar.Seguradoras.FirstOrDefault((Seguradora p) => p.Id == x.Field("idseguradora")) : null), + Ramo = (x.Field("idramo") != null ? Auxiliar.Ramos.FirstOrDefault((Ramo p) => p.Id == x.Field("idramo")) : null), + Produto = (x.Field("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault((Produto p) => p.Id == x.Field("idproduto")) : null) + }, + Pasta = x.Field("Pasta"), + TipoRecebimento = new TipoRecebimento?(TipoRecebimento.Fatura), + AdicionalComiss = false, + Apolice = x.Field("apolice"), + Endosso = x.Field("fatura"), + Comissao = x.Field("comissao"), + NegocioCorretora = new NegocioCorretora?((x.Field("negociocorretora") == null ? ((TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()) != TipoSeguro.Renovacao || x.Field("idnegocio") == null || x.Field("idnegocio") != (long)1 ? NegocioCorretora.Novo : NegocioCorretora.Proprio) : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), x.Field("negociocorretora").ToString()))), + Negocio = new Negocio?((x.Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field("idnegocio").ToString()))) + }; + decimal? nullable = x.Field("liquido"); + documento.PremioLiquido = nullable.GetValueOrDefault(); + nullable = x.Field("total"); + documento.PremioTotal = nullable.GetValueOrDefault(); + DateTime? nullable1 = x.Field("vigenciainicial"); + documento.Vigencia1 = (nullable1.HasValue ? nullable1.GetValueOrDefault() : DateTime.MinValue); + documento.Vigencia2 = x.Field("vigenciafinal"); + documento.Emissao = x.Field("emissao"); + documento.VendedorPrincipal = (x.Field("idvendedor") != null ? Auxiliar.Vendedores.FirstOrDefault((Vendedor p) => p.Id == x.Field("idvendedor")) : null); + documento.Estipulante1 = (x.Field("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault((Estipulante p) => p.Id == x.Field("idestipulante")) : null); + documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()); + documento.Vendedores = Auxiliar.Vendedores.Where((Vendedor v) => { + List list = dataTable1.AsEnumerable().ToList(); + Func u003cu003e9_9 = func2; + if (u003cu003e9_9 == null) + { + Func func = (DataRow d) => d.Field("id") == x.Field("id"); + Func func1 = func; + func2 = func; + u003cu003e9_9 = func1; + } + IEnumerable dataRows = list.Where(u003cu003e9_9); + Func u003cu003e9_2210 = ParcelaRepository.u003cu003ec.u003cu003e9__22_10; + if (u003cu003e9_2210 == null) + { + u003cu003e9_2210 = (DataRow d) => d.Field("idvendedor"); + ParcelaRepository.u003cu003ec.u003cu003e9__22_10 = u003cu003e9_2210; + } + return dataRows.Select(u003cu003e9_2210).ToList().Contains(v.Id); + }).ToList(); + documento.Tipo = x.Field("tipo"); + documento.DataControle = x.Field("dataparcelacontrole"); + documento.Status = (x.Field("idstatus") != null ? Auxiliar.StatusApolice.FirstOrDefault((Status p) => p.Id == x.Field("idstatus")) : null); + documento.DataCriacao = x.Field("cri_data"); + documento.Banco = new Banco() + { + Nome = x.Field("banco") + }; + documento.Agencia = x.Field("agencia"); + documento.Conta = x.Field("conta"); + documento.PropostaAssinada = (x.Field("propassinada") == null ? false : x.Field("propassinada") == "1"); + return documento; + }).ToList(); + } + + public bool FindParcel(long id) + { + bool flag; + object connection; + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + DataTable dataTable = new DataTable(); + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + Auxiliar.CriarAuxiliar(sqlCommand, false); + string str = "SELECT DISTINCT c.idcliente, d.idcontrole, d.iddocumento as id, d.contrato as apolice, d.emissao, d.situacao, d.vigencia1 as vigenciainicial, d.vigencia2 as vigenciafinal, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, d.idestipulante, d.idnegocio, d.datacontrole, d.idstatus, d.tiporecebimento, p.idparcela, pe.idparcela AS idParcelaParcelaExtrato, p.datacred FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN parcela p ON p.iddocumento = d.iddocumento INNER JOIN parcelaextrato pe ON pe.iddocumento = d.iddocumento WHERE (d.excluido IS NULL OR d.excluido = 0) "; + DateTime networkTime = Funcoes.GetNetworkTime(); + sqlCommand.CommandText = string.Format("{0} AND (d.vigencia2 IS NULL AND d.situacao IN (1,2) OR d.vigencia2 >= '{1:yyyy-MM-dd}') AND DATALENGTH(ISNULL( d.contrato, '' )) > 0 AND d.iddocumento in ({2}) AND pe.idparcela = p.idparcela", str, networkTime.Date, id); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + bool flag1 = false; + foreach (DataRow row in dataTable.Rows) + { + string str1 = string.Format("{0}", row["datacred"]); + flag1 = (string.Format("{0}", row["idparcela"]) != string.Format("{0}", row["idParcelaParcelaExtrato"]) ? false : !string.IsNullOrEmpty(str1)); + } + flag = flag1; + } + } + return flag; + } + + public Parcela Merge(Parcela parcela) + { + ParcelaDb parcelaDb = ApplicationMapper.Mapper.Map(parcela); + if (parcelaDb.IdEmpresa == 0) + { + parcelaDb.IdEmpresa = (long)1; + } + base.Merge(parcelaDb); + if (parcelaDb.Documento.TipoRecebimento.GetValueOrDefault() == TipoRecebimento.Parcela) + { + return ApplicationMapper.Mapper.Map(parcelaDb); + } + FaturaDb fatura = this._unitOfWork.Query().FirstOrDefault((FaturaDb x) => x.Parcela.Id == parcelaDb.Id) ?? new FaturaDb(); + fatura.Parcela = parcelaDb; + fatura.Fatura = parcelaDb.Fatura; + FaturaDb faturaDb = fatura; + DateTime? vigenciaIncial = parcelaDb.VigenciaIncial; + faturaDb.VigenciaInicial = (vigenciaIncial.HasValue ? vigenciaIncial : fatura.VigenciaInicial); + FaturaDb faturaDb1 = fatura; + vigenciaIncial = parcelaDb.VigenciaFinal; + faturaDb1.VigenciaFinal = (vigenciaIncial.HasValue ? vigenciaIncial : fatura.VigenciaFinal); + FaturaDb faturaDb2 = fatura; + vigenciaIncial = parcelaDb.Emissao; + faturaDb2.Emissao = (vigenciaIncial.HasValue ? vigenciaIncial : fatura.Emissao); + if (fatura.Id != 0) + { + this._unitOfWork.Repository().Merge(fatura); + } + else + { + this._unitOfWork.Repository().SaveOrUpdate(fatura); + } + return ApplicationMapper.Mapper.Map(parcelaDb); + } + + public List PrevisaoPagamentoComissao(Filtros filtro) + { + object connection; + string str2 = (filtro.Status == null || filtro.Status.Count == 0 ? "" : string.Concat(" AND d.situacao IN (", string.Join(",", + from v in filtro.Status + select v), ")")); + string str3 = (filtro.Negocio == null || filtro.Negocio.Count == 0 ? "" : string.Concat(" AND NegocioCorretora IN (", string.Join(",", + from v in filtro.Negocio + select v), ")")); + string str4 = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND c.idciaseg IN (", string.Join(",", + from v in filtro.Seguradoras + select v), ")")); + string str5 = (filtro.Ramos == null || filtro.Ramos.Count == 0 ? "" : string.Concat(" AND c.idramo IN (", string.Join(",", + from v in filtro.Ramos + select v), ")")); + string str6 = (filtro.Produtos == null || filtro.Produtos.Count == 0 ? "" : string.Concat(" AND c.idproduto IN (", string.Join(",", + from v in filtro.Produtos + select v), ")")); + string str7 = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? " AND vp.idvendedor IS NOT NULL " : string.Concat(" AND vp.idvendedor IN (", string.Join(",", + from v in filtro.Vendedores + select v), ")")); + string str8 = (filtro.TipoVendedor == null || filtro.TipoVendedor.Count == 0 ? " AND vp.idtipovendedor = 1 " : string.Concat(" AND vp.idtipovendedor IN (", string.Join(",", + from v in filtro.TipoVendedor + select v), ")")); + string str9 = (filtro.Estipulantes == null || filtro.Estipulantes.Count == 0 ? "" : string.Concat(" AND d.idestipulante IN (", string.Join(",", + from v in filtro.Estipulantes + select v), ")")); + string str10 = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", filtro.IdEmpresa)); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + DataTable dataTable = new DataTable(); + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandTimeout = 15000; + Auxiliar.CriarAuxiliar(sqlCommand, false); + sqlCommand.CommandText = string.Concat("SELECT DISTINCT d.tipo, f.NUMFATURA, f.VIGENCIAI, vp.idvendedorparcela, vp.idvendedor, cl.nome AS cliente, d.situacao, d.contrato, d.VIGENCIA1, d.aditamento, c.idciaseg, c.idramo, p.parcela, ISNULL(v.desconto, 0) as desconto, p.vencto, ISNULL(vp.vlrrep, 0) as vlrliquido, ISNULL(d.pr_liq, 0) as pr_liq, ISNULL(p.VALORLF, 0) as valorlf, ISNULL(p.vlrcomiss, 0) as vlrcomiss, p.idsubtipo, d.n_parc, d.tiporecebimento FROM controle c INNER JOIN cliente cl on cl.idcliente = c.idcliente INNER JOIN documento d on d.idcontrole = c.idcontrole INNER JOIN parcela p on p.iddocumento = d.iddocumento INNER JOIN vendedorparcela vp on vp.idparcela = p.idparcela INNER JOIN vendedor v on v.idvendedor = vp.idvendedor LEFT OUTER JOIN fatura f on f.idparcela = p.idparcela ", string.Format("WHERE (d.excluido IS NULL OR d.excluido != 1) AND v.corretora != '1' AND vp.datapgt IS NULL AND vp.vlrrep != 0 AND (d.tiporecebimento = '1' AND ISNULL(d.com01, 0.00) > 0 OR d.tiporecebimento = '2') {0} {1} {2} {3} {4} {5} {6} {7} {8} AND p.vencto >= '{9:yyyy-MM-dd}' AND p.vencto <= '{10:yyyy-MM-dd}';", new object[] { str10, str7, str2, str3, str4, str5, str6, str8, str9, filtro.Inicio, filtro.Fim })); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + } + } + return dataTable.AsEnumerable().ToList().Select((DataRow x) => { + string nome; + string str; + string nome1; + string str1; + PrevisaoPagamento previsaoPagamento = new PrevisaoPagamento() + { + Nome = x.Campo("cliente"), + Apolice = (x.IsNull("tiporecebimento") ? "" : (x.Campo("tiporecebimento") == "1" ? x.Campo("contrato") : x.Campo("NUMFATURA"))), + Endosso = (x.Campo("tiporecebimento") == "1" ? x.Campo("aditamento") : ""), + Status = x.Campo("situacao").GetDescription(), + VigenciaInicial = (x.Campo("tiporecebimento") == "1" ? x.Campo("VIGENCIA1") : x.Campo("VIGENCIAI")), + TipoDocumento = (x.IsNull("tiporecebimento") ? "" : (x.Campo("tiporecebimento") == "2" ? "FATURA" : (x.Campo("tipo") == "0" ? "APÓLICE" : "ENDOSSO"))) + }; + Seguradora seguradora = Auxiliar.Seguradoras.Find((Seguradora p) => p.Id == x.Campo("idciaseg")); + if (seguradora != null) + { + nome = seguradora.Nome; + } + else + { + nome = null; + } + previsaoPagamento.NomeSeguradora = nome; + Ramo ramo = Auxiliar.Ramos.Find((Ramo p) => p.Id == x.Campo("idramo")); + if (ramo != null) + { + str = ramo.Nome; + } + else + { + str = null; + } + previsaoPagamento.NomeRamo = str; + previsaoPagamento.PremioLiquido = (x.Campo("tiporecebimento") == "1" ? x.Campo("pr_liq") : x.Campo("valorlf")); + previsaoPagamento.Parcela = (x.Campo("idsubtipo") > (long)1 ? "ESPECIAL" : (x.Campo("tiporecebimento") == "1" ? string.Concat(x.Campo("parcela").PadLeft(2, '0'), " DE ", x.Campo("n_parc")) : x.Campo("parcela").PadLeft(2, '0'))); + previsaoPagamento.VencimentoParcela = x.Campo("vencto"); + previsaoPagamento.RepasseLiquido = x.Campo("vlrliquido") * (decimal.One - (x.Campo("desconto") > decimal.One ? x.Campo("desconto") * new decimal(1, 0, 0, false, 2) : x.Campo("desconto"))); + previsaoPagamento.Repasse = x.Campo("vlrliquido"); + previsaoPagamento.Vendedor = Auxiliar.Vendedores.Find((Vendedor p) => p.Id == x.Campo("idvendedor")); + Seguradora seguradora1 = Auxiliar.Seguradoras.Find((Seguradora p) => p.Id == x.Campo("idciaseg")); + if (seguradora1 != null) + { + nome1 = seguradora1.Nome; + } + else + { + nome1 = null; + } + previsaoPagamento.Seguradora = nome1; + Ramo ramo1 = Auxiliar.Ramos.Find((Ramo p) => p.Id == x.Campo("idramo")); + if (ramo1 != null) + { + str1 = ramo1.Nome; + } + else + { + str1 = null; + } + previsaoPagamento.Ramo = str1; + return previsaoPagamento; + }).ToList(); + } + + public Parcela SaveOrUpdate(Parcela parcela) + { + ParcelaDb parcelaDb = ApplicationMapper.Mapper.Map(parcela); + if (parcelaDb.IdEmpresa == 0) + { + parcelaDb.IdEmpresa = (long)1; + } + this.SaveOrUpdate(parcelaDb); + if (parcelaDb.Documento.TipoRecebimento.GetValueOrDefault() == TipoRecebimento.Parcela) + { + return ApplicationMapper.Mapper.Map(parcelaDb); + } + FaturaDb faturaDb = new FaturaDb() + { + Parcela = parcelaDb, + Fatura = parcelaDb.Fatura, + VigenciaInicial = parcelaDb.VigenciaIncial, + VigenciaFinal = parcelaDb.VigenciaFinal, + Emissao = parcelaDb.Emissao + }; + this._unitOfWork.Repository().SaveOrUpdate(faturaDb); + return ApplicationMapper.Mapper.Map(parcelaDb); + } + + public int[] SincronizarPendencia(DateTime date, List ids = null) + { + // + // Current member / type: System.Int32[] Gestor.Infrastructure.Repository.Logic.ParcelaRepository::SincronizarPendencia(System.DateTime,System.Collections.Generic.List`1) + // File path: C:\AggerSeguros\Lib\Gestor.Infrastructure.dll + // + // Product version: 0.0.0.0 + // Exception in: System.Int32[] SincronizarPendencia(System.DateTime,System.Collections.Generic.List) + // + // An item with the same key has already been added. Key: Label0 + // at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior) + // at System.Collections.Generic.Dictionary`2.System.Collections.Generic.ICollection>.Add(KeyValuePair`2 keyValuePair) + // at Telerik.JustDecompiler.Common.Extensions.AddRange[TKey,TValue](IDictionary`2 self, IDictionary`2 source) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Common\Extensions.cs:line 101 + // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.AnonymousDelegateRebuilder.VisitObjectCreationExpression(ObjectCreationExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 332 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit[TCollection,TElement](TCollection original) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 312 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitMethodInvocationExpression(MethodInvocationExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 500 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitExpressionStatement(ExpressionStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 384 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit[TCollection,TElement](TCollection original) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 312 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitBlockStatement(BlockStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 338 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitIfStatement(IfStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 363 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit[TCollection,TElement](TCollection original) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 312 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitBlockStatement(BlockStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 338 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitTryStatement(TryStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 483 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit[TCollection,TElement](TCollection original) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 312 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitBlockStatement(BlockStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 338 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitTryStatement(TryStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 483 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 + // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.AnonymousDelegateRebuilder.Match(BlockStatement theBlock, Int32 index) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 74 + // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.VisitBlockStatement(BlockStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 33 + // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.Process(DecompilationContext context, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 23 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61 + // at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 133 + // + // mailto: JustDecompilePublicFeedback@telerik.com + + } + + public bool Update(List detalhes, bool desabilitaAproximação) + { + // + // Current member / type: System.Boolean Gestor.Infrastructure.Repository.Logic.ParcelaRepository::Update(System.Collections.Generic.List`1,System.Boolean) + // File path: C:\AggerSeguros\Lib\Gestor.Infrastructure.dll + // + // Product version: 0.0.0.0 + // Exception in: System.Boolean Update(System.Collections.Generic.List,System.Boolean) + // + // An item with the same key has already been added. Key: Label0 + // at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior) + // at System.Collections.Generic.Dictionary`2.System.Collections.Generic.ICollection>.Add(KeyValuePair`2 keyValuePair) + // at Telerik.JustDecompiler.Common.Extensions.AddRange[TKey,TValue](IDictionary`2 self, IDictionary`2 source) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Common\Extensions.cs:line 101 + // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.AnonymousDelegateRebuilder.VisitObjectCreationExpression(ObjectCreationExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 351 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit[TCollection,TElement](TCollection original) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 312 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitMethodInvocationExpression(MethodInvocationExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 500 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitExpressionStatement(ExpressionStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 384 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 + // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.AnonymousDelegateRebuilder.Match(BlockStatement theBlock, Int32 index) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 74 + // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.VisitBlockStatement(BlockStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 33 + // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.Process(DecompilationContext context, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 23 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61 + // at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 133 + // + // mailto: JustDecompilePublicFeedback@telerik.com + + } + + public List UpdateRange(List parcelas) + { + List parcelaDbs = ApplicationMapper.Mapper.Map, List>(parcelas); + parcelaDbs.ForEach((ParcelaDb x) => { + if (x.IdEmpresa == 0) + { + x.IdEmpresa = (long)1; + } + }); + ParcelaRepository parcelaRepository = this; + parcelaDbs.ForEach(new Action(parcelaRepository.Merge)); + return ApplicationMapper.Mapper.Map, List>(parcelaDbs); + } + + private async Task VerificaVendedorPropriaCorretora(List vendedores) + { + bool valueOrDefault; + object connection; + List condicaos = new List(); + Condicao condicao = new Condicao() + { + Campo = "IdVendedor", + Valores = vendedores.CriarValor(), + Grupo = 1, + Operacao = Operacao.Or + }; + condicaos.Add(condicao); + SqlQueryCondition sqlQueryCondition = condicaos.CreateParameters(0); + using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) + { + SessionFactoryImpl sessionFactoryImpl = sessionFactory; + if (sessionFactoryImpl != null) + { + connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = string.Concat("SELECT COUNT(IdVendedor) FROM Vendedor WHERE Corretora = 1 AND ", sqlQueryCondition.Condicao); + sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray()); + int? nullable = (int?)await sqlCommand.ExecuteScalarAsync(); + valueOrDefault = nullable.GetValueOrDefault() > 0; + } + } + } + return valueOrDefault; + } + + private class VinculoParcela + { + public string Apolice + { + get; + set; + } + + public string Endosso + { + get; + set; + } + + public long IdDocumento + { + get; + set; + } + + public long IdParcela + { + get; + set; + } + + public int Parcela + { + get; + set; + } + + public Seguradora Seguradora + { + get; + set; + } + + public int Tipo + { + get; + set; + } + + public VinculoParcela() + { + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PatrimonialRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PatrimonialRepository.cs new file mode 100644 index 0000000..f3b92f0 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PatrimonialRepository.cs @@ -0,0 +1,251 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Helpers; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class PatrimonialRepository : GenericRepository, IPatrimonialRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public PatrimonialRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public void DeleteRange(List ids) + { + List list = ( + from x in base.All() + where ids.Contains(x.Item.Id) + select x).ToList(); + base.DeleteRange(list); + } + + public Patrimonial Find(long id) + { + PatrimonialDb patrimonialDb = base.All().FirstOrDefault((PatrimonialDb x) => x.Item.Id == id) ?? new PatrimonialDb(); + return ApplicationMapper.Mapper.Map(patrimonialDb); + } + + public Patrimonial FindById(long id) + { + PatrimonialDb patrimonialDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(patrimonialDb); + } + + public List FindImobiliaria(string imobiliaria, FiltroStatusDocumento status, List vendedorVinculado) + { + List pesquisaAvancadas; + object connection; + DataTable dataTable = new DataTable(); + DataTable dataTable1 = new DataTable(); + DataTable dataTable2 = new DataTable(); + DataTable dataTable3 = new DataTable(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = string.Concat("SELECT iditem as id FROM resempco WHERE imobiliaria LIKE '%", imobiliaria, "%'"); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + if (dataTable.Rows.Count != 0) + { + string str = string.Concat(" AND iditem IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); + sqlCommand.CommandText = string.Concat("SELECT iddocumento as id, descricao, iditem FROM item WHERE 1=1 ", str); + using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) + { + sqlDataAdapter1.SelectCommand = sqlCommand; + sqlDataAdapter1.Fill(dataTable1); + } + sqlCommand.CommandText = string.Concat("SELECT DISTINCT cl.nome as cliente, c.idcliente, d.idcontrole, d.iddocumento, situacao, vigencia1, vigencia2, proposta, contrato as apolice, aditamento as endosso, CAST(tipo as INTEGER) as tipo FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE d.iddocumento IN (", string.Join(",", dataTable1.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); + using (SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter()) + { + sqlDataAdapter2.SelectCommand = sqlCommand; + sqlDataAdapter2.Fill(dataTable2); + } + string str1 = string.Concat(" AND d.idcontrole IN (", string.Join(",", ( + from x in dataTable2.AsEnumerable().ToList() + select x.Field("idcontrole")).ToList()), ")"); + sqlCommand.CommandText = string.Concat("SELECT DISTINCT vp.idvendedor, d.iddocumento, d.idcontrole, vp.idtipovendedor FROM vendedorparcela vp INNER JOIN documento d on d.iddocumento = vp.iddocumento WHERE 1=1 ", str1); + using (SqlDataAdapter sqlDataAdapter3 = new SqlDataAdapter()) + { + sqlDataAdapter3.SelectCommand = sqlCommand; + sqlDataAdapter3.Fill(dataTable3); + List list = null; + if (vendedorVinculado != null && vendedorVinculado.Count > 0) + { + list = dataTable3.AsEnumerable().Where((DataRow x) => { + List vendedorUsuarios = vendedorVinculado; + Func u003cu003e9_85 = PatrimonialRepository.u003cu003ec.u003cu003e9__8_5; + if (u003cu003e9_85 == null) + { + u003cu003e9_85 = (VendedorUsuario v) => v.Vendedor.Id; + PatrimonialRepository.u003cu003ec.u003cu003e9__8_5 = u003cu003e9_85; + } + return vendedorUsuarios.Select(u003cu003e9_85).Contains(x.Field("idvendedor")); + }).Select((DataRow x) => x.Field("idcontrole")).ToList(); + } + if (list != null && list.Count == 0) + { + return new List(); + } + return Auxiliar.PesquisaAvancada(status, dataTable2, dataTable1, list); + } + } + else + { + pesquisaAvancadas = new List(); + } + } + } + return pesquisaAvancadas; + } + + public List Findlocatario(string imobiliaria, FiltroStatusDocumento status, List vendedorVinculado) + { + List pesquisaAvancadas; + object connection; + bool count; + DataTable dataTable = new DataTable(); + DataTable dataTable1 = new DataTable(); + DataTable dataTable2 = new DataTable(); + DataTable dataTable3 = new DataTable(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = string.Concat(new string[] { "SELECT DISTINCT rec.iditem AS id FROM resempco rec INNER JOIN item i ON i.iditem = rec.iditem INNER JOIN documento d ON i.IDDOCUMENTO = d.IDDOCUMENTO WHERE (rec.locatario LIKE '%", imobiliaria, "%' OR rec.locatario2 LIKE '%", imobiliaria, "%' OR rec.locatario3 LIKE '%", imobiliaria, "%') AND d.excluido != 1;" }); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + if (dataTable.Rows.Count != 0) + { + string str = string.Concat(" AND iditem IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); + sqlCommand.CommandText = string.Concat("SELECT iddocumento as id, descricao, iditem FROM item WHERE 1=1 ", str); + using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) + { + sqlDataAdapter1.SelectCommand = sqlCommand; + sqlDataAdapter1.Fill(dataTable1); + } + sqlCommand.CommandText = string.Concat("SELECT DISTINCT cl.nome as cliente, c.idcliente, d.idcontrole, d.iddocumento, situacao, vigencia1, vigencia2, proposta, contrato as apolice, aditamento as endosso, CAST(tipo as INTEGER) as tipo FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE d.iddocumento IN (", string.Join(",", dataTable1.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); + using (SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter()) + { + sqlDataAdapter2.SelectCommand = sqlCommand; + sqlDataAdapter2.Fill(dataTable2); + } + string str1 = string.Concat(" AND d.idcontrole IN (", string.Join(",", ( + from x in dataTable2.AsEnumerable().ToList() + select x.Field("idcontrole")).ToList()), ")"); + sqlCommand.CommandText = string.Concat("SELECT DISTINCT vp.idvendedor, d.iddocumento, d.idcontrole, vp.idtipovendedor FROM vendedorparcela vp INNER JOIN documento d on d.iddocumento = vp.iddocumento WHERE 1=1 ", str1); + using (SqlDataAdapter sqlDataAdapter3 = new SqlDataAdapter()) + { + sqlDataAdapter3.SelectCommand = sqlCommand; + sqlDataAdapter3.Fill(dataTable3); + goto Label0; + } + } + else + { + pesquisaAvancadas = new List(); + } + } + } + return pesquisaAvancadas; + Label0: + List list = null; + if (vendedorVinculado != null && vendedorVinculado.Count > 0) + { + list = dataTable3.AsEnumerable().Where((DataRow x) => { + List vendedorUsuarios = vendedorVinculado; + Func u003cu003e9_97 = PatrimonialRepository.u003cu003ec.u003cu003e9__9_7; + if (u003cu003e9_97 == null) + { + u003cu003e9_97 = (VendedorUsuario v) => v.Vendedor.Id; + PatrimonialRepository.u003cu003ec.u003cu003e9__9_7 = u003cu003e9_97; + } + return vendedorUsuarios.Select(u003cu003e9_97).Contains(x.Field("idvendedor")); + }).Select((DataRow x) => x.Field("idcontrole")).ToList(); + } + if (vendedorVinculado != null) + { + List vendedorUsuarios1 = vendedorVinculado; + if (vendedorUsuarios1 != null) + { + count = vendedorUsuarios1.Count == 0; + } + else + { + count = false; + } + if (count) + { + list = dataTable2.AsEnumerable().Where((DataRow x) => x.Field("idcontrole").HasValue).Select((DataRow x) => x.Field("idcontrole")).ToList(); + } + } + return Auxiliar.PesquisaAvancada(status, dataTable2, dataTable1, list); + } + + public Patrimonial Merge(Patrimonial patrimonial) + { + PatrimonialDb patrimonialDb = ApplicationMapper.Mapper.Map(patrimonial); + base.Merge(patrimonialDb); + return ApplicationMapper.Mapper.Map(patrimonialDb); + } + + public Patrimonial SaveOrUpdate(Patrimonial patrimonial) + { + PatrimonialDb patrimonialDb = ApplicationMapper.Mapper.Map(patrimonial); + this.SaveOrUpdate(patrimonialDb); + return ApplicationMapper.Mapper.Map(patrimonialDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PerfilEmpresaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PerfilEmpresaRepository.cs new file mode 100644 index 0000000..b32c539 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PerfilEmpresaRepository.cs @@ -0,0 +1,64 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class PerfilEmpresaRepository : GenericRepository, IPerfilEmpresaRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public PerfilEmpresaRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + PerfilEmpresaDb perfilEmpresaDb = base.FindEntityById(id); + if (perfilEmpresaDb == null) + { + return; + } + base.Delete(perfilEmpresaDb); + } + + public PerfilEmpresa Find(long id) + { + PerfilEmpresaDb perfilEmpresaDb = base.All().FirstOrDefault((PerfilEmpresaDb x) => x.Id == id); + return ApplicationMapper.Mapper.Map(perfilEmpresaDb); + } + + public PerfilEmpresa FindByControleId(long id) + { + PerfilEmpresaDb perfilEmpresaDb = ( + from x in base.All() + where x.Controle.Id == id + select x).FirstOrDefault(); + return ApplicationMapper.Mapper.Map(perfilEmpresaDb); + } + + public PerfilEmpresa Merge(PerfilEmpresa perfil) + { + PerfilEmpresaDb perfilEmpresaDb = ApplicationMapper.Mapper.Map(perfil); + base.Merge(perfilEmpresaDb); + return ApplicationMapper.Mapper.Map(perfilEmpresaDb); + } + + public PerfilEmpresa SaveOrUpdate(PerfilEmpresa perfilEmpresa) + { + PerfilEmpresaDb perfilEmpresaDb = ApplicationMapper.Mapper.Map(perfilEmpresa); + this.SaveOrUpdate(perfilEmpresaDb); + return ApplicationMapper.Mapper.Map(perfilEmpresaDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PerfilRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PerfilRepository.cs new file mode 100644 index 0000000..67375a5 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PerfilRepository.cs @@ -0,0 +1,191 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class PerfilRepository : GenericRepository, IPerfilRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public PerfilRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + PerfilDb perfilDb = base.FindEntityById(id); + if (perfilDb == null) + { + return; + } + base.Delete(perfilDb); + } + + public Perfil Find(long id) + { + PerfilDb perfilDb = base.All().FirstOrDefault((PerfilDb x) => x.Id == id); + return ApplicationMapper.Mapper.Map(perfilDb); + } + + public List FindByControleId(long id) + { + List list = ( + from x in base.All() + where x.Controle.Id == id + select x).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public List FindByControleIds(string ids) + { + object connection; + DataTable dataTable = new DataTable(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = string.Concat("SELECT * FROM perfil WHERE idcontrole IN (", ids, ");"); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + } + } + if (dataTable.Rows.Count == 0) + { + return new List(); + } + return dataTable.AsEnumerable().Select((DataRow p) => { + GaragemTrabalhoEstudo? nullable; + bool? nullable1; + GaragemTrabalhoEstudo? nullable2; + GaragemTrabalhoEstudo? nullable3; + bool? nullable4; + bool? nullable5; + bool? nullable6; + Perfil perfil = new Perfil() + { + Cliente = new Cliente() + { + Id = long.Parse(p["idcliente"].ToString()) + }, + Controle = new Controle() + { + Id = long.Parse(p["idcontrole"].ToString()) + }, + Nome = p["nomecompleto"].ToString(), + Cpf = p["cpf"].ToString(), + Nascimento = (string.IsNullOrEmpty(p["datanascimento"].ToString()) ? null : new DateTime?(DateTime.Parse(p["datanascimento"].ToString()))), + EstadoCivil = (string.IsNullOrEmpty(p["estadocivil"].ToString()) ? null : new EstadoCivil?((EstadoCivil)int.Parse(p["estadocivil"].ToString()))), + Sexo = (string.IsNullOrEmpty(p["sexo"].ToString()) ? null : new Sexo?((Sexo)int.Parse(p["sexo"].ToString()))), + Relacao = (string.IsNullOrEmpty(p["relacao"].ToString()) ? null : new Relacao?((Relacao)int.Parse(p["relacao"].ToString()))), + Habilitacao = p["numerohabilitacao"].ToString(), + TempoHabilitacao = (string.IsNullOrEmpty(p["tempohabilitacao"].ToString()) ? null : new TempoHabilitacao?((TempoHabilitacao)int.Parse(p["tempohabilitacao"].ToString()))), + VeiculoResidencia = (string.IsNullOrEmpty(p["veiculosresidencia"].ToString()) ? null : new int?(int.Parse(p["veiculosresidencia"].ToString()))), + GaragemResidencia = (string.IsNullOrEmpty(p["garagemresidencia"].ToString()) ? null : new GaragemResidencia?((GaragemResidencia)int.Parse(p["garagemresidencia"].ToString()))) + }; + if (string.IsNullOrEmpty(p["garagemtrabalho"].ToString())) + { + nullable = null; + nullable2 = nullable; + } + else + { + nullable2 = new GaragemTrabalhoEstudo?((GaragemTrabalhoEstudo)int.Parse(p["garagemtrabalho"].ToString())); + } + perfil.GaragemTrabalho = nullable2; + if (string.IsNullOrEmpty(p["garagemestudo"].ToString())) + { + nullable = null; + nullable3 = nullable; + } + else + { + nullable3 = new GaragemTrabalhoEstudo?((GaragemTrabalhoEstudo)int.Parse(p["garagemestudo"].ToString())); + } + perfil.GaragemEstudo = nullable3; + perfil.TipoResidencia = (string.IsNullOrEmpty(p["tiporesidencia"].ToString()) ? null : new TipoResidencia?((TipoResidencia)int.Parse(p["tiporesidencia"].ToString()))); + perfil.KmMensal = p["quilometragemmensal"].ToString(); + perfil.DistanciaResidenciaTrabalho = (string.IsNullOrEmpty(p["distanciaresidenciatrabalho"].ToString()) ? null : new DistanciaTrabalho?((DistanciaTrabalho)int.Parse(p["distanciaresidenciatrabalho"].ToString()))); + if (string.IsNullOrEmpty(p["usoprofissional"].ToString())) + { + nullable1 = null; + nullable4 = nullable1; + } + else + { + nullable4 = new bool?(p["usoprofissional"].ToString() == "1"); + } + perfil.UsoProfissional = nullable4; + perfil.UsoDependentes = (string.IsNullOrEmpty(p["usodependentes"].ToString()) ? null : new UsoDependetes?((UsoDependetes)int.Parse(p["usodependentes"].ToString()))); + perfil.Ocupacao = (string.IsNullOrEmpty(p["ocupacao"].ToString()) ? null : new Ocupacao?((Ocupacao)int.Parse(p["ocupacao"].ToString()))); + if (string.IsNullOrEmpty(p["segurovida"].ToString())) + { + nullable1 = null; + nullable5 = nullable1; + } + else + { + nullable5 = new bool?(p["segurovida"].ToString() == "1"); + } + perfil.SeguroVida = nullable5; + perfil.EstenderCobertura = (bool?)p["EstenderCobertura"]; + if (string.IsNullOrEmpty(p["isencao"].ToString())) + { + nullable1 = null; + nullable6 = nullable1; + } + else + { + nullable6 = new bool?(p["isencao"].ToString() == "1"); + } + perfil.Isencao = nullable6; + perfil.AntiFurto = (string.IsNullOrEmpty(p["antifurto"].ToString()) ? null : new Antifurto?((Antifurto)int.Parse(p["antifurto"].ToString()))); + return perfil; + }).ToList(); + } + + public Perfil Merge(Perfil perfil) + { + PerfilDb perfilDb = ApplicationMapper.Mapper.Map(perfil); + base.Merge(perfilDb); + return ApplicationMapper.Mapper.Map(perfilDb); + } + + public Perfil SaveOrUpdate(Perfil perfil) + { + PerfilDb perfilDb = ApplicationMapper.Mapper.Map(perfil); + this.SaveOrUpdate(perfilDb); + return ApplicationMapper.Mapper.Map(perfilDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PermissaoArquivoDigitalRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PermissaoArquivoDigitalRepository.cs new file mode 100644 index 0000000..50201a9 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PermissaoArquivoDigitalRepository.cs @@ -0,0 +1,54 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class PermissaoArquivoDigitalRepository : GenericRepository, IPermissaoArquivoDigitalRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public PermissaoArquivoDigitalRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public PermissaoArquivoDigital FindByPermissao(long id, TipoArquivoDigital tela) + { + PermissaoArquivoDigitalDb permissaoArquivoDigitalDb = base.All().FirstOrDefault((PermissaoArquivoDigitalDb x) => x.Usuario.Id == id && (int)x.Tela == (int)tela); + return ApplicationMapper.Mapper.Map(permissaoArquivoDigitalDb); + } + + public List FindByUsuario(long id) + { + List list = this._unitOfWork.Session.CreateQuery(string.Format("from PermissaoArquivoDigitalDb WHERE IdUsuario = {0}", id)).List().ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public PermissaoArquivoDigital Merge(PermissaoArquivoDigital permissao) + { + PermissaoArquivoDigitalDb permissaoArquivoDigitalDb = ApplicationMapper.Mapper.Map(permissao); + base.Merge(permissaoArquivoDigitalDb); + return ApplicationMapper.Mapper.Map(permissaoArquivoDigitalDb); + } + + public PermissaoArquivoDigital SaveOrUpdate(PermissaoArquivoDigital permissao) + { + PermissaoArquivoDigitalDb permissaoArquivoDigitalDb = ApplicationMapper.Mapper.Map(permissao); + this.SaveOrUpdate(permissaoArquivoDigitalDb); + return ApplicationMapper.Mapper.Map(permissaoArquivoDigitalDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PermissaoUsuarioRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PermissaoUsuarioRepository.cs new file mode 100644 index 0000000..e0e226c --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PermissaoUsuarioRepository.cs @@ -0,0 +1,84 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Helpers; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class PermissaoUsuarioRepository : GenericRepository, IPermissaoUsuarioRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public PermissaoUsuarioRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public PermissaoUsuario FindByPermissao(long id, TipoTela tela) + { + return this.Select(string.Format(" AND IdUsuario = {0} AND Tela = {1}", id, (int)tela)).FirstOrDefault(); + } + + public List FindByUsuario(long id) + { + return this.Select(string.Format(" AND IdUsuario = {0}", id)); + } + + public PermissaoUsuario Merge(PermissaoUsuario permissao) + { + PermissaoUsuarioDb permissaoUsuarioDb = ApplicationMapper.Mapper.Map(permissao); + base.Merge(permissaoUsuarioDb); + return ApplicationMapper.Mapper.Map(permissaoUsuarioDb); + } + + public PermissaoUsuario SaveOrUpdate(PermissaoUsuario permissao) + { + PermissaoUsuarioDb permissaoUsuarioDb = ApplicationMapper.Mapper.Map(permissao); + this.SaveOrUpdate(permissaoUsuarioDb); + return ApplicationMapper.Mapper.Map(permissaoUsuarioDb); + } + + private List Select(string condition) + { + object connection; + DataTable dataTable = new DataTable(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + Auxiliar.CriarAuxiliarUsuario(sqlCommand); + sqlCommand.CommandText = string.Concat("SELECT DISTINCT * FROM PermissaoUsuario WHERE 1=1 ", condition, ";"); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + } + } + return dataTable.MapPermissao(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PlanoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PlanoRepository.cs new file mode 100644 index 0000000..47044d1 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PlanoRepository.cs @@ -0,0 +1,93 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Financeiro; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class PlanoRepository : GenericRepository, IPlanoRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public PlanoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public List Find(string filter) + { + PlanoRepository.u003cu003ec__DisplayClass2_0 variable = null; + IQueryable planoDbs = base.All(); + ParameterExpression parameterExpression = Expression.Parameter(typeof(PlanoDb), "x"); + IQueryable planoDbs1 = planoDbs.Where(Expression.Lambda>(Expression.AndAlso(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(PlanoDb).GetMethod("get_Ativo").MethodHandle)), Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(PlanoDb).GetMethod("get_Descricao").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(PlanoRepository.u003cu003ec__DisplayClass2_0)), FieldInfo.GetFieldFromHandle(typeof(PlanoRepository.u003cu003ec__DisplayClass2_0).GetField("filter").FieldHandle)) })), new ParameterExpression[] { parameterExpression })); + parameterExpression = Expression.Parameter(typeof(PlanoDb), "x"); + return planoDbs1.Select(Expression.Lambda>(Expression.MemberInit(Expression.New(typeof(Plano)), new MemberBinding[] { Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(DomainBase).GetMethod("set_Id", new Type[] { typeof(long) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(EntityBase).GetMethod("get_Id").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Plano).GetMethod("set_Descricao", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(PlanoDb).GetMethod("get_Descricao").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Plano).GetMethod("set_Ativo", new Type[] { typeof(bool) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(PlanoDb).GetMethod("get_Ativo").MethodHandle))) }), new ParameterExpression[] { parameterExpression })).ToList(); + } + + public List Find() + { + object connection; + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + DataTable dataTable = new DataTable(); + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = "SELECT DISTINCT idcplano as id, descricao as nome, ativo FROM cplano;"; + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + } + } + return ( + from a in dataTable.AsEnumerable().ToList() + select new Plano() + { + Id = a.Field("id"), + Descricao = a.Field("nome"), + Ativo = (a.Field("ativo") == null ? true : a.Field("ativo").ToString() == "1") + }).ToList(); + } + + public Plano Merge(Plano plano) + { + PlanoDb planoDb = ApplicationMapper.Mapper.Map(plano); + base.Merge(planoDb); + return ApplicationMapper.Mapper.Map(planoDb); + } + + public Plano SaveOrUpdate(Plano plano) + { + PlanoDb planoDb = ApplicationMapper.Mapper.Map(plano); + this.SaveOrUpdate(planoDb); + return ApplicationMapper.Mapper.Map(planoDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PlanosRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PlanosRepository.cs new file mode 100644 index 0000000..d76619d --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PlanosRepository.cs @@ -0,0 +1,101 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Financeiro; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Helpers; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Financeiro; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class PlanosRepository : GenericRepository, IPlanosRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public PlanosRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public List Find(string description) + { + PlanosRepository.u003cu003ec__DisplayClass3_0 variable = null; + IQueryable planosDbs = base.All(); + ParameterExpression parameterExpression = Expression.Parameter(typeof(PlanosDb), "x"); + List list = planosDbs.Where(Expression.Lambda>(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(PlanosDb).GetMethod("get_Descricao").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(PlanosRepository.u003cu003ec__DisplayClass3_0)), FieldInfo.GetFieldFromHandle(typeof(PlanosRepository.u003cu003ec__DisplayClass3_0).GetField("description").FieldHandle)) }), new ParameterExpression[] { parameterExpression })).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public List Find() + { + object connection; + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + DataTable dataTable = new DataTable(); + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + AuxiliarFinanceiro.Criar(sqlCommand); + sqlCommand.CommandText = "SELECT DISTINCT cs.idcplanos as id, cs.descricao as nome, cs.ativo, cs.idcplano, cs.idtipoconta, cs.ctipo, cp.descricao FROM cplanos cs INNER JOIN cplano cp ON cs.idcplano = cp.idcplano;"; + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + } + } + return CustomMap.MapPlanos(dataTable); + } + + public Planos FindById(long id) + { + PlanosDb planosDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(planosDb); + } + + public List FindByPlanoId(long id) + { + List list = ( + from x in base.All() + where x.Plano.Id == id + select x).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public Planos Merge(Planos planos) + { + PlanosDb planosDb = ApplicationMapper.Mapper.Map(planos); + base.Merge(planosDb); + return ApplicationMapper.Mapper.Map(planosDb); + } + + public Planos SaveOrUpdate(Planos planos) + { + PlanosDb planosDb = ApplicationMapper.Mapper.Map(planos); + this.SaveOrUpdate(planosDb); + return ApplicationMapper.Mapper.Map(planosDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProdutoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProdutoRepository.cs new file mode 100644 index 0000000..472ec21 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProdutoRepository.cs @@ -0,0 +1,76 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class ProdutoRepository : GenericRepository, IProdutoRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public ProdutoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public List Find(string value) + { + ProdutoRepository.u003cu003ec__DisplayClass6_0 variable = null; + IQueryable produtoDbs = base.All(); + ParameterExpression parameterExpression = Expression.Parameter(typeof(ProdutoDb), "x"); + IQueryable produtoDbs1 = produtoDbs.Where(Expression.Lambda>(Expression.OrElse(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(ProdutoDb).GetMethod("get_Nome").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(ProdutoRepository.u003cu003ec__DisplayClass6_0)), FieldInfo.GetFieldFromHandle(typeof(ProdutoRepository.u003cu003ec__DisplayClass6_0).GetField("value").FieldHandle)) }), Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(ProdutoDb).GetMethod("get_Nome").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(ProdutoRepository.u003cu003ec__DisplayClass6_0)), FieldInfo.GetFieldFromHandle(typeof(ProdutoRepository.u003cu003ec__DisplayClass6_0).GetField("value").FieldHandle)) })), new ParameterExpression[] { parameterExpression })); + parameterExpression = Expression.Parameter(typeof(ProdutoDb), "x"); + return produtoDbs1.Select(Expression.Lambda>(Expression.MemberInit(Expression.New(typeof(Produto)), new MemberBinding[] { Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(DomainBase).GetMethod("set_Id", new Type[] { typeof(long) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(EntityBase).GetMethod("get_Id").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Produto).GetMethod("set_Nome", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(ProdutoDb).GetMethod("get_Nome").MethodHandle))) }), new ParameterExpression[] { parameterExpression })).ToList(); + } + + public List Find() + { + return ( + from x in this._unitOfWork.Session.CreateQuery("from ProdutoDb").List() + select new Produto() + { + Id = x.Id, + Nome = x.Nome, + Ativo = x.Ativo + }).ToList(); + } + + public Produto FindById(long id) + { + ProdutoDb produtoDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(produtoDb); + } + + public Produto Merge(Produto produto) + { + ProdutoDb produtoDb = ApplicationMapper.Mapper.Map(produto); + base.Merge(produtoDb); + return ApplicationMapper.Mapper.Map(produtoDb); + } + + public Produto SaveOrUpdate(Produto produto) + { + ProdutoDb produtoDb = ApplicationMapper.Mapper.Map(produto); + this.SaveOrUpdate(produtoDb); + return ApplicationMapper.Mapper.Map(produtoDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProfissaoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProfissaoRepository.cs new file mode 100644 index 0000000..f251e6e --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProfissaoRepository.cs @@ -0,0 +1,92 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class ProfissaoRepository : GenericRepository, IProfissaoRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public ProfissaoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public List Find(string filter) + { + ProfissaoRepository.u003cu003ec__DisplayClass5_0 variable = null; + IQueryable profissaoDbs = base.All(); + ParameterExpression parameterExpression = Expression.Parameter(typeof(ProfissaoDb), "x"); + IQueryable profissaoDbs1 = profissaoDbs.Where(Expression.Lambda>(Expression.OrElse(Expression.Call(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(ProfissaoDb).GetMethod("get_Nome").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Trim").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(ProfissaoRepository.u003cu003ec__DisplayClass5_0)), FieldInfo.GetFieldFromHandle(typeof(ProfissaoRepository.u003cu003ec__DisplayClass5_0).GetField("filter").FieldHandle)) }), Expression.Call(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(ProfissaoDb).GetMethod("get_Codigo").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Trim").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(ProfissaoRepository.u003cu003ec__DisplayClass5_0)), FieldInfo.GetFieldFromHandle(typeof(ProfissaoRepository.u003cu003ec__DisplayClass5_0).GetField("filter").FieldHandle)) })), new ParameterExpression[] { parameterExpression })); + parameterExpression = Expression.Parameter(typeof(ProfissaoDb), "x"); + return profissaoDbs1.Select(Expression.Lambda>(Expression.MemberInit(Expression.New(typeof(Profissao)), new MemberBinding[] { Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(DomainBase).GetMethod("set_Id", new Type[] { typeof(long) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(EntityBase).GetMethod("get_Id").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Profissao).GetMethod("set_Nome", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(ProfissaoDb).GetMethod("get_Nome").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Profissao).GetMethod("set_Codigo", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(ProfissaoDb).GetMethod("get_Codigo").MethodHandle))) }), new ParameterExpression[] { parameterExpression })).ToList(); + } + + public long FindLastId() + { + long num; + object connection; + SqlCommand sqlCommand; + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + if (sqlConnection != null) + { + sqlCommand = sqlConnection.CreateCommand(); + } + else + { + sqlCommand = null; + } + using (SqlCommand sqlCommand1 = sqlCommand) + { + sqlCommand1.CommandText = "SELECT MAX(idprofissao) as id FROM profissao"; + SqlDataReader sqlDataReader = sqlCommand1.ExecuteReader(); + sqlDataReader.Read(); + object item = sqlDataReader["id"]; + num = (sqlDataReader["id"] == null || sqlDataReader["id"].ToString() == "" || sqlDataReader["id"].ToString() == "{}" ? (long)0 : long.Parse(sqlDataReader["id"].ToString())); + } + } + return num; + } + + public Profissao Merge(Profissao profissao) + { + ProfissaoDb profissaoDb = ApplicationMapper.Mapper.Map(profissao); + base.Merge(profissaoDb); + return ApplicationMapper.Mapper.Map(profissaoDb); + } + + public Profissao SaveOrUpdate(Profissao profissao) + { + ProfissaoDb profissaoDb = ApplicationMapper.Mapper.Map(profissao); + this.SaveOrUpdate(profissaoDb); + return ApplicationMapper.Mapper.Map(profissaoDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProspectRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProspectRepository.cs new file mode 100644 index 0000000..8b4909c --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProspectRepository.cs @@ -0,0 +1,245 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class ProspectRepository : GenericRepository, IProspectRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public ProspectRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + ProspeccaoDb prospeccaoDb = base.FindEntityById(id); + if (prospeccaoDb == null) + { + return; + } + base.Delete(prospeccaoDb); + } + + public List Find(long idempresa, long id, DateTime inicio, DateTime fim, StatusProspeccao? status) + { + VendedorDb vendedorDb = this._unitOfWork.Query().First((VendedorDb x) => x.Corretora); + List prospeccaoDbs = new List(); + if (status.HasValue) + { + if (idempresa == 0 && id == 0) + { + prospeccaoDbs = ( + from x in base.All() + where (x.VigenciaFinal != null) && (x.VigenciaFinal >= (DateTime?)inicio) && (x.VigenciaFinal <= (DateTime?)fim) && (int?)x.Status == (int?)status + select x).ToList(); + } + if (idempresa == 0 && id > (long)0) + { + prospeccaoDbs = ( + from x in base.All() + where x.Vendedor.Id == id && (x.VigenciaFinal != null) && (x.VigenciaFinal >= (DateTime?)inicio) && (x.VigenciaFinal <= (DateTime?)fim) && (int?)x.Status == (int?)status + select x).ToList(); + } + if (idempresa > (long)0 && id == 0) + { + prospeccaoDbs = ( + from x in base.All() + where x.IdEmpresa == idempresa && (x.VigenciaFinal != null) && (x.VigenciaFinal >= (DateTime?)inicio) && (x.VigenciaFinal <= (DateTime?)fim) && (int?)x.Status == (int?)status + select x).ToList(); + } + if (idempresa > (long)0 && id > (long)0) + { + prospeccaoDbs = ( + from x in base.All() + where x.IdEmpresa == idempresa && x.Vendedor.Id == id && (x.VigenciaFinal != null) && (x.VigenciaFinal >= (DateTime?)inicio) && (x.VigenciaFinal <= (DateTime?)fim) && (int?)x.Status == (int?)status + select x).ToList(); + } + } + else + { + if (idempresa == 0 && id == 0) + { + prospeccaoDbs = ( + from x in base.All() + where (x.VigenciaFinal != null) && (x.VigenciaFinal >= (DateTime?)inicio) && (x.VigenciaFinal <= (DateTime?)fim) + select x).ToList(); + } + if (idempresa == 0 && id > (long)0) + { + prospeccaoDbs = ( + from x in base.All() + where x.Vendedor.Id == id && (x.VigenciaFinal != null) && (x.VigenciaFinal >= (DateTime?)inicio) && (x.VigenciaFinal <= (DateTime?)fim) + select x).ToList(); + } + if (idempresa > (long)0 && id == 0) + { + prospeccaoDbs = ( + from x in base.All() + where x.IdEmpresa == idempresa && (x.VigenciaFinal != null) && (x.VigenciaFinal >= (DateTime?)inicio) && (x.VigenciaFinal <= (DateTime?)fim) + select x).ToList(); + } + if (idempresa > (long)0 && id > (long)0) + { + prospeccaoDbs = ( + from x in base.All() + where x.IdEmpresa == idempresa && x.Vendedor.Id == id && (x.VigenciaFinal != null) && (x.VigenciaFinal >= (DateTime?)inicio) && (x.VigenciaFinal <= (DateTime?)fim) + select x).ToList(); + } + } + foreach (ProspeccaoDb prospeccaoDb in prospeccaoDbs) + { + if (prospeccaoDb.Vendedor == null || prospeccaoDb.Vendedor.Id == 0) + { + prospeccaoDb.Vendedor = vendedorDb; + } + bool? renovacao = prospeccaoDb.Renovacao; + prospeccaoDb.Renovacao = new bool?(renovacao.GetValueOrDefault(true)); + } + return ApplicationMapper.Mapper.Map, List>(prospeccaoDbs); + } + + public List Find(Filtros filtro) + { + List prospeccaoDbs; + VendedorDb vendedorDb = this._unitOfWork.Query().First((VendedorDb x) => x.Corretora); + List statusProspeccaos = new List() + { + StatusProspeccao.Agendado, + StatusProspeccao.EmAndamento, + StatusProspeccao.NaoTrabalhado, + StatusProspeccao.Perdido, + StatusProspeccao.Ganho + }; + if (filtro.Status != null && filtro.Status.Count > 0) + { + statusProspeccaos.RemoveAll((StatusProspeccao x) => true); + if (filtro.Status.Contains((long)1) || filtro.Status.Contains((long)2)) + { + statusProspeccaos.Add(StatusProspeccao.Agendado); + statusProspeccaos.Add(StatusProspeccao.NaoTrabalhado); + statusProspeccaos.Add(StatusProspeccao.EmAndamento); + } + if (filtro.Status.Contains((long)6)) + { + statusProspeccaos.Add(StatusProspeccao.Perdido); + } + if (filtro.Status.Contains((long)5)) + { + statusProspeccaos.Add(StatusProspeccao.Ganho); + } + } + prospeccaoDbs = (filtro.Vendedores == null || filtro.Vendedores.Count <= 0 ? ( + from x in base.All() + where (x.VigenciaFinal != null) && (x.VigenciaFinal >= (DateTime?)filtro.Inicio) && (x.VigenciaFinal <= (DateTime?)filtro.Fim) && statusProspeccaos.Contains(x.Status.Value) + select x).ToList() : ( + from x in base.All() + where filtro.Vendedores.Contains(x.Vendedor.Id) && (x.VigenciaFinal != null) && (x.VigenciaFinal >= (DateTime?)filtro.Inicio) && (x.VigenciaFinal <= (DateTime?)filtro.Fim) && statusProspeccaos.Contains(x.Status.Value) + select x).ToList()); + foreach (ProspeccaoDb nullable in prospeccaoDbs) + { + if (nullable.Vendedor == null || nullable.Vendedor.Id == 0) + { + nullable.Vendedor = vendedorDb; + } + bool? renovacao = nullable.Renovacao; + nullable.Renovacao = new bool?(renovacao.GetValueOrDefault(true)); + } + prospeccaoDbs = (filtro.IdEmpresa == 0 ? prospeccaoDbs : ( + from x in prospeccaoDbs + where x.IdEmpresa == filtro.IdEmpresa + select x).ToList()); + return ApplicationMapper.Mapper.Map, List>(prospeccaoDbs); + } + + public List FindByData(DateTime inicio, DateTime fim) + { + List list = ( + from x in base.All() + where (x.VigenciaFinal != null) && (x.VigenciaFinal >= (DateTime?)inicio) && (x.VigenciaFinal <= (DateTime?)fim) + select x).ToList(); + list.ForEach((ProspeccaoDb x) => x.Renovacao = new bool?(x.Renovacao.GetValueOrDefault(true))); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public Prospeccao FindById(long id) + { + ProspeccaoDb nullable = base.FindEntityById(id); + if (nullable != null) + { + bool? renovacao = nullable.Renovacao; + nullable.Renovacao = new bool?(renovacao.GetValueOrDefault(true)); + } + return ApplicationMapper.Mapper.Map(nullable); + } + + public List FindByStatus(StatusProspeccao status) + { + List list = ( + from x in base.All() + where (int?)x.Status == (int?)status + select x).ToList(); + list.ForEach((ProspeccaoDb x) => x.Renovacao = new bool?(x.Renovacao.GetValueOrDefault(true))); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public List FindByStatusPersonalizado(long statusId) + { + List list = ( + from x in base.All() + where x.StatusPersonalizado.Id == statusId + select x).ToList(); + list.ForEach((ProspeccaoDb x) => x.Renovacao = new bool?(x.Renovacao.GetValueOrDefault(true))); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public Prospeccao FindByTarefa(long id) + { + ProspeccaoDb nullable = base.All().FirstOrDefault((ProspeccaoDb x) => x.Tarefa.Id == id); + if (nullable != null) + { + bool? renovacao = nullable.Renovacao; + nullable.Renovacao = new bool?(renovacao.GetValueOrDefault(true)); + } + return ApplicationMapper.Mapper.Map(nullable); + } + + public List FindByVendedor(long id) + { + List list = ( + from x in base.All() + where x.Vendedor.Id == id + select x).ToList(); + list.ForEach((ProspeccaoDb x) => x.Renovacao = new bool?(x.Renovacao.GetValueOrDefault(true))); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public Prospeccao Merge(Prospeccao prospeccao) + { + ProspeccaoDb prospeccaoDb = ApplicationMapper.Mapper.Map(prospeccao); + base.Merge(prospeccaoDb); + return ApplicationMapper.Mapper.Map(prospeccaoDb); + } + + public Prospeccao SaveOrUpdate(Prospeccao prospeccao) + { + ProspeccaoDb prospeccaoDb = ApplicationMapper.Mapper.Map(prospeccao); + this.SaveOrUpdate(prospeccaoDb); + return ApplicationMapper.Mapper.Map(prospeccaoDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/QualificacaoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/QualificacaoRepository.cs new file mode 100644 index 0000000..e8c621b --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/QualificacaoRepository.cs @@ -0,0 +1,38 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Seguros; +using System; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class QualificacaoRepository : GenericRepository, IQualificacaoRepository, IGenericRepository + { + public QualificacaoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + } + + public Qualificacao FindById(long id) + { + QualificacaoDb qualificacaoDb = base.FindEntityById(id) ?? new QualificacaoDb(); + return ApplicationMapper.Mapper.Map(qualificacaoDb); + } + + public Qualificacao Merge(Qualificacao qualificacao) + { + QualificacaoDb qualificacaoDb = ApplicationMapper.Mapper.Map(qualificacao); + base.Merge(qualificacaoDb); + return ApplicationMapper.Mapper.Map(qualificacaoDb); + } + + public Qualificacao SaveOrUpdate(Qualificacao qualificacao) + { + QualificacaoDb qualificacaoDb = ApplicationMapper.Mapper.Map(qualificacao); + this.SaveOrUpdate(qualificacaoDb); + return ApplicationMapper.Mapper.Map(qualificacaoDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RamoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RamoRepository.cs new file mode 100644 index 0000000..563c6bf --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RamoRepository.cs @@ -0,0 +1,85 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class RamoRepository : GenericRepository, IRamoRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public RamoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public List Find(bool ativo) + { + return ( + from x in this._unitOfWork.Session.CreateQuery("from RamoDb \r\n where ativo IS NULL OR ativo != '1'").List() + select new Ramo() + { + Id = x.Id, + Nome = x.Nome, + Iof = x.Iof, + Ativo = x.Ativo + }).ToList(); + } + + public List Find() + { + return ( + from x in this._unitOfWork.Session.CreateQuery("from RamoDb").List() + select new Ramo() + { + Id = x.Id, + Nome = x.Nome, + Iof = x.Iof, + Ativo = x.Ativo + }).ToList(); + } + + public Ramo FindById(long id) + { + RamoDb ramoDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(ramoDb); + } + + public Ramo Merge(Ramo ramo) + { + RamoDb ramoDb = ApplicationMapper.Mapper.Map(ramo); + base.Merge(ramoDb); + return ApplicationMapper.Mapper.Map(ramoDb); + } + + public List MergeRange(List ramos) + { + List ramoDbs = ApplicationMapper.Mapper.Map, List>(ramos); + RamoRepository ramoRepository = this; + ramoDbs.ForEach(new Action(ramoRepository.Merge)); + return ApplicationMapper.Mapper.Map, List>(ramoDbs); + } + + public Ramo SaveOrUpdate(Ramo ramo) + { + RamoDb ramoDb = ApplicationMapper.Mapper.Map(ramo); + this.SaveOrUpdate(ramoDb); + return ApplicationMapper.Mapper.Map(ramoDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ReciboRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ReciboRepository.cs new file mode 100644 index 0000000..cff93a5 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ReciboRepository.cs @@ -0,0 +1,71 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Ferramentas; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class ReciboRepository : GenericRepository, IReciboRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public ReciboRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public List BuscarRecibos() + { + List list = base.All().ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public void Delete(long id) + { + ReciboDb reciboDb = base.FindEntityById(id); + if (reciboDb == null) + { + return; + } + base.Delete(reciboDb); + } + + public void DeleteRange(List ids) + { + List list = ( + from x in base.All() + where ids.Contains(x.Id) + select x).ToList(); + base.DeleteRange(list); + } + + public Recibo FindById(long id) + { + ReciboDb reciboDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(reciboDb); + } + + public Recibo Merge(Recibo recibo) + { + ReciboDb reciboDb = ApplicationMapper.Mapper.Map(recibo); + base.Merge(reciboDb); + return ApplicationMapper.Mapper.Map(reciboDb); + } + + public Recibo SaveOrUpdate(Recibo recibo) + { + ReciboDb reciboDb = ApplicationMapper.Mapper.Map(recibo); + this.SaveOrUpdate(reciboDb); + return ApplicationMapper.Mapper.Map(reciboDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RegistroAcaoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RegistroAcaoRepository.cs new file mode 100644 index 0000000..158bcb9 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RegistroAcaoRepository.cs @@ -0,0 +1,183 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Relatorios; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class RegistroAcaoRepository : GenericRepository, IRegistroAcaoRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public RegistroAcaoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + RegistroAcaoDb registroAcaoDb = base.FindEntityById(id); + if (registroAcaoDb == null) + { + return; + } + base.Delete(registroAcaoDb); + } + + public List Find(Filtros filtros) + { + return this.Select(filtros); + } + + public List FindByEntityId(long id, TipoTela tela) + { + List list = ( + from x in base.All() + where x.EntidadeId == id && (int?)x.Tela == (int?)tela + select x).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public RegistroAcao FindById(long id) + { + RegistroAcaoDb registroAcaoDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(registroAcaoDb); + } + + public List FindOld(Filtros filtros, string connection) + { + return this.SelectOld(filtros, connection); + } + + public RegistroAcao SaveOrUpdate(RegistroAcao log) + { + RegistroAcaoDb registroAcaoDb = ApplicationMapper.Mapper.Map(log); + this.SaveOrUpdate(registroAcaoDb); + return ApplicationMapper.Mapper.Map(registroAcaoDb); + } + + private List Select(Filtros filtros) + { + List registroAcaos; + object connection; + DataTable dataTable = new DataTable(); + string str = (filtros.Usuarios == null || filtros.Usuarios.Count == 0 ? "" : string.Concat(" AND IdUsuario IN (", string.Join(",", + from v in filtros.Usuarios + select v), ")")); + string str1 = (filtros.Telas == null || filtros.Telas.Count == 0 ? "" : string.Concat(" AND Tela IN (", string.Join(",", + from v in filtros.Telas + select v), ")")); + string str2 = (filtros.Relatorios == null || filtros.Relatorios.Count == 0 ? "" : string.Concat(" AND Relatorio IN (", string.Join(",", + from v in filtros.Relatorios + select v), ")")); + string str3 = (filtros.Inicio == DateTime.MinValue ? "" : string.Format(" AND CAST(DataHora AS DATE) >= '{0:yyyy-MM-dd}'", filtros.Inicio)); + string str4 = (filtros.Fim == DateTime.MinValue ? "" : string.Format(" AND CAST(DataHora AS DATE) <= '{0:yyyy-MM-dd}'", filtros.Fim)); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = string.Concat(new string[] { "SELECT * FROM RegistroAcao WHERE 1=1 ", str3, str4, str, str1, str2 }); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + if (dataTable.Rows.Count != 0) + { + return CustomMap.MapLogAcao(dataTable); + } + else + { + registroAcaos = new List(); + } + } + } + return registroAcaos; + } + + private List SelectOld(Filtros filtros, string conn) + { + List registroAcaos; + object connection; + try + { + DataTable dataTable = new DataTable(); + string str = (filtros.Usuarios == null || filtros.Usuarios.Count == 0 ? "" : string.Concat(" AND IDUSUARIO IN (", string.Join(",", + from v in filtros.Usuarios + select v), ")")); + string str1 = (filtros.Inicio == DateTime.MinValue ? "" : string.Format(" AND CAST(DATA AS DATE) >= '{0:yyyy-MM-dd}'", filtros.Inicio)); + string str2 = (filtros.Fim == DateTime.MinValue ? "" : string.Format(" AND CAST(DATA AS DATE) <= '{0:yyyy-MM-dd}'", filtros.Fim)); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = "SELECT TOP 1 * FROM controlelog"; + SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); + sqlDataReader.Read(); + string str3 = sqlDataReader["bdname"].ToString(); + sqlDataReader["tabela"].ToString(); + sqlDataReader.Close(); + if (sqlConnection.Database != str3) + { + conn = conn.Replace(sqlConnection.Database, str3); + } + } + } + using (SqlConnection sqlConnection1 = new SqlConnection(conn)) + { + sqlConnection1.Open(); + using (SqlCommand sqlCommand1 = sqlConnection1.CreateCommand()) + { + sqlCommand1.CommandTimeout = 15000; + sqlCommand1.CommandText = string.Concat("SELECT IDACTION, ID, FORM, IDUSUARIO, DATA, ACAO, historico, maquina FROM actionlog WHERE 1=1 ", str1, str2, str); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand1; + sqlDataAdapter.Fill(dataTable); + } + } + } + registroAcaos = (dataTable.Rows.Count != 0 ? CustomMap.MapOldLogAcao(dataTable) : new List()); + } + catch (Exception exception) + { + registroAcaos = new List(); + } + return registroAcaos; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RegistroLogRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RegistroLogRepository.cs new file mode 100644 index 0000000..a57c17e --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RegistroLogRepository.cs @@ -0,0 +1,222 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Helpers; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Relatorios.LogsEnvio; +using Gestor.Model.Validation; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class RegistroLogRepository : GenericRepository, IRegistroLogRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public RegistroLogRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void AddRange(List registrosLog) + { + base.AddRange(ApplicationMapper.Mapper.Map, List>(registrosLog)); + } + + public List BuscaLogParcelas(List entidadeId) + { + return this.Select((new List() + { + new Condicao() + { + Campo = "Tela", + Valores = 5.CriarValor() + }, + new Condicao() + { + Campo = "EntidadeId", + Valores = entidadeId.CriarValor() + } + }).CreateParameters(0)); + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public List FindByCredential(long id) + { + List list = ( + from x in this._unitOfWork.Query() + where x.Credencial.Id == id + select x).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public List FindByEntity(TipoTela tela, long id) + { + List list = ( + from x in this._unitOfWork.Query() + where x.EntityId == id && (int)x.Tela == (int)tela + select x).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public List FindByEntityId(TipoTela tela, long entidadeId) + { + List condicaos = new List() + { + new Condicao() + { + Campo = "Tela", + Valores = tela.CriarValor() + } + }; + Condicao condicao = new Condicao() + { + Campo = "EntidadeId", + Valores = entidadeId.CriarValor() + }; + if (tela != TipoTela.Configuracoes) + { + condicaos.Add(condicao); + } + return this.Select(condicaos.CreateParameters(0)); + } + + public RegistroLog FindById(long id) + { + RegistroLogDb registroLogDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map(registroLogDb); + } + + public List FindByIdSingle(long id) + { + List list = ( + from x in this._unitOfWork.Query() + where x.Id == id + select x).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public List FindByUser(TipoTela tela, long idUsuario) + { + return this.Select((new List() + { + new Condicao() + { + Campo = "IdUsuario", + Valores = idUsuario.CriarValor() + }, + new Condicao() + { + Campo = "Tela", + Valores = 0.CriarValor(), + Operacao = Operacao.Or, + Grupo = 1 + }, + new Condicao() + { + Campo = "Tela", + Valores = tela.CriarValor(), + Operacao = Operacao.Or, + Grupo = 1 + } + }).CreateParameters(0)); + } + + public List FindByUsuario(long id) + { + List list = ( + from x in this._unitOfWork.Query() + where x.Usuario.Id == id + select x).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public List LogsEnvio(Filtros filtro) + { + object connection; + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + DataTable dataTable = new DataTable(); + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + if (sqlConnection != null) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandTimeout = 15000; + Auxiliar.CriarAuxiliar(sqlCommand, false); + sqlCommand.CommandText = string.Concat("SELECT e.email as emailenvio, u.nome as usuarionome, l.id as id, l.tela as tela, l.data as data, l.destinatarios as destinatarios, l.assunto as assunto, l.cco as cco, l.versao as versao, l.nomemaquina as nomemaquina, l.usuariomaquina as usuariomaquina, l.ip as ip FROM LogEmail l INNER JOIN enviosmtp e on e.idenviosmtp = l.Credencial_id INNER JOIN usuario u on u.idusuario = l.Usuario_id ", string.Format("AND CAST(l.data AS DATE) >= '{0:yyyy-MM-dd}' AND CAST(l.data as DATE) <= '{1:yyyy-MM-dd}'", filtro.Inicio, filtro.Fim)); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + } + } + } + return dataTable.AsEnumerable().Select((DataRow x) => new LogsEnvio() + { + Id = x.Campo("id"), + Tela = x.Campo("tela").GetDescription(), + Assunto = x.Campo("assunto"), + Destinatarios = x.Campo("destinatarios").Replace(";", ";\n"), + Data = x.Campo("data"), + Ip = x.Campo("ip"), + Versao = x.Campo("versao"), + Cco = x.Campo("cco").Replace(";", ";\n"), + Maquina = x.Campo("nomemaquina"), + UsuarioMaquina = x.Campo("usuariomaquina"), + UsuarioAgger = x.Campo("usuarionome"), + Remetente = x.Campo("emailenvio") + }).ToList(); + } + + public RegistroLog SaveOrUpdate(RegistroLog registroLog) + { + RegistroLogDb registroLogDb = ApplicationMapper.Mapper.Map(registroLog); + this.SaveOrUpdate(registroLogDb); + return ApplicationMapper.Mapper.Map(registroLogDb); + } + + public LogEmail SaveOrUpdate(LogEmail log) + { + LogEmailDb logEmailDb = ApplicationMapper.Mapper.Map(log); + this._unitOfWork.Repository().SaveOrUpdate(logEmailDb); + return ApplicationMapper.Mapper.Map(logEmailDb); + } + + private List Select(SqlQueryCondition sqlCondition) + { + return this._unitOfWork.Select(sqlCondition, "SELECT DISTINCT * FROM RegistroLog WHERE", "").MapRegistroLog(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RepasseRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RepasseRepository.cs new file mode 100644 index 0000000..861ac85 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RepasseRepository.cs @@ -0,0 +1,298 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Helpers; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class RepasseRepository : GenericRepository, IRepasseRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public RepasseRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public List DefaultSelect(long idempresa = 0L) + { + List repasses; + object connection; + List nums = null; + Func func1 = null; + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + DataTable dataTable = new DataTable(); + DataTable dataTable1 = new DataTable(); + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + Auxiliar.CriarVendedor(sqlCommand, true); + Auxiliar.LoadTipoVendedor(sqlCommand); + List condicaos = new List() + { + new Condicao() + { + Campo = "idempresa", + Valores = idempresa.CriarValor() + } + }; + string str = "SELECT * FROM repasse WHERE "; + string str1 = "SELECT * FROM VinculoRepasse WHERE "; + List condicaos1 = new List() + { + new Condicao() + { + Campo = "1", + Valores = "1".CriarValor() + } + }; + if (idempresa > (long)0) + { + condicaos1.AddRange(condicaos); + } + dataTable = sqlCommand.Select(condicaos1.CreateParameters(0), str, ""); + if (dataTable.Rows.Count != 0) + { + for (List i = dataTable.AsEnumerable().Select((DataRow x) => x.Field("idrepasse")).Distinct().ToList(); i.Count > 0; i = nums) + { + List nums1 = i.Take(2000).ToList(); + List condicaos2 = new List() + { + new Condicao() + { + Campo = "IdRepasse", + Valores = nums1.CriarValor() + } + }; + DataTable dataTable2 = sqlCommand.Select(condicaos2.CreateParameters(0), str1, ""); + dataTable1.Merge(dataTable2); + nums = (nums1.Count < 2000 ? new List() : i.Except(nums1).ToList()); + } + List repasses1 = dataTable.AsEnumerable().Select((DataRow x) => { + long? nullable1; + long? nullable2; + Repasse repasse = new Repasse() + { + Id = x.Field("idrepasse"), + Ativo = (x.Field("ativo") == null ? true : x.Field("ativo").ToString() != "0"), + Base = (x.Field("base") == null ? null : new BaseRepasse?((BaseRepasse)Enum.Parse(typeof(BaseRepasse), x.Field("base").ToString()))), + Forma = (x.Field("forma") == null ? null : new FormaRepasse?((FormaRepasse)Enum.Parse(typeof(FormaRepasse), x.Field("forma").ToString()))), + Incidencia = (x.Field("incidencia") == null ? null : new TipoIncidencia?((TipoIncidencia)Enum.Parse(typeof(TipoIncidencia), x.Field("incidencia").ToString()))), + Tipo = (x.Field("tipo") == null ? null : new TipoRepasse?((TipoRepasse)Enum.Parse(typeof(TipoRepasse), x.Field("tipo").ToString()))) + }; + decimal? nullable3 = x.Field("vlrnovo"); + repasse.ValorNovo = nullable3.GetValueOrDefault(); + nullable3 = x.Field("vlrrenovacao"); + repasse.ValorRenovacao = nullable3.GetValueOrDefault(); + repasse.Vendedor = Auxiliar.Vendedores.FirstOrDefault((Vendedor z) => z.Id == x.Field("idvendedor")); + repasse.Ramo = (x.Field("idramo") == null ? null : Auxiliar.Ramos.FirstOrDefault((Ramo z) => { + long id = z.Id; + long? nullable = x.Field("idramo"); + return id == nullable.GetValueOrDefault() & nullable.HasValue; + })); + if (x.Field("idciaseg") == null) + { + nullable1 = null; + nullable2 = nullable1; + } + else + { + Seguradora seguradora = Auxiliar.Seguradoras.FirstOrDefault((Seguradora z) => { + long id = z.Id; + long? nullable = x.Field("idciaseg"); + return id == nullable.GetValueOrDefault() & nullable.HasValue; + }); + if (seguradora != null) + { + nullable2 = new long?(seguradora.Id); + } + else + { + nullable1 = null; + nullable2 = nullable1; + } + } + repasse.Seguradora = nullable2; + return repasse; + }).ToList(); + List repasses2 = ( + from x in repasses1 + where x.Ativo + select x).ToList(); + repasses2.ForEach((Repasse x) => { + Repasse list = x; + EnumerableRowCollection dataRows = dataTable1.AsEnumerable().Where((DataRow r) => r.Field("IdRepasse") == x.Id); + Func u003cu003e9_8 = func1; + if (u003cu003e9_8 == null) + { + Func vinculoRepasse = (DataRow v) => new VinculoRepasse() + { + Id = v.Field("Id"), + IdRepasse = v.Field("IdRepasse"), + RepasseVinculo = repasses1.Find((Repasse z) => z.Id == v.Field("RepasseVinculo_id")), + TipoVendedor = Auxiliar.TipoVendedores.Find((TipoVendedor z) => z.Id == v.Field("TipoVendedor_id")), + TipoVendedorVinculo = Auxiliar.TipoVendedores.Find((TipoVendedor z) => z.Id == v.Field("TipoVendedorVinculo_id")) + }; + Func func = vinculoRepasse; + func1 = vinculoRepasse; + u003cu003e9_8 = func; + } + list.Vinculo = dataRows.Select(u003cu003e9_8).ToList(); + }); + repasses = repasses2; + } + else + { + repasses = new List(); + } + } + } + return repasses; + } + + public void Delete(long id) + { + RepasseDb repasseDb = base.FindEntityById(id); + if (repasseDb == null) + { + return; + } + base.Delete(repasseDb); + } + + public void DeleteVinculo(long id) + { + VinculoRepasseDb vinculoRepasseDb = this._unitOfWork.Repository().FindEntityById(id); + if (vinculoRepasseDb == null) + { + return; + } + this._unitOfWork.Repository().Delete(vinculoRepasseDb); + } + + public Repasse FindById(long id) + { + List vinculoRepasses; + RepasseDb repasseDb = base.FindEntityById(id); + List vinculoRepasses1 = this.FindByRepasse(id); + Repasse repasse = ApplicationMapper.Mapper.Map(repasseDb); + if (vinculoRepasses1 == null || vinculoRepasses1.Count <= 0) + { + vinculoRepasses = null; + } + else + { + vinculoRepasses = vinculoRepasses1; + } + repasse.Vinculo = vinculoRepasses; + return repasse; + } + + public List FindByIdRepasse(long id) + { + object connection; + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + DataTable dataTable = new DataTable(); + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + Auxiliar.CriarVendedor(sqlCommand, false); + sqlCommand.CommandText = string.Format("SELECT idvendedorparcela FROM vendedorparcela WHERE idrepasse = {0}", id); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + } + } + return dataTable.AsEnumerable().Select((DataRow x) => new VendedorParcela() + { + Id = x.Field("idvendedorparcela") + }).ToList(); + } + + public List FindByIdVendedor(long id) + { + List list = this._unitOfWork.Session.CreateQuery(string.Format("from RepasseDb \r\n where IdVendedor = {0}", id)).List().ToList(); + List repasses = ApplicationMapper.Mapper.Map, List>(list); + repasses.ForEach((Repasse x) => { + List vinculoRepasses = this.FindByRepasse(x.Id); + x.Vinculo = (vinculoRepasses == null || vinculoRepasses.Count <= 0 ? null : vinculoRepasses); + }); + return repasses; + } + + public List FindByRepasse(long id) + { + List list = ( + from x in this._unitOfWork.Query() + where x.IdRepasse == id + select x).ToList(); + return ApplicationMapper.Mapper.Map, List>(list); + } + + public Repasse Merge(Repasse repasse) + { + RepasseDb repasseDb = ApplicationMapper.Mapper.Map(repasse); + base.Merge(repasseDb); + return ApplicationMapper.Mapper.Map(repasseDb); + } + + public VinculoRepasse Merge(VinculoRepasse vinculo) + { + VinculoRepasseDb vinculoRepasseDb = ApplicationMapper.Mapper.Map(vinculo); + this._unitOfWork.Repository().Merge(vinculoRepasseDb); + return ApplicationMapper.Mapper.Map(vinculoRepasseDb); + } + + public Repasse SaveOrUpdate(Repasse repasse) + { + RepasseDb repasseDb = ApplicationMapper.Mapper.Map(repasse); + this.SaveOrUpdate(repasseDb); + return ApplicationMapper.Mapper.Map(repasseDb); + } + + public VinculoRepasse SaveOrUpdate(VinculoRepasse vinculo) + { + VinculoRepasseDb vinculoRepasseDb = ApplicationMapper.Mapper.Map(vinculo); + this._unitOfWork.Repository().SaveOrUpdate(vinculoRepasseDb); + return ApplicationMapper.Mapper.Map(vinculoRepasseDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ReportRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ReportRepository.cs new file mode 100644 index 0000000..990e3a2 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ReportRepository.cs @@ -0,0 +1,1991 @@ +using Gestor.Common.Helpers; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Helpers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text.RegularExpressions; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class ReportRepository : GenericRepository, IReportRepository, IGenericRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public ReportRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public List PlanilhaCompleta(List ids, bool configFranquia, bool configSomaPremio) + { + object connection; + List nums = null; + List nums1 = null; + if (ids == null || ids.Count == 0) + { + return new List(); + } + DataTable dataTable = new DataTable(); + DataTable dataTable1 = new DataTable(); + DataTable dataTable2 = new DataTable(); + DataTable dataTable3 = new DataTable(); + DataTable dataTable4 = new DataTable(); + DataTable dataTable5 = new DataTable(); + DataTable dataTable6 = new DataTable(); + DataTable dataTable7 = new DataTable(); + DataTable dataTable8 = new DataTable(); + DataTable dataTable9 = new DataTable(); + DataTable dataTable10 = new DataTable(); + DataTable dataTable11 = new DataTable(); + DataTable dataTable12 = new DataTable(); + DataTable dataTable13 = new DataTable(); + DataTable dataTable14 = new DataTable(); + DataTable dataTable15 = new DataTable(); + DataTable dataTable16 = new DataTable(); + DataTable dataTable17 = new DataTable(); + DataTable dataTable18 = new DataTable(); + DataTable dataTable19 = new DataTable(); + DataTable dataTable20 = new DataTable(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + Auxiliar.CriarAuxiliar(sqlCommand, false); + for (List i1 = ids; i1.Count > 0; i1 = nums1) + { + List nums2 = i1.Take(2100).ToList(); + string str9 = string.Concat(" AND d.iddocumento IN (", string.Join(",", nums2), ")"); + DataTable table = new DataTable(); + string str10 = string.Concat("SELECT DISTINCT *, r.nome AS nomeRamo, cs.nome AS nomeCiaseg, ven.nome AS nomeVendedor, cl.idcodigobanco AS cliBanco, cl.agencia AS cliAgencia, cl.Conta AS cliConta, d.adinacomis as adinacomis, prod.nome as nomeProduto, c.idciasegant as idciasegant FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente INNER JOIN ramo r on r.idramo = c.idramo INNER JOIN ciaseg cs on cs.idciaseg = c.idciaseg OUTER APPLY (SELECT TOP 1 idvendedor FROM vendedorparcela vp WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor = 1) vp LEFT OUTER JOIN vendedor ven on ven.idvendedor = vp.idvendedor LEFT OUTER JOIN produto prod on prod.idproduto = c.idproduto WHERE 1=1 ", str9, " AND d.tiporecebimento = 1;"); + sqlCommand.CommandText = str10 ?? ""; + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlCommand.CommandTimeout = 3000; + sqlDataAdapter.Fill(table); + } + dataTable.Merge(table); + table = new DataTable(); + string str11 = string.Concat("SELECT d.idcontrole, d.pedadit, d.aditamento, d.ordem, pr_liq, pr_adic, pr_custo, pr_iof, pr_total FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole WHERE 1=1 AND c.idcontrole IN (SELECT d.idcontrole FROM documento d WHERE 1=1 ", str9, ")AND d.tiporecebimento = 1 AND d.ordem != 0 ORDER BY d.ordem"); + sqlCommand.CommandText = str11 ?? ""; + using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) + { + sqlDataAdapter1.SelectCommand = sqlCommand; + sqlDataAdapter1.Fill(table); + } + dataTable16.Merge(table); + table = new DataTable(); + string str12 = string.Concat("SELECT d.iddocumento, ce.endereco, ce.numero, ce.uf, ce.bairro, ce.cep, ce.cidade, ce.ordem FROM cliendereco ce INNER JOIN cliente cl on cl.idcliente = ce.idcliente INNER JOIN controle c on c.idcliente = cl.idcliente INNER JOIN documento d on d.idcontrole = c.idcontrole WHERE 1=1 ", str9, ";"); + sqlCommand.CommandText = str12 ?? ""; + using (SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter()) + { + sqlDataAdapter2.SelectCommand = sqlCommand; + sqlDataAdapter2.Fill(table); + } + DataView defaultView = table.DefaultView; + defaultView.Sort = "ordem"; + table = defaultView.ToTable(); + dataTable4.Merge(table); + table = new DataTable(); + string str13 = string.Concat("SELECT d.iddocumento, email, cm.ordem FROM climail cm INNER JOIN cliente cl on cl.idcliente = cm.idcliente INNER JOIN controle c on c.idcliente = cl.idcliente INNER JOIN documento d on d.idcontrole = c.idcontrole WHERE 1=1 ", str9, " ;"); + sqlCommand.CommandText = str13 ?? ""; + using (SqlDataAdapter sqlDataAdapter3 = new SqlDataAdapter()) + { + sqlDataAdapter3.SelectCommand = sqlCommand; + sqlDataAdapter3.Fill(table); + } + DataView dataViews = table.DefaultView; + dataViews.Sort = "ordem"; + table = dataViews.ToTable(); + dataTable3.Merge(table); + table = new DataTable(); + string str14 = string.Concat("SELECT d.iddocumento, ddd, fone, ct.ordem FROM clitelefone ct INNER JOIN cliente cl on cl.idcliente = ct.idcliente INNER JOIN controle c on c.idcliente = cl.idcliente INNER JOIN documento d on d.idcontrole = c.idcontrole WHERE 1=1 ", str9, ";"); + sqlCommand.CommandText = str14 ?? ""; + using (SqlDataAdapter sqlDataAdapter4 = new SqlDataAdapter()) + { + sqlDataAdapter4.SelectCommand = sqlCommand; + sqlDataAdapter4.Fill(table); + } + DataView defaultView1 = table.DefaultView; + defaultView1.Sort = "ordem"; + table = defaultView1.ToTable(); + dataTable2.Merge(table); + table = new DataTable(); + string str15 = string.Concat("SELECT d.iddocumento, nome AS nomeEstipulante, CASE WHEN es.idestipulante = d.idestipulante THEN '1'WHEN es.idestipulante = d.idestipulante2 THEN '2'WHEN es.idestipulante = d.idestipulante3 THEN '3'WHEN es.idestipulante = d.idestipulante4 THEN '4'WHEN es.idestipulante = d.idestipulante5 THEN '5'ELSE 'N/A'END AS 'index'FROM estipulante es INNER JOIN documento d on es.idestipulante IN (d.idestipulante, d.idestipulante2, d.idestipulante3, d.idestipulante4, d.idestipulante5) WHERE 1=1 ", str9, ";"); + sqlCommand.CommandText = str15 ?? ""; + using (SqlDataAdapter sqlDataAdapter5 = new SqlDataAdapter()) + { + sqlDataAdapter5.SelectCommand = sqlCommand; + sqlDataAdapter5.Fill(table); + } + dataTable1.Merge(table); + table = new DataTable(); + string str16 = string.Concat("SELECT d.iddocumento, * FROM cliContato cc INNER JOIN cliente cl on cl.idcliente = cc.idcliente INNER JOIN controle c on c.idcliente = cl.idcliente INNER JOIN documento d on d.idcontrole = c.idcontrole WHERE 1=1 ", str9, ";"); + sqlCommand.CommandText = str16 ?? ""; + using (SqlDataAdapter sqlDataAdapter6 = new SqlDataAdapter()) + { + sqlDataAdapter6.SelectCommand = sqlCommand; + sqlDataAdapter6.Fill(table); + } + dataTable5.Merge(table); + table = new DataTable(); + string str17 = string.Concat("SELECT DISTINCT idcontrolesinistro, idcontrole as id FROM controlesinistro cs INNER JOIN item i on i.iditem = cs.iditem INNER JOIN documento d on d.iddocumento = i.iddocumento WHERE 1=1 ", str9); + sqlCommand.CommandText = str17 ?? ""; + using (SqlDataAdapter sqlDataAdapter7 = new SqlDataAdapter()) + { + sqlDataAdapter7.SelectCommand = sqlCommand; + sqlDataAdapter7.Fill(table); + } + dataTable7.Merge(table); + table = new DataTable(); + string str18 = string.Concat(" AND d.idcontrole IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("idcontrole"))), ")"); + sqlCommand.CommandText = string.Concat("SELECT it.iditem, d.iddocumento, it.descricao, it.sinistrado, it.obs, it.status, d.idcontrole FROM item it INNER JOIN documento d on d.iddocumento = it.iddocumento WHERE 1=1 AND (cancelado IS NULL OR cancelado != '1') AND idsubstituido IS NULL ", " ", str18); + using (SqlDataAdapter sqlDataAdapter8 = new SqlDataAdapter()) + { + sqlDataAdapter8.SelectCommand = sqlCommand; + sqlDataAdapter8.Fill(table); + } + dataTable6.Merge(table); + for (List j = table.AsEnumerable().Select((DataRow i) => i.Field("iditem")).ToList(); j.Count > 0; j = nums) + { + List nums3 = j.Take(2000).ToList(); + SqlQueryCondition sqlQueryCondition = (new List() + { + new Condicao() + { + Campo = "iditem", + Valores = nums3.CriarValor() + } + }).CreateParameters(0); + table = sqlCommand.Select(sqlQueryCondition, "SELECT iditem, a.codfipe, a.modelo, a.idcategoria, a.idtabelareferencia, a.idcombustivel, a.chassi, a.placa, a.anofab, a.anomod, a.renavam, a.capacidade, a.portas, a.idcor, a.obs, a.regiaocirculacao, a.bonus, a.porcentagemreferencia, a.valordeterminado, a.ci, a.ceppernoite, a.financiado, a.zerokm, a.isencao, a.pcd, a.correcao, a.idfabricante, fab.descricao as fabricante FROM auto a LEFT JOIN fabricante fab on fab.idfabricante = a.idfabricante WHERE ", ""); + dataTable9.Merge(table); + table = sqlCommand.Select(sqlQueryCondition, "SELECT iditem, res.endereco as enderecoitem, res.numero as numeroitem, res.bens, res.cidade as cidadeitem, res.uf as ufitem, res.bairro as bairroitem, res.cep as cepitem, res.complemento as complementoitem, res.tiporesidencia, res.obs as obsresidencia, res.imobiliaria, res.contato as contatoresidencia, res.idfonetipo as fonetipoloc, res.ddd as dddloc, res.fone as foneloc, res.locatario, res.cpflocatario1, res.ddd2 as ddd2loc, res.fone2 as fone2loc, res.locatario2, res.cpflocatario2, res.dddlocatario2, res.fonelocatario2, res.locatario3, res.cpflocatario3, res.dddlocatario3, res.fonelocatario3 FROM resempco res WHERE ", ""); + dataTable10.Merge(table); + table = sqlCommand.Select(sqlQueryCondition, "SELECT * FROM granizo g WHERE ", ""); + dataTable11.Merge(table); + table = sqlCommand.Select(sqlQueryCondition, "SELECT * FROM aeronautico a WHERE ", ""); + dataTable12.Merge(table); + table = sqlCommand.Select(sqlQueryCondition, "SELECT * FROM riscosdiversos r WHERE ", ""); + dataTable13.Merge(table); + table = sqlCommand.Select(sqlQueryCondition, "SELECT * FROM vida v WHERE ", ""); + dataTable14.Merge(table); + table = sqlCommand.Select(sqlQueryCondition, "SELECT * FROM controlesinistro cs INNER JOIN sinistro s on s.idcontrolesinistro = cs.idcontrolesinistro WHERE ", ""); + dataTable8.Merge(table); + table = sqlCommand.Select(sqlQueryCondition, "SELECT * FROM consorcio WHERE", ""); + dataTable20.Merge(table); + nums = (nums3.Count < 2000 ? new List() : j.Except(nums3).ToList()); + } + table = new DataTable(); + string str19 = string.Concat(" select cli.* from clivinculo cli inner join controle con on cli.idcliente1 = con.idcliente inner join documento d on d.idcontrole = con.idcontrole inner join cliente cliente on cliente.IDCLIENTE = cli.idcliente1 WHERE 1=1 ", str9, ";"); + sqlCommand.CommandText = str19 ?? ""; + using (SqlDataAdapter sqlDataAdapter9 = new SqlDataAdapter()) + { + sqlDataAdapter9.SelectCommand = sqlCommand; + sqlDataAdapter9.Fill(table); + } + dataTable15.Merge(table); + table = new DataTable(); + string str20 = string.Concat("SELECT franquia, d.iddocumento FROM cobertura c INNER JOIN item i ON i.iditem = c.iditem INNER JOIN documento d ON d.iddocumento = i.iddocumento WHERE 1=1 AND franquia IS NOT NULL AND franquia != 0 ", str9, " ;"); + if (configFranquia) + { + str20 = string.Concat("SELECT SUM(franquia) AS franquia, d.iddocumento FROM cobertura c INNER JOIN item i ON i.iditem = c.iditem INNER JOIN documento d ON d.iddocumento = i.iddocumento WHERE 1=1 ", str9, " GROUP BY d.iddocumento;"); + } + sqlCommand.CommandText = str20 ?? ""; + using (SqlDataAdapter sqlDataAdapter10 = new SqlDataAdapter()) + { + sqlDataAdapter10.SelectCommand = sqlCommand; + sqlDataAdapter10.Fill(table); + } + dataTable17.Merge(table); + table = new DataTable(); + string str21 = string.Concat("SELECT idcoberturapadrao, franquia, lmi, observacao, premio, c.iditem FROM cobertura c INNER JOIN item i ON i.iditem = c.iditem INNER JOIN documento d ON d.iddocumento = i.iddocumento WHERE 1=1 ", str9, " AND idcoberturapadrao IN (2, 3, 17, 7, 5);"); + sqlCommand.CommandText = str21 ?? ""; + using (SqlDataAdapter sqlDataAdapter11 = new SqlDataAdapter()) + { + sqlDataAdapter11.SelectCommand = sqlCommand; + sqlDataAdapter11.Fill(table); + } + dataTable18.Merge(table); + table = new DataTable(); + string str22 = string.Concat("SELECT DISTINCT p.nomecompleto, p.cpf, p.datanascimento, p.sexo, p.estadocivil, p.ceppernoite, p.cepcirculacao, c.idcontrole, d.iddocumento FROM perfil p INNER JOIN controle c on c.idcontrole = p.idcontrole INNER JOIN documento d on d.idcontrole = c.idcontrole WHERE 1=1 ", str9); + sqlCommand.CommandText = str22 ?? ""; + using (SqlDataAdapter sqlDataAdapter12 = new SqlDataAdapter()) + { + sqlDataAdapter12.SelectCommand = sqlCommand; + sqlDataAdapter12.Fill(table); + } + dataTable19.Merge(table); + nums1 = (nums2.Count < 2100 ? new List() : i1.Except(nums2).ToList()); + } + } + } + if (dataTable.Rows.Count == 0) + { + return new List(); + } + List planilhaCompletas = new List(); + dataTable.AsEnumerable().ToList().ForEach((DataRow x) => { + decimal? nullable; + decimal? nullable1; + decimal? nullable2; + decimal? nullable3; + decimal? nullable4; + decimal? nullable5; + decimal? nullable6; + decimal? nullable7; + decimal num; + DateTime? nullable8; + long? nullable9; + string nome; + decimal? nullable10; + decimal? nullable11; + decimal? nullable12; + decimal? nullable13; + decimal? nullable14; + decimal? nullable15; + string str; + DateTime? nullable16; + DateTime? nullable17; + DateTime? nullable18; + DateTime? nullable19; + decimal? nullable20; + decimal? nullable21; + decimal? nullable22; + int? nullable23; + decimal? nullable24; + object empty; + object obj; + object empty1; + object obj1; + object empty2; + DateTime? nullable25; + string nome1; + DateTime? nullable26; + DateTime? nullable27; + DateTime? nullable28; + DateTime? nullable29; + DateTime? nullable30; + DateTime? nullable31; + DateTime? nullable32; + DateTime? nullable33; + string description; + string description1; + string str1; + decimal? nullable34; + decimal? nullable35; + string description2; + string str2; + DateTime? nullable36; + DateTime? nullable37; + decimal? nullable38; + decimal? nullable39; + int? nullable40; + int? nullable41; + int? nullable42; + long? nullable43; + DateTime? nullable44; + decimal? nullable45; + decimal? nullable46; + int? nullable47; + int? nullable48; + decimal? nullable49; + decimal? nullable50; + DateTime? nullable51; + DateTime? nullable52; + DateTime? nullable53; + decimal? nullable54; + decimal? nullable55; + decimal? nullable56; + decimal? nullable57; + decimal? nullable58; + decimal? nullable59; + decimal? nullable60; + decimal? nullable61; + decimal? nullable62; + decimal? nullable63; + decimal? nullable64; + decimal? nullable65; + decimal? nullable66; + decimal? nullable67; + decimal? nullable68; + decimal? nullable69; + decimal? nullable70; + decimal? nullable71; + try + { + DataRow dataRow = dataTable16.AsEnumerable().FirstOrDefault((DataRow e) => e.Field("idcontrole") == x.Field("idcontrole")); + List list = dataTable2.AsEnumerable().Where((DataRow e) => e.Field("iddocumento") == x.Field("iddocumento")).Take(3).ToList(); + List dataRows = dataTable3.AsEnumerable().Where((DataRow e) => e.Field("iddocumento") == x.Field("iddocumento")).Take(2).ToList(); + DataRow dataRow1 = dataTable4.AsEnumerable().FirstOrDefault((DataRow e) => e.Field("iddocumento") == x.Field("iddocumento")); + DataRow dataRow2 = dataTable5.AsEnumerable().FirstOrDefault((DataRow e) => e.Field("iddocumento") == x.Field("iddocumento")); + List list1 = dataTable6.AsEnumerable().Where((DataRow e) => e.Field("idcontrole") == x.Field("idcontrole")).ToList(); + bool count = list1.Count != 1; + DataRow dataRow3 = (count ? null : dataTable9.AsEnumerable().FirstOrDefault((DataRow e) => e.Field("iditem") == list1.First().Field("iditem"))); + DataRow dataRow4 = (count ? null : dataTable10.AsEnumerable().FirstOrDefault((DataRow e) => e.Field("iditem") == list1.First().Field("iditem"))); + DataRow dataRow5 = (count ? null : dataTable11.AsEnumerable().FirstOrDefault((DataRow e) => e.Field("iditem") == list1.First().Field("iditem"))); + DataRow dataRow6 = (count ? null : dataTable12.AsEnumerable().FirstOrDefault((DataRow e) => e.Field("iditem") == list1.First().Field("iditem"))); + DataRow dataRow7 = (count ? null : dataTable13.AsEnumerable().FirstOrDefault((DataRow e) => e.Field("iditem") == list1.First().Field("iditem"))); + DataRow dataRow8 = (count ? null : dataTable14.AsEnumerable().FirstOrDefault((DataRow e) => e.Field("iditem") == list1.First().Field("iditem"))); + DataRow dataRow9 = (count ? null : dataTable8.AsEnumerable().FirstOrDefault((DataRow e) => e.Field("iditem") == list1.First().Field("iditem"))); + NegocioCorretora negocioCorretora = (x.Field("negociocorretora") == null ? ((TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()) != TipoSeguro.Renovacao || x.Field("idnegocio") == null || !(x.Field("idnegocio").ToString() == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio) : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), x.Field("negociocorretora").ToString())); + EnumerableRowCollection dataRows1 = dataTable1.AsEnumerable().Where((DataRow e) => e.Field("iddocumento") == x.Field("iddocumento")); + string str3 = (x.Field("situacao") == null || !(x.Field("situacao").ToString() != "") || string.IsNullOrWhiteSpace(x.Field("situacao").ToString()) ? null : ((TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString())).GetDescription()); + string str4 = (x.Field("sexo") == null || !(x.Field("sexo").ToString() != "") || string.IsNullOrWhiteSpace(x.Field("sexo").ToString()) ? "" : ((Sexo)Enum.Parse(typeof(Sexo), x.Field("sexo").ToString())).GetDescription()); + object obj2 = x.Field("clibanco"); + List banco = Auxiliar.Banco; + List bancos = banco; + Predicate u003cu003e9_217 = ReportRepository.u003cu003ec.u003cu003e9__2_17; + if (u003cu003e9_217 == null) + { + u003cu003e9_217 = (Banco y) => y == null; + ReportRepository.u003cu003ec.u003cu003e9__2_17 = u003cu003e9_217; + } + bancos.RemoveAll(u003cu003e9_217); + if (obj2 == null || string.IsNullOrWhiteSpace(obj2.ToString())) + { + nome = ""; + } + else + { + Banco banco1 = banco.FirstOrDefault((Banco b) => b.Id == int.Parse(obj2.ToString())); + if (banco1 != null) + { + nome = banco1.Nome; + } + else + { + nome = null; + } + } + string str5 = nome; + string str6 = ""; + if (dataRow9 != null && dataRow9.Field("observacao") != null) + { + str6 = (new Regex(".*<\\/title>")).Replace((dataRow9 != null ? dataRow9.Field<string>("observacao") : null), "").Trim(); + str6 = (new Regex("(<[^>]*>)|(p\\s?{[^}]*})|(\\r)|(\\n)")).Replace(str6, "").Trim(); + } + if (dataRow3 == null || dataRow3.Field<object>("bonus") == null) + { + nullable5 = null; + nullable10 = nullable5; + } + else + { + nullable10 = new decimal?(decimal.Parse(dataRow3.Field<object>("bonus").ToString())); + } + decimal? nullable72 = nullable10; + DataRow dataRow10 = dataTable15.AsEnumerable().FirstOrDefault<DataRow>((DataRow v) => v.Field<long>("idcliente1") == x.Field<long>("idcliente")) ?? dataTable15.AsEnumerable().FirstOrDefault<DataRow>((DataRow v) => v.Field<long>("idcliente2") == x.Field<long>("idcliente")); + DataRow dataRow11 = dataTable17.AsEnumerable().FirstOrDefault<DataRow>((DataRow e) => e.Field<long>("iddocumento") == x.Field<long>("iddocumento")); + EnumerableRowCollection<DataRow> dataRows2 = dataTable18.AsEnumerable().Where<DataRow>((DataRow e) => e.Field<long>("iditem") == list1.First<DataRow>().Field<long>("iditem")); + Cobertura cobertura = new Cobertura(); + if (list1.Count > 0) + { + EnumerableRowCollection<DataRow> dataRows3 = dataRows2; + Func<DataRow, bool> u003cu003e9_223 = ReportRepository.u003cu003ec.u003cu003e9__2_23; + if (u003cu003e9_223 == null) + { + u003cu003e9_223 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)3; + ReportRepository.u003cu003ec.u003cu003e9__2_23 = u003cu003e9_223; + } + if (dataRows3.Where<DataRow>(u003cu003e9_223).AsEnumerable<DataRow>().ToList<DataRow>().Count > 0) + { + Cobertura valueOrDefault = new Cobertura(); + EnumerableRowCollection<DataRow> dataRows4 = dataRows2; + Func<DataRow, bool> u003cu003e9_234 = ReportRepository.u003cu003ec.u003cu003e9__2_34; + if (u003cu003e9_234 == null) + { + u003cu003e9_234 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)3; + ReportRepository.u003cu003ec.u003cu003e9__2_34 = u003cu003e9_234; + } + nullable5 = dataRows4.FirstOrDefault<DataRow>(u003cu003e9_234).Field<decimal?>("franquia"); + valueOrDefault.Franquia = nullable5.GetValueOrDefault(); + EnumerableRowCollection<DataRow> dataRows5 = dataRows2; + Func<DataRow, bool> u003cu003e9_235 = ReportRepository.u003cu003ec.u003cu003e9__2_35; + if (u003cu003e9_235 == null) + { + u003cu003e9_235 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)3; + ReportRepository.u003cu003ec.u003cu003e9__2_35 = u003cu003e9_235; + } + nullable5 = dataRows5.FirstOrDefault<DataRow>(u003cu003e9_235).Field<decimal?>("premio"); + valueOrDefault.Premio = nullable5.GetValueOrDefault(); + EnumerableRowCollection<DataRow> dataRows6 = dataRows2; + Func<DataRow, bool> u003cu003e9_236 = ReportRepository.u003cu003ec.u003cu003e9__2_36; + if (u003cu003e9_236 == null) + { + u003cu003e9_236 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)3; + ReportRepository.u003cu003ec.u003cu003e9__2_36 = u003cu003e9_236; + } + nullable5 = dataRows6.FirstOrDefault<DataRow>(u003cu003e9_236).Field<decimal?>("lmi"); + valueOrDefault.Lmi = nullable5.GetValueOrDefault(); + cobertura = valueOrDefault; + } + } + Cobertura cobertura1 = new Cobertura(); + if (list1.Count > 0) + { + EnumerableRowCollection<DataRow> dataRows7 = dataRows2; + Func<DataRow, bool> u003cu003e9_224 = ReportRepository.u003cu003ec.u003cu003e9__2_24; + if (u003cu003e9_224 == null) + { + u003cu003e9_224 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)2; + ReportRepository.u003cu003ec.u003cu003e9__2_24 = u003cu003e9_224; + } + if (dataRows7.Where<DataRow>(u003cu003e9_224).AsEnumerable<DataRow>().ToList<DataRow>().Count > 0) + { + Cobertura valueOrDefault1 = new Cobertura(); + EnumerableRowCollection<DataRow> dataRows8 = dataRows2; + Func<DataRow, bool> u003cu003e9_237 = ReportRepository.u003cu003ec.u003cu003e9__2_37; + if (u003cu003e9_237 == null) + { + u003cu003e9_237 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)2; + ReportRepository.u003cu003ec.u003cu003e9__2_37 = u003cu003e9_237; + } + nullable5 = dataRows8.FirstOrDefault<DataRow>(u003cu003e9_237).Field<decimal?>("franquia"); + valueOrDefault1.Franquia = nullable5.GetValueOrDefault(); + EnumerableRowCollection<DataRow> dataRows9 = dataRows2; + Func<DataRow, bool> u003cu003e9_238 = ReportRepository.u003cu003ec.u003cu003e9__2_38; + if (u003cu003e9_238 == null) + { + u003cu003e9_238 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)2; + ReportRepository.u003cu003ec.u003cu003e9__2_38 = u003cu003e9_238; + } + nullable5 = dataRows9.FirstOrDefault<DataRow>(u003cu003e9_238).Field<decimal?>("premio"); + valueOrDefault1.Premio = nullable5.GetValueOrDefault(); + EnumerableRowCollection<DataRow> dataRows10 = dataRows2; + Func<DataRow, bool> u003cu003e9_239 = ReportRepository.u003cu003ec.u003cu003e9__2_39; + if (u003cu003e9_239 == null) + { + u003cu003e9_239 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)2; + ReportRepository.u003cu003ec.u003cu003e9__2_39 = u003cu003e9_239; + } + nullable5 = dataRows10.FirstOrDefault<DataRow>(u003cu003e9_239).Field<decimal?>("lmi"); + valueOrDefault1.Lmi = nullable5.GetValueOrDefault(); + cobertura1 = valueOrDefault1; + } + } + Cobertura cobertura2 = new Cobertura(); + if (list1.Count > 0) + { + EnumerableRowCollection<DataRow> dataRows11 = dataRows2; + Func<DataRow, bool> u003cu003e9_225 = ReportRepository.u003cu003ec.u003cu003e9__2_25; + if (u003cu003e9_225 == null) + { + u003cu003e9_225 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)17; + ReportRepository.u003cu003ec.u003cu003e9__2_25 = u003cu003e9_225; + } + if (dataRows11.Where<DataRow>(u003cu003e9_225).AsEnumerable<DataRow>().ToList<DataRow>().Count > 0) + { + Cobertura valueOrDefault2 = new Cobertura(); + EnumerableRowCollection<DataRow> dataRows12 = dataRows2; + Func<DataRow, bool> u003cu003e9_240 = ReportRepository.u003cu003ec.u003cu003e9__2_40; + if (u003cu003e9_240 == null) + { + u003cu003e9_240 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)17; + ReportRepository.u003cu003ec.u003cu003e9__2_40 = u003cu003e9_240; + } + nullable5 = dataRows12.FirstOrDefault<DataRow>(u003cu003e9_240).Field<decimal?>("franquia"); + valueOrDefault2.Franquia = nullable5.GetValueOrDefault(); + EnumerableRowCollection<DataRow> dataRows13 = dataRows2; + Func<DataRow, bool> u003cu003e9_241 = ReportRepository.u003cu003ec.u003cu003e9__2_41; + if (u003cu003e9_241 == null) + { + u003cu003e9_241 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)17; + ReportRepository.u003cu003ec.u003cu003e9__2_41 = u003cu003e9_241; + } + nullable5 = dataRows13.FirstOrDefault<DataRow>(u003cu003e9_241).Field<decimal?>("premio"); + valueOrDefault2.Premio = nullable5.GetValueOrDefault(); + EnumerableRowCollection<DataRow> dataRows14 = dataRows2; + Func<DataRow, bool> u003cu003e9_242 = ReportRepository.u003cu003ec.u003cu003e9__2_42; + if (u003cu003e9_242 == null) + { + u003cu003e9_242 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)17; + ReportRepository.u003cu003ec.u003cu003e9__2_42 = u003cu003e9_242; + } + nullable5 = dataRows14.FirstOrDefault<DataRow>(u003cu003e9_242).Field<decimal?>("lmi"); + valueOrDefault2.Lmi = nullable5.GetValueOrDefault(); + cobertura2 = valueOrDefault2; + } + } + Cobertura cobertura3 = new Cobertura(); + if (list1.Count > 0) + { + EnumerableRowCollection<DataRow> dataRows15 = dataRows2; + Func<DataRow, bool> u003cu003e9_226 = ReportRepository.u003cu003ec.u003cu003e9__2_26; + if (u003cu003e9_226 == null) + { + u003cu003e9_226 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)5; + ReportRepository.u003cu003ec.u003cu003e9__2_26 = u003cu003e9_226; + } + if (dataRows15.Where<DataRow>(u003cu003e9_226).AsEnumerable<DataRow>().ToList<DataRow>().Count > 0) + { + Cobertura valueOrDefault3 = new Cobertura(); + EnumerableRowCollection<DataRow> dataRows16 = dataRows2; + Func<DataRow, bool> u003cu003e9_243 = ReportRepository.u003cu003ec.u003cu003e9__2_43; + if (u003cu003e9_243 == null) + { + u003cu003e9_243 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)5; + ReportRepository.u003cu003ec.u003cu003e9__2_43 = u003cu003e9_243; + } + nullable5 = dataRows16.FirstOrDefault<DataRow>(u003cu003e9_243).Field<decimal?>("franquia"); + valueOrDefault3.Franquia = nullable5.GetValueOrDefault(); + EnumerableRowCollection<DataRow> dataRows17 = dataRows2; + Func<DataRow, bool> u003cu003e9_244 = ReportRepository.u003cu003ec.u003cu003e9__2_44; + if (u003cu003e9_244 == null) + { + u003cu003e9_244 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)5; + ReportRepository.u003cu003ec.u003cu003e9__2_44 = u003cu003e9_244; + } + nullable5 = dataRows17.FirstOrDefault<DataRow>(u003cu003e9_244).Field<decimal?>("premio"); + valueOrDefault3.Premio = nullable5.GetValueOrDefault(); + EnumerableRowCollection<DataRow> dataRows18 = dataRows2; + Func<DataRow, bool> u003cu003e9_245 = ReportRepository.u003cu003ec.u003cu003e9__2_45; + if (u003cu003e9_245 == null) + { + u003cu003e9_245 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)5; + ReportRepository.u003cu003ec.u003cu003e9__2_45 = u003cu003e9_245; + } + nullable5 = dataRows18.FirstOrDefault<DataRow>(u003cu003e9_245).Field<decimal?>("lmi"); + valueOrDefault3.Lmi = nullable5.GetValueOrDefault(); + cobertura3 = valueOrDefault3; + } + } + Cobertura cobertura4 = new Cobertura(); + if (list1.Count > 0) + { + EnumerableRowCollection<DataRow> dataRows19 = dataRows2; + Func<DataRow, bool> u003cu003e9_227 = ReportRepository.u003cu003ec.u003cu003e9__2_27; + if (u003cu003e9_227 == null) + { + u003cu003e9_227 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)7; + ReportRepository.u003cu003ec.u003cu003e9__2_27 = u003cu003e9_227; + } + if (dataRows19.Where<DataRow>(u003cu003e9_227).AsEnumerable<DataRow>().ToList<DataRow>().Count > 0) + { + Cobertura valueOrDefault4 = new Cobertura(); + EnumerableRowCollection<DataRow> dataRows20 = dataRows2; + Func<DataRow, bool> u003cu003e9_246 = ReportRepository.u003cu003ec.u003cu003e9__2_46; + if (u003cu003e9_246 == null) + { + u003cu003e9_246 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)7; + ReportRepository.u003cu003ec.u003cu003e9__2_46 = u003cu003e9_246; + } + valueOrDefault4.Observacao = dataRows20.FirstOrDefault<DataRow>(u003cu003e9_246).Field<string>("observacao") ?? ""; + EnumerableRowCollection<DataRow> dataRows21 = dataRows2; + Func<DataRow, bool> u003cu003e9_247 = ReportRepository.u003cu003ec.u003cu003e9__2_47; + if (u003cu003e9_247 == null) + { + u003cu003e9_247 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)7; + ReportRepository.u003cu003ec.u003cu003e9__2_47 = u003cu003e9_247; + } + nullable5 = dataRows21.FirstOrDefault<DataRow>(u003cu003e9_247).Field<decimal?>("franquia"); + valueOrDefault4.Franquia = nullable5.GetValueOrDefault(); + EnumerableRowCollection<DataRow> dataRows22 = dataRows2; + Func<DataRow, bool> u003cu003e9_248 = ReportRepository.u003cu003ec.u003cu003e9__2_48; + if (u003cu003e9_248 == null) + { + u003cu003e9_248 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)7; + ReportRepository.u003cu003ec.u003cu003e9__2_48 = u003cu003e9_248; + } + nullable5 = dataRows22.FirstOrDefault<DataRow>(u003cu003e9_248).Field<decimal?>("premio"); + valueOrDefault4.Premio = nullable5.GetValueOrDefault(); + EnumerableRowCollection<DataRow> dataRows23 = dataRows2; + Func<DataRow, bool> u003cu003e9_249 = ReportRepository.u003cu003ec.u003cu003e9__2_49; + if (u003cu003e9_249 == null) + { + u003cu003e9_249 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)7; + ReportRepository.u003cu003ec.u003cu003e9__2_49 = u003cu003e9_249; + } + nullable5 = dataRows23.FirstOrDefault<DataRow>(u003cu003e9_249).Field<decimal?>("lmi"); + valueOrDefault4.Lmi = nullable5.GetValueOrDefault(); + cobertura4 = valueOrDefault4; + } + } + IEnumerable<DataRow> list2 = + from e in dataTable16.AsEnumerable().ToList<DataRow>() + where e.Field<long>("idcontrole") == x.Field<long>("idcontrole") + select e; + if (!configSomaPremio) + { + nullable6 = x.Field<decimal?>("pr_liq"); + if (nullable6.HasValue) + { + nullable11 = x.Field<decimal?>("pr_liq"); + } + else + { + nullable6 = null; + nullable11 = nullable6; + } + nullable = nullable11; + nullable6 = x.Field<decimal?>("pr_adic"); + if (nullable6.HasValue) + { + nullable12 = x.Field<decimal?>("pr_adic"); + } + else + { + nullable6 = null; + nullable12 = nullable6; + } + nullable1 = nullable12; + nullable6 = x.Field<decimal?>("pr_custo"); + if (nullable6.HasValue) + { + nullable13 = x.Field<decimal?>("pr_custo"); + } + else + { + nullable6 = null; + nullable13 = nullable6; + } + nullable2 = nullable13; + nullable6 = x.Field<decimal?>("pr_iof"); + if (nullable6.HasValue) + { + nullable14 = x.Field<decimal?>("pr_iof"); + } + else + { + nullable6 = null; + nullable14 = nullable6; + } + nullable3 = nullable14; + nullable6 = x.Field<decimal?>("pr_total"); + if (nullable6.HasValue) + { + nullable15 = x.Field<decimal?>("pr_total"); + } + else + { + nullable6 = null; + nullable15 = nullable6; + } + nullable4 = nullable15; + } + else + { + IEnumerable<DataRow> dataRows24 = list2; + Func<DataRow, bool> u003cu003e9_250 = ReportRepository.u003cu003ec.u003cu003e9__2_50; + if (u003cu003e9_250 == null) + { + u003cu003e9_250 = (DataRow z) => z.Field<decimal?>("pr_liq").HasValue; + ReportRepository.u003cu003ec.u003cu003e9__2_50 = u003cu003e9_250; + } + IEnumerable<DataRow> dataRows25 = dataRows24.Where<DataRow>(u003cu003e9_250); + if (dataRows25 != null) + { + Func<DataRow, decimal?> u003cu003e9_251 = ReportRepository.u003cu003ec.u003cu003e9__2_51; + if (u003cu003e9_251 == null) + { + u003cu003e9_251 = (DataRow y) => y.Field<decimal?>("pr_liq"); + ReportRepository.u003cu003ec.u003cu003e9__2_51 = u003cu003e9_251; + } + nullable62 = dataRows25.Sum<DataRow>(u003cu003e9_251); + } + else + { + nullable7 = null; + nullable62 = nullable7; + } + nullable5 = nullable62; + nullable6 = x.Field<decimal?>("pr_liq"); + if (nullable5.HasValue & nullable6.HasValue) + { + nullable63 = new decimal?(nullable5.GetValueOrDefault() + nullable6.GetValueOrDefault()); + } + else + { + nullable7 = null; + nullable63 = nullable7; + } + nullable = nullable63; + IEnumerable<DataRow> dataRows26 = list2; + Func<DataRow, bool> u003cu003e9_252 = ReportRepository.u003cu003ec.u003cu003e9__2_52; + if (u003cu003e9_252 == null) + { + u003cu003e9_252 = (DataRow z) => z.Field<decimal?>("pr_adic").HasValue; + ReportRepository.u003cu003ec.u003cu003e9__2_52 = u003cu003e9_252; + } + IEnumerable<DataRow> dataRows27 = dataRows26.Where<DataRow>(u003cu003e9_252); + if (dataRows27 != null) + { + Func<DataRow, decimal?> u003cu003e9_253 = ReportRepository.u003cu003ec.u003cu003e9__2_53; + if (u003cu003e9_253 == null) + { + u003cu003e9_253 = (DataRow y) => y.Field<decimal?>("pr_adic"); + ReportRepository.u003cu003ec.u003cu003e9__2_53 = u003cu003e9_253; + } + nullable64 = dataRows27.Sum<DataRow>(u003cu003e9_253); + } + else + { + nullable7 = null; + nullable64 = nullable7; + } + nullable6 = nullable64; + nullable5 = x.Field<decimal?>("pr_adic"); + if (nullable6.HasValue & nullable5.HasValue) + { + nullable65 = new decimal?(nullable6.GetValueOrDefault() + nullable5.GetValueOrDefault()); + } + else + { + nullable7 = null; + nullable65 = nullable7; + } + nullable1 = nullable65; + IEnumerable<DataRow> dataRows28 = list2; + Func<DataRow, bool> u003cu003e9_254 = ReportRepository.u003cu003ec.u003cu003e9__2_54; + if (u003cu003e9_254 == null) + { + u003cu003e9_254 = (DataRow z) => z.Field<decimal?>("pr_custo").HasValue; + ReportRepository.u003cu003ec.u003cu003e9__2_54 = u003cu003e9_254; + } + IEnumerable<DataRow> dataRows29 = dataRows28.Where<DataRow>(u003cu003e9_254); + if (dataRows29 != null) + { + Func<DataRow, decimal?> u003cu003e9_255 = ReportRepository.u003cu003ec.u003cu003e9__2_55; + if (u003cu003e9_255 == null) + { + u003cu003e9_255 = (DataRow y) => y.Field<decimal?>("pr_custo"); + ReportRepository.u003cu003ec.u003cu003e9__2_55 = u003cu003e9_255; + } + nullable66 = dataRows29.Sum<DataRow>(u003cu003e9_255); + } + else + { + nullable7 = null; + nullable66 = nullable7; + } + nullable5 = nullable66; + nullable6 = x.Field<decimal?>("pr_custo"); + if (nullable5.HasValue & nullable6.HasValue) + { + nullable67 = new decimal?(nullable5.GetValueOrDefault() + nullable6.GetValueOrDefault()); + } + else + { + nullable7 = null; + nullable67 = nullable7; + } + nullable2 = nullable67; + IEnumerable<DataRow> dataRows30 = list2; + Func<DataRow, bool> u003cu003e9_256 = ReportRepository.u003cu003ec.u003cu003e9__2_56; + if (u003cu003e9_256 == null) + { + u003cu003e9_256 = (DataRow z) => z.Field<decimal?>("pr_iof").HasValue; + ReportRepository.u003cu003ec.u003cu003e9__2_56 = u003cu003e9_256; + } + IEnumerable<DataRow> dataRows31 = dataRows30.Where<DataRow>(u003cu003e9_256); + if (dataRows31 != null) + { + Func<DataRow, decimal?> u003cu003e9_257 = ReportRepository.u003cu003ec.u003cu003e9__2_57; + if (u003cu003e9_257 == null) + { + u003cu003e9_257 = (DataRow y) => y.Field<decimal?>("pr_iof"); + ReportRepository.u003cu003ec.u003cu003e9__2_57 = u003cu003e9_257; + } + nullable68 = dataRows31.Sum<DataRow>(u003cu003e9_257); + } + else + { + nullable7 = null; + nullable68 = nullable7; + } + nullable6 = nullable68; + nullable5 = x.Field<decimal?>("pr_iof"); + if (nullable6.HasValue & nullable5.HasValue) + { + nullable69 = new decimal?(nullable6.GetValueOrDefault() + nullable5.GetValueOrDefault()); + } + else + { + nullable7 = null; + nullable69 = nullable7; + } + nullable3 = nullable69; + IEnumerable<DataRow> dataRows32 = list2; + Func<DataRow, bool> u003cu003e9_258 = ReportRepository.u003cu003ec.u003cu003e9__2_58; + if (u003cu003e9_258 == null) + { + u003cu003e9_258 = (DataRow z) => z.Field<decimal?>("pr_total").HasValue; + ReportRepository.u003cu003ec.u003cu003e9__2_58 = u003cu003e9_258; + } + IEnumerable<DataRow> dataRows33 = dataRows32.Where<DataRow>(u003cu003e9_258); + if (dataRows33 != null) + { + Func<DataRow, decimal?> u003cu003e9_259 = ReportRepository.u003cu003ec.u003cu003e9__2_59; + if (u003cu003e9_259 == null) + { + u003cu003e9_259 = (DataRow y) => y.Field<decimal?>("pr_total"); + ReportRepository.u003cu003ec.u003cu003e9__2_59 = u003cu003e9_259; + } + nullable70 = dataRows33.Sum<DataRow>(u003cu003e9_259); + } + else + { + nullable7 = null; + nullable70 = nullable7; + } + nullable5 = nullable70; + nullable6 = x.Field<decimal?>("pr_total"); + if (nullable5.HasValue & nullable6.HasValue) + { + nullable71 = new decimal?(nullable5.GetValueOrDefault() + nullable6.GetValueOrDefault()); + } + else + { + nullable7 = null; + nullable71 = nullable7; + } + nullable4 = nullable71; + } + int num1 = dataTable16.AsEnumerable().Count<DataRow>((DataRow e) => e.Field<long>("idcontrole") == x.Field<long>("idcontrole")); + int num2 = dataTable7.AsEnumerable().Count<DataRow>((DataRow s) => s.Field<long>("id") == x.Field<long>("idcontrole")); + DataRow dataRow12 = dataTable19.AsEnumerable().FirstOrDefault<DataRow>((DataRow e) => e.Field<long>("iddocumento") == x.Field<long>("iddocumento")); + string str7 = ((dataRow12 != null ? dataRow12.Field<object>("sexo") == null : true) ? "" : (dataRow12.Field<object>("sexo").ToString() == "2" ? Sexo.Feminino.GetDescription<Sexo>() : (dataRow12.Field<object>("sexo").ToString() == "1" ? Sexo.Masculino.GetDescription<Sexo>() : ""))); + if (x.Field<object>("idciasegant") == null) + { + str = ""; + } + else + { + Seguradora seguradora = Auxiliar.Seguradoras.FirstOrDefault<Seguradora>((Seguradora ciaseg) => ciaseg.Id == x.Field<long>("idciasegant")); + if (seguradora != null) + { + str = seguradora.Nome; + } + else + { + str = null; + } + } + string str8 = str; + DataRow dataRow13 = dataTable20.AsEnumerable().FirstOrDefault<DataRow>((DataRow e) => e.Field<long>("iditem") == list1.First<DataRow>().Field<long>("iditem")); + PlanilhaCompleta planilhaCompletum = new PlanilhaCompleta() + { + NumeroProposta = x.Field<string>("proposta"), + NumeroApolice = x.Field<string>("contrato"), + NumeroPedidoEndosso = (!string.IsNullOrEmpty(x.Field<string>("pedadit")) || dataRow == null ? x.Field<string>("pedadit") : dataRow.Field<string>("pedadit")), + NumeroEndosso = (!string.IsNullOrEmpty(x.Field<string>("aditamento")) || dataRow == null ? x.Field<string>("aditamento") : dataRow.Field<string>("aditamento")), + Status = str3, + TipoRecebimento = TipoRecebimento.Parcela.GetDescription<TipoRecebimento>() + }; + DateTime? nullable73 = x.Field<DateTime?>("emissao"); + if (nullable73.HasValue) + { + nullable16 = x.Field<DateTime?>("emissao"); + } + else + { + nullable73 = null; + nullable16 = nullable73; + } + planilhaCompletum.Emissao = nullable16; + nullable73 = x.Field<DateTime?>("vigencia1"); + if (nullable73.HasValue) + { + nullable17 = x.Field<DateTime?>("vigencia1"); + } + else + { + nullable73 = null; + nullable17 = nullable73; + } + planilhaCompletum.VigenciaInicial = nullable17; + nullable73 = x.Field<DateTime?>("vigencia2"); + if (nullable73.HasValue) + { + nullable18 = x.Field<DateTime?>("vigencia2"); + } + else + { + nullable73 = null; + nullable18 = nullable73; + } + planilhaCompletum.VigenciaFinal = nullable18; + nullable73 = x.Field<DateTime?>("remessa"); + if (nullable73.HasValue) + { + nullable19 = x.Field<DateTime?>("remessa"); + } + else + { + nullable73 = null; + nullable19 = nullable73; + } + planilhaCompletum.Remessa = nullable19; + nullable6 = x.Field<decimal?>("com01"); + if (nullable6.HasValue) + { + nullable20 = x.Field<decimal?>("com01"); + } + else + { + nullable6 = null; + nullable20 = nullable6; + } + planilhaCompletum.Comissao = nullable20; + planilhaCompletum.AdicionalComiss = x.Field<string>("adinacomis") == "1"; + nullable7 = nullable; + if (x.Field<string>("adinacomis") == "1") + { + nullable21 = nullable1; + } + else + { + num = new decimal(); + nullable21 = new decimal?(num); + } + decimal? nullable74 = nullable21; + nullable6 = (nullable7.HasValue & nullable74.HasValue ? new decimal?(nullable7.GetValueOrDefault() + nullable74.GetValueOrDefault()) : null); + nullable5 = x.Field<decimal?>("com01"); + if (nullable6.HasValue & nullable5.HasValue) + { + nullable22 = new decimal?((nullable6.GetValueOrDefault() * nullable5.GetValueOrDefault()) * new decimal(1, 0, 0, false, 2)); + } + else + { + nullable74 = null; + nullable22 = nullable74; + } + planilhaCompletum.ComissaoGerada = nullable22; + planilhaCompletum.PremioLiquido = new decimal?(nullable.GetValueOrDefault()); + planilhaCompletum.PremioAdicional = new decimal?(nullable1.GetValueOrDefault()); + planilhaCompletum.PremioCusto = new decimal?(nullable2.GetValueOrDefault()); + num = new decimal(); + planilhaCompletum.LiquidoFatura = new decimal?(num); + num = new decimal(); + planilhaCompletum.TotalFatura = new decimal?(num); + planilhaCompletum.Iof = new decimal?(nullable3.GetValueOrDefault()); + planilhaCompletum.PremioTotal = nullable4; + int? nullable75 = x.Field<int?>("n_parc"); + if (nullable75.HasValue) + { + nullable23 = x.Field<int?>("n_parc"); + } + else + { + nullable75 = null; + nullable23 = nullable75; + } + planilhaCompletum.NumParcelas = nullable23; + nullable75 = x.Field<int?>("n_parc"); + if (!nullable75.HasValue || x.Field<int>("n_parc") <= 0) + { + num = new decimal(); + nullable24 = new decimal?(num); + } + else + { + nullable5 = x.Field<decimal?>("pr_total"); + num = x.Field<int>("n_parc"); + if (nullable5.HasValue) + { + nullable24 = new decimal?(nullable5.GetValueOrDefault() / num); + } + else + { + nullable6 = null; + nullable24 = nullable6; + } + } + planilhaCompletum.ValorParcela = nullable24; + planilhaCompletum.FormaPagamento = (x.Field<object>("formapagamento") == null || !(x.Field<object>("formapagamento").ToString() != "") || string.IsNullOrWhiteSpace(x.Field<object>("formapagamento").ToString()) ? null : ((FormaPagamento)Enum.Parse(typeof(FormaPagamento), x.Field<object>("formapagamento").ToString())).GetDescription<FormaPagamento>()); + planilhaCompletum.Negocio = negocioCorretora.GetDescription<NegocioCorretora>(); + if (dataRows1 != null) + { + EnumerableRowCollection<DataRow> dataRows34 = dataRows1; + Func<DataRow, bool> u003cu003e9_260 = ReportRepository.u003cu003ec.u003cu003e9__2_60; + if (u003cu003e9_260 == null) + { + u003cu003e9_260 = (DataRow e) => e.Field<string>("index").Equals("1"); + ReportRepository.u003cu003ec.u003cu003e9__2_60 = u003cu003e9_260; + } + DataRow dataRow14 = dataRows34.FirstOrDefault<DataRow>(u003cu003e9_260); + if (dataRow14 != null) + { + empty = dataRow14.Field<string>("nomeEstipulante"); + } + else + { + empty = null; + } + } + else + { + empty = null; + } + if (empty == null) + { + empty = string.Empty; + } + planilhaCompletum.Estipulante = (string)empty; + if (dataRows1 != null) + { + EnumerableRowCollection<DataRow> dataRows35 = dataRows1; + Func<DataRow, bool> u003cu003e9_261 = ReportRepository.u003cu003ec.u003cu003e9__2_61; + if (u003cu003e9_261 == null) + { + u003cu003e9_261 = (DataRow e) => e.Field<string>("index").Equals("2"); + ReportRepository.u003cu003ec.u003cu003e9__2_61 = u003cu003e9_261; + } + DataRow dataRow15 = dataRows35.FirstOrDefault<DataRow>(u003cu003e9_261); + if (dataRow15 != null) + { + obj = dataRow15.Field<string>("nomeEstipulante"); + } + else + { + obj = null; + } + } + else + { + obj = null; + } + if (obj == null) + { + obj = string.Empty; + } + planilhaCompletum.Estipulante2 = (string)obj; + if (dataRows1 != null) + { + EnumerableRowCollection<DataRow> dataRows36 = dataRows1; + Func<DataRow, bool> u003cu003e9_262 = ReportRepository.u003cu003ec.u003cu003e9__2_62; + if (u003cu003e9_262 == null) + { + u003cu003e9_262 = (DataRow e) => e.Field<string>("index").Equals("3"); + ReportRepository.u003cu003ec.u003cu003e9__2_62 = u003cu003e9_262; + } + DataRow dataRow16 = dataRows36.FirstOrDefault<DataRow>(u003cu003e9_262); + if (dataRow16 != null) + { + empty1 = dataRow16.Field<string>("nomeEstipulante"); + } + else + { + empty1 = null; + } + } + else + { + empty1 = null; + } + if (empty1 == null) + { + empty1 = string.Empty; + } + planilhaCompletum.Estipulante3 = (string)empty1; + if (dataRows1 != null) + { + EnumerableRowCollection<DataRow> dataRows37 = dataRows1; + Func<DataRow, bool> u003cu003e9_263 = ReportRepository.u003cu003ec.u003cu003e9__2_63; + if (u003cu003e9_263 == null) + { + u003cu003e9_263 = (DataRow e) => e.Field<string>("index").Equals("4"); + ReportRepository.u003cu003ec.u003cu003e9__2_63 = u003cu003e9_263; + } + DataRow dataRow17 = dataRows37.FirstOrDefault<DataRow>(u003cu003e9_263); + if (dataRow17 != null) + { + obj1 = dataRow17.Field<string>("nomeEstipulante"); + } + else + { + obj1 = null; + } + } + else + { + obj1 = null; + } + if (obj1 == null) + { + obj1 = string.Empty; + } + planilhaCompletum.Estipulante4 = (string)obj1; + if (dataRows1 != null) + { + EnumerableRowCollection<DataRow> dataRows38 = dataRows1; + Func<DataRow, bool> u003cu003e9_264 = ReportRepository.u003cu003ec.u003cu003e9__2_64; + if (u003cu003e9_264 == null) + { + u003cu003e9_264 = (DataRow e) => e.Field<string>("index").Equals("5"); + ReportRepository.u003cu003ec.u003cu003e9__2_64 = u003cu003e9_264; + } + DataRow dataRow18 = dataRows38.FirstOrDefault<DataRow>(u003cu003e9_264); + if (dataRow18 != null) + { + empty2 = dataRow18.Field<string>("nomeEstipulante"); + } + else + { + empty2 = null; + } + } + else + { + empty2 = null; + } + if (empty2 == null) + { + empty2 = string.Empty; + } + planilhaCompletum.Estipulante5 = (string)empty2; + planilhaCompletum.Vendedor = x.Field<string>("nomeVendedor"); + planilhaCompletum.Produto = x.Field<string>("nomeProduto"); + nullable73 = x.Field<DateTime?>("datacontrole"); + if (nullable73.HasValue) + { + nullable25 = x.Field<DateTime?>("datacontrole"); + } + else + { + nullable73 = null; + nullable25 = nullable73; + } + planilhaCompletum.DataControle = nullable25; + planilhaCompletum.Seguradora = x.Field<string>("nomeCiaseg"); + planilhaCompletum.Ramo = x.Field<string>("nomeRamo"); + planilhaCompletum.SeguradoraAnterior = str8 ?? ""; + planilhaCompletum.IdDocumento = x.Field<long>("iddocumento"); + planilhaCompletum.ObservacaoDocumento = (x.Field<string>("obs") == null || x.Field<string>("obs").Length <= 30000 ? x.Field<string>("obs") : x.Field<string>("obs").Substring(0, 30000)); + planilhaCompletum.NomeCliente = x.Field<string>("nome"); + if (x.Field<object>("idprofissao") != null) + { + Profissao profissao = Auxiliar.Profissoes.FirstOrDefault<Profissao>((Profissao p) => p.Id == long.Parse(x.Field<object>("idprofissao").ToString())); + if (profissao != null) + { + nome1 = profissao.Nome; + } + else + { + nome1 = null; + } + } + else + { + nome1 = ""; + } + planilhaCompletum.ProfissaoCliente = nome1; + nullable73 = x.Field<DateTime?>("dtnasc"); + if (nullable73.HasValue) + { + nullable26 = x.Field<DateTime?>("dtnasc"); + } + else + { + nullable73 = null; + nullable26 = nullable73; + } + planilhaCompletum.NascimentoCliente = nullable26; + planilhaCompletum.SexoCliente = str4; + planilhaCompletum.EstadoCivilCliente = x.Field<string>("estadocivi"); + planilhaCompletum.DocumentoCliente = x.Field<string>("cgccpf"); + planilhaCompletum.IdentidadeCliente = x.Field<string>("rg"); + planilhaCompletum.EmissorCliente = x.Field<string>("emissor"); + planilhaCompletum.EstadoEmissorCliente = x.Field<string>("rguf"); + nullable73 = x.Field<DateTime?>("rgexpedica"); + if (nullable73.HasValue) + { + nullable27 = x.Field<DateTime?>("rgexpedica"); + } + else + { + nullable73 = null; + nullable27 = nullable73; + } + planilhaCompletum.ExpedicaoCliente = nullable27; + planilhaCompletum.HabilitacaoCliente = x.Field<string>("numehabili"); + nullable73 = x.Field<DateTime?>("primehabil"); + if (nullable73.HasValue) + { + nullable28 = x.Field<DateTime?>("primehabil"); + } + else + { + nullable73 = null; + nullable28 = nullable73; + } + planilhaCompletum.PrimeiraHabilitacaoCliente = nullable28; + nullable73 = x.Field<DateTime?>("venchabili"); + if (nullable73.HasValue) + { + nullable29 = x.Field<DateTime?>("venchabili"); + } + else + { + nullable73 = null; + nullable29 = nullable73; + } + planilhaCompletum.VencimentoHabilitacaoCliente = nullable29; + planilhaCompletum.CategoriaHabilitacaoCliente = x.Field<string>("cathabili"); + nullable73 = x.Field<DateTime?>("clidesde"); + if (nullable73.HasValue) + { + nullable30 = x.Field<DateTime?>("clidesde"); + } + else + { + nullable73 = null; + nullable30 = nullable73; + } + planilhaCompletum.ClienteDesde = nullable30; + planilhaCompletum.PastaCliente = x.Field<string>("pasta"); + planilhaCompletum.CeiCliente = x.Field<string>("cei"); + planilhaCompletum.RneCliente = x.Field<string>("rne"); + planilhaCompletum.FalecidoCliente = (!x.Field<bool?>("falecido").HasValue || !x.Field<bool?>("falecido").GetValueOrDefault() ? "NÃO" : "SIM"); + planilhaCompletum.ObservacaoCliente = (x.Field<string>("anotacoes") == null || x.Field<string>("anotacoes").Length <= 30000 ? x.Field<string>("anotacoes") : x.Field<string>("anotacoes").Substring(0, 30000)); + planilhaCompletum.Prefixo1 = (list == null || list.Count <= 0 ? "" : list[0].Field<string>("ddd")); + planilhaCompletum.Telefone1 = (list == null || list.Count <= 0 ? "" : list[0].Field<string>("fone")); + planilhaCompletum.Prefixo2 = (list == null || list.Count <= 1 ? "" : list[1].Field<string>("ddd")); + planilhaCompletum.Telefone2 = (list == null || list.Count <= 1 ? "" : list[1].Field<string>("fone")); + planilhaCompletum.Prefixo3 = (list == null || list.Count <= 2 ? "" : list[2].Field<string>("ddd")); + planilhaCompletum.Telefone3 = (list == null || list.Count <= 2 ? "" : list[2].Field<string>("fone")); + planilhaCompletum.Email1 = (dataRows == null || dataRows.Count <= 0 ? "" : dataRows[0].Field<string>("email")); + planilhaCompletum.Email2 = (dataRows == null || dataRows.Count <= 1 ? "" : dataRows[1].Field<string>("email")); + planilhaCompletum.Endereco = (dataRow1 != null ? dataRow1.Field<string>("endereco") : null); + planilhaCompletum.Numero = (dataRow1 != null ? dataRow1.Field<string>("numero") : null); + planilhaCompletum.Bairro = (dataRow1 != null ? dataRow1.Field<string>("bairro") : null); + planilhaCompletum.Cidade = (dataRow1 != null ? dataRow1.Field<string>("cidade") : null); + planilhaCompletum.Estado = (dataRow1 != null ? dataRow1.Field<string>("uf") : null); + planilhaCompletum.Cep = (dataRow1 != null ? dataRow1.Field<string>("cep") : null); + planilhaCompletum.BancoCliente = str5; + planilhaCompletum.AgenciaCliente = x.Field<string>("cliAgencia"); + planilhaCompletum.ContaCliente = x.Field<string>("cliConta"); + planilhaCompletum.NomeContato = (dataRow2 != null ? dataRow2.Field<string>("nome") : null); + if (dataRow2 != null) + { + nullable73 = dataRow2.Field<DateTime?>("dtnasc"); + if (!nullable73.HasValue) + { + goto Label1; + } + if (dataRow2 != null) + { + nullable31 = dataRow2.Field<DateTime?>("dtnasc"); + goto Label0; + } + else + { + nullable73 = null; + nullable31 = nullable73; + goto Label0; + } + } + Label1: + nullable73 = null; + nullable31 = nullable73; + Label0: + planilhaCompletum.NascimentoContato = nullable31; + planilhaCompletum.DocumentoContato = (dataRow2 != null ? dataRow2.Field<string>("cgccpf") : null); + planilhaCompletum.IdentidadeContato = (dataRow2 != null ? dataRow2.Field<string>("rg") : null); + if (dataRow2 != null) + { + nullable73 = dataRow2.Field<DateTime?>("rgexpedicao"); + if (!nullable73.HasValue) + { + goto Label3; + } + if (dataRow2 != null) + { + nullable32 = dataRow2.Field<DateTime?>("rgexpedicao"); + goto Label2; + } + else + { + nullable73 = null; + nullable32 = nullable73; + goto Label2; + } + } + Label3: + nullable73 = null; + nullable32 = nullable73; + Label2: + planilhaCompletum.ExpedicaoContato = nullable32; + planilhaCompletum.PrefixoContato = (dataRow2 != null ? dataRow2.Field<string>("ddd") : null); + planilhaCompletum.TelefoneContato = (dataRow2 != null ? dataRow2.Field<string>("fone") : null); + planilhaCompletum.EmailContato = (dataRow2 != null ? dataRow2.Field<string>("email") : null); + planilhaCompletum.HabilitacaoContato = (dataRow2 != null ? dataRow2.Field<string>("cnh") : null); + if (dataRow2 != null) + { + nullable73 = dataRow2.Field<DateTime?>("prihabilitacao"); + if (!nullable73.HasValue) + { + goto Label5; + } + if (dataRow2 != null) + { + nullable33 = dataRow2.Field<DateTime?>("prihabilitacao"); + goto Label4; + } + else + { + nullable73 = null; + nullable33 = nullable73; + goto Label4; + } + } + Label5: + nullable73 = null; + nullable33 = nullable73; + Label4: + planilhaCompletum.PrimeiraHabilitacaoContato = nullable33; + planilhaCompletum.BancoContato = (dataRow2 != null ? dataRow2.Field<string>("banco") : null); + planilhaCompletum.AgenciaContato = (dataRow2 != null ? dataRow2.Field<string>("agencia") : null); + planilhaCompletum.ContaContato = (dataRow2 != null ? dataRow2.Field<string>("conta") : null); + planilhaCompletum.DocumentoSinistrado = (num2 > 0 ? "SIM" : "NÃO"); + planilhaCompletum.Frota = (list1.Count == 0 ? "" : (list1.Count > 1 ? "ESTE DOCUMENTO SE TRATA DE UMA FROTA" : "")); + planilhaCompletum.DescricaoItem = (list1.Count == 0 ? "" : (list1.Count > 1 ? "ESTE DOCUMENTO SE TRATA DE UMA FROTA" : list1.First<DataRow>().Field<string>("descricao"))); + planilhaCompletum.StatusItem = (list1.Count == 0 || list1.Count > 1 ? "" : list1.First<DataRow>().Field<string>("status")); + planilhaCompletum.CodFipe = (string)((dataRow3 != null ? dataRow3.Field<string>("codfipe") : null) ?? ""); + if (dataRow3 != null && dataRow3.Field<object>("idcombustivel") != null) + { + if (string.IsNullOrWhiteSpace((dataRow3 != null ? dataRow3.Field<object>("idcombustivel").ToString() : null))) + { + goto Label7; + } + description = ((Combustivel)Enum.Parse(typeof(Combustivel), dataRow3.Field<object>("idcombustivel").ToString())).GetDescription<Combustivel>(); + goto Label6; + } + Label7: + description = ""; + Label6: + planilhaCompletum.Combustivel = description; + planilhaCompletum.Modelo = (string)((dataRow3 != null ? dataRow3.Field<string>("modelo") : null) ?? ""); + planilhaCompletum.Fabricante = (string)((dataRow3 != null ? dataRow3.Field<string>("fabricante") : null) ?? ""); + if (dataRow3 != null && dataRow3.Field<object>("idcategoria") != null) + { + if (string.IsNullOrWhiteSpace((dataRow3 != null ? dataRow3.Field<object>("idcategoria").ToString() : null))) + { + goto Label9; + } + description1 = ((Categoria)Enum.Parse(typeof(Categoria), dataRow3.Field<object>("idcategoria").ToString())).GetDescription<Categoria>(); + goto Label8; + } + Label9: + description1 = ""; + Label8: + planilhaCompletum.Categoria = description1; + planilhaCompletum.Chassi = (string)((dataRow3 != null ? dataRow3.Field<string>("chassi") : null) ?? ""); + planilhaCompletum.Placa = (string)((dataRow3 != null ? dataRow3.Field<string>("placa") : null) ?? ""); + planilhaCompletum.AnoFab = (string)((dataRow3 != null ? dataRow3.Field<string>("anofab") : null) ?? ""); + planilhaCompletum.AnoMod = (string)((dataRow3 != null ? dataRow3.Field<string>("anomod") : null) ?? ""); + planilhaCompletum.Renavam = (string)((dataRow3 != null ? dataRow3.Field<string>("renavam") : null) ?? ""); + planilhaCompletum.Capacidade = (string)((dataRow3 != null ? dataRow3.Field<string>("capacidade") : null) ?? ""); + planilhaCompletum.Portas = (string)((dataRow3 != null ? dataRow3.Field<string>("portas") : null) ?? ""); + planilhaCompletum.ObsAuto = (string)((dataRow3 != null ? dataRow3.Field<string>("obs") : null) ?? ""); + planilhaCompletum.ObsVida = (string)((dataRow8 != null ? dataRow8.Field<string>("obs") : null) ?? ""); + planilhaCompletum.RegCirc = (string)((dataRow3 != null ? dataRow3.Field<string>("regiaocirculacao") : null) ?? ""); + if (dataRow3 != null && dataRow3.Field<object>("idtabelareferencia") != null) + { + if (string.IsNullOrWhiteSpace((dataRow3 != null ? dataRow3.Field<object>("idtabelareferencia").ToString() : null))) + { + goto Label11; + } + str1 = ((TabelaReferencia)Enum.Parse(typeof(TabelaReferencia), dataRow3.Field<object>("idtabelareferencia").ToString())).GetDescription<TabelaReferencia>(); + goto Label10; + } + Label11: + str1 = ""; + Label10: + planilhaCompletum.TabelaRef = str1; + if (dataRow3 != null) + { + nullable34 = dataRow3.Field<decimal?>("porcentagemreferencia"); + } + else + { + nullable5 = null; + nullable34 = nullable5; + } + planilhaCompletum.PorcRef = nullable34; + if (dataRow3 != null) + { + nullable35 = dataRow3.Field<decimal?>("valordeterminado"); + } + else + { + nullable5 = null; + nullable35 = nullable5; + } + planilhaCompletum.ValorDeterminado = nullable35; + planilhaCompletum.Ci = (string)((dataRow3 != null ? dataRow3.Field<string>("ci") : null) ?? ""); + planilhaCompletum.CepPernoite = (string)((dataRow3 != null ? dataRow3.Field<string>("ceppernoite") : null) ?? ""); + planilhaCompletum.Financiado = (dataRow3 == null ? "" : (dataRow3.Field<string>("financiado") == "1" ? "SIM" : "NÃO")); + planilhaCompletum.ZeroKm = (dataRow3 == null ? "" : (dataRow3.Field<string>("zerokm") == "1" ? "SIM" : "NÃO")); + planilhaCompletum.Pcd = (dataRow3 == null ? "" : (dataRow3.Field<object>("pcd") == null || !(dataRow3.Field<object>("pcd").ToString() == "1") ? "NÃO" : "SIM")); + if (dataRow3 != null && dataRow3.Field<object>("idcor") != null) + { + if (string.IsNullOrWhiteSpace((dataRow3 != null ? dataRow3.Field<object>("idcor").ToString() : null))) + { + goto Label13; + } + description2 = ((Cor)Enum.Parse(typeof(Cor), dataRow3.Field<object>("idcor").ToString())).GetDescription<Cor>(); + goto Label12; + } + Label13: + description2 = ""; + Label12: + planilhaCompletum.Cor = description2; + if (dataRow3 != null && dataRow3.Field<object>("correcao") != null) + { + if (string.IsNullOrWhiteSpace((dataRow3 != null ? dataRow3.Field<object>("correcao").ToString() : null))) + { + goto Label15; + } + str2 = ((Correcao)Enum.Parse(typeof(Correcao), dataRow3.Field<object>("correcao").ToString())).GetDescription<Correcao>(); + goto Label14; + } + Label15: + str2 = ""; + Label14: + planilhaCompletum.Correcao = str2; + planilhaCompletum.Bonus = nullable72; + planilhaCompletum.CpfPerfil = (string)((dataRow12 != null ? dataRow12.Field<string>("cpf") : null) ?? ""); + planilhaCompletum.NomePerfil = (string)((dataRow12 != null ? dataRow12.Field<string>("nomecompleto") : null) ?? ""); + if (dataRow12 != null) + { + nullable36 = dataRow12.Field<DateTime?>("datanascimento"); + } + else + { + nullable8 = null; + nullable36 = nullable8; + } + nullable73 = nullable36; + if (nullable73.HasValue) + { + nullable37 = nullable73; + } + else + { + nullable8 = null; + nullable37 = nullable8; + } + planilhaCompletum.NascimentoPerfil = nullable37; + planilhaCompletum.SexoPerfil = str7 ?? ""; + planilhaCompletum.EstadoCivilPerfil = (string)((dataRow12 != null ? dataRow12.Field<string>("estadocivil") : null) ?? ""); + planilhaCompletum.CEPCirculacaoPerfil = (string)((dataRow12 != null ? dataRow12.Field<string>("cepcirculacao") : null) ?? ""); + planilhaCompletum.CEPPernoitePerfil = (string)((dataRow12 != null ? dataRow12.Field<string>("ceppernoite") : null) ?? ""); + planilhaCompletum.DanosMateriasPremios = new decimal?((cobertura1 != null ? cobertura1.Premio : decimal.Zero)); + planilhaCompletum.DanosMateriasFranquia = new decimal?((cobertura1 != null ? cobertura1.Franquia : decimal.Zero)); + planilhaCompletum.DanosMateriasLmi = new decimal?((cobertura1 != null ? cobertura1.Lmi : decimal.Zero)); + planilhaCompletum.DanosCorporaisPremios = new decimal?((cobertura != null ? cobertura.Premio : decimal.Zero)); + planilhaCompletum.DanosCorporaisFranquia = new decimal?((cobertura != null ? cobertura.Franquia : decimal.Zero)); + planilhaCompletum.DanosCorporaisLmi = new decimal?((cobertura != null ? cobertura.Lmi : decimal.Zero)); + planilhaCompletum.DanosMoraisPremios = new decimal?((cobertura2 != null ? cobertura2.Premio : decimal.Zero)); + planilhaCompletum.DanosMoraisFranquia = new decimal?((cobertura2 != null ? cobertura2.Franquia : decimal.Zero)); + planilhaCompletum.DanosMoraisLmi = new decimal?((cobertura2 != null ? cobertura2.Lmi : decimal.Zero)); + planilhaCompletum.AppPremios = new decimal?((cobertura3 != null ? cobertura3.Premio : decimal.Zero)); + planilhaCompletum.AppFranquia = new decimal?((cobertura3 != null ? cobertura3.Franquia : decimal.Zero)); + planilhaCompletum.AppLmi = new decimal?((cobertura3 != null ? cobertura3.Lmi : decimal.Zero)); + planilhaCompletum.CarroReservaPremios = new decimal?((cobertura4 != null ? cobertura4.Premio : decimal.Zero)); + planilhaCompletum.CarroReservaFranquia = new decimal?((cobertura4 != null ? cobertura4.Franquia : decimal.Zero)); + planilhaCompletum.CarroReservaLmi = new decimal?((cobertura4 != null ? cobertura4.Lmi : decimal.Zero)); + planilhaCompletum.CarroReservaObs = (cobertura4 != null ? cobertura4.Observacao : ""); + planilhaCompletum.EnderecoItem = (dataRow4 != null ? dataRow4.Field<string>("enderecoitem") : (dataRow5 != null ? dataRow5.Field<string>("endereco") : null)); + planilhaCompletum.NumeroItem = (dataRow4 != null ? dataRow4.Field<string>("numeroitem") : (dataRow5 != null ? dataRow5.Field<string>("numero") : null)); + planilhaCompletum.ComplementoItem = (dataRow4 != null ? dataRow4.Field<string>("complementoitem") : (dataRow5 != null ? dataRow5.Field<string>("complemento") : null)); + planilhaCompletum.BairroItem = (dataRow4 != null ? dataRow4.Field<string>("bairroitem") : (dataRow5 != null ? dataRow5.Field<string>("bairro") : null)); + planilhaCompletum.CidadeItem = (dataRow4 != null ? dataRow4.Field<string>("cidadeitem") : (dataRow5 != null ? dataRow5.Field<string>("cidade") : null)); + planilhaCompletum.UfItem = (dataRow4 != null ? dataRow4.Field<string>("ufitem") : (dataRow5 != null ? dataRow5.Field<string>("uf") : null)); + planilhaCompletum.CepItem = (dataRow4 != null ? dataRow4.Field<string>("cepitem") : (dataRow5 != null ? dataRow5.Field<string>("cep") : null)); + planilhaCompletum.ObsPatrimonial = (dataRow4 != null ? dataRow4.Field<string>("obsresidencia") : null); + planilhaCompletum.ObsGranizo = (dataRow5 != null ? dataRow5.Field<string>("obs") : null); + planilhaCompletum.CulturaGranizo = (dataRow5 != null ? dataRow5.Field<string>("cultura") : null); + planilhaCompletum.SitioGranizo = (dataRow5 != null ? dataRow5.Field<string>("sitio") : null); + if (dataRow5 != null) + { + nullable38 = dataRow5.Field<decimal?>("subfed"); + } + else + { + nullable5 = null; + nullable38 = nullable5; + } + planilhaCompletum.SubFedGranizo = nullable38; + if (dataRow5 != null) + { + nullable39 = dataRow5.Field<decimal?>("subest"); + } + else + { + nullable5 = null; + nullable39 = nullable5; + } + planilhaCompletum.SubEstGranizo = nullable39; + planilhaCompletum.ImobiliariaPatrimonial = (dataRow4 != null ? dataRow4.Field<string>("imobiliaria") : null); + planilhaCompletum.ContatoPatrimonial = (dataRow4 != null ? dataRow4.Field<string>("contatoresidencia") : null); + planilhaCompletum.Locatario = (dataRow4 != null ? dataRow4.Field<string>("locatario") : null); + planilhaCompletum.DocumentoLocatario = (dataRow4 != null ? dataRow4.Field<string>("cpflocatario1") : null); + planilhaCompletum.DddLocatario = (dataRow4 != null ? dataRow4.Field<string>("dddloc") : null); + planilhaCompletum.TelefoneLocatario = (dataRow4 != null ? dataRow4.Field<string>("foneloc") : null); + planilhaCompletum.Ddd2Locatario = (dataRow4 != null ? dataRow4.Field<string>("ddd2loc") : null); + planilhaCompletum.Telefone2Locatario = (dataRow4 != null ? dataRow4.Field<string>("fone2loc") : null); + planilhaCompletum.Locatario2 = (dataRow4 != null ? dataRow4.Field<string>("locatario2") : null); + planilhaCompletum.DocumentoLocatario2 = (dataRow4 != null ? dataRow4.Field<string>("cpflocatario2") : null); + planilhaCompletum.DddLocatario2 = (dataRow4 != null ? dataRow4.Field<string>("dddlocatario2") : null); + planilhaCompletum.TelefoneLocatario2 = (dataRow4 != null ? dataRow4.Field<string>("fonelocatario2") : null); + planilhaCompletum.Locatario3 = (dataRow4 != null ? dataRow4.Field<string>("locatario3") : null); + planilhaCompletum.DocumentoLocatario3 = (dataRow4 != null ? dataRow4.Field<string>("cpflocatario3") : null); + planilhaCompletum.DddLocatario3 = (dataRow4 != null ? dataRow4.Field<string>("dddlocatario3") : null); + planilhaCompletum.TelefoneLocatario3 = (dataRow4 != null ? dataRow4.Field<string>("fonelocatario3") : null); + planilhaCompletum.BensPatrimonial = (dataRow4 != null ? dataRow4.Field<string>("bens") : null); + planilhaCompletum.FabricanteAero = (dataRow6 != null ? dataRow6.Field<string>("fabricante") : null); + planilhaCompletum.ModeloAero = (dataRow6 != null ? dataRow6.Field<string>("modelo") : null); + planilhaCompletum.SerieAero = (dataRow6 != null ? dataRow6.Field<string>("serieregistro") : null); + planilhaCompletum.NomeAero = (dataRow6 != null ? dataRow6.Field<string>("nomeprefixo") : null); + if (dataRow6 != null) + { + nullable40 = dataRow6.Field<int?>("anofab"); + } + else + { + nullable75 = null; + nullable40 = nullable75; + } + planilhaCompletum.AnoFabAero = nullable40; + if (dataRow6 != null) + { + nullable41 = dataRow6.Field<int?>("tripulantes"); + } + else + { + nullable75 = null; + nullable41 = nullable75; + } + planilhaCompletum.TripulantesAero = nullable41; + if (dataRow6 != null) + { + nullable42 = dataRow6.Field<int?>("passageiros"); + } + else + { + nullable75 = null; + nullable42 = nullable75; + } + nullable75 = nullable42; + planilhaCompletum.PassageirosAero = new int?(nullable75.GetValueOrDefault()); + if (dataRow6 != null) + { + nullable43 = dataRow6.Field<long?>("peso"); + } + else + { + nullable9 = null; + nullable43 = nullable9; + } + nullable9 = nullable43; + planilhaCompletum.PesoAero = new decimal?(nullable9.GetValueOrDefault()); + planilhaCompletum.MarinaAero = (dataRow6 != null ? dataRow6.Field<string>("marinaaero") : null); + planilhaCompletum.CertificadoAero = (dataRow6 != null ? dataRow6.Field<string>("certificado") : null); + if (dataRow6 != null) + { + nullable44 = dataRow6.Field<DateTime?>("vistoria"); + } + else + { + nullable73 = null; + nullable44 = nullable73; + } + planilhaCompletum.VistoriaAero = nullable44; + planilhaCompletum.CascoAero = (dataRow6 != null ? dataRow6.Field<string>("casco") : null); + planilhaCompletum.NavegacaoAero = (dataRow6 != null ? dataRow6.Field<string>("navegacao") : null); + planilhaCompletum.ObsAero = (dataRow6 != null ? dataRow6.Field<string>("obs") : null); + planilhaCompletum.ObsRiscos = (dataRow7 != null ? dataRow7.Field<string>("obs") : null); + if (dataRow7 != null) + { + nullable45 = dataRow7.Field<decimal?>("subfed"); + } + else + { + nullable5 = null; + nullable45 = nullable5; + } + planilhaCompletum.SubFedRiscos = nullable45; + if (dataRow7 != null) + { + nullable46 = dataRow7.Field<decimal?>("subest"); + } + else + { + nullable5 = null; + nullable46 = nullable5; + } + planilhaCompletum.SubEstRiscos = nullable46; + planilhaCompletum.PlanoVida = (dataRow8 != null ? dataRow8.Field<string>("plano") : null); + if (dataRow8 != null) + { + nullable47 = dataRow8.Field<int?>("socios"); + } + else + { + nullable75 = null; + nullable47 = nullable75; + } + planilhaCompletum.SociosVida = nullable47; + if (dataRow8 != null) + { + nullable48 = dataRow8.Field<int?>("funcionarios"); + } + else + { + nullable75 = null; + nullable48 = nullable75; + } + planilhaCompletum.FuncionariosVida = nullable48; + if (dataRow8 != null) + { + nullable49 = dataRow8.Field<decimal?>("capitalsocio"); + } + else + { + nullable5 = null; + nullable49 = nullable5; + } + planilhaCompletum.CapitalSociosVida = nullable49; + if (dataRow8 != null) + { + nullable50 = dataRow8.Field<decimal?>("capitalfunc"); + } + else + { + nullable5 = null; + nullable50 = nullable5; + } + planilhaCompletum.CapitalFuncionariosVida = nullable50; + planilhaCompletum.ObsItem = (list1.Count != 1 ? "" : list1.First<DataRow>().Field<string>("obs")); + planilhaCompletum.DescricaoSinistro = (dataRow9 != null ? dataRow9.Field<string>("descricao") : null); + planilhaCompletum.NumeroSinistro = (dataRow9 != null ? dataRow9.Field<string>("numsinistro") : null); + if (dataRow9 != null) + { + nullable73 = dataRow9.Field<DateTime?>("datareclamacao"); + if (!nullable73.HasValue) + { + goto Label17; + } + if (dataRow9 != null) + { + nullable51 = dataRow9.Field<DateTime?>("datareclamacao"); + goto Label16; + } + else + { + nullable73 = null; + nullable51 = nullable73; + goto Label16; + } + } + Label17: + nullable73 = null; + nullable51 = nullable73; + Label16: + planilhaCompletum.DataReclamacao = nullable51; + if (dataRow9 != null) + { + nullable73 = dataRow9.Field<DateTime?>("datasinistro"); + if (!nullable73.HasValue) + { + goto Label19; + } + if (dataRow9 != null) + { + nullable52 = dataRow9.Field<DateTime?>("datasinistro"); + goto Label18; + } + else + { + nullable73 = null; + nullable52 = nullable73; + goto Label18; + } + } + Label19: + nullable73 = null; + nullable52 = nullable73; + Label18: + planilhaCompletum.DataSinistro = nullable52; + if (dataRow9 != null) + { + nullable73 = dataRow9.Field<DateTime?>("dataliquidacao"); + if (!nullable73.HasValue) + { + goto Label21; + } + if (dataRow9 != null) + { + nullable53 = dataRow9.Field<DateTime?>("dataliquidacao"); + goto Label20; + } + else + { + nullable73 = null; + nullable53 = nullable73; + goto Label20; + } + } + Label21: + nullable73 = null; + nullable53 = nullable73; + Label20: + planilhaCompletum.DataLiquidacao = nullable53; + planilhaCompletum.ObsSinistro = (str6.Length > 30000 ? str6.Substring(0, 30000) : str6); + planilhaCompletum.MotivoSinistro = (dataRow9 != null ? dataRow9.Field<string>("motivo") : null); + if (dataRow9 != null) + { + nullable5 = dataRow9.Field<decimal?>("valor"); + if (!nullable5.HasValue) + { + goto Label23; + } + if (dataRow9 != null) + { + nullable54 = dataRow9.Field<decimal?>("valor"); + goto Label22; + } + else + { + nullable5 = null; + nullable54 = nullable5; + goto Label22; + } + } + Label23: + nullable5 = null; + nullable54 = nullable5; + Label22: + planilhaCompletum.ValorSinistro = nullable54; + if (dataRow9 != null) + { + nullable5 = dataRow9.Field<decimal?>("vlrfranquia"); + if (!nullable5.HasValue) + { + goto Label25; + } + if (dataRow9 != null) + { + nullable55 = dataRow9.Field<decimal?>("vlrfranquia"); + goto Label24; + } + else + { + nullable5 = null; + nullable55 = nullable5; + goto Label24; + } + } + Label25: + nullable5 = null; + nullable55 = nullable5; + Label24: + planilhaCompletum.ValorFranquiaSinistro = nullable55; + if (dataRow9 != null) + { + nullable5 = dataRow9.Field<decimal?>("vlrorcado"); + if (!nullable5.HasValue) + { + goto Label27; + } + if (dataRow9 != null) + { + nullable56 = dataRow9.Field<decimal?>("vlrorcado"); + goto Label26; + } + else + { + nullable5 = null; + nullable56 = nullable5; + goto Label26; + } + } + Label27: + nullable5 = null; + nullable56 = nullable5; + Label26: + planilhaCompletum.ValorOrcado = nullable56; + if (dataRow9 != null) + { + nullable5 = dataRow9.Field<decimal?>("vlrliberado"); + if (!nullable5.HasValue) + { + goto Label29; + } + if (dataRow9 != null) + { + nullable57 = dataRow9.Field<decimal?>("vlrliberado"); + goto Label28; + } + else + { + nullable5 = null; + nullable57 = nullable5; + goto Label28; + } + } + Label29: + nullable5 = null; + nullable57 = nullable5; + Label28: + planilhaCompletum.ValorLiberado = nullable57; + if (dataRow9 != null) + { + nullable5 = dataRow9.Field<decimal?>("vlrpago"); + if (!nullable5.HasValue) + { + goto Label31; + } + if (dataRow9 != null) + { + nullable58 = dataRow9.Field<decimal?>("vlrpago"); + goto Label30; + } + else + { + nullable5 = null; + nullable58 = nullable5; + goto Label30; + } + } + Label31: + nullable5 = null; + nullable58 = nullable5; + Label30: + planilhaCompletum.ValorPago = nullable58; + if (dataRow9 != null) + { + nullable5 = dataRow9.Field<decimal?>("vlrsalvado"); + if (!nullable5.HasValue) + { + goto Label33; + } + if (dataRow9 != null) + { + nullable59 = dataRow9.Field<decimal?>("vlrsalvado"); + goto Label32; + } + else + { + nullable5 = null; + nullable59 = nullable5; + goto Label32; + } + } + Label33: + nullable5 = null; + nullable59 = nullable5; + Label32: + planilhaCompletum.ValorSalvo = nullable59; + planilhaCompletum.Parentesco = (dataRow10 != null ? ((ParentescoVinculo?)Enum.Parse(typeof(ParentescoVinculo), dataRow10.Field<object>("parentesco").ToString())).GetDescription<ParentescoVinculo?>() : ""); + if (dataRow11 != null) + { + nullable5 = dataRow11.Field<decimal?>("franquia"); + if (!nullable5.HasValue) + { + goto Label35; + } + if (dataRow11 != null) + { + nullable60 = dataRow11.Field<decimal?>("franquia"); + goto Label34; + } + else + { + nullable5 = null; + nullable60 = nullable5; + goto Label34; + } + } + Label35: + nullable5 = null; + nullable60 = nullable5; + Label34: + planilhaCompletum.ValorFranquiaApolice = nullable60; + planilhaCompletum.QtdeEndosso = num1; + planilhaCompletum.QtdeSinistro = num2; + planilhaCompletum.BensConsorcio = (dataRow13 != null ? dataRow13.Field<string>("bensconsorcio") : null); + planilhaCompletum.Grupo = (dataRow13 != null ? dataRow13.Field<string>("grupo") : null); + planilhaCompletum.Cota = (dataRow13 != null ? dataRow13.Field<string>("cota") : null); + if (dataRow13 != null) + { + nullable61 = dataRow13.Field<decimal?>("valorCredito"); + } + else + { + nullable5 = null; + nullable61 = nullable5; + } + planilhaCompletum.ValorCredito = nullable61; + planilhaCompletum.AreaRiscos = (dataRow7 != null ? dataRow7.Field<string>("area") : null); + planilhaCompletum.AreaGranizo = (dataRow5 != null ? dataRow5.Field<string>("area") : null); + planilhaCompletas.Add(planilhaCompletum); + } + catch (Exception exception) + { + } + }); + return planilhaCompletas; + } + + public List<PlanilhaCompleta> PlanilhaCompletaFatura(List<long> ids, Relatorio relatorio, DateTime inicio, DateTime fim, bool configFranquia, bool configSomaPremio) + { + // + // Current member / type: System.Collections.Generic.List`1<Gestor.Model.Domain.Relatorios.PlanilhaCompleta> Gestor.Infrastructure.Repository.Logic.ReportRepository::PlanilhaCompletaFatura(System.Collections.Generic.List`1<System.Int64>,Gestor.Model.Common.Relatorio,System.DateTime,System.DateTime,System.Boolean,System.Boolean) + // File path: C:\AggerSeguros\Lib\Gestor.Infrastructure.dll + // + // Product version: 0.0.0.0 + // Exception in: System.Collections.Generic.List<Gestor.Model.Domain.Relatorios.PlanilhaCompleta> PlanilhaCompletaFatura(System.Collections.Generic.List<System.Int64>,Gestor.Model.Common.Relatorio,System.DateTime,System.DateTime,System.Boolean,System.Boolean) + // + // An item with the same key has already been added. Key: Label0 + // at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior) + // at System.Collections.Generic.Dictionary`2.System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Add(KeyValuePair`2 keyValuePair) + // at Telerik.JustDecompiler.Common.Extensions.AddRange[TKey,TValue](IDictionary`2 self, IDictionary`2 source) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Common\Extensions.cs:line 99 + // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.AnonymousDelegateRebuilder.VisitObjectCreationExpression(ObjectCreationExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 332 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit[TCollection,TElement](TCollection original) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 290 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ExpressionCollection node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 322 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitMethodInvocationExpression(MethodInvocationExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 499 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitExpressionStatement(ExpressionStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 383 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 + // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.AnonymousDelegateRebuilder.Match(BlockStatement theBlock, Int32 index) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 114 + // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.VisitBlockStatement(BlockStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 30 + // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.Process(DecompilationContext context, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 21 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 + // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 + // at Telerik.JustDecompiler.Decompiler.Extensions.RunPipeline(DecompilationPipeline pipeline, ILanguage language, MethodBody body, DecompilationContext& context) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 95 + // at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61 + // at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 118 + // + // mailto: JustDecompilePublicFeedback@telerik.com + + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RestricaoUsuarioCamposRelatoriosRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RestricaoUsuarioCamposRelatoriosRepository.cs new file mode 100644 index 0000000..12ab574 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RestricaoUsuarioCamposRelatoriosRepository.cs @@ -0,0 +1,44 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class RestricaoUsuarioCamposRelatoriosRepository : GenericRepository<RestricaoUsuarioCamposRelatoriosDb>, IRestricaoUsuarioCamposRelatoriosRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public RestricaoUsuarioCamposRelatoriosRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public List<RestricaoUsuarioCamposRelatorios> FindByUsuario(long id) + { + List<RestricaoUsuarioCamposRelatoriosDb> list = this._unitOfWork.Session.CreateQuery(string.Format("from RestricaoUsuarioCamposRelatoriosDb WHERE Usuario = {0}", id)).List<RestricaoUsuarioCamposRelatoriosDb>().ToList<RestricaoUsuarioCamposRelatoriosDb>(); + return ApplicationMapper.Mapper.Map<List<RestricaoUsuarioCamposRelatoriosDb>, List<RestricaoUsuarioCamposRelatorios>>(list); + } + + public RestricaoUsuarioCamposRelatorios Merge(RestricaoUsuarioCamposRelatorios restricao) + { + RestricaoUsuarioCamposRelatoriosDb restricaoUsuarioCamposRelatoriosDb = ApplicationMapper.Mapper.Map<RestricaoUsuarioCamposRelatorios, RestricaoUsuarioCamposRelatoriosDb>(restricao); + base.Merge(restricaoUsuarioCamposRelatoriosDb); + return ApplicationMapper.Mapper.Map<RestricaoUsuarioCamposRelatoriosDb, RestricaoUsuarioCamposRelatorios>(restricaoUsuarioCamposRelatoriosDb); + } + + public RestricaoUsuarioCamposRelatorios SaveOrUpdate(RestricaoUsuarioCamposRelatorios restricao) + { + RestricaoUsuarioCamposRelatoriosDb restricaoUsuarioCamposRelatoriosDb = ApplicationMapper.Mapper.Map<RestricaoUsuarioCamposRelatorios, RestricaoUsuarioCamposRelatoriosDb>(restricao); + this.SaveOrUpdate(restricaoUsuarioCamposRelatoriosDb); + return ApplicationMapper.Mapper.Map<RestricaoUsuarioCamposRelatoriosDb, RestricaoUsuarioCamposRelatorios>(restricaoUsuarioCamposRelatoriosDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RestricaoUsuarioRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RestricaoUsuarioRepository.cs new file mode 100644 index 0000000..3d1fbcc --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RestricaoUsuarioRepository.cs @@ -0,0 +1,54 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class RestricaoUsuarioRepository : GenericRepository<RestricaoUsuarioDb>, IRestricaoUsuarioRepository + { + private readonly GenericUnitOfWork _unitOfWork; + + public RestricaoUsuarioRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public List<RestricaoUsuario> FindByUsuario(long id) + { + List<RestricaoUsuarioDb> list = this._unitOfWork.Session.CreateQuery(string.Format("from RestricaoUsuarioDb WHERE IdUsuario = {0}", id)).List<RestricaoUsuarioDb>().ToList<RestricaoUsuarioDb>(); + return ApplicationMapper.Mapper.Map<List<RestricaoUsuarioDb>, List<RestricaoUsuario>>(list); + } + + public RestricaoUsuario FindRestricao(long id, TipoRestricao restricao) + { + RestricaoUsuarioDb restricaoUsuarioDb = base.All().FirstOrDefault<RestricaoUsuarioDb>((RestricaoUsuarioDb x) => x.Usuario.Id == id && (int)x.Tipo == (int)restricao); + return ApplicationMapper.Mapper.Map<RestricaoUsuarioDb, RestricaoUsuario>(restricaoUsuarioDb); + } + + public RestricaoUsuario Merge(RestricaoUsuario restricao) + { + RestricaoUsuarioDb restricaoUsuarioDb = ApplicationMapper.Mapper.Map<RestricaoUsuario, RestricaoUsuarioDb>(restricao); + base.Merge(restricaoUsuarioDb); + return ApplicationMapper.Mapper.Map<RestricaoUsuarioDb, RestricaoUsuario>(restricaoUsuarioDb); + } + + public RestricaoUsuario SaveOrUpdate(RestricaoUsuario restricao) + { + RestricaoUsuarioDb restricaoUsuarioDb = ApplicationMapper.Mapper.Map<RestricaoUsuario, RestricaoUsuarioDb>(restricao); + this.SaveOrUpdate(restricaoUsuarioDb); + return ApplicationMapper.Mapper.Map<RestricaoUsuarioDb, RestricaoUsuario>(restricaoUsuarioDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RiscosDiversosRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RiscosDiversosRepository.cs new file mode 100644 index 0000000..6353540 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RiscosDiversosRepository.cs @@ -0,0 +1,66 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class RiscosDiversosRepository : GenericRepository<RiscosDiversosDb>, IRiscosDiversosRepository, IGenericRepository<RiscosDiversosDb> + { + private readonly GenericUnitOfWork _unitOfWork; + + public RiscosDiversosRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public void DeleteRange(List<long> ids) + { + List<RiscosDiversosDb> list = ( + from x in base.All() + where ids.Contains(x.Item.Id) + select x).ToList<RiscosDiversosDb>(); + base.DeleteRange(list); + } + + public RiscosDiversos Find(long id) + { + RiscosDiversosDb riscosDiversosDb = base.All().FirstOrDefault<RiscosDiversosDb>((RiscosDiversosDb x) => x.Item.Id == id) ?? new RiscosDiversosDb(); + return ApplicationMapper.Mapper.Map<RiscosDiversosDb, RiscosDiversos>(riscosDiversosDb); + } + + public RiscosDiversos FindById(long id) + { + RiscosDiversosDb riscosDiversosDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map<RiscosDiversosDb, RiscosDiversos>(riscosDiversosDb); + } + + public RiscosDiversos Merge(RiscosDiversos risco) + { + RiscosDiversosDb riscosDiversosDb = ApplicationMapper.Mapper.Map<RiscosDiversos, RiscosDiversosDb>(risco); + base.Merge(riscosDiversosDb); + return ApplicationMapper.Mapper.Map<RiscosDiversosDb, RiscosDiversos>(riscosDiversosDb); + } + + public RiscosDiversos SaveOrUpdate(RiscosDiversos risco) + { + RiscosDiversosDb riscosDiversosDb = ApplicationMapper.Mapper.Map<RiscosDiversos, RiscosDiversosDb>(risco); + this.SaveOrUpdate(riscosDiversosDb); + return ApplicationMapper.Mapper.Map<RiscosDiversosDb, RiscosDiversos>(riscosDiversosDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SaldoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SaldoRepository.cs new file mode 100644 index 0000000..5249fcf --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SaldoRepository.cs @@ -0,0 +1,136 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Financeiro; +using Gestor.Infrastructure.Helpers; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Financeiro; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class SaldoRepository : GenericRepository<SaldoDb>, ISaldoRepository, IGenericRepository<SaldoDb> + { + private readonly GenericUnitOfWork _unitOfWork; + + public SaldoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public Saldo BuscarAberto(long id) + { + string str = string.Format(" AND idconta = {0} AND dtfim IS NULL", id); + return this.Select(str).FirstOrDefault<Saldo>(); + } + + public List<Saldo> BuscarPorConta(long id) + { + return this.Select(string.Format(" AND idconta = {0}", id)); + } + + public Saldo BuscarPorData(DateTime inicio, long id) + { + string str = string.Format(" AND idconta = {0}", id); + return ( + from x in this.Select(str) + orderby x.DataInicio descending + select x).FirstOrDefault<Saldo>((Saldo x) => { + DateTime? dataInicio = x.DataInicio; + DateTime dateTime = inicio; + if (!dataInicio.HasValue) + { + return false; + } + return dataInicio.GetValueOrDefault() <= dateTime; + }); + } + + public Saldo BuscarPorMenorData(long id) + { + string str = string.Format(" AND idconta = {0}", id); + return ( + from x in this.Select(str) + orderby x.DataInicio + select x).FirstOrDefault<Saldo>(); + } + + public void Delete(long id) + { + SaldoDb saldoDb = base.FindEntityById(id); + if (saldoDb == null) + { + return; + } + base.Delete(saldoDb); + } + + public Saldo FindById(long id) + { + SaldoDb saldoDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map<SaldoDb, Saldo>(saldoDb); + } + + public Saldo Merge(Saldo saldo) + { + SaldoDb saldoDb = ApplicationMapper.Mapper.Map<Saldo, SaldoDb>(saldo); + base.Merge(saldoDb); + return ApplicationMapper.Mapper.Map<SaldoDb, Saldo>(saldoDb); + } + + public Saldo SaveOrUpdate(Saldo saldo) + { + SaldoDb saldoDb = ApplicationMapper.Mapper.Map<Saldo, SaldoDb>(saldo); + this.SaveOrUpdate(saldoDb); + return ApplicationMapper.Mapper.Map<SaldoDb, Saldo>(saldoDb); + } + + private List<Saldo> Select(string condition) + { + List<Saldo> saldos; + object connection; + DataTable dataTable = new DataTable(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + AuxiliarFinanceiro.Criar(sqlCommand); + sqlCommand.CommandText = string.Concat("SELECT * FROM saldo WHERE 1=1 ", condition); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + if (dataTable.Rows.Count != 0) + { + return CustomMap.MapSaldo(dataTable); + } + else + { + saldos = new List<Saldo>(); + } + } + } + return saldos; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraContatoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraContatoRepository.cs new file mode 100644 index 0000000..19ee09a --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraContatoRepository.cs @@ -0,0 +1,131 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Helpers; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class SeguradoraContatoRepository : GenericRepository<SeguradoraContatoDb>, ISeguradoraContatoRepository, IGenericRepository<SeguradoraContatoDb> + { + private readonly GenericUnitOfWork _unitOfWork; + + public SeguradoraContatoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + SeguradoraContatoDb seguradoraContatoDb = base.FindEntityById(id); + if (seguradoraContatoDb == null) + { + return; + } + base.Delete(seguradoraContatoDb); + } + + public List<SeguradoraContato> FindAssistencia(long empresa, long id) + { + List<Condicao> condicaos = new List<Condicao>() + { + new Condicao() + { + Campo = "idempresa", + Valores = empresa.CriarValor<long>() + }, + new Condicao() + { + Campo = "idciaseg", + Valores = id.CriarValor<long>() + }, + new Condicao() + { + Campo = "TipoContato", + Valores = 1.CriarValor<int>() + } + }; + return this._unitOfWork.Select(condicaos.CreateParameters(0), "SELECT TOP 4 * FROM ciacontato WHERE ", "").MapSeguradoraContato(); + } + + public SeguradoraContato FindById(long id) + { + SeguradoraContatoDb seguradoraContatoDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map<SeguradoraContatoDb, SeguradoraContato>(seguradoraContatoDb); + } + + public List<SeguradoraContato> FindBySeguradora(long empresa, long id) + { + List<Condicao> condicaos = new List<Condicao>() + { + new Condicao() + { + Campo = "idempresa", + Valores = empresa.CriarValor<long>() + }, + new Condicao() + { + Campo = "idciaseg", + Valores = id.CriarValor<long>() + } + }; + return this._unitOfWork.Select(condicaos.CreateParameters(0), "SELECT * FROM ciacontato WHERE ", "").MapSeguradoraContato(); + } + + public SeguradoraContato Merge(SeguradoraContato contato) + { + SeguradoraContatoDb seguradoraContatoDb = ApplicationMapper.Mapper.Map<SeguradoraContato, SeguradoraContatoDb>(contato); + base.Merge(seguradoraContatoDb); + return ApplicationMapper.Mapper.Map<SeguradoraContatoDb, SeguradoraContato>(seguradoraContatoDb); + } + + public List<SeguradoraContato> Merge(List<SeguradoraContato> contatos, Seguradora seguradora, long empresa) + { + IQueryable<SeguradoraContatoDb> seguradoraContatoDbs = + from x in base.All() + where x.Seguradora.Id == seguradora.Id && x.Empresa.Id == empresa + select x; + SeguradoraContatoRepository seguradoraContatoRepository = this; + ( + from x in seguradoraContatoDbs + select x.Id).ToList<long>().Where<long>((long x) => { + List<SeguradoraContato> seguradoraContatos = contatos; + Func<SeguradoraContato, long> u003cu003e9_64 = SeguradoraContatoRepository.u003cu003ec.u003cu003e9__6_4; + if (u003cu003e9_64 == null) + { + u003cu003e9_64 = (SeguradoraContato t) => t.Id; + SeguradoraContatoRepository.u003cu003ec.u003cu003e9__6_4 = u003cu003e9_64; + } + return !seguradoraContatos.Select<SeguradoraContato, long>(u003cu003e9_64).Contains<long>(x); + }).ToList<long>().ForEach(new Action<long>(seguradoraContatoRepository.Delete)); + List<SeguradoraContatoDb> seguradoraContatoDbs1 = ApplicationMapper.Mapper.Map<List<SeguradoraContato>, List<SeguradoraContatoDb>>(contatos); + seguradoraContatoDbs1.ForEach((SeguradoraContatoDb x) => { + if (x.Id == 0) + { + this.SaveOrUpdate(x); + return; + } + base.Merge(x); + }); + return ApplicationMapper.Mapper.Map<List<SeguradoraContatoDb>, List<SeguradoraContato>>(seguradoraContatoDbs1); + } + + public SeguradoraContato SaveOrUpdate(SeguradoraContato contato) + { + SeguradoraContatoDb seguradoraContatoDb = ApplicationMapper.Mapper.Map<SeguradoraContato, SeguradoraContatoDb>(contato); + this.SaveOrUpdate(seguradoraContatoDb); + return ApplicationMapper.Mapper.Map<SeguradoraContatoDb, SeguradoraContato>(seguradoraContatoDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraEnderecoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraEnderecoRepository.cs new file mode 100644 index 0000000..a88001e --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraEnderecoRepository.cs @@ -0,0 +1,97 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class SeguradoraEnderecoRepository : GenericRepository<SeguradoraEnderecoDb>, ISeguradoraEnderecoRepository, IGenericRepository<SeguradoraEnderecoDb> + { + private readonly GenericUnitOfWork _unitOfWork; + + public SeguradoraEnderecoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + SeguradoraEnderecoDb seguradoraEnderecoDb = base.FindEntityById(id); + if (seguradoraEnderecoDb == null) + { + return; + } + base.Delete(seguradoraEnderecoDb); + } + + public SeguradoraEndereco FindById(long id) + { + SeguradoraEnderecoDb seguradoraEnderecoDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map<SeguradoraEnderecoDb, SeguradoraEndereco>(seguradoraEnderecoDb); + } + + public List<SeguradoraEndereco> FindBySeguradora(long empresa, long id) + { + List<SeguradoraEnderecoDb> list = ( + from x in base.All() + where x.Empresa.Id == empresa && x.Seguradora.Id == id + select x).ToList<SeguradoraEnderecoDb>(); + return ApplicationMapper.Mapper.Map<List<SeguradoraEnderecoDb>, List<SeguradoraEndereco>>(list); + } + + public SeguradoraEndereco Merge(SeguradoraEndereco endereco) + { + SeguradoraEnderecoDb seguradoraEnderecoDb = ApplicationMapper.Mapper.Map<SeguradoraEndereco, SeguradoraEnderecoDb>(endereco); + base.Merge(seguradoraEnderecoDb); + return ApplicationMapper.Mapper.Map<SeguradoraEnderecoDb, SeguradoraEndereco>(seguradoraEnderecoDb); + } + + public List<SeguradoraEndereco> Merge(List<SeguradoraEndereco> enderecos, Seguradora seguradora, long empresa) + { + IQueryable<SeguradoraEnderecoDb> seguradoraEnderecoDbs = + from x in base.All() + where x.Seguradora.Id == seguradora.Id && x.Empresa.Id == empresa + select x; + SeguradoraEnderecoRepository seguradoraEnderecoRepository = this; + ( + from x in seguradoraEnderecoDbs + select x.Id).ToList<long>().Where<long>((long x) => { + List<SeguradoraEndereco> seguradoraEnderecos = enderecos; + Func<SeguradoraEndereco, long> u003cu003e9_64 = SeguradoraEnderecoRepository.u003cu003ec.u003cu003e9__6_4; + if (u003cu003e9_64 == null) + { + u003cu003e9_64 = (SeguradoraEndereco t) => t.Id; + SeguradoraEnderecoRepository.u003cu003ec.u003cu003e9__6_4 = u003cu003e9_64; + } + return !seguradoraEnderecos.Select<SeguradoraEndereco, long>(u003cu003e9_64).Contains<long>(x); + }).ToList<long>().ForEach(new Action<long>(seguradoraEnderecoRepository.Delete)); + List<SeguradoraEnderecoDb> seguradoraEnderecoDbs1 = ApplicationMapper.Mapper.Map<List<SeguradoraEndereco>, List<SeguradoraEnderecoDb>>(enderecos); + seguradoraEnderecoDbs1.ForEach((SeguradoraEnderecoDb x) => { + if (x.Id == 0) + { + this.SaveOrUpdate(x); + return; + } + base.Merge(x); + }); + return ApplicationMapper.Mapper.Map<List<SeguradoraEnderecoDb>, List<SeguradoraEndereco>>(seguradoraEnderecoDbs1); + } + + public SeguradoraEndereco SaveOrUpdate(SeguradoraEndereco endereco) + { + SeguradoraEnderecoDb seguradoraEnderecoDb = ApplicationMapper.Mapper.Map<SeguradoraEndereco, SeguradoraEnderecoDb>(endereco); + this.SaveOrUpdate(seguradoraEnderecoDb); + return ApplicationMapper.Mapper.Map<SeguradoraEnderecoDb, SeguradoraEndereco>(seguradoraEnderecoDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraRepository.cs new file mode 100644 index 0000000..328fa86 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraRepository.cs @@ -0,0 +1,76 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class SeguradoraRepository : GenericRepository<SeguradoraDb>, ISeguradoraRepository, IGenericRepository<SeguradoraDb> + { + private readonly GenericUnitOfWork _unitOfWork; + + public SeguradoraRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public List<Seguradora> Find(string filter) + { + SeguradoraRepository.u003cu003ec__DisplayClass3_0 variable = null; + IQueryable<SeguradoraDb> seguradoraDbs = base.All(); + ParameterExpression parameterExpression = Expression.Parameter(typeof(SeguradoraDb), "x"); + IQueryable<SeguradoraDb> seguradoraDbs1 = seguradoraDbs.Where<SeguradoraDb>(Expression.Lambda<Func<SeguradoraDb, bool>>(Expression.OrElse(Expression.OrElse(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(SeguradoraDb).GetMethod("get_Nome").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty<Expression>()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(SeguradoraRepository.u003cu003ec__DisplayClass3_0)), FieldInfo.GetFieldFromHandle(typeof(SeguradoraRepository.u003cu003ec__DisplayClass3_0).GetField("filter").FieldHandle)) }), Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(SeguradoraDb).GetMethod("get_Documento").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(SeguradoraRepository.u003cu003ec__DisplayClass3_0)), FieldInfo.GetFieldFromHandle(typeof(SeguradoraRepository.u003cu003ec__DisplayClass3_0).GetField("filter").FieldHandle)) })), Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(SeguradoraDb).GetMethod("get_Susep").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(SeguradoraRepository.u003cu003ec__DisplayClass3_0)), FieldInfo.GetFieldFromHandle(typeof(SeguradoraRepository.u003cu003ec__DisplayClass3_0).GetField("filter").FieldHandle)) })), new ParameterExpression[] { parameterExpression })); + parameterExpression = Expression.Parameter(typeof(SeguradoraDb), "x"); + return seguradoraDbs1.Select<SeguradoraDb, Seguradora>(Expression.Lambda<Func<SeguradoraDb, Seguradora>>(Expression.MemberInit(Expression.New(typeof(Seguradora)), new MemberBinding[] { Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(DomainBase).GetMethod("set_Id", new Type[] { typeof(long) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(EntityBase).GetMethod("get_Id").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Seguradora).GetMethod("set_Nome", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(SeguradoraDb).GetMethod("get_Nome").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Seguradora).GetMethod("set_Documento", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(SeguradoraDb).GetMethod("get_Documento").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Seguradora).GetMethod("set_Susep", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(SeguradoraDb).GetMethod("get_Susep").MethodHandle))) }), new ParameterExpression[] { parameterExpression })).ToList<Seguradora>(); + } + + public List<Seguradora> Find(bool ativo) + { + List<SeguradoraDb> list = this._unitOfWork.Session.CreateQuery("from SeguradoraDb where ativo IS NULL OR ativo = '1'").List<SeguradoraDb>().ToList<SeguradoraDb>(); + return ApplicationMapper.Mapper.Map<List<SeguradoraDb>, List<Seguradora>>(list); + } + + public List<Seguradora> Find() + { + List<SeguradoraDb> list = base.All().ToList<SeguradoraDb>(); + return ApplicationMapper.Mapper.Map<List<SeguradoraDb>, List<Seguradora>>(list); + } + + public Seguradora FindById(long id) + { + SeguradoraDb seguradoraDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map<SeguradoraDb, Seguradora>(seguradoraDb); + } + + public Seguradora Merge(Seguradora seguradora) + { + SeguradoraDb seguradoraDb = ApplicationMapper.Mapper.Map<Seguradora, SeguradoraDb>(seguradora); + base.Merge(seguradoraDb); + return ApplicationMapper.Mapper.Map<SeguradoraDb, Seguradora>(seguradoraDb); + } + + public Seguradora SaveOrUpdate(Seguradora seguradora) + { + SeguradoraDb seguradoraDb = ApplicationMapper.Mapper.Map<Seguradora, SeguradoraDb>(seguradora); + this.SaveOrUpdate(seguradoraDb); + return ApplicationMapper.Mapper.Map<SeguradoraDb, Seguradora>(seguradoraDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroAutoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroAutoRepository.cs new file mode 100644 index 0000000..f4ad079 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroAutoRepository.cs @@ -0,0 +1,61 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class SinistroAutoRepository : GenericRepository<SinistroAutoDb>, ISinistroAutoRepository, IGenericRepository<SinistroAutoDb> + { + private readonly GenericUnitOfWork _unitOfWork; + + public SinistroAutoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public SinistroAuto FindById(long id) + { + SinistroAutoDb sinistroAutoDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map<SinistroAutoDb, SinistroAuto>(sinistroAutoDb); + } + + public SinistroAuto FindBySinistroId(long id) + { + SinistroAutoDb sinistroAutoDb = base.All().FirstOrDefault<SinistroAutoDb>((SinistroAutoDb x) => x.Sinistro.Id == id); + return ApplicationMapper.Mapper.Map<SinistroAutoDb, SinistroAuto>(sinistroAutoDb); + } + + public SinistroAuto Merge(SinistroAuto sinistroAuto) + { + SinistroAutoDb sinistroAutoDb = ApplicationMapper.Mapper.Map<SinistroAuto, SinistroAutoDb>(sinistroAuto); + base.Merge(sinistroAutoDb); + return ApplicationMapper.Mapper.Map<SinistroAutoDb, SinistroAuto>(sinistroAutoDb); + } + + public bool ParceiroUtilizado(long id) + { + return base.All().Any<SinistroAutoDb>((SinistroAutoDb x) => x.ParceiroFunilaria.Id == id || x.ParceiroMecanica.Id == id); + } + + public SinistroAuto SaveOrUpdate(SinistroAuto sinistroAuto) + { + SinistroAutoDb sinistroAutoDb = ApplicationMapper.Mapper.Map<SinistroAuto, SinistroAutoDb>(sinistroAuto); + this.SaveOrUpdate(sinistroAutoDb); + return ApplicationMapper.Mapper.Map<SinistroAutoDb, SinistroAuto>(sinistroAutoDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroRepository.cs new file mode 100644 index 0000000..ba62ba0 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroRepository.cs @@ -0,0 +1,415 @@ +using AutoMapper; +using Gestor.Common.Validation; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Helpers; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using NHibernate.Util; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class SinistroRepository : GenericRepository<SinistroDb>, ISinistroRepository, IGenericRepository<SinistroDb> + { + private readonly GenericUnitOfWork _unitOfWork; + + public SinistroRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public List<Sinistro> Find(string numero) + { + List<SinistroDb> list = ( + from x in base.All() + where x.Numero.Normalized().Contains(numero.Normalized()) && numero.Normalized().Contains(x.Numero.Normalized()) + select x).ToList<SinistroDb>(); + return ApplicationMapper.Mapper.Map<List<SinistroDb>, List<Sinistro>>(list); + } + + public List<Sinistro> FindByControleId(long id) + { + List<SinistroDb> list = ( + from x in base.All() + where x.ControleSinistro.Id == id + select x).ToList<SinistroDb>(); + List<Sinistro> sinistros = ApplicationMapper.Mapper.Map<List<SinistroDb>, List<Sinistro>>(list); + sinistros.ForEach((Sinistro x) => { + x.SinistroAuto = (new SinistroAutoRepository(this._unitOfWork)).FindBySinistroId(x.Id); + x.SinistroVida = (new SinistroVidaRepository(this._unitOfWork)).FindBySinistroId(x.Id); + }); + return sinistros; + } + + public List<Sinistro> FindByData(Filtros filtro, bool pendentes = false) + { + object connection; + string str = "CAST(cs.datasinistro AS DATE)"; + string referencia = filtro.Referencia; + if (referencia == "DATA LIQUIDAÇÃO") + { + str = "CAST(s.dataliquidacao AS DATE)"; + } + else if (referencia == "DATA RECLAMAÇÃO") + { + str = "CAST(s.datareclamacao AS DATE)"; + } + List<Condicao> condicaos2 = filtro.CriarCondicao(str); + List<Condicao> list = ( + from x in condicaos2 + where x.Campo == str + select x).ToList<Condicao>(); + if (pendentes) + { + list.Add(new Condicao() + { + Campo = "CAST(s.dataliquidacao AS DATE)", + Valores = null + }); + } + string str1 = (filtro.TipoVendedor == null || filtro.TipoVendedor.Count == 0 ? "OUTER APPLY (SELECT TOP 1 idvendedor FROM vendedorparcela vp WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor = 1) vp" : string.Concat("INNER JOIN vendedorparcela vp ON vp.iddocumento = d.iddocumento AND vp.idtipovendedor IN (", string.Join<long>(",", + from v in filtro.TipoVendedor + select v), ")")); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + DataTable dataTable = new DataTable(); + DataTable dataTable1 = new DataTable(); + DataTable dataTable2 = new DataTable(); + DataTable dataTable3 = new DataTable(); + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + if (sqlConnection != null) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandTimeout = 15000; + string str2 = "SELECT DISTINCT cs.iditem as id, cs.idcontrolesinistro, s.idsinistro, cs.datasinistro as data, s.numsinistro as numero, s.datareclamacao as reclamacao, s.itemsinistrado as item, s.motivo, s.tiposinistro, s.valor as valor, s.vlrorcado as valororcado, s.vlrliberado as valorliberado, s.vlrpago as valorpago, s.vlrfranquia as valorfranquia, s.vlrsalvado as valorsalvado, s.dataliquidacao as liquidacao, s.idstatussinistro, s.StatusPersonalizado, s.auxiliar, s.usuariocriacao, s.usuarioalteracao, s.datacriacao, s.dataalteracao FROM sinistro s INNER JOIN controlesinistro cs on cs.idcontrolesinistro = s.idcontrolesinistro WHERE "; + dataTable = sqlCommand.Select(list.CreateParameters(0), str2, ""); + if (dataTable.Rows.Count != 0) + { + Auxiliar.CriarAuxiliar(sqlCommand, false); + List<Condicao> list1 = condicaos2.Where<Condicao>((Condicao x) => { + if (x.Campo == this.referencia) + { + return false; + } + return x.Campo != "CAST(s.dataliquidacao AS DATE)"; + }).ToList<Condicao>(); + list1.Add(new Condicao() + { + Campo = "d.excluido", + Valores = null, + Grupo = 1, + Operacao = Operacao.Or + }); + list1.Add(new Condicao() + { + Campo = "d.excluido", + Valores = "0".CriarValor<string>(), + Grupo = 1, + Operacao = Operacao.Or + }); + string str3 = string.Concat("SELECT i.iditem as id, cl.nome as cliente, cl.MalaDireta, cl.idcliente, c.idcontrole, c.idempresa, i.iddocumento, d.contrato as apolice, d.aditamento as endosso, d.vigencia1, d.vigencia2, c.idramo, c.idciaseg as idseguradora, c.idproduto, vp.idvendedor, d.idestipulante, d.datacontrole, d.idstatus, d.pasta, cl.pasta as pastacliente, cl.cgccpf as cpfcnpj FROM item i INNER JOIN documento d on d.iddocumento = i.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente ", str1, " WHERE "); + dataTable.AsEnumerable().ForEach<DataRow>((DataRow sinistro) => { + List<Condicao> condicaos = new List<Condicao>() + { + new Condicao() + { + Campo = "i.iditem", + Valores = sinistro.Field<long>("id").CriarValor<long>() + } + }; + condicaos.AddRange(list1); + List<Condicao> condicaos1 = new List<Condicao>() + { + new Condicao() + { + Campo = "idsinistro", + Valores = sinistro.Field<long>("idsinistro").CriarValor<long>() + } + }; + dataTable1.Merge(sqlCommand.Select(condicaos.CreateParameters(0), str3, "")); + dataTable2.Merge(sqlCommand.Select(condicaos1.CreateParameters(0), "SELECT * FROM sinistroauto WHERE", "")); + dataTable3.Merge(sqlCommand.Select(condicaos1.CreateParameters(0), "SELECT * FROM sinistrovida WHERE", "")); + }); + } + else + { + return new List<Sinistro>(); + } + } + } + } + List<long> nums = dataTable1.AsEnumerable().Select<DataRow, long>((DataRow x) => x.Field<long>("id")).ToList<long>(); + List<Sinistro> sinistros = new List<Sinistro>(); + dataTable.AsEnumerable().Where<DataRow>((DataRow x) => nums.Contains(x.Field<long>("id"))).ForEach<DataRow>((DataRow x) => { + TipoPerda? nullable; + object sinistroAuto; + object sinistroVida; + TipoPerda? nullable1; + Parceiro parceiro; + Parceiro parceiro1; + TipoPerda? nullable2; + DataRow dataRow = dataTable1.Select(string.Format("id = {0}", x.Field<long>("id"))).FirstOrDefault<DataRow>(); + if (dataRow == null) + { + return; + } + DataRow dataRow1 = dataTable2.AsEnumerable().ToList<DataRow>().FirstOrDefault<DataRow>((DataRow a) => a.Field<long>("idsinistro") == x.Field<long>("idsinistro")); + if (dataRow1 == null) + { + sinistroAuto = null; + } + else + { + sinistroAuto = new SinistroAuto(); + ((DomainBase)sinistroAuto).Id = dataRow1.Field<long>("idsinistroauto"); + parceiro = (dataRow1.Field<object>("idparceirofunilaria") == null ? null : Auxiliar.Parceiros.Find((Parceiro a) => a.Id == dataRow1.Field<long>("idparceirofunilaria"))); + ((SinistroAuto)sinistroAuto).ParceiroFunilaria = parceiro; + parceiro1 = (dataRow1.Field<object>("idparceiromecanica") == null ? null : Auxiliar.Parceiros.Find((Parceiro a) => a.Id == dataRow1.Field<long>("idparceiromecanica"))); + ((SinistroAuto)sinistroAuto).ParceiroMecanica = parceiro1; + if (dataRow1.Field<object>("idtipoperda") == null) + { + nullable = null; + nullable2 = nullable; + } + else + { + nullable2 = new TipoPerda?((TipoPerda)int.Parse(dataRow1.Field<object>("idtipoperda").ToString())); + } + ((SinistroAuto)sinistroAuto).TipoPerda = nullable2; + ((SinistroAuto)sinistroAuto).Email = dataRow1.Field<string>("email"); + ((SinistroAuto)sinistroAuto).Telefone = string.Concat(dataRow1.Field<string>("ddd"), " ", dataRow1.Field<string>("telefone")); + } + SinistroAuto sinistroAuto1 = (SinistroAuto)sinistroAuto; + DataRow dataRow2 = dataTable3.AsEnumerable().ToList<DataRow>().FirstOrDefault<DataRow>((DataRow a) => a.Field<long>("idsinistro") == x.Field<long>("idsinistro")); + if (dataRow2 == null) + { + sinistroVida = null; + } + else + { + sinistroVida = new SinistroVida(); + ((DomainBase)sinistroVida).Id = dataRow2.Field<long>("idsinistrovida"); + if (dataRow2.Field<object>("tipoperda") == null) + { + nullable = null; + nullable1 = nullable; + } + else + { + nullable1 = new TipoPerda?((TipoPerda)int.Parse(dataRow2.Field<object>("tipoperda").ToString())); + } + ((SinistroVida)sinistroVida).TipoPerda = nullable1; + ((SinistroVida)sinistroVida).Beneficiario = dataRow2.Field<string>("beneficiario"); + } + SinistroVida sinistroVida1 = (SinistroVida)sinistroVida; + Sinistro sinistro1 = new Sinistro() + { + Id = x.Field<long>("idsinistro"), + Numero = x.Field<string>("numero"), + ItemSinistrado = x.Field<string>("item"), + Motivo = x.Field<string>("motivo"), + TipoSinistro = new TipoSinistro?((TipoSinistro)Enum.Parse(typeof(TipoSinistro), x.Field<object>("tiposinistro").ToString())), + DataReclamacao = new DateTime?((x.Field<object>("reclamacao") != null ? x.Field<DateTime>("reclamacao") : (x.Field<object>("data") != null ? x.Field<DateTime>("data") : DateTime.MinValue))), + Valor = (x.Field<object>("valor") == null ? decimal.Zero : x.Field<decimal>("valor")), + ValorOrcado = (x.Field<object>("valororcado") == null ? decimal.Zero : x.Field<decimal>("valororcado")), + ValorLiberado = (x.Field<object>("valorliberado") == null ? decimal.Zero : x.Field<decimal>("valorliberado")), + ValorSalvado = new decimal?((x.Field<object>("valorsalvado") == null ? decimal.Zero : x.Field<decimal>("valorsalvado"))), + ValorFranquia = (x.Field<object>("valorfranquia") == null ? decimal.Zero : x.Field<decimal>("valorfranquia")), + ValorPago = (x.Field<object>("valorpago") == null ? decimal.Zero : x.Field<decimal>("valorpago")), + DataLiquidacao = x.Field<DateTime?>("liquidacao"), + StatusSinistro = new StatusSinistro?((StatusSinistro)((x.Field<object>("idstatussinistro") == null ? 0 : (StatusSinistro)x.Field<object>("idstatussinistro")))), + SinistroAuto = sinistroAuto1, + SinistroVida = sinistroVida1, + StatusPersonalizado = x.Field<string>("StatusPersonalizado"), + Auxiliar = x.Field<string>("auxiliar"), + IdUsuarioCriacao = (x.Field<object>("usuariocriacao") == null ? (long)0 : x.Field<long>("usuariocriacao")), + DataCriacao = x.Field<DateTime?>("datacriacao"), + IdUsuarioAlteracao = (x.Field<object>("usuarioalteracao") == null ? (long)0 : x.Field<long>("usuarioalteracao")), + DataAlteracao = x.Field<DateTime?>("dataalteracao") + }; + ControleSinistro controleSinistro = new ControleSinistro() + { + Id = x.Field<long>("idcontrolesinistro"), + DataSinistro = new DateTime?((x.Field<object>("data") != null ? x.Field<DateTime>("data") : DateTime.MinValue)) + }; + Item item = new Item() + { + Id = x.Field<long>("id") + }; + Documento documento = new Documento() + { + Id = dataRow.Field<long>("iddocumento"), + Controle = new Controle() + { + Id = dataRow.Field<long>("idcontrole"), + IdEmpresa = dataRow.Field<long>("idempresa"), + Cliente = new Cliente() + { + Id = dataRow.Field<long>("idcliente"), + Nome = dataRow.Field<string>("cliente"), + Pasta = dataRow.Field<string>("pastacliente"), + Documento = dataRow.Field<string>("cpfcnpj"), + MalaDireta = new bool?(dataRow.Field<bool?>("MalaDireta").GetValueOrDefault(true)) + }, + Seguradora = Auxiliar.Seguradoras.Find((Seguradora p) => p.Id == dataRow.Field<long>("idseguradora")), + Ramo = Auxiliar.Ramos.Find((Ramo p) => p.Id == dataRow.Field<long>("idramo")), + Produto = (dataRow.Field<object>("idproduto") != null ? Auxiliar.Produtos.Find((Produto p) => p.Id == dataRow.Field<long>("idproduto")) : null) + }, + Apolice = dataRow.Field<string>("apolice"), + Endosso = dataRow.Field<string>("endosso"), + VendedorPrincipal = (dataRow.Field<object>("idvendedor") != null ? Auxiliar.Vendedores.Find((Vendedor p) => p.Id == dataRow.Field<long>("idvendedor")) : null), + Estipulante1 = (dataRow.Field<object>("idestipulante") != null ? Auxiliar.Estipulantes.Find((Estipulante p) => p.Id == dataRow.Field<long>("idestipulante")) : null), + DataControle = dataRow.Field<DateTime?>("datacontrole"), + Status = (dataRow.Field<object>("idstatus") != null ? Auxiliar.StatusApolice.Find((Status p) => p.Id == dataRow.Field<long>("idstatus")) : null) + }; + DateTime? nullable3 = dataRow.Field<DateTime?>("vigencia1"); + documento.Vigencia1 = (nullable3.HasValue ? nullable3.GetValueOrDefault() : DateTime.MinValue); + documento.Vigencia2 = dataRow.Field<DateTime?>("vigencia2"); + documento.Pasta = dataRow.Field<string>("Pasta"); + item.Documento = documento; + controleSinistro.Item = item; + sinistro1.ControleSinistro = controleSinistro; + sinistros.Add(sinistro1); + }); + return sinistros; + } + + public Sinistro FindById(long id) + { + SinistroDb sinistroDb = base.FindEntityById(id); + if (sinistroDb == null) + { + return null; + } + Sinistro sinistro = ApplicationMapper.Mapper.Map<SinistroDb, Sinistro>(sinistroDb); + sinistro.SinistroAuto = (new SinistroAutoRepository(this._unitOfWork)).FindBySinistroId(sinistro.Id); + sinistro.SinistroVida = (new SinistroVidaRepository(this._unitOfWork)).FindBySinistroId(sinistro.Id); + return sinistro; + } + + public List<Sinistro> FindByItemId(long id) + { + IEnumerable<long> nums = + from cs in (new ControleSinistroRepository(this._unitOfWork)).FindByIdItem(id) + select cs.Id; + return ( + from s in base.All().ToList<SinistroDb>() + where nums.Contains<long>(s.ControleSinistro.Id) + select new Sinistro() + { + Id = s.Id, + Descricao = (string.IsNullOrEmpty(s.Descricao) ? "" : s.Descricao), + DataReclamacao = s.DataReclamacao, + Observacao = (string.IsNullOrEmpty(s.Observacao) ? "" : s.Observacao), + Valor = s.Valor, + ValorPago = s.ValorPago, + Numero = s.Numero, + ControleSinistro = new ControleSinistro() + { + DataSinistro = s.ControleSinistro.DataSinistro + }, + ItemSinistrado = s.ItemSinistrado, + SinistroAuto = (new SinistroAutoRepository(this._unitOfWork)).FindBySinistroId(s.Id), + SinistroVida = (new SinistroVidaRepository(this._unitOfWork)).FindBySinistroId(s.Id) + }).ToList<Sinistro>(); + } + + public List<Sinistro> FindNumeroSinistro(string numero) + { + return this.Select((new List<Condicao>() + { + new Condicao() + { + Campo = "s.numsinistro", + Valores = null, + Operador = Operador.Diferente + }, + new Condicao() + { + Campo = "s.numsinistro", + Valores = numero.CriarValor<string>() + } + }).CreateParameters(0)); + } + + public Sinistro Merge(Sinistro sinistro) + { + SinistroDb sinistroDb = ApplicationMapper.Mapper.Map<Sinistro, SinistroDb>(sinistro); + base.Merge(sinistroDb); + return ApplicationMapper.Mapper.Map<SinistroDb, Sinistro>(sinistroDb); + } + + public Sinistro SaveOrUpdate(Sinistro sinistro) + { + SinistroDb sinistroDb = ApplicationMapper.Mapper.Map<Sinistro, SinistroDb>(sinistro); + this.SaveOrUpdate(sinistroDb); + return ApplicationMapper.Mapper.Map<SinistroDb, Sinistro>(sinistroDb); + } + + private List<Sinistro> Select(SqlQueryCondition condition) + { + DataTable dataTable = this._unitOfWork.Select(condition, "SELECT * FROM sinistro s INNER JOIN controlesinistro cs on cs.idcontrolesinistro = s.idcontrolesinistro WHERE ", ""); + if (dataTable != null && dataTable.Rows.Count == 0) + { + return new List<Sinistro>(); + } + List<long> list = ( + from x in dataTable.AsEnumerable().ToList<DataRow>() + select x.Field<long>("iditem")).ToList<long>(); + List<Condicao> condicaos = new List<Condicao>() + { + new Condicao() + { + Campo = "i.iditem", + Valores = list.CriarValor<long>() + }, + new Condicao() + { + Campo = "d.excluido", + Valores = null, + Grupo = 1, + Operacao = Operacao.Or + }, + new Condicao() + { + Campo = "d.excluido", + Valores = "0".CriarValor<string>(), + Grupo = 1, + Operacao = Operacao.Or + } + }; + DataTable dataTable1 = this._unitOfWork.Select(condicaos.CreateParameters(0), "SELECT i.iditem, d.iddocumento, ISNULL(d.contrato, '') as apolice, c.idcontrole, cl.idcliente, cl.nome FROM item i INNER JOIN documento d on d.iddocumento = i.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE ", ""); + return dataTable.MapSinistro(dataTable1); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroVidaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroVidaRepository.cs new file mode 100644 index 0000000..8f22151 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroVidaRepository.cs @@ -0,0 +1,56 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class SinistroVidaRepository : GenericRepository<SinistroVidaDb>, ISinistroVidaRepository, IGenericRepository<SinistroVidaDb> + { + private readonly GenericUnitOfWork _unitOfWork; + + public SinistroVidaRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public SinistroVida FindById(long id) + { + SinistroVidaDb sinistroVidaDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map<SinistroVidaDb, SinistroVida>(sinistroVidaDb); + } + + public SinistroVida FindBySinistroId(long id) + { + SinistroVidaDb sinistroVidaDb = base.All().FirstOrDefault<SinistroVidaDb>((SinistroVidaDb x) => x.Sinistro.Id == id); + return ApplicationMapper.Mapper.Map<SinistroVidaDb, SinistroVida>(sinistroVidaDb); + } + + public SinistroVida Merge(SinistroVida sinistroVida) + { + SinistroVidaDb sinistroVidaDb = ApplicationMapper.Mapper.Map<SinistroVida, SinistroVidaDb>(sinistroVida); + base.Merge(sinistroVidaDb); + return ApplicationMapper.Mapper.Map<SinistroVidaDb, SinistroVida>(sinistroVidaDb); + } + + public SinistroVida SaveOrUpdate(SinistroVida sinistroVida) + { + SinistroVidaDb sinistroVidaDb = ApplicationMapper.Mapper.Map<SinistroVida, SinistroVidaDb>(sinistroVida); + this.SaveOrUpdate(sinistroVidaDb); + return ApplicationMapper.Mapper.Map<SinistroVidaDb, SinistroVida>(sinistroVidaDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SocioRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SocioRepository.cs new file mode 100644 index 0000000..0bacb70 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SocioRepository.cs @@ -0,0 +1,75 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Common; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Common; +using NHibernate; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class SocioRepository : GenericRepository<SocioDb>, ISocioRepository, IGenericRepository<SocioDb> + { + private readonly GenericUnitOfWork _unitOfWork; + + public SocioRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public List<Socio> Find() + { + return ( + from x in base.All() + select new Socio() + { + Id = x.Id, + Nome = x.Nome, + Email = x.Email, + Prefixo = x.Prefixo, + Telefone = x.Telefone + }).ToList<Socio>(); + } + + public List<Socio> FindByEmpresa(long id) + { + List<SocioDb> list = ( + from x in this._unitOfWork.Session.CreateQuery("FROM SocioDb WHERE (excluido IS NULL OR excluido != '1')").List<SocioDb>() + where x.IdEmpresa == id + select x).ToList<SocioDb>(); + return ApplicationMapper.Mapper.Map<List<SocioDb>, List<Socio>>(list); + } + + public Socio FindById(long id) + { + SocioDb socioDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map<SocioDb, Socio>(socioDb); + } + + public Socio Merge(Socio socio) + { + SocioDb socioDb = ApplicationMapper.Mapper.Map<Socio, SocioDb>(socio); + base.Merge(socioDb); + return ApplicationMapper.Mapper.Map<SocioDb, Socio>(socioDb); + } + + public Socio SaveOrUpdate(Socio socio) + { + SocioDb socioDb = ApplicationMapper.Mapper.Map<Socio, SocioDb>(socio); + this.SaveOrUpdate(socioDb); + return ApplicationMapper.Mapper.Map<SocioDb, Socio>(socioDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/StatusProspeccaoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/StatusProspeccaoRepository.cs new file mode 100644 index 0000000..9e9cac0 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/StatusProspeccaoRepository.cs @@ -0,0 +1,54 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Ferramentas; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class StatusProspeccaoRepository : GenericRepository<StatusDeProspeccaoDb>, IStatusProspeccaoRepository, IGenericRepository<StatusDeProspeccaoDb> + { + private readonly GenericUnitOfWork _unitOfWork; + + public StatusProspeccaoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public List<StatusDeProspeccao> FindAll() + { + return ( + from x in base.All() + select new StatusDeProspeccao() + { + Id = x.Id, + Nome = x.Nome, + Descricao = x.Descricao, + Ativo = x.Ativo, + Excluido = x.Excluido + }).ToList<StatusDeProspeccao>(); + } + + public StatusDeProspeccao Merge(StatusDeProspeccao statusProspeccao) + { + StatusDeProspeccaoDb statusDeProspeccaoDb = ApplicationMapper.Mapper.Map<StatusDeProspeccao, StatusDeProspeccaoDb>(statusProspeccao); + base.Merge(statusDeProspeccaoDb); + return ApplicationMapper.Mapper.Map<StatusDeProspeccaoDb, StatusDeProspeccao>(statusDeProspeccaoDb); + } + + public StatusDeProspeccao SaveOrUpdate(StatusDeProspeccao statusProspeccao) + { + StatusDeProspeccaoDb statusDeProspeccaoDb = ApplicationMapper.Mapper.Map<StatusDeProspeccao, StatusDeProspeccaoDb>(statusProspeccao); + this.SaveOrUpdate(statusDeProspeccaoDb); + return ApplicationMapper.Mapper.Map<StatusDeProspeccaoDb, StatusDeProspeccao>(statusDeProspeccaoDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/StatusRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/StatusRepository.cs new file mode 100644 index 0000000..0eac8b3 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/StatusRepository.cs @@ -0,0 +1,76 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class StatusRepository : GenericRepository<StatusDb>, IStatusRepository, IGenericRepository<StatusDb> + { + private readonly GenericUnitOfWork _unitOfWork; + + public StatusRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public List<Status> Find(string value) + { + StatusRepository.u003cu003ec__DisplayClass6_0 variable = null; + IQueryable<StatusDb> statusDbs = base.All(); + ParameterExpression parameterExpression = Expression.Parameter(typeof(StatusDb), "x"); + IQueryable<StatusDb> statusDbs1 = statusDbs.Where<StatusDb>(Expression.Lambda<Func<StatusDb, bool>>(Expression.OrElse(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(StatusDb).GetMethod("get_Nome").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty<Expression>()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(StatusRepository.u003cu003ec__DisplayClass6_0)), FieldInfo.GetFieldFromHandle(typeof(StatusRepository.u003cu003ec__DisplayClass6_0).GetField("value").FieldHandle)) }), Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(StatusDb).GetMethod("get_Nome").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty<Expression>()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(StatusRepository.u003cu003ec__DisplayClass6_0)), FieldInfo.GetFieldFromHandle(typeof(StatusRepository.u003cu003ec__DisplayClass6_0).GetField("value").FieldHandle)) })), new ParameterExpression[] { parameterExpression })); + parameterExpression = Expression.Parameter(typeof(StatusDb), "x"); + return statusDbs1.Select<StatusDb, Status>(Expression.Lambda<Func<StatusDb, Status>>(Expression.MemberInit(Expression.New(typeof(Status)), new MemberBinding[] { Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(DomainBase).GetMethod("set_Id", new Type[] { typeof(long) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(EntityBase).GetMethod("get_Id").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Status).GetMethod("set_Nome", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(StatusDb).GetMethod("get_Nome").MethodHandle))) }), new ParameterExpression[] { parameterExpression })).ToList<Status>(); + } + + public List<Status> Find() + { + return ( + from x in this._unitOfWork.Session.CreateQuery("from StatusDb").List<StatusDb>() + select new Status() + { + Id = x.Id, + Nome = x.Nome, + Ativo = x.Ativo + }).ToList<Status>(); + } + + public Status FindById(long id) + { + StatusDb statusDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map<StatusDb, Status>(statusDb); + } + + public Status Merge(Status status) + { + StatusDb statusDb = ApplicationMapper.Mapper.Map<Status, StatusDb>(status); + base.Merge(statusDb); + return ApplicationMapper.Mapper.Map<StatusDb, Status>(statusDb); + } + + public Status SaveOrUpdate(Status status) + { + StatusDb statusDb = ApplicationMapper.Mapper.Map<Status, StatusDb>(status); + this.SaveOrUpdate(statusDb); + return ApplicationMapper.Mapper.Map<StatusDb, Status>(statusDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TarefaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TarefaRepository.cs new file mode 100644 index 0000000..bfcdd72 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TarefaRepository.cs @@ -0,0 +1,462 @@ +using AutoMapper; +using Gestor.Common.Validation; +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Helpers; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios.Tarefa; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class TarefaRepository : GenericRepository<TarefaDb>, ITarefaRepository, IGenericRepository<TarefaDb> + { + private readonly GenericUnitOfWork _unitOfWork; + + public TarefaRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public Gestor.Model.Domain.Ferramentas.Tarefa Atualizar(Gestor.Model.Domain.Ferramentas.Tarefa tarefa) + { + List<ResponsavelTarefa> list; + Gestor.Model.Domain.Ferramentas.Tarefa tarefa1 = tarefa; + List<ResponsavelTarefa> responsaveis = tarefa1.Responsaveis; + if (responsaveis != null) + { + list = ( + from x in responsaveis + where x.Usuario.Id != tarefa1.Usuario.Id + select x).ToList<ResponsavelTarefa>(); + } + else + { + list = null; + } + List<ResponsavelTarefa> responsavelTarefas = list; + TarefaDb tarefaDb = ApplicationMapper.Mapper.Map<Gestor.Model.Domain.Ferramentas.Tarefa, TarefaDb>(tarefa1); + List<ResponsavelTarefaDb> responsavelTarefaDbs = ( + from x in this._unitOfWork.Query<ResponsavelTarefaDb>() + where x.IdTarefa == tarefa1.Id + select x).ToList<ResponsavelTarefaDb>(); + this._unitOfWork.Repository<ResponsavelTarefaDb>().DeleteRange(responsavelTarefaDbs); + base.Merge(tarefaDb); + tarefa1 = ApplicationMapper.Mapper.Map<TarefaDb, Gestor.Model.Domain.Ferramentas.Tarefa>(tarefaDb); + if (responsavelTarefas != null) + { + responsavelTarefas.ForEach((ResponsavelTarefa x) => { + x.Id = (long)0; + x.IdTarefa = tarefa1.Id; + x = this.Save(x); + }); + } + tarefa1.Responsaveis = responsavelTarefas; + return tarefa1; + } + + public Trilha Atualizar(Trilha trilha) + { + TrilhaDb trilhaDb = ApplicationMapper.Mapper.Map<Trilha, TrilhaDb>(trilha); + this._unitOfWork.Repository<TrilhaDb>().Merge(trilhaDb); + return ApplicationMapper.Mapper.Map<TrilhaDb, Trilha>(trilhaDb); + } + + public Fase Atualizar(Fase fase) + { + FaseDb faseDb = ApplicationMapper.Mapper.Map<Fase, FaseDb>(fase); + this._unitOfWork.Repository<FaseDb>().Merge(faseDb); + return ApplicationMapper.Mapper.Map<FaseDb, Fase>(faseDb); + } + + public List<Fase> BuscarFases(long id) + { + List<FaseDb> list = ( + from x in this._unitOfWork.Query<FaseDb>() + where x.Trilha.Id == id + select x).ToList<FaseDb>(); + return ApplicationMapper.Mapper.Map<List<FaseDb>, List<Fase>>(list); + } + + public Gestor.Model.Domain.Ferramentas.Tarefa BuscarTarefa(long id) + { + TarefaDb tarefaDb = base.FindEntityById(id); + List<ResponsavelTarefaDb> list = ( + from x in this._unitOfWork.Query<ResponsavelTarefaDb>() + where x.IdTarefa == id + select x).ToList<ResponsavelTarefaDb>(); + Gestor.Model.Domain.Ferramentas.Tarefa tarefa = ApplicationMapper.Mapper.Map<TarefaDb, Gestor.Model.Domain.Ferramentas.Tarefa>(tarefaDb); + tarefa.Responsaveis = ApplicationMapper.Mapper.Map<List<ResponsavelTarefaDb>, List<ResponsavelTarefa>>(list); + return tarefa; + } + + public List<Gestor.Model.Domain.Ferramentas.Tarefa> BuscarTarefa(TipoTarefa entidade, long id, bool? concluido = false) + { + string str; + if (!concluido.HasValue) + { + str = ""; + } + else + { + str = (concluido.GetValueOrDefault() ? " AND t.Conclusao IS NOT NULL" : " AND t.Conclusao IS NULL"); + } + string str1 = str; + return this.Select(string.Format(" AND t.Entidade = {0} AND t.IdEntidade = {1} {2}", (int)entidade, id, str1)); + } + + public List<Gestor.Model.Domain.Ferramentas.Tarefa> BuscarTarefaConcluidaPorUsuario(long id, TipoTarefa tipo) + { + return this.Select(string.Format(" AND t.Entidade = {0} AND t.Conclusao IS NOT NULL AND (t.IdUsuario = {1} OR r.Usuario_id = {2})", (int)tipo, id, id)); + } + + public List<Gestor.Model.Domain.Ferramentas.Tarefa> BuscarTarefaPorCliente(long id) + { + return this.Select(string.Format(" AND t.Entidade != 1 AND t.IdCliente = {0}", id)); + } + + public List<Gestor.Model.Domain.Ferramentas.Tarefa> BuscarTarefaPorData(DateTime data, long idUsuario, bool? concluido = false) + { + string str; + if (!concluido.HasValue) + { + str = ""; + } + else + { + str = (concluido.GetValueOrDefault() ? "AND t.Conclusao IS NOT NULL" : " AND t.Conclusao IS NULL"); + } + string str1 = str; + return this.Select(string.Format(" AND t.Entidade != 1 AND CAST(t.Agendamento AS DATE) == '{0:yyyy-MM-dd}' {1} AND (t.IdUsuario = {2} OR r.Usuario_id = {3})", new object[] { data, str1, idUsuario, idUsuario })); + } + + public List<Gestor.Model.Domain.Relatorios.Tarefa.Tarefa> BuscarTarefaPorFiltro(DateTime inicio, DateTime fim) + { + return ( + from x in this.Select(string.Format(" AND t.Entidade != 1 AND CAST(t.agendamento AS DATE) BETWEEN '{0:yyyy-MM-dd}' AND '{1:yyyy-MM-dd}'", inicio, fim)) + select new Gestor.Model.Domain.Relatorios.Tarefa.Tarefa() + { + Id = x.Id, + IdCliente = x.IdCliente, + Cliente = x.Cliente, + Agendamento = x.Agendamento, + Conclusao = x.Conclusao, + Referencia = x.Referencia, + Titulo = x.Titulo, + Usuario = (x.Usuario != null ? x.Usuario.Nome : ""), + IdEntidade = x.IdEntidade, + Entidade = x.Entidade, + TipoTarefa = (x.TipoDeTarefa != null ? x.TipoDeTarefa.Nome : ""), + Status = x.Status.GetDescription() + }).ToList<Gestor.Model.Domain.Relatorios.Tarefa.Tarefa>(); + } + + public List<Gestor.Model.Domain.Ferramentas.Tarefa> BuscarTarefaPorTrilha(long id) + { + return this.Select(string.Format(" AND t.IdTrilha = {0}", id)); + } + + public List<Gestor.Model.Domain.Ferramentas.Tarefa> BuscarTarefaPorUsuario(long id, bool? concluido = false) + { + string str; + if (!concluido.HasValue) + { + str = ""; + } + else + { + str = (concluido.GetValueOrDefault() ? " AND t.Conclusao IS NOT NULL" : " AND t.Conclusao IS NULL"); + } + string str1 = str; + return this.Select(string.Format(" AND {0} AND (t.IdUsuario = {1} OR r.Usuario_id = {2})", str1, id, id)); + } + + public List<Gestor.Model.Domain.Ferramentas.Tarefa> BuscarTarefaPorUsuario(long id, DateTime inicio, DateTime fim, bool? concluido) + { + string str; + fim = fim.AddDays(1); + if (!concluido.HasValue) + { + str = ""; + } + else + { + str = (concluido.GetValueOrDefault() ? " AND t.Conclusao IS NOT NULL" : " AND t.Conclusao IS NULL"); + } + string str1 = str; + string str2 = (id == 0 ? "" : string.Format(" AND (t.IdUsuario = {0} OR r.Usuario_id = {1})", id, id)); + return this.Select(string.Format(" AND t.Entidade != 1 AND t.Agendamento >= '{0:yyyy-MM-dd}' AND t.Agendamento <= '{1:yyyy-MM-dd}' {2} {3}", new object[] { inicio, fim, str1, str2 })); + } + + public List<Gestor.Model.Domain.Ferramentas.Tarefa> BuscarTarefaPorUsuario(long id, TipoTarefa tipo) + { + return this.Select(string.Format(" AND t.Entidade = {0} AND t.Conclusao IS NULL AND (t.IdUsuario = {1} OR r.Usuario_id = {2})", (int)tipo, id, id)); + } + + public List<Gestor.Model.Domain.Ferramentas.Tarefa> BuscarTarefasPorTipo(long id) + { + return this.Select(string.Format(" AND t.IdTipoTarefa = {0}", id)); + } + + public Trilha BuscarTrilha(long id) + { + TrilhaDb trilhaDb = this._unitOfWork.Query<TrilhaDb>().FirstOrDefault<TrilhaDb>((TrilhaDb x) => x.Id == id); + return ApplicationMapper.Mapper.Map<TrilhaDb, Trilha>(trilhaDb); + } + + public List<Trilha> BuscarTrilhas(bool ativo = true) + { + List<TrilhaDb> list = ( + from x in this._unitOfWork.Query<TrilhaDb>() + where x.Ativo == ativo + select x).ToList<TrilhaDb>(); + return ApplicationMapper.Mapper.Map<List<TrilhaDb>, List<Trilha>>(list); + } + + public List<Trilha> BuscarTrilhas(string titulo, bool ativo = true) + { + List<TrilhaDb> list = this._unitOfWork.Query<TrilhaDb>().ToList<TrilhaDb>().Where<TrilhaDb>((TrilhaDb x) => { + if (x.Ativo != ativo) + { + return false; + } + return x.Titulo.Normalized() == titulo.Normalized(); + }).ToList<TrilhaDb>(); + return ApplicationMapper.Mapper.Map<List<TrilhaDb>, List<Trilha>>(list); + } + + public int[] ContarTarefas(long id) + { + int[] numArray = new int[] { this.Count(string.Format(" AND t.Entidade = 1 AND t.Conclusao IS NULL AND (t.IdUsuario = {0} OR r.Usuario_id = {1})", id, id)), 0 }; + DateTime date = Funcoes.GetNetworkTime().Date; + numArray[1] = this.Count(string.Format(" AND t.Entidade != 1 AND t.Conclusao IS NULL AND t.Agendamento < '{0:yyyy-MM-dd}' AND (t.IdUsuario = {1} OR r.Usuario_id = {2})", date.AddDays(1), id, id)); + return numArray; + } + + private int Count(string condition) + { + int num; + object connection; + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = string.Concat("SELECT Count(DISTINCT t.Id) as quantidade FROM Tarefa t LEFT OUTER JOIN ResponsavelTarefa r on r.IdTarefa = t.id WHERE 1=1 ", condition); + SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); + sqlDataReader.Read(); + num = int.Parse(sqlDataReader["quantidade"].ToString()); + } + } + return num; + } + + public void Excluir(long id) + { + TarefaDb tarefaDb = base.FindEntityById(id); + if (tarefaDb == null) + { + return; + } + List<ResponsavelTarefaDb> list = ( + from x in this._unitOfWork.Query<ResponsavelTarefaDb>() + where x.IdTarefa == id + select x).ToList<ResponsavelTarefaDb>(); + this._unitOfWork.Repository<ResponsavelTarefaDb>().DeleteRange(list); + ( + from x in this._unitOfWork.Query<ProspeccaoDb>() + where x.Tarefa.Id == tarefaDb.Id + select x).ToList<ProspeccaoDb>().ForEach((ProspeccaoDb x) => { + x.Tarefa = null; + this._unitOfWork.Repository<ProspeccaoDb>().Merge(x); + }); + base.Delete(tarefaDb); + } + + public void ExcluirFase(long id) + { + FaseDb faseDb = this._unitOfWork.Query<FaseDb>().FirstOrDefault<FaseDb>((FaseDb x) => x.Id == id); + if (faseDb == null) + { + return; + } + this._unitOfWork.Repository<FaseDb>().Delete(faseDb); + } + + public void ExcluirTrilha(long id) + { + TrilhaDb trilhaDb = this._unitOfWork.Query<TrilhaDb>().FirstOrDefault<TrilhaDb>((TrilhaDb x) => x.Id == id); + if (trilhaDb == null) + { + return; + } + this._unitOfWork.Repository<TrilhaDb>().Delete(trilhaDb); + } + + public Gestor.Model.Domain.Ferramentas.Tarefa Salvar(Gestor.Model.Domain.Ferramentas.Tarefa tarefa) + { + List<ResponsavelTarefa> list; + Gestor.Model.Domain.Ferramentas.Tarefa tarefa1 = tarefa; + List<ResponsavelTarefa> responsaveis = tarefa1.Responsaveis; + if (responsaveis != null) + { + list = ( + from x in responsaveis + where x.Usuario.Id != tarefa1.Usuario.Id + select x).ToList<ResponsavelTarefa>(); + } + else + { + list = null; + } + List<ResponsavelTarefa> responsavelTarefas = list; + TarefaDb tarefaDb = ApplicationMapper.Mapper.Map<Gestor.Model.Domain.Ferramentas.Tarefa, TarefaDb>(tarefa1); + this.SaveOrUpdate(tarefaDb); + tarefa1 = ApplicationMapper.Mapper.Map<TarefaDb, Gestor.Model.Domain.Ferramentas.Tarefa>(tarefaDb); + if (responsavelTarefas != null) + { + responsavelTarefas.ForEach((ResponsavelTarefa x) => { + x.IdTarefa = tarefa1.Id; + x = this.Save(x); + }); + } + tarefa1.Responsaveis = responsavelTarefas; + return tarefa1; + } + + public List<Gestor.Model.Domain.Ferramentas.Tarefa> Salvar(List<Gestor.Model.Domain.Ferramentas.Tarefa> tarefas) + { + tarefas.ForEach((Gestor.Model.Domain.Ferramentas.Tarefa x) => x = this.Salvar(x)); + return tarefas; + } + + public Trilha Salvar(Trilha trilha) + { + TrilhaDb trilhaDb = ApplicationMapper.Mapper.Map<Trilha, TrilhaDb>(trilha); + this._unitOfWork.Repository<TrilhaDb>().SaveOrUpdate(trilhaDb); + return ApplicationMapper.Mapper.Map<TrilhaDb, Trilha>(trilhaDb); + } + + public Fase Salvar(Fase fase) + { + FaseDb faseDb = ApplicationMapper.Mapper.Map<Fase, FaseDb>(fase); + this._unitOfWork.Repository<FaseDb>().SaveOrUpdate(faseDb); + return ApplicationMapper.Mapper.Map<FaseDb, Fase>(faseDb); + } + + public List<Fase> Salvar(List<Fase> fases) + { + List<FaseDb> faseDbs = new List<FaseDb>(); + List<Fase> list = ( + from x in fases + where x.Id == (long)0 + select x).ToList<Fase>(); + List<Fase> list1 = fases.Except<Fase>(list).ToList<Fase>(); + if (list.Count > 0) + { + faseDbs = ApplicationMapper.Mapper.Map<List<Fase>, List<FaseDb>>(list); + this._unitOfWork.Repository<FaseDb>().AddRange(faseDbs); + } + if (list1 != null) + { + list1.ForEach((Fase x) => { + FaseDb faseDb = ApplicationMapper.Mapper.Map<Fase, FaseDb>(x); + this._unitOfWork.Repository<FaseDb>().SaveOrUpdate(faseDb); + faseDbs.Add(faseDb); + }); + } + else + { + } + return ApplicationMapper.Mapper.Map<List<FaseDb>, List<Fase>>(faseDbs); + } + + public ResponsavelTarefa Save(ResponsavelTarefa responsavel) + { + ResponsavelTarefaDb responsavelTarefaDb = ApplicationMapper.Mapper.Map<ResponsavelTarefa, ResponsavelTarefaDb>(responsavel); + this._unitOfWork.Repository<ResponsavelTarefaDb>().SaveOrUpdate(responsavelTarefaDb); + return ApplicationMapper.Mapper.Map<ResponsavelTarefaDb, ResponsavelTarefa>(responsavelTarefaDb); + } + + private List<Gestor.Model.Domain.Ferramentas.Tarefa> Select(string condition) + { + object connection; + List<long> nums = null; + DataTable dataTable = new DataTable(); + DataTable dataTable1 = new DataTable(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandTimeout = 15000; + Auxiliar.LoadTipoTarefa(sqlCommand); + Auxiliar.CriarAuxiliar(sqlCommand, false); + sqlCommand.CommandText = string.Concat("SELECT DISTINCT t.* FROM Tarefa t LEFT OUTER JOIN ResponsavelTarefa r on r.IdTarefa = t.id WHERE 1=1 ", condition); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + for (List<long> i = dataTable.AsEnumerable().Select<DataRow, long>((DataRow x) => x.Field<long>("Id")).ToList<long>(); i.Count > 0; i = nums) + { + List<long> list = i.Take<long>(2100).ToList<long>(); + string str = string.Concat(" AND IdTarefa IN (", string.Join<long>(",", list), ")"); + DataTable dataTable2 = new DataTable(); + sqlCommand.CommandText = string.Concat("SELECT * FROM ResponsavelTarefa WHERE 1=1 ", str); + using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) + { + sqlDataAdapter1.SelectCommand = sqlCommand; + sqlDataAdapter1.Fill(dataTable2); + } + dataTable1.Merge(dataTable2); + nums = (list.Count < 2100 ? new List<long>() : i.Except<long>(list).ToList<long>()); + } + } + } + return CustomMap.MapTarefa(dataTable, dataTable1); + } + + public List<long> Validar(List<long> ids, long trilha) + { + return ( + from x in base.All() + where ids.Contains(x.IdEntidade) && x.Trilha != null && x.Trilha.Id == trilha + select x.Id).ToList<long>(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoContaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoContaRepository.cs new file mode 100644 index 0000000..4f5a3cf --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoContaRepository.cs @@ -0,0 +1,52 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Financeiro; +using NHibernate; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class TipoContaRepository : GenericRepository<TipoContaDb>, ITipoContaRepository, IGenericRepository<TipoContaDb> + { + private readonly GenericUnitOfWork _unitOfWork; + + public TipoContaRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public List<TipoConta> Find() + { + return ( + from x in this._unitOfWork.Session.CreateQuery("from TipoContaDb").List<TipoContaDb>() + select new TipoConta() + { + Descricao = x.Descricao, + Ativo = x.Ativo, + Id = x.Id + }).ToList<TipoConta>(); + } + + public TipoConta Merge(TipoConta tipoConta) + { + TipoContaDb tipoContaDb = ApplicationMapper.Mapper.Map<TipoConta, TipoContaDb>(tipoConta); + base.Merge(tipoContaDb); + return ApplicationMapper.Mapper.Map<TipoContaDb, TipoConta>(tipoContaDb); + } + + public TipoConta SaveOrUpdate(TipoConta tipoConta) + { + TipoContaDb tipoContaDb = ApplicationMapper.Mapper.Map<TipoConta, TipoContaDb>(tipoConta); + this.SaveOrUpdate(tipoContaDb); + return ApplicationMapper.Mapper.Map<TipoContaDb, TipoConta>(tipoContaDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoTarefaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoTarefaRepository.cs new file mode 100644 index 0000000..df36a20 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoTarefaRepository.cs @@ -0,0 +1,54 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Ferramentas; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Ferramentas; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class TipoTarefaRepository : GenericRepository<TipoDeTarefaDb>, ITipoTarefaRepository, IGenericRepository<TipoDeTarefaDb> + { + private readonly GenericUnitOfWork _unitOfWork; + + public TipoTarefaRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public List<TipoDeTarefa> FindAll() + { + return ( + from x in base.All() + select new TipoDeTarefa() + { + Id = x.Id, + Nome = x.Nome, + Descricao = x.Descricao, + Ativo = x.Ativo, + Excluido = x.Excluido + }).ToList<TipoDeTarefa>(); + } + + public TipoDeTarefa Merge(TipoDeTarefa tipoTarefa) + { + TipoDeTarefaDb tipoDeTarefaDb = ApplicationMapper.Mapper.Map<TipoDeTarefa, TipoDeTarefaDb>(tipoTarefa); + base.Merge(tipoDeTarefaDb); + return ApplicationMapper.Mapper.Map<TipoDeTarefaDb, TipoDeTarefa>(tipoDeTarefaDb); + } + + public TipoDeTarefa SaveOrUpdate(TipoDeTarefa tipoTarefa) + { + TipoDeTarefaDb tipoDeTarefaDb = ApplicationMapper.Mapper.Map<TipoDeTarefa, TipoDeTarefaDb>(tipoTarefa); + this.SaveOrUpdate(tipoDeTarefaDb); + return ApplicationMapper.Mapper.Map<TipoDeTarefaDb, TipoDeTarefa>(tipoDeTarefaDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoVendedorRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoVendedorRepository.cs new file mode 100644 index 0000000..30382b0 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoVendedorRepository.cs @@ -0,0 +1,139 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class TipoVendedorRepository : GenericRepository<TipoVendedorDb>, ITipoVendedorRepository, IGenericRepository<TipoVendedorDb> + { + private readonly GenericUnitOfWork _unitOfWork; + + public TipoVendedorRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public List<TipoVendedor> DefaultSelect() + { + List<TipoVendedorDb> list = base.All().ToList<TipoVendedorDb>(); + return ApplicationMapper.Mapper.Map<List<TipoVendedorDb>, List<TipoVendedor>>(list); + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public List<TipoVendedor> Find(bool ativo) + { + return ( + from x in base.All() + where x.Ativo == (bool?)ativo + select new TipoVendedor() + { + Id = x.Id, + Descricao = x.Descricao, + Ativo = x.Ativo + }).ToList<TipoVendedor>(); + } + + public List<TipoVendedor> Find() + { + return ( + from x in this._unitOfWork.Session.CreateQuery("from TipoVendedorDb").List<TipoVendedorDb>() + select new TipoVendedor() + { + Id = x.Id, + Descricao = x.Descricao, + Ativo = x.Ativo + }).ToList<TipoVendedor>(); + } + + public TipoVendedor FindById(long id) + { + TipoVendedorDb tipoVendedorDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map<TipoVendedorDb, TipoVendedor>(tipoVendedorDb); + } + + public long FindLastId() + { + long num; + object connection; + SqlCommand sqlCommand; + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + if (sqlConnection != null) + { + sqlCommand = sqlConnection.CreateCommand(); + } + else + { + sqlCommand = null; + } + using (SqlCommand sqlCommand1 = sqlCommand) + { + sqlCommand1.CommandText = "SELECT MAX(idtipovendedor) as id FROM tipovendedor"; + SqlDataReader sqlDataReader = sqlCommand1.ExecuteReader(); + sqlDataReader.Read(); + num = (sqlDataReader["id"] == null ? (long)0 : long.Parse(sqlDataReader["id"].ToString())); + } + } + return num; + } + + public TipoVendedor Merge(TipoVendedor tipoVendedor) + { + TipoVendedorDb tipoVendedorDb = ApplicationMapper.Mapper.Map<TipoVendedor, TipoVendedorDb>(tipoVendedor); + base.Merge(tipoVendedorDb); + return ApplicationMapper.Mapper.Map<TipoVendedorDb, TipoVendedor>(tipoVendedorDb); + } + + public List<TipoVendedor> MergeRange(List<TipoVendedor> tiposVendedor) + { + List<TipoVendedor> tipoVendedors = new List<TipoVendedor>(); + tiposVendedor.ForEach((TipoVendedor x) => { + TipoVendedorDb tipoVendedorDb = ApplicationMapper.Mapper.Map<TipoVendedor, TipoVendedorDb>(x); + if (!x.Inserido.HasValue || x.Inserido.Value) + { + base.Merge(tipoVendedorDb); + } + else + { + this.SaveOrUpdate(tipoVendedorDb); + } + tipoVendedors.Add(ApplicationMapper.Mapper.Map<TipoVendedorDb, TipoVendedor>(tipoVendedorDb)); + }); + return tipoVendedors; + } + + public TipoVendedor SaveOrUpdate(TipoVendedor tipoVendedor) + { + TipoVendedorDb tipoVendedorDb = ApplicationMapper.Mapper.Map<TipoVendedor, TipoVendedorDb>(tipoVendedor); + this.SaveOrUpdate(tipoVendedorDb); + return ApplicationMapper.Mapper.Map<TipoVendedorDb, TipoVendedor>(tipoVendedorDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TitularesVidaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TitularesVidaRepository.cs new file mode 100644 index 0000000..4a0f512 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TitularesVidaRepository.cs @@ -0,0 +1,152 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class TitularesVidaRepository : GenericRepository<TitularesVidaDb>, ITitularesVidaRepository, IGenericRepository<TitularesVidaDb> + { + private readonly GenericUnitOfWork _unitOfWork; + + public TitularesVidaRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public void DeleteRange(List<long> ids) + { + for (int i = 0; i < ids.Count; i += 200) + { + IEnumerable<long> nums = ids.Skip<long>(i).Take<long>(200); + List<TitularesVidaDb> list = ( + from x in base.All() + where nums.Contains<long>(x.Id) + select x).ToList<TitularesVidaDb>(); + base.DeleteRange(list); + } + } + + public List<TitularesVida> Find(long id) + { + object connection; + DataTable dataTable = new DataTable(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + if (sqlConnection != null) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = string.Format("SELECT * FROM TitularesVida WHERE IdItem = {0}", id); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + } + } + } + return dataTable.AsEnumerable().ToList<DataRow>().Select<DataRow, TitularesVida>((DataRow x) => { + DateTime? nullable; + DateTime? nullable1; + DateTime? nullable2; + DateTime? nullable3; + TitularesVida titularesVida = new TitularesVida() + { + Id = x.Field<long>("Id"), + Codigo = (x.Field<object>("Codigo") != null ? x.Field<object>("Codigo").ToString() : null) + }; + if (x.Field<object>("Inicio") != null) + { + nullable1 = new DateTime?(DateTime.Parse(x.Field<object>("Inicio").ToString())); + } + else + { + nullable = null; + nullable1 = nullable; + } + titularesVida.Inicio = nullable1; + if (x.Field<object>("Fim") != null) + { + nullable2 = new DateTime?(DateTime.Parse(x.Field<object>("Fim").ToString())); + } + else + { + nullable = null; + nullable2 = nullable; + } + titularesVida.Fim = nullable2; + titularesVida.Fatura = (x.Field<object>("Fatura") != null ? x.Field<object>("Fatura").ToString() : null); + titularesVida.Nome = (x.Field<object>("Nome") != null ? x.Field<object>("Nome").ToString() : null); + titularesVida.Observacao = (x.Field<object>("Observacao") != null ? x.Field<object>("Observacao").ToString() : null); + if (x.Field<object>("Nascimento") != null) + { + nullable3 = new DateTime?(DateTime.Parse(x.Field<object>("Nascimento").ToString())); + } + else + { + nullable = null; + nullable3 = nullable; + } + titularesVida.Nascimento = nullable3; + titularesVida.Cpf = (x.Field<object>("Cpf") != null ? x.Field<object>("Cpf").ToString() : null); + titularesVida.Matricula = (x.Field<object>("Matricula") != null ? x.Field<object>("Matricula").ToString() : null); + titularesVida.Premio = new decimal?((x.Field<object>("Premio") != null ? x.Field<decimal>("Premio") : decimal.Zero)); + titularesVida.Capital = new decimal?((x.Field<object>("Capital") != null ? x.Field<decimal>("Capital") : decimal.Zero)); + titularesVida.Tipo = (x.Field<object>("Tipo") != null ? (TipoTitular?)Enum.Parse(typeof(TipoTitular), x.Field<object>("Tipo").ToString()) : null); + titularesVida.Dependente = (x.Field<object>("Dependente_id") != null ? this.FindById(x.Field<long>("Dependente_id")) : null); + return titularesVida; + }).ToList<TitularesVida>(); + } + + public TitularesVida FindById(long id) + { + TitularesVidaDb titularesVidaDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map<TitularesVidaDb, TitularesVida>(titularesVidaDb); + } + + public TitularesVida Merge(TitularesVida vida) + { + TitularesVidaDb titularesVidaDb = ApplicationMapper.Mapper.Map<TitularesVida, TitularesVidaDb>(vida); + base.Merge(titularesVidaDb); + return ApplicationMapper.Mapper.Map<TitularesVidaDb, TitularesVida>(titularesVidaDb); + } + + public TitularesVida SaveOrUpdate(TitularesVida vida) + { + TitularesVidaDb titularesVidaDb = ApplicationMapper.Mapper.Map<TitularesVida, TitularesVidaDb>(vida); + this.SaveOrUpdate(titularesVidaDb); + return ApplicationMapper.Mapper.Map<TitularesVidaDb, TitularesVida>(titularesVidaDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/UsuarioRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/UsuarioRepository.cs new file mode 100644 index 0000000..f1f9993 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/UsuarioRepository.cs @@ -0,0 +1,305 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.API; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class UsuarioRepository : GenericRepository<UsuarioDb>, IUsuarioRepository, IGenericRepository<UsuarioDb> + { + private readonly GenericUnitOfWork _unitOfWork; + + public UsuarioRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public Usuario AddUsuarioFromSso(UserSso userSso) + { + return this.SaveOrUpdate(new Usuario() + { + SsoId = userSso.Id, + IdEmpresa = userSso.IdEmpresa, + Nome = userSso.Name, + Login = userSso.Username, + Senha = userSso.Password, + Administrador = false, + Excluido = userSso.IsDeleted, + PermissaoAggilizador = new long?((long)1) + }); + } + + public void Delete(long id) + { + UsuarioDb nullable = base.FindEntityById(id); + if (nullable.Login.IndexOf("_REM", StringComparison.InvariantCultureIgnoreCase) == -1) + { + UsuarioDb usuarioDb = nullable; + usuarioDb.Login = string.Concat(usuarioDb.Login, "_REM"); + } + nullable.Excluido = new bool?(true); + base.Merge(nullable); + } + + public List<Usuario> Find(string filter, long idempresa = 0L) + { + UsuarioRepository.u003cu003ec__DisplayClass11_0 variable = null; + ParameterExpression parameterExpression; + bool? nullable; + IQueryable<UsuarioDb> usuarioDbs; + if (idempresa == 0) + { + IQueryable<UsuarioDb> usuarioDbs1 = base.All(); + parameterExpression = Expression.Parameter(typeof(UsuarioDb), "x"); + nullable = null; + usuarioDbs = usuarioDbs1.Where<UsuarioDb>(Expression.Lambda<Func<UsuarioDb, bool>>(Expression.OrElse(Expression.AndAlso(Expression.AndAlso(Expression.NotEqual(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UsuarioDb).GetMethod("get_Excluido").MethodHandle)), Expression.Constant(nullable, typeof(bool?))), Expression.Equal(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UsuarioDb).GetMethod("get_Excluido").MethodHandle)), Expression.Convert(Expression.Constant(false, typeof(bool)), typeof(bool?)))), Expression.Call(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UsuarioDb).GetMethod("get_Nome").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty<Expression>()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Trim").MethodHandle), Array.Empty<Expression>()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(UsuarioRepository.u003cu003ec__DisplayClass11_0)), FieldInfo.GetFieldFromHandle(typeof(UsuarioRepository.u003cu003ec__DisplayClass11_0).GetField("filter").FieldHandle)) })), Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UsuarioDb).GetMethod("get_Documento").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Trim").MethodHandle), Array.Empty<Expression>()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(UsuarioRepository.u003cu003ec__DisplayClass11_0)), FieldInfo.GetFieldFromHandle(typeof(UsuarioRepository.u003cu003ec__DisplayClass11_0).GetField("filter").FieldHandle)) })), new ParameterExpression[] { parameterExpression })); + } + else + { + IQueryable<UsuarioDb> usuarioDbs2 = base.All(); + parameterExpression = Expression.Parameter(typeof(UsuarioDb), "x"); + nullable = null; + usuarioDbs = usuarioDbs2.Where<UsuarioDb>(Expression.Lambda<Func<UsuarioDb, bool>>(Expression.AndAlso(Expression.AndAlso(Expression.AndAlso(Expression.NotEqual(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UsuarioDb).GetMethod("get_Excluido").MethodHandle)), Expression.Constant(nullable, typeof(bool?))), Expression.Equal(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UsuarioDb).GetMethod("get_Excluido").MethodHandle)), Expression.Convert(Expression.Constant(false, typeof(bool)), typeof(bool?)))), Expression.Equal(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UsuarioDb).GetMethod("get_IdEmpresa").MethodHandle)), Expression.Field(Expression.Constant(variable, typeof(UsuarioRepository.u003cu003ec__DisplayClass11_0)), FieldInfo.GetFieldFromHandle(typeof(UsuarioRepository.u003cu003ec__DisplayClass11_0).GetField("idempresa").FieldHandle)))), Expression.OrElse(Expression.Call(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UsuarioDb).GetMethod("get_Nome").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty<Expression>()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Trim").MethodHandle), Array.Empty<Expression>()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(UsuarioRepository.u003cu003ec__DisplayClass11_0)), FieldInfo.GetFieldFromHandle(typeof(UsuarioRepository.u003cu003ec__DisplayClass11_0).GetField("filter").FieldHandle)) }), Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UsuarioDb).GetMethod("get_Documento").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Trim").MethodHandle), Array.Empty<Expression>()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(UsuarioRepository.u003cu003ec__DisplayClass11_0)), FieldInfo.GetFieldFromHandle(typeof(UsuarioRepository.u003cu003ec__DisplayClass11_0).GetField("filter").FieldHandle)) }))), new ParameterExpression[] { parameterExpression })); + } + parameterExpression = Expression.Parameter(typeof(UsuarioDb), "x"); + return usuarioDbs.Select<UsuarioDb, Usuario>(Expression.Lambda<Func<UsuarioDb, Usuario>>(Expression.MemberInit(Expression.New(typeof(Usuario)), new MemberBinding[] { Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Usuario).GetMethod("set_IdEmpresa", new Type[] { typeof(long) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UsuarioDb).GetMethod("get_IdEmpresa").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(DomainBase).GetMethod("set_Id", new Type[] { typeof(long) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(EntityBase).GetMethod("get_Id").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Usuario).GetMethod("set_Nome", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UsuarioDb).GetMethod("get_Nome").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Usuario).GetMethod("set_Documento", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UsuarioDb).GetMethod("get_Documento").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Usuario).GetMethod("set_Excluido", new Type[] { typeof(bool) }).MethodHandle), Expression.Coalesce(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UsuarioDb).GetMethod("get_Excluido").MethodHandle)), Expression.Constant(false, typeof(bool)))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Usuario).GetMethod("set_PermissaoAggilizador", new Type[] { typeof(long?) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UsuarioDb).GetMethod("get_PermissaoAggilizador").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Usuario).GetMethod("set_Administrador", new Type[] { typeof(bool) }).MethodHandle), Expression.Coalesce(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UsuarioDb).GetMethod("get_Administrador").MethodHandle)), Expression.Constant(false, typeof(bool)))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Usuario).GetMethod("set_Visita", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UsuarioDb).GetMethod("get_Visita").MethodHandle))) }), new ParameterExpression[] { parameterExpression })).ToList<Usuario>(); + } + + public List<Usuario> Find(long idempresa = 0L) + { + List<Usuario> usuarios; + object connection; + DataTable dataTable = new DataTable(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + string str = (idempresa == 0 ? "SELECT * FROM usuario" : "SELECT * FROM usuario WHERE idempresa = @idempresa"); + try + { + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + if (sqlConnection != null) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = str; + sqlCommand.Parameters.AddWithValue("@idempresa", idempresa); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + } + } + else + { + usuarios = null; + return usuarios; + } + } + usuarios = CustomMap.MapUsuario(dataTable); + } + catch (Exception exception) + { + usuarios = null; + } + return usuarios; + } + + public Usuario FindById(long id) + { + UsuarioDb usuarioDb = base.FindEntityById(id); + if (usuarioDb == null) + { + return null; + } + return ApplicationMapper.Mapper.Map<UsuarioDb, Usuario>(usuarioDb); + } + + public List<Usuario> FindByLoginInteiro(string filter) + { + return ( + from x in ( + from x in base.All() + where x.Excluido != null && x.Excluido == (bool?)false && x.Login.Equals(filter) + select x).ToList<UsuarioDb>() + select new Usuario() + { + IdEmpresa = x.IdEmpresa, + Id = x.Id, + Nome = x.Nome, + Documento = x.Documento, + Excluido = x.Excluido.GetValueOrDefault(), + PermissaoAggilizador = x.PermissaoAggilizador, + Administrador = x.Administrador.GetValueOrDefault(), + Visita = x.Visita + } into x + where !x.Excluido + select x).ToList<Usuario>(); + } + + private Usuario FindBySso(string ssoId) + { + UsuarioDb usuarioDb = base.All().FirstOrDefault<UsuarioDb>((UsuarioDb u) => u.SsoId == ssoId); + if (usuarioDb == null) + { + return null; + } + return ApplicationMapper.Mapper.Map<UsuarioDb, Usuario>(usuarioDb); + } + + public bool FindDocUsedByDocumento(string filter, long id, long idempresa) + { + return base.All().Any<UsuarioDb>((UsuarioDb u) => u.IdEmpresa == idempresa && u.Excluido != null && u.Excluido == (bool?)false && u.Id != id && u.Documento != null && u.Documento.Replace(".", string.Empty).Replace("-", string.Empty).Replace("/", string.Empty).Equals(filter)); + } + + public Usuario FindFromSso(UserSso userSso) + { + UsuarioRepository.u003cu003ec__DisplayClass4_0 variable = null; + if (userSso.IsDeleted) + { + return null; + } + IQueryable<UsuarioDb> usuarioDbs = base.All(); + ParameterExpression parameterExpression = Expression.Parameter(typeof(UsuarioDb), "u"); + UsuarioDb usuarioDb = usuarioDbs.FirstOrDefault<UsuarioDb>(Expression.Lambda<Func<UsuarioDb, bool>>(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UsuarioDb).GetMethod("get_Login").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty<Expression>()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Equals", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Call(Expression.Property(Expression.Field(Expression.Constant(variable, typeof(UsuarioRepository.u003cu003ec__DisplayClass4_0)), FieldInfo.GetFieldFromHandle(typeof(UsuarioRepository.u003cu003ec__DisplayClass4_0).GetField("userSso").FieldHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UserSso).GetMethod("get_Username").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty<Expression>()) }), new ParameterExpression[] { parameterExpression })); + if (usuarioDb == null) + { + return null; + } + return ApplicationMapper.Mapper.Map<UsuarioDb, Usuario>(usuarioDb); + } + + public Usuario FindUsuario(string login) + { + UsuarioDb usuarioDb = ( + from x in base.All() + where x.Excluido != null && x.Excluido == (bool?)false + select x).FirstOrDefault<UsuarioDb>((UsuarioDb x) => x.Login == login); + return ApplicationMapper.Mapper.Map<UsuarioDb, Usuario>(usuarioDb); + } + + public Usuario Merge(Usuario usuario) + { + UsuarioDb usuarioDb = ApplicationMapper.Mapper.Map<Usuario, UsuarioDb>(usuario); + base.Merge(usuarioDb); + return ApplicationMapper.Mapper.Map<UsuarioDb, Usuario>(usuarioDb); + } + + public List<PermissaoAggilizador> PermissaoAggilizador() + { + List<PermissaoAggilizador> list; + object connection; + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + DataTable dataTable = new DataTable(); + try + { + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + if (sqlConnection != null) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = "SELECT * FROM Permissao where IdPermissao != 4"; + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + } + } + } + list = ( + from x in dataTable.AsEnumerable().ToList<DataRow>() + select new PermissaoAggilizador() + { + Id = x.Field<long>("IdPermissao"), + Descricao = x.Field<string>("Nome").ToUpper() + }).ToList<PermissaoAggilizador>(); + } + catch (Exception exception) + { + list = new List<PermissaoAggilizador>() + { + new PermissaoAggilizador() + { + Id = (long)1, + Descricao = "ADMINISTRADOR" + }, + new PermissaoAggilizador() + { + Id = (long)2, + Descricao = "NORMAL" + }, + new PermissaoAggilizador() + { + Id = (long)3, + Descricao = "LIMITADO" + } + }; + } + return list; + } + + public Usuario SaveOrUpdate(Usuario usuario) + { + UsuarioDb usuarioDb = ApplicationMapper.Mapper.Map<Usuario, UsuarioDb>(usuario); + this.SaveOrUpdate(usuarioDb); + return ApplicationMapper.Mapper.Map<UsuarioDb, Usuario>(usuarioDb); + } + + public Usuario SsoId(AuthSso sso) + { + if (sso.Code != 200) + { + return null; + } + return this.FindBySso(sso.Data.User.Id); + } + + public Usuario ValidateLogin(string login, string password) + { + UsuarioDb usuarioDb = this._unitOfWork.Session.CreateQuery("FROM UsuarioDb WHERE (removido IS NULL OR removido != '1') AND (inativo = '0' OR inativo IS NULL)").List<UsuarioDb>().FirstOrDefault<UsuarioDb>((UsuarioDb u) => { + if (!string.Equals(u.Login.Trim(), login.Trim(), StringComparison.CurrentCultureIgnoreCase)) + { + return false; + } + return u.Senha == password; + }); + return ApplicationMapper.Mapper.Map<UsuarioDb, Usuario>(usuarioDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorParcelaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorParcelaRepository.cs new file mode 100644 index 0000000..e765212 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorParcelaRepository.cs @@ -0,0 +1,474 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Helpers; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class VendedorParcelaRepository : GenericRepository<VendedorParcelaDb>, IVendedorParcelaRepository, IGenericRepository<VendedorParcelaDb> + { + private readonly GenericUnitOfWork _unitOfWork; + + public VendedorParcelaRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public List<VendedorParcela> AddRange(List<VendedorParcela> repasses) + { + List<VendedorParcelaDb> vendedorParcelaDbs = ApplicationMapper.Mapper.Map<List<VendedorParcela>, List<VendedorParcelaDb>>(repasses); + base.AddRange(vendedorParcelaDbs); + return ApplicationMapper.Mapper.Map<List<VendedorParcelaDb>, List<VendedorParcela>>(vendedorParcelaDbs); + } + + public Vendedor BuscarVendedorPorControle(long id) + { + Vendedor vendedor; + object connection; + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + Auxiliar.CriarVendedor(sqlCommand, false); + sqlCommand.CommandText = string.Format("SELECT TOP 1 idvendedor as id FROM vendedorparcela vp INNER JOIN parcela p on p.idparcela = vp.idparcela INNER JOIN documento d on d.iddocumento = vp.iddocumento WHERE vp.idtipovendedor = 1 AND p.idsubtipo = 1 AND d.idcontrole = {0};", id); + SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); + if (sqlDataReader.HasRows) + { + sqlDataReader.Read(); + long num = (sqlDataReader["id"] == null ? (long)0 : long.Parse(sqlDataReader["id"].ToString())); + sqlDataReader.Close(); + return Auxiliar.Vendedores.FirstOrDefault<Vendedor>((Vendedor x) => { + if (x == null) + { + return false; + } + return x.Id == num; + }); + } + else + { + vendedor = null; + } + } + } + return vendedor; + } + + public bool Delete(long id) + { + VendedorParcelaDb vendedorParcelaDb = base.FindEntityById(id); + if (vendedorParcelaDb == null) + { + return true; + } + base.Delete(vendedorParcelaDb); + return true; + } + + public void DeleteRange(long id) + { + List<VendedorParcelaDb> list = ( + from vp in base.All() + where vp.Documento.Id == id && (int)vp.Parcela.SubTipo == 1 + select vp).ToList<VendedorParcelaDb>(); + if (list.Count == 0) + { + return; + } + VendedorParcelaRepository vendedorParcelaRepository = this; + list.ForEach(new Action<VendedorParcelaDb>(vendedorParcelaRepository.Delete)); + } + + public void DeleteRange(List<VendedorParcela> repasses) + { + List<long> list = ( + from y in repasses + select y.Id).ToList<long>(); + List<VendedorParcelaDb> vendedorParcelaDbs = ( + from x in base.All() + where list.Contains(x.Id) + select x).ToList<VendedorParcelaDb>(); + if (vendedorParcelaDbs.Count == 0) + { + return; + } + VendedorParcelaRepository vendedorParcelaRepository = this; + vendedorParcelaDbs.ForEach(new Action<VendedorParcelaDb>(vendedorParcelaRepository.Delete)); + } + + public List<ManutencaoPagamentos> FindByDate(Filtros filtro) + { + List<ManutencaoPagamentos> manutencaoPagamentos; + object connection; + DataTable dataTable = new DataTable(); + string str = (filtro.Referencia == "DATA PAGAMENTO" ? "CAST(vp.datapgt AS DATE)" : "CAST(vp.dataprepagto AS DATE)"); + List<Condicao> condicaos = new List<Condicao>() + { + new Condicao() + { + Campo = "vp.datapgt", + Valores = null, + Operador = Operador.Diferente, + Operacao = Operacao.And + }, + new Condicao() + { + Campo = str, + Valores = filtro.Inicio.CriarValor<DateTime>(), + Operador = Operador.MaiorEIgual + }, + new Condicao() + { + Campo = str, + Valores = filtro.Fim.CriarValor<DateTime>(), + Operador = Operador.MenorEIgual + } + }; + if (filtro.Vendedores != null && filtro.Vendedores.Any<long>()) + { + condicaos.Add(new Condicao() + { + Campo = "vp.idvendedor", + Valores = filtro.Vendedores.CriarValor<long>() + }); + } + if (filtro.IdEmpresa > (long)0) + { + condicaos.Add(new Condicao() + { + Campo = "c.idempresa", + Valores = filtro.IdEmpresa.CriarValor<long>() + }); + } + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + if (sqlConnection != null) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + Auxiliar.CriarAuxiliar(sqlCommand, false); + string str1 = "SELECT p.idparcela, vp.idvendedorparcela as idvendedorparcela, vp.iddocumento as iddocumento, c.idciaseg as idseguradora, cl.nome as nomecliente, c.idramo, d.contrato as apolice, d.aditamento as endosso, v.nome as nomevendedor, p.parcela as numeroparcela, p.valor as valor, p.datarec as datarecebimento, vp.datapgt as datapagamento, vp.dataprepagto as dataprepagamento, p.idsubtipo, c.idempresa, vp.vlrrep, c.idproduto FROM vendedorparcela vp INNER JOIN documento d on d.iddocumento = vp.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN vendedor v on v.idvendedor = vp.idvendedor INNER JOIN parcela p on p.idparcela = vp.idparcela INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE "; + dataTable = sqlCommand.Select(condicaos.CreateParameters(0), str1, ""); + return dataTable.MapManutencao(); + } + } + else + { + manutencaoPagamentos = null; + } + } + return manutencaoPagamentos; + } + + public List<VendedorParcela> FindByDocumentId(long documentId) + { + return this.Select(string.Format(" AND vp.iddocumento = {0}", documentId)); + } + + public VendedorParcela FindById(long id) + { + VendedorParcelaDb vendedorParcelaDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map<VendedorParcelaDb, VendedorParcela>(vendedorParcelaDb); + } + + public Vendedor FindByMainDocumentId(long id) + { + Vendedor vendedor; + object connection; + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + Auxiliar.CriarVendedor(sqlCommand, false); + sqlCommand.CommandText = string.Format("SELECT TOP 1 idvendedor as id FROM vendedorparcela vp INNER JOIN parcela p on p.idparcela = vp.idparcela WHERE vp.idtipovendedor = 1 AND p.idsubtipo = 1 AND vp.iddocumento = {0};", id); + SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); + if (sqlDataReader.HasRows) + { + sqlDataReader.Read(); + long num = (sqlDataReader["id"] == null ? (long)0 : long.Parse(sqlDataReader["id"].ToString())); + sqlDataReader.Close(); + return Auxiliar.Vendedores.FirstOrDefault<Vendedor>((Vendedor x) => { + if (x == null) + { + return false; + } + return x.Id == num; + }); + } + else + { + vendedor = null; + } + } + } + return vendedor; + } + + public List<VendedorParcela> FindByParcela(long id) + { + return this.Select(string.Format(" AND vp.idparcela = {0}", id)); + } + + public List<Vendedor> FindVendedoresByDocumentId(long documentId) + { + object connection; + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + DataTable dataTable = new DataTable(); + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + Auxiliar.CriarVendedor(sqlCommand, false); + sqlCommand.CommandText = string.Format("SELECT DISTINCT idvendedor as id FROM vendedorparcela WHERE iddocumento = {0}", documentId); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + } + } + return Auxiliar.Vendedores.Where<Vendedor>((Vendedor x) => { + List<DataRow> list = dataTable.AsEnumerable().ToList<DataRow>(); + Func<DataRow, long> u003cu003e9_181 = VendedorParcelaRepository.u003cu003ec.u003cu003e9__18_1; + if (u003cu003e9_181 == null) + { + u003cu003e9_181 = (DataRow v) => v.Field<long>("id"); + VendedorParcelaRepository.u003cu003ec.u003cu003e9__18_1 = u003cu003e9_181; + } + return list.Select<DataRow, long>(u003cu003e9_181).Contains<long>(x.Id); + }).ToList<Vendedor>(); + } + + public List<Vendedor> FindVinculoByIdCliente(long idcliente) + { + object connection; + SqlCommand sqlCommand; + List<long> list; + List<Condicao> condicaos = new List<Condicao>(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + condicaos.Add(new Condicao() + { + Campo = "cl.idcliente", + Valores = idcliente.CriarValor<long>() + }); + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + if (sqlConnection != null) + { + sqlCommand = sqlConnection.CreateCommand(); + } + else + { + sqlCommand = null; + } + using (SqlCommand sqlCommand1 = sqlCommand) + { + Auxiliar.CriarAuxiliar(sqlCommand1, false); + string str = "SELECT DISTINCT vp.idvendedor idvendedor FROM vendedorparcela vp LEFT JOIN documento d ON vp.iddocumento = d.iddocumento LEFT JOIN controle c ON c.idcontrole = d.idcontrole LEFT JOIN cliente cl on cl.idcliente = c.idcliente WHERE"; + DataTable dataTable = sqlCommand1.Select(condicaos.CreateParameters(0), str, ""); + list = dataTable.AsEnumerable().Select<DataRow, long>((DataRow column) => column.Field<long>("idvendedor")).ToList<long>(); + } + } + return ( + from v in Auxiliar.Vendedores + where list.Contains(v.Id) + select v).ToList<Vendedor>(); + } + + public bool GerarPagamento(List<long> ids, DateTime data) + { + bool flag; + object connection; + try + { + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + if (sqlConnection != null) + { + SqlTransaction sqlTransaction = sqlConnection.BeginTransaction(); + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandTimeout = 15000; + sqlCommand.Transaction = sqlTransaction; + List<long> nums = ids; + while (nums.Count > 0) + { + List<long> list = nums.Take<long>(1000).ToList<long>(); + List<Condicao> condicaos = new List<Condicao>() + { + new Condicao() + { + Campo = "idvendedorparcela", + Valores = list.CriarValor<long>() + }, + new Condicao() + { + Campo = "datapgt", + Valores = null + } + }; + List<SqlParameter> sqlParameters = new List<SqlParameter>() + { + new SqlParameter() + { + ParameterName = "@datapgt", + SqlDbType = Funcoes.GetDbType(typeof(DateTime)), + Value = data + } + }; + if (sqlCommand.Update(condicaos.CreateParameters(0), "UPDATE vendedorparcela SET datapgt = @datapgt WHERE ", sqlParameters)) + { + nums = (list.Count < 1000 ? new List<long>() : nums.Except<long>(list).ToList<long>()); + } + else + { + flag = false; + return flag; + } + } + sqlTransaction.Commit(); + sqlCommand.Dispose(); + } + } + else + { + flag = false; + return flag; + } + } + return true; + } + catch (Exception exception) + { + flag = false; + } + return flag; + } + + public VendedorParcela Merge(VendedorParcela vendedorParcela) + { + VendedorParcelaDb vendedorParcelaDb = ApplicationMapper.Mapper.Map<VendedorParcela, VendedorParcelaDb>(vendedorParcela); + base.Merge(vendedorParcelaDb); + return ApplicationMapper.Mapper.Map<VendedorParcelaDb, VendedorParcela>(vendedorParcelaDb); + } + + public VendedorParcela SaveOrUpdate(VendedorParcela vendedorParcela) + { + VendedorParcelaDb vendedorParcelaDb = ApplicationMapper.Mapper.Map<VendedorParcela, VendedorParcelaDb>(vendedorParcela); + this.SaveOrUpdate(vendedorParcelaDb); + return ApplicationMapper.Mapper.Map<VendedorParcelaDb, VendedorParcela>(vendedorParcelaDb); + } + + public List<VendedorParcela> Select(string condition) + { + object connection; + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + DataTable dataTable = new DataTable(); + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + Auxiliar.CriarVendedor(sqlCommand, true); + sqlCommand.CommandText = string.Concat("SELECT DISTINCT * FROM vendedorparcela vp INNER JOIN parcela p on p.idparcela = vp.idparcela WHERE 1=1 ", condition); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + } + } + return CustomMap.MapVendedorParcela(dataTable); + } + + public bool TemPagamentoParcela(long id) + { + return base.All().Any<VendedorParcelaDb>((VendedorParcelaDb x) => x.Parcela.Id == id && (x.DataPagamento != null) && (int?)x.Repasse.Forma == (int?)FormaRepasse.Recebimento); + } + + public bool TipoVendedorUtilizado(long id) + { + return base.All().Any<VendedorParcelaDb>((VendedorParcelaDb x) => x.TipoVendedor.Id == id); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorRepository.cs new file mode 100644 index 0000000..04a6532 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorRepository.cs @@ -0,0 +1,132 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Helpers; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Seguros; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class VendedorRepository : GenericRepository<VendedorDb>, IVendedorRepository, IGenericRepository<VendedorDb> + { + private readonly GenericUnitOfWork _unitOfWork; + + private const string comandoVendedor = "SELECT idvendedor, nome, corretora, tipoincidenciadesconto, desconto, ativo, idempresa, idcodigobanco, agencia, conta, cpfcnpj, idtipoconta, cpfcnpjtitular, titularconta, obs FROM vendedor WHERE"; + + public VendedorRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public List<Vendedor> Find(bool ativo, long idempresa = 0L) + { + List<Condicao> condicaos = new List<Condicao>() + { + new Condicao() + { + Campo = "idempresa", + Valores = idempresa.CriarValor<long>() + } + }; + List<Condicao> condicaos1 = new List<Condicao>() + { + new Condicao() + { + Campo = "ISNULL(ativo, '1')", + Valores = (ativo ? "1".CriarValor<string>() : "0".CriarValor<string>()) + } + }; + if (idempresa > (long)0) + { + condicaos1.AddRange(condicaos); + } + return this._unitOfWork.Select(condicaos1.CreateParameters(0), "SELECT idvendedor, nome, corretora, tipoincidenciadesconto, desconto, ativo, idempresa, idcodigobanco, agencia, conta, cpfcnpj, idtipoconta, cpfcnpjtitular, titularconta, obs FROM vendedor WHERE", "").MapVendedor(); + } + + public List<Vendedor> Find(long idempresa = 0L) + { + return this.Select((idempresa == 0 ? "" : string.Format(" AND idempresa = {0}", idempresa))); + } + + public List<Vendedor> Find(string nome, long idempresa = 0L) + { + string str = (idempresa == 0 ? "" : string.Format(" AND idempresa = {0}", idempresa)); + string str1 = string.Concat(" AND UPPER(ISNULL(nome, '')) LIKE '%", nome.ToUpper(), "%'"); + return this.Select(string.Concat(str, str1)); + } + + public Vendedor FindById(long id) + { + VendedorDb vendedorDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map<VendedorDb, Vendedor>(vendedorDb); + } + + public Vendedor FindCorretora() + { + VendedorDb vendedorDb = base.All().FirstOrDefault<VendedorDb>((VendedorDb x) => x.Corretora); + return ApplicationMapper.Mapper.Map<VendedorDb, Vendedor>(vendedorDb); + } + + public Vendedor Merge(Vendedor vendedor) + { + VendedorDb vendedorDb = ApplicationMapper.Mapper.Map<Vendedor, VendedorDb>(vendedor); + base.Merge(vendedorDb); + return ApplicationMapper.Mapper.Map<VendedorDb, Vendedor>(vendedorDb); + } + + public Vendedor SaveOrUpdate(Vendedor vendedor) + { + VendedorDb vendedorDb = ApplicationMapper.Mapper.Map<Vendedor, VendedorDb>(vendedor); + this.SaveOrUpdate(vendedorDb); + return ApplicationMapper.Mapper.Map<VendedorDb, Vendedor>(vendedorDb); + } + + public List<Vendedor> Select(string condition) + { + object connection; + DataTable dataTable = new DataTable(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + Auxiliar.CriarAuxiliar(sqlCommand, false); + sqlCommand.CommandText = string.Concat("SELECT idvendedor, nome, corretora, tipoincidenciadesconto, desconto, ativo, idempresa, idcodigobanco, agencia, conta, cpfcnpj, idtipoconta, cpfcnpjtitular, titularconta, obs FROM vendedor WHERE 1=1 ", condition, " "); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + } + } + return dataTable.MapVendedor(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorTelefoneRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorTelefoneRepository.cs new file mode 100644 index 0000000..2f4d3c1 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorTelefoneRepository.cs @@ -0,0 +1,115 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class VendedorTelefoneRepository : GenericRepository<VendedorTelefoneDb>, IVendedorTelefoneRepository, IGenericRepository<VendedorTelefoneDb> + { + private readonly GenericUnitOfWork _unitOfWork; + + public VendedorTelefoneRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public VendedorTelefone FindById(long id) + { + VendedorTelefoneDb vendedorTelefoneDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map<VendedorTelefoneDb, VendedorTelefone>(vendedorTelefoneDb); + } + + public List<VendedorTelefone> FindByVendedorId(long id) + { + List<VendedorTelefoneDb> list = ( + from x in base.All() + where x.Vendedor.Id == id + select x).ToList<VendedorTelefoneDb>(); + return ApplicationMapper.Mapper.Map<List<VendedorTelefoneDb>, List<VendedorTelefone>>(list); + } + + public List<VendedorTelefone> Inserir(List<VendedorTelefone> telefones) + { + List<VendedorTelefoneDb> vendedorTelefoneDbs = ApplicationMapper.Mapper.Map<List<VendedorTelefone>, List<VendedorTelefoneDb>>(telefones); + vendedorTelefoneDbs.ForEach((VendedorTelefoneDb x) => { + if (x.Id == 0) + { + this.SaveOrUpdate(x); + return; + } + base.Merge(x); + }); + return ApplicationMapper.Mapper.Map<List<VendedorTelefoneDb>, List<VendedorTelefone>>(vendedorTelefoneDbs); + } + + public List<VendedorTelefone> Inserir(List<VendedorTelefone> telefones, Vendedor vendedor) + { + telefones.ForEach((VendedorTelefone x) => x.Vendedor = vendedor); + List<VendedorTelefoneDb> vendedorTelefoneDbs = ApplicationMapper.Mapper.Map<List<VendedorTelefone>, List<VendedorTelefoneDb>>(telefones); + base.AddRange(vendedorTelefoneDbs); + return ApplicationMapper.Mapper.Map<List<VendedorTelefoneDb>, List<VendedorTelefone>>(vendedorTelefoneDbs); + } + + public VendedorTelefone Merge(VendedorTelefone telefone) + { + VendedorTelefoneDb vendedorTelefoneDb = ApplicationMapper.Mapper.Map<VendedorTelefone, VendedorTelefoneDb>(telefone); + base.Merge(vendedorTelefoneDb); + return ApplicationMapper.Mapper.Map<VendedorTelefoneDb, VendedorTelefone>(vendedorTelefoneDb); + } + + public List<VendedorTelefone> Merge(List<VendedorTelefone> telefones, Vendedor vendedor) + { + IQueryable<VendedorTelefoneDb> vendedorTelefoneDbs = + from x in base.All() + where x.Vendedor.Id == vendedor.Id + select x; + VendedorTelefoneRepository vendedorTelefoneRepository = this; + ( + from x in vendedorTelefoneDbs + select x.Id).ToList<long>().Where<long>((long x) => { + List<VendedorTelefone> vendedorTelefones = telefones; + Func<VendedorTelefone, long> u003cu003e9_94 = VendedorTelefoneRepository.u003cu003ec.u003cu003e9__9_4; + if (u003cu003e9_94 == null) + { + u003cu003e9_94 = (VendedorTelefone t) => t.Id; + VendedorTelefoneRepository.u003cu003ec.u003cu003e9__9_4 = u003cu003e9_94; + } + return !vendedorTelefones.Select<VendedorTelefone, long>(u003cu003e9_94).Contains<long>(x); + }).ToList<long>().ForEach(new Action<long>(vendedorTelefoneRepository.Delete)); + List<VendedorTelefoneDb> vendedorTelefoneDbs1 = ApplicationMapper.Mapper.Map<List<VendedorTelefone>, List<VendedorTelefoneDb>>(telefones); + vendedorTelefoneDbs1.ForEach((VendedorTelefoneDb x) => { + if (x.Id != 0) + { + base.Merge(x); + return; + } + x.Vendedor = ApplicationMapper.Mapper.Map<Vendedor, VendedorDb>(vendedor); + this.SaveOrUpdate(x); + }); + return ApplicationMapper.Mapper.Map<List<VendedorTelefoneDb>, List<VendedorTelefone>>(vendedorTelefoneDbs1); + } + + public VendedorTelefone SaveOrUpdate(VendedorTelefone telefone) + { + VendedorTelefoneDb vendedorTelefoneDb = ApplicationMapper.Mapper.Map<VendedorTelefone, VendedorTelefoneDb>(telefone); + this.SaveOrUpdate(vendedorTelefoneDb); + return ApplicationMapper.Mapper.Map<VendedorTelefoneDb, VendedorTelefone>(vendedorTelefoneDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorUsuarioRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorUsuarioRepository.cs new file mode 100644 index 0000000..49c552f --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorUsuarioRepository.cs @@ -0,0 +1,94 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class VendedorUsuarioRepository : GenericRepository<VendedorUsuarioDb>, IVendedorUsuarioRepository, IGenericRepository<VendedorUsuarioDb> + { + private readonly GenericUnitOfWork _unitOfWork; + + public VendedorUsuarioRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public bool Exist(long id) + { + return base.All().Any<VendedorUsuarioDb>((VendedorUsuarioDb v) => v.Vendedor.Id == id); + } + + public bool ExistVinculoUsuario(long idUsuario) + { + return base.All().Any<VendedorUsuarioDb>((VendedorUsuarioDb v) => v.Usuario.Id == idUsuario); + } + + public VendedorUsuario FindById(long id) + { + VendedorUsuarioDb vendedorUsuarioDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map<VendedorUsuarioDb, VendedorUsuario>(vendedorUsuarioDb); + } + + public IList<Vendedor> FindByUsuario(long idUsuario) + { + List<VendedorUsuarioDb> list = ( + from x in base.All() + where x.Usuario.Id == idUsuario + select x).ToList<VendedorUsuarioDb>(); + List<Vendedor> vendedors = new List<Vendedor>(); + list.ForEach((VendedorUsuarioDb vu) => vendedors.Add((new VendedorRepository(this._unitOfWork)).FindById(vu.Vendedor.Id))); + return vendedors; + } + + public List<VendedorUsuario> FindByVinculo(long idUsuario) + { + return ( + from x in base.All() + where x.Usuario.Id == idUsuario + select x into u + select new VendedorUsuario() + { + Id = u.Id, + Usuario = new Usuario() + { + Id = u.Usuario.Id, + Nome = u.Usuario.Nome + }, + Vendedor = new Vendedor() + { + Id = u.Vendedor.Id, + Nome = u.Vendedor.Nome + } + }).ToList<VendedorUsuario>(); + } + + public VendedorUsuario Merge(VendedorUsuario vendedorUsuario) + { + VendedorUsuarioDb vendedorUsuarioDb = ApplicationMapper.Mapper.Map<VendedorUsuario, VendedorUsuarioDb>(vendedorUsuario); + base.Merge(vendedorUsuarioDb); + return ApplicationMapper.Mapper.Map<VendedorUsuarioDb, VendedorUsuario>(vendedorUsuarioDb); + } + + public VendedorUsuario SaveOrUpdate(VendedorUsuario vendedorUsuario) + { + VendedorUsuarioDb vendedorUsuarioDb = ApplicationMapper.Mapper.Map<VendedorUsuario, VendedorUsuarioDb>(vendedorUsuario); + this.SaveOrUpdate(vendedorUsuarioDb); + return ApplicationMapper.Mapper.Map<VendedorUsuarioDb, VendedorUsuario>(vendedorUsuarioDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VidaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VidaRepository.cs new file mode 100644 index 0000000..d5507ae --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VidaRepository.cs @@ -0,0 +1,66 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Entities.Seguros; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class VidaRepository : GenericRepository<VidaDb>, IVidaRepository, IGenericRepository<VidaDb> + { + private readonly GenericUnitOfWork _unitOfWork; + + public VidaRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public void Delete(long id) + { + base.Delete(base.FindEntityById(id)); + } + + public void DeleteRange(List<long> ids) + { + List<VidaDb> list = ( + from x in base.All() + where ids.Contains(x.Item.Id) + select x).ToList<VidaDb>(); + base.DeleteRange(list); + } + + public Vida Find(long id) + { + VidaDb vidaDb = base.All().FirstOrDefault<VidaDb>((VidaDb x) => x.Item.Id == id) ?? new VidaDb(); + return ApplicationMapper.Mapper.Map<VidaDb, Vida>(vidaDb); + } + + public Vida FindById(long id) + { + VidaDb vidaDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map<VidaDb, Vida>(vidaDb); + } + + public Vida Merge(Vida vida) + { + VidaDb vidaDb = ApplicationMapper.Mapper.Map<Vida, VidaDb>(vida); + base.Merge(vidaDb); + return ApplicationMapper.Mapper.Map<VidaDb, Vida>(vidaDb); + } + + public Vida SaveOrUpdate(Vida vida) + { + VidaDb vidaDb = ApplicationMapper.Mapper.Map<Vida, VidaDb>(vida); + this.SaveOrUpdate(vidaDb); + return ApplicationMapper.Mapper.Map<VidaDb, Vida>(vidaDb); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VinculoDocumentoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VinculoDocumentoRepository.cs new file mode 100644 index 0000000..4ad03aa --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VinculoDocumentoRepository.cs @@ -0,0 +1,345 @@ +using AutoMapper; +using Gestor.Infrastructure.Entities.Aggilizador; +using Gestor.Infrastructure.Entities.Generic; +using Gestor.Infrastructure.Mappers; +using Gestor.Infrastructure.Repository.Generic; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Aggilizador; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Helper; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Gestor.Infrastructure.Repository.Logic +{ + public class VinculoDocumentoRepository : GenericRepository<VinculoDocumentoDb>, IVinculoDocumentoRepository, IGenericRepository<VinculoDocumentoDb> + { + private readonly GenericUnitOfWork _unitOfWork; + + public VinculoDocumentoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) + { + this._unitOfWork = unitOfWork; + } + + public List<ArquivoVinculo> BuscarArquivos(List<long> ids, TipoArquivoVinculo type) + { + string str; + str = (type == TipoArquivoVinculo.Proposta ? "IdPropostaDigital" : "IdApoliceDigital"); + return this.Select(string.Concat(new string[] { " AND ", str, " IN (", string.Join<long>(",", ids), ")" }), type); + } + + public void Delete(long id) + { + VinculoDocumentoDb vinculoDocumentoDb = base.FindEntityById(id); + if (vinculoDocumentoDb == null) + { + return; + } + base.Delete(vinculoDocumentoDb); + } + + public VinculoDocumento FindById(long id) + { + VinculoDocumentoDb vinculoDocumentoDb = base.FindEntityById(id); + return ApplicationMapper.Mapper.Map<VinculoDocumentoDb, VinculoDocumento>(vinculoDocumentoDb); + } + + public VinculoDocumento Merge(VinculoDocumento vinculo) + { + VinculoDocumentoDb vinculoDocumentoDb = ApplicationMapper.Mapper.Map<VinculoDocumento, VinculoDocumentoDb>(vinculo); + base.Merge(vinculoDocumentoDb); + return ApplicationMapper.Mapper.Map<VinculoDocumentoDb, VinculoDocumento>(vinculoDocumentoDb); + } + + public VinculoDocumento SaveOrUpdate(VinculoDocumento vinculo) + { + VinculoDocumentoDb vinculoDocumentoDb = ApplicationMapper.Mapper.Map<VinculoDocumento, VinculoDocumentoDb>(vinculo); + this.SaveOrUpdate(vinculoDocumentoDb); + return ApplicationMapper.Mapper.Map<VinculoDocumentoDb, VinculoDocumento>(vinculoDocumentoDb); + } + + public void SaveVinculo(VinculoDocumentoDb vinculoDb) + { + if (vinculoDb.Id == 0) + { + this.SaveOrUpdate(vinculoDb); + return; + } + base.Merge(vinculoDb); + } + + private List<ArquivoVinculo> Select(string condition, TipoArquivoVinculo type) + { + string str; + string str1; + object connection; + DataTable dataTable = new DataTable(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + if (sqlConnection != null) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + if (type == TipoArquivoVinculo.Proposta) + { + str = "IdArquivoProposta as Id, Conteudo as Arquivo, IdPropostaDigital as IdVinculo, Chave, Ano, Storage"; + str1 = "ArquivoProposta"; + } + else + { + str = "IdArquivoApolice as Id, Conteudo as Arquivo, IdApoliceDigital as IdVinculo, Chave, Ano, Storage"; + str1 = "ArquivoApolice"; + } + sqlCommand.CommandText = string.Concat(new string[] { "SELECT ", str, " FROM ", str1, " WHERE 1=1 ", condition }); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + sqlCommand.Parameters.Clear(); + } + } + } + return CustomMap.MapArquivoVinculo(dataTable); + } + + public int Sincronize(DateTime inicio, List<DadosVinculo> dados) + { + int num1; + object connection; + int num2; + int num3 = 0; + int num4 = 0; + try + { + DataTable dataTable = new DataTable(); + DataTable dataTable1 = new DataTable(); + SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + if (sqlConnection != null) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = "SELECT * FROM PropostaDigital p INNER JOIN ClienteDigital c on c.idcliente = p.idcliente WHERE Data >= @Data"; + sqlCommand.Parameters.AddWithValue("@Data", inicio.AddMonths(-2)); + using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) + { + sqlDataAdapter.SelectCommand = sqlCommand; + sqlDataAdapter.Fill(dataTable); + } + sqlCommand.CommandText = "SELECT * FROM ApoliceDigital p INNER JOIN ClienteDigital c on c.idcliente = p.idcliente WHERE DataEmissao >= @Data"; + using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) + { + sqlDataAdapter1.SelectCommand = sqlCommand; + sqlDataAdapter1.Fill(dataTable1); + } + sqlCommand.Parameters.Clear(); + } + } + } + dataTable = dataTable.AsEnumerable().Where<DataRow>((DataRow x) => !string.IsNullOrWhiteSpace(x.Field<string>("Numero"))).CopyToDataTable<DataRow>(); + dados.ForEach((DadosVinculo x) => { + num3++; + if (x.IdSeguradora != (long)1) + { + x.Proposta = x.Proposta.Clear(); + } + x.Documento = x.Documento.Clear(); + x.Vinculo = x.Vinculo ?? new VinculoDocumento() + { + IdDocumento = x.Id + }; + if (!string.IsNullOrWhiteSpace(x.Proposta) && string.IsNullOrWhiteSpace(x.Endosso)) + { + DataRow dataRow = (x.Vinculo.IdPropostaDigital > (long)0 ? dataTable.AsEnumerable().FirstOrDefault<DataRow>((DataRow p) => p.Field<long>("IdProposta") == x.Vinculo.IdPropostaDigital) : dataTable.AsEnumerable().FirstOrDefault<DataRow>((DataRow p) => { + if (x.IdSeguradora == (long)1 && !p.IsNull("Identificacao")) + { + return p.Field<string>("Identificacao").Equals(x.Proposta); + } + if (!p.Field<string>("Numero").Equals(x.Proposta)) + { + return false; + } + return p.Field<int>("Seguradora").Equals((int)x.IdSeguradora); + })); + if (dataRow != null) + { + x.Vinculo.IdPropostaDigital = dataRow.Field<long>("IdProposta"); + DataRow dataRow1 = dataTable1.AsEnumerable().FirstOrDefault<DataRow>((DataRow y) => { + if (!y.Field<long?>("IdProposta").HasValue) + { + return false; + } + return y.Field<long>("IdProposta") == x.Vinculo.IdPropostaDigital; + }); + x.Vinculo.IdApoliceDigital = (dataRow1 != null ? dataRow1.Field<long>("IdApolice") : (long)0); + this.SaveVinculo(ApplicationMapper.Mapper.Map<VinculoDocumento, VinculoDocumentoDb>(x.Vinculo)); + num4++; + return; + } + EnumerableRowCollection<DataRow> dataRows = dataTable.AsEnumerable().Where<DataRow>((DataRow p) => { + if (!string.IsNullOrEmpty(p.Field<string>("Documento")) && !p.Field<string>("Documento").Equals(x.Documento) || !p.Field<int>("Seguradora").Equals((int)x.IdSeguradora)) + { + return false; + } + if (x.Proposta.Contains(p.Field<string>("Numero"))) + { + return true; + } + return p.Field<string>("Numero").Contains(x.Proposta); + }); + Func<DataRow, long> u003cu003e9_38 = VinculoDocumentoRepository.u003cu003ec.u003cu003e9__3_8; + if (u003cu003e9_38 == null) + { + u003cu003e9_38 = (DataRow y) => y.Field<long>("idProposta"); + VinculoDocumentoRepository.u003cu003ec.u003cu003e9__3_8 = u003cu003e9_38; + } + List<long> list = dataRows.Select<DataRow, long>(u003cu003e9_38).ToList<long>(); + if (list.Count != 0) + { + DataRow dataRow2 = dataTable1.AsEnumerable().Where<DataRow>((DataRow y) => { + if (!y.Field<long?>("IdProposta").HasValue) + { + return false; + } + return list.Contains(y.Field<long>("IdProposta")); + }).FirstOrDefault<DataRow>((DataRow y) => { + if (y.Field<string>("Endosso") != null && (!int.TryParse(y.Field<string>("Endosso"), out num2) || num2 != 0)) + { + return false; + } + DateTime? nullable = y.Field<DateTime?>("VigenciaInicial"); + DateTime vigenciaInicial = x.VigenciaInicial; + if ((nullable.HasValue ? nullable.GetValueOrDefault() != vigenciaInicial : true)) + { + nullable = y.Field<DateTime?>("VigenciaFinal"); + DateTime? vigenciafinal = x.Vigenciafinal; + if ((nullable.HasValue == vigenciafinal.HasValue ? (nullable.HasValue ? nullable.GetValueOrDefault() != vigenciafinal.GetValueOrDefault() : false) : true)) + { + vigenciafinal = y.Field<DateTime?>("DataEmissao"); + if (!vigenciafinal.HasValue) + { + return false; + } + vigenciaInicial = y.Field<DateTime>("DataEmissao"); + return vigenciaInicial.AddMonths(1) >= x.VigenciaInicial; + } + } + return true; + }); + if (dataRow2 != null) + { + dataRow = dataTable.AsEnumerable().First<DataRow>((DataRow p) => p.Field<long>("IdProposta") == dataRow2.Field<long>("IdProposta")); + x.Vinculo.IdPropostaDigital = dataRow.Field<long>("IdProposta"); + x.Vinculo.IdApoliceDigital = dataRow2.Field<long>("IdApolice"); + this.SaveVinculo(ApplicationMapper.Mapper.Map<VinculoDocumento, VinculoDocumentoDb>(x.Vinculo)); + num4++; + return; + } + } + } + num2 = 0; + DataRow dataRow3 = dataTable1.AsEnumerable().Where<DataRow>((DataRow p) => { + if (p.Field<string>("Documento") == null || !p.Field<string>("Documento").Equals(x.Documento)) + { + return false; + } + return p.Field<int>("Seguradora").Equals((int)x.IdSeguradora); + }).ToList<DataRow>().FirstOrDefault<DataRow>((DataRow y) => { + DateTime vigenciaInicial; + DateTime? vigenciafinal; + if (!string.IsNullOrWhiteSpace(x.Endosso)) + { + if (y.Field<string>("Endosso") == null || !int.TryParse(y.Field<string>("Endosso"), out num2) || num2 <= 0) + { + return false; + } + vigenciafinal = y.Field<DateTime?>("VigenciaInicial"); + vigenciaInicial = x.VigenciaInicial; + if (!vigenciafinal.HasValue) + { + return false; + } + return vigenciafinal.GetValueOrDefault() == vigenciaInicial; + } + if (y.Field<string>("Endosso") == null) + { + return true; + } + if (!int.TryParse(y.Field<string>("Endosso"), out num2) || num2 != 0) + { + return false; + } + DateTime? nullable = y.Field<DateTime?>("VigenciaInicial"); + vigenciaInicial = x.VigenciaInicial; + if ((nullable.HasValue ? nullable.GetValueOrDefault() != vigenciaInicial : true)) + { + nullable = y.Field<DateTime?>("VigenciaFinal"); + vigenciafinal = x.Vigenciafinal; + if ((nullable.HasValue == vigenciafinal.HasValue ? (nullable.HasValue ? nullable.GetValueOrDefault() != vigenciafinal.GetValueOrDefault() : false) : true)) + { + vigenciafinal = y.Field<DateTime?>("DataEmissao"); + if (!vigenciafinal.HasValue) + { + return false; + } + vigenciaInicial = y.Field<DateTime>("DataEmissao"); + return vigenciaInicial.AddMonths(1) >= x.VigenciaInicial; + } + } + return true; + }); + if (dataRow3 == null) + { + return; + } + DataRow dataRow4 = dataTable.AsEnumerable().FirstOrDefault<DataRow>((DataRow p) => { + if (!dataRow3.Field<long?>("IdProposta").HasValue) + { + return false; + } + return p.Field<long>("IdProposta") == dataRow3.Field<long>("IdProposta"); + }); + x.Vinculo.IdPropostaDigital = (dataRow4 != null ? dataRow4.Field<long>("IdProposta") : (long)0); + x.Vinculo.IdApoliceDigital = dataRow3.Field<long>("IdApolice"); + this.SaveVinculo(ApplicationMapper.Mapper.Map<VinculoDocumento, VinculoDocumentoDb>(x.Vinculo)); + num4++; + }); + num1 = num4; + } + catch (Exception exception) + { + num1 = num4; + } + return num1; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Types/CustomBoolType.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Types/CustomBoolType.cs new file mode 100644 index 0000000..7b53b5a --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Types/CustomBoolType.cs @@ -0,0 +1,150 @@ +using NHibernate; +using NHibernate.Engine; +using NHibernate.SqlTypes; +using NHibernate.Type; +using NHibernate.UserTypes; +using System; +using System.Collections; +using System.Data; +using System.Data.Common; + +namespace Gestor.Infrastructure.Types +{ + [Serializable] + public class CustomBoolType : IUserType + { + public bool IsMutable + { + get + { + return false; + } + } + + public Type ReturnedType + { + get + { + return typeof(CustomBoolType); + } + } + + public SqlType[] SqlTypes + { + get + { + return new SqlType[] { NHibernateUtil.String.SqlType }; + } + } + + public CustomBoolType() + { + } + + public object Assemble(object cached, object owner) + { + return cached; + } + + public object DeepCopy(object value) + { + return value; + } + + public object Disassemble(object value) + { + return value; + } + + public new bool Equals(object x, object y) + { + if (x == y) + { + return true; + } + if (x == null || y == null) + { + return false; + } + return x.Equals(y); + } + + public int GetHashCode(object x) + { + if (x != null) + { + return x.GetHashCode(); + } + return typeof(bool).GetHashCode() + 473; + } + + public object NullSafeGet(DbDataReader rs, string[] names, ISessionImplementor session, object owner) + { + int num; + string str; + object obj = NHibernateUtil.String.NullSafeGet(rs, names[0], session, owner); + if (obj != null) + { + str = obj.ToString(); + } + else + { + str = null; + } + string str1 = str; + if (!int.TryParse(str1, out num) && Math.Abs(num) > 1 && str1 != null) + { + throw new Exception(); + } + return str1 == "1"; + } + + public object NullSafeGet(IDataReader rs, string[] names, object owner) + { + int num; + string str; + object obj = NHibernateUtil.String.NullSafeGet(rs, names[0]); + if (obj != null) + { + str = obj.ToString(); + } + else + { + str = null; + } + string str1 = str; + if (!int.TryParse(str1, out num) && Math.Abs(num) > 1 && str1 != null) + { + throw new Exception(); + } + return str1 == "1"; + } + + public void NullSafeSet(DbCommand cmd, object value, int index, ISessionImplementor session) + { + IDataParameter item = cmd.Parameters[index]; + if (value == null) + { + item.Value = DBNull.Value; + return; + } + item.Value = ((bool)value ? "1" : "0"); + } + + public void NullSafeSet(IDbCommand cmd, object value, int index) + { + IDataParameter item = cmd.Parameters[index] as IDataParameter; + if (value == null) + { + item.Value = DBNull.Value; + return; + } + item.Value = ((bool)value ? "1" : "0"); + } + + public object Replace(object original, object target, object owner) + { + return original; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Types/CustomEnumType2_T_.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Types/CustomEnumType2_T_.cs new file mode 100644 index 0000000..d782980 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Types/CustomEnumType2_T_.cs @@ -0,0 +1,163 @@ +using Gestor.Common.Helpers; +using NHibernate; +using NHibernate.Engine; +using NHibernate.SqlTypes; +using NHibernate.Type; +using NHibernate.UserTypes; +using System; +using System.Collections; +using System.Data; +using System.Data.Common; + +namespace Gestor.Infrastructure.Types +{ + [Serializable] + public class CustomEnumType2<T> : IUserType + { + public bool IsMutable + { + get + { + return false; + } + } + + public Type ReturnedType + { + get + { + return typeof(CustomEnumType2<T>); + } + } + + public SqlType[] SqlTypes + { + get + { + return new SqlType[] { NHibernateUtil.String.SqlType }; + } + } + + public CustomEnumType2() + { + } + + public object Assemble(object cached, object owner) + { + return cached; + } + + public object DeepCopy(object value) + { + return value; + } + + public object Disassemble(object value) + { + return value; + } + + public new bool Equals(object x, object y) + { + if (x == y) + { + return true; + } + if (x == null || y == null) + { + return false; + } + return x.Equals(y); + } + + public int GetHashCode(object x) + { + if (x != null) + { + return x.GetHashCode(); + } + return typeof(bool).GetHashCode() + 473; + } + + public object NullSafeGet(DbDataReader rs, string[] names, ISessionImplementor session, object owner) + { + string str; + object obj = NHibernateUtil.String.NullSafeGet(rs, names[0], session, owner); + if (obj != null) + { + str = obj.ToString(); + } + else + { + str = null; + } + string str1 = str; + if (str1 == null || string.IsNullOrWhiteSpace(str1)) + { + return null; + } + return str1.ToEnumByOldValue2<T>(); + } + + public object NullSafeGet(IDataReader rs, string[] names, object owner) + { + string str; + object obj = NHibernateUtil.String.NullSafeGet(rs, names[0]); + if (obj != null) + { + str = obj.ToString(); + } + else + { + str = null; + } + string str1 = str; + if (str1 == null || string.IsNullOrWhiteSpace(str1)) + { + return null; + } + return str1.ToEnumByOldValue2<T>(); + } + + public void NullSafeSet(DbCommand cmd, object value, int index, ISessionImplementor session) + { + IDataParameter item = cmd.Parameters[index]; + if (value == null) + { + item.Value = DBNull.Value; + return; + } + T t = (T)value; + IDataParameter dataParameter = item; + object oldValue2 = t.GetOldValue2<T>(); + if (oldValue2 == null) + { + oldValue2 = DBNull.Value; + } + dataParameter.Value = oldValue2; + } + + public void NullSafeSet(IDbCommand cmd, object value, int index) + { + IDataParameter item = cmd.Parameters[index] as IDataParameter; + if (value == null) + { + item.Value = DBNull.Value; + return; + } + T t = (T)value; + IDataParameter dataParameter = item; + object oldValue2 = t.GetOldValue2<T>(); + if (oldValue2 == null) + { + oldValue2 = DBNull.Value; + } + dataParameter.Value = oldValue2; + } + + public object Replace(object original, object target, object owner) + { + return original; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Types/CustomEnumType_T_.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Types/CustomEnumType_T_.cs new file mode 100644 index 0000000..affce9f --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Types/CustomEnumType_T_.cs @@ -0,0 +1,163 @@ +using Gestor.Common.Helpers; +using NHibernate; +using NHibernate.Engine; +using NHibernate.SqlTypes; +using NHibernate.Type; +using NHibernate.UserTypes; +using System; +using System.Collections; +using System.Data; +using System.Data.Common; + +namespace Gestor.Infrastructure.Types +{ + [Serializable] + public class CustomEnumType<T> : IUserType + { + public bool IsMutable + { + get + { + return false; + } + } + + public Type ReturnedType + { + get + { + return typeof(CustomEnumType<T>); + } + } + + public SqlType[] SqlTypes + { + get + { + return new SqlType[] { NHibernateUtil.String.SqlType }; + } + } + + public CustomEnumType() + { + } + + public object Assemble(object cached, object owner) + { + return cached; + } + + public object DeepCopy(object value) + { + return value; + } + + public object Disassemble(object value) + { + return value; + } + + public new bool Equals(object x, object y) + { + if (x == y) + { + return true; + } + if (x == null || y == null) + { + return false; + } + return x.Equals(y); + } + + public int GetHashCode(object x) + { + if (x != null) + { + return x.GetHashCode(); + } + return typeof(bool).GetHashCode() + 473; + } + + public object NullSafeGet(DbDataReader rs, string[] names, ISessionImplementor session, object owner) + { + string str; + object obj = NHibernateUtil.String.NullSafeGet(rs, names[0], session, owner); + if (obj != null) + { + str = obj.ToString(); + } + else + { + str = null; + } + string str1 = str; + if (str1 == null || string.IsNullOrWhiteSpace(str1)) + { + return null; + } + return str1.ToEnumByOldValue<T>(); + } + + public object NullSafeGet(IDataReader rs, string[] names, object owner) + { + string str; + object obj = NHibernateUtil.String.NullSafeGet(rs, names[0]); + if (obj != null) + { + str = obj.ToString(); + } + else + { + str = null; + } + string str1 = str; + if (str1 == null || string.IsNullOrWhiteSpace(str1)) + { + return null; + } + return str1.ToEnumByOldValue<T>(); + } + + public void NullSafeSet(DbCommand cmd, object value, int index, ISessionImplementor session) + { + IDataParameter item = cmd.Parameters[index]; + if (value == null) + { + item.Value = DBNull.Value; + return; + } + T t = (T)value; + IDataParameter dataParameter = item; + object oldValue = t.GetOldValue<T>(); + if (oldValue == null) + { + oldValue = DBNull.Value; + } + dataParameter.Value = oldValue; + } + + public void NullSafeSet(IDbCommand cmd, object value, int index) + { + IDataParameter item = cmd.Parameters[index] as IDataParameter; + if (value == null) + { + item.Value = DBNull.Value; + return; + } + T t = (T)value; + IDataParameter dataParameter = item; + object oldValue = t.GetOldValue<T>(); + if (oldValue == null) + { + oldValue = DBNull.Value; + } + dataParameter.Value = oldValue; + } + + public object Replace(object original, object target, object owner) + { + return original; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Types/CustomIntType.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Types/CustomIntType.cs new file mode 100644 index 0000000..2afb90f --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Types/CustomIntType.cs @@ -0,0 +1,150 @@ +using NHibernate; +using NHibernate.Engine; +using NHibernate.SqlTypes; +using NHibernate.Type; +using NHibernate.UserTypes; +using System; +using System.Collections; +using System.Data; +using System.Data.Common; + +namespace Gestor.Infrastructure.Types +{ + [Serializable] + public class CustomIntType : IUserType + { + public bool IsMutable + { + get + { + return false; + } + } + + public Type ReturnedType + { + get + { + return typeof(CustomIntType); + } + } + + public SqlType[] SqlTypes + { + get + { + return new SqlType[] { NHibernateUtil.String.SqlType }; + } + } + + public CustomIntType() + { + } + + public object Assemble(object cached, object owner) + { + return cached; + } + + public object DeepCopy(object value) + { + return value; + } + + public object Disassemble(object value) + { + return value; + } + + public new bool Equals(object x, object y) + { + if (x == y) + { + return true; + } + if (x == null || y == null) + { + return false; + } + return x.Equals(y); + } + + public int GetHashCode(object x) + { + if (x != null) + { + return x.GetHashCode(); + } + return typeof(int).GetHashCode() + 473; + } + + public object NullSafeGet(DbDataReader rs, string[] names, ISessionImplementor session, object owner) + { + int num; + string str; + object obj = NHibernateUtil.String.NullSafeGet(rs, names[0], session, owner); + if (obj != null) + { + str = obj.ToString(); + } + else + { + str = null; + } + string str1 = str; + if (!int.TryParse(str1, out num) && !string.IsNullOrWhiteSpace(str1)) + { + throw new Exception(); + } + return num; + } + + public object NullSafeGet(IDataReader rs, string[] names, object owner) + { + int num; + string str; + object obj = NHibernateUtil.String.NullSafeGet(rs, names[0]); + if (obj != null) + { + str = obj.ToString(); + } + else + { + str = null; + } + string str1 = str; + if (!int.TryParse(str1, out num) && !string.IsNullOrWhiteSpace(str1)) + { + throw new Exception(); + } + return num; + } + + public void NullSafeSet(DbCommand cmd, object value, int index, ISessionImplementor session) + { + IDataParameter item = cmd.Parameters[index]; + if (value == null) + { + item.Value = DBNull.Value; + return; + } + item.Value = (int)value; + } + + public void NullSafeSet(IDbCommand cmd, object value, int index) + { + IDataParameter item = cmd.Parameters[index] as IDataParameter; + if (value == null) + { + item.Value = DBNull.Value; + return; + } + item.Value = (int)value; + } + + public object Replace(object original, object target, object owner) + { + return original; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.UnitOfWork.Generic/GenericUnitOfWork.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.UnitOfWork.Generic/GenericUnitOfWork.cs new file mode 100644 index 0000000..0e0998f --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.UnitOfWork.Generic/GenericUnitOfWork.cs @@ -0,0 +1,148 @@ +using Gestor.Infrastructure.Configuration; +using Gestor.Infrastructure.Repository.Generic; +using NHibernate; +using NHibernate.Linq; +using System; +using System.Data; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Gestor.Infrastructure.UnitOfWork.Generic +{ + public class GenericUnitOfWork : IDisposable, IGenericUnitOfWork + { + public bool HasSession + { + get + { + return this.Session != null; + } + } + + public ISession Session + { + get; + } + + private ITransaction Transaction + { + get; + } + + protected GenericUnitOfWork(string connectionString, bool withTransaction = true) + { + bool state; + ITransaction transaction; + int num = 0; + while (true) + { + if (num < 3) + { + try + { + this.Session = SessionFactory.OpenSession(connectionString); + if (withTransaction) + { + ISession session = this.Session; + if (session != null) + { + transaction = session.BeginTransaction(IsolationLevel.ReadUncommitted); + } + else + { + transaction = null; + } + this.Transaction = transaction; + } + else if (this.Session != null) + { + ISession session1 = this.Session; + if (session1 != null) + { + state = session1.Connection.State != ConnectionState.Open; + } + else + { + state = true; + } + if (state) + { + this.Session.Connection.Open(); + } + } + break; + } + catch (ArgumentNullException argumentNullException) + { + throw; + } + catch (Exception exception) + { + if (SessionFactory.Retry) + { + Thread.Sleep(1000); + } + else + { + this.Session = null; + break; + } + } + num++; + } + else + { + this.Session = null; + break; + } + } + } + + public void Commit() + { + if (this.Transaction != null && this.Transaction.IsActive) + { + this.Transaction.Commit(); + } + } + + public void Dispose() + { + ISession session = this.Session; + if (session != null) + { + session.Dispose(); + } + else + { + } + ITransaction transaction = this.Transaction; + if (transaction == null) + { + return; + } + transaction.Dispose(); + } + + public IQueryable<TEntity> Query<TEntity>() + where TEntity : class + { + return this.Session.Query<TEntity>(); + } + + public IGenericRepository<TEntity> Repository<TEntity>() + where TEntity : class + { + return new GenericRepository<TEntity>(this.Session); + } + + public void Rollback() + { + if (this.Transaction != null && this.Transaction.IsActive) + { + this.Transaction.Rollback(); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.UnitOfWork.Generic/IGenericUnitOfWork.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.UnitOfWork.Generic/IGenericUnitOfWork.cs new file mode 100644 index 0000000..a131045 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.UnitOfWork.Generic/IGenericUnitOfWork.cs @@ -0,0 +1,19 @@ +using Gestor.Infrastructure.Repository.Generic; +using System; +using System.Linq; + +namespace Gestor.Infrastructure.UnitOfWork.Generic +{ + public interface IGenericUnitOfWork + { + void Commit(); + + IQueryable<TEntity> Query<TEntity>() + where TEntity : class; + + IGenericRepository<TEntity> Repository<TEntity>() + where TEntity : class; + + void Rollback(); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.UnitOfWork.Interface/IUnitOfWork.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.UnitOfWork.Interface/IUnitOfWork.cs new file mode 100644 index 0000000..27fa13c --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.UnitOfWork.Interface/IUnitOfWork.cs @@ -0,0 +1,343 @@ +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.UnitOfWork.Generic; + +namespace Gestor.Infrastructure.UnitOfWork.Interface +{ + public interface IUnitOfWork : IGenericUnitOfWork + { + IAeronauticoRepository AeronauticoRepository + { + get; + } + + IAtividadeRepository AtividadeRepository + { + get; + } + + IAtualizacaoRepository AtualizacaoRepository + { + get; + } + + IAutoRepository AutoRepository + { + get; + } + + IBancoRepository BancoRepository + { + get; + } + + IBancosContasRepository BancosContasRepository + { + get; + } + + ICategoriaTarefaRepository CategoriaTarefaRepository + { + get; + } + + ICentroRepository CentroRepository + { + get; + } + + IClienteEmailRepository ClienteEmailRepository + { + get; + } + + IClienteEnderecoRepository ClienteEnderecoRepository + { + get; + } + + IClienteRepository ClienteRepository + { + get; + } + + IClienteTelefoneRepository ClienteTelefoneRepository + { + get; + } + + ICoberturaGranizoRepository CoberturaGranizoRepository + { + get; + } + + ICoberturaPadraoRepository CoberturaPadraoRepository + { + get; + } + + ICoberturaRepository CoberturaRepository + { + get; + } + + ICondicaoRepasseRepository CondicaoRepasseRepository + { + get; + } + + IConfigExtratoImportRepository ConfigExtratoImportRepository + { + get; + } + + IConfiguracaoRepository ConfiguracaoRepository + { + get; + } + + IControleFinanceiroRepository ControleFinanceiroRepository + { + get; + } + + IControleRepository ControleRepository + { + get; + } + + IControleSinistroRepository ControleSinistroRepository + { + get; + } + + ICredencialRepository CredencialRepository + { + get; + } + + ICriticaApoliceRepository CriticaApoliceRepository + { + get; + } + + IDetalheExtratoRepository DetalheExtratoRepository + { + get; + } + + IDocumentoRepository DocumentoRepository + { + get; + } + + IEmpresaRepository EmpresaRepository + { + get; + } + + IEstipulanteRepository EstipulanteRepository + { + get; + } + + IExtratoRepository ExtratoRepository + { + get; + } + + IFabricanteRepository FabricanteRepository + { + get; + } + + IFornecedorRepository FornecedorRepository + { + get; + } + + IGranizoRepository GranizoRepository + { + get; + } + + IImpostoRepository ImpostoRepository + { + get; + } + + IIndiceArquivoDigitalRepository IndiceArquivoDigitalRepository + { + get; + } + + IItemRepository ItemRepository + { + get; + } + + ILancamentoRepository LancamentoRepository + { + get; + } + + IMaisContatoRepository MaisContatoRepository + { + get; + } + + IMetaSeguradoraRepository MetaSeguradoraRepository + { + get; + } + + IMetaVendedorRepository MetaVendedorRepository + { + get; + } + + IModeloMalaDiretaRepository ModeloMalaDiretaRepository + { + get; + } + + INotaFiscalRepository NotaFiscalRepository + { + get; + } + + IParceiroRepository ParceiroRepository + { + get; + } + + IParcelaRepository ParcelaRepository + { + get; + } + + IPatrimonialRepository PatrimonialRepository + { + get; + } + + IPlanoRepository PlanoRepository + { + get; + } + + IProdutoRepository ProdutoRepository + { + get; + } + + IProfissaoRepository ProfissaoRepository + { + get; + } + + IProspectRepository ProspectRepository + { + get; + } + + IQualificacaoRepository QualificacaoRepository + { + get; + } + + IRamoRepository RamoRepository + { + get; + } + + IRegistroAcaoRepository RegistroAcaoRepository + { + get; + } + + IRegistroLogRepository RegistroLogRepository + { + get; + } + + IRepasseRepository RepasseRepository + { + get; + } + + IReportRepository ReportRepository + { + get; + } + + IRiscosDiversosRepository RiscosDiversosRepository + { + get; + } + + ISaldoRepository SaldoRepository + { + get; + } + + ISeguradoraContatoRepository SeguradoraContatoRepository + { + get; + } + + ISeguradoraEnderecoRepository SeguradoraEnderecoRepository + { + get; + } + + ISeguradoraRepository SeguradoraRepository + { + get; + } + + ISinistroAutoRepository SinistroAutoRepository + { + get; + } + + ISinistroRepository SinistroRepository + { + get; + } + + ISinistroVidaRepository SinistroVidaRepository + { + get; + } + + ITarefaRepository TarefaRepository + { + get; + } + + ITipoTarefaRepository TipoTarefaRepository + { + get; + } + + ITipoVendedorRepository TipoVendedorRepository + { + get; + } + + IVendedorParcelaRepository VendedorParcelaRepository + { + get; + } + + IVendedorRepository VendedorRepository + { + get; + } + + IVinculoDocumentoRepository VinculoDocumentoRepository + { + get; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.UnitOfWork.Logic/UnitOfWork.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.UnitOfWork.Logic/UnitOfWork.cs new file mode 100644 index 0000000..7f5bc9c --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.UnitOfWork.Logic/UnitOfWork.cs @@ -0,0 +1,1069 @@ +using Gestor.Infrastructure.Helpers; +using Gestor.Infrastructure.Repository.Interface; +using Gestor.Infrastructure.Repository.Logic; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Interface; +using NHibernate; +using NHibernate.Connection; +using NHibernate.Impl; +using System; +using System.Data.SqlClient; + +namespace Gestor.Infrastructure.UnitOfWork.Logic +{ + public class UnitOfWork : GenericUnitOfWork, IUnitOfWork, IGenericUnitOfWork + { + private Gestor.Infrastructure.Repository.Logic.AtividadeRepository _atividadeRepository; + + private Gestor.Infrastructure.Repository.Logic.AutoRepository _autoRepository; + + private Gestor.Infrastructure.Repository.Logic.BancoRepository _bancoRepository; + + private Gestor.Infrastructure.Repository.Logic.ClienteEmailRepository _clienteEmailRepository; + + private Gestor.Infrastructure.Repository.Logic.ClienteEnderecoRepository _clienteEnderecoRepository; + + private Gestor.Infrastructure.Repository.Logic.ClienteRepository _clienteRepository; + + private Gestor.Infrastructure.Repository.Logic.ClienteVinculoRepository _clienteVinculoRepository; + + private Gestor.Infrastructure.Repository.Logic.ClienteTelefoneRepository _clienteTelefoneRepository; + + private Gestor.Infrastructure.Repository.Logic.CondicaoRepasseRepository _condicaoRepasseRepository; + + private Gestor.Infrastructure.Repository.Logic.ControleRepository _controleRepository; + + private Gestor.Infrastructure.Repository.Logic.ControleSinistroRepository _controleSinistroRepository; + + private Gestor.Infrastructure.Repository.Logic.DocumentoRepository _documentoRepository; + + private Gestor.Infrastructure.Repository.Logic.EmpresaRepository _empresaRepository; + + private Gestor.Infrastructure.Repository.Logic.EstipulanteRepository _estipulanteRepository; + + private Gestor.Infrastructure.Repository.Logic.ItemRepository _itemRepository; + + private Gestor.Infrastructure.Repository.Logic.MaisContatoRepository _maisContatoRepository; + + private Gestor.Infrastructure.Repository.Logic.ParcelaRepository _parcelaRepository; + + private Gestor.Infrastructure.Repository.Logic.ProdutoRepository _produtoRepository; + + private Gestor.Infrastructure.Repository.Logic.StatusRepository _statusRepository; + + private Gestor.Infrastructure.Repository.Logic.ProfissaoRepository _profissaoRepository; + + private Gestor.Infrastructure.Repository.Logic.RamoRepository _ramoRepository; + + private Gestor.Infrastructure.Repository.Logic.QualificacaoRepository _qualificacaoRepository; + + private Gestor.Infrastructure.Repository.Logic.RepasseRepository _repasseRepository; + + private Gestor.Infrastructure.Repository.Logic.SeguradoraRepository _seguradoraRepository; + + private Gestor.Infrastructure.Repository.Logic.SinistroRepository _sinistroRepository; + + private Gestor.Infrastructure.Repository.Logic.SinistroAutoRepository _sinistroAutoRepository; + + private Gestor.Infrastructure.Repository.Logic.SinistroVidaRepository _sinistroVidaRepository; + + private Gestor.Infrastructure.Repository.Logic.ParceiroRepository _parceiroRepository; + + private Gestor.Infrastructure.Repository.Logic.TipoVendedorRepository _tipoVendedorRepository; + + private Gestor.Infrastructure.Repository.Logic.UsuarioRepository _usuarioRepository; + + private Gestor.Infrastructure.Repository.Logic.VendedorParcelaRepository _vendedorParcelaRepository; + + private Gestor.Infrastructure.Repository.Logic.VendedorRepository _vendedorRepository; + + private Gestor.Infrastructure.Repository.Logic.VendedorTelefoneRepository _vendedorTelefoneRepository; + + private Gestor.Infrastructure.Repository.Logic.CoberturaPadraoRepository _coberturaPadraoRepository; + + private Gestor.Infrastructure.Repository.Logic.CoberturaRepository _coberturaRepository; + + private Gestor.Infrastructure.Repository.Logic.FabricanteRepository _fabricanteRepository; + + private Gestor.Infrastructure.Repository.Logic.PatrimonialRepository _patrimonialRepository; + + private Gestor.Infrastructure.Repository.Logic.VidaRepository _vidaRepository; + + private Gestor.Infrastructure.Repository.Logic.TitularesVidaRepository _titularesVidaRepository; + + private Gestor.Infrastructure.Repository.Logic.RiscosDiversosRepository _riscosDiversosRepository; + + private Gestor.Infrastructure.Repository.Logic.SeguradoraContatoRepository _seguradoraContatoRepository; + + private Gestor.Infrastructure.Repository.Logic.SeguradoraEnderecoRepository _seguradoraEnderecoRepository; + + private Gestor.Infrastructure.Repository.Logic.AeronauticoRepository _aeronauticoRepository; + + private Gestor.Infrastructure.Repository.Logic.GranizoRepository _granizoRepository; + + private Gestor.Infrastructure.Repository.Logic.CoberturaGranizoRepository _coberturaGranizoRepository; + + private Gestor.Infrastructure.Repository.Logic.ExtratoRepository _extratoRepository; + + private Gestor.Infrastructure.Repository.Logic.DetalheExtratoRepository _detalheExtratoRepository; + + private Gestor.Infrastructure.Repository.Logic.IndiceArquivoDigitalRepository _indiceArquivoDigitalRepository; + + private Gestor.Infrastructure.Repository.Logic.CriticaApoliceRepository _criticaApoliceRepository; + + private Gestor.Infrastructure.Repository.Logic.CredencialRepository _credencialRepository; + + private Gestor.Infrastructure.Repository.Logic.TarefaRepository _tarefaRepository; + + private Gestor.Infrastructure.Repository.Logic.VendedorUsuarioRepository _vendedorUsuarioRepository; + + private Gestor.Infrastructure.Repository.Logic.RegistroLogRepository _registroLogRepository; + + private Gestor.Infrastructure.Repository.Logic.CentroRepository _centroRepository; + + private Gestor.Infrastructure.Repository.Logic.PlanoRepository _planoRepository; + + private Gestor.Infrastructure.Repository.Logic.BancosContasRepository _bancosContasRepository; + + private Gestor.Infrastructure.Repository.Logic.PlanosRepository _planosRepository; + + private Gestor.Infrastructure.Repository.Logic.FornecedorRepository _fornecedorRepository; + + private Gestor.Infrastructure.Repository.Logic.ControleFinanceiroRepository _controleFinanceiroRepository; + + private Gestor.Infrastructure.Repository.Logic.LancamentoRepository _lancamentoRepository; + + private Gestor.Infrastructure.Repository.Logic.SaldoRepository _saldoRepository; + + private Gestor.Infrastructure.Repository.Logic.MetaVendedorRepository _metaVendedorRepository; + + private Gestor.Infrastructure.Repository.Logic.MetaSeguradoraRepository _metaSeguradoraRepository; + + private Gestor.Infrastructure.Repository.Logic.TipoContaRepository _tipoContaRepository; + + private Gestor.Infrastructure.Repository.Logic.PermissaoUsuarioRepository _permissaoUsuarioRepository; + + private Gestor.Infrastructure.Repository.Logic.PermissaoArquivoDigitalRepository _permissaoArquivoDigitalRepository; + + private Gestor.Infrastructure.Repository.Logic.RestricaoUsuarioRepository _restricaoUsuarioRepository; + + private Gestor.Infrastructure.Repository.Logic.RestricaoUsuarioCamposRelatoriosRepository _restricaoUsuarioCamposRelatoriosRepository; + + private Gestor.Infrastructure.Repository.Logic.PerfilRepository _perfilRepository; + + private Gestor.Infrastructure.Repository.Logic.ConfigExtratoImportRepository _configExtratoImportRepository; + + private Gestor.Infrastructure.Repository.Logic.ProspectRepository _prospectRepository; + + private Gestor.Infrastructure.Repository.Logic.AgendaRepository _agendaRepository; + + private Gestor.Infrastructure.Repository.Logic.AgendaTelefoneRepository _agendaTelefoneRepository; + + private Gestor.Infrastructure.Repository.Logic.AgendaEmailRepository _agendaEmailRepository; + + private Gestor.Infrastructure.Repository.Logic.ParametrosRelatorioRepository _parametrosRelatorioRepository; + + private Gestor.Infrastructure.Repository.Logic.ParametrosTotalizacaoRepository _parametrosTotalizacaoRepository; + + private Gestor.Infrastructure.Repository.Logic.AdiantamentoRepository _adiantamentoRepository; + + private Gestor.Infrastructure.Repository.Logic.ModeloMalaDiretaRepository _modeloMalaDiretaRepository; + + private Gestor.Infrastructure.Repository.Logic.CategoriaTarefaRepository _categoriaTarefaRepository; + + private Gestor.Infrastructure.Repository.Logic.AtualizacaoRepository _atualizacaoRepository; + + private Gestor.Infrastructure.Repository.Logic.SocioRepository _socioRepository; + + private Gestor.Infrastructure.Repository.Logic.ReciboRepository _reciboRepository; + + private Gestor.Infrastructure.Repository.Logic.ExpedicaoRepository _expedicaoRepository; + + private Gestor.Infrastructure.Repository.Logic.VinculoDocumentoRepository _vinculoDocumentoRepository; + + private Gestor.Infrastructure.Repository.Logic.ConfiguracaoRepository _configuracaoRepository; + + private Gestor.Infrastructure.Repository.Logic.TipoTarefaRepository _tipoTarefaRepository; + + private Gestor.Infrastructure.Repository.Logic.StatusProspeccaoRepository _statusProspeccaoRepository; + + private Gestor.Infrastructure.Repository.Logic.NotaFiscalRepository _notaFiscalRepository; + + private Gestor.Infrastructure.Repository.Logic.ImpostoRepository _impostoRepository; + + private Gestor.Infrastructure.Repository.Logic.RegistroAcaoRepository _registroAcaoRepository; + + private Gestor.Infrastructure.Repository.Logic.ReportRepository _reportRepository; + + private Gestor.Infrastructure.Repository.Logic.PerfilEmpresaRepository _perfilEmpresaRepository; + + private Gestor.Infrastructure.Repository.Logic.ConsorcioRepository _consorcioRepository; + + public IAdiantamentoRepository AdiantamentoRepository + { + get + { + return this._adiantamentoRepository; + } + } + + public IAeronauticoRepository AeronauticoRepository + { + get + { + return this._aeronauticoRepository; + } + } + + public IAgendaEmailRepository AgendaEmailRepository + { + get + { + return this._agendaEmailRepository; + } + } + + public IAgendaRepository AgendaRepository + { + get + { + return this._agendaRepository; + } + } + + public IAgendaTelefoneRepository AgendaTelefoneRepository + { + get + { + return this._agendaTelefoneRepository; + } + } + + public IAtividadeRepository AtividadeRepository + { + get + { + return this._atividadeRepository; + } + } + + public IAtualizacaoRepository AtualizacaoRepository + { + get + { + return this._atualizacaoRepository; + } + } + + public IAutoRepository AutoRepository + { + get + { + return this._autoRepository; + } + } + + public IBancoRepository BancoRepository + { + get + { + return this._bancoRepository; + } + } + + public IBancosContasRepository BancosContasRepository + { + get + { + return this._bancosContasRepository; + } + } + + public ICategoriaTarefaRepository CategoriaTarefaRepository + { + get + { + return this._categoriaTarefaRepository; + } + } + + public ICentroRepository CentroRepository + { + get + { + return this._centroRepository; + } + } + + public IClienteEmailRepository ClienteEmailRepository + { + get + { + return this._clienteEmailRepository; + } + } + + public IClienteEnderecoRepository ClienteEnderecoRepository + { + get + { + return this._clienteEnderecoRepository; + } + } + + public IClienteRepository ClienteRepository + { + get + { + return this._clienteRepository; + } + } + + public IClienteTelefoneRepository ClienteTelefoneRepository + { + get + { + return this._clienteTelefoneRepository; + } + } + + public IClienteVinculoRepository ClienteVinculoRepository + { + get + { + return this._clienteVinculoRepository; + } + } + + public ICoberturaGranizoRepository CoberturaGranizoRepository + { + get + { + return this._coberturaGranizoRepository; + } + } + + public ICoberturaPadraoRepository CoberturaPadraoRepository + { + get + { + return this._coberturaPadraoRepository; + } + } + + public ICoberturaRepository CoberturaRepository + { + get + { + return this._coberturaRepository; + } + } + + public ICondicaoRepasseRepository CondicaoRepasseRepository + { + get + { + return this._condicaoRepasseRepository; + } + } + + public IConfigExtratoImportRepository ConfigExtratoImportRepository + { + get + { + return this._configExtratoImportRepository; + } + } + + public IConfiguracaoRepository ConfiguracaoRepository + { + get + { + return this._configuracaoRepository; + } + } + + public IConsorcioRepository ConsorcioRepository + { + get + { + return this._consorcioRepository; + } + } + + public IControleFinanceiroRepository ControleFinanceiroRepository + { + get + { + return this._controleFinanceiroRepository; + } + } + + public IControleRepository ControleRepository + { + get + { + return this._controleRepository; + } + } + + public IControleSinistroRepository ControleSinistroRepository + { + get + { + return this._controleSinistroRepository; + } + } + + public ICredencialRepository CredencialRepository + { + get + { + return this._credencialRepository; + } + } + + public ICriticaApoliceRepository CriticaApoliceRepository + { + get + { + return this._criticaApoliceRepository; + } + } + + public IDetalheExtratoRepository DetalheExtratoRepository + { + get + { + return this._detalheExtratoRepository; + } + } + + public IDocumentoRepository DocumentoRepository + { + get + { + return this._documentoRepository; + } + } + + public IEmpresaRepository EmpresaRepository + { + get + { + return this._empresaRepository; + } + } + + public IEstipulanteRepository EstipulanteRepository + { + get + { + return this._estipulanteRepository; + } + } + + public IExpedicaoRepository ExpedicaoRepository + { + get + { + return this._expedicaoRepository; + } + } + + public IExtratoRepository ExtratoRepository + { + get + { + return this._extratoRepository; + } + } + + public IFabricanteRepository FabricanteRepository + { + get + { + return this._fabricanteRepository; + } + } + + public IFornecedorRepository FornecedorRepository + { + get + { + return this._fornecedorRepository; + } + } + + public IGranizoRepository GranizoRepository + { + get + { + return this._granizoRepository; + } + } + + public IImpostoRepository ImpostoRepository + { + get + { + return this._impostoRepository; + } + } + + public IIndiceArquivoDigitalRepository IndiceArquivoDigitalRepository + { + get + { + return this._indiceArquivoDigitalRepository; + } + } + + public IItemRepository ItemRepository + { + get + { + return this._itemRepository; + } + } + + public ILancamentoRepository LancamentoRepository + { + get + { + return this._lancamentoRepository; + } + } + + public IMaisContatoRepository MaisContatoRepository + { + get + { + return this._maisContatoRepository; + } + } + + public IMetaSeguradoraRepository MetaSeguradoraRepository + { + get + { + return this._metaSeguradoraRepository; + } + } + + public IMetaVendedorRepository MetaVendedorRepository + { + get + { + return this._metaVendedorRepository; + } + } + + public IModeloMalaDiretaRepository ModeloMalaDiretaRepository + { + get + { + return this._modeloMalaDiretaRepository; + } + } + + public INotaFiscalRepository NotaFiscalRepository + { + get + { + return this._notaFiscalRepository; + } + } + + public IParametrosRelatorioRepository ParametrosRelatorioRepository + { + get + { + return this._parametrosRelatorioRepository; + } + } + + public IParametrosTotalizacaoRepository ParametrosTotalizacaoRepository + { + get + { + return this._parametrosTotalizacaoRepository; + } + } + + public IParceiroRepository ParceiroRepository + { + get + { + return this._parceiroRepository; + } + } + + public IParcelaRepository ParcelaRepository + { + get + { + return this._parcelaRepository; + } + } + + public IPatrimonialRepository PatrimonialRepository + { + get + { + return this._patrimonialRepository; + } + } + + public IPerfilEmpresaRepository PerfilEmpresaRepository + { + get + { + return this._perfilEmpresaRepository; + } + } + + public IPerfilRepository PerfilRepository + { + get + { + return this._perfilRepository; + } + } + + public IPermissaoArquivoDigitalRepository PermissaoArquivoDigitalRepository + { + get + { + return this._permissaoArquivoDigitalRepository; + } + } + + public IPermissaoUsuarioRepository PermissaoUsuarioRepository + { + get + { + return this._permissaoUsuarioRepository; + } + } + + public IPlanoRepository PlanoRepository + { + get + { + return this._planoRepository; + } + } + + public IPlanosRepository PlanosRepository + { + get + { + return this._planosRepository; + } + } + + public IProdutoRepository ProdutoRepository + { + get + { + return this._produtoRepository; + } + } + + public IProfissaoRepository ProfissaoRepository + { + get + { + return this._profissaoRepository; + } + } + + public IProspectRepository ProspectRepository + { + get + { + return this._prospectRepository; + } + } + + public IQualificacaoRepository QualificacaoRepository + { + get + { + return this._qualificacaoRepository; + } + } + + public IRamoRepository RamoRepository + { + get + { + return this._ramoRepository; + } + } + + public IReciboRepository ReciboRepository + { + get + { + return this._reciboRepository; + } + } + + public IRegistroAcaoRepository RegistroAcaoRepository + { + get + { + return this._registroAcaoRepository; + } + } + + public IRegistroLogRepository RegistroLogRepository + { + get + { + return this._registroLogRepository; + } + } + + public IRepasseRepository RepasseRepository + { + get + { + return this._repasseRepository; + } + } + + public IReportRepository ReportRepository + { + get + { + return this._reportRepository; + } + } + + public IRestricaoUsuarioCamposRelatoriosRepository RestricaoUsuarioCamposRelatoriosRepository + { + get + { + return this._restricaoUsuarioCamposRelatoriosRepository; + } + } + + public IRestricaoUsuarioRepository RestricaoUsuarioRepository + { + get + { + return this._restricaoUsuarioRepository; + } + } + + public IRiscosDiversosRepository RiscosDiversosRepository + { + get + { + return this._riscosDiversosRepository; + } + } + + public ISaldoRepository SaldoRepository + { + get + { + return this._saldoRepository; + } + } + + public ISeguradoraContatoRepository SeguradoraContatoRepository + { + get + { + return this._seguradoraContatoRepository; + } + } + + public ISeguradoraEnderecoRepository SeguradoraEnderecoRepository + { + get + { + return this._seguradoraEnderecoRepository; + } + } + + public ISeguradoraRepository SeguradoraRepository + { + get + { + return this._seguradoraRepository; + } + } + + public ISinistroAutoRepository SinistroAutoRepository + { + get + { + return this._sinistroAutoRepository; + } + } + + public ISinistroRepository SinistroRepository + { + get + { + return this._sinistroRepository; + } + } + + public ISinistroVidaRepository SinistroVidaRepository + { + get + { + return this._sinistroVidaRepository; + } + } + + public ISocioRepository SocioRepository + { + get + { + return this._socioRepository; + } + } + + public IStatusProspeccaoRepository StatusProspeccaoRepository + { + get + { + return this._statusProspeccaoRepository; + } + } + + public IStatusRepository StatusRepository + { + get + { + return this._statusRepository; + } + } + + public ITarefaRepository TarefaRepository + { + get + { + return this._tarefaRepository; + } + } + + public ITipoContaRepository TipoContaRepository + { + get + { + return this._tipoContaRepository; + } + } + + public ITipoTarefaRepository TipoTarefaRepository + { + get + { + return this._tipoTarefaRepository; + } + } + + public ITipoVendedorRepository TipoVendedorRepository + { + get + { + return this._tipoVendedorRepository; + } + } + + public ITitularesVidaRepository TitularesVidaRepository + { + get + { + return this._titularesVidaRepository; + } + } + + public IUsuarioRepository UsuarioRepository + { + get + { + return this._usuarioRepository; + } + } + + public IVendedorParcelaRepository VendedorParcelaRepository + { + get + { + return this._vendedorParcelaRepository; + } + } + + public IVendedorRepository VendedorRepository + { + get + { + return this._vendedorRepository; + } + } + + public IVendedorTelefoneRepository VendedorTelefoneRepository + { + get + { + return this._vendedorTelefoneRepository; + } + } + + public IVendedorUsuarioRepository VendedorUsuarioRepository + { + get + { + return this._vendedorUsuarioRepository; + } + } + + public IVidaRepository VidaRepository + { + get + { + return this._vidaRepository; + } + } + + public IVinculoDocumentoRepository VinculoDocumentoRepository + { + get + { + return this._vinculoDocumentoRepository; + } + } + + public UnitOfWork(string connectionString, bool withTransaction = true) : base(connectionString, true) + { + this.SetRepositories(); + } + + public void CriarAuxiliar(bool force = false) + { + object connection; + SessionFactoryImpl sessionFactory = base.Session.SessionFactory as SessionFactoryImpl; + if (sessionFactory != null) + { + connection = sessionFactory.ConnectionProvider.GetConnection(); + } + else + { + connection = null; + } + using (SqlConnection sqlConnection = connection as SqlConnection) + { + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + Auxiliar.CriarAuxiliar(sqlCommand, force); + } + } + } + + private void SetRepositories() + { + this._atividadeRepository = new Gestor.Infrastructure.Repository.Logic.AtividadeRepository(this); + this._autoRepository = new Gestor.Infrastructure.Repository.Logic.AutoRepository(this); + this._bancoRepository = new Gestor.Infrastructure.Repository.Logic.BancoRepository(this); + this._clienteEmailRepository = new Gestor.Infrastructure.Repository.Logic.ClienteEmailRepository(this); + this._clienteEnderecoRepository = new Gestor.Infrastructure.Repository.Logic.ClienteEnderecoRepository(this); + this._clienteRepository = new Gestor.Infrastructure.Repository.Logic.ClienteRepository(this); + this._clienteTelefoneRepository = new Gestor.Infrastructure.Repository.Logic.ClienteTelefoneRepository(this); + this._clienteVinculoRepository = new Gestor.Infrastructure.Repository.Logic.ClienteVinculoRepository(this); + this._condicaoRepasseRepository = new Gestor.Infrastructure.Repository.Logic.CondicaoRepasseRepository(this); + this._controleRepository = new Gestor.Infrastructure.Repository.Logic.ControleRepository(this); + this._controleSinistroRepository = new Gestor.Infrastructure.Repository.Logic.ControleSinistroRepository(this); + this._documentoRepository = new Gestor.Infrastructure.Repository.Logic.DocumentoRepository(this); + this._empresaRepository = new Gestor.Infrastructure.Repository.Logic.EmpresaRepository(this); + this._estipulanteRepository = new Gestor.Infrastructure.Repository.Logic.EstipulanteRepository(this); + this._itemRepository = new Gestor.Infrastructure.Repository.Logic.ItemRepository(this); + this._maisContatoRepository = new Gestor.Infrastructure.Repository.Logic.MaisContatoRepository(this); + this._parcelaRepository = new Gestor.Infrastructure.Repository.Logic.ParcelaRepository(this); + this._produtoRepository = new Gestor.Infrastructure.Repository.Logic.ProdutoRepository(this); + this._statusRepository = new Gestor.Infrastructure.Repository.Logic.StatusRepository(this); + this._profissaoRepository = new Gestor.Infrastructure.Repository.Logic.ProfissaoRepository(this); + this._ramoRepository = new Gestor.Infrastructure.Repository.Logic.RamoRepository(this); + this._qualificacaoRepository = new Gestor.Infrastructure.Repository.Logic.QualificacaoRepository(this); + this._repasseRepository = new Gestor.Infrastructure.Repository.Logic.RepasseRepository(this); + this._seguradoraRepository = new Gestor.Infrastructure.Repository.Logic.SeguradoraRepository(this); + this._sinistroRepository = new Gestor.Infrastructure.Repository.Logic.SinistroRepository(this); + this._sinistroAutoRepository = new Gestor.Infrastructure.Repository.Logic.SinistroAutoRepository(this); + this._sinistroVidaRepository = new Gestor.Infrastructure.Repository.Logic.SinistroVidaRepository(this); + this._parceiroRepository = new Gestor.Infrastructure.Repository.Logic.ParceiroRepository(this); + this._tipoVendedorRepository = new Gestor.Infrastructure.Repository.Logic.TipoVendedorRepository(this); + this._usuarioRepository = new Gestor.Infrastructure.Repository.Logic.UsuarioRepository(this); + this._vendedorParcelaRepository = new Gestor.Infrastructure.Repository.Logic.VendedorParcelaRepository(this); + this._vendedorRepository = new Gestor.Infrastructure.Repository.Logic.VendedorRepository(this); + this._vendedorTelefoneRepository = new Gestor.Infrastructure.Repository.Logic.VendedorTelefoneRepository(this); + this._coberturaPadraoRepository = new Gestor.Infrastructure.Repository.Logic.CoberturaPadraoRepository(this); + this._coberturaRepository = new Gestor.Infrastructure.Repository.Logic.CoberturaRepository(this); + this._fabricanteRepository = new Gestor.Infrastructure.Repository.Logic.FabricanteRepository(this); + this._patrimonialRepository = new Gestor.Infrastructure.Repository.Logic.PatrimonialRepository(this); + this._vidaRepository = new Gestor.Infrastructure.Repository.Logic.VidaRepository(this); + this._titularesVidaRepository = new Gestor.Infrastructure.Repository.Logic.TitularesVidaRepository(this); + this._riscosDiversosRepository = new Gestor.Infrastructure.Repository.Logic.RiscosDiversosRepository(this); + this._seguradoraContatoRepository = new Gestor.Infrastructure.Repository.Logic.SeguradoraContatoRepository(this); + this._seguradoraEnderecoRepository = new Gestor.Infrastructure.Repository.Logic.SeguradoraEnderecoRepository(this); + this._aeronauticoRepository = new Gestor.Infrastructure.Repository.Logic.AeronauticoRepository(this); + this._granizoRepository = new Gestor.Infrastructure.Repository.Logic.GranizoRepository(this); + this._coberturaGranizoRepository = new Gestor.Infrastructure.Repository.Logic.CoberturaGranizoRepository(this); + this._extratoRepository = new Gestor.Infrastructure.Repository.Logic.ExtratoRepository(this); + this._detalheExtratoRepository = new Gestor.Infrastructure.Repository.Logic.DetalheExtratoRepository(this); + this._indiceArquivoDigitalRepository = new Gestor.Infrastructure.Repository.Logic.IndiceArquivoDigitalRepository(this); + this._criticaApoliceRepository = new Gestor.Infrastructure.Repository.Logic.CriticaApoliceRepository(this); + this._credencialRepository = new Gestor.Infrastructure.Repository.Logic.CredencialRepository(this); + this._tarefaRepository = new Gestor.Infrastructure.Repository.Logic.TarefaRepository(this); + this._vendedorUsuarioRepository = new Gestor.Infrastructure.Repository.Logic.VendedorUsuarioRepository(this); + this._registroLogRepository = new Gestor.Infrastructure.Repository.Logic.RegistroLogRepository(this); + this._centroRepository = new Gestor.Infrastructure.Repository.Logic.CentroRepository(this); + this._planoRepository = new Gestor.Infrastructure.Repository.Logic.PlanoRepository(this); + this._bancosContasRepository = new Gestor.Infrastructure.Repository.Logic.BancosContasRepository(this); + this._planosRepository = new Gestor.Infrastructure.Repository.Logic.PlanosRepository(this); + this._fornecedorRepository = new Gestor.Infrastructure.Repository.Logic.FornecedorRepository(this); + this._controleFinanceiroRepository = new Gestor.Infrastructure.Repository.Logic.ControleFinanceiroRepository(this); + this._lancamentoRepository = new Gestor.Infrastructure.Repository.Logic.LancamentoRepository(this); + this._saldoRepository = new Gestor.Infrastructure.Repository.Logic.SaldoRepository(this); + this._metaVendedorRepository = new Gestor.Infrastructure.Repository.Logic.MetaVendedorRepository(this); + this._metaSeguradoraRepository = new Gestor.Infrastructure.Repository.Logic.MetaSeguradoraRepository(this); + this._tipoContaRepository = new Gestor.Infrastructure.Repository.Logic.TipoContaRepository(this); + this._permissaoUsuarioRepository = new Gestor.Infrastructure.Repository.Logic.PermissaoUsuarioRepository(this); + this._permissaoArquivoDigitalRepository = new Gestor.Infrastructure.Repository.Logic.PermissaoArquivoDigitalRepository(this); + this._restricaoUsuarioRepository = new Gestor.Infrastructure.Repository.Logic.RestricaoUsuarioRepository(this); + this._restricaoUsuarioCamposRelatoriosRepository = new Gestor.Infrastructure.Repository.Logic.RestricaoUsuarioCamposRelatoriosRepository(this); + this._perfilRepository = new Gestor.Infrastructure.Repository.Logic.PerfilRepository(this); + this._configExtratoImportRepository = new Gestor.Infrastructure.Repository.Logic.ConfigExtratoImportRepository(this); + this._prospectRepository = new Gestor.Infrastructure.Repository.Logic.ProspectRepository(this); + this._agendaRepository = new Gestor.Infrastructure.Repository.Logic.AgendaRepository(this); + this._agendaTelefoneRepository = new Gestor.Infrastructure.Repository.Logic.AgendaTelefoneRepository(this); + this._agendaEmailRepository = new Gestor.Infrastructure.Repository.Logic.AgendaEmailRepository(this); + this._parametrosRelatorioRepository = new Gestor.Infrastructure.Repository.Logic.ParametrosRelatorioRepository(this); + this._parametrosTotalizacaoRepository = new Gestor.Infrastructure.Repository.Logic.ParametrosTotalizacaoRepository(this); + this._adiantamentoRepository = new Gestor.Infrastructure.Repository.Logic.AdiantamentoRepository(this); + this._modeloMalaDiretaRepository = new Gestor.Infrastructure.Repository.Logic.ModeloMalaDiretaRepository(this); + this._categoriaTarefaRepository = new Gestor.Infrastructure.Repository.Logic.CategoriaTarefaRepository(this); + this._atualizacaoRepository = new Gestor.Infrastructure.Repository.Logic.AtualizacaoRepository(this); + this._socioRepository = new Gestor.Infrastructure.Repository.Logic.SocioRepository(this); + this._reciboRepository = new Gestor.Infrastructure.Repository.Logic.ReciboRepository(this); + this._expedicaoRepository = new Gestor.Infrastructure.Repository.Logic.ExpedicaoRepository(this); + this._vinculoDocumentoRepository = new Gestor.Infrastructure.Repository.Logic.VinculoDocumentoRepository(this); + this._configuracaoRepository = new Gestor.Infrastructure.Repository.Logic.ConfiguracaoRepository(this); + this._tipoTarefaRepository = new Gestor.Infrastructure.Repository.Logic.TipoTarefaRepository(this); + this._statusProspeccaoRepository = new Gestor.Infrastructure.Repository.Logic.StatusProspeccaoRepository(this); + this._notaFiscalRepository = new Gestor.Infrastructure.Repository.Logic.NotaFiscalRepository(this); + this._impostoRepository = new Gestor.Infrastructure.Repository.Logic.ImpostoRepository(this); + this._registroAcaoRepository = new Gestor.Infrastructure.Repository.Logic.RegistroAcaoRepository(this); + this._reportRepository = new Gestor.Infrastructure.Repository.Logic.ReportRepository(this); + this._perfilEmpresaRepository = new Gestor.Infrastructure.Repository.Logic.PerfilEmpresaRepository(this); + this._consorcioRepository = new Gestor.Infrastructure.Repository.Logic.ConsorcioRepository(this); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.csproj b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.csproj new file mode 100644 index 0000000..8d665e4 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.csproj @@ -0,0 +1,1717 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup> + <ProjectGuid>{21360061-8C6F-4A8A-8E1B-2850369E55AA}</ProjectGuid> + <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> + <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> + <AssemblyName>Gestor.Infrastructure</AssemblyName> + <OutputType>Library</OutputType> + <TargetFrameworkVersion>v4.8</TargetFrameworkVersion> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> + <OutputPath>bin\Debug\</OutputPath> + <DebugSymbols>true</DebugSymbols> + <DefineConstants>DEBUG;TRACE</DefineConstants> + <Optimize>false</Optimize> + <WarningLevel>4</WarningLevel> + <DebugType>full</DebugType> + <ErrorReport>prompt</ErrorReport> + <PlatformTarget>AnyCPU</PlatformTarget> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> + <OutputPath>bin\Release\</OutputPath> + <DebugSymbols>false</DebugSymbols> + <DefineConstants>TRACE</DefineConstants> + <Optimize>true</Optimize> + <WarningLevel>4</WarningLevel> + <DebugType>pdbonly</DebugType> + <ErrorReport>prompt</ErrorReport> + <PlatformTarget>AnyCPU</PlatformTarget> + </PropertyGroup> + <ItemGroup> + <Reference Include="System.Data" /> + <Reference Include="NHibernate"> + <HintPath>.\Gestor.InfrastructureReferences\NHibernate.dll</HintPath> + </Reference> + <Reference Include="System.Core" /> + <Reference Include="Gestor.Model"> + <HintPath>.\Gestor.InfrastructureReferences\Gestor.Model.dll</HintPath> + </Reference> + <Reference Include="System.Data.DataSetExtensions" /> + <Reference Include="System" /> + <Reference Include="FluentNHibernate"> + <HintPath>.\Gestor.InfrastructureReferences\FluentNHibernate.dll</HintPath> + </Reference> + <Reference Include="AutoMapper"> + <HintPath>.\Gestor.InfrastructureReferences\AutoMapper.dll</HintPath> + </Reference> + <Reference Include="Gestor.Common"> + <HintPath>.\Gestor.InfrastructureReferences\Gestor.Common.dll</HintPath> + </Reference> + <Reference Include="Microsoft.CSharp" /> + <Reference Include="System.Xml" /> + </ItemGroup> + <ItemGroup> + <Compile Include="Properties\AssemblyInfo.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\PerfilCondominioDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IAtualizacaoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\ICategoriaTarefaRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IConfiguracaoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\CondicaoRepasseMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IExpedicaoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IClienteVinculoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IImpostoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\INotaFiscalRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\ConfigExtratoImportMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IParametrosTotalizacaoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IPerfilEmpresaRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IPermissaoArquivoDigitalRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IQualificacaoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\PerfilEmpresaDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IRegistroAcaoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IReportRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\PermissaoArquivoDigitalDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IRestricaoUsuarioCamposRelatoriosRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IConsorcioRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IStatusRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\ResponsavelAssinaturaDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\ControleMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IReciboRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IModeloMalaDiretaRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\RestricaoUsuarioCamposRelatoriosDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IParametrosRelatorioRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IAtividadeRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\ConsorcioDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IAgendaEmailRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\ControleSinistroMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IAgendaTelefoneRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IPerfilRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IAutoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IBancoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\TitularesVidaDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IBancosContasRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IControleFinanceiroRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IMetaSeguradoraRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IMetaVendedorRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\CriticaApoliceMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IConfigExtratoImportRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IProspectRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IRestricaoUsuarioRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IAgendaRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\ISocioRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\PerfilDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\ITipoContaRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IPlanosRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IFornecedorRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IPermissaoUsuarioRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IPlanoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\AeronauticoDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IClienteEnderecoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IClienteEmailRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\DetalheExtratoMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\ICentroRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IClienteRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IClienteTelefoneRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\ICoberturaGranizoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\ICoberturaPadraoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\ICoberturaRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\AutoDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\ICondicaoRepasseRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IControleRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IControleSinistroRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\ICredencialRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\ICriticaApoliceRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IDetalheExtratoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IDocumentoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\ClienteDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IEmpresaRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\ClienteEmailDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IEstipulanteRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\ClienteEnderecoDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IExtratoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IFabricanteRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\ClienteTelefoneDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IGranizoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IIndiceArquivoDigitalRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\CoberturaDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IItemRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.UnitOfWork.Logic\UnitOfWork.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IMaisContatoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IParceiroRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.UnitOfWork.Interface\IUnitOfWork.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IParcelaRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IRegistroLogRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\ISaldoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\ISinistroAutoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\ISinistroVidaRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\ITarefaRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IStatusProspeccaoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\ITipoTarefaRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\ITitularesVidaRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IVidaRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IPatrimonialRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IProdutoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IProfissaoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IRamoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IRepasseRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\DocumentoMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IRiscosDiversosRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\ISeguradoraContatoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\ISeguradoraEnderecoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\ISeguradoraRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\ISinistroRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\ITipoVendedorRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IUsuarioRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.UnitOfWork.Generic\GenericUnitOfWork.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IVendedorParcelaRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.UnitOfWork.Generic\IGenericUnitOfWork.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IVendedorRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IVendedorTelefoneRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\EstipulanteMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IVendedorUsuarioRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\ILancamentoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IVinculoDocumentoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\ExpedicaoMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Types\CustomEnumType2_T_.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Generic\GenericRepository_T_.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Generic\IGenericRepository_TEntity_.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\ExtratoMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Types\CustomIntType.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\FabricanteMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\AdiantamentoMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\FaturaMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Types\CustomEnumType_T_.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\AeronauticoMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Types\CustomBoolType.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\GranizoMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\ItemMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\AutoMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\ClienteEmailMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\PerfilEmpresaMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\PermissaoArquivoDigitalMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\ClienteEnderecoMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\ResponsavelAssinaturaMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\AdiantamentoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\RestricaoUsuarioCamposRelatoriosMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\RestricaoUsuarioMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\AeronauticoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\ConsorcioMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\AtualizacaoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\ClienteMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\CategoriaTarefaRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\TitularesVidaMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\ClienteTelefoneMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\ConfiguracaoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\ExpedicaoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\CoberturaGranizoMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\MaisContatoMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\CoberturaMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\CoberturaPadraoMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\MetaSeguradoraMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\ClienteVinculoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\MetaVendedorMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\ImpostoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\ProspeccaoMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\ParceiroMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\QualificacaoMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\RamoMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\NotaFiscalRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\ParametrosTotalizacaoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\RepasseMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\ParcelaMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\PerfilEmpresaRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\RiscosDiversosMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\PermissaoArquivoDigitalRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\SeguradoraContatoMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\QualificacaoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\PatrimonialMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\SeguradoraEnderecoMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\RegistroAcaoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\SeguradoraMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\PerfilMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\PermissaoUsuarioMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\SinistroAutoMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\ClienteVinculoMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\ProdutoMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\SinistroMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\VendedorParcelaMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\SinistroVidaMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\VendedorTelefoneMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\StatusMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\VendedorUsuarioMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\TipoContaMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\TipoVendedorMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\VidaMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Relatorios\ParametrosTotalizacaoMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Relatorios\ParametrosRelatorioMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Financeiro\BancosContasMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Financeiro\CentroMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Financeiro\ControleFinanceiroMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\UsuarioMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Financeiro\FornecedorMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Seguros\VendedorMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Financeiro\LancamentoMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Ferramentas\AgendaMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Financeiro\PlanoMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Ferramentas\AgendaTelefoneMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Financeiro\PlanosMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Ferramentas\CategoriaTarefaMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Financeiro\SaldoMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Financeiro\TipoContaMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Ferramentas\CredencialMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Ferramentas\AgendaEmailMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Ferramentas\FaseMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Configuracoes\ConfiguracaoSistemaMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Common\AtividadeMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Ferramentas\ImpostoMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Common\AtualizacaoMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Common\BancoMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Common\ControleArquivoDigitalMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Ferramentas\LogEmailMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Ferramentas\NotaFiscalMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Ferramentas\OrigemClienteMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Common\EmpresaMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Ferramentas\ReciboMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Ferramentas\ResponsavelTarefaMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Ferramentas\TarefaMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Common\IndiceArquivoDigitalMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Ferramentas\StatusProspeccaoMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Common\ModeloMalaDiretaMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Common\ProfissaoMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Ferramentas\TipoTarefaMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Ferramentas\TrilhaMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Common\RegistroAcaoMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Ferramentas\VinculoRepasseMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Common\RegistroLogMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Common\SocioMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappings.Aggilizador\VinculoDocumentoMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappers\ApplicationMapper.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\CoberturaGranizoDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\CoberturaPadraoDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\CondicaoRepasseDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Helpers\Auxiliar.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\ControleDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\ControleSinistroDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\CriticaApoliceDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\DetalheExtratoDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Helpers\AuxiliarFinanceiro.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Helpers\Comparador.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\DocumentoDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\EstipulanteDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\ExtratoDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\FabricanteDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\FaturaDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\GranizoDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\ItemDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Helpers\QueryableHelper.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\MaisContatoDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\MetaSeguradoraDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\MetaVendedorDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\ParceiroDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Helpers\SqlDataReaderHelper.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\AdiantamentoDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\ParcelaDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\ClienteVinculoDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\ExpedicaoDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\SeguradoraEnderecoDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\PatrimonialDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\PermissaoUsuarioDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\SinistroAutoDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\QualificacaoDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\StatusDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\ProdutoDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\ConfigExtratoImportDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\SinistroDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\SinistroVidaDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\TipoContaDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\TipoVendedorDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Mappers\CustomMap.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\ProspeccaoDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\UsuarioDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\RamoDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\VendedorDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\RepasseDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\RestricaoUsuarioDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\VendedorParcelaDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\VendedorTelefoneDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\VendedorUsuarioDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\RiscosDiversosDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\VidaDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\SeguradoraContatoDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Relatorios\ParametrosTotalizacaoDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Relatorios\ParametrosRelatorioDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Generic\EmailBase.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Seguros\SeguradoraDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Generic\EnderecoBase.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Generic\EntityBase.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Ferramentas\CategoriaTarefaDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Generic\TelefoneBase.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Ferramentas\CredencialDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Financeiro\BancosContasDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Ferramentas\FaseDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Financeiro\ControleFinanceiroDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Financeiro\FornecedorDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Ferramentas\LogEmailDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Ferramentas\ResponsavelTarefaDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Financeiro\LancamentoDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Ferramentas\TarefaDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Financeiro\PlanosDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Ferramentas\StatusDeProspeccaoDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Financeiro\PlanoDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Financeiro\CentroDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Ferramentas\TipoDeTarefaDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Financeiro\SaldoDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Ferramentas\TrilhaDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Ferramentas\AgendaEmailDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Ferramentas\VinculoRepasseDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Ferramentas\AgendaTelefoneDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Ferramentas\AgendaDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Configuracoes\ConfiguracaoSistemaDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Ferramentas\ImpostoDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Common\AtividadeDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Common\BancoDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Ferramentas\NotaFiscalDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Common\ControleArquivoDigitalDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Ferramentas\OrigemClienteDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Ferramentas\ReciboDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Common\EmpresaDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Common\IndiceArquivoDigitalDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Common\ModeloMalaDiretaDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Common\ProfissaoDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Configuration\ConfigurationFileCache.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Common\RegistroAcaoDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Common\RegistroLogDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Common\SocioDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Configuration\SessionFactory.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Common\AtualizacaoDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Entities.Aggilizador\VinculoDocumentoDb.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\AgendaTelefoneRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\LancamentoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\PermissaoUsuarioRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\PerfilRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\PlanoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Helpers\Funcoes.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\DetalheExtratoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\ClienteEmailRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\ClienteEnderecoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\CentroRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\AutoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\BancoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\BancosContasRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\ControleFinanceiroRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\MetaSeguradoraRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\MetaVendedorRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\ConfigExtratoImportRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\ProspectRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\RestricaoUsuarioRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\AgendaRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\SocioRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\TipoContaRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\PlanosRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\FornecedorRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\TarefaRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\StatusProspeccaoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\TipoTarefaRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\VendedorUsuarioRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\TitularesVidaRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\VidaRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\PatrimonialRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\ProdutoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\ProfissaoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\RamoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\RepasseRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\RiscosDiversosRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\SeguradoraContatoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\SeguradoraEnderecoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\SeguradoraRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\ClienteRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\SinistroRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\TipoVendedorRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\ClienteTelefoneRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\CoberturaGranizoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\CoberturaPadraoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\CoberturaRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\CondicaoRepasseRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\ControleRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\UsuarioRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\ControleSinistroRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\CredencialRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\VendedorParcelaRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\CriticaApoliceRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\VendedorRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\VendedorTelefoneRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\VinculoDocumentoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IAdiantamentoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Interface\IAeronauticoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\ReportRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\RestricaoUsuarioCamposRelatoriosRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\ConsorcioRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\StatusRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\DocumentoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\ReciboRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\ModeloMalaDiretaRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\ParametrosRelatorioRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\EmpresaRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\AtividadeRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\EstipulanteRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\AgendaEmailRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\ExtratoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\FabricanteRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\GranizoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\IndiceArquivoDigitalRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\ItemRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\MaisContatoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\ParceiroRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\ParcelaRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\RegistroLogRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\SaldoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\SinistroAutoRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Gestor.Infrastructure.Repository.Logic\SinistroVidaRepository.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + </ItemGroup> + <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> +</Project> \ No newline at end of file diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.sln b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.sln new file mode 100644 index 0000000..7244098 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.sln @@ -0,0 +1,21 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29728.190 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Gestor.Infrastructure", "Gestor.Infrastructure.csproj", "{21360061-8C6F-4A8A-8E1B-2850369E55AA}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {21360061-8C6F-4A8A-8E1B-2850369E55AA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {21360061-8C6F-4A8A-8E1B-2850369E55AA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {21360061-8C6F-4A8A-8E1B-2850369E55AA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {21360061-8C6F-4A8A-8E1B-2850369E55AA}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Codemerx/Gestor.Infrastructure/Gestor.InfrastructureReferences/AutoMapper.dll b/Codemerx/Gestor.Infrastructure/Gestor.InfrastructureReferences/AutoMapper.dll new file mode 100644 index 0000000..a1e2827 Binary files /dev/null and b/Codemerx/Gestor.Infrastructure/Gestor.InfrastructureReferences/AutoMapper.dll differ diff --git a/Codemerx/Gestor.Infrastructure/Gestor.InfrastructureReferences/FluentNHibernate.dll b/Codemerx/Gestor.Infrastructure/Gestor.InfrastructureReferences/FluentNHibernate.dll new file mode 100644 index 0000000..c8f03b9 Binary files /dev/null and b/Codemerx/Gestor.Infrastructure/Gestor.InfrastructureReferences/FluentNHibernate.dll differ diff --git a/Codemerx/Gestor.Infrastructure/Gestor.InfrastructureReferences/Gestor.Common.dll b/Codemerx/Gestor.Infrastructure/Gestor.InfrastructureReferences/Gestor.Common.dll new file mode 100644 index 0000000..87ccf4e Binary files /dev/null and b/Codemerx/Gestor.Infrastructure/Gestor.InfrastructureReferences/Gestor.Common.dll differ diff --git a/Codemerx/Gestor.Infrastructure/Gestor.InfrastructureReferences/Gestor.Model.dll b/Codemerx/Gestor.Infrastructure/Gestor.InfrastructureReferences/Gestor.Model.dll new file mode 100644 index 0000000..2b2b2d0 Binary files /dev/null and b/Codemerx/Gestor.Infrastructure/Gestor.InfrastructureReferences/Gestor.Model.dll differ diff --git a/Codemerx/Gestor.Infrastructure/Gestor.InfrastructureReferences/NHibernate.dll b/Codemerx/Gestor.Infrastructure/Gestor.InfrastructureReferences/NHibernate.dll new file mode 100644 index 0000000..d216963 Binary files /dev/null and b/Codemerx/Gestor.Infrastructure/Gestor.InfrastructureReferences/NHibernate.dll differ diff --git a/Codemerx/Gestor.Infrastructure/Properties/AssemblyInfo.cs b/Codemerx/Gestor.Infrastructure/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..d29679c --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/Properties/AssemblyInfo.cs @@ -0,0 +1,22 @@ +using System.Diagnostics; +using System.Reflection; +using System.Resources; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; + +[assembly: AssemblyCompany("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCopyright("Copyright © 2019")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyFileVersion("8.4.0.0")] +[assembly: AssemblyProduct("Gestor.Infrastructure")] +[assembly: AssemblyTitle("Gestor.Infrastructure")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyVersion("8.4.0.0")] +[assembly: CompilationRelaxations(8)] +[assembly: ComVisible(false)] +[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] +[assembly: Guid("9a0abf0e-b5c2-451f-a54c-3d0383a4b984")] +[assembly: NeutralResourcesLanguage("pt-BR", UltimateResourceFallbackLocation.MainAssembly)] +[assembly: RuntimeCompatibility(WrapNonExceptionThrows=true)] diff --git a/Codemerx/Gestor.Infrastructure/obj/Debug/.NETFramework,Version=v4.8.AssemblyAttributes.cs b/Codemerx/Gestor.Infrastructure/obj/Debug/.NETFramework,Version=v4.8.AssemblyAttributes.cs new file mode 100644 index 0000000..3cf0af3 --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/obj/Debug/.NETFramework,Version=v4.8.AssemblyAttributes.cs @@ -0,0 +1,4 @@ +// <autogenerated /> +using System; +using System.Reflection; +[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] diff --git a/Codemerx/Gestor.Infrastructure/obj/Debug/DesignTimeResolveAssemblyReferencesInput.cache b/Codemerx/Gestor.Infrastructure/obj/Debug/DesignTimeResolveAssemblyReferencesInput.cache new file mode 100644 index 0000000..baa7eff Binary files /dev/null and b/Codemerx/Gestor.Infrastructure/obj/Debug/DesignTimeResolveAssemblyReferencesInput.cache differ diff --git a/Codemerx/Gestor.Infrastructure/obj/Debug/Gestor.Infrastructure.csproj.AssemblyReference.cache b/Codemerx/Gestor.Infrastructure/obj/Debug/Gestor.Infrastructure.csproj.AssemblyReference.cache new file mode 100644 index 0000000..e5d4a02 Binary files /dev/null and b/Codemerx/Gestor.Infrastructure/obj/Debug/Gestor.Infrastructure.csproj.AssemblyReference.cache differ diff --git a/Codemerx/Gestor.Infrastructure/obj/Debug/Gestor.Infrastructure.csproj.CoreCompileInputs.cache b/Codemerx/Gestor.Infrastructure/obj/Debug/Gestor.Infrastructure.csproj.CoreCompileInputs.cache new file mode 100644 index 0000000..841e0bc --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/obj/Debug/Gestor.Infrastructure.csproj.CoreCompileInputs.cache @@ -0,0 +1 @@ +b264f6b68ca486f83aa9b21592553a9aa15b3d3f7754afe2934115d2d0f09bf4 diff --git a/Codemerx/Gestor.Infrastructure/obj/Debug/Gestor.Infrastructure.csproj.FileListAbsolute.txt b/Codemerx/Gestor.Infrastructure/obj/Debug/Gestor.Infrastructure.csproj.FileListAbsolute.txt new file mode 100644 index 0000000..1cb898d --- /dev/null +++ b/Codemerx/Gestor.Infrastructure/obj/Debug/Gestor.Infrastructure.csproj.FileListAbsolute.txt @@ -0,0 +1,2 @@ +C:\Users\Usuario\Downloads\CodemerxDecompile-windows-x64\Gestor\Gestor.Infra\obj\Debug\Gestor.Infrastructure.csproj.AssemblyReference.cache +C:\Users\Usuario\Downloads\CodemerxDecompile-windows-x64\Gestor\Gestor.Infra\obj\Debug\Gestor.Infrastructure.csproj.CoreCompileInputs.cache diff --git a/Codemerx/Gestor.Model/Gestor.Model.csproj b/Codemerx/Gestor.Model/Gestor.Model.csproj new file mode 100644 index 0000000..487f238 --- /dev/null +++ b/Codemerx/Gestor.Model/Gestor.Model.csproj @@ -0,0 +1,1644 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup> + <ProjectGuid>{38886FAE-B3AF-42BA-BAC3-9295A61CB2C5}</ProjectGuid> + <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> + <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> + <AssemblyName>Gestor.Model</AssemblyName> + <OutputType>Library</OutputType> + <RootNamespace>Gestor</RootNamespace> + <TargetFrameworkVersion>v4.8</TargetFrameworkVersion> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> + <OutputPath>bin\Debug\</OutputPath> + <DebugSymbols>true</DebugSymbols> + <DefineConstants>DEBUG;TRACE</DefineConstants> + <Optimize>false</Optimize> + <WarningLevel>4</WarningLevel> + <DebugType>full</DebugType> + <ErrorReport>prompt</ErrorReport> + <PlatformTarget>AnyCPU</PlatformTarget> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> + <OutputPath>bin\Release\</OutputPath> + <DebugSymbols>false</DebugSymbols> + <DefineConstants>TRACE</DefineConstants> + <Optimize>true</Optimize> + <WarningLevel>4</WarningLevel> + <DebugType>pdbonly</DebugType> + <ErrorReport>prompt</ErrorReport> + <PlatformTarget>AnyCPU</PlatformTarget> + </PropertyGroup> + <ItemGroup> + <Reference Include="System" /> + <Reference Include="Newtonsoft.Json"> + <HintPath>.\Gestor.ModelReferences\Newtonsoft.Json.dll</HintPath> + </Reference> + <Reference Include="System.Core" /> + <Reference Include="System.Data" /> + <Reference Include="Microsoft.CSharp" /> + </ItemGroup> + <ItemGroup> + <Compile Include="Properties\AssemblyInfo.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Validation\ControleValidacao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\TipoRelatorio.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\ValorSintetico.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\Tarefa\Tarefa.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Ferramentas\AgendaEmail.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\Renovacao\Renovacao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Ferramentas\AgendaTelefone.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Configuracoes\ConfiguracaoSistema.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\Renovacao\SinteticoRenovacao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Common\ArquivoDigital.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Common\Atividade.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Validation\Funcoes.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Common\FipeDetalhe.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Relatorios\Cliente.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Relatorios\ClienteEmail.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Common\RegistroAcao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Relatorios\ClienteEndereco.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\Sinistro\Sinistro.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Common\TrocaCliente.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Relatorios\ClienteTelefone.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\Sinistro\SinteticoSinistro.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Relatorios\Controle.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Common\Banco.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Common\Contato.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Relatorios\Documento.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Common\ControleArquivoDigital.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Relatorios\EstipulanteCliente.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Relatorios\Ramo.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Common\PesquisaAvancada.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Relatorios\Vendedor.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.License\Instalacao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.License\Licenca.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.License\Produto.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\Producao\Producao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.License\StatusLicenca.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\Producao\SinteticoProducao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\PrevisaoPagamentoComissao\PrevisaoPagamento.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\PrevisaoPagamentoComissao\PrevisaoPagamentoComissao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\PrevisaoPagamentoComissao\PrevisaoPagamentoComissaoSintetico.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\PrevisaoPagamentoComissao\AgrupamentoSintetico.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\Placa\Placas.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Common\Empresa.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Common\Fipe.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\Pendente\Pendente.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\Pendente\SinteticoPendente.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\Pagamento\PagamentoSintetico.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\Pagamento\AgrupamentoPagamentoSintetico.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\Pagamento\Pagamento.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Common\IndiceArquivoDigital.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Common\Profissao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\Pagamento\AgrupamentoVendedor.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\Pagamento\SinteticoPagamento.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Common\RegistroLog.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Helper\ValidationHelper.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\NotaFiscal\NotaFiscalRelatorio.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\MetaVendedor\MetaVendedorRelatorio.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Common\Socio.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\MetaVendedor\SinteticoMetaVendedor.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\Adiantamento.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\MetaSeguradora\MetaSeguradoraRelatorio.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\MetaSeguradora\SinteticoMetaSeguradora.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Card\Assistance.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\Log\LogAcaoRelatorio.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Card\AssistenciaCia.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\LogsEnvio\LogsEnvio.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Card\Card.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Card\Logo.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\Licenciamento\Licenciamento.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.BI\Analitico.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\Fechamento\Fechamento.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\Fechamento\Fechamentos.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\Aeronautico.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.BI\AtalhosApolice.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\Fechamento\SinteticoFechamento.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.BI\AtalhosCalculo.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.BI\AtalhosCliente.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\ClienteVinculo.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.BI\AtalhosComissao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.BI\AtalhosParcela.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\FaturaPendente\FaturaPendente.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.BI\AtalhosSinistro.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\Expedicao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Aggilizador\ArquivoVinculo.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\Extrato\DetalhesExtrato.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Aggilizador\Calculo.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Aggilizador\LocalArquivo.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\PerfilEmpresa.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Aggilizador\ParcelaPendente.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\Extrato\Extrato.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Aggilizador\VinculoDocumento.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\Extrato\ExtratoComissao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\PermissaoArquivoDigital.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\Extrato\InformacoesExtrato.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\Extrato\SinteticoExtrato.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Converter\EnumDescriptionTypeConverter.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\AcessoApolice.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\Agrupamento.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\ProspeccaoToPrint.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\Antifurto.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\BandeiraCartao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\BaseRepasse.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\ExtratoBaixado\ExtratoBaixadoRelatorio.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\Rastreador.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\UsoVeiculo.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\Condicao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\ResponsavelAssinatura.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\ConfiguracaoImpressao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\EquipamentoIncendio.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\EquipamentoSeguranca.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\FiltroLancamentoData.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\RestricaoUsuarioCamposRelatorios.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\Operacao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\Operador.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\SqlQueryCondition.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\EndossoCancelamento\Endosso.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\StatusCalculo.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\Localizacao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoConta.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoContatoSeguradora.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoIncidenciaDesconto.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoFiltroBusca.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\Dashboard\Prospectar.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoFiltroCliente.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoConstrucao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\AtividadeEmpresa.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoProtocoloEtiqueta.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\CriticaApolice\ApoliceCritica.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\Consorcio.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\Configuracao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\ParentescoVinculo.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\StatusProspeccao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoEmail.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoMoradia.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoPavimentacao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoTelaInicial.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoTitular.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\StatusAssinatura.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\Comissao\Comissao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\StatusDocumentoAssinado.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\StatusPagamento.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoArquivoVinculo.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoRecibo.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\Comissao\SinteticoComissao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\Ocupacao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\Cliente\SinteticoClientes.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\DistanciaTrabalho.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\StatusItem.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoTrilha.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\UsoDependetes.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\GaragemTrabalhoEstudo.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\GaragemResidencia.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoResidencia.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TempoHabilitacao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\TitularesVida.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\Relacao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\Categoria.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\Combustivel.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\Cor.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\Correcao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\FiltroArquivoDigital.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\FiltroCritica.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\FiltroLancamento.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\FiltroStatusDocumento.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\ClientesAtivosInativos\ClientesAtivosInativos.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\FormaPagamento.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\ClientesAtivosInativos\SinteticoClientesAtivosInativos.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\FormaRepasse.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\Isencao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\ManutencaoItem.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\Parcelas.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\Classificacao\Classificacao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\Mes.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\NegocioCorretora.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\PermissaoAggilizador.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoExtrato.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\Relatorio.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\Negocio.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\SinteticoFinanceiroTipo.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\StatusExtrato.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\Auditoria\Auditoria.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\StatusLancamento.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\StatusParcela.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\StatusSinistro.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\StatusTarefa.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\SubTipo.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TabelaReferencia.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\Sinal.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\Perfil.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoContato.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoFiltroFinanceiro.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\ApolicePendente\ApolicePendente.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\ApolicePendente\ContainerApolicePendente.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.MalaDireta\Copia.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.MalaDireta\MalaDireta.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoRestricao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.MalaDireta\ModeloMalaDireta.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.MalaDireta\VariaveisMalaDireta.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoTela.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoAcao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Generic\Diferenca.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Generic\FieldInformation.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoAeronautico.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Generic\IDomain.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoArquivoDigital.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoCobertura.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoEndereco.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoEndosso.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoFiltroRelatorio.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoIncidencia.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoManutencao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoPagamento.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoPerda.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoPesquisa.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoRecebimento.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\EstadoCivil.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\Sexo.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoDocumento.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoRepasse.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoSeguro.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoSinistro.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TpoSituacaoSinistro.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoTarefa.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\TipoTelefone.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\Utilizacao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\ValidationStates.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\Auto.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Common\Parentesco.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.CalculoWeb\Calculo.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.CalculoWeb\Segurado.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.CalculoWeb\Resultados.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.CalculoWeb\Seguro.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.CalculoWeb\Telefone.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.CalculoWeb\Usuario.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.CalculoWeb\VidaIndividual\CalculoVidaIndividual.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.CalculoWeb\VidaIndividual\CoberturaVidaIndividual.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.CalculoWeb\VidaIndividual\Profissao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.CalculoWeb\VidaIndividual\QuestionarioVidaIndividual.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.CalculoWeb\VidaGlobal\CalculoVidaGlobal.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.CalculoWeb\VidaGlobal\CoberturaVidaGlobal.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.CalculoWeb\VidaGlobal\QuestionarioVidaGlobal.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.CalculoWeb\Residencia\CoberturaResidencia.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.CalculoWeb\Residencia\EnderecoResidencia.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.CalculoWeb\Residencia\Imovel.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.CalculoWeb\Residencia\QuestionarioResidencia.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.CalculoWeb\Residencia\CalculoResidencia.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.CalculoWeb\Empresa\CalculoEmpresa.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.CalculoWeb\Empresa\CoberturaEmpresa.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.CalculoWeb\Empresa\EnderecoEmpresa.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.CalculoWeb\Empresa\QuestionarioEmpresa.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.CalculoWeb\Condominio\CalculoCondominio.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.CalculoWeb\Condominio\CoberturaCondominio.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.CalculoWeb\Condominio\QuestionarioCondominio.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.CalculoWeb\Auto\CalculoAuto.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.CalculoWeb\Auto\ComissaoSeguradora.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.CalculoWeb\Auto\Caminhao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.CalculoWeb\Auto\CoberturaAuto.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.CalculoWeb\Auto\CondutorPrincipal.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\Cliente.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.CalculoWeb\Auto\Fipe.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\ClienteEmail.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.CalculoWeb\Auto\QuestionarioAuto.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.CalculoWeb\Auto\Veiculo.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Attributes\EntityAttribute.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\ClienteEndereco.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Attributes\ForceLogAttribute.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Attributes\HelpAttribute.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\ClienteTelefone.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Attributes\NameAttribute.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Attributes\LogAttribute.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Attributes\OldValue2Attribute.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\Cobertura.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Attributes\OldValueAttribute.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Attributes\TipoAttribute.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Attributes\WidthAttribute.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\CoberturaGranizo.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.API\Access.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.API\AccessControl.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.API\AjudaTela.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\CoberturaPadrao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.API\Attachment.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\CondicaoRepasse.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.API\AuthSso.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\Controle.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.API\ConnectionAddress.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\ControleSinistro.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.API\Customer.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.API\CustomerAttendance.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.API\CustomerData.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.API\HorarioAtendimento.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\CriticaApolice.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.API\LogError.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.API\Owner.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.API\Parameters.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.API\Payment.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\DetalheExtrato.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Generic\DomainBase.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Generic\EmailBase.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.API\TipoErro.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Generic\EnderecoBase.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.API\TokenSso.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.API\UploadFile.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Generic\TelefoneBase.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Generic\ValorOriginal.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.API\UserSso.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.API\UsuarioCentralSegurado.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Financeiro\BancosContas.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.API\Version.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Financeiro\ControleFinanceiro.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Financeiro\ExtratoConta.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Financeiro\FiltroPersonalizado.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\Item.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\Documento.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\MaisContato.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Financeiro\Fornecedor.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\MetaSeguradora.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\MetaVendedor.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Financeiro\Lancamento.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\Estipulante.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Financeiro\SinteticoFinanceiro.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Financeiro\TipoConta.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\Extrato.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Financeiro\Planos.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\Fabricante.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\Parceiro.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Financeiro\Plano.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Financeiro\Centro.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Financeiro\RelatorioLancamentos.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\Granizo.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Financeiro\Saldo.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\RestricaoUsuario.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Financeiro\Transferencia.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Financeiro\Relatorios\DadosFechamento.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\RiscosDiversos.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Financeiro\Relatorios\DadosFechamentoAnalitico.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Financeiro\Relatorios\FechamentoFinanceiro.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Financeiro\Relatorios\FechamentoFinanceiroAnalitico.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Financeiro\Relatorios\FiltroFinanceiro.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Ferramentas\Imposto.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\Parcela.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Ferramentas\ManutencaoPagamentos.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Ferramentas\NotaFiscal.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Ferramentas\OrigemCliente.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\Seguradora.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\SeguradoraContato.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Ferramentas\Recibo.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Ferramentas\CategoriaTarefa.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\Patrimonial.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\AggilizadorPermissao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\PermissaoUsuario.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\SeguradoraEndereco.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Ferramentas\Credencial.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\Qualificacao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Ferramentas\Destinatario.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Ferramentas\Fase.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\Status.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Ferramentas\LogEmail.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Ferramentas\LogEnvio.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\Produto.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\ConfigExtratoImport.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Ferramentas\Agenda.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Ferramentas\ResponsavelTarefa.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\Prospeccao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Ferramentas\Tarefa.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\Ramo.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Ferramentas\StatusDeProspeccao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Ferramentas\TipoDeTarefa.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\Sinistro.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\Repasse.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Ferramentas\Trilha.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\SinistroAuto.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\SinistroVida.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\TipoVendedor.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\TupleList.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\Vida.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\Sintetico.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\SinteticoFinanceiro.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\VinculoRepasse.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\StatusRelatorio.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\VinculoVendedor.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\CartaoSegurado.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\NegocioRelatorio.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\DadosRelatorio.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\DadosVinculo.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\FiltroPersonalizado.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\FiltroTipoParcela.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\ParametrosTotalizacao.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\Usuario.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\ParametrosRelatorio.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\Filtros.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\FiltroRelatorio.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\Listagem.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\Vendedor.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\VendedorParcelas.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\VendedorParcela.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\VendedorTelefone.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Seguros\VendedorUsuario.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\PlanilhaCompleta.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\SinteticModel.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + <Compile Include="Model.Domain.Relatorios\SinteticModelList.cs"> + <AutoGen>false</AutoGen> + <DesignTimeSharedInput>false</DesignTimeSharedInput> + </Compile> + </ItemGroup> + <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> +</Project> \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Gestor.Model.sln b/Codemerx/Gestor.Model/Gestor.Model.sln new file mode 100644 index 0000000..451a17d --- /dev/null +++ b/Codemerx/Gestor.Model/Gestor.Model.sln @@ -0,0 +1,21 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29728.190 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Gestor.Model", "Gestor.Model.csproj", "{38886FAE-B3AF-42BA-BAC3-9295A61CB2C5}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {38886FAE-B3AF-42BA-BAC3-9295A61CB2C5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {38886FAE-B3AF-42BA-BAC3-9295A61CB2C5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {38886FAE-B3AF-42BA-BAC3-9295A61CB2C5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {38886FAE-B3AF-42BA-BAC3-9295A61CB2C5}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Codemerx/Gestor.Model/Gestor.ModelReferences/Newtonsoft.Json.dll b/Codemerx/Gestor.Model/Gestor.ModelReferences/Newtonsoft.Json.dll new file mode 100644 index 0000000..7af125a Binary files /dev/null and b/Codemerx/Gestor.Model/Gestor.ModelReferences/Newtonsoft.Json.dll differ diff --git a/Codemerx/Gestor.Model/Model.API/Access.cs b/Codemerx/Gestor.Model/Model.API/Access.cs new file mode 100644 index 0000000..35f3dd7 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.API/Access.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.API +{ + public class Access + { + public long? AgreementId + { + get; + set; + } + + public decimal? Ammount + { + get; + set; + } + + public IList<AccessControl> Control + { + get; + set; + } + + public DateTime CurrentDate + { + get; + set; + } + + public long CustomerId + { + get; + set; + } + + public long Id + { + get; + set; + } + + public long? ProductId + { + get; + set; + } + + public long? SchemeId + { + get; + set; + } + + public string Status + { + get; + set; + } + + public Access() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.API/AccessControl.cs b/Codemerx/Gestor.Model/Model.API/AccessControl.cs new file mode 100644 index 0000000..d78f403 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.API/AccessControl.cs @@ -0,0 +1,42 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.API +{ + public class AccessControl + { + public Gestor.Model.API.Access Access + { + get; + set; + } + + public DateTime? Compensation + { + get; + set; + } + + public DateTime Expiration + { + get; + set; + } + + public long Id + { + get; + set; + } + + public DateTime Maturity + { + get; + set; + } + + public AccessControl() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.API/AjudaTela.cs b/Codemerx/Gestor.Model/Model.API/AjudaTela.cs new file mode 100644 index 0000000..5c49f0c --- /dev/null +++ b/Codemerx/Gestor.Model/Model.API/AjudaTela.cs @@ -0,0 +1,55 @@ +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.API +{ + public class AjudaTela + { + public string Descricao + { + get; + set; + } + + public long Id + { + get; + set; + } + + public string Link + { + get; + set; + } + + public int Minuto + { + get; + set; + } + + public int Segundo + { + get; + set; + } + + public TipoTela Tela + { + get; + set; + } + + public string Titulo + { + get; + set; + } + + public AjudaTela() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.API/Attachment.cs b/Codemerx/Gestor.Model/Model.API/Attachment.cs new file mode 100644 index 0000000..cdfdb8e --- /dev/null +++ b/Codemerx/Gestor.Model/Model.API/Attachment.cs @@ -0,0 +1,30 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.API +{ + public class Attachment + { + public string Description + { + get; + set; + } + + public string Extension + { + get; + set; + } + + public byte[] File + { + get; + set; + } + + public Attachment() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.API/AuthSso.cs b/Codemerx/Gestor.Model/Model.API/AuthSso.cs new file mode 100644 index 0000000..4b57fe9 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.API/AuthSso.cs @@ -0,0 +1,24 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.API +{ + public class AuthSso + { + public int Code + { + get; + set; + } + + public TokenSso Data + { + get; + set; + } + + public AuthSso() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.API/ConnectionAddress.cs b/Codemerx/Gestor.Model/Model.API/ConnectionAddress.cs new file mode 100644 index 0000000..e34ae49 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.API/ConnectionAddress.cs @@ -0,0 +1,114 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.API +{ + public class ConnectionAddress + { + public string Aggilizador + { + get; + set; + } + + public string AppleLogin + { + get; + set; + } + + public string ApplePass + { + get; + set; + } + + public string AzureStorage + { + get; + set; + } + + public string Catalog + { + get; + set; + } + + public long CustomerId + { + get; + set; + } + + public string EpicAndroid + { + get; + set; + } + + public string EpicIos + { + get; + set; + } + + public long Id + { + get; + set; + } + + public string Mobile + { + get; + set; + } + + public string Password + { + get; + set; + } + + public string Pool + { + get; + set; + } + + public string Server + { + get; + set; + } + + public int Type + { + get; + set; + } + + public string UrlCentralSegurado + { + get; + set; + } + + public bool UsaAzureStorage + { + get; + set; + } + + public string User + { + get; + set; + } + + public ConnectionAddress() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.API/Customer.cs b/Codemerx/Gestor.Model/Model.API/Customer.cs new file mode 100644 index 0000000..2aefe82 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.API/Customer.cs @@ -0,0 +1,127 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.API +{ + public class Customer + { + public string Adjunct + { + get; + set; + } + + public string AreaCode + { + get; + set; + } + + public string City + { + get; + set; + } + + public string District + { + get; + set; + } + + public string Document + { + get; + set; + } + + public long Id + { + get; + set; + } + + public DateTime LastUpdate + { + get; + set; + } + + public string Mail + { + get; + set; + } + + public string Name + { + get; + set; + } + + public string Number + { + get; + set; + } + + public List<Owner> Owners + { + get; + set; + } + + public string Phone + { + get; + set; + } + + public string PostCode + { + get; + set; + } + + public string SecondAreaCode + { + get; + set; + } + + public string SecondPhone + { + get; + set; + } + + public string Site + { + get; + set; + } + + public string State + { + get; + set; + } + + public string Street + { + get; + set; + } + + public string Updated + { + get; + set; + } + + public Customer() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.API/CustomerAttendance.cs b/Codemerx/Gestor.Model/Model.API/CustomerAttendance.cs new file mode 100644 index 0000000..04961f3 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.API/CustomerAttendance.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.API +{ + public class CustomerAttendance + { + public List<Attachment> Attachments + { + get; + set; + } + + public string Body + { + get; + set; + } + + public Gestor.Model.API.CustomerData CustomerData + { + get; + set; + } + + public string Subject + { + get; + set; + } + + public CustomerAttendance() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.API/CustomerData.cs b/Codemerx/Gestor.Model/Model.API/CustomerData.cs new file mode 100644 index 0000000..ca78e4a --- /dev/null +++ b/Codemerx/Gestor.Model/Model.API/CustomerData.cs @@ -0,0 +1,42 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.API +{ + public class CustomerData + { + public string AreaCode + { + get; + set; + } + + public string Corretora + { + get; + set; + } + + public string Email + { + get; + set; + } + + public string Name + { + get; + set; + } + + public string Number + { + get; + set; + } + + public CustomerData() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.API/HorarioAtendimento.cs b/Codemerx/Gestor.Model/Model.API/HorarioAtendimento.cs new file mode 100644 index 0000000..e9e6564 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.API/HorarioAtendimento.cs @@ -0,0 +1,48 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.API +{ + public class HorarioAtendimento + { + public bool Autorizado + { + get; + set; + } + + public int? FimDia + { + get; + set; + } + + public string FimHora + { + get; + set; + } + + public DateTime HoraServidor + { + get; + set; + } + + public int? InicioDia + { + get; + set; + } + + public string InicioHora + { + get; + set; + } + + public HorarioAtendimento() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.API/LogError.cs b/Codemerx/Gestor.Model/Model.API/LogError.cs new file mode 100644 index 0000000..07f9731 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.API/LogError.cs @@ -0,0 +1,126 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.API +{ + public class LogError + { + public DateTime Data + { + get; + set; + } + + public string Erro + { + get; + set; + } + + public string Fornecedor + { + get; + set; + } + + public string HelpLink + { + get; + set; + } + + public int HResult + { + get; + set; + } + + public long Id + { + get; + set; + } + + public int IdErro + { + get; + set; + } + + public long IdFornecedor + { + get; + set; + } + + public long IdUsuarioLogado + { + get; + set; + } + + public string InnerException + { + get; + set; + } + + public string Linha + { + get; + set; + } + + public string Maquina + { + get; + set; + } + + public string Message + { + get; + set; + } + + public string Objeto + { + get; + set; + } + + public string Source + { + get; + set; + } + + public string StackTrace + { + get; + set; + } + + public string UsuarioLogado + { + get; + set; + } + + public string UsuarioMaquina + { + get; + set; + } + + public string Versao + { + get; + set; + } + + public LogError() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.API/Owner.cs b/Codemerx/Gestor.Model/Model.API/Owner.cs new file mode 100644 index 0000000..3fde471 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.API/Owner.cs @@ -0,0 +1,54 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.API +{ + public class Owner + { + public string AreaCode + { + get; + set; + } + + public Gestor.Model.API.Customer Customer + { + get; + set; + } + + public long Id + { + get; + set; + } + + public string Mail + { + get; + set; + } + + public string Name + { + get; + set; + } + + public string Phone + { + get; + set; + } + + public long Type + { + get; + set; + } + + public Owner() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.API/Parameters.cs b/Codemerx/Gestor.Model/Model.API/Parameters.cs new file mode 100644 index 0000000..efea126 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.API/Parameters.cs @@ -0,0 +1,48 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.API +{ + public class Parameters + { + public string Application + { + get; + set; + } + + public string Arguments + { + get; + set; + } + + public bool Beta + { + get; + set; + } + + public string Directory + { + get; + set; + } + + public bool Run + { + get; + set; + } + + public int Type + { + get; + set; + } + + public Parameters() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.API/Payment.cs b/Codemerx/Gestor.Model/Model.API/Payment.cs new file mode 100644 index 0000000..b0440d8 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.API/Payment.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.API +{ + public class Payment + { + public string Codigo + { + get; + set; + } + + public DateTime Compensation + { + get; + set; + } + + public string Descricao + { + get; + set; + } + + public long Id + { + get; + set; + } + + public string Nota + { + get; + set; + } + + public DateTime Processamento + { + get; + set; + } + + public List<string> Products + { + get; + set; + } + + public decimal Valor + { + get; + set; + } + + public DateTime Vencimento + { + get; + set; + } + + public Payment() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.API/TipoErro.cs b/Codemerx/Gestor.Model/Model.API/TipoErro.cs new file mode 100644 index 0000000..155a0df --- /dev/null +++ b/Codemerx/Gestor.Model/Model.API/TipoErro.cs @@ -0,0 +1,1014 @@ +using System; +using System.ComponentModel; + +namespace Gestor.Model.API +{ + public enum TipoErro + { + [Category("CONSTATAMOS UM ERRO AO SALVAR O LOG DO PROCEDIMENTO EXECUTADO")] + [Description("ERRO AO SALVAR LOG")] + SalvarLog = 0, + [Category("CONSTATAMOS UM ERRO AO BUSCAR AS APÓLICES DO CLIENTE SELECIONADO")] + [Description("ERRO AO BUSCAR APÓLICES POR STATUS E FORNECEDOR")] + BuscarApolicesSatus = 1, + [Category("CONSTATAMOS UM ERRO AO BUSCAR AS APÓLICES DO CLIENTE SELECIONADO PARA CRÍTICA DE COMISSÃO")] + [Description("ERRO AO BUSCAR APÓLICES FORNECEDOR PARA CRÍTICA DE COMISSÃO")] + BuscarApolicesComissao = 2, + [Category("CONSTATAMOS UM ERRO AO BUSCAR UMA APÓLICE DO CLIENTE SELECIONADO")] + [Description("ERRO AO BUSCAR APÓLICES POR ID")] + BuscarApoliceId = 3, + [Category("CONSTATAMOS UM ERRO AO BUSCAR A UM CONTROLE DO CLIENTE SELECIONADO")] + [Description("ERRO AO BUSCAR CONTROLE POR ID")] + BuscarControleId = 4, + [Category("CONSTATAMOS UM ERRO AO BUSCAR AS APÓLICES DO CLIENTE SELECIONADO")] + [Description("ERRO AO BUSCAR APÓLICES POR VIGENCIA E FILTRO")] + BuscarApolicesVigenciaFiltro = 5, + [Category("CONSTATAMOS UM ERRO AO BUSCAR AS APÓLICES DO CLIENTE SELECIONADO")] + [Description("ERRO AO BUSCAR APÓLICES POR VIGENCIA FINAL E FILTRO")] + BuscarApolicesVigenciaFinalFiltro = 6, + [Category("CONSTATAMOS UM ERRO AO BUSCAR AS APÓLICES DO CLIENTE SELECIONADO")] + [Description("ERRO AO BUSCAR APÓLICES POR PESQUISA E STATUS")] + BuscarApolicesPesquisaStatus = 7, + [Category("CONSTATAMOS UM ERRO AO BUSCAR OS FECHAMENTOS DO DOCUMENTO SELECIONADO")] + [Description("ERRO AO BUSCAR FECHAMENTOS POR FILTRO")] + BuscarFechamentosFiltro = 8, + [Category("CONSTATAMOS UM ERRO AO BUSCAR OS LOGS DE ENVIO")] + [Description("ERRO AO BUSCAR LOGS DE ENVIO POR FILTRO")] + BuscarLogsEnvioFiltro = 9, + [Category("CONSTATAMOS UM ERRO AO BUSCAR AS APÓLICES PENDENTES DO CLIENTE SELECIONADO")] + [Description("ERRO AO BUSCAR APÓLICES PENDENTES POR FILTRO")] + BuscarApolicesPendentesFiltro = 10, + [Category("CONSTATAMOS UM ERRO AO BUSCAR AS APÓLICES")] + [Description("ERRO AO BUSCAR APÓLICES POR ESTIPULANTE")] + BuscarApolicesEstipulante = 11, + [Category("CONSTATAMOS UM ERRO AO BUSCAR AS APÓLICES")] + [Description("ERRO AO BUSCAR APÓLICES POR STATUS")] + BuscarApolicesStatus = 12, + [Category("CONSTATAMOS UM ERRO AO BUSCAR AS AUDITORIAS")] + [Description("ERRO AO BUSCAR AUDITORIAS POR FILTRO")] + BuscarAuditoriasFiltro = 13, + [Category("CONSTATAMOS UM ERRO AO BUSCAR AS COTAÇÕES")] + [Description("ERRO AO BUSCAR COTAÇÕES POR FILTRO")] + BuscarCotacoesFiltro = 14, + [Category("CONSTATAMOS UM ERRO AO BUSCAR OS ADIANTAMENTOS")] + [Description("ERRO AO BUSCAR ADIANTAMENTOS POR DATA")] + BuscarAdiantamentosData = 15, + [Category("CONSTATAMOS UM ERRO AO BUSCAR OS ADIANTAMENTOS")] + [Description("ERRO AO BUSCAR ADIANTAMENTOS POR ID")] + BuscarAdiantamentosId = 16, + [Category("CONSTATAMOS UM ERRO AO BUSCAR O ULTIMO ID")] + [Description("ERRO AO BUSCAR ULTIMO ID")] + BuscarUltimoId = 17, + [Category("CONSTATAMOS UM ERRO AO SALVAR O DOCUMENTO SELECIONADO")] + [Description("ERRO AO SALVAR DOCUMENTO")] + SalvarDocumento = 18, + [Category("CONSTATAMOS UM ERRO AO ATUALIZAR O DOCUMENTO SELECIONADO")] + [Description("ERRO AO ATUALIZAR DOCUMENTO")] + SalvarAtualizarControle = 19, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR O DOCUMENTO SELECIONADO")] + [Description("ERRO AO EXCLUIR DOCUMENTO")] + ExcluirDocumento = 20, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR O PAGAMENTO DE VENDEDORES")] + [Description("ERRO AO EXCLUIR PAGAMENTO DE VENDEDORES")] + ExcluirPagamentoVendedor = 21, + [Category("CONSTATAMOS UM ERRO AO INCLUIR PAGAMENTO A VENDEDORES")] + [Description("ERRO AO INCLUIR PAGAMENTO A VENDEDORES")] + IncluirPagamentoVendedor = 22, + [Category("CONSTATAMOS UM ERRO AO ALTERAR O STATUS DO DOCUMENTO PARA PERDIDO")] + [Description("ERRO AO ALTERAR O STATUS DO DOCUMENTO PARA PERDIDO")] + AlterarStatusPerdido = 23, + [Category("CONSTATAMOS UM ERRO AO SALVAR A PARCELA SELECIONADA")] + [Description("ERRO AO SALVAR PARCELA")] + SalvarParcela = 24, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR A CRITICA DE IMPORTAÇÃO DO DOCUMENTO SELECIONADO")] + [Description("ERRO AO EXCLUIR CRÍTICA DE IMPORTAÇÃO")] + ExcluirCritica = 25, + [Category("CONSTATAMOS UM ERRO AO BAIXAR AS PARCELAS DO DOCUMENTO SELECIONADO")] + [Description("ERRO AO BAIXAR PARCELAS")] + BaixarParcelas = 26, + [Category("CONSTATAMOS UM ERRO AO BUSCAR O CLIENTE")] + [Description("ERRO AO BUSCAR CLIENTE POR ID")] + BuscarClienteId = 27, + [Category("CONSTATAMOS UM ERRO AO BUSCAR OS CLIENTES")] + [Description("ERRO AO BUSCAR CLIENTES POR ID")] + BuscarClientesId = 28, + [Category("CONSTATAMOS UM ERRO AO BUSCAR OS CLIENTES")] + [Description("ERRO AO BUSCAR CLIENTES POR FILTRO")] + BuscarClientesFiltro = 29, + [Category("CONSTATAMOS UM ERRO AO BUSCAR OS TELEFONES DO CLIENTE")] + [Description("ERRO AO BUSCAR TELEFONES DO CLIENTE POR ID")] + BuscarTelefonesClienteId = 30, + [Category("CONSTATAMOS UM ERRO AO BUSCAR OS TELEFONES DO CLIENTE")] + [Description("ERRO AO BUSCAR TELEFONES DO CLIENTE POR FILTRO")] + BuscarTelefonesClienteFiltro = 31, + [Category("CONSTATAMOS UM ERRO AO BUSCAR OS EMAILS DO CLIENTE")] + [Description("ERRO AO BUSCAR EMAILS DO CLIENTE POR ID")] + BuscarEmailsClienteId = 32, + [Category("CONSTATAMOS UM ERRO AO BUSCAR VINCULOS DO CLIENTE")] + [Description("ERRO AO BUSCAR VINCULOS DO CLIENTE POR ID")] + BuscarVinculosClienteId = 33, + [Category("CONSTATAMOS UM ERRO AO BUSCAR OS ENDEREÇOS DO CLIENTE")] + [Description("ERRO AO BUSCAR ENDEREÇOS DO CLIENTE POR ID")] + BuscarEnderecosClienteId = 34, + [Category("CONSTATAMOS UM ERRO AO BUSCAR OS CONTATOS DO CLIENTE")] + [Description("ERRO AO BUSCAR CONTATOS DO CLIENTE POR ID")] + BuscarContatosClienteId = 35, + [Category("CONSTATAMOS UM ERRO AO BUSCAR TODOS OS CLIENTES")] + [Description("ERRO AO BUSCAR TODOS OS CLIENTES")] + BuscarTodosClienteId = 36, + [Category("CONSTATAMOS UM ERRO AO BUSCAR OS EMAILS DOS CLIENTES")] + [Description("ERRO AO BUSCAR EMAILS DOS CLIENTES POR IDS")] + BuscarEmailsClientesId = 37, + [Category("CONSTATAMOS UM ERRO AO BUSCAR OS ENDEREÇOS DOS CLIENTES")] + [Description("ERRO AO BUSCAR ENDEREÇOS DOS CLIENTES POR ID")] + BuscarEnderecosClientesId = 38, + [Category("CONSTATAMOS UM ERRO AO BUSCAR OS CLIENTES")] + [Description("ERRO AO BUSCAR CLIENTES POR OBSERVAÇÃO")] + BuscarClientesObs = 39, + [Category("CONSTATAMOS UM ERRO AO BUSCAR OS CLIENTES")] + [Description("ERRO AO BUSCAR CLIENTES POR PASTA")] + BuscarClientesPasta = 40, + [Category("CONSTATAMOS UM ERRO AO BUSCAR OS CLIENTES")] + [Description("ERRO AO BUSCAR CLIENTES POR ANIVERSÁRIO")] + BuscarClientesAniversario = 41, + [Category("CONSTATAMOS UM ERRO AO BUSCAR OS CLIENTES")] + [Description("ERRO AO BUSCAR CLIENTES POR VALIDADE DA CNH")] + BuscarClientesCnh = 42, + [Category("CONSTATAMOS UM ERRO AO BUSCAR AS CRÍTICAS")] + [Description("ERRO AO BUSCAR CRÍTICAS POR ID E DATA")] + BuscarCriticasIdData = 43, + [Category("CONSTATAMOS UM ERRO AO BUSCAR AS CRÍTICAS")] + [Description("ERRO AO BUSCAR CRÍTICAS POR ID")] + BuscarCriticasId = 44, + [Category("CONSTATAMOS UM ERRO AO BUSCAR AS IMPORTAÇÕES")] + [Description("ERRO AO BUSCAR IMPORTAÇÕES POR ID")] + BuscarImportacoesId = 45, + [Category("CONSTATAMOS UM ERRO AO BUSCAR OS PERFIS")] + [Description("ERRO AO BUSCAR PERFIS POR ID")] + BuscarPerfisId = 46, + [Category("CONSTATAMOS UM ERRO AO BUSCAR OS PERFIS")] + [Description("ERRO AO BUSCAR PERFIS POR IDS")] + BuscarPerfisIds = 47, + [Category("CONSTATAMOS UM ERRO AO BUSCAR OS CONTROLES SINISTRO")] + [Description("ERRO AO BUSCAR CONTROLES SINISTRO POR ID")] + BuscarControlesSinistroId = 48, + [Category("CONSTATAMOS UM ERRO AO BUSCAR O SINISTRO")] + [Description("ERRO AO BUSCAR SINISTRO POR ID")] + BuscarSinistroId = 49, + [Category("CONSTATAMOS UM ERRO AO BUSCAR O AUTOMÓVEL")] + [Description("ERRO AO BUSCAR AUTOMÓVEL POR CHASSI")] + BuscarAutoChassi = 50, + [Category("CONSTATAMOS UM ERRO AO BUSCAR O ITEM")] + [Description("ERRO AO BUSCAR ITEM POR ID")] + BuscarItemId = 51, + [Category("CONSTATAMOS UM ERRO AO BUSCAR OS ITENS")] + [Description("ERRO AO BUSCAR ITENS POR IDS")] + BuscarItensIds = 52, + [Category("CONSTATAMOS UM ERRO AO BUSCAR OS ITENS")] + [Description("ERRO AO BUSCAR ITENS POR ID E POR STATUS")] + BuscarItensIdStatus = 53, + [Category("CONSTATAMOS UM ERRO AO BUSCAR O PRÓXIMO")] + [Description("ERRO AO BUSCAR PRÓXIMO ITEM")] + BuscarProximoItem = 54, + [Category("CONSTATAMOS UM ERRO AO BUSCAR O AUTOMÓVEL")] + [Description("ERRO AO BUSCAR AUTOMÓVEL POR ID")] + BuscarAutoId = 55, + [Category("CONSTATAMOS UM ERRO AO BUSCAR O AUTOMÓVEL")] + [Description("ERRO AO BUSCAR GRANIZO POR ID")] + BuscarGranizoId = 56, + [Category("CONSTATAMOS UM ERRO AO BUSCAR AS COBERTURAS")] + [Description("ERRO AO BUSCAR COBERTURAS POR ID")] + BuscarCoberturasId = 57, + [Category("CONSTATAMOS UM ERRO AO BUSCAR AS COBERTURAS")] + [Description("ERRO AO BUSCAR COBERTURAS")] + BuscarCoberturas = 58, + [Category("CONSTATAMOS UM ERRO AO BUSCAR O PATRIMONIAL")] + [Description("ERRO AO BUSCAR PATRIMONIAL POR ID")] + BuscarPatrimonialId = 59, + [Category("CONSTATAMOS UM ERRO AO BUSCAR O VIDA")] + [Description("ERRO AO BUSCAR VIDA POR ID")] + BuscarVidaId = 60, + [Category("CONSTATAMOS UM ERRO AO BUSCAR TITULARES VIDA")] + [Description("ERRO AO BUSCAR TITULARES VIDA POR ID")] + BuscarTitularesVidaId = 61, + [Category("CONSTATAMOS UM ERRO AO BUSCAR O RISCOS DIVERSOS")] + [Description("ERRO AO BUSCAR RISCOS DIVERSOS POR ID")] + BuscarRiscosDiversosId = 62, + [Category("CONSTATAMOS UM ERRO AO BUSCAR O AERONAUTICO")] + [Description("ERRO AO BUSCAR AERONAUTICO POR ID")] + BuscarAeronauticoId = 63, + [Category("CONSTATAMOS UM ERRO AO BUSCAR O INDICE ARQUIVO DIGITAL")] + [Description("ERRO AO BUSCAR INDICE ARQUIVO DIGITAL POR TIPO E ID")] + BuscarIndiceArquivoDigitalTipoId = 64, + [Category("CONSTATAMOS UM ERRO AO BUSCAR ANEXO POR ID E BANCO")] + [Description("ERRO AO BUSCAR ANEXO POR ID E BANCO")] + BuscarAnexoIdBanco = 65, + [Category("CONSTATAMOS UM ERRO AO BUSCAR OS ANEXOS")] + [Description("ERRO AO BUSCAR ANEXOS POR IDS")] + BuscarAnexosIds = 66, + [Category("CONSTATAMOS UM ERRO AO BUSCAR OS REGISTROS LOG")] + [Description("ERRO AO BUSCAR REGISTROS LOG POR ID E TIPO TELA")] + BuscarRegistrosLogIdTipo = 67, + [Category("CONSTATAMOS UM ERRO AO BUSCAR OS LOG EMAIL")] + [Description("ERRO AO BUSCAR LOG EMAIL POR ID E TIPO TELA")] + BuscarEmailLogIdTipo = 68, + [Category("CONSTATAMOS UM ERRO AO BUSCAR OS LOG EMAIL")] + [Description("ERRO AO BUSCAR LOG EMAIL POR ID")] + BuscarEmailLogId = 69, + [Category("CONSTATAMOS UM ERRO AO BUSCAR MODELOS MALA DIRETA")] + [Description("ERRO AO BUSCAR MODELOS MALA DIRETA")] + BuscarModelosMalaDireta = 70, + [Category("CONSTATAMOS UM ERRO AO BUSCAR PARCEIRO")] + [Description("ERRO AO BUSCAR PARCEIRO POR ID")] + BuscarParceiroId = 71, + [Category("CONSTATAMOS UM ERRO AO BUSCAR PARCEIROS")] + [Description("ERRO AO BUSCAR PARCEIROS")] + BuscarParceiros = 72, + [Category("CONSTATAMOS UM ERRO AO BUSCAR PARCELAS")] + [Description("ERRO AO BUSCAR PARCELAS POR ID")] + BuscarParcelasId = 73, + [Category("CONSTATAMOS UM ERRO AO BUSCAR PARCELA")] + [Description("ERRO AO BUSCAR PARCELA POR ID")] + BuscarParcelaId = 74, + [Category("CONSTATAMOS UM ERRO AO BUSCAR PARCELAS")] + [Description("ERRO AO BUSCAR PARCELAS POR IDS")] + BuscarParcelasIds = 75, + [Category("CONSTATAMOS UM ERRO AO BUSCAR FATURAS")] + [Description("ERRO AO BUSCAR FATURAS POR FILTRO")] + BuscarFaturasFiltro = 76, + [Category("CONSTATAMOS UM ERRO AO BUSCAR PARCELAS RECEBIMENTO")] + [Description("ERRO AO BUSCAR PARCELAS RECEBIMENTO POR FILTRO")] + BuscarParcelasRecebimentoFiltro = 77, + [Category("CONSTATAMOS UM ERRO AO BUSCAR PARCELAS PENDENTES")] + [Description("ERRO AO BUSCAR PARCELAS PENDENTES POR FILTRO")] + BuscarParcelasPendentesFiltro = 78, + [Category("CONSTATAMOS UM ERRO AO BUSCAR PARCELAS")] + [Description("ERRO AO BUSCAR PARCELAS POR FILTRO")] + BuscarParcelasFiltro = 79, + [Category("CONSTATAMOS UM ERRO AO BUSCAR PAGAMENTO VENDEDOR")] + [Description("ERRO AO BUSCAR PAGAMENTO VENDEDOR POR FILTRO")] + BuscarPagamentoVendedorFiltro = 80, + [Category("CONSTATAMOS UM ERRO AO BUSCAR PAGAMENTO VENDEDOR")] + [Description("ERRO AO BUSCAR PAGAMENTO VENDEDOR POR ID")] + BuscarPagamentoVendedor = 81, + [Category("CONSTATAMOS UM ERRO AO VERIFICAR SE TEM PAGAMENTO")] + [Description("ERRO AO VERIFICAR SE TEM PAGAMENTO POR ID")] + TemPagamentoId = 82, + [Category("CONSTATAMOS UM ERRO AO BUSCAR FATURAS PENDENTES")] + [Description("ERRO AO BUSCAR FATURAS PENDENTES POR FILTRO")] + BuscarFaturasPendentesFiltro = 83, + [Category("CONSTATAMOS UM ERRO AO BUSCAR PERMISSÕES")] + [Description("ERRO AO BUSCAR PERMISSÕES POR ID")] + BuscarPermissoesId = 84, + [Category("CONSTATAMOS UM ERRO AO BUSCAR PERMISSÃO")] + [Description("ERRO AO BUSCAR PERMISSÃO POR ID E TIPO TELA")] + BuscarPermissaoIdTipoTela = 85, + [Category("CONSTATAMOS UM ERRO AO BUSCAR PROSPEÇÕES")] + [Description("ERRO AO BUSCAR PROSPEÇÕES POR ID, POR DATA E POR STATUS")] + BuscarProspeccoesIdDataStatus = 86, + [Category("CONSTATAMOS UM ERRO AO BUSCAR PROSPEÇÃO")] + [Description("ERRO AO BUSCAR PROSPEÇÃO POR ID")] + BuscarProspeccaoId = 87, + [Category("CONSTATAMOS UM ERRO AO BUSCAR PROSPEÇÕES")] + [Description("ERRO AO BUSCAR PROSPEÇÕES POR FILTRO")] + BuscarProspeccoesFiltro = 88, + [Category("CONSTATAMOS UM ERRO AO BUSCAR RESTRIÇÃO")] + [Description("ERRO AO BUSCAR RESTRIÇÃO POR ID E POR FILTRO")] + BuscarRestricaoIdFiltro = 89, + [Category("CONSTATAMOS UM ERRO AO BUSCAR RESTRIÇÕES")] + [Description("ERRO AO BUSCAR RESTRIÇÕES POR ID")] + BuscarRestricoesId = 90, + [Category("CONSTATAMOS UM ERRO AO BUSCAR DETALHES EXTRATO")] + [Description("ERRO AO BUSCAR DETALHES EXTRATO POR ID")] + BuscarDetalhesExtratoId = 91, + [Category("CONSTATAMOS UM ERRO AO BUSCAR EXTRATOS")] + [Description("ERRO AO BUSCAR EXTRATOS POR ID, POR DATA E POR STATUS")] + BuscarExtratosIdDataStatus = 92, + [Category("CONSTATAMOS UM ERRO AO BUSCAR EXTRATOS")] + [Description("ERRO AO BUSCAR EXTRATOS POR ID, POR DATA E POR FILTRO")] + BuscarExtratosIdDataFiltro = 93, + [Category("CONSTATAMOS UM ERRO AO BUSCAR TAREFAS")] + [Description("ERRO AO BUSCAR TAREFAS POR ID, ENTIDADE E CONCLUIDO")] + BuscarTarefasIdEntidadeConcluido = 94, + [Category("CONSTATAMOS UM ERRO AO BUSCAR TAREFAS")] + [Description("ERRO AO BUSCAR TAREFAS POR ID, DATA E CONCLUIDO")] + BuscarTarefasIdDataConcluido = 95, + [Category("CONSTATAMOS UM ERRO AO BUSCAR TAREFAS")] + [Description("ERRO AO BUSCAR TAREFAS POR CLIENTE")] + BuscarTarefasCliente = 96, + [Category("CONSTATAMOS UM ERRO AO BUSCAR TAREFAS")] + [Description("ERRO AO BUSCAR TAREFAS POR FILTRO")] + BuscarTarefasFiltro = 97, + [Category("CONSTATAMOS UM ERRO AO BUSCAR NOTAS")] + [Description("ERRO AO BUSCAR NOTAS POR ID")] + BuscarNotasId = 98, + [Category("CONSTATAMOS UM ERRO AO BUSCAR NOTAS CONCLUÍDAS")] + [Description("ERRO AO BUSCAR NOTAS CONCLUÍDAS POR ID")] + BuscarNotasConcluidasId = 99, + [Category("CONSTATAMOS UM ERRO AO ATUALIZAR NOTAS E TAREFAS")] + [Description("ERRO AO ATUALIZAR NOTAS E TAREFAS")] + AtualizarNotasTarefas = 100, + [Category("CONSTATAMOS UM ERRO AO BUSCAR TAREFAS")] + [Description("ERRO AO BUSCAR TAREFAS POR ID")] + BuscarTarefasId = 101, + [Category("CONSTATAMOS UM ERRO AO BUSCAR FASES")] + [Description("ERRO AO BUSCAR FASES POR ID")] + BuscarFasesId = 102, + [Category("CONSTATAMOS UM ERRO AO BUSCAR TRILHAS")] + [Description("ERRO AO BUSCAR TRILHAS POR TITULO")] + BuscarTrilhasTitulo = 103, + [Category("CONSTATAMOS UM ERRO AO BUSCAR TRILHAS")] + [Description("ERRO AO BUSCAR TRILHAS")] + BuscarTrilhas = 104, + [Category("CONSTATAMOS UM ERRO AO BUSCAR TAREFA")] + [Description("ERRO AO BUSCAR TAREFA POR ID")] + BuscarTarefaId = 105, + [Category("CONSTATAMOS UM ERRO AO BUSCAR VENDEDOR USUÁRIO")] + [Description("ERRO AO BUSCAR VENDEDOR USUÁRIO POR ID")] + BuscarVendedorUsuarioId = 106, + [Category("CONSTATAMOS UM ERRO AO BUSCAR AGENDA TELEFONE")] + [Description("ERRO AO BUSCAR AGENDA TELEFONE POR ID")] + BuscarAgendaTelefoneId = 107, + [Category("CONSTATAMOS UM ERRO AO BUSCAR AGENDA EMAIL")] + [Description("ERRO AO BUSCAR AGENDA EMAIL POR ID")] + BuscarAgendaEmailId = 108, + [Category("CONSTATAMOS UM ERRO AO BUSCAR CLIENTE EMAIL")] + [Description("ERRO AO BUSCAR CLIENTE EMAIL POR FILTRO")] + BuscarClienteEmailFiltro = 109, + [Category("CONSTATAMOS UM ERRO AO BUSCAR ESTIPULANTE")] + [Description("ERRO AO BUSCAR ESTIPULANTE POR ID")] + BuscarEstipulanteId = 110, + [Category("CONSTATAMOS UM ERRO AO BUSCAR ESTIPULANTE")] + [Description("ERRO AO BUSCAR ESTIPULANTE POR NOME")] + BuscarEstipulanteNome = 111, + [Category("CONSTATAMOS UM ERRO AO BUSCAR ESTIPULANTES")] + [Description("ERRO AO BUSCAR ESTIPULANTES")] + BuscarEstipulantes = 112, + [Category("CONSTATAMOS UM ERRO AO BUSCAR EMPRESAS")] + [Description("ERRO AO BUSCAR EMPRESAS")] + BuscarEmpresas = 113, + [Category("CONSTATAMOS UM ERRO AO BUSCAR EMPRESA")] + [Description("ERRO AO BUSCAR EMPRESA POR ID")] + BuscarEmpresaId = 114, + [Category("CONSTATAMOS UM ERRO AO BUSCAR SENHA EMPRESA")] + [Description("ERRO AO BUSCAR SENHA EMPRESA")] + BuscarSenhaEmpresa = 115, + [Category("CONSTATAMOS UM ERRO AO BUSCAR PRODUTO")] + [Description("ERRO AO BUSCAR PRODUTO POR ID")] + BuscarProdutoId = 116, + [Category("CONSTATAMOS UM ERRO AO BUSCAR PRODUTO")] + [Description("ERRO AO BUSCAR PRODUTO POR NOME")] + BuscarProdutoNome = 117, + [Category("CONSTATAMOS UM ERRO AO BUSCAR PRODUTOS")] + [Description("ERRO AO BUSCAR PRODUTOS")] + BuscarProdutos = 118, + [Category("CONSTATAMOS UM ERRO AO BUSCAR STATUS")] + [Description("ERRO AO BUSCAR STATUS POR ID")] + BuscarStatusId = 119, + [Category("CONSTATAMOS UM ERRO AO BUSCAR STATUS")] + [Description("ERRO AO BUSCAR STATUS POR NOME")] + BuscarStatusNome = 120, + [Category("CONSTATAMOS UM ERRO AO BUSCAR STATUS")] + [Description("ERRO AO BUSCAR STATUS")] + BuscarStatus = 121, + [Category("CONSTATAMOS UM ERRO AO BUSCAR SÓCIOS")] + [Description("ERRO AO BUSCAR SÓCIOS POR ID")] + BuscarSociosId = 122, + [Category("CONSTATAMOS UM ERRO AO BUSCAR RECIBOS")] + [Description("ERRO AO BUSCAR RECIBOS")] + BuscarRecibos = 123, + [Category("CONSTATAMOS UM ERRO AO BUSCAR CONFIG EXTRATO")] + [Description("ERRO AO BUSCAR CONFIG EXTRATO")] + BuscarConfigExtratoId = 124, + [Category("CONSTATAMOS UM ERRO AO BUSCAR SEGURADORA CONTATO")] + [Description("ERRO AO BUSCAR SEGURADORA CONTATO")] + BuscarContatoSeguradoraIdEmpresa = 125, + [Category("CONSTATAMOS UM ERRO AO BUSCAR SEGURADORA ENDEREÇO")] + [Description("ERRO AO BUSCAR SEGURADORA ENDEREÇO")] + BuscarEnderecoSeguradoraIdEmpresa = 126, + [Category("CONSTATAMOS UM ERRO AO BUSCAR SEGURADORAS")] + [Description("ERRO AO BUSCAR SEGURADORAS")] + BuscarSeguradoras = 127, + [Category("CONSTATAMOS UM ERRO AO BUSCAR SEGURADORA")] + [Description("ERRO AO BUSCAR SEGURADORA POR ID")] + BuscarSeguradora = 128, + [Category("CONSTATAMOS UM ERRO AO BUSCAR AGENDAS")] + [Description("ERRO AO BUSCAR AGENDAS")] + BuscarAgendas = 129, + [Category("CONSTATAMOS UM ERRO AO BUSCAR USUÁRIO")] + [Description("ERRO AO BUSCAR USUÁRIO POR ID")] + BuscarUsuarioId = 130, + [Category("CONSTATAMOS UM ERRO AO BUSCAR USUÁRIOS")] + [Description("ERRO AO BUSCAR USUÁRIOS")] + BuscarUsuarios = 131, + [Category("CONSTATAMOS UM ERRO AO BUSCAR USUÁRIOS")] + [Description("ERRO AO BUSCAR USUÁRIOS POR FILTRO")] + BuscarUsuariosFiltro = 132, + [Category("CONSTATAMOS UM ERRO AO BUSCAR PERMISSÃO AGGILIZADOR")] + [Description("ERRO AO BUSCAR PERMISSÃO AGGILIZADOR")] + BuscarPermissaoAggilizador = 133, + [Category("CONSTATAMOS UM ERRO AO BUSCAR USUÁRIO")] + [Description("ERRO AO BUSCAR USUÁRIO POR LOGIN")] + BuscarUsuarioLogin = 134, + [Category("CONSTATAMOS UM ERRO AO BUSCAR VENDEDORES ATIVOS")] + [Description("ERRO AO BUSCAR VENDEDORES ATIVOS")] + BuscarVendedoresAtivos = 135, + [Category("CONSTATAMOS UM ERRO AO BUSCAR REPASSES")] + [Description("ERRO AO BUSCAR REPASSES POR ID")] + BuscarRepassesId = 136, + [Category("CONSTATAMOS UM ERRO AO BUSCAR REPASSES PARCELA")] + [Description("ERRO AO BUSCAR REPASSES PARCELA POR ID")] + BuscarRepassesParcelaId = 137, + [Category("CONSTATAMOS UM ERRO AO BUSCAR VENDEDOR TELEFONE")] + [Description("ERRO AO BUSCAR VENDEDOR TELEFONE POR ID")] + BuscarVendedorTelefoneId = 138, + [Category("CONSTATAMOS UM ERRO AO BUSCAR VENDEDOR")] + [Description("ERRO AO BUSCAR VENDEDOR POR ID")] + BuscarVendedorId = 139, + [Category("CONSTATAMOS UM ERRO AO BUSCAR VENDEDORES")] + [Description("ERRO AO BUSCAR VENDEDORES")] + BuscarVendedores = 140, + [Category("CONSTATAMOS UM ERRO AO BUSCAR TIPO VENDEDORES")] + [Description("ERRO AO BUSCAR TIPO VENDEDORES")] + BuscarTipoVendedores = 141, + [Category("CONSTATAMOS UM ERRO AO BUSCAR REPASSES")] + [Description("ERRO AO BUSCAR REPASSES")] + BuscarRepasses = 142, + [Category("CONSTATAMOS UM ERRO AO BUSCAR REPASSES")] + [Description("ERRO AO BUSCAR REPASSES POR ID VENDEDOR")] + BuscarRepassesIdVendedor = 143, + [Category("CONSTATAMOS UM ERRO AO BUSCAR BANCOS")] + [Description("ERRO AO BUSCAR BANCOS POR DESCRIÇÃO")] + BuscarBancosDescricao = 144, + [Category("CONSTATAMOS UM ERRO AO BUSCAR BANCOS")] + [Description("ERRO AO BUSCAR BANCOS")] + BuscarBancos = 145, + [Category("CONSTATAMOS UM ERRO AO BUSCAR BANCOS CONTAS")] + [Description("ERRO AO BUSCAR BANCOS CONTAS POR DESCRIÇÃO")] + BuscarBancosContasDescricao = 146, + [Category("CONSTATAMOS UM ERRO AO BUSCAR SALDO")] + [Description("ERRO AO BUSCAR SALDO POR ID")] + BuscarSaldoId = 147, + [Category("CONSTATAMOS UM ERRO AO BUSCAR SALDOS")] + [Description("ERRO AO BUSCAR SALDO POR IDS")] + BuscarSaldosIds = 148, + [Category("CONSTATAMOS UM ERRO AO FECHAR SALDO")] + [Description("ERRO AO FECHAR SALDO")] + FecharSaldo = 149, + [Category("CONSTATAMOS UM ERRO AO BUSCAR SALDOS")] + [Description("ERRO AO BUSCAR SALDOS POR ID")] + BuscarSaldosId = 150, + [Category("CONSTATAMOS UM ERRO AO BUSCAR SALDO")] + [Description("ERRO AO BUSCAR SALDO POR DATA E ID")] + BuscarSaldoDataId = 151, + [Category("CONSTATAMOS UM ERRO AO BUSCAR CENTROS")] + [Description("ERRO AO BUSCAR CENTROS POR DESCRICAO")] + BuscarCentrosDescricao = 152, + [Category("CONSTATAMOS UM ERRO AO BUSCAR CENTROS")] + [Description("ERRO AO BUSCAR CENTROS")] + BuscarCentros = 153, + [Category("CONSTATAMOS UM ERRO AO VERIFICAR SE TEM LANÇAMENTOS POR FORNECEDOR")] + [Description("ERRO AO VERIFICAR SE TEM LANÇAMENTOS POR FORNECEDOR POR ID")] + TemLancamentosFornecedorId = 154, + [Category("CONSTATAMOS UM ERRO AO VERIFICAR SE TIPO VENDEDOR ESTÁ SENDO UTILIZADO")] + [Description("ERRO AO VERIFICAR SE TIPO VENDEDOR ESTÁ SENDO UTILIZADO")] + TipoVendedorUtilizado = 155, + [Category("CONSTATAMOS UM ERRO AO VERIFICAR SE O PARCEIRO ESTÁ SENDO UTILIZADO")] + [Description("ERRO AO VERIFICAR SE O PARCEIRO ESTÁ SENDO UTILIZADO")] + ParceiroUtilizado = 156, + [Category("CONSTATAMOS UM ERRO AO BUSCAR LANÇAMENTOS POR FORNECEDOR")] + [Description("ERRO AO BUSCAR LANÇAMENTOS POR FORNECEDOR POR ID E STATUS")] + BuscarLancamentosFornecedorIdStatus = 157, + [Category("CONSTATAMOS UM ERRO AO BUSCAR LANÇAMENTOS POR CONTROLE")] + [Description("ERRO AO BUSCAR LANÇAMENTOS POR CONTROLE POR ID")] + BuscarLancamentosControleId = 158, + [Category("CONSTATAMOS UM ERRO AO BUSCAR FORNECEDORES")] + [Description("ERRO AO BUSCAR FORNECEDORES POR FILTRO")] + BuscarFornecedoresFiltro = 159, + [Category("CONSTATAMOS UM ERRO AO BUSCAR LANÇAMENTOS POR FORNECEDOR")] + [Description("ERRO AO BUSCAR LANÇAMENTOS POR FORNECEDOR POR VENCIMENTO E STATUS")] + BuscarLancamentosVencimentoStatus = 160, + [Category("CONSTATAMOS UM ERRO AO BUSCAR LANÇAMENTOS")] + [Description("ERRO AO BUSCAR LANÇAMENTOS POR BAIXA")] + BuscarLancamentosBaixa = 161, + [Category("CONSTATAMOS UM ERRO AO BUSCAR LANÇAMENTOS")] + [Description("ERRO AO BUSCAR LANÇAMENTOS POR PAGAMENTO")] + BuscarLancamentosPagamento = 162, + [Category("CONSTATAMOS UM ERRO AO BUSCAR LANÇAMENTO")] + [Description("ERRO AO BUSCAR LANÇAMENTO POR ID E PARCELA")] + BuscarLancamentoIdParcela = 163, + [Category("CONSTATAMOS UM ERRO AO BUSCAR LANÇAMENTO")] + [Description("ERRO AO BUSCAR LANÇAMENTO POR ID")] + BuscarLancamentoId = 164, + [Category("CONSTATAMOS UM ERRO AO BUSCAR LANÇAMENTO")] + [Description("ERRO AO BUSCAR LANÇAMENTO POR CONTA")] + BuscarLancamentosConta = 165, + [Category("CONSTATAMOS UM ERRO AO BUSCAR FORNECEDORES")] + [Description("ERRO AO BUSCAR FORNECEDORES")] + BuscarFornecedores = 166, + [Category("CONSTATAMOS UM ERRO AO BUSCAR PLANO")] + [Description("ERRO AO BUSCAR PLANO")] + BuscarPlano = 167, + [Category("CONSTATAMOS UM ERRO AO BUSCAR PLANOS")] + [Description("ERRO AO BUSCAR PLANOS")] + BuscarPlanos = 168, + [Category("CONSTATAMOS UM ERRO AO BUSCAR RAMOS")] + [Description("ERRO AO BUSCAR RAMOS")] + BuscarRamos = 169, + [Category("CONSTATAMOS UM ERRO AO BUSCAR QUALIFICACAO")] + [Description("ERRO AO BUSCAR QUALIFICACAO")] + BuscarQualificacao = 170, + [Category("CONSTATAMOS UM ERRO AO SALVAR O CLIENTE SELECIONADO")] + [Description("ERRO AO SALVAR CLIENTE")] + SalvarCliente = 171, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR O CLIENTE SELECIONADO")] + [Description("ERRO AO EXCLUIR CLIENTE")] + ExcluirCliente = 172, + [Category("CONSTATAMOS UM ERRO AO CONCLUIR A CRÍTICA DE IMPORTAÇÃO SELECIONADA")] + [Description("ERRO AO CONCLUIR CRÍTICA DE IMPORTAÇÃO")] + SalvarCritica = 173, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR O SINISTRO SELECIONADO")] + [Description("ERRO AO EXCLUIR SINISTRO")] + ExcluirSinistro = 174, + [Category("CONSTATAMOS UM ERRO AO SALVAR O SINISTRO SELECIONADO")] + [Description("ERRO AO SALVAR SINISTRO")] + SalvarSinistro = 175, + [Category("CONSTATAMOS UM ERRO AO BUSCAR SINISTROS")] + [Description("ERRO AO BUSCAR SINISTROS POR FILTRO")] + BuscarSinistrosFiltro = 176, + [Category("CONSTATAMOS UM ERRO AO BUSCAR SINISTROS")] + [Description("ERRO AO BUSCAR SINISTROS POR NÚMERO")] + BuscarSinistrosPorNumero = 177, + [Category("CONSTATAMOS UM ERRO AO BUSCAR SINISTROS")] + [Description("ERRO AO BUSCAR SINISTROS POR CONTROLE")] + BuscarSinistrosPorControle = 178, + [Category("CONSTATAMOS UM ERRO AO SALVAR CONTROLE")] + [Description("ERRO AO SALVAR CONTROLE")] + SlavarControle = 179, + [Category("CONSTATAMOS UM ERRO AO BUSCAR PROFISSÃO")] + [Description("ERRO AO BUSCAR PROFISSÃO POR DESCRIÇÃO")] + BuscarProfissaoDescricao = 180, + [Category("CONSTATAMOS UM ERRO AO BUSCAR ATIVIDADE")] + [Description("ERRO AO BUSCAR ATIVIDADE POR DESCRIÇÃO")] + BuscarAtividadeDescricao = 181, + [Category("CONSTATAMOS UM ERRO AO BUSCAR FABRICANTE")] + [Description("ERRO AO BUSCAR FABRICANTE POR DESCRIÇÃO")] + BuscarFabricanteDescricao = 182, + [Category("CONSTATAMOS UM ERRO AO BUSCAR META VENDEDOR")] + [Description("ERRO AO BUSCAR META VENDEDOR POR ID")] + BuscarMetaVendedorId = 183, + [Category("CONSTATAMOS UM ERRO AO BUSCAR META SEGURADORA")] + [Description("ERRO AO BUSCAR META SEGURADORA POR ID")] + BuscarMetaSeguradoraId = 184, + [Category("CONSTATAMOS UM ERRO AO BUSCAR ADIANTAMENTO VENDEDOR")] + [Description("ERRO AO BUSCAR ADIANTAMENTO POR ID")] + BuscarAdiantamentoId = 185, + [Category("CONSTATAMOS UM ERRO AO CARREGAR PARAMETROS INICIAIS")] + [Description("ERRO AO CARREGAR PARAMETROS INICIAIS")] + CarregarParametrosIniciais = 186, + [Category("CONSTATAMOS UM ERRO AO BUSCAR CREDENCIAIS")] + [Description("ERRO AO BUSCAR CREDENCIAIS")] + BuscarCredenciais = 187, + [Category("CONSTATAMOS UM ERRO AO BUSCAR ARQUIVO DIGITAL")] + [Description("ERRO AO BUSCAR ARQUIVO DIGITAL")] + BuscarArquivoDigital = 188, + [Category("CONSTATAMOS UM ERRO AO SALVAR O PAGAMENTO (REPASSE) DO VENDEDOR")] + [Description("ERRO AO SALVAR PAGAMENTO PARA O VENDEDOR")] + SalvarPagamentoVendedor = 189, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR PARCELA")] + [Description("ERRO AO EXCLUIR PARCELA")] + ExcluirParcela = 190, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR A BAIXA DA PARCELA")] + [Description("ERRO AO EXCLUIR A BAIXA DA PARCELA")] + ExcluirBaixaParcela = 191, + [Category("CONSTATAMOS UM ERRO AO ATUALIZAR EXTRATO DE COMISSÃO")] + [Description("ERRO AO ATUALIZAR EXTRATO DE COMISSÃO")] + AtualizarExtrato = 192, + [Category("CONSTATAMOS UM ERRO AO GERAR PAGAMENTOS PARA OS VENDEDORES SELECIONADOS")] + [Description("ERRO AO GERAR PAGAMENTOS PARA OS VENDEDORES")] + GerarPagamentos = 193, + [Category("CONSTATAMOS UM ERRO AO GERAR PAGAMENTO PARA OS ATENDIMENTOS")] + [Description("ERRO AO GERAR PAGAMENTO PARA OS ATENDIMENTOS")] + GerarPagamentoAtendimentos = 194, + [Category("CONSTATAMOS UM ERRO AO SALVAR O ITEM SELECIONADO")] + [Description("ERRO AO SALVAR ITEM")] + SalvarItem = 195, + [Category("CONSTATAMOS UM ERRO AO SALVAR O ITEM SELECIONADO")] + [Description("ERRO AO SALVAR PATRIMONIAL")] + SalvarPatrimonial = 196, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR O ITEM SELECIONADO")] + [Description("ERRO AO EXCLUIR PATRIMONIAL")] + ExcluirPatrimonial = 197, + [Category("CONSTATAMOS UM ERRO AO SALVAR O ITEM SELECIONADO")] + [Description("ERRO AO SALVAR RISCOS DIVERSOS")] + SalvarRiscosDiversos = 198, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR O ITEM SELECIONADO")] + [Description("ERRO AO EXCLUIR RISCOS DIVERSOS")] + ExcluirRiscosDiversos = 199, + [Category("CONSTATAMOS UM ERRO AO SALVAR O ITEM SELECIONADO")] + [Description("ERRO AO SALVAR VIDA")] + SalvarVida = 200, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR O ITEM SELECIONADO")] + [Description("ERRO AO EXCLUIR VIDA")] + ExcluirVida = 201, + [Category("CONSTATAMOS UM ERRO AO SALVAR O ITEM SELECIONADO")] + [Description("ERRO AO SALVAR AERONÁUTICO")] + SalvarAeronautico = 202, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR O ITEM SELECIONADO")] + [Description("ERRO AO EXCLUIR AERONÁUTICO")] + ExcluirAeronautico = 203, + [Category("CONSTATAMOS UM ERRO AO SALVAR O ITEM SELECIONADO")] + [Description("ERRO AO SALVAR AUTOMOVEL")] + SalvarAuto = 204, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR O ITEM SELECIONADO")] + [Description("ERRO AO EXCLUIR AUTOMOVEL")] + ExcluirAuto = 205, + [Category("CONSTATAMOS UM ERRO AO SALVAR O ITEM SELECIONADO")] + [Description("ERRO AO SALVAR GRANIZO")] + SalvarGranizo = 206, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR O ITEM SELECIONADO")] + [Description("ERRO AO EXCLUIR GRANIZO")] + ExcluirGranizo = 207, + [Category("CONSTATAMOS UM ERRO AO SALVAR AS COBERTURAS")] + [Description("ERRO AO SALVAR COBERTURAS")] + SalvarCoberturas = 208, + [Category("CONSTATAMOS UM ERRO AO SALVAR O ADIANTAMENTO SELECIONADO")] + [Description("ERRO AO SALVAR ADIANTAMENTO")] + SalvarAdiantamento = 209, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR O ADIANTAMENTO SELECIONADO")] + [Description("ERRO AO EXCLUIR ADIANTAMENTO")] + ExcluirAdiantamento = 210, + [Category("CONSTATAMOS UM ERRO AO SALVAR A ATIVIDADE SELECIONADA")] + [Description("ERRO AO SALVAR ATIVIDADE")] + SalvarAtividade = 211, + [Category("CONSTATAMOS UM ERRO AO SALVAR O PERFIL SELECIONADO")] + [Description("ERRO AO SALVAR PERFIL")] + SalvarPerfil = 212, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR O PERFIL SELECIONADO")] + [Description("ERRO AO EXCLUIR PERFIL")] + ExcluirPerfil = 213, + [Category("CONSTATAMOS UM ERRO AO SALVAR A PROFISSÃO SELECIONADA")] + [Description("ERRO AO SALVAR PROFISSÃO")] + SalvarProfissao = 214, + [Category("CONSTATAMOS UM ERRO AO SALVAR A AGENDA SELECIONADA")] + [Description("ERRO AO SALVAR AGENDA")] + SalvarAgenda = 215, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR A AGENDA SELECIONADA")] + [Description("ERRO AO EXCLUIR AGENDA")] + ExcluirAgenda = 216, + [Category("CONSTATAMOS UM ERRO AO SALVAR O EMAIL SELECIONADO")] + [Description("ERRO AO SALVAR EMAIL")] + SalvarEmail = 217, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR O EMAIL SELECIONADO")] + [Description("ERRO AO EXCLUIR EMAIL")] + ExcluirEmail = 218, + [Category("CONSTATAMOS UM ERRO AO SALVAR O ESTIPULANTE SELECIONADO")] + [Description("ERRO AO SALVAR ESTIPULANTE")] + SalvarEstipulante = 219, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR O ESTIPULANTE SELECIONADO")] + [Description("ERRO AO EXCLUIR ESTIPULANTE")] + ExcluirEstipulante = 220, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR O STATUS SELECIONADO")] + [Description("ERRO AO EXCLUIR STATUS")] + ExcluirStatus = 221, + [Category("CONSTATAMOS UM ERRO AO SALVAR META DA SEGURADORA SELECIONADA")] + [Description("ERRO AO SALVAR META DA SEGURADORA")] + SalvarMetaSeguradora = 222, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR META DA SEGURADORA SELECIONADA")] + [Description("ERRO AO EXCLUIR META DA SEGURADORA")] + ExcluirMetaSeguradora = 223, + [Category("CONSTATAMOS UM ERRO AO SALVAR A META DO VENDEDOR SELECIONADO")] + [Description("ERRO AO SALVAR META DO VENDEDOR")] + SalvarMetaVendedor = 224, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR META DO VENDEDOR SELECIONADO")] + [Description("ERRO AO EXCLUIR META DO VENDEDOR")] + ExcluirMetaVendedor = 225, + [Category("CONSTATAMOS UM ERRO AO SALVAR O PRODUTO SELECIONADO")] + [Description("ERRO AO SALVAR PRODUTO")] + SalvarProduto = 226, + [Category("CONSTATAMOS UM ERRO AO SALVAR O STATUS SELECIONADO")] + [Description("ERRO AO SALVAR STATUS")] + SalvarStatus = 227, + [Category("CONSTATAMOS UM ERRO AO SALVAR O RAMO SELECIONADO")] + [Description("ERRO AO SALVAR RAMO")] + SalvarRamo = 228, + [Category("CONSTATAMOS UM ERRO AO SALVAR O QUALIFICACAO")] + [Description("ERRO AO SALVAR QUALIFICACAO")] + SalvarQualificacao = 229, + [Category("CONSTATAMOS UM ERRO AO INSERIR O RAMO SELECIONADO")] + [Description("ERRO AO INSERIR RAMO")] + InserirRamo = 230, + [Category("CONSTATAMOS UM ERRO AO SALVAR O RECIBO SELECIONADO")] + [Description("ERRO AO SALVAR RECIBO")] + SalvarRecibo = 231, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR O RECIBO SELECIONADO")] + [Description("ERRO AO EXCLUIR RECIBO")] + ExcluirRecibo = 232, + [Category("CONSTATAMOS UM ERRO AO SALVAR A SEGURADORA SELECIONADA")] + [Description("ERRO AO SALVAR SEGURADORA")] + SalvarSeguradora = 233, + [Category("CONSTATAMOS UM ERRO AO INSERIR A SEGURADORA SELECIONADA")] + [Description("ERRO AO INSERIR SEGURADORA")] + InserirSeguradora = 234, + [Category("CONSTATAMOS UM ERRO AO SALVAR O SÓCIO SELECIONADO")] + [Description("ERRO AO SALVAR SÓCIO")] + SalvarSocio = 235, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR O SÓCIO SELECIONADO")] + [Description("ERRO AO EXCLUIR SÓCIO")] + ExcluirSocio = 236, + [Category("CONSTATAMOS UM ERRO AO SALVAR O TIPO VENDEDOR SELECIONADO")] + [Description("ERRO AO SALVAR TIPO VENDEDOR")] + SalvarTipoVendedor = 237, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR O TIPO VENDEDOR SELECIONADO")] + [Description("ERRO AO EXCLUIR TIPO VENDEDOR")] + ExcluirTipoVendedor = 238, + [Category("CONSTATAMOS UM ERRO AO SALVAR O USUÁRIO SELECIONADO")] + [Description("ERRO AO SALVAR USUÁRIO")] + SalvarUsuario = 239, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR O USUÁRIO SELECIONADO")] + [Description("ERRO AO EXCLUIR USUÁRIO")] + ExcluirUsuario = 240, + [Category("CONSTATAMOS UM ERRO AO SALVAR O VENDEDOR SELECIONADO")] + [Description("ERRO AO SALVAR VENDEDOR")] + SalvarVendedor = 241, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR O VENDEDOR SELECIONADO")] + [Description("ERRO AO EXCLUIR VENDEDOR")] + ExcluirVendedor = 242, + [Category("CONSTATAMOS UM ERRO AO SALVAR O FORNECEDOR SELECIONADO")] + [Description("ERRO AO SALVAR FORNECEDOR")] + SalvarFornecedor = 243, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR O FORNECEDOR SELECIONADO")] + [Description("ERRO AO EXCLUIR FORNECEDOR")] + ExcluirFornecedor = 244, + [Category("CONSTATAMOS UM ERRO AO SALVAR O BANCO E CONTA SELECIONADO")] + [Description("ERRO AO SALVAR BANCO E CONTA")] + SalvarBancoConta = 245, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR O BANCO E CONTA SELECIONADO")] + [Description("ERRO AO EXCLUIR BANCO E CONTA")] + ExcluirBancoConta = 246, + [Category("CONSTATAMOS UM ERRO AO SALVAR O SALDO SELECIONADO")] + [Description("ERRO AO SALVAR SALDO")] + SalvarSaldo = 247, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR O SALDO SELECIONADO")] + [Description("ERRO AO EXCLUIR SALDO")] + ExcluirSaldo = 248, + [Category("CONSTATAMOS UM ERRO AO SALVAR O CENTRO DE CUSTO SELECIONADO")] + [Description("ERRO AO SALVAR CENTRO DE CUSTO")] + SalvarCentro = 249, + [Category("CONSTATAMOS UM ERRO AO SALVAR O PLANO DE SERVIÇO SELECIONADO")] + [Description("ERRO AO SALVAR PLANO DE SERVIÇO")] + SalvarPlano = 250, + [Category("CONSTATAMOS UM ERRO AO SALVAR O PLANOS DE SERVIÇO SELECIONADO")] + [Description("ERRO AO SALVAR PLANOS DE SERVIÇO")] + SalvarPlanos = 251, + [Category("CONSTATAMOS UM ERRO AO SALVAR O ARQUIVO DIGITAL SELECIONADO")] + [Description("ERRO AO SALVAR ARQUIVO DIGITAL")] + SalvarAd = 252, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR O ARQUIVO DIGITAL SELECIONADO")] + [Description("ERRO AO EXCLUIR ARQUIVO DIGITAL")] + ExcluirAd = 253, + [Category("CONSTATAMOS UM ERRO AO SALVAR A MALA DIRETA SELECIONADA")] + [Description("ERRO AO SALVAR MALA DIRETA")] + SalvarMalaDireta = 254, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR A MALA DIRETA SELECIONADA")] + [Description("ERRO AO EXCLUIR MALA DIRETA")] + ExcluirMalaDireta = 255, + [Category("CONSTATAMOS UM ERRO AO SALVAR O PARCEIRO SELECIONADO")] + [Description("ERRO AO SALVAR PARCEIRO")] + SalvarParceiro = 256, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR O PARCEIRO SELECIONADO")] + [Description("ERRO AO EXCLUIR PARCEIRO")] + ExcluirParceiro = 257, + [Category("CONSTATAMOS UM ERRO AO SALVAR AS PERMISSÕES DO USUÁRIO SELECIONADO")] + [Description("ERRO AO SALVAR PERMISSÕES DO USUÁRIO")] + SalvarPermissao = 258, + [Category("CONSTATAMOS UM ERRO AO SALVAR A PROSPECÇÃO SELECIONADA")] + [Description("ERRO AO SALVAR PROSPECÇÃO")] + SalvarProspeccao = 259, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR A PROSPECÇÃO SELECIONADA")] + [Description("ERRO AO EXCLUIR PROSPECÇÃO")] + ExcluirProspeccao = 260, + [Category("CONSTATAMOS UM ERRO AO SALVAR AS RESTRIÇÕES DO USUÁRIO SELECIONADO")] + [Description("ERRO AO SALVAR RESTRIÇÕES DO USUÁRIO")] + SalvarRestricao = 261, + [Category("CONSTATAMOS UM ERRO AO SALVAR OS DETALHES DO EXTRATO SELECIONADO")] + [Description("ERRO AO SALVAR OS DETALHES DO EXTRATO")] + SalvarDetalheExtrato = 262, + [Category("CONSTATAMOS UM ERRO AO SALVAR O EXTRATO SELECIONADO")] + [Description("ERRO AO SALVAR EXTRATO")] + SalvarExtrato = 263, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR O EXTRATO SELECIONADO")] + [Description("ERRO AO EXCLUIR EXTRATO")] + ExcluirExtrato = 264, + [Category("CONSTATAMOS UM ERRO AO SALVAR A TAREFA SELECIONADA")] + [Description("ERRO AO SALVAR TAREFA")] + SalvarTarefa = 265, + [Category("CONSTATAMOS UM ERRO AO VALIDAR ANALITICO POR ID E TRILHAID")] + [Description("ERRO AO VALIDAR ANALITICO POR ID E TRILHAID")] + ValidarAnaliticoIdTrilhaId = 266, + [Category("CONSTATAMOS UM ERRO AO SALVAR A TRILHA SELECIONADA")] + [Description("ERRO AO SALVAR TRILHA")] + SalvarTrilha = 267, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR A TAREFA SELECIONADA")] + [Description("ERRO AO EXCLUIR TAREFA")] + ExcluirTarefa = 268, + [Category("CONSTATAMOS UM ERRO AO SALVAR A FASE SELECIONADA")] + [Description("ERRO AO SALVAR FASE")] + SalvarFase = 269, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR A FASE SELECIONADA")] + [Description("ERRO AO EXCLUIR FASE")] + ExcluirFase = 270, + [Category("CONSTATAMOS UM ERRO AO SALVAR O VÍNCULO DE VENDEDOR COM O USUÁRIO SELECIONADO")] + [Description("ERRO AO SALVAR VÍNCULO DE VENDEDOR COM USUÁRIO")] + SalvarVendedorUsuario = 271, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR O VÍNCULO DE VENDEDOR COM O USUÁRIO SELECIONADO")] + [Description("ERRO AO EXCLUIR VÍNCULO DE VENDEDOR COM USUÁRIO")] + ExcluirVendedorUsuario = 272, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR A INSTALAÇÃO SELECIONADA")] + [Description("ERRO AO EXCLUIR INSTALAÇÃO")] + ExcluirInstalacao = 273, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR ITEM")] + [Description("ERRO AO EXCLUIR ITEM")] + ExcluirItem = 274, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR ITENS")] + [Description("ERRO AO EXCLUIR ITENS")] + ExcluirItens = 275, + [Category("CONSTATAMOS UM ERRO AO SALVAR ITENS")] + [Description("ERRO AO SALVAR ITENS")] + SalvarItens = 276, + [Category("CONSTATAMOS UM ERRO AO SALVAR A EMPRESA SELECIONADA")] + [Description("ERRO AO SALVAR EMPRESA")] + SalvarEmpresa = 277, + [Category("CONSTATAMOS UM ERRO AO SALVAR O ARQUIVO ENVIADO PARA ASSINATURA DIGITAL")] + [Description("ERRO AO SALVAR ARQUIVO ASSINTATURA DIGITAL")] + SalvarArquivoAssinado = 278, + [Category("CONSTATAMOS UM ERRO AO SALVAR O LANÇAMENTO SELECIONADO")] + [Description("ERRO AO SALVAR LANÇAMENTO")] + SalvarLancamento = 279, + [Category("CONSTATAMOS UM ERRO AO ATUALIZAR O LANÇAMENTO SELECIONADO")] + [Description("ERRO AO ATUALIZAR LANÇAMENTO")] + AtualizarLancamento = 280, + [Category("CONSTATAMOS UM ERRO AO INCLUIR O LANÇAMENTO SELECIONADO")] + [Description("ERRO AO INCLUIR LANÇAMENTO")] + IncluirLancamento = 281, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR O LANÇAMENTO SELECIONADO")] + [Description("ERRO AO EXCLUIR LANÇAMENTO")] + ExcluirLancamento = 282, + [Category("CONSTATAMOS UM ERRO NA TRANSFERÊNCIA SELECIONADA")] + [Description("ERRO AO TRANSFERIR")] + Transferir = 283, + [Category("CONSTATAMOS UM ERRO AO BUSCAR METAS DE SEGURADORAS")] + [Description("ERRO AO BUSCAR METAS DE SEGURADORAS")] + BuscarMetasSeguradora = 284, + [Category("CONSTATAMOS UM ERRO AO BUSCAR METAS DE VENDEDORES")] + [Description("ERRO AO BUSCAR METAS DE VENDEDORES")] + BuscarMetasVendedor = 285, + [Category("CONSTATAMOS UM ERRO AO BUSCAR CLIENTES ATIVOS/INATIVOS")] + [Description("ERRO AO BUSCAR CLIENTES ATIVOS/INATIVOS")] + BuscarClienteAtivosInativos = 286, + [Category("ERRO AO VERIFICAR VERSÃO")] + [Description("ERRO AO VERIFICAR VERSÃO")] + VerificarVersao = 287, + [Category("CONFIGURAR ARQUIVO DIGITAL")] + [Description("CONFIGURAR ARQUIVO DIGITAL")] + CriarBancoAd = 288, + [Category("CONSTATAMOS UM ERRO AO BUSCAR EXPEDIÇÃO")] + [Description("ERRO AO BUSCAR EXPEDIÇÃO")] + BuscarExpedicao = 289, + [Category("CONSTATAMOS UM ERRO AO SALVAR A EXPEDIÇÃO SELECIONADA")] + [Description("ERRO AO SALVAR EXPEDIÇÃO")] + SalvarExpedicao = 290, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR A EXPEDIÇÃO SELECIONADA")] + [Description("ERRO AO EXCLUIR EXPEDIÇÃO")] + ExcluirExpedicao = 291, + [Category("CONSTATAMOS UM ERRO AO DESFAZER PARCELA")] + [Description("ERRO AO DESFAZER PARCELA")] + DesfazerParcela = 292, + [Category("CONSTATAMOS UM ERRO AO SINCRONIZAR APOLICES PENDENTES")] + [Description("ERRO AO SINCRONIZAR APOLICES PENDENTES")] + SincronizarApolicePendente = 293, + [Category("CONSTATAMOS UM ERRO AO GERAR FECHAMENTO FINANCEIRO")] + [Description("ERRO AO GERAR FECHAMENTO FINANCEIRO")] + BuscarFechamentoFinanceiro = 294, + [Category("CONSTATAMOS UM ERRO AO BUSCAR LICENCIAMENTOS POR PERIODO E FILTRO")] + [Description("ERRO AO BUSCAR LICENCIAMENTOS POR PERIODO E FILTRO")] + BuscarLicenciamentos = 295, + [Category("CONSTATAMOS UM ERRO AO BUSCAR A PLANILHA COMPLETA")] + [Description("ERRO AO BUSCAR PLANILHA COMPLETA POR ID DO DOCUMENTO")] + BuscarPlanilhaCompletaId = 296, + [Category("CONSTATAMOS UM ERRO AO BUSCAR CONFIGURAÇÕES")] + [Description("ERRO AO BUSCAR CONFIGURAÇÕES")] + BuscarConfiguracoes = 297, + [Category("CONSTATAMOS UM ERRO AO INCLUR CONFIGURACAO")] + [Description("ERRO AO INCLUR CONFIGURACAO")] + IncluirConfuguracao = 298, + [Category("CONSTATAMOS UM ERRO AO BUSCAR PARCELA PENDENTE DE PAGAMENTO")] + [Description("ERRO AO BUSCAR PARCELA PENDENTE DE PAGAMENTO")] + BuscarParcelaPendente = 299, + [Category("CONSTATAMOS UM ERRO AO SINCRONIZAR PARCELA PENDENTE")] + [Description("ERRO AO SINCRONIZAR PARCELA PENDENTE")] + SincronizarParcelaPendente = 300, + [Category("CONSTATAMOS UM ERRO AO BUSCAR PARAMETROS DO RELATORIO SELECIONADO")] + [Description("ERRO AO BUSCAR PARAMETROS DO RELATORIO")] + BuscarParametrosRelatorio = 301, + [Category("CONSTATAMOS UM ERRO AO BUSCAR PARAMETROS DE TOTALIZAÇÃO SELECIONADO")] + [Description("ERRO AO BUSCAR PARAMETROS DE TOTALIZAÇÃO")] + BuscarParametrosTotalizacao = 302, + [Category("CONSTATAMOS UM ERRO AO SALVAR PARAMETROS DO RELATORIO SELECIONADO")] + [Description("ERRO AO SALVAR PARAMETROS DO RELATORIO")] + SalvarParametrosRelatorio = 303, + [Category("CONSTATAMOS UM ERRO AO SALVAR PARAMETROS DE TOTALIZAÇÃO SELECIONADO")] + [Description("ERRO AO SALVAR PARAMETROS DE TOTALIZAÇÃO")] + SalvarParametrosTotalizacao = 304, + [Category("CONSTATAMOS UM ERRO AO BUSCAR OS ITENS")] + [Description("ERRO AO BUSCAR ITENS POR IDDOCUMENTO")] + BuscarItensIdDocumento = 305, + [Category("CONSTATAMOS UM ERRO AO SALVAR O TIPO DE TAREFA SELECIONADO")] + [Description("ERRO AO SALVAR TIPO DE TAREFA")] + SalvarTipoTarefa = 306, + [Category("CONSTATAMOS UM ERRO AO SALVAR O STATUS DE PROSPECÇÃO")] + [Description("ERRO AO SALVAR STATUS DE PROSPECÇÃO")] + SalvarStatusProspeccao = 307, + [Category("CONSTATAMOS UM ERRO AO BUSCAR TIPOS DE TAREFA")] + [Description("ERRO AO BUSCAR TIPOS DE TAREFA")] + BuscarTiposTarefa = 308, + [Category("CONSTATAMOS UM ERRO AO BUSCAR TAREFAS POR TIPO")] + [Description("ERRO AO BUSCAR TAREFAS POR TIPO")] + BuscarTarefasPorTipo = 309, + [Category("CONSTATAMOS UM ERRO AO BUSCAR PROSPECÇÕES POR STATUS")] + [Description("ERRO AO BUSCAR PROSPECÇÕES POR STATUS")] + BuscarProspeccoesPorStatus = 310, + [Category("CONSTATAMOS UM ERRO AO SALVAR VINCULO DE REPASSES")] + [Description("ERRO AO SALVAR VINCULO DE REPASSES")] + SalvarVinculoRepasse = 311, + [Category("CONSTATAMOS UM ERRO AO BUSCAR NOTAS FISCAIS")] + [Description("ERRO AO BUSCAR NOTAS FISCAIS")] + BuscarNotasFiscais = 312, + [Category("CONSTATAMOS UM ERRO AO SALVAR A NOTA FISCAL SELECIONADA")] + [Description("ERRO AO SALVAR NOTA FISCAL")] + SalvarNotaFiscal = 313, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR A NOTA FISCAL SELECIONADO")] + [Description("ERRO AO EXCLUIR NOTA FISCAL")] + ExcluirNotaFiscal = 314, + [Category("CONSTATAMOS UM ERRO AO BUSCAR NOTAS FISCAIS NO RELATÓRIO")] + [Description("ERRO AO BUSCAR NOTAS FISCAIS NO RELATÓRIO")] + BuscarNotasFiscaisRelatorio = 315, + [Category("CONSTATAMOS UM ERRO AO BUSCAR PREVISÃO DE PAGAMENTO DE COMISSÃO")] + [Description("ERRO AO BUSCAR PREVISÃO DE PAGAMENTO DE COMISSÃO")] + BuscarPrevisaoPagamentoComissao = 316, + [Category("CONSTATAMOS UM ERRO AO BUSCAR OS PARAMETROS DE IMPOSTO")] + [Description("ERRO AO BUSCAR PARAMETROS DE IMPOSTO")] + BuscarImpostos = 317, + [Category("CONSTATAMOS UM ERRO AO SALVAR O PARAMETRO DE IMPOSTO")] + [Description("ERRO AO SALVAR PARAMETROS DE IMPOSTO")] + SalvarImposto = 318, + [Category("CONSTATAMOS UM ERRO AO BUSCAR LOG DO SISTEMA ANTIGO")] + [Description("ERRO AO BUSCAR LOG SISTEMA ANTIGO")] + BuscarLogAntigo = 319, + [Category("CONSTATAMOS UM ERRO AO SALVAR O LOG DO PROCEDIMENTO EXECUTADO")] + [Description("ERRO AO SALVAR LOG DE AÇÃO")] + SalvarAction = 320, + [Category("CONSTATAMOS UM ERRO AO BUSCAR LOG DE UTILIZAÇÃO")] + [Description("ERRO AO BUSCAR LOG DE UTILIZAÇÃO")] + BuscarAction = 321, + [Category("CONSTATAMOS UM ERRO AO BUSCAR FATURAS")] + [Description("ERRO AO BUSCAR FATURAS POR NÚMERO")] + BuscarFaturaPorNumero = 322, + [Category("CONSTATAMOS UM ERRO AO BUSCAR LANÇAMENTO PELO CÓDIGO BANCÁRIO")] + [Description("ERRO AO BUSCAR LANÇAMENTO PELO CÓDIGO BANCÁRIO")] + BuscarLancamentoCodigoBanco = 323, + [Category("CONSTATAMOS UM ERRO AO BUSCAR OS CLIENTES PARA PROSPECTAR NOVAS VENDAS")] + [Description("ERRO AO BUSCAR CLIENTES PARA PROSPECTAR")] + Prospectar = 324, + [Category("CONSTATAMOS UM ERRO AO TROCAR APÓLICE DE UM CLIENTE PARA OUTRO")] + [Description("ERRO AO TROCAR CLIENTE")] + TrocarCliente = 325, + [Category("CONSTATAMOS UM ERRO AO BUSCAR ORIGENS DO CLIENTE")] + [Description("ERRO AO BUSCAR ORIGENS DO CLIENTE")] + BuscarOrigensClienteId = 326, + [Category("CONSTATAMOS UM ERRO AO BUSCAR PLACAS POR PERIODO E FILTRO")] + [Description("ERRO AO BUSCAR PLACAS POR PERIODO E FILTRO")] + BuscarPlacas = 327, + [Category("CONSTATAMOS UM ERRO AO BUSCAR DATA DE NASCIMENTO")] + [Description("ERRO AO BUSCAR DATA DE NASCIMENTO")] + BuscarNascimento = 328, + [Category("CONSTATAMOS UM ERRO AO BUSCAR LANÇAMENTOS POR DATA LANÇAMENTO")] + [Description("ERRO AO BUSCAR LANÇAMENTOS POR DATA LANÇAMENTO E STATUS")] + BuscarLancamentosPorDataLancamento = 329, + [Category("CONSTATAMOS UM ERRO AO BUSCAR O RISCOS DIVERSOS")] + [Description("ERRO AO BUSCAR CONSORCIO POR ID")] + BuscarConsorcioId = 330, + [Category("CONSTATAMOS UM ERRO AO SALVAR O ITEM SELECIONADO")] + [Description("ERRO AO SALVAR CONSORCIO")] + SalvarConsorcio = 331, + [Category("CONSTATAMOS UM ERRO AO EXCLUIR O CONSORCIO SELECIONADO")] + [Description("ERRO AO EXCLUIR CONSORCIO")] + ExcluirConsorcio = 332, + [Category("CONSTATAMOS UM ERRO INESPERADO")] + [Description("ERRO INESPERADO")] + Inesperado = 1000, + [Category("CONSTATAMOS QUE NÃO HÁ ESPAÇO LIVRE EM DISCO SUFICENTE PARA A ATUALIZAÇÃO DO SISTEMA.")] + [Description("ERRO AO ATUALIZAR")] + EspacoLivre = 1001 + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.API/TokenSso.cs b/Codemerx/Gestor.Model/Model.API/TokenSso.cs new file mode 100644 index 0000000..ec028b5 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.API/TokenSso.cs @@ -0,0 +1,36 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.API +{ + public class TokenSso + { + public double Expires + { + get; + set; + } + + public string Token + { + get; + set; + } + + public string Type + { + get; + set; + } + + public UserSso User + { + get; + set; + } + + public TokenSso() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.API/UploadFile.cs b/Codemerx/Gestor.Model/Model.API/UploadFile.cs new file mode 100644 index 0000000..fe8699f --- /dev/null +++ b/Codemerx/Gestor.Model/Model.API/UploadFile.cs @@ -0,0 +1,61 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.API +{ + public class UploadFile + { + private string _extensao; + + public int Ano + { + get; + set; + } + + public byte[] Arquivo + { + get; + set; + } + + public string Extensao + { + get + { + return this._extensao; + } + set + { + string lower; + if (value != null) + { + string str = value.Trim(); + if (str != null) + { + lower = str.ToLower(); + } + else + { + lower = null; + } + } + else + { + lower = null; + } + this._extensao = lower; + } + } + + public Guid Id + { + get; + set; + } + + public UploadFile() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.API/UserSso.cs b/Codemerx/Gestor.Model/Model.API/UserSso.cs new file mode 100644 index 0000000..ce62ae9 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.API/UserSso.cs @@ -0,0 +1,78 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.API +{ + public class UserSso + { + public string CustomerDocument + { + get; + set; + } + + public string Document + { + get; + set; + } + + public string Email + { + get; + set; + } + + public string Id + { + get; + set; + } + + public long IdEmpresa + { + get; + set; + } + + public bool IsDeleted + { + get; + set; + } + + public string Name + { + get; + set; + } + + public string Password + { + get; + set; + } + + public string Phone + { + get; + set; + } + + public string Serial + { + get; + set; + } + + public string Username + { + get; + set; + } + + public UserSso() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.API/UsuarioCentralSegurado.cs b/Codemerx/Gestor.Model/Model.API/UsuarioCentralSegurado.cs new file mode 100644 index 0000000..327d282 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.API/UsuarioCentralSegurado.cs @@ -0,0 +1,112 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.API +{ + public class UsuarioCentralSegurado + { + public bool Admin + { + get; + set; + } + + public string Bairro + { + get; + set; + } + + public string Cep + { + get; + set; + } + + public string Cidade + { + get; + set; + } + + public string Corretora + { + get; + set; + } + + public string Documento + { + get; + set; + } + + public string Email + { + get; + set; + } + + public string Estado + { + get; + set; + } + + public long FornecedorId + { + get; + set; + } + + public string Id { get; set; } = string.Empty; + + public long IdEmpresa { get; set; } = (long)1; + + public string Nome + { + get; + set; + } + + public string Numero + { + get; + set; + } + + public string Rua + { + get; + set; + } + + public string Senha + { + get; + set; + } + + public string Serial + { + get; + set; + } + + public string Telefone + { + get; + set; + } + + public string UriCorretora + { + get; + set; + } + + public UsuarioCentralSegurado() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.API/Version.cs b/Codemerx/Gestor.Model/Model.API/Version.cs new file mode 100644 index 0000000..78da24d --- /dev/null +++ b/Codemerx/Gestor.Model/Model.API/Version.cs @@ -0,0 +1,60 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.API +{ + public class Version + { + public string Beta + { + get; + set; + } + + public DateTime Data + { + get; + set; + } + + public bool Erro + { + get; + set; + } + + public string Name + { + get; + set; + } + + public bool Obrigatorio + { + get; + set; + } + + public string Status + { + get; + set; + } + + public string Uri + { + get; + set; + } + + public string VersaoAplicacao + { + get; + set; + } + + public Version() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Attributes/EntityAttribute.cs b/Codemerx/Gestor.Model/Model.Attributes/EntityAttribute.cs new file mode 100644 index 0000000..46113ad --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Attributes/EntityAttribute.cs @@ -0,0 +1,40 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Attributes +{ + [AttributeUsage(AttributeTargets.All)] + public class EntityAttribute : Attribute + { + public virtual string Description + { + get + { + return this.DescriptionValue; + } + } + + protected string DescriptionValue + { + get + { + return this.Tipo; + } + set + { + this.Tipo = value; + } + } + + public string Tipo + { + get; + set; + } + + public EntityAttribute(string tipo) + { + this.Tipo = tipo; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Attributes/ForceLogAttribute.cs b/Codemerx/Gestor.Model/Model.Attributes/ForceLogAttribute.cs new file mode 100644 index 0000000..a9b0f20 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Attributes/ForceLogAttribute.cs @@ -0,0 +1,39 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Attributes +{ + public class ForceLogAttribute : Attribute + { + public virtual bool Description + { + get + { + return this.DescriptionValue; + } + } + + protected bool DescriptionValue + { + get + { + return this.Log; + } + set + { + this.Log = value; + } + } + + public bool Log + { + get; + set; + } + + public ForceLogAttribute(bool log = true) + { + this.Log = log; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Attributes/HelpAttribute.cs b/Codemerx/Gestor.Model/Model.Attributes/HelpAttribute.cs new file mode 100644 index 0000000..54ed201 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Attributes/HelpAttribute.cs @@ -0,0 +1,40 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Attributes +{ + [AttributeUsage(AttributeTargets.All)] + public class HelpAttribute : Attribute + { + public virtual string Description + { + get + { + return this.DescriptionValue; + } + } + + protected string DescriptionValue + { + get + { + return this.Tipo; + } + set + { + this.Tipo = value; + } + } + + public string Tipo + { + get; + set; + } + + public HelpAttribute(string tipo) + { + this.Tipo = tipo; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Attributes/LogAttribute.cs b/Codemerx/Gestor.Model/Model.Attributes/LogAttribute.cs new file mode 100644 index 0000000..ca9e763 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Attributes/LogAttribute.cs @@ -0,0 +1,40 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Attributes +{ + [AttributeUsage(AttributeTargets.All)] + public class LogAttribute : Attribute + { + public virtual bool Description + { + get + { + return this.DescriptionValue; + } + } + + protected bool DescriptionValue + { + get + { + return this.Log; + } + set + { + this.Log = value; + } + } + + public bool Log + { + get; + set; + } + + public LogAttribute(bool log = true) + { + this.Log = log; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Attributes/NameAttribute.cs b/Codemerx/Gestor.Model/Model.Attributes/NameAttribute.cs new file mode 100644 index 0000000..fd04e69 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Attributes/NameAttribute.cs @@ -0,0 +1,40 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Attributes +{ + [AttributeUsage(AttributeTargets.All)] + public class NameAttribute : Attribute + { + public virtual bool Description + { + get + { + return this.DescriptionValue; + } + } + + protected bool DescriptionValue + { + get + { + return this.Log; + } + set + { + this.Log = value; + } + } + + public bool Log + { + get; + set; + } + + public NameAttribute(bool log = true) + { + this.Log = log; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Attributes/OldValue2Attribute.cs b/Codemerx/Gestor.Model/Model.Attributes/OldValue2Attribute.cs new file mode 100644 index 0000000..83fb5cf --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Attributes/OldValue2Attribute.cs @@ -0,0 +1,20 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Attributes +{ + [AttributeUsage(AttributeTargets.Field)] + public class OldValue2Attribute : Attribute + { + public string OldValue2 + { + get; + private set; + } + + public OldValue2Attribute(string oldValue) + { + this.OldValue2 = oldValue; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Attributes/OldValueAttribute.cs b/Codemerx/Gestor.Model/Model.Attributes/OldValueAttribute.cs new file mode 100644 index 0000000..4f8c17c --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Attributes/OldValueAttribute.cs @@ -0,0 +1,20 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Attributes +{ + [AttributeUsage(AttributeTargets.Field)] + public class OldValueAttribute : Attribute + { + public string OldValue + { + get; + private set; + } + + public OldValueAttribute(string oldValue) + { + this.OldValue = oldValue; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Attributes/TipoAttribute.cs b/Codemerx/Gestor.Model/Model.Attributes/TipoAttribute.cs new file mode 100644 index 0000000..f4590da --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Attributes/TipoAttribute.cs @@ -0,0 +1,40 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Attributes +{ + [AttributeUsage(AttributeTargets.All)] + public class TipoAttribute : Attribute + { + public virtual string Description + { + get + { + return this.DescriptionValue; + } + } + + protected string DescriptionValue + { + get + { + return this.Tipo; + } + set + { + this.Tipo = value; + } + } + + public string Tipo + { + get; + set; + } + + public TipoAttribute(string tipo) + { + this.Tipo = tipo; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Attributes/WidthAttribute.cs b/Codemerx/Gestor.Model/Model.Attributes/WidthAttribute.cs new file mode 100644 index 0000000..af31e8f --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Attributes/WidthAttribute.cs @@ -0,0 +1,40 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Attributes +{ + [AttributeUsage(AttributeTargets.All)] + public class WidthAttribute : Attribute + { + public virtual string Description + { + get + { + return this.DescriptionValue; + } + } + + protected string DescriptionValue + { + get + { + return this.Tipo; + } + set + { + this.Tipo = value; + } + } + + public string Tipo + { + get; + set; + } + + public WidthAttribute(string tipo) + { + this.Tipo = tipo; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.CalculoWeb/Auto/CalculoAuto.cs b/Codemerx/Gestor.Model/Model.CalculoWeb/Auto/CalculoAuto.cs new file mode 100644 index 0000000..770eaa0 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.CalculoWeb/Auto/CalculoAuto.cs @@ -0,0 +1,61 @@ +using Gestor.Model.CalculoWeb; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.CalculoWeb.Auto +{ + public class CalculoAuto + { + public Gestor.Model.CalculoWeb.Auto.Caminhao Caminhao + { + get; + set; + } + + public CoberturaAuto Cobertura + { + get; + set; + } + + public Gestor.Model.CalculoWeb.Auto.CondutorPrincipal CondutorPrincipal + { + get; + set; + } + + public QuestionarioAuto Questionario + { + get; + set; + } + + public Gestor.Model.CalculoWeb.Segurado Segurado + { + get; + set; + } + + public Gestor.Model.CalculoWeb.Seguro Seguro + { + get; + set; + } + + public int TipoVeiculo + { + get; + set; + } + + public Gestor.Model.CalculoWeb.Auto.Veiculo Veiculo + { + get; + set; + } + + public CalculoAuto() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.CalculoWeb/Auto/Caminhao.cs b/Codemerx/Gestor.Model/Model.CalculoWeb/Auto/Caminhao.cs new file mode 100644 index 0000000..dba0c83 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.CalculoWeb/Auto/Caminhao.cs @@ -0,0 +1,78 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.CalculoWeb.Auto +{ + public class Caminhao + { + public string Carga + { + get; + set; + } + + public string Carroceria + { + get; + set; + } + + public string Equipamento + { + get; + set; + } + + public string Garagem + { + get; + set; + } + + public string GerenciamentoRisco + { + get; + set; + } + + public int Id + { + get; + set; + } + + public string Periodo + { + get; + set; + } + + public string ProprioEstado + { + get; + set; + } + + public string RegiaoCirculacao + { + get; + set; + } + + public string SeguroCarga + { + get; + set; + } + + public string Uso + { + get; + set; + } + + public Caminhao() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.CalculoWeb/Auto/CoberturaAuto.cs b/Codemerx/Gestor.Model/Model.CalculoWeb/Auto/CoberturaAuto.cs new file mode 100644 index 0000000..b97f258 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.CalculoWeb/Auto/CoberturaAuto.cs @@ -0,0 +1,132 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.CalculoWeb.Auto +{ + public class CoberturaAuto + { + public string ArCondicionado + { + get; + set; + } + + public string Assistencia + { + get; + set; + } + + public decimal Blindagem + { + get; + set; + } + + public decimal Carroceria + { + get; + set; + } + + public string CarroReserva + { + get; + set; + } + + public string DanosCorporais + { + get; + set; + } + + public string DanosMateriais + { + get; + set; + } + + public string DanosMorais + { + get; + set; + } + + public string DespesasExtras + { + get; + set; + } + + public decimal Equipamento + { + get; + set; + } + + public decimal FatorAjuste + { + get; + set; + } + + public string GarantiaZero + { + get; + set; + } + + public int Id + { + get; + set; + } + + public decimal KitGas + { + get; + set; + } + + public string MorteInvalidez + { + get; + set; + } + + public string ProtecaoBuracos + { + get; + set; + } + + public string ReparoRapido + { + get; + set; + } + + public string TipoCobertura + { + get; + set; + } + + public string TipoFranquia + { + get; + set; + } + + public string Vidros + { + get; + set; + } + + public CoberturaAuto() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.CalculoWeb/Auto/ComissaoSeguradora.cs b/Codemerx/Gestor.Model/Model.CalculoWeb/Auto/ComissaoSeguradora.cs new file mode 100644 index 0000000..f19675c --- /dev/null +++ b/Codemerx/Gestor.Model/Model.CalculoWeb/Auto/ComissaoSeguradora.cs @@ -0,0 +1,24 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.CalculoWeb.Auto +{ + public class ComissaoSeguradora + { + public long Seguradora + { + get; + set; + } + + public decimal Valor + { + get; + set; + } + + public ComissaoSeguradora() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.CalculoWeb/Auto/CondutorPrincipal.cs b/Codemerx/Gestor.Model/Model.CalculoWeb/Auto/CondutorPrincipal.cs new file mode 100644 index 0000000..84810f9 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.CalculoWeb/Auto/CondutorPrincipal.cs @@ -0,0 +1,127 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.CalculoWeb.Auto +{ + public class CondutorPrincipal + { + private string _sexo; + + private string _estadoCivil; + + public string CpfCnpj + { + get; + set; + } + + public DateTime? DataHabilitacao + { + get; + set; + } + + public DateTime? DataNascimento + { + get; + set; + } + + public string EstadoCivil + { + get + { + return this._estadoCivil; + } + set + { + this._estadoCivil = value; + value = this.ConvertEstCivCalculo(this._estadoCivil); + } + } + + public long Id + { + get; + set; + } + + public string NomeCompleto + { + get; + set; + } + + public string NumeroHabilitacao + { + get; + set; + } + + public string Sexo + { + get + { + return this._sexo; + } + set + { + this._sexo = value; + this.ConvertSexoCalculo(this._sexo); + } + } + + public string TempoHabilitacao + { + get; + set; + } + + public CondutorPrincipal() + { + } + + private string ConvertEstCivCalculo(string estadoCivil) + { + if (estadoCivil != null && estadoCivil.Length == 1) + { + switch (estadoCivil[0]) + { + case '0': + { + return "1"; + } + case '1': + { + return "2"; + } + case '2': + { + return "3"; + } + case '3': + case '5': + case '6': + case '7': + { + return "4"; + } + case '4': + { + return "5"; + } + } + } + return string.Empty; + } + + private string ConvertSexoCalculo(string sexo) + { + if (sexo != "0") + { + return "2"; + } + return "1"; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.CalculoWeb/Auto/Fipe.cs b/Codemerx/Gestor.Model/Model.CalculoWeb/Auto/Fipe.cs new file mode 100644 index 0000000..1f4bee6 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.CalculoWeb/Auto/Fipe.cs @@ -0,0 +1,84 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.CalculoWeb.Auto +{ + public class Fipe + { + public string AnoMaximo + { + get; + set; + } + + public string AnoMinimo + { + get; + set; + } + + public string AnoModelo + { + get; + set; + } + + public string Codigo + { + get; + set; + } + + public string Combustivel + { + get; + set; + } + + public int Id + { + get; + set; + } + + public string Marca + { + get; + set; + } + + public string Modelo + { + get; + set; + } + + public int TipoVeiculo + { + get; + set; + } + + public decimal Valor + { + get; + set; + } + + public decimal ValorAntigo + { + get; + set; + } + + public bool ZeroKm + { + get; + set; + } + + public Fipe() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.CalculoWeb/Auto/QuestionarioAuto.cs b/Codemerx/Gestor.Model/Model.CalculoWeb/Auto/QuestionarioAuto.cs new file mode 100644 index 0000000..9fb7d71 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.CalculoWeb/Auto/QuestionarioAuto.cs @@ -0,0 +1,90 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.CalculoWeb.Auto +{ + public class QuestionarioAuto + { + public string Associado + { + get; + set; + } + + public string FaixaEtariaDependentes + { + get; + set; + } + + public string GaragemEstudo + { + get; + set; + } + + public string GaragemResidencia + { + get; + set; + } + + public string GaragemTrabalho + { + get; + set; + } + + public long Id + { + get; + set; + } + + public string IsencaoFiscal + { + get; + set; + } + + public string Pcd + { + get; + set; + } + + public string PeriodoUso + { + get; + set; + } + + public string QuilometragemMensal + { + get; + set; + } + + public string TipoResidencia + { + get; + set; + } + + public string UsoDependentes + { + get; + set; + } + + public string UsoVeiculo + { + get; + set; + } + + public QuestionarioAuto() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.CalculoWeb/Auto/Veiculo.cs b/Codemerx/Gestor.Model/Model.CalculoWeb/Auto/Veiculo.cs new file mode 100644 index 0000000..a616133 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.CalculoWeb/Auto/Veiculo.cs @@ -0,0 +1,217 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.CalculoWeb.Auto +{ + public class Veiculo + { + private string _combustivel; + + public string Alienado + { + get; + set; + } + + public string AnoFabricacao + { + get; + set; + } + + public string AnoModelo + { + get; + set; + } + + public string Antifurto + { + get; + set; + } + + public string Blindado + { + get; + set; + } + + public string CepPernoite + { + get; + set; + } + + public string CodigoFipe + { + get; + set; + } + + public string Combustivel + { + get + { + return this._combustivel; + } + set + { + this._combustivel = value; + Veiculo.ConvertCombustivelCalculo(this._combustivel); + } + } + + public string Fabricante + { + get; + set; + } + + public Gestor.Model.CalculoWeb.Auto.Fipe Fipe + { + get; + set; + } + + public long Id + { + get; + set; + } + + public string KitGas + { + get; + set; + } + + public string Modelo + { + get; + set; + } + + public string NumeroChassi + { + get; + set; + } + + public string Placa + { + get; + set; + } + + public string Rastreador + { + get; + set; + } + + public string Uf + { + get; + set; + } + + public string ZeroKm + { + get; + set; + } + + public Veiculo() + { + } + + private static string ConvertCombustivelCalculo(string combustivel) + { + if (combustivel != null) + { + int length = combustivel.Length; + if (length == 1) + { + switch (combustivel[0]) + { + case '1': + { + return "3"; + } + case '2': + { + return "2"; + } + case '3': + { + return "4"; + } + case '4': + { + return "1"; + } + case '5': + case '7': + case '8': + { + return "6"; + } + case '6': + { + return string.Empty; + } + case '9': + { + break; + } + default: + { + return string.Empty; + } + } + } + else if (length == 2) + { + switch (combustivel[1]) + { + case '0': + { + if (combustivel == "10") + { + break; + } + return string.Empty; + } + case '1': + { + if (combustivel == "11") + { + return "7"; + } + return string.Empty; + } + case '2': + { + if (combustivel == "12") + { + break; + } + return string.Empty; + } + default: + { + return string.Empty; + } + } + } + else + { + return string.Empty; + } + return "5"; + } + return string.Empty; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.CalculoWeb/Calculo.cs b/Codemerx/Gestor.Model/Model.CalculoWeb/Calculo.cs new file mode 100644 index 0000000..40b8d39 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.CalculoWeb/Calculo.cs @@ -0,0 +1,73 @@ +using Gestor.Model.CalculoWeb.Auto; +using Gestor.Model.CalculoWeb.Condominio; +using Gestor.Model.CalculoWeb.Empresa; +using Gestor.Model.CalculoWeb.Residencia; +using Gestor.Model.CalculoWeb.VidaGlobal; +using Gestor.Model.CalculoWeb.VidaIndividual; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.CalculoWeb +{ + public class Calculo + { + public CalculoAuto Auto + { + get; + set; + } + + public CalculoCondominio Condominio + { + get; + set; + } + + public CalculoEmpresa Empresa + { + get; + set; + } + + public CalculoResidencia Residencia + { + get; + set; + } + + public List<Gestor.Model.CalculoWeb.Resultados> Resultados + { + get; + set; + } + + public string SerialNumber + { + get; + set; + } + + public Gestor.Model.CalculoWeb.Usuario Usuario + { + get; + set; + } + + public CalculoVidaIndividual Vida + { + get; + set; + } + + public CalculoVidaGlobal VidaGlobal + { + get; + set; + } + + public Calculo() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.CalculoWeb/Condominio/CalculoCondominio.cs b/Codemerx/Gestor.Model/Model.CalculoWeb/Condominio/CalculoCondominio.cs new file mode 100644 index 0000000..9b3d7d7 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.CalculoWeb/Condominio/CalculoCondominio.cs @@ -0,0 +1,44 @@ +using Gestor.Model.CalculoWeb; +using Gestor.Model.CalculoWeb.Empresa; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.CalculoWeb.Condominio +{ + public class CalculoCondominio + { + public CoberturaCondominio Cobertura + { + get; + set; + } + + public EnderecoEmpresa Endereco + { + get; + set; + } + + public QuestionarioCondominio Questionario + { + get; + set; + } + + public Gestor.Model.CalculoWeb.Segurado Segurado + { + get; + set; + } + + public Gestor.Model.CalculoWeb.Seguro Seguro + { + get; + set; + } + + public CalculoCondominio() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.CalculoWeb/Condominio/CoberturaCondominio.cs b/Codemerx/Gestor.Model/Model.CalculoWeb/Condominio/CoberturaCondominio.cs new file mode 100644 index 0000000..b020d5c --- /dev/null +++ b/Codemerx/Gestor.Model/Model.CalculoWeb/Condominio/CoberturaCondominio.cs @@ -0,0 +1,186 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.CalculoWeb.Condominio +{ + public class CoberturaCondominio + { + public decimal? Alagamento + { + get; + set; + } + + public decimal? Aluguel + { + get; + set; + } + + public decimal? Anuncios + { + get; + set; + } + + public string Assistencia + { + get; + set; + } + + public decimal? Basica + { + get; + set; + } + + public decimal? Chuveiro + { + get; + set; + } + + public decimal? Condominio + { + get; + set; + } + + public decimal? DanosEletricos + { + get; + set; + } + + public decimal? DanosMorais + { + get; + set; + } + + public decimal? Desmoronamento + { + get; + set; + } + + public decimal? DespesasFixas + { + get; + set; + } + + public decimal? Empregador + { + get; + set; + } + + public decimal? Equipamento + { + get; + set; + } + + public decimal? Garagista + { + get; + set; + } + + public decimal? GaragistaExclusiva + { + get; + set; + } + + public int? Id + { + get; + set; + } + + public decimal? ImpactoVeiculo + { + get; + set; + } + + public decimal? IncendioBens + { + get; + set; + } + + public decimal? PlacasSolares + { + get; + set; + } + + public decimal? Portoes + { + get; + set; + } + + public decimal? RouboBens + { + get; + set; + } + + public decimal? RouboCondominio + { + get; + set; + } + + public decimal? Sindico + { + get; + set; + } + + public decimal? TumultoGreve + { + get; + set; + } + + public string ValorNovo + { + get; + set; + } + + public decimal? Vazamento + { + get; + set; + } + + public decimal? Vendaval + { + get; + set; + } + + public decimal? VidaFuncionario + { + get; + set; + } + + public decimal? Vidros + { + get; + set; + } + + public CoberturaCondominio() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.CalculoWeb/Condominio/QuestionarioCondominio.cs b/Codemerx/Gestor.Model/Model.CalculoWeb/Condominio/QuestionarioCondominio.cs new file mode 100644 index 0000000..082fd13 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.CalculoWeb/Condominio/QuestionarioCondominio.cs @@ -0,0 +1,96 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.CalculoWeb.Condominio +{ + public class QuestionarioCondominio + { + public string AnoConstrucao + { + get; + set; + } + + public string AreaComercial + { + get; + set; + } + + public string AreaConstruida + { + get; + set; + } + + public string Blocos + { + get; + set; + } + + public string Desmoronamento + { + get; + set; + } + + public string Elevadores + { + get; + set; + } + + public string EquipamentoIncendio + { + get; + set; + } + + public string EquipamentoSeguranca + { + get; + set; + } + + public string Estrutura + { + get; + set; + } + + public string Funcionarios + { + get; + set; + } + + public int Id + { + get; + set; + } + + public string ImovelTombado + { + get; + set; + } + + public string Ocupacao + { + get; + set; + } + + public string Pavimentos + { + get; + set; + } + + public QuestionarioCondominio() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.CalculoWeb/Empresa/CalculoEmpresa.cs b/Codemerx/Gestor.Model/Model.CalculoWeb/Empresa/CalculoEmpresa.cs new file mode 100644 index 0000000..9a3e09a --- /dev/null +++ b/Codemerx/Gestor.Model/Model.CalculoWeb/Empresa/CalculoEmpresa.cs @@ -0,0 +1,43 @@ +using Gestor.Model.CalculoWeb; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.CalculoWeb.Empresa +{ + public class CalculoEmpresa + { + public CoberturaEmpresa Cobertura + { + get; + set; + } + + public EnderecoEmpresa Endereco + { + get; + set; + } + + public QuestionarioEmpresa Questionario + { + get; + set; + } + + public Gestor.Model.CalculoWeb.Segurado Segurado + { + get; + set; + } + + public Gestor.Model.CalculoWeb.Seguro Seguro + { + get; + set; + } + + public CalculoEmpresa() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.CalculoWeb/Empresa/CoberturaEmpresa.cs b/Codemerx/Gestor.Model/Model.CalculoWeb/Empresa/CoberturaEmpresa.cs new file mode 100644 index 0000000..c8faa20 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.CalculoWeb/Empresa/CoberturaEmpresa.cs @@ -0,0 +1,186 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.CalculoWeb.Empresa +{ + public class CoberturaEmpresa + { + public decimal? Alagamento + { + get; + set; + } + + public decimal? Aluguel + { + get; + set; + } + + public decimal? Anuncio + { + get; + set; + } + + public string Assistencia + { + get; + set; + } + + public decimal? Basica + { + get; + set; + } + + public decimal? ContaminacaoDeterioracao + { + get; + set; + } + + public decimal? DanoEletrico + { + get; + set; + } + + public decimal? DanoMoral + { + get; + set; + } + + public decimal? Desmoronamento + { + get; + set; + } + + public decimal? DespesaFixa + { + get; + set; + } + + public decimal? Empregador + { + get; + set; + } + + public decimal? Equipamento + { + get; + set; + } + + public decimal? Fidelidade + { + get; + set; + } + + public int? Id + { + get; + set; + } + + public decimal? ImpactoVeiculo + { + get; + set; + } + + public decimal? LucroCessante + { + get; + set; + } + + public decimal? PlacasSolares + { + get; + set; + } + + public decimal? RecomposicaoDocumento + { + get; + set; + } + + public decimal? ResponsabilidadeCivil + { + get; + set; + } + + public decimal? ResponsabilidadeCivilGaragista + { + get; + set; + } + + public decimal? RouboFurto + { + get; + set; + } + + public decimal? RouboValor + { + get; + set; + } + + public decimal? Sprinkler + { + get; + set; + } + + public decimal? TumultoGreve + { + get; + set; + } + + public string ValorNovo + { + get; + set; + } + + public decimal? Vazamento + { + get; + set; + } + + public decimal? Vendaval + { + get; + set; + } + + public string Verba + { + get; + set; + } + + public decimal? Vidro + { + get; + set; + } + + public CoberturaEmpresa() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.CalculoWeb/Empresa/EnderecoEmpresa.cs b/Codemerx/Gestor.Model/Model.CalculoWeb/Empresa/EnderecoEmpresa.cs new file mode 100644 index 0000000..473149b --- /dev/null +++ b/Codemerx/Gestor.Model/Model.CalculoWeb/Empresa/EnderecoEmpresa.cs @@ -0,0 +1,60 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.CalculoWeb.Empresa +{ + public class EnderecoEmpresa + { + public string Bairro + { + get; + set; + } + + public string Cep + { + get; + set; + } + + public string Cidade + { + get; + set; + } + + public string Complemento + { + get; + set; + } + + public string Estado + { + get; + set; + } + + public int Id + { + get; + set; + } + + public string Logradouro + { + get; + set; + } + + public string Numero + { + get; + set; + } + + public EnderecoEmpresa() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.CalculoWeb/Empresa/QuestionarioEmpresa.cs b/Codemerx/Gestor.Model/Model.CalculoWeb/Empresa/QuestionarioEmpresa.cs new file mode 100644 index 0000000..73dbcca --- /dev/null +++ b/Codemerx/Gestor.Model/Model.CalculoWeb/Empresa/QuestionarioEmpresa.cs @@ -0,0 +1,115 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.CalculoWeb.Empresa +{ + public class QuestionarioEmpresa + { + public DateTime AnoConstrucao + { + get; + set; + } + + public string Atividade + { + get; + set; + } + + public List<object> Atividades + { + get; + set; + } + + public string CaixaEletronico + { + get; + set; + } + + public string Cnae + { + get; + set; + } + + public string Construcao + { + get; + set; + } + + public string Deposito + { + get; + set; + } + + public string EquipamentoIncendio + { + get; + set; + } + + public string EquipamentoSeguranca + { + get; + set; + } + + public string EstruturaMetal + { + get; + set; + } + + public int Id + { + get; + set; + } + + public string ImovelTombado + { + get; + set; + } + + public string Isopainel + { + get; + set; + } + + public string Localizacao + { + get; + set; + } + + public string Pavimento + { + get; + set; + } + + public string TerrenoBaldio + { + get; + set; + } + + public string TipoConstrucao + { + get; + set; + } + + public QuestionarioEmpresa() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.CalculoWeb/Residencia/CalculoResidencia.cs b/Codemerx/Gestor.Model/Model.CalculoWeb/Residencia/CalculoResidencia.cs new file mode 100644 index 0000000..a168a04 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.CalculoWeb/Residencia/CalculoResidencia.cs @@ -0,0 +1,43 @@ +using Gestor.Model.CalculoWeb; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.CalculoWeb.Residencia +{ + public class CalculoResidencia + { + public CoberturaResidencia Cobertura + { + get; + set; + } + + public Gestor.Model.CalculoWeb.Residencia.Imovel Imovel + { + get; + set; + } + + public QuestionarioResidencia Questionario + { + get; + set; + } + + public Gestor.Model.CalculoWeb.Segurado Segurado + { + get; + set; + } + + public Gestor.Model.CalculoWeb.Seguro Seguro + { + get; + set; + } + + public CalculoResidencia() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.CalculoWeb/Residencia/CoberturaResidencia.cs b/Codemerx/Gestor.Model/Model.CalculoWeb/Residencia/CoberturaResidencia.cs new file mode 100644 index 0000000..bdc8403 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.CalculoWeb/Residencia/CoberturaResidencia.cs @@ -0,0 +1,138 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.CalculoWeb.Residencia +{ + public class CoberturaResidencia + { + public decimal Alagamento + { + get; + set; + } + + public decimal Aluguel + { + get; + set; + } + + public string Assistencia + { + get; + set; + } + + public decimal Basica + { + get; + set; + } + + public decimal Bike + { + get; + set; + } + + public decimal DanosEletricos + { + get; + set; + } + + public decimal DanosMorais + { + get; + set; + } + + public decimal Desmoronamento + { + get; + set; + } + + public decimal Equipamentos + { + get; + set; + } + + public int Id + { + get; + set; + } + + public decimal ImpactoVeiculos + { + get; + set; + } + + public decimal PlacasSolares + { + get; + set; + } + + public decimal RecomposicaoDocumento + { + get; + set; + } + + public decimal ResponsabilidadeCivilFamiliar + { + get; + set; + } + + public decimal RouboFurto + { + get; + set; + } + + public decimal TumultoGreve + { + get; + set; + } + + public string ValorNovo + { + get; + set; + } + + public decimal Vazamentos + { + get; + set; + } + + public decimal Vendaval + { + get; + set; + } + + public string Verba + { + get; + set; + } + + public decimal Vidros + { + get; + set; + } + + public CoberturaResidencia() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.CalculoWeb/Residencia/EnderecoResidencia.cs b/Codemerx/Gestor.Model/Model.CalculoWeb/Residencia/EnderecoResidencia.cs new file mode 100644 index 0000000..9874c8d --- /dev/null +++ b/Codemerx/Gestor.Model/Model.CalculoWeb/Residencia/EnderecoResidencia.cs @@ -0,0 +1,60 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.CalculoWeb.Residencia +{ + public class EnderecoResidencia + { + public string Bairro + { + get; + set; + } + + public string Cep + { + get; + set; + } + + public string Cidade + { + get; + set; + } + + public string Complemento + { + get; + set; + } + + public string Estado + { + get; + set; + } + + public int Id + { + get; + set; + } + + public string Logradouro + { + get; + set; + } + + public string Numero + { + get; + set; + } + + public EnderecoResidencia() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.CalculoWeb/Residencia/Imovel.cs b/Codemerx/Gestor.Model/Model.CalculoWeb/Residencia/Imovel.cs new file mode 100644 index 0000000..6cedbb0 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.CalculoWeb/Residencia/Imovel.cs @@ -0,0 +1,42 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.CalculoWeb.Residencia +{ + public class Imovel + { + public EnderecoResidencia Endereco + { + get; + set; + } + + public int Id + { + get; + set; + } + + public string TipoConstrucao + { + get; + set; + } + + public string TipoMoradia + { + get; + set; + } + + public string TipoOcupacao + { + get; + set; + } + + public Imovel() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.CalculoWeb/Residencia/QuestionarioResidencia.cs b/Codemerx/Gestor.Model/Model.CalculoWeb/Residencia/QuestionarioResidencia.cs new file mode 100644 index 0000000..d8a6269 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.CalculoWeb/Residencia/QuestionarioResidencia.cs @@ -0,0 +1,66 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.CalculoWeb.Residencia +{ + public class QuestionarioResidencia + { + public string AreaRisco + { + get; + set; + } + + public string AtividadeProfissional + { + get; + set; + } + + public string CondominioFechado + { + get; + set; + } + + public string EquipamentoSeguranca + { + get; + set; + } + + public int Id + { + get; + set; + } + + public string ImovelDesocupado + { + get; + set; + } + + public string ImovelTombado + { + get; + set; + } + + public string SeguradoProprietario + { + get; + set; + } + + public string ZonaRural + { + get; + set; + } + + public QuestionarioResidencia() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.CalculoWeb/Resultados.cs b/Codemerx/Gestor.Model/Model.CalculoWeb/Resultados.cs new file mode 100644 index 0000000..18bb86a --- /dev/null +++ b/Codemerx/Gestor.Model/Model.CalculoWeb/Resultados.cs @@ -0,0 +1,18 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.CalculoWeb +{ + public class Resultados + { + public string Erros + { + get; + set; + } + + public Resultados() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.CalculoWeb/Segurado.cs b/Codemerx/Gestor.Model/Model.CalculoWeb/Segurado.cs new file mode 100644 index 0000000..34b57c8 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.CalculoWeb/Segurado.cs @@ -0,0 +1,158 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.CalculoWeb +{ + public class Segurado + { + private string _estadoCivil; + + private string _sexo; + + public string Cep { get; set; } = string.Empty; + + public string CpfCnpj + { + get; + set; + } + + public DateTime? DataHabilitacao { get; set; } = new DateTime?(DateTime.MinValue); + + public DateTime? DataNascimento { get; set; } = new DateTime?(DateTime.MinValue); + + public string Email + { + get; + set; + } + + public string EstadoCivil + { + get + { + return this._estadoCivil; + } + set + { + this._estadoCivil = value; + this._estadoCivil = this.ConvertEstCivCalculo(value); + } + } + + public long Id + { + get; + set; + } + + public string NomeCompleto + { + get; + set; + } + + public string NumeroHabilitacao + { + get; + set; + } + + public bool Perfil + { + get; + set; + } + + public string RelacaoSeguradoCondutor + { + get; + set; + } + + public string Sexo + { + get + { + return this._sexo; + } + set + { + this._sexo = value; + this._sexo = this.ConvertSexoCalculo(this._sexo); + value = this._sexo; + } + } + + public Telefone TelefoneCelular + { + get; + set; + } + + public Telefone TelefoneResidencial + { + get; + set; + } + + public string TempoHabilitacao + { + get; + set; + } + + public string Uf + { + get; + set; + } + + public Segurado() + { + } + + private string ConvertEstCivCalculo(string estadoCivil) + { + if (estadoCivil != null && estadoCivil.Length == 1) + { + switch (estadoCivil[0]) + { + case '0': + { + return "1"; + } + case '1': + { + return "2"; + } + case '2': + { + return "3"; + } + case '3': + case '5': + case '6': + case '7': + { + return "4"; + } + case '4': + { + return "5"; + } + } + } + return string.Empty; + } + + private string ConvertSexoCalculo(string sexo) + { + if (sexo != "0") + { + return "2"; + } + return "1"; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.CalculoWeb/Seguro.cs b/Codemerx/Gestor.Model/Model.CalculoWeb/Seguro.cs new file mode 100644 index 0000000..34154f9 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.CalculoWeb/Seguro.cs @@ -0,0 +1,110 @@ +using Gestor.Model.CalculoWeb.Auto; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.CalculoWeb +{ + public class Seguro + { + public decimal Agenciamento + { + get; + set; + } + + public string Banco + { + get; + set; + } + + public string Bonus + { + get; + set; + } + + public string CodigoIdentificacao + { + get; + set; + } + + public decimal Comissao + { + get; + set; + } + + public List<Gestor.Model.CalculoWeb.Auto.ComissaoSeguradora> ComissaoSeguradora + { + get; + set; + } + + public long Id + { + get; + set; + } + + public string NumeroApoliceAnterior + { + get; + set; + } + + public string Observacoes + { + get; + set; + } + + public bool RenovacaoGarantida + { + get; + set; + } + + public string SeguradoraAnterior + { + get; + set; + } + + public string Sinistros + { + get; + set; + } + + public string TipoSeguro + { + get; + set; + } + + public DateTime VigenciaFinal + { + get; + set; + } + + public DateTime VigenciaFinalAnterior + { + get; + set; + } + + public DateTime VigenciaInicial + { + get; + set; + } + + public Seguro() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.CalculoWeb/Telefone.cs b/Codemerx/Gestor.Model/Model.CalculoWeb/Telefone.cs new file mode 100644 index 0000000..364a57f --- /dev/null +++ b/Codemerx/Gestor.Model/Model.CalculoWeb/Telefone.cs @@ -0,0 +1,30 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.CalculoWeb +{ + public class Telefone + { + public string Ddd + { + get; + set; + } + + public long Id + { + get; + set; + } + + public string Numero + { + get; + set; + } + + public Telefone() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.CalculoWeb/Usuario.cs b/Codemerx/Gestor.Model/Model.CalculoWeb/Usuario.cs new file mode 100644 index 0000000..5b46cf6 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.CalculoWeb/Usuario.cs @@ -0,0 +1,18 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.CalculoWeb +{ + public class Usuario + { + public string Email + { + get; + set; + } + + public Usuario() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.CalculoWeb/VidaGlobal/CalculoVidaGlobal.cs b/Codemerx/Gestor.Model/Model.CalculoWeb/VidaGlobal/CalculoVidaGlobal.cs new file mode 100644 index 0000000..60a3b45 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.CalculoWeb/VidaGlobal/CalculoVidaGlobal.cs @@ -0,0 +1,44 @@ +using Gestor.Model.CalculoWeb; +using Gestor.Model.CalculoWeb.Empresa; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.CalculoWeb.VidaGlobal +{ + public class CalculoVidaGlobal + { + public CalculoVidaGlobal Cobertura + { + get; + set; + } + + public EnderecoEmpresa Endereco + { + get; + set; + } + + public QuestionarioVidaGlobal Questionario + { + get; + set; + } + + public Gestor.Model.CalculoWeb.Segurado Segurado + { + get; + set; + } + + public Gestor.Model.CalculoWeb.Seguro Seguro + { + get; + set; + } + + public CalculoVidaGlobal() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.CalculoWeb/VidaGlobal/CoberturaVidaGlobal.cs b/Codemerx/Gestor.Model/Model.CalculoWeb/VidaGlobal/CoberturaVidaGlobal.cs new file mode 100644 index 0000000..dc43427 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.CalculoWeb/VidaGlobal/CoberturaVidaGlobal.cs @@ -0,0 +1,66 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.CalculoWeb.VidaGlobal +{ + public class CoberturaVidaGlobal + { + public string AssistenciaFuneral + { + get; + set; + } + + public decimal? CapitalFuncionario + { + get; + set; + } + + public decimal? CapitalSocio + { + get; + set; + } + + public int Funcionario + { + get; + set; + } + + public int Id + { + get; + set; + } + + public string Ifpd + { + get; + set; + } + + public string Ipa + { + get; + set; + } + + public string MorteAcidental + { + get; + set; + } + + public int Socio + { + get; + set; + } + + public CoberturaVidaGlobal() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.CalculoWeb/VidaGlobal/QuestionarioVidaGlobal.cs b/Codemerx/Gestor.Model/Model.CalculoWeb/VidaGlobal/QuestionarioVidaGlobal.cs new file mode 100644 index 0000000..8732069 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.CalculoWeb/VidaGlobal/QuestionarioVidaGlobal.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.CalculoWeb.VidaGlobal +{ + public class QuestionarioVidaGlobal + { + public List<string> Atividades + { + get; + set; + } + + public string Cnae + { + get; + set; + } + + public int Funcionario + { + get; + set; + } + + public int Id + { + get; + set; + } + + public QuestionarioVidaGlobal() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.CalculoWeb/VidaIndividual/CalculoVidaIndividual.cs b/Codemerx/Gestor.Model/Model.CalculoWeb/VidaIndividual/CalculoVidaIndividual.cs new file mode 100644 index 0000000..33eb7fd --- /dev/null +++ b/Codemerx/Gestor.Model/Model.CalculoWeb/VidaIndividual/CalculoVidaIndividual.cs @@ -0,0 +1,44 @@ +using Gestor.Model.CalculoWeb; +using Gestor.Model.CalculoWeb.Empresa; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.CalculoWeb.VidaIndividual +{ + public class CalculoVidaIndividual + { + public CoberturaVidaIndividual Cobertura + { + get; + set; + } + + public EnderecoEmpresa Endereco + { + get; + set; + } + + public QuestionarioVidaIndividual Questionario + { + get; + set; + } + + public Gestor.Model.CalculoWeb.Segurado Segurado + { + get; + set; + } + + public Gestor.Model.CalculoWeb.Seguro Seguro + { + get; + set; + } + + public CalculoVidaIndividual() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.CalculoWeb/VidaIndividual/CoberturaVidaIndividual.cs b/Codemerx/Gestor.Model/Model.CalculoWeb/VidaIndividual/CoberturaVidaIndividual.cs new file mode 100644 index 0000000..5b3f83f --- /dev/null +++ b/Codemerx/Gestor.Model/Model.CalculoWeb/VidaIndividual/CoberturaVidaIndividual.cs @@ -0,0 +1,108 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.CalculoWeb.VidaIndividual +{ + public class CoberturaVidaIndividual + { + public string AssistenciaFuneral + { + get; + set; + } + + public decimal? Capital + { + get; + set; + } + + public decimal CapitalDih + { + get; + set; + } + + public decimal? CapitalDit + { + get; + set; + } + + public decimal? CapitalDoenca + { + get; + set; + } + + public decimal? CapitalIfpd + { + get; + set; + } + + public decimal? CapitalIpa + { + get; + set; + } + + public decimal? CapitalMorteAcidental + { + get; + set; + } + + public string Dih + { + get; + set; + } + + public string Dit + { + get; + set; + } + + public string DoencaGrave + { + get; + set; + } + + public int? Id + { + get; + set; + } + + public string Ifpd + { + get; + set; + } + + public string Ipa + { + get; + set; + } + + public string Morte + { + get; + set; + } + + public string MorteAcidental + { + get; + set; + } + + public CoberturaVidaIndividual() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.CalculoWeb/VidaIndividual/Profissao.cs b/Codemerx/Gestor.Model/Model.CalculoWeb/VidaIndividual/Profissao.cs new file mode 100644 index 0000000..fd20834 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.CalculoWeb/VidaIndividual/Profissao.cs @@ -0,0 +1,36 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.CalculoWeb.VidaIndividual +{ + public class Profissao + { + public string Chave + { + get; + set; + } + + public int Id + { + get; + set; + } + + public int Seguradora + { + get; + set; + } + + public string Valor + { + get; + set; + } + + public Profissao() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.CalculoWeb/VidaIndividual/QuestionarioVidaIndividual.cs b/Codemerx/Gestor.Model/Model.CalculoWeb/VidaIndividual/QuestionarioVidaIndividual.cs new file mode 100644 index 0000000..9ff0b62 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.CalculoWeb/VidaIndividual/QuestionarioVidaIndividual.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.CalculoWeb.VidaIndividual +{ + public class QuestionarioVidaIndividual + { + public float Altura + { + get; + set; + } + + public string Aposentado + { + get; + set; + } + + public string Esporte + { + get; + set; + } + + public string Fumante + { + get; + set; + } + + public int? Id + { + get; + set; + } + + public int? Peso + { + get; + set; + } + + public string Profissao + { + get; + set; + } + + public List<Gestor.Model.CalculoWeb.VidaIndividual.Profissao> Profissoes + { + get; + set; + } + + public decimal? RendaMensal + { + get; + set; + } + + public QuestionarioVidaIndividual() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/AcessoApolice.cs b/Codemerx/Gestor.Model/Model.Common/AcessoApolice.cs new file mode 100644 index 0000000..0be3aa9 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/AcessoApolice.cs @@ -0,0 +1,17 @@ +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + public enum AcessoApolice + { + [Description("NORMAL")] + Normal, + [Description("PARCELA")] + Parcela, + [Description("ENDOSSO")] + Endosso, + [Description("RENOVAÇÃO")] + Renovacao + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/Agrupamento.cs b/Codemerx/Gestor.Model/Model.Common/Agrupamento.cs new file mode 100644 index 0000000..b36c4fc --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/Agrupamento.cs @@ -0,0 +1,23 @@ +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum Agrupamento + { + [Description("SEM DIVISÃO")] + SemDivisoes, + [Description("SEGURADORA")] + Seguradora, + [Description("RAMO")] + Ramo, + [Description("VENDEDOR")] + Vendedor, + [Description("ESTIPULANTE")] + Estipulante, + [Description("SITUAÇÃO")] + Situacao + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/Antifurto.cs b/Codemerx/Gestor.Model/Model.Common/Antifurto.cs new file mode 100644 index 0000000..2c77cb7 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/Antifurto.cs @@ -0,0 +1,30 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum Antifurto + { + [Description("NÃO POSSUI")] + [OldValue("0")] + NaoSeAplica, + [Description("ALARME")] + [OldValue("1")] + Alarme, + [Description("BLOQUEADOR DE IGNIÇÃO")] + [OldValue("2")] + Bloqueador, + [Description("TRAVA CARNEIRO")] + [OldValue("3")] + TravaCarneiro, + [Description("TRAVA MUL-T-LOCK")] + [OldValue("4")] + TravaMulTLock, + [Description("OUTROS")] + [OldValue("5")] + Outros + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/AtividadeEmpresa.cs b/Codemerx/Gestor.Model/Model.Common/AtividadeEmpresa.cs new file mode 100644 index 0000000..19c49c6 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/AtividadeEmpresa.cs @@ -0,0 +1,129 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum AtividadeEmpresa + { + [Description("OUTROS")] + [OldValue("1")] + Outro, + [Description("ACADEMIA")] + [OldValue("2")] + Academia, + [Description("BAR")] + [OldValue("3")] + Bar, + [Description("BELEZA E ESTÉTICA")] + [OldValue("4")] + BelezaEstetica, + [Description("CLÍNICA VETERINÁRIA")] + [OldValue("5")] + ClinicaVeterinaria, + [Description("CONCESSIONÁRIA")] + [OldValue("6")] + Concessionaria, + [Description("CONSULTÓRIO MÉDICO")] + [OldValue("7")] + ConsultorioMedico, + [Description("CONSULTÓRIO ODONTOLÓGICO")] + [OldValue("8")] + ConsultorioOdontologico, + [Description("ESCOLA DE INFORMÁTICA")] + [OldValue("9")] + EscolaInformatica, + [Description("ESCOLA DE IDIOMAS")] + [OldValue("10")] + EscolaIdiomas, + [Description("ESCOLA TÉCNICA")] + [OldValue("11")] + EscolaTecnica, + [Description("ESCOLA OU COLÉGIO")] + [OldValue("12")] + EscolaDemais, + [Description("ESCRITÓRIO")] + [OldValue("13")] + Escritorio, + [Description("FARMÁCIA")] + [OldValue("14")] + Farmacia, + [Description("FLORICULTURA")] + [OldValue("15")] + Floricultura, + [Description("HOTEL")] + [OldValue("16")] + Hotel, + [Description("IGREJA")] + [OldValue("17")] + Igreja, + [Description("LAVANDERIA")] + [OldValue("18")] + Lavanderia, + [Description("LIVRARIA")] + [OldValue("19")] + Livraria, + [Description("LOJA DE CALÇADOS")] + [OldValue("20")] + LojaCalcado, + [Description("LOJA DE ROUPAS")] + [OldValue("21")] + LojaRoupa, + [Description("SUPERMERCADO")] + [OldValue("22")] + Mercado, + [Description("MOTEL")] + [OldValue("23")] + Motel, + [Description("ÓTICA")] + [OldValue("24")] + Otica, + [Description("PADARIA")] + [OldValue("25")] + Padaria, + [Description("PAPELARIA")] + [OldValue("26")] + Papelaria, + [Description("PERFUMARIA")] + [OldValue("27")] + Perfumaria, + [Description("PET SHOP")] + [OldValue("28")] + PetShop, + [Description("POSTO DE COMBUSTÍVEL")] + [OldValue("29")] + PostoCombustivel, + [Description("POUSADA")] + [OldValue("30")] + Pousada, + [Description("RESTAURANTE")] + [OldValue("31")] + Restaurante, + [Description("LOJA DE MÓVEIS")] + [OldValue("32")] + LojaMoveis, + [Description("LOJA DE MATERIAL DE CONSTRUÇÃO")] + [OldValue("33")] + LojaMaterialConstrucao, + [Description("LOJA DE ELETRODOMÉSTICOS")] + [OldValue("34")] + LojaEletrodomesticos, + [Description("LOJA DE COLCHÕES")] + [OldValue("35")] + LojaColchoes, + [Description("BUFFET")] + [OldValue("36")] + Buffet, + [Description("AÇOUGUE")] + [OldValue("37")] + Acougue, + [Description("TRANSPORTADORA")] + [OldValue("38")] + Transportadora, + [Description("COPIADORA")] + [OldValue("39")] + Copiadora + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/BandeiraCartao.cs b/Codemerx/Gestor.Model/Model.Common/BandeiraCartao.cs new file mode 100644 index 0000000..2607262 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/BandeiraCartao.cs @@ -0,0 +1,33 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum BandeiraCartao + { + [Description("VISA")] + [OldValue("1")] + Visa = 1, + [Description("MASTERCARD")] + [OldValue("2")] + Master = 2, + [Description("ELO")] + [OldValue("3")] + Elo = 3, + [Description("AMERICAN EXPRESS")] + [OldValue("4")] + AmericanExpress = 4, + [Description("HIPERCARD")] + [OldValue("5")] + Hipercard = 5, + [Description("DINERS CLUB")] + [OldValue("6")] + Diners = 6, + [Description("SOROCRED")] + [OldValue("7")] + Sorocred = 7 + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/BaseRepasse.cs b/Codemerx/Gestor.Model/Model.Common/BaseRepasse.cs new file mode 100644 index 0000000..f5c12eb --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/BaseRepasse.cs @@ -0,0 +1,27 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum BaseRepasse + { + [Description("VIGÊNCIA DO DOCUMENTO")] + [OldValue("1")] + Vigencia = 1, + [Description("CADASTRO DO DOCUMENTO")] + [OldValue("2")] + Cadastro = 2, + [Description("VENCIMENTO DA PARCELA")] + [OldValue("3")] + Vencimento = 3, + [Description("EMISSÃO DA APÓLICE")] + [OldValue("4")] + Emissao = 4, + [Description("TRANSMISSÃO DA PROPOSTA")] + [OldValue("5")] + Transmissao = 5 + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/Categoria.cs b/Codemerx/Gestor.Model/Model.Common/Categoria.cs new file mode 100644 index 0000000..6ae62dc --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/Categoria.cs @@ -0,0 +1,51 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum Categoria + { + [Description("PICKUP")] + [OldValue("1")] + Pickup = 1, + [Description("OUTROS")] + [OldValue("2")] + Outros = 2, + [Description("PASSEIO")] + [OldValue("3")] + Passeio = 3, + [Description("CAMINHÃO")] + [OldValue("4")] + Caminhao = 4, + [Description("CAMINHONETE")] + [OldValue("5")] + Caminhonete = 5, + [Description("ÔNIBUS")] + [OldValue("6")] + Onibus = 6, + [Description("UTILITÁRIO")] + [OldValue("7")] + Utilitario = 7, + [Description("CARGA")] + [OldValue("8")] + Carga = 8, + [Description("MOTOCICLETA")] + [OldValue("9")] + Motocicleta = 9, + [Description("TAXI")] + [OldValue("10")] + Taxi = 10, + [Description("UBER")] + [OldValue("11")] + Uber = 11, + [Description("REBOCADOR")] + [OldValue("12")] + Rebocador = 12, + [Description("REBOQUE/SEMI REBOQUE")] + [OldValue("13")] + Reboque = 13 + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/Combustivel.cs b/Codemerx/Gestor.Model/Model.Common/Combustivel.cs new file mode 100644 index 0000000..9e6b6b2 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/Combustivel.cs @@ -0,0 +1,60 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum Combustivel + { + [Category("1")] + [Description("ÁLCOOL")] + [OldValue("1")] + Alcool = 1, + [Category("1")] + [Description("GASOLINA")] + [OldValue("2")] + Gasolina = 2, + [Category("1")] + [Description("DIESEL")] + [OldValue("3")] + Diesel = 3, + [Category("0")] + [Description("FLEX (GASOLINA/ÁLCOOL)")] + [OldValue("4")] + Flex = 4, + [Category("2")] + [Description("GNV")] + [OldValue("5")] + Gnv = 5, + [Category("4")] + [Description("OUTROS")] + [OldValue("6")] + Outros = 6, + [Category("2")] + [Description("GASOLINA/GNV")] + [OldValue("7")] + GasolinaGnv = 7, + [Category("2")] + [Description("GASOLINA/ÁLCOOL/GNV")] + [OldValue("8")] + GasolinaAlcoolGnv = 8, + [Category("3")] + [Description("GASOLINA/ELÉTRICO")] + [OldValue("9")] + GasolinaEletrico = 9, + [Category("3")] + [Description("HÍBRIDO")] + [OldValue("10")] + Hibrido = 10, + [Category("3")] + [Description("ELÉTRICO")] + [OldValue("11")] + Eletrico = 11, + [Category("3")] + [Description("GASOLINA/ÁLCOOL/ELÉTRICO")] + [OldValue("12")] + GasolinaAlcoolEletrico = 12 + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/Condicao.cs b/Codemerx/Gestor.Model/Model.Common/Condicao.cs new file mode 100644 index 0000000..6d5d015 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/Condicao.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Common +{ + public class Condicao + { + public string Campo + { + get; + set; + } + + public int Grupo + { + get; + set; + } + + public Gestor.Model.Common.Operacao Operacao + { + get; + set; + } + + public Gestor.Model.Common.Operador Operador + { + get; + set; + } + + public List<dynamic> Valores + { + get; + set; + } + + public Condicao() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/Configuracao.cs b/Codemerx/Gestor.Model/Model.Common/Configuracao.cs new file mode 100644 index 0000000..e5b0264 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/Configuracao.cs @@ -0,0 +1,179 @@ +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum Configuracao + { + [Category("SEMPRE ATUALIZAR DADOS DO CLIENTE AO IMPORTAR UM NOVO PDF")] + [Description("IMPORTADOR PDF - ATUALIZAR DADOS CLIENTE AUTOMATICAMENTE")] + AtualizarDados = 0, + [Category("SEMPRE ATUALIZAR ENDEREÇO CLIENTE AO IMPORTAR UM NOVO PDF")] + [Description("IMPORTADOR PDF - ATUALIZAR ENDEREÇO CLIENTE AUTOMATICAMENTE")] + AtualizarEndereco = 1, + [Category("NÃO EXCLUIR O ARQUIVO PDF DA PASTA DE ORIGEM AO IMPORTA-LO")] + [Description("IMPORTADOR PDF - MANTER PDF")] + ManterPdf = 2, + [Category("OBRIGAR USUARIO A PREENCHER O CAMPO STATUS DO DOCUMENTO MANUALMENTE DURANTE A CRÍTICA")] + [Description("CRÍTICA DE DOCUMENTOS - OBRIGAR STATUS DOCUMENTO")] + StatusDocumento = 3, + [Category("RESTRINGIR A VISUALIZAÇÃO DAS PARCELAS DO DOCUMENTO NO ACESSO AO APLICATIVO MOBILE EPIC")] + [Description("AGGER EPIC - RESTRINGIR ACESSO ÁS PARCELAS")] + AcessoParcelasEpic = 4, + [Category("HABILITAR CAMPOS DE IMPOSTOS E REALIZA A DEDUÇÃO AUTOMATICAMENTE DO PERCENTUAL DE IMPOSTOS PARAMETRIZADOS")] + [Description("BAIXA DE COMISSÃO - HABILITAR IMPOSTOS RECEBIMENTO DE COMISSÃO")] + ImpostoComissao = 5, + [Category("HABILITAR APELIDO SEGURADORA")] + [Description("CADASTRO DE SEGURADORAS - HABILITAR APELIDO SEGURADORA")] + ApelidoSeguradora = 6, + [Category("PERMITIR DUPLICIDADE NO DOCUMENTO DE VENDEDORES")] + [Description("CADASTRO DE VENDEDORES - PERMITIR DUPLICIDADE NO DOCUMENTO DE VENDEDORES")] + DuplicidadeVendedores = 7, + [Category("DISPONIBILIZA OPÇÃO DE ORDENAR O RELATORIO DE PAGAMENTO DE VENDEDORES.")] + [Description("RELATÓRIO PAGAMENTO DE VENDEDORES - ORDEM RELATÓRIO")] + OrdernarPagamentos = 8, + [Category("PERMITE QUE O VENCIMENTO DA PARCELA SEJA MENOR QUE A VIGÊNCIA INICIAL DO DOCUMENTO")] + [Description("CADASTRO DE PARCELAS - PERMITIR VENCIMENTO MENOR QUE VIGÊNCIA INICIAL")] + VencimentoParcelaVigenciaInicial = 9, + [Category("NÃO MOSTRAR PAGAMENTO DE VENDEDOR OU RECEBIMENTO DE COMISSÃO COM VALOR LÍQUIDO ZERADO NO RELATÓRIO")] + [Description("RELATÓRIOS - ESCONDER COMISSÃO ZERADA NO RELATÓRIO")] + EsconderComissaoZerada = 10, + [Category("PERMITE QUE O VENCIMENTO DA PARCELA SEJA MAIOR QUE A VIGÊNCIA FINAL DO DOCUMENTO")] + [Description("CADASTRO DE PARCELAS - PERMITIR VENCIMENTO PARCELA MAIOR QUE VIGÊNCIA FINAL")] + VencimentoParcelaVigenciaFinal = 11, + [Category("PERMITE QUE A PARCELA ESPECIAL IMPORTADA NO EXTRATO SEJA BAIXADA NA PARCELA NORMAL DO SEGURO")] + [Description("BAIXA DE COMISSÃO AUTOMÁTICA - PERMITIR BAIXA DE PARCELA ESPECIAL EM PARCELA NORMAL")] + BaixaParcelaEspecialNormal = 12, + [Category("PERMITE ENDOSSAR UM DOCUMENTO SEM VALIDAR AS INFORMAÇÕES DA APÓLICE, TAIS COMO NÚMERO DA APÓLICE, DATA DE EMISSÃO E TRANSMISSÃO DA PROPOSTA.\nNÃO RECOMENDAMOS HABILITAR ESSA OPÇÃO")] + [Description("CADASTRO DE APÓLICES - PERMITIR ENDOSSO SEM VERIFICAÇÃO DA APÓLICE")] + EndossoSemVerificacao = 13, + [Category("IMPRESSÃO DOS RELATÓRIOS TERÃO FONTES MAIORES QUE O PADRÃO")] + [Description("RELATÓRIOS - EXIBIR MAIOR FONTE NOS RELATÓRIO")] + FontesGrandesRelatorio = 14, + [Category("PERMITE REPASSAR MAIS QUE A COMISSÃO RECEBIDA NO SEGURO.\nNÃO RECOMENDAMOS HABILITAR ESSA OPÇÃO")] + [Description("BAIXA DE COMISSÃO - PERMITIR REPASSE MAIOR QUE A COMISSÃO RECEBIDA")] + RepasseSuperiorComissao = 15, + [Category("PERMITE QUE CADASTRE FATURAS COM COMISSÃO MAIOR QUE 100% DO PRÊMIO PARA FATURAS")] + [Description("CADASTRO DE FATURAS - PERMITIR PERCENTUAL DE COMISSÃO MAIOR QUE 100%")] + ComissaoSuperiorTotal = 16, + [Category("PERMITE CADASTRAR ITENS DE AUTOMÓVEL COM CHASSI INVÁLIDO")] + [Description("CADASTRO DE ITENS - PERMITIR CHASSIS INVÁLIDOS")] + ChassiInvalido = 18, + [Category("BLOQUEIA A RECUSA DE APÓLICE QUANDO TIVER NÚMERO DE APÓLICE E DATA DE EMISSÃO")] + [Description("CADASTRO DE APÓLICES - BLOQUEAR RECUSA DE APÓLICE")] + Recusa = 19, + [Category("PERMITIR O CADASTRO DE REPASSE POR RAMO ESPECÍFICO")] + [Description("REPASSES - PERMITIR CADASTRO DE REPASSE POR RAMO")] + RepasseRamo = 20, + [Category("ALTERAR FORMA DE PAGAMENTO 'NENHUM' AO SALVAR DOCUMENTO, QUANDO O CAMPO ESTIVER EM BRANCO")] + [Description("CADASTRO DE APÓLICES - FORMA DE PAGAMENTO AO SALVAR")] + FormaPagamento = 21, + [Category("HABILITA RELATORIO DE LOG DE UTILIZAÇÃO SISTEMA ANTIGO")] + [Description("LOG - HABILITAR LOG DE UTILIZAÇÃO SISTEMA ANTIGO")] + LoagAcaoAntigo = 22, + [Category("HABILITA A OPÇÃO DA CRIAÇÃO AUTOMÁTICA DE ESTORNO DE PAGAMENTO AOS VENDEDORES DURANTE A RECUSA DE DOCUMENTOS")] + [Description("CADASTRO DE APÓLICES - HABILITAR CRIAÇÃO DE ESTORNO AO RECUSAR DOCUMENTO")] + EstornoRecusa = 23, + [Category("AO ADICIONAR UM REPASSE DE VALOR FIXO NUMA PARCELA NEGATIVA, O SISTEMA GERARÁ O ESTORNO, COLOCANDO O VALOR DE REPASSE COM O VALOR NEGATIVO")] + [Description("REPASSES - PERMITIR ESTORNO DE VALOR FIXO")] + EstornoValorFixo = 24, + [Category("HABILITA O CÁCULO PROPORCIONAL DO VALOR FIXO DE REPASSE EM RELAÇÃO AO PERCENTUAL DE COMISSÃO RECEBIDA")] + [Description("REPASSES - HABILITAR REPASSE FIXO PROPORCIONAL AO PERCENTUAL DE COMISSÃO")] + ValorFixoProporcional = 25, + [Category("PERMITE O CADASTRO DE CHASSI EM DUPLICIDADE")] + [Description("CADASTRO DE ITENS - PERMITIR DUPLICIDADE DE CHASSI")] + ChassiDuplicado = 26, + [Category("PERMITE O CADASTRO FABRICANTE EM BRANCO")] + [Description("CADASTRO DE ITENS - PERMITIR FABRICANTE EM BRANCO")] + FabricanteBranco = 27, + [Category("IGNORA A REGRA ONDE NÃO PERMITE DESFAZER BAIXA DE FATURAS QUANDO HÁ FATURAS ACIMA BAIXADAS.")] + [Description("BAIXA DE COMISSÃO AUTOMÁTICA - PERMITIR DESFAZER BAIXA DE FATURA TELA DE COMISSÃO AUTOMÁTICA")] + DesfazerFatura = 28, + [Category("IGNORA A REGRA ONDE OBRIGA A INCLUSÃO DE E-MAIL PARA O CLIENTE.")] + [Description("CADASTRO DE CLIENTES - PERMITIR INCLUIR CLIENTE SEM E-MAIL")] + ClienteSemEmail = 29, + [Category("UTILIZA OS DADOS DE CONTATO DO USUÁRIO NA GERAÇÃO DO CARTÃO DE VISITA, COMO PADRÃO É UTILIZADO OS TELEFONES E E-MAILS CADASTRADOS NA TELA DE EMPRESAS/FILIAIS")] + [Description("CARTÃO VISITA - UTILIZAR DADOS DE CONTATO DO USUÁRIO NA GERAÇÃO DO CARTÃO")] + DadosUsuarioVisita = 30, + [Category("SOMA OS PRÊMIOS DOS ENDOSSOS DA APÓLICE PARA APRESENTAR NA LISTAGEM DO RELATÓRIO E EM SEUS SINTÉTICOS. O PROCESSO ACARRETA UM PROCESSO A MAIS NA GERAÇÃO DO RELATÓRIO E POR CONSEQUÊNCIA O TEMPO PARA EXIBIÇÃO IRÁ AUMENTAR.")] + [Description("RELATÓRIO DE RENOVAÇÕES - SOMAR PRÊMIOS")] + SomarPremioRelatorioRenovacoes = 31, + [Category("CONSIDERA A PARCELA ESPECIAL DO TIPO ACERTO DE COMISSÃO NA SOMA DE COMISSÃO RECEBIDA DA APÓLICE PARA DEMONSTRAÇÃO DE COMISSÃO PENDENTE NAS TELAS DE CONSULTA E CADASTRO DE APÓLICES.")] + [Description("BAIXA DE COMISSÃO - CONSIDERAR ACERTO DE COMISSÃO COMO COMISSÃO DA APÓLICE")] + ConsiderarAcertoComissao = 32, + [Category("PERMITE A VISUALIZAÇÃO DA DATA DE CONTROLE APENAS QUANDO O USUÁRIO FOR ADMINISTRADOR.")] + [Description("CADASTRO DE APÓLICES - DATA DE CONTROLE APENAS ADM")] + DataControleAdm = 33, + [Category("ALTERA A BASE DE PAGAMENTO DE VENDEDORES DE TODOS OS REPASSES PARA A DATA DE CONTROLE DA APÓLICE/ENDOSSO.\nNÃO RECOMENDAMOS HABILITAR ESSA OPÇÃO.")] + [Description("RELATÓRIO PAGAMENTO DE VENDEDORES - BASE DE PAGAMENTO DATA DE CONTROLE")] + RepasseDataControle = 34, + [Category("AO IMPORTAR FIANÇA LOCATÍCIA O SISTEMA INCLUI O LOCATÁRIO COMO SEGURADO, NORMALMENTE O SEGURADO É A IMOBILIÁRIA.")] + [Description("IMPORTADOR PDF - IMPORTAR LOCATÁRIO COMO SEGURADO")] + LocatarioCliente = 35, + [Category("PERMITE CADASTRAR TAREFAS PARA USUARIOS DE OUTRAS FILIAIS.")] + [Description("CADASTRO DE TAREFAS - TAREFAS ENTRE FILIAIS")] + TarefasFiliais = 36, + [Category("SELECIONA O % DE REPASSE DO VENDEDOR PRINCIPAL DA APOLICE E EXIBE NO RELATÓRIO DE PRODUÇÃO.")] + [Description("RELATÓRIO DE PRODUÇÃO - SELECIONAR % REPASSE VENDEDOR PRINCIPAL")] + RepasseProducao = 37, + [Category("NA TELA DE CRÍTICA DE DOCUMENTOS, POR PADRÃO, NÃO É APLICADO OS VINCULOS DE VENDEDORES DOS USUÁRIOS, ADICIONANDO ESSA CONFIGURAÇÃO ESSE VINCULO SERÁ APLICADO.")] + [Description("CRÍTICA DE DOCUMENTOS - APLICAR VINCULO DE VENDEDORES")] + VinculoVendedorCritica = 38, + [Category("PERMITE QUE O CAMPO DE OBSERVAÇÕES POSSA SER EDITADO SOMENTE NA TELA DE CADASTRO DE APÓLICES.")] + [Description("CADASTRO DE APÓLICES - PERMITIR EDIÇÃO DO CAMPO OBSERVAÇÃO")] + EditarObservacoes = 39, + [Category("NA PLANILHA COMPLETA, POR PADRÃO, É COLOCADO A PRIMEIRA FRANQUIA ENCONTRADA, ADICIONANDO ESSA CONFIGURAÇÃO O SISTEMA SOMA TODAS AS FRANQUIAS DO DOCUMENTO")] + [Description("PLANILHA COMPLETA - SOMAR FRANQUIAS NA PLANILHA")] + SomarFranquiaPlanilhaCompleta = 40, + [Category("ABRE UMA OPÇÃO PARA ESCOLHER UMA PASTA PARA SALVAR O EXCEL")] + [Description("EXCEL - SALVAR EXCEL")] + SalvarExcel = 41, + [Category("NO EXTRATO CASO UMA APOLICE POSSUA UM ENDOSSO CADASTRADO IRA REGISTRAR O NUMERO DO ENDOSSO NO CAMPO ADITAMENTO")] + [Description("EXTRATO - NUMERO DO ENDOSSO EM APÓLICES")] + NumEndossoExtrato = 42, + [Category("PERMITE QUE USUÁRIOS COM VINCULO DE VENDEDORES POSSAM VER APÓLICES SEM VENDEDOR CADASTRADO NAS TELAS DE CRITICA DE APÓLICE, CONSULTA DE DOCUMENTOS, CADASTRO DE APÓLICES E PESQUISA AVANÇADA.")] + [Description("VINCULO DE VENDEDORES")] + VinculoVendedorEmBranco = 43, + [Category("MOSTRA O NOME COMPLETO DA SEGURADORA EM TODOS OS RELATÓRIOS. ATENÇÃO: ESSA CONFIGURAÇÃO SOBREPÕE A CONFIGURAÇÃO DE APELIDO DA SEGURADORA.")] + [Description("RELATÓRIOS - NOME COMPLETO SEGURADORA")] + NomeCompletoSeguradora = 44, + [Category("PERMITE AGENDAR UMA TAREFA COM DATA RETROATIVA.")] + [Description("CADASTRO DE TAREFAS - PERMITIR DATA DE AGENDAMENTO RETROATIVA")] + AgendamentoTarefaRetroativo = 45, + [Category("CALCULA IOF PARA O CADASTRO DE FATURAS.")] + [Description("CADASTRO DE FATURAS - CALCULAR IOF")] + IofFaturas = 46, + [Category("DESABILITA A OPÇÃO DE ALTERAR O NOME DO ARQUIVO AO ANEXAR.")] + [Description("ANEXO DIGITAL - NÃO ALTERAR O NOME DO ARQUIVO")] + AlterarNomeArquivo = 47, + [Category("PERMITE A IMPORTAÇÃO DE EXTRATOS PELA FILIAL. ATENÇÃO: ESSA CONFIGURAÇÃO FUNCIONA SOMENTE PARA IMPORTAÇÃO E NÃO PARA A TELA DE COMISSÃO.")] + [Description("IMPORTADOR PDF - PERMITIR IMPORTAÇÃO DE EXTRATOS")] + FilialImportarExtrato = 48, + [Category("PERMITE QUE O CAMPO DE HISTÓRICO POSSA SER EDITADO.")] + [Description("CADASTRO DE SINISTROS - PERMITIR EDIÇÃO DO CAMPO HISTÓRICO")] + EditarHistorico = 49, + [Category("VALORES NEGATIVOS (TANTO ESTORNOS QUANTO ADIANTAMENTOS) SERÃO DESCONSIDERADOS AO EMITIR O RELATORIO DE PAGAMENTO DE VENDEDORES.\nNÃO RECOMENDAMOS HABILITAR ESSA OPÇÃO.")] + [Description("RELATÓRIO PAGAMENTO DE VENDEDORES - OPÇÃO DE DESCONSIDERAR VALORES NEGATIVOS")] + DesconsiderarNegativos = 50, + [Category("DESABILITA A BUSCA DE APÓLICES POR APROXIMAÇÃO.")] + [Description("COMISSÃO AUTOMÁTICA - DESATIVA A BUSCA POR APROXIMAÇÃO")] + DesabilitaBuscaAproximada = 51, + [Category("NÃO UTILIZA O ENDEREÇO DA CORRETORA NA GERAÇÃO DO CARTÃO DE VISITA, COMO PADRÃO É UTILIZADO O ENDEREÇO CADASTRADO NA TELA DE EMPRESAS/FILIAIS")] + [Description("CARTÃO VISITA - NÃO UTILIZA O ENDEREÇO DA CORRETORA NA GERAÇÃO DO CARTÃO")] + SemEnderecoCorretoraVisita = 52, + [Category("DESABILITA AS VERIFICAÇÕES DE CRÍTICA PDF DENTRO DA IMPORTAÇÃO. \nNÃO RECOMENDAMOS HABILITAR ESSA OPÇÃO.")] + [Description("IMPORTADOR PDF - DESABILITAR CRÍTICA PDF NA IMPORTAÇÃO")] + DesabilitaCriticaImport = 53, + [Category("VALORES MENORES QUE A TOLERÂNCIA SERÃO SOLICITADOS CONFIRMAÇÃO PARA QUE NÃO SEJAM BAIXADOS POR ESGOTAMENTO, PORTANTO ZERADOS. \nNÃO RECOMENDAMOS HABILITAR ESSA OPÇÃO.")] + [Description("BAIXA COMISSÃO/REPASSE - SOLICITA CONFIRMAÇÃO BAIXA POR ESGOTAMENTO")] + SolicitaConfirmacaoBaixaEsgotamento = 54, + [Category("HABILITA VISUALIZAÇÃO DA AUDITORIA DO SISTEMA (DETALHES DO LOG)")] + [Description("LOG - HABILITAR VISUALIZAÇÃO DA AUDITORIA (DETALHES)")] + LogDetalhesVisivel = 55, + [Category("HABILITA O CADASTRO DE VENDEDOR E REPASSE COM CO-CORRETAGEM, TAMBÉM HABILITA O USO DE CO-CORRETAGEM NO DOCUMENTO.")] + [Description("REPASSE - HABILITAR USO DE CO-CORRETAGEM.")] + CoCorretagem = 56 + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/ConfiguracaoImpressao.cs b/Codemerx/Gestor.Model/Model.Common/ConfiguracaoImpressao.cs new file mode 100644 index 0000000..7e6dc6a --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/ConfiguracaoImpressao.cs @@ -0,0 +1,32 @@ +using Gestor.Model.Domain.Relatorios; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Common +{ + public class ConfiguracaoImpressao + { + public List<ParametrosRelatorio> Campos + { + get; + set; + } + + public bool? OrientacaoImpressao + { + get; + set; + } + + public int TamanhoFonte + { + get; + set; + } + + public ConfiguracaoImpressao() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/Cor.cs b/Codemerx/Gestor.Model/Model.Common/Cor.cs new file mode 100644 index 0000000..ebe80a7 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/Cor.cs @@ -0,0 +1,63 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum Cor + { + [Description("SEM INFORMAÇÃO")] + [OldValue("0")] + OutrosNull, + [Description("PRETO")] + [OldValue("1")] + Preto, + [Description("BRANCO")] + [OldValue("2")] + Branco, + [Description("CINZA")] + [OldValue("3")] + Cinza, + [Description("PRATA")] + [OldValue("4")] + Prata, + [Description("VERMELHO")] + [OldValue("5")] + Vermelho, + [Description("AMARELO")] + [OldValue("6")] + Amarelo, + [Description("OURO")] + [OldValue("7")] + Ouro, + [Description("LARANJA")] + [OldValue("8")] + Laranja, + [Description("ROSA")] + [OldValue("9")] + Rosa, + [Description("VERDE")] + [OldValue("10")] + Verde, + [Description("AZUL")] + [OldValue("11")] + Azul, + [Description("VINHO")] + [OldValue("12")] + Vinho, + [Description("MARROM")] + [OldValue("13")] + Marrom, + [Description("BEGE")] + [OldValue("14")] + Bege, + [Description("DOURADO")] + [OldValue("15")] + Dourado, + [Description("OUTROS")] + [OldValue("16")] + Outros + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/Correcao.cs b/Codemerx/Gestor.Model/Model.Common/Correcao.cs new file mode 100644 index 0000000..24ff966 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/Correcao.cs @@ -0,0 +1,18 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum Correcao + { + [Description("VALOR DE MERCADO")] + [OldValue("0")] + Mercado, + [Description("VALOR DETERMINADO")] + [OldValue("1")] + Determinado + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/DistanciaTrabalho.cs b/Codemerx/Gestor.Model/Model.Common/DistanciaTrabalho.cs new file mode 100644 index 0000000..b121242 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/DistanciaTrabalho.cs @@ -0,0 +1,30 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum DistanciaTrabalho + { + [Description("NÃO SE APLICA")] + [OldValue("0")] + NaoSeAplica, + [Description("ATÉ 10 KM")] + [OldValue("1")] + Ate10Km, + [Description("ATÉ 20 KM")] + [OldValue("2")] + Ate20Km, + [Description("ATÉ 30 KM")] + [OldValue("3")] + Ate30Km, + [Description("ATÉ 40 KM")] + [OldValue("4")] + Ate40Km, + [Description("ACIMA DE 40 KM")] + [OldValue("5")] + AcimaDe40Km + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/EquipamentoIncendio.cs b/Codemerx/Gestor.Model/Model.Common/EquipamentoIncendio.cs new file mode 100644 index 0000000..f285a3d --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/EquipamentoIncendio.cs @@ -0,0 +1,19 @@ +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + public enum EquipamentoIncendio + { + [Description("Extintor")] + Extintor = 1, + [Description("Hidrante")] + Hidrante = 2, + [Description("Sprinkler")] + Sprinkler = 3, + [Description("Detector de Fumaça")] + DetectorFumaca = 4, + [Description("Brigada de Incêndio")] + BrigadaIncendio = 5 + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/EquipamentoSeguranca.cs b/Codemerx/Gestor.Model/Model.Common/EquipamentoSeguranca.cs new file mode 100644 index 0000000..1083e33 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/EquipamentoSeguranca.cs @@ -0,0 +1,19 @@ +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + public enum EquipamentoSeguranca + { + [Description("Alarme")] + Alarme = 1, + [Description("Cerca Elétrica")] + CercaEletrica = 2, + [Description("Circuito Fechado de CFTV")] + CircuitoFechado = 3, + [Description("Porteiro Eletrônico")] + PorteiroEletronico = 4, + [Description("Catraca Eletrônica")] + CatracaEletronica = 5 + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/EstadoCivil.cs b/Codemerx/Gestor.Model/Model.Common/EstadoCivil.cs new file mode 100644 index 0000000..847f174 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/EstadoCivil.cs @@ -0,0 +1,36 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum EstadoCivil + { + [Description("CASADO(A)")] + [OldValue("C")] + Casado, + [Description("DIVORCIADO(A)")] + [OldValue("D")] + Divorciado, + [Description("SEPARADO(A)")] + [OldValue("X")] + Separado, + [Description("SOLTEIRO(A)")] + [OldValue("S")] + Solteiro, + [Description("VIÚVO(A)")] + [OldValue("V")] + Viuvo, + [Description("AMASIADO(A)")] + [OldValue("A")] + Amasiado, + [Description("UNIÃO ESTÁVEL")] + [OldValue("U")] + UniaoEstavel, + [Description("OUTRO")] + [OldValue("O")] + Outros + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/FiltroArquivoDigital.cs b/Codemerx/Gestor.Model/Model.Common/FiltroArquivoDigital.cs new file mode 100644 index 0000000..4068f80 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/FiltroArquivoDigital.cs @@ -0,0 +1,36 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Common +{ + public class FiltroArquivoDigital + { + public long Id + { + get; + set; + } + + public long IdApolice + { + get; + set; + } + + public object Parente + { + get; + set; + } + + public TipoArquivoDigital Tipo + { + get; + set; + } + + public FiltroArquivoDigital() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/FiltroCritica.cs b/Codemerx/Gestor.Model/Model.Common/FiltroCritica.cs new file mode 100644 index 0000000..43234fe --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/FiltroCritica.cs @@ -0,0 +1,15 @@ +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum FiltroCritica + { + [Description("CLIENTE")] + Cliente, + [Description("USUÁRIO")] + Usuario + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/FiltroLancamento.cs b/Codemerx/Gestor.Model/Model.Common/FiltroLancamento.cs new file mode 100644 index 0000000..03a28fe --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/FiltroLancamento.cs @@ -0,0 +1,23 @@ +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum FiltroLancamento + { + [Description("VENCIMENTO")] + Vencimento, + [Description("BAIXA")] + Baixa, + [Description("PAGAMENTO")] + Pagamento, + [Description("FORNECEDOR")] + Fornecedor, + [Description("LANÇAMENTO")] + Lancamento, + [Description("PERSONALIZADO")] + Personalizado + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/FiltroLancamentoData.cs b/Codemerx/Gestor.Model/Model.Common/FiltroLancamentoData.cs new file mode 100644 index 0000000..741a2fc --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/FiltroLancamentoData.cs @@ -0,0 +1,17 @@ +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum FiltroLancamentoData + { + [Description("VENCIMENTO")] + Vencimento, + [Description("DATA DE BAIXA")] + Baixa, + [Description("DATA PAGAMENTO")] + Pagamento + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/FiltroStatusDocumento.cs b/Codemerx/Gestor.Model/Model.Common/FiltroStatusDocumento.cs new file mode 100644 index 0000000..9a7424a --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/FiltroStatusDocumento.cs @@ -0,0 +1,21 @@ +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum FiltroStatusDocumento + { + [Description("DOCUMENTOS VIGENTES")] + Ativos, + [Description("DOCUMENTOS VENCIDOS")] + Vencidos, + [Description("DOCUMENTOS CANCELADOS")] + Cancelados, + [Description("DOCUMENTOS RECUSADOS")] + Recusados, + [Description("TODOS DOCUMENTOS")] + Todos + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/FormaPagamento.cs b/Codemerx/Gestor.Model/Model.Common/FormaPagamento.cs new file mode 100644 index 0000000..9c814e9 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/FormaPagamento.cs @@ -0,0 +1,63 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum FormaPagamento + { + [Description("TODAS EM DÉBITO")] + [OldValue("0")] + Debito, + [Description("TODAS EM CARTÃO")] + [OldValue("1")] + Cartao, + [Description("TODAS EM BOLETO")] + [OldValue("2")] + Boleto, + [Description("1ª BOLETO E DEMAIS DÉBITO")] + [OldValue("3")] + PrimeiraBoleto, + [Description("NENHUM")] + [OldValue("4")] + Nenhum, + [Description("FATURA")] + [OldValue("5")] + Fatura, + [Description("1ª DÉBITO E DEMAIS BOLETO")] + [OldValue("6")] + PrimeiraDebito, + [Description("CRÉDITO EM CONTA")] + [OldValue("7")] + Credito, + [Description("CARNÊ")] + [OldValue("8")] + Carne, + [Description("1º BOLETO E DEMAIS NO CARNÊ")] + [OldValue("9")] + PrimeiraBoletoDemaisCarne, + [Description("FICHA + CARNÊ")] + [OldValue("10")] + FichaMaisCarne, + [Description("DÓLAR")] + [OldValue("11")] + Dolar, + [Description("À VISTA")] + [OldValue("12")] + AVista, + [Description("1ª BOLETO E DEMAIS C. CRÉDITO")] + [OldValue("13")] + PrimeiraBoletoDemaisCredito, + [Description("1ª CARTÃO E DEMAIS BOLETO")] + [OldValue("14")] + PrimeiraCartaoDemaisBoleto, + [Description("PIX")] + [OldValue("15")] + Pix, + [Description("TODAS EM CARTÃO SEGURADORA")] + [OldValue("16")] + CartaoSeguradora + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/FormaRepasse.cs b/Codemerx/Gestor.Model/Model.Common/FormaRepasse.cs new file mode 100644 index 0000000..3ae4a15 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/FormaRepasse.cs @@ -0,0 +1,21 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum FormaRepasse + { + [Description("CONFORME O RECEBIMENTO")] + [OldValue("1")] + Recebimento = 1, + [Description("SEMPRE À VISTA")] + [OldValue("2")] + Vista = 2, + [Description("SEMPRE À PRAZO")] + [OldValue("3")] + Prazo = 3 + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/GaragemResidencia.cs b/Codemerx/Gestor.Model/Model.Common/GaragemResidencia.cs new file mode 100644 index 0000000..7229c13 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/GaragemResidencia.cs @@ -0,0 +1,27 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum GaragemResidencia + { + [Description("COM PORTÃO ELETRONICO")] + [OldValue("1")] + ComPortaoEletronico, + [Description("COM PORTÃO MANUAL")] + [OldValue("2")] + Fechada, + [Description("NÃO POSSUI GARAGEM")] + [OldValue("3")] + NaoPossuiGaragem, + [Description("NÃO UTILIZA PARA ESTE FIM")] + [OldValue("4")] + NaoUtilizaParaEsteFim, + [Description("NÃO INFORMADO")] + [OldValue("5")] + NaoInformado + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/GaragemTrabalhoEstudo.cs b/Codemerx/Gestor.Model/Model.Common/GaragemTrabalhoEstudo.cs new file mode 100644 index 0000000..2ee3a1c --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/GaragemTrabalhoEstudo.cs @@ -0,0 +1,30 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum GaragemTrabalhoEstudo + { + [Description("NÃO UTILIZA PARA ESTE FIM")] + [OldValue("0")] + NaoUtiliza, + [Description("NÃO")] + [OldValue("1")] + Nao, + [Description("SIM")] + [OldValue("2")] + Sim, + [Description("NÃO INFORMADO")] + [OldValue("3")] + NaoInformado, + [Description("NÃO ESTUDA")] + [OldValue("4")] + NaoEstuda, + [Description("NÃO TRABALHA")] + [OldValue("5")] + NaoTrabalha + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/Isencao.cs b/Codemerx/Gestor.Model/Model.Common/Isencao.cs new file mode 100644 index 0000000..c7bb5e6 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/Isencao.cs @@ -0,0 +1,24 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum Isencao + { + [Description("SEM ISENÇÃO")] + [OldValue("0")] + SemIsencao, + [Description("ICMS")] + [OldValue("1")] + Icms, + [Description("IPI")] + [OldValue("2")] + Ipi, + [Description("IPI E ICMS")] + [OldValue("3")] + IpiIcms + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/Localizacao.cs b/Codemerx/Gestor.Model/Model.Common/Localizacao.cs new file mode 100644 index 0000000..b62c89d --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/Localizacao.cs @@ -0,0 +1,30 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum Localizacao + { + [Description("OUTROS")] + [OldValue("1")] + Outros, + [Description("AEROPORTO")] + [OldValue("2")] + Aeroporto, + [Description("CEASA/MERCADO")] + [OldValue("3")] + Ceasa, + [Description("CONDOMÍNIO COMERCIAL")] + [OldValue("4")] + CondominioComercial, + [Description("SHOPPING")] + [OldValue("5")] + Shopping, + [Description("SUPERMERCADO")] + [OldValue("6")] + Supermercado + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/ManutencaoItem.cs b/Codemerx/Gestor.Model/Model.Common/ManutencaoItem.cs new file mode 100644 index 0000000..b8f59fb --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/ManutencaoItem.cs @@ -0,0 +1,25 @@ +using Gestor.Model.Domain.Seguros; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Common +{ + public class ManutencaoItem + { + public Gestor.Model.Domain.Seguros.Documento Documento + { + get; + set; + } + + public TipoManutencao Tipo + { + get; + set; + } + + public ManutencaoItem() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/Mes.cs b/Codemerx/Gestor.Model/Model.Common/Mes.cs new file mode 100644 index 0000000..06a2a45 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/Mes.cs @@ -0,0 +1,48 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum Mes + { + [Description("JANEIRO")] + [OldValue("1")] + Janeiro = 1, + [Description("FEVEREIRO")] + [OldValue("2")] + Fevereiro = 2, + [Description("MARÇO")] + [OldValue("3")] + Marco = 3, + [Description("ABRIL")] + [OldValue("4")] + Abril = 4, + [Description("MAIO")] + [OldValue("5")] + Maio = 5, + [Description("JUNHO")] + [OldValue("6")] + Junho = 6, + [Description("JULHO")] + [OldValue("7")] + Julho = 7, + [Description("AGOSTO")] + [OldValue("8")] + Agosto = 8, + [Description("SETEMBRO")] + [OldValue("9")] + Setembro = 9, + [Description("OUTUBRO")] + [OldValue("10")] + Outubro = 10, + [Description("NOVEMBRO")] + [OldValue("11")] + Novembro = 11, + [Description("DEZEMBRO")] + [OldValue("12")] + Dezembro = 12 + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/Negocio.cs b/Codemerx/Gestor.Model/Model.Common/Negocio.cs new file mode 100644 index 0000000..3b77342 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/Negocio.cs @@ -0,0 +1,18 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum Negocio + { + [Description("PRÓPRIA")] + [OldValue("1")] + Proprio = 1, + [Description("OUTRA CORRETORA")] + [OldValue("2")] + Outro = 2 + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/NegocioCorretora.cs b/Codemerx/Gestor.Model/Model.Common/NegocioCorretora.cs new file mode 100644 index 0000000..95aa863 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/NegocioCorretora.cs @@ -0,0 +1,18 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum NegocioCorretora + { + [Description("NOVO NEGÓCIO")] + [OldValue("0")] + Novo, + [Description("NEGÓCIO PRÓPRIO")] + [OldValue("1")] + Proprio + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/Ocupacao.cs b/Codemerx/Gestor.Model/Model.Common/Ocupacao.cs new file mode 100644 index 0000000..7b4731b --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/Ocupacao.cs @@ -0,0 +1,30 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum Ocupacao + { + [Description("NÃO POSSUI OCUPAÇÃO")] + [OldValue("0")] + NaoPossuiOcupacao, + [Description("ASSALARIADO(A)")] + [OldValue("1")] + Assalariado, + [Description("ESTUDANTE")] + [OldValue("2")] + Estudante, + [Description("ASSALARIADO(A) E ESTUDANTE")] + [OldValue("3")] + AsssalariadoEstudante, + [Description("APOSENTADO(A)")] + [OldValue("4")] + Aposentado, + [Description("OUTROS")] + [OldValue("5")] + Outros + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/Operacao.cs b/Codemerx/Gestor.Model/Model.Common/Operacao.cs new file mode 100644 index 0000000..1970e86 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/Operacao.cs @@ -0,0 +1,13 @@ +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + public enum Operacao + { + [Description(" AND ")] + And, + [Description(" OR ")] + Or + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/Operador.cs b/Codemerx/Gestor.Model/Model.Common/Operador.cs new file mode 100644 index 0000000..c9ef82b --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/Operador.cs @@ -0,0 +1,29 @@ +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + public enum Operador + { + [Description("=")] + Igual, + [Description("!=")] + Diferente, + [Description(">=")] + MaiorEIgual, + [Description(">")] + Maior, + [Description("LIKE")] + Like, + [Description("NOT LIKE")] + NotLike, + [Description("<")] + Menor, + [Description("<=")] + MenorEIgual, + [Description("LIKE")] + ComecaCom, + [Description("LIKE")] + TerminaCom + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/Parentesco.cs b/Codemerx/Gestor.Model/Model.Common/Parentesco.cs new file mode 100644 index 0000000..a8c9047 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/Parentesco.cs @@ -0,0 +1,99 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum Parentesco + { + [Description("PAI")] + [OldValue("0")] + Pai, + [Description("FILHO")] + [OldValue("1")] + Filho, + [Description("MÃE")] + [OldValue("2")] + Mae, + [Description("IRMÃOS")] + [OldValue("3")] + Irmaos, + [Description("AVÓS")] + [OldValue("4")] + Avos, + [Description("TIOS")] + [OldValue("5")] + Tios, + [Description("SOBRINHOS")] + [OldValue("6")] + Sobrinhos, + [Description("BISAVÓS")] + [OldValue("7")] + Bisavos, + [Description("PRIMOS")] + [OldValue("8")] + Primos, + [Description("SOGRA")] + [OldValue("9")] + Sogra, + [Description("SOGRO")] + [OldValue("10")] + Sogro, + [Description("GENRO")] + [OldValue("11")] + Genro, + [Description("NORA")] + [OldValue("12")] + Nora, + [Description("CUNHADO")] + [OldValue("13")] + Cunhado, + [Description("CUNHADA")] + [OldValue("14")] + Cunhada, + [Description("CONCUNHADO")] + [OldValue("15")] + Concunhado, + [Description("CONCUNHADA")] + [OldValue("16")] + Concunhada, + [Description("PADRASTO")] + [OldValue("17")] + Padrasto, + [Description("MADRASTA")] + [OldValue("18")] + Madrasta, + [Description("ENTEADO")] + [OldValue("19")] + Enteado, + [Description("ENTEADA")] + [OldValue("20")] + Enteada, + [Description("CÔNJUGE")] + [OldValue("21")] + Conjuge, + [Description("SÓCIO")] + [OldValue("22")] + Socio, + [Description("FUNCIONÁRIO")] + [OldValue("23")] + Funcionário, + [Description("EX-CÔNJUGE")] + [OldValue("24")] + Exconjuge, + [Description("AMIGO(A)")] + [OldValue("25")] + Amigo, + [Description("NETO")] + [OldValue("26")] + Neto, + [Description("PROPRIETÁRIO DA EMPRESA")] + [OldValue("27")] + Proprietario, + [Description("SÍNDICO")] + [OldValue("28")] + Sindico + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/ParentescoVinculo.cs b/Codemerx/Gestor.Model/Model.Common/ParentescoVinculo.cs new file mode 100644 index 0000000..e8551b3 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/ParentescoVinculo.cs @@ -0,0 +1,84 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum ParentescoVinculo + { + [Description("MÃE/PAI")] + [OldValue("0")] + MaePai, + [Description("FILHO(A)")] + [OldValue("1")] + Filho, + [Description("IRMÃO(A)")] + [OldValue("2")] + Irmao, + [Description("AVÔ(Ó)")] + [OldValue("3")] + Avo, + [Description("NETO(A)")] + [OldValue("4")] + Neto, + [Description("TIO(A)")] + [OldValue("5")] + Tio, + [Description("SOBRINHO(A)")] + [OldValue("6")] + Sobrinho, + [Description("BISAVÔ(Ó)")] + [OldValue("7")] + Bisavo, + [Description("BISNETO(A)")] + [OldValue("8")] + Bisneto, + [Description("PRIMO(A)")] + [OldValue("9")] + Primo, + [Description("SOGRO(A)")] + [OldValue("10")] + Sogro, + [Description("GENRO/NORA")] + [OldValue("11")] + Genro, + [Description("CUNHADO(A)")] + [OldValue("12")] + Cunhado, + [Description("MADRASTA/PADRASTO")] + [OldValue("13")] + MadrastaPadrasto, + [Description("ENTEADO(A)")] + [OldValue("14")] + Enteado, + [Description("CÔNJUGE")] + [OldValue("15")] + Conjuge, + [Description("EX-CÔNJUGE")] + [OldValue("16")] + Exconjuge, + [Description("SÓCIO(A)")] + [OldValue("17")] + Socio, + [Description("AMIGO(A)")] + [OldValue("18")] + Amigo, + [Description("PROPRIETÁRIO(A)")] + [OldValue("19")] + Proprietario, + [Description("PROPRIEDADE")] + [OldValue("20")] + Propriedade, + [Description("CONTRATANTE")] + [OldValue("21")] + Contratante, + [Description("FUNCIONÁRIO(A)")] + [OldValue("22")] + Funcionario, + [Description("OUTROS")] + [OldValue("23")] + Outros + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/PermissaoAggilizador.cs b/Codemerx/Gestor.Model/Model.Common/PermissaoAggilizador.cs new file mode 100644 index 0000000..9e06911 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/PermissaoAggilizador.cs @@ -0,0 +1,19 @@ +using Gestor.Model.Domain.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Common +{ + public class PermissaoAggilizador : DomainBase + { + public string Descricao + { + get; + set; + } + + public PermissaoAggilizador() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/Rastreador.cs b/Codemerx/Gestor.Model/Model.Common/Rastreador.cs new file mode 100644 index 0000000..c88bbb8 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/Rastreador.cs @@ -0,0 +1,66 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum Rastreador + { + [Description("NÃO POSSUI")] + [OldValue("0")] + NaoPossui, + [Description("AUTO TRAC")] + [OldValue("1")] + AutoTrac, + [Description("CAR SYSTEM")] + [OldValue("2")] + CarSystem, + [Description("CELTEC")] + [OldValue("3")] + Celtec, + [Description("CIELO")] + [OldValue("4")] + Cielo, + [Description("GRABER")] + [OldValue("5")] + Graber, + [Description("ITURAN")] + [OldValue("6")] + Ituran, + [Description("TRACKER")] + [OldValue("7")] + Tracker, + [Description("OMNILINK")] + [OldValue("8")] + Omnilink, + [Description("POSITRON")] + [OldValue("9")] + Positron, + [Description("SASCAR")] + [OldValue("10")] + Sascar, + [Description("DAF-V")] + [OldValue("11")] + Dafv, + [Description("CEABS")] + [OldValue("12")] + CEABS, + [Description("ONSTAR")] + [OldValue("13")] + OnStar, + [Description("LO JACK")] + [OldValue("14")] + LoJack, + [Description("ORIGINAL DE FÁBRICA")] + [OldValue("15")] + OriginalDeFabrica, + [Description("SEGSAT")] + [OldValue("16")] + Segsat, + [Description("SAT COMPANY")] + [OldValue("17")] + SatCompany + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/Relacao.cs b/Codemerx/Gestor.Model/Model.Common/Relacao.cs new file mode 100644 index 0000000..aefa5cb --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/Relacao.cs @@ -0,0 +1,42 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum Relacao + { + [Description("PRÓPRIO")] + [OldValue("0")] + Proprio, + [Description("PROPRIETÁRIO(A)")] + [OldValue("1")] + Proprietario, + [Description("CÔNJUGE")] + [OldValue("2")] + Conjuge, + [Description("EMPREGADO(A)")] + [OldValue("3")] + Empregado, + [Description("IRMÃO(Ã)")] + [OldValue("4")] + Irmao, + [Description("FILHO(A)")] + [OldValue("5")] + Filho, + [Description("MÃE")] + [OldValue("6")] + Mae, + [Description("PAI")] + [OldValue("7")] + Pai, + [Description("OUTROS")] + [OldValue("8")] + Outros, + [Description("INDETERMINADO")] + [OldValue("9")] + Indeterminado + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/Relatorio.cs b/Codemerx/Gestor.Model/Model.Common/Relatorio.cs new file mode 100644 index 0000000..700754d --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/Relatorio.cs @@ -0,0 +1,132 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum Relatorio + { + [Description("RELATÓRIO DE CLIENTE")] + [OldValue("1000")] + [Tipo("CLIENTE")] + Cliente, + [Description("RELATÓRIO DE ANIVERSARIANTE")] + [OldValue("1001")] + [Tipo("CLIENTE")] + Aniversariante, + [Description("RELATÓRIO DE PRODUÇÃO")] + [OldValue("1002")] + [Tipo("DOCUMENTO")] + Producao, + [Description("RELATÓRIO DE APÓLICES PENDENTES")] + [OldValue("1003")] + [Tipo("DOCUMENTO")] + ApolicePendente, + [Description("RELATÓRIO DE RENOVAÇÕES")] + [OldValue("1004")] + [Tipo("DOCUMENTO")] + Renovacao, + [Description("RELATÓRIO DE RECEBIMENTO DE COMISSÃO")] + [OldValue("1005")] + [Tipo("PARCELA")] + Comissao, + [Description("RELATÓRIO DE COMISSÃO A RECEBER")] + [OldValue("1006")] + [Tipo("PARCELA")] + Pendente, + [Description("RELATÓRIO DE PAGAMENTO DE VENDEDOR")] + [OldValue("1007")] + [Tipo("PARCELA")] + Pagamento, + [Description("RELATÓRIO DE AUDITORIA DE COMISSÃO")] + [OldValue("1008")] + [Tipo("FECHAMENTO")] + Auditoria, + [Description("RELATÓRIO DE SINISTRO PENDENTE")] + [OldValue("1009")] + [Tipo("SINISTRO")] + SinistroPendente, + [Description("RELATÓRIO DE SINISTRO")] + [OldValue("1010")] + [Tipo("SINISTRO")] + Sinistro, + [Description("RELATÓRIO DE FECHAMENTO")] + [OldValue("1011")] + [Tipo("FECHAMENTO")] + Fechamento, + [Description("RELATÓRIO DE FATURAS PENDENTES")] + [OldValue("1012")] + [Tipo("PARCELA")] + FaturaPendente, + [Description("RELATÓRIO DE EXTRATOS BAIXADOS NO PERIODO")] + [OldValue("1013")] + [Tipo("EXTRATO")] + ExtratosBaixados, + [Description("RELATÓRIO DE METAS DE SEGURADORAS")] + [OldValue("1014")] + [Tipo("DOCUMENTO")] + MetaSeguradora, + [Description("RELATÓRIO DE METAS DE VENDEDORES")] + [OldValue("1015")] + [Tipo("DOCUMENTO")] + MetaVendedor, + [Description("RELATÓRIO DE VENCIMENTO DE PARCELAS")] + [OldValue("1016")] + [Tipo("PARCELA")] + ParcelasVencendo, + [Description("RELATÓRIO DE LICENCIAMENTO")] + [OldValue("1017")] + [Tipo("CLIENTE")] + Licenciamento, + [Description("RELATÓRIO DE TAREFAS")] + [OldValue("1018")] + [Tipo("TAREFA")] + Tarefa, + [Description("RELATÓRIO DE NOTAS FISCAIS")] + [OldValue("1019")] + [Tipo("NOTA FISCAL")] + NotaFiscal, + [Description("RELATÓRIO DE PREVISÃO DE PAGAMENTO DE COMISSÃO")] + [OldValue("1020")] + [Tipo("PARCELA")] + PrevisaoPagamentoComissao, + [Description("RELATÓRIO DE ASSINATURAS ENVIADAS")] + [OldValue("1021")] + [Tipo("DOCUMENTO")] + AssinaturasEnviadas, + [Description("PRODUÇÃO")] + [OldValue("1022")] + [Tipo("DOCUMENTO")] + Apolice, + [Description("RELATÓRIO DE LOGS DE ENVIO DE E-MAIL")] + [OldValue("1023")] + [Tipo("LOGS")] + LogsEnvio, + [Description("RELATÓRIO DE LOGS UTILIZAÇÃO")] + [OldValue("1024")] + [Tipo("LOGS")] + LogsUtilizacao, + [Description("RELATÓRIO DE LOGS UTILIZAÇÃO SISTEMA ANTIGO")] + [OldValue("1025")] + [Tipo("LOGS")] + LogsUtilizacaoAntigo, + [Description("RELATÓRIO DE IMPORTAÇÃO")] + [OldValue("1026")] + [Tipo("DOCUMENTO")] + Importacao, + [Description("RELATÓRIO DE PLACAS")] + [OldValue("1027")] + [Tipo("DOCUMENTO")] + Placa, + [Description("RELATÓRIO DE ENDOSSO")] + [OldValue("1028")] + [Tipo("DOCUMENTO")] + Endosso, + [Description("RELATÓRIO DE CLASSIFICAÇÃO")] + [OldValue("1029")] + [Tipo("CLIENTE")] + Classificacao + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/Sexo.cs b/Codemerx/Gestor.Model/Model.Common/Sexo.cs new file mode 100644 index 0000000..db9da64 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/Sexo.cs @@ -0,0 +1,20 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum Sexo + { + [Description("MASCULINO")] + [OldValue2("1")] + [OldValue("0")] + Masculino, + [Description("FEMININO")] + [OldValue2("2")] + [OldValue("1")] + Feminino + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/Sinal.cs b/Codemerx/Gestor.Model/Model.Common/Sinal.cs new file mode 100644 index 0000000..7ddf8a5 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/Sinal.cs @@ -0,0 +1,18 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum Sinal + { + [Description("CRÉDITO")] + [OldValue("0")] + Credito, + [Description("DÉBITO")] + [OldValue("1")] + Debito + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/SinteticoFinanceiroTipo.cs b/Codemerx/Gestor.Model/Model.Common/SinteticoFinanceiroTipo.cs new file mode 100644 index 0000000..0eebaf5 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/SinteticoFinanceiroTipo.cs @@ -0,0 +1,21 @@ +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum SinteticoFinanceiroTipo + { + [Description("PLANO DE CONTAS")] + Plano, + [Description("CENTRO DE CUSTO")] + Centro, + [Description("FORNECEDOR")] + Fornecedor, + [Description("CONTA CORRENTE")] + Conta, + [Description("PLANO")] + PlanoRaiz + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/SqlQueryCondition.cs b/Codemerx/Gestor.Model/Model.Common/SqlQueryCondition.cs new file mode 100644 index 0000000..fcf3138 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/SqlQueryCondition.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Common +{ + public class SqlQueryCondition + { + public string Condicao + { + get; + set; + } + + public List<SqlParameter> Parametros + { + get; + set; + } + + public SqlQueryCondition() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/StatusAssinatura.cs b/Codemerx/Gestor.Model/Model.Common/StatusAssinatura.cs new file mode 100644 index 0000000..f4d6fd1 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/StatusAssinatura.cs @@ -0,0 +1,21 @@ +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum StatusAssinatura + { + [Description("ASSINATURA PENDENTE")] + Pendente, + [Description("DOCUMENTO ASSINADO")] + Assinado, + [Description("ASSINATURA REJEITADA")] + Rejeitado, + [Description("NÃO ENVIADO")] + NaoEnviado, + [Description("ASSINADO MANUALMENTE")] + AssinadoManualmente + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/StatusCalculo.cs b/Codemerx/Gestor.Model/Model.Common/StatusCalculo.cs new file mode 100644 index 0000000..2c38412 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/StatusCalculo.cs @@ -0,0 +1,25 @@ +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum StatusCalculo + { + [Description("Não Calculado")] + NaoCalculado, + [Description("Em Andamento")] + EmAndamento, + [Description("Ganho")] + Ganho, + [Description("Perdido")] + Perdido, + [Description("Enviado")] + Enviado, + [Description("Calculando")] + Calculando, + [Description("Salvando")] + Salvando + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/StatusDocumentoAssinado.cs b/Codemerx/Gestor.Model/Model.Common/StatusDocumentoAssinado.cs new file mode 100644 index 0000000..109a1b0 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/StatusDocumentoAssinado.cs @@ -0,0 +1,49 @@ +using Gestor.Model.Domain.Seguros; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Common +{ + public class StatusDocumentoAssinado + { + public string Documento + { + get; + set; + } + + public DateTime? Envio + { + get; + set; + } + + public long Id + { + get; + set; + } + + public bool Selecionado + { + get; + set; + } + + public StatusAssinatura Status + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Usuario Usuario + { + get; + set; + } + + public StatusDocumentoAssinado() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/StatusExtrato.cs b/Codemerx/Gestor.Model/Model.Common/StatusExtrato.cs new file mode 100644 index 0000000..c70550b --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/StatusExtrato.cs @@ -0,0 +1,23 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum StatusExtrato + { + [Description("PENDENTE")] + [OldValue("1")] + Pendente = 1, + [Description("INCOMPLETO")] + [OldValue("2")] + IncompletoFinalizado = 2, + [Description("BAIXADO")] + [OldValue("3")] + Baixado = 3, + [Description("TODOS")] + Todos = 4 + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/StatusItem.cs b/Codemerx/Gestor.Model/Model.Common/StatusItem.cs new file mode 100644 index 0000000..c6fa74a --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/StatusItem.cs @@ -0,0 +1,12 @@ +using System; + +namespace Gestor.Model.Common +{ + public enum StatusItem + { + Ativos, + Inativos, + Documento, + Controle + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/StatusLancamento.cs b/Codemerx/Gestor.Model/Model.Common/StatusLancamento.cs new file mode 100644 index 0000000..a14c0d1 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/StatusLancamento.cs @@ -0,0 +1,17 @@ +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum StatusLancamento + { + [Description("PENDENTES")] + Pendentes, + [Description("BAIXADOS")] + Baixados, + [Description("TODOS")] + Todos + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/StatusPagamento.cs b/Codemerx/Gestor.Model/Model.Common/StatusPagamento.cs new file mode 100644 index 0000000..9a1c77d --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/StatusPagamento.cs @@ -0,0 +1,17 @@ +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum StatusPagamento + { + [Description("SEM PENDÊNCIA")] + All, + [Description("PAGAMENTO PENDENTE")] + Pending, + [Description("PENDÊNCIA NOTIFICADA")] + Notified + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/StatusParcela.cs b/Codemerx/Gestor.Model/Model.Common/StatusParcela.cs new file mode 100644 index 0000000..e2895cc --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/StatusParcela.cs @@ -0,0 +1,75 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum StatusParcela + { + [Description("BAIXADA NORMALMENTE")] + [OldValue("1")] + Baixada = 1, + [Description("DOCUMENTO NÃO ENCONTRADO")] + [OldValue("2")] + DocumentoNaoEncontrado = 2, + [Description("PARCELA NÃO ENCONTRADA")] + [OldValue("3")] + ParcelaNaoEncontrada = 3, + [Description("DIFERENÇA DE COMISSÃO")] + [OldValue("4")] + DiferencaPercentual = 4, + [Description("BAIXADA ANTERIORMENTE")] + [OldValue("5")] + BaixadaAnteriormente = 5, + [Description("DESCONSIDERADA PELO USUÁRIO")] + [OldValue("6")] + DesconsideradaUsuario = 6, + [Description("ANTERIOR NÃO BAIXADA")] + [OldValue("7")] + ParcelaAnteriorNaoBaixada = 7, + [Description("DESCONSIDERADA PELO SISTEMA")] + [OldValue("8")] + DesconsideradaSistema = 8, + [Description("A SER BAIXADA")] + [OldValue("9")] + ASerBaixada = 9, + [Description("BAIXADA COM DIFERENÇA DE COMISSÃO")] + [OldValue("10")] + BaixadaDiferencaPercentual = 10, + [Description("APÓLICE DUPLICADA")] + [OldValue("11")] + ApoliceDuplicada = 11, + [Description("BAIXADA MANUALMENTE")] + [OldValue("12")] + BaixadaManualmente = 12, + [Description("BAIXADA PELA CRÍTICA")] + [OldValue("13")] + BaixadaCritica = 13, + [Description("A SER BAIXADA, CRÍTICA MANUAL")] + [OldValue("14")] + Criticada = 14, + [Description("FATURA NÃO ENCONTRADA")] + [OldValue("15")] + FaturaNaoEncontrada = 15, + [Description("A SER BAIXADO, ENCONTRADO POR APROXIMAÇÃO")] + [OldValue("16")] + ASerBaixadoPorAproximacao = 16, + [Description("PARCELA ESPECIAL A SER CRIADA")] + [OldValue("17")] + ParcelaEspecialASerCriada = 17, + [Description("A SER BAIXADO, ENCONTRADO POR APROXIMAÇÃO COM DIFERENÇA DE COMISSÃO")] + [OldValue("18")] + ASerBaixadoPorAproximacaoDiferencaPercentual = 18, + [Description("DOCUMENTO ENCONTRADO SEM % DE COMISSÃO")] + [OldValue("18")] + SemComissao = 19, + [Description("FATURA ENCONTRADA SEM % DE COMISSÃO")] + [OldValue("19")] + FaturaSemComissao = 20, + [Description("PARCELA ESPECIAL BAIXADA ANTERIORMENTE")] + [OldValue("20")] + ParcelaEspecialBaixadaAnteriormente = 21 + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/StatusProspeccao.cs b/Codemerx/Gestor.Model/Model.Common/StatusProspeccao.cs new file mode 100644 index 0000000..8720d3d --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/StatusProspeccao.cs @@ -0,0 +1,27 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum StatusProspeccao + { + [Description("AGENDADO")] + [OldValue("1")] + Agendado = 1, + [Description("GANHO")] + [OldValue("2")] + Ganho = 2, + [Description("PERDIDO")] + [OldValue("3")] + Perdido = 3, + [Description("NÃO TRABALHADO")] + [OldValue("4")] + NaoTrabalhado = 4, + [Description("EM ANDAMENTO")] + [OldValue("5")] + EmAndamento = 5 + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/StatusSinistro.cs b/Codemerx/Gestor.Model/Model.Common/StatusSinistro.cs new file mode 100644 index 0000000..96df478 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/StatusSinistro.cs @@ -0,0 +1,27 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum StatusSinistro + { + [Description("EM ANDAMENTO")] + [OldValue("1")] + EmAndamento = 1, + [Description("LIQUIDADO")] + [OldValue("2")] + Liquidado = 2, + [Description("LIQUIDADO SEM INDENIZAÇÃO")] + [OldValue("3")] + SemIndenizacao = 3, + [Description("NEGADO")] + [OldValue("4")] + Negado = 4, + [Description("ATENDIDO COMO TERCEIRO")] + [OldValue("5")] + Terceiro = 5 + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/StatusTarefa.cs b/Codemerx/Gestor.Model/Model.Common/StatusTarefa.cs new file mode 100644 index 0000000..ffabaf1 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/StatusTarefa.cs @@ -0,0 +1,17 @@ +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum StatusTarefa + { + [Description("PENDENTE")] + Pendente, + [Description("REAGENDADO")] + Reagendado, + [Description("REALIZADO")] + Realizado + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/SubTipo.cs b/Codemerx/Gestor.Model/Model.Common/SubTipo.cs new file mode 100644 index 0000000..3453227 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/SubTipo.cs @@ -0,0 +1,30 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum SubTipo + { + [Description("PARCELA NORMAL")] + [OldValue("1")] + ParcelaNormal = 1, + [Description("RESTITUIÇÃO")] + [OldValue("2")] + Restituicao = 2, + [Description("CRÉDITO")] + [OldValue("3")] + Credito = 3, + [Description("CUSTO DE APÓLICE")] + [OldValue("4")] + Custo = 4, + [Description("CARTÃO DE CRÉDITO")] + [OldValue("5")] + Cartao = 5, + [Description("ACERTO DE COMISSÃO")] + [OldValue("6")] + Acerto = 6 + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TabelaReferencia.cs b/Codemerx/Gestor.Model/Model.Common/TabelaReferencia.cs new file mode 100644 index 0000000..4b27359 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TabelaReferencia.cs @@ -0,0 +1,18 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TabelaReferencia + { + [Description("MOLICAR")] + [OldValue("0")] + Molicar, + [Description("FIPE")] + [OldValue("1")] + Fipe + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TempoHabilitacao.cs b/Codemerx/Gestor.Model/Model.Common/TempoHabilitacao.cs new file mode 100644 index 0000000..501b8f0 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TempoHabilitacao.cs @@ -0,0 +1,45 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TempoHabilitacao + { + [Description("UM ANO")] + [OldValue("1")] + UmAno, + [Description("DOIS ANOS")] + [OldValue("2")] + DoisAnos, + [Description("TRÊS ANOS")] + [OldValue("3")] + TresAnos, + [Description("QUATRO ANOS")] + [OldValue("4")] + QutroAnos, + [Description("CINCO ANOS")] + [OldValue("5")] + CincoAnos, + [Description("SEIS ANOS")] + [OldValue("6")] + SeisAnos, + [Description("SETE ANOS")] + [OldValue("7")] + SeteAnos, + [Description("OITO ANOS")] + [OldValue("8")] + OitoAnos, + [Description("NOVE ANOS")] + [OldValue("9")] + NoveAnos, + [Description("DEZ ANOS")] + [OldValue("10")] + DezAnos, + [Description("MAIS DE DEZ ANOS")] + [OldValue("11")] + MaisDeDezAnos + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoAcao.cs b/Codemerx/Gestor.Model/Model.Common/TipoAcao.cs new file mode 100644 index 0000000..ccb6dc9 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoAcao.cs @@ -0,0 +1,17 @@ +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoAcao + { + [Description("INSERÇÃO")] + Insert, + [Description("ATUALIZAÇÃO")] + Update, + [Description("EXCLUSÃO")] + Delete + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoAeronautico.cs b/Codemerx/Gestor.Model/Model.Common/TipoAeronautico.cs new file mode 100644 index 0000000..b59a788 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoAeronautico.cs @@ -0,0 +1,120 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoAeronautico + { + [Category("Aero")] + [Description("AERONAVE")] + [OldValue("1")] + Aeronave = 1, + [Category("Aero")] + [Description("BALÃO")] + [OldValue("2")] + Balao = 2, + [Category("Aero")] + [Description("PLANADOR")] + [OldValue("3")] + Planador = 3, + [Category("Aero")] + [Description("ULTRALEVE")] + [OldValue("4")] + Ultraleve = 4, + [Category("Aero")] + [Description("HELICÓPTERO")] + [OldValue("5")] + Helicoptero = 5, + [Category("Aero")] + [Description("HIDROAVIÃO")] + [OldValue("6")] + Hidroaviao = 6, + [Category("Aero")] + [Description("ECRANOPLANO")] + [OldValue("7")] + Ecranoplano = 7, + [Category("Aero")] + [Description("AVIÃO ANFÍBIO")] + [OldValue("8")] + AviãoAnfibio = 8, + [Category("Aero")] + [Description("GIROCÓPTERO")] + [OldValue("9")] + Girocoptero = 9, + [Category("Nautico")] + [Description("LANCHA")] + [OldValue("10")] + Lancha = 10, + [Category("Nautico")] + [Description("VELEIRO")] + [OldValue("11")] + Veleiro = 11, + [Category("Nautico")] + [Description("ESCUNA")] + [OldValue("12")] + Escuna = 12, + [Category("Nautico")] + [Description("TRANEIRA/PESQUEIRO")] + [OldValue("13")] + TraneiraPesqueiro = 13, + [Category("Nautico")] + [Description("TRAWLER")] + [OldValue("14")] + Trawler = 14, + [Category("Nautico")] + [Description("BARCO ALUMÍNEO")] + [OldValue("15")] + BarcoAlumineo = 15, + [Category("Nautico")] + [Description("BOTE INFLÁVEL")] + [OldValue("16")] + BoteInflavel = 16, + [Category("Nautico")] + [Description("JET-SKI")] + [OldValue("17")] + JetSki = 17, + [Category("Nautico")] + [Description("JET BOAT")] + [OldValue("18")] + JetBoat = 18, + [Category("Nautico")] + [Description("CAIAQUE")] + [OldValue("19")] + Caiaque = 19, + [Category("Nautico")] + [Description("CANOA")] + [OldValue("20")] + Canoa = 20, + [Category("Nautico")] + [Description("ALVARENGA")] + [OldValue("21")] + Alvarenga = 21, + [Category("Nautico")] + [Description("BARCAÇA")] + [OldValue("22")] + Barcaca = 22, + [Category("Nautico")] + [Description("CARGUEIRO")] + [OldValue("23")] + Cargueiro = 23, + [Category("Nautico")] + [Description("DRAGA")] + [OldValue("24")] + Draga = 24, + [Category("Nautico")] + [Description("IATE")] + [OldValue("25")] + Iate = 25, + [Category("Nautico")] + [Description("REBOCADOR")] + [OldValue("26")] + Rebocador = 26, + [Category("Aero")] + [Description("DRONE")] + [OldValue("27")] + Drone = 27 + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoArquivoDigital.cs b/Codemerx/Gestor.Model/Model.Common/TipoArquivoDigital.cs new file mode 100644 index 0000000..1a6f269 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoArquivoDigital.cs @@ -0,0 +1,47 @@ +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoArquivoDigital + { + [Description("TODOS")] + Todos, + [Description("CLIENTE")] + Cliente, + [Description("APÓLICE")] + Apolice, + [Description("PARCELA")] + Parcela, + [Description("ITEM")] + Item, + [Description("SINISTRO")] + Sinistro, + [Description("VENDEDOR")] + Vendedor, + [Description("EXTRATO")] + Extrato, + [Description("SEGURADORA")] + Seguradora, + [Description("LANÇAMENTO")] + Lancamento, + [Description("FORNECEDOR")] + Fornecedor, + [Description("PROSPECÇÃO")] + Prospeccao, + [Description("USUÁRIO")] + Usuario, + [Description("EMPRESA")] + Empresa, + [Description("SÓCIO")] + Socio, + [Description("TAREFA")] + Tarefa, + [Description("NOTA FISCAL")] + NotaFiscal, + [Description("ESTIPULANTE")] + Estipulante + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoArquivoVinculo.cs b/Codemerx/Gestor.Model/Model.Common/TipoArquivoVinculo.cs new file mode 100644 index 0000000..c66bdc0 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoArquivoVinculo.cs @@ -0,0 +1,10 @@ +using System; + +namespace Gestor.Model.Common +{ + public enum TipoArquivoVinculo + { + Proposta, + Apolice + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoCobertura.cs b/Codemerx/Gestor.Model/Model.Common/TipoCobertura.cs new file mode 100644 index 0000000..663288e --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoCobertura.cs @@ -0,0 +1,27 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoCobertura + { + [Description("COMPREENSIVA")] + [OldValue("1")] + Compreensiva = 1, + [Description("INCÊNDIO E ROUBO/FURTO")] + [OldValue("2")] + IncendioRouboFurto = 2, + [Description("DANOS A TERCEIROS")] + [OldValue("3")] + DanosTerceiros = 3, + [Description("PASSAGEIROS")] + [OldValue("4")] + Passageiros = 4, + [Description("ROUBO/FURTO")] + [OldValue("5")] + RouboFurto = 5 + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoConstrucao.cs b/Codemerx/Gestor.Model/Model.Common/TipoConstrucao.cs new file mode 100644 index 0000000..8b4c387 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoConstrucao.cs @@ -0,0 +1,24 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoConstrucao + { + [Description("SUPERIOR")] + [OldValue("1")] + SUPERIOR, + [Description("SÓLIDA")] + [OldValue("2")] + SOLIDA, + [Description("MISTA")] + [OldValue("3")] + MISTA, + [Description("INFERIOR")] + [OldValue("4")] + INFERIOR + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoConta.cs b/Codemerx/Gestor.Model/Model.Common/TipoConta.cs new file mode 100644 index 0000000..821da42 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoConta.cs @@ -0,0 +1,17 @@ +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoConta + { + [Description("NENHUM")] + Nenhum, + [Description("POUPANÇA")] + Poupanca, + [Description("CORRENTE")] + Corrente + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoContato.cs b/Codemerx/Gestor.Model/Model.Common/TipoContato.cs new file mode 100644 index 0000000..d2599a4 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoContato.cs @@ -0,0 +1,10 @@ +using System; + +namespace Gestor.Model.Common +{ + public enum TipoContato + { + Telefone, + Email + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoContatoSeguradora.cs b/Codemerx/Gestor.Model/Model.Common/TipoContatoSeguradora.cs new file mode 100644 index 0000000..760066a --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoContatoSeguradora.cs @@ -0,0 +1,17 @@ +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoContatoSeguradora + { + [Description("CONTATO")] + Contato, + [Description("ASSISTÊNCIA 24HS")] + Assistencia, + [Description("EMAIL")] + Email + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoDocumento.cs b/Codemerx/Gestor.Model/Model.Common/TipoDocumento.cs new file mode 100644 index 0000000..5de497b --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoDocumento.cs @@ -0,0 +1,24 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoDocumento + { + [Description("CPF/CNPJ")] + [OldValue("0")] + Cpf, + [Description("RNE")] + [OldValue("1")] + Rne, + [Description("CEI")] + [OldValue("2")] + Cei, + [Description("CAEPF")] + [OldValue("3")] + Caepf + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoEmail.cs b/Codemerx/Gestor.Model/Model.Common/TipoEmail.cs new file mode 100644 index 0000000..3dfb317 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoEmail.cs @@ -0,0 +1,17 @@ +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoEmail + { + [Description("OUTROS")] + Outros, + [Description("GOOGLE")] + Google, + [Description("MS OFFICE 365")] + Office365 + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoEndereco.cs b/Codemerx/Gestor.Model/Model.Common/TipoEndereco.cs new file mode 100644 index 0000000..452cdde --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoEndereco.cs @@ -0,0 +1,33 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoEndereco + { + [Description("OUTROS")] + [OldValue("1")] + Outros = 1, + [Description("CORRESPONDÊNCIA")] + [OldValue("2")] + Correspondencia = 2, + [Description("RESIDENCIAL")] + [OldValue("3")] + Residencial = 3, + [Description("COMERCIAL")] + [OldValue("4")] + Comercial = 4, + [Description("RECADO")] + [OldValue("5")] + Recado = 5, + [Description("COBRANÇA")] + [OldValue("6")] + Cobranca = 6, + [Description("FINANCEIRO")] + [OldValue("7")] + Financeiro = 7 + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoEndosso.cs b/Codemerx/Gestor.Model/Model.Common/TipoEndosso.cs new file mode 100644 index 0000000..6f83f7f --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoEndosso.cs @@ -0,0 +1,27 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoEndosso + { + [Description("COM MOVIMENTO DE PRÊMIO")] + [OldValue("0")] + ComMovimento, + [Description("SEM MOVIMENTO DE PRÊMIO")] + [OldValue("1")] + SemMovimento, + [Description("CANCELAMENTO DA APÓLICE")] + [OldValue("2")] + Cancelamento, + [Description("REABILITAÇÃO DA APÓLICE")] + [OldValue("3")] + Reabilitacao, + [Description("PRORROGAÇÃO DE VIGÊNCIA")] + [OldValue("4")] + Prorrogacao + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoExtrato.cs b/Codemerx/Gestor.Model/Model.Common/TipoExtrato.cs new file mode 100644 index 0000000..635277c --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoExtrato.cs @@ -0,0 +1,17 @@ +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoExtrato + { + [Description("SOMENTE CLIENTE")] + Cliente, + [Description("APÓLICE SELECIONADA")] + ApoliceSelecionada, + [Description("RELAÇÃO DE APÓLICES")] + RelacaoApolices + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoFiltroBusca.cs b/Codemerx/Gestor.Model/Model.Common/TipoFiltroBusca.cs new file mode 100644 index 0000000..1fdb02d --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoFiltroBusca.cs @@ -0,0 +1,15 @@ +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoFiltroBusca + { + [Description("APROXIMADO")] + Aproximado, + [Description("IGUAL")] + Igual + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoFiltroCliente.cs b/Codemerx/Gestor.Model/Model.Common/TipoFiltroCliente.cs new file mode 100644 index 0000000..a0eb153 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoFiltroCliente.cs @@ -0,0 +1,17 @@ +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoFiltroCliente + { + [Description("NOME OU SOBRENOME")] + NomeSobrenome, + [Description("NOME APENAS")] + Nome, + [Description("NOME E DOCS")] + NomeDocumentos + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoFiltroFinanceiro.cs b/Codemerx/Gestor.Model/Model.Common/TipoFiltroFinanceiro.cs new file mode 100644 index 0000000..8ca6af3 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoFiltroFinanceiro.cs @@ -0,0 +1,21 @@ +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoFiltroFinanceiro + { + [Description("FORNECEDOR")] + Fornecedor, + [Description("PLANO DE CONTAS")] + Plano, + [Description("CENTRO DE CUSTO")] + Centro, + [Description("CONTA")] + Conta, + [Description("SINAL")] + Sinal + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoFiltroRelatorio.cs b/Codemerx/Gestor.Model/Model.Common/TipoFiltroRelatorio.cs new file mode 100644 index 0000000..3e40c0a --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoFiltroRelatorio.cs @@ -0,0 +1,27 @@ +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoFiltroRelatorio + { + [Description("SEGURADORA")] + Seguradora, + [Description("RAMO")] + Ramo, + [Description("VENDEDOR")] + Vendedor, + [Description("ESTIPULANTE")] + Estipulante, + [Description("PRODUTO")] + Produto, + [Description("STATUS")] + Status, + [Description("TIPO VENDEDOR")] + TipoVendedor, + [Description("NEGÓCIO CORRETORA")] + Negocio + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoIncidencia.cs b/Codemerx/Gestor.Model/Model.Common/TipoIncidencia.cs new file mode 100644 index 0000000..2722b65 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoIncidencia.cs @@ -0,0 +1,18 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoIncidencia + { + [Description("SOBRE A COMISSÃO")] + [OldValue("1")] + SobreComissao = 1, + [Description("SOBRE O PRÊMIO LÍQUIDO")] + [OldValue("2")] + SobrePremioLiquido = 2 + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoIncidenciaDesconto.cs b/Codemerx/Gestor.Model/Model.Common/TipoIncidenciaDesconto.cs new file mode 100644 index 0000000..d2c1d18 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoIncidenciaDesconto.cs @@ -0,0 +1,15 @@ +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoIncidenciaDesconto + { + [Description("AMBOS")] + Ambos, + [Description("SOMENTE POSITIVOS")] + Positivos + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoManutencao.cs b/Codemerx/Gestor.Model/Model.Common/TipoManutencao.cs new file mode 100644 index 0000000..61fb240 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoManutencao.cs @@ -0,0 +1,19 @@ +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoManutencao + { + [Description("RENOVAÇÃO")] + Renovacao, + [Description("ENDOSSO")] + Endosso, + [Description("REATIVAR")] + Reativar, + [Description("CANCELAR")] + Cancelar + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoMoradia.cs b/Codemerx/Gestor.Model/Model.Common/TipoMoradia.cs new file mode 100644 index 0000000..2375491 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoMoradia.cs @@ -0,0 +1,15 @@ +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoMoradia + { + [Description("APARTAMENTO")] + Apartamento = 1, + [Description("CASA")] + Casa = 2 + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoPagamento.cs b/Codemerx/Gestor.Model/Model.Common/TipoPagamento.cs new file mode 100644 index 0000000..110188c --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoPagamento.cs @@ -0,0 +1,63 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoPagamento + { + [Description("NENHUM")] + [OldValue("0")] + Nenhum = 0, + [Description("CAIXA")] + [OldValue("2")] + Caixa = 2, + [Description("CARTÃO DE CRÉDITO")] + [OldValue("3")] + Cartao = 3, + [Description("CHEQUE")] + [OldValue("4")] + Cheque = 4, + [Description("CRÉDITO EM CONTA")] + [OldValue("5")] + Credito = 5, + [Description("DÉBITO AUTOMÁTICO")] + [OldValue("6")] + DebitoAuto = 6, + [Description("DÉBITO EM CONTA")] + [OldValue("7")] + DebitoConta = 7, + [Description("DEPÓSITO")] + [OldValue("8")] + Deposito = 8, + [Description("DINHEIRO")] + [OldValue("9")] + Dinheiro = 9, + [Description("SAQUE")] + [OldValue("10")] + Saque = 10, + [Description("TRANSFERÊNCIA")] + [OldValue("11")] + Transferencia = 11, + [Description("OUTROS")] + [OldValue("12")] + Outros = 12, + [Description("REEMBOLSO")] + [OldValue("13")] + Reembolso = 13, + [Description("CARNÊ")] + [OldValue("14")] + Carne = 14, + [Description("BOLETO BANCÁRIO")] + [OldValue("15")] + Boleto = 15, + [Description("PIX")] + [OldValue("18")] + Pix = 18, + [Description("VOUCHER")] + [OldValue("19")] + Voucher = 19 + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoPavimentacao.cs b/Codemerx/Gestor.Model/Model.Common/TipoPavimentacao.cs new file mode 100644 index 0000000..1b98f92 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoPavimentacao.cs @@ -0,0 +1,21 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoPavimentacao + { + [Description("TÉRREO")] + [OldValue("1")] + Terreo, + [Description("PRIMEIRO")] + [OldValue("2")] + Primeiro, + [Description("SEGUNDO EM DIANTE")] + [OldValue("3")] + SegundoEmDiante + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoPerda.cs b/Codemerx/Gestor.Model/Model.Common/TipoPerda.cs new file mode 100644 index 0000000..722be67 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoPerda.cs @@ -0,0 +1,27 @@ +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoPerda + { + [Description("CONSTATAÇÃO")] + Constatacao = 1, + [Description("PARCIAL")] + Parcial = 2, + [Description("TOTAL")] + Total = 3, + [Description("ROUBO/FURTO")] + RouboFurto = 4, + [Description("MORTE")] + Morte = 5, + [Description("INVALIDEZ")] + Invalidez = 6, + [Description("PERDA DE RENDA")] + PerdaRenda = 7, + [Description("OUTROS")] + Outros = 8 + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoPesquisa.cs b/Codemerx/Gestor.Model/Model.Common/TipoPesquisa.cs new file mode 100644 index 0000000..fdf12e6 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoPesquisa.cs @@ -0,0 +1,49 @@ +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoPesquisa + { + [Description("CHASSI")] + Chassi, + [Description("CÓDIGO DOCUMENTO")] + CodDocumento, + [Description("CÓDIGO SINISTRO")] + CodSinistro, + [Description("E-MAIL")] + Email, + [Description("ESTIPULANTE")] + Estipulante, + [Description("IMOBILIÁRIA")] + Imobiliaria, + [Description("ITEM")] + Item, + [Description("LOCATÁRIO/TOMADOR")] + Locatario, + [Description("Nº DA APÓLICE")] + Apolice, + [Description("Nº DO SINISTRO")] + Sinistro, + [Description("Nº DA PROPOSTA")] + Proposta, + [Description("NÚMERO ENDOSSO")] + NumeroEndosso, + [Description("OBSERVAÇÕES DO CLIENTE")] + ObsCliente, + [Description("PASTA")] + Pasta, + [Description("PLACA")] + Placa, + [Description("PROPOSTA ENDOSSO")] + PedidoEndosso, + [Description("TELEFONE")] + Telefone, + [Description("Nº DA FATURA")] + Fatura, + [Description("OBSERVAÇÕES DO ITEM")] + ObsItem + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoProtocoloEtiqueta.cs b/Codemerx/Gestor.Model/Model.Common/TipoProtocoloEtiqueta.cs new file mode 100644 index 0000000..14b3692 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoProtocoloEtiqueta.cs @@ -0,0 +1,15 @@ +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoProtocoloEtiqueta + { + [Description("PROTOCOLO")] + Protocolo, + [Description("ETIQUETA")] + Etiqueta + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoRecebimento.cs b/Codemerx/Gestor.Model/Model.Common/TipoRecebimento.cs new file mode 100644 index 0000000..249d6d6 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoRecebimento.cs @@ -0,0 +1,18 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoRecebimento + { + [Description("PARCELA")] + [OldValue("1")] + Parcela = 1, + [Description("FATURA")] + [OldValue("2")] + Fatura = 2 + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoRecibo.cs b/Codemerx/Gestor.Model/Model.Common/TipoRecibo.cs new file mode 100644 index 0000000..0f451f9 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoRecibo.cs @@ -0,0 +1,18 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoRecibo + { + [Description("PAGAMENTO")] + [OldValue("0")] + Pagamento, + [Description("RECEBIMENTO")] + [OldValue("1")] + Recebimento + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoRepasse.cs b/Codemerx/Gestor.Model/Model.Common/TipoRepasse.cs new file mode 100644 index 0000000..e2d528a --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoRepasse.cs @@ -0,0 +1,24 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoRepasse + { + [Description("VALOR FIXO")] + [OldValue("1")] + [Tipo("0")] + ValorFixo = 1, + [Description("PERCENTUAL")] + [OldValue("2")] + [Tipo("0")] + Percentual = 2, + [Description("CO-CORRETAGEM")] + [OldValue("3")] + [Tipo("1")] + CoCorretagem = 3 + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoResidencia.cs b/Codemerx/Gestor.Model/Model.Common/TipoResidencia.cs new file mode 100644 index 0000000..06ece42 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoResidencia.cs @@ -0,0 +1,24 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoResidencia + { + [Description("CASA")] + [OldValue("1")] + Casa, + [Description("APARTAMENTO")] + [OldValue("2")] + Apartamento, + [Description("CONDOMÍNIO")] + [OldValue("3")] + Condominio, + [Description("OUTROS")] + [OldValue("4")] + Outros + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoRestricao.cs b/Codemerx/Gestor.Model/Model.Common/TipoRestricao.cs new file mode 100644 index 0000000..6822f3b --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoRestricao.cs @@ -0,0 +1,528 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoRestricao + { + [Description("SEGUROS VENCENDO")] + SegurosVencendo, + [Description("SEGUROS VENCIDOS")] + SegurosVencidos, + [Description("PRODUÇÃO")] + Producao, + [Description("APÓLICES PENDENTES")] + ApolicesPendentes, + [Description("NOVOS NEGÓCIOS")] + NovosNegocios, + [Description("RENOVADOS")] + Renovados, + [Description("COMISSÃO GERADA")] + ComissaoGerada, + [Description("CANCELADOS")] + Cancelados, + [Description("PERDIDOS")] + Perdidos, + [Description("PARCELAS PAGAS")] + ParcelasPagas, + [Description("COMISSÃO RECEBIDA")] + ComissaoRecebida, + [Description("PARCELAS PENDENTES")] + ParcelasPendentes, + [Description("PARCELAS A VENCER")] + ParcelasVencer, + [Category("Seguros")] + [Description("RESTRINGIR ACESSO AO EXTRATO DO CLIENTE")] + [Help("IMPEDE USUÁRIO DE ACESSAR EXTRATO DE CLIENTE.")] + ExtratoCliente, + [Category("Seguros")] + [Description("OCULTAR COMISSÃO")] + [Help("OCULTA TUDO RELACIONADO A COMISSÃO.")] + Comissao, + [Category("Seguros")] + [Description("RESTRINGIR ACESSO À BAIXA DE COMISSÃO MANUAL")] + [Help("IMPEDE USUÁRIO DE REALIZAR BAIXA DE COMISSÃO MANUALMENTE.")] + BaixaManual, + [Category("Seguros")] + [Description("RESTRINGIR ACESSO AO IMPORTADOR PDF")] + [Help("IMPEDE USUÁRIO DE ACESSAR A PLATAFORMA DE IMPORTAÇÃO DE PDF DO GESTOR AGGER.")] + Importacao, + [Category("Seguros")] + [Description("RESTRINGIR ACESSO À RENOVAR")] + [Help("IMPEDE USUÁRIO DE RENOVAR UM DOCUMENTO.")] + Renovar, + [Category("Seguros")] + [Description("RESTRINGIR ACESSO À RECUSAR")] + [Help("IMPEDE USUÁRIO DE RECUSAR UM DOCUMENTO.")] + Recusar, + Tarefas, + [Category("Seguros")] + [Description("RESTRINGIR ACESSO AO ENVIO DE E-MAIL")] + [Help("IMPEDE USUÁRIO DE ENVIAR E-MAIL.")] + EnvioEmail, + [Category("Seguros")] + [Description("RESTRINGIR ACESSO À TROCAR CLIENTE")] + [Help("IMPEDE USUÁRIO DE TROCAR UM CLIENTE POR OUTRO MANTENDO AS MESMAS INFORMAÇÕES DO DOCUMENTO.")] + TrocarCliente, + [Category("Seguros")] + [Description("RESTRINGIR ACESSO À MANUTENÇÃO DOS ITENS")] + [Help("IMPEDE USUÁRIO DE REALIZAR MANUTENÇÃO DE ITENS.")] + ManutencaoItens, + [Category("Relatorios")] + [Description("RESTRINGIR ACESSO AO RELATÓRIO DE PRODUÇÃO")] + [Help("IMPEDE O USUÁRIO DE ACESSAR O RELATÓRIO DE PRODUÇÃO.")] + [OldValue("0")] + [Tipo("RELATORIOS")] + RelatorioProducao, + [Category("Relatorios")] + [Description("RESTRINGIR ACESSO AO RELATÓRIO DE RENOVAÇÕES")] + [Help("IMPEDE O USUÁRIO DE ACESSAR O RELATÓRIO DE RENOVAÇÕES.")] + [OldValue("1")] + [Tipo("RELATORIOS")] + RelatorioRenovacao, + [Category("Relatorios")] + [Description("RESTRINGIR ACESSO AO RELATÓRIO DE SINISTRO PENDENTE")] + [Help("IMPEDE O USUÁRIO DE ACESSAR O RELATÓRIO DE SINISTRO PENDENTE.")] + [OldValue("2")] + [Tipo("RELATORIOS")] + RelatorioSinistroPendente, + [Category("Relatorios")] + [Description("RESTRINGIR ACESSO AO RELATÓRIO DE SINISTRO")] + [Help("IMPEDE O USUÁRIO DE ACESSAR O RELATÓRIO DE SINISTRO.")] + [OldValue("3")] + [Tipo("RELATORIOS")] + RelatorioSinistro, + [Category("Relatorios")] + [Description("RESTRINGIR ACESSO AO RELATÓRIO DE RECEBIMENTO DE COMISSÃO")] + [Help("IMPEDE O USUÁRIO DE ACESSAR O RELATÓRIO DE RECEBIMENTO DE COMISSÃO.")] + [OldValue("4")] + [Tipo("RELATORIOS")] + RelatorioRecebimentoComissao, + [Category("Relatorios")] + [Description("RESTRINGIR ACESSO AO RELATÓRIO DE PAGAMENTO DE COMISSÃO")] + [OldValue("5")] + [Tipo("RELATORIOS")] + RelatorioPagamentoComissao, + [Category("Relatorios")] + [Description("RESTRINGIR ACESSO AO RELATÓRIO DE COMISSÃO A RECEBER")] + [Help("IMPEDE O USUÁRIO DE ACESSAR O RELATÓRIO DE COMISSÃO A RECEBER.")] + [OldValue("6")] + [Tipo("RELATORIOS")] + RelatorioParcelaPendente, + [Category("Relatorios")] + [Description("RESTRINGIR ACESSO AO RELATÓRIO DE CLIENTE")] + [Help("IMPEDE O USUÁRIO DE ACESSAR O RELATÓRIO DE CLIENTE.")] + [OldValue("7")] + [Tipo("RELATORIOS")] + RelatorioCliente, + [Category("Relatorios")] + [Description("RESTRINGIR ACESSO AO RELATÓRIO DE TAREFAS")] + [Help("IMPEDE O USUÁRIO DE ACESSAR O RELATÓRIO DE TAREFAS.")] + [OldValue("8")] + [Tipo("RELATORIOS")] + RelatorioTarefa, + [Category("Seguros")] + [Description("RESTRINGIR ACESSO AO WHATSAPP DO CLIENTE")] + [Help("IMPEDE USUÁRIO DE ACESSAR O WHATSAOO DO CLIENTE PARA ENVIO DE DOCUMENTAÇÃO.")] + Whatsapp, + [Category("Seguros")] + [Description("RESTRINGIR ACESSO A OPÇÃO DE ENDOSSAR")] + [Help("IMPEDE USUÁRIO DE TER ACESSO PARA REALIZAR UM ENDOSSO.")] + Endossar, + [Category("Relatorios")] + [Description("RESTRINGIR ACESSO AO RELATÓRIO DE APÓLICES PENDENTES")] + [Help("IMPEDE O USUÁRIO DE ACESSAR O RELATÓRIO DE APÓLICES PENDENTES.")] + [Tipo("RELATORIOS")] + RelatorioApolicePendente, + [Category("Financeiro")] + [Description("RESTRINGIR ACESSO AO FINANCEIRO")] + [Help("IMPEDE O USUÁRIO DE ACESSAR O FINANCEIRO.")] + Financeiro, + [Category("Aggilizador")] + [Description("RESTRINGIR ACESSO À CÁLCULO")] + Calculo, + [Category("Aggilizador")] + [Description("RESTRINGIR ACESSO ÀS PROPOSTAS/APÓLICES")] + PropApol, + [Category("Aggilizador")] + [Description("RESTRINGIR ACESSO AO EXTRATO DE COMISSÃO")] + ExtratoComissao, + [Category("Aggilizador")] + [Description("RESTRINGIR ACESSO ÀS PARCELAS PENDENTES")] + ParcelaPendente, + [Category("Aggilizador")] + [Description("RESTRINGIR ACESSO ÀS RENOVAÇÕES")] + Renovacao, + [Category("Relatorios")] + [Description("RESTRINGIR ACESSO AO RELATÓRIO DE FECHAMENTO")] + [Help("IMPEDE O USUÁRIO DE ACESSAR O RELATÓRIO DE FECHAMENTO.")] + [Tipo("RELATORIOS")] + RelatorioFechamento, + [Category("Seguros")] + [Description("RESTRINGIR ACESSO À CRÍTICA PDF")] + [Help("IMPEDE USUÁRIO DE ACESSAR A TELA DE CRÍTICA PDF.")] + CriticaApolice, + [Category("Seguros")] + [Description("RESTRINGIR ACESSO À COMISSÃO AUTOMÁTICA")] + [Help("IMPEDE USUÁRIO DE ACESSAR A TELA DE COMISSÃO AUTOMÁTICA.")] + BaixaAutomatica, + [Category("B.I.")] + [Description("RESTRINGIR ACESSO À PROSPECÇÃO")] + [Help("IMPEDE O USUÁRIO DE ACESSAR A TELA DE PROSPECÇÃO")] + Prospeccao, + [Description("RESTRINGIR ACESSO À TRILHA")] + Trilha, + [Category("Relatorios")] + [Description("RESTRINGIR ACESSO AO RELATÓRIO DE AUDITORIA")] + [Help("IMPEDE O USUÁRIO DE ACESSAR O RELATÓRIO DE AUDITORIA.")] + [Tipo("RELATORIOS")] + RelatorioAuditoria, + [Category("B.I.")] + [Description("RESTRINGIR ACESSO AO PAINEL B.I.")] + [Help("IMPEDE O USUÁRIO DE ACESSAR A TELA DO PAINEL B.I.")] + Bi, + [Category("Ferramentas")] + [Description("RESTRINGIR ACESSO ÀS ETIQUETAS")] + [Help("IMPEDE O USUÁRIO DE ACESSAR ÀS ETIQUETAS.")] + Etiquetas, + [Category("Relatorios")] + [Description("RESTRINGIR ACESSO AO RELATÓRIO DE ANIVERSARIANTES")] + [Help("IMPEDE O USUÁRIO DE ACESSAR O RELATÓRIO DE ANIVERSARIANTES")] + [OldValue("8")] + [Tipo("RELATORIOS")] + RelatorioAniversariante, + [Category("Relatorios")] + [Description("RESTRINGIR ACESSO AO RELATÓRIO DE EXTRATOS BAIXADOS")] + [Help("IMPEDE O USUÁRIO DE ACESSAR O RELATÓRIO DE EXTRATOS BAIXADOS.")] + [Tipo("RELATORIOS")] + RelatorioExtratosBaixados, + [Category("Relatorios")] + [Description("RESTRINGIR ACESSO AO RELATÓRIO DE FATURAS PENDENTES")] + [Help("IMPEDE O USUÁRIO DE ACESSAR O RELATÓRIO DE FATURAS PENDENTES.")] + [Tipo("RELATORIOS")] + RelatorioFaturaPendente, + [Category("Relatorios")] + [Description("RESTRINGIR ACESSO AO RELATÓRIO DE METAS DE SEGURADORAS")] + [Help("IMPEDE O USUÁRIO DE ACESSAR O RELATÓRIO DE METAS DE SEGURADORAS.")] + [Tipo("RELATORIOS")] + RelatorioMetaSeguradora, + [Category("Relatorios")] + [Description("RESTRINGIR ACESSO AO RELATÓRIO DE METAS DE VENDEDORES")] + [Help("IMPEDE O USUÁRIO DE ACESSAR O RELATÓRIO DE METAS DE VENDEDORES.")] + [Tipo("RELATORIOS")] + RelatorioMetaVendedor, + [Category("Ajuda")] + [Description("RESTRINGIR ACESSO AOS ATENDIMENTOS")] + [Help("IMPEDE O USUÁRIO DE ACESSAR OS ATENDIMENTOS DO GESTOR")] + Atendimentos, + [Category("Ajuda")] + [Description("RESTRINGIR ACESSO AOS BOLETOS E NOTAS")] + [Help("IMPEDE O USUÁRIO DE ACESSAR OS BOLETOS E NOTAS DO GESTOR")] + BoletosNotas, + [Category("Ajuda")] + [Description("RESTRINGIR ACESSO AOS CONTRATOS")] + [Help("IMPEDE O USUÁRIO DE ACESSAR OS CONTRATOS DO GESTOR")] + Contratos, + [Category("Ajuda")] + [Description("RESTRINGIR ACESSO À INSTALAÇÕES")] + [Help("IMPEDE O USUÁRIO DE ACESSAR INSTALAÇÕES DO GESTOR")] + Instalacoes, + [Category("Ajuda")] + [Description("RESTRINGIR ACESSO AO ACESSO REMOTO")] + [Help("IMPEDE O USUÁRIO DE ACESSAR O ACESSO REMOTO DO GESTOR")] + AcessoRemoto, + [Category("Seguros")] + [Description("RESTRINGIR ACESSO À AGGER EPIC")] + [Help("IMPEDE USUÁRIO DE ACESSAR A PLATAFORMA AGGER EPIC.")] + Epic, + [Category("Seguros")] + [Description("RESTRINGIR ACESSO AO AGGER SIGGNER")] + [Help("IMPEDE O USUÁRIO DE ACESSAR A PLATAFORMA AGGER SIGGNER E TER ACESSO A ASSINATURA ELETRÔNICA QUE SE ENCONTRA NOS ARQUIVOS DIGITAIS.")] + AssinaturaEletronica, + [Category("Ajuda")] + [Description("OCULTAR VIDEOS DE AJUDA")] + [Help("IMPEDE O USUÁRIO DE ACESSAR OS VÍDEOS DE AJUDA DO GESTOR")] + Videos, + [Category("Relatorios")] + [Description("RESTRINGIR ACESSO AO RELATÓRIO DE VENCIMENTO DE PARCELAS")] + [Help("IMPEDE O USUÁRIO DE ACESSAR O RELATÓRIO DE VENCIMENTO DE PARCELAS.")] + [Tipo("RELATORIOS")] + RelatorioParcelasVencendo, + [Category("Relatorios")] + [Description("RESTRINGIR ACESSO AO RELATÓRIO LICENCIAMENTO")] + [Help("IMPEDE O USUÁRIO DE ACESSAR O RELATÓRIO DE LICENCIAMENTO.")] + [Tipo("RELATORIOS")] + RelatorioLicenciamento, + [Category("Ferramentas")] + [Description("RESTRINGIR ACESSO AS CONFIGURAÇÕES DO SISTEMA")] + [Help("IMPEDE O USUÁRIO DE ACESSAR AS CONFIGURAÇÕES DO SISTEMA.")] + Configuracoes, + [Category("TotalizacoesRelatorios")] + [Description("RESTRINGIR VISUALIZAÇÃO DA TOTALIZAÇÃO DE PRÊMIO TOTAL")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR A TOTALIZAÇÃO DE PRÊMIO TOTAL DO RELATÓRIO.")] + [OldValue("9")] + [Tipo("RELATORIOS")] + RelatorioTotalizacaoPremioTotal, + [Category("TotalizacoesRelatorios")] + [Description("RESTRINGIR VISUALIZAÇÃO DA TOTALIZAÇÃO DE TOTAIS DE CLIENTES")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR A TOTALIZAÇÃO DE TOTAIS DE CLIENTES DO RELATÓRIO.")] + [OldValue("10")] + [Tipo("RELATORIOS")] + RelatorioTotalizacaoTotalCliente, + [Category("TotalizacoesRelatorios")] + [Description("RESTRINGIR VISUALIZAÇÃO DA TOTALIZAÇÃO DE PRÊMIO LÍQUIDO")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR A TOTALIZAÇÃO DE PRÊMIO LÍQUIDO DO RELATÓRIO.")] + [OldValue("11")] + [Tipo("RELATORIOS")] + RelatorioTotalizacaoPremioLiquido, + [Category("TotalizacoesRelatorios")] + [Description("RESTRINGIR VISUALIZAÇÃO DA TOTALIZAÇÃO DE MÉDIAS DE COMISSÕES")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR A TOTALIZAÇÃO DE MÉDIAS DE COMISSÕES DO RELATÓRIO.")] + [OldValue("12")] + [Tipo("RELATORIOS")] + RelatorioTotalizacaoMediaComissao, + [Category("TotalizacoesRelatorios")] + [Description("RESTRINGIR VISUALIZAÇÃO DA TOTALIZAÇÃO DE QUANTIDADE DE NOVOS NEGÓCIOS")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR A TOTALIZAÇÃO DE QUANTIDADE DE NOVOS NEGÓCIOS DO RELATÓRIO.")] + [OldValue("13")] + [Tipo("RELATORIOS")] + RelatorioTotalizacaoQuantidadeNovoNegocio, + [Category("TotalizacoesRelatorios")] + [Description("RESTRINGIR VISUALIZAÇÃO DA TOTALIZAÇÃO DE QUANTIDADE DE RENOVAÇÕES")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR A TOTALIZAÇÃO DE QUANTIDADE DE RENOVAÇÕES DO RELATÓRIO.")] + [OldValue("14")] + [Tipo("RELATORIOS")] + RelatorioTotalizacaoQuantidadeRenovacoes, + [Category("TotalizacoesRelatorios")] + [Description("RESTRINGIR VISUALIZAÇÃO DA TOTALIZAÇÃO DE QUANTIDADE DE CANCELAMENTOS")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR A TOTALIZAÇÃO DE QUANTIDADE DE CANCELAMENTOS DO RELATÓRIO.")] + [OldValue("15")] + [Tipo("RELATORIOS")] + RelatorioTotalizacaoQuantidadeCancelamentos, + [Category("TotalizacoesRelatorios")] + [Description("RESTRINGIR VISUALIZAÇÃO DA TOTALIZAÇÃO DE QUANTIDADE DE APÓLICES")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR A TOTALIZAÇÃO DE QUANTIDADE DE AÓLICES DO RELATÓRIO.")] + [OldValue("16")] + [Tipo("RELATORIOS")] + RelatorioTotalizacaoQuantidadeApolices, + [Category("TotalizacoesRelatorios")] + [Description("RESTRINGIR VISUALIZAÇÃO DA TOTALIZAÇÃO DE QUANTIDADE DE ENDOSSOS")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR A TOTALIZAÇÃO DE QUANTIDADE DE ENDOSSOS DO RELATÓRIO.")] + [OldValue("17")] + [Tipo("RELATORIOS")] + RelatorioTotalizacaoQuantidadeEndossos, + [Category("TotalizacoesRelatorios")] + [Description("RESTRINGIR VISUALIZAÇÃO DA TOTALIZAÇÃO DE QUANTIDADE DE FATURAS")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR A TOTALIZAÇÃO DE QUANTIDADE DE FATURAS DO RELATÓRIO.")] + [OldValue("18")] + [Tipo("RELATORIOS")] + RelatorioTotalizacaoQuantidadeFaturas, + [Category("TotalizacoesRelatorios")] + [Description("RESTRINGIR VISUALIZAÇÃO DA TOTALIZAÇÃO DE TOTAL GERAL")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR A TOTALIZAÇÃO DE TOTAL GERAL DO RELATÓRIO.")] + [OldValue("19")] + [Tipo("RELATORIOS")] + RelatorioTotalizacaoTotalGeral, + [Category("TotalizacoesRelatorios")] + [Description("RESTRINGIR VISUALIZAÇÃO DA TOTALIZAÇÃO DE TOTAL DE LÍQUIDO")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR A TOTALIZAÇÃO DE TOTAL DE LÍQUIDO DO RELATÓRIO.")] + [OldValue("20")] + [Tipo("RELATORIOS")] + RelatorioTotalizacaoTotalLiquido, + [Category("TotalizacoesRelatorios")] + [Description("RESTRINGIR VISUALIZAÇÃO DA TOTALIZAÇÃO DE QUANTIDADE DE PROSPECÇÕES")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR A TOTALIZAÇÃO DE QUANTIDADE DE PROSPECÇÕES DO RELATÓRIO.")] + [OldValue("21")] + [Tipo("RELATORIOS")] + RelatorioTotalizacaoQuantidadeProspeccoes, + [Category("TotalizacoesRelatorios")] + [Description("RESTRINGIR VISUALIZAÇÃO DA TOTALIZAÇÃO DE TOTAL DE COMISSÃO GERADA")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR A TOTALIZAÇÃO DE TOTAL DE COMISSÃO GERADA DO RELATÓRIO.")] + [OldValue("22")] + [Tipo("RELATORIOS")] + RelatorioTotalizacaoTotalComissaoGerada, + [Category("TotalizacoesRelatorios")] + [Description("RESTRINGIR VISUALIZAÇÃO DA TOTALIZAÇÃO DE COMISSÃO RECEBIDA BRUTA")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR A TOTALIZAÇÃO DE COMISSÃO RECEBIDA BRUTA DO RELATÓRIO.")] + [OldValue("23")] + [Tipo("RELATORIOS")] + RelatorioTotalizacaoComissaoRecebidaBruta, + [Category("TotalizacoesRelatorios")] + [Description("RESTRINGIR VISUALIZAÇÃO DA TOTALIZAÇÃO DE COMISSÃO PREVISTA")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR A TOTALIZAÇÃO DE COMISSÃO PREVISTA DO RELATÓRIO.")] + [OldValue("24")] + [Tipo("RELATORIOS")] + RelatorioTotalizacaoComissaoPrevisata, + [Category("TotalizacoesRelatorios")] + [Description("RESTRINGIR VISUALIZAÇÃO DA TOTALIZAÇÃO DE REPASSE")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR A TOTALIZAÇÃO DE REPASSE DO RELATÓRIO.")] + [OldValue("25")] + [Tipo("RELATORIOS")] + RelatorioTotalizacaoRepasse, + [Category("TotalizacoesRelatorios")] + [Description("RESTRINGIR VISUALIZAÇÃO DA TOTALIZAÇÃO DE TOTAL PREVISTO")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR A TOTALIZAÇÃO DE TOTAL PREVISTO DO RELATÓRIO.")] + [OldValue("26")] + [Tipo("RELATORIOS")] + RelatorioTotalizacaoTotalPrevisto, + [Category("TotalizacoesRelatorios")] + [Description("RESTRINGIR VISUALIZAÇÃO DA TOTALIZAÇÃO DE TOTAL DE TERCEIROS")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR A TOTALIZAÇÃO DE TOTAL DE TERCEIROS DO RELATÓRIO.")] + [OldValue("27")] + [Tipo("RELATORIOS")] + RelatorioTotalizacaoTotalTerceiros, + [Category("TotalizacoesRelatorios")] + [Description("RESTRINGIR VISUALIZAÇÃO DA TOTALIZAÇÃO DE QUANTIDADE LIQUIDADO")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR A TOTALIZAÇÃO DE QUANTIDADE DE LIQUIDADOS DO RELATÓRIO.")] + [OldValue("28")] + [Tipo("RELATORIOS")] + RelatorioTotalizacaoQuantidadeLiquidado, + [Category("TotalizacoesRelatorios")] + [Description("RESTRINGIR VISUALIZAÇÃO DA TOTALIZAÇÃO DE QUANTIDADE PENDENTE")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR A TOTALIZAÇÃO DE QUANTIDADE DE PENDENTES DO RELATÓRIO.")] + [OldValue("29")] + [Tipo("RELATORIOS")] + RelatorioTotalizacaoQuantidadePendente, + [Category("TotalizacoesRelatorios")] + [Description("RESTRINGIR VISUALIZAÇÃO DA TOTALIZAÇÃO DE VALOR LIQUIDADO")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR A TOTALIZAÇÃO DE VALOR LIQUIDADO DO RELATÓRIO.")] + [OldValue("30")] + [Tipo("RELATORIOS")] + RelatorioTotalizacaoValorLiquidado, + [Category("TotalizacoesRelatorios")] + [Description("RESTRINGIR VISUALIZAÇÃO DA TOTALIZAÇÃO DE COMISSÃO PENDENTE")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR A TOTALIZAÇÃO DE COMISSÃO PENDENTE DO RELATÓRIO.")] + [OldValue("31")] + [Tipo("RELATORIOS")] + RelatorioTotalizacaoComissaoPendente, + [Category("TotalizacoesRelatorios")] + [Description("RESTRINGIR VISUALIZAÇÃO DA TOTALIZAÇÃO DE META ATINGIR")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR A TOTALIZAÇÃO DE META A ATINGIR DO RELATÓRIO.")] + [OldValue("32")] + [Tipo("RELATORIOS")] + RelatorioTotalizacaoMetaAtingir, + [Category("TotalizacoesRelatorios")] + [Description("RESTRINGIR VISUALIZAÇÃO DA TOTALIZAÇÃO DE META CUMPRIDA")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR A TOTALIZAÇÃO DE META CUMPRIDA DO RELATÓRIO.")] + [OldValue("33")] + [Tipo("RELATORIOS")] + RelatorioTotalizacaoMetaCumprida, + [Category("Relatorios")] + [Description("RESTRINGIR ACESSO AO RELATÓRIO DE NOTAS FISCAIS")] + [Help("IMPEDE O USUÁRIO DE ACESSAR O RELATÓRIO DE NOTAS FISCAIS.")] + [Tipo("RELATORIOS")] + RelatorioNotaFiscal, + [Category("Relatorios")] + [Description("RESTRINGIR ACESSO AO RELATÓRIO DE PREVISÃO DE PAGAMENTO DE COMISSÃO")] + [Help("IMPEDE O USUÁRIO DE ACESSAR O RELATÓRIO DE PREVISÃO DE PAGAMENTO DE COMISSÃO.")] + [Tipo("RELATORIOS")] + RelatorioPrevisaoPagamentoComissao, + [Category("TotalizacoesRelatorios")] + [Description("RESTRINGIR VISUALIZAÇÃO DA TOTALIZAÇÃO DE COMISSÃO RECEBIDA LÍQUIDA")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR A TOTALIZAÇÃO DE COMISSÃO RECEBIDA LÍQUIDA DO RELATÓRIO.")] + [Tipo("RELATORIOS")] + RelatorioTotalizacaoComissaoRecebidaLiquida, + [Category("TotalizacoesRelatorios")] + [Description("RESTRINGIR VISUALIZAÇÃO DA TOTALIZAÇÃO DE IMPOSTOS")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR A TOTALIZAÇÃO DE IMPOSTOS DO RELATÓRIO.")] + [Tipo("RELATORIOS")] + RelatorioTotalizacaoImpostos, + [Category("Ferramentas")] + [Description("RESTRINGIR VISUALIZAÇÃO DO HORÁRIO DE ACESSO DO USUÁRIO")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR OS HORÁRIOS DE ACESSO AO GESTOR.")] + HorarioAcesso, + [Category("Seguros")] + [Description("OCULTAR COMISSÃO (MENOS PORCENTAGEM)")] + [Help("OCULTA OS VALORES RELACIONADOS A COMISSÃO MAS A PORCENTAGEM DE COMISSÃO FICA VISÍVEL.")] + ComissaoPorcentagem, + [Category("Relatorios")] + [Description("RESTRINGIR ACESSO AO RELATÓRIO DE LOGS DE ENVIO DE E-MAIL")] + [Help("IMPEDE O USUÁRIO DE ACESSAR O RELATÓRIO DE LOGS DE ENVIO DE E-MAIL.")] + [Tipo("RELATORIOS")] + RelatorioLogsEnvio, + [Category("Seguros")] + [Description("RESTRINGIR INFORMAÇÕES VALORES")] + [Help("RESTRINGIR AS INFORMAÇÕES DE VALORES NA CONSULTA")] + MaisValores, + [Category("Relatorios")] + [Description("RESTRINGIR ACESSO AO RELATÓRIO DE LOGS DE UTILIZAÇÃO DO SISTEMA")] + [Help("IMPEDE O USUÁRIO DE ACESSAR O RELATÓRIO DE LOGS DE UTILIZAÇÃO DO SISTEMA.")] + [Tipo("RELATORIOS")] + RelatorioLogsAcao, + [Category("Relatorios")] + [Description("RESTRINGIR ACESSO AO PLANILHA COMPLETA")] + [Help("IMPEDE O USUÁRIO DE ACESSAR O PLANILHA COMPLETA NOS RELATÓRIOS DE PRODUÇÃO E FECHAMENTO.")] + [Tipo("RELATORIOS")] + RelatorioPlanilhaCompleta, + [Category("TotalizacoesRelatorios")] + [Description("RESTRINGIR VISUALIZAÇÃO DA TOTALIZAÇÃO DE VALOR")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR A TOTALIZAÇÃO DE VALOR DO RELATÓRIO.")] + [Tipo("RELATORIOS")] + RelatorioTotalizacaoValor, + [Category("TotalizacoesRelatorios")] + [Description("RESTRINGIR VISUALIZAÇÃO DA TOTALIZAÇÃO DE VALOR ORÇADO")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR A TOTALIZAÇÃO DE VALOR ORÇADO DO RELATÓRIO.")] + [Tipo("RELATORIOS")] + RelatorioTotalizacaoValorOrcado, + [Category("TotalizacoesRelatorios")] + [Description("RESTRINGIR VISUALIZAÇÃO DA TOTALIZAÇÃO DE VALOR DAS PARCELAS")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR A TOTALIZAÇÃO DE VALOR DAS PARCELAS RELATÓRIO.")] + [Tipo("RELATORIOS")] + RelatorioTotalizacaoValorParcelas, + [Category("TotalizacoesRelatorios")] + [Description("RESTRINGIR VISUALIZAÇÃO DA TOTALIZAÇÃO DE VALOR LIBERADO")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR A TOTALIZAÇÃO DE VALOR LIBERADO DO RELATÓRIO.")] + [Tipo("RELATORIOS")] + RelatorioTotalizacaoValorLiberado, + [Category("TotalizacoesRelatorios")] + [Description("RESTRINGIR VISUALIZAÇÃO DA TOTALIZAÇÃO DE VALOR PAGO")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR A TOTALIZAÇÃO DE VALOR PAGO DO RELATÓRIO.")] + [Tipo("RELATORIOS")] + RelatorioTotalizacaoValorPago, + [Category("TotalizacoesRelatorios")] + [Description("RESTRINGIR VISUALIZAÇÃO DA TOTALIZAÇÃO DE VALOR SALVADO")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR A TOTALIZAÇÃO DE VALOR SALVADO DO RELATÓRIO.")] + [Tipo("RELATORIOS")] + RelatorioTotalizacaoValorSalvado, + [Category("TotalizacoesRelatorios")] + [Description("RESTRINGIR VISUALIZAÇÃO DA TOTALIZAÇÃO DE VALOR FRANQUIA")] + [Help("IMPEDE O USUÁRIO DE VISUALIZAR A TOTALIZAÇÃO DE VALOR FRANQUIA DO RELATÓRIO.")] + [Tipo("RELATORIOS")] + RelatorioTotalizacaoValorFranquia, + [Category("Relatorios")] + [Description("RESTRINGIR ACESSO AO RELATÓRIO DE IMPORTAÇÃO")] + [Help("IMPEDE O USUÁRIO DE ACESSAR O RELATÓRIO DE IMPORTAÇÃO.")] + [OldValue("0")] + [Tipo("RELATORIOS")] + RelatorioImportacao, + [Category("B.I.")] + [Description("RESTRINGIR ACESSO À DASHBOARD DO USUÁRIO")] + [Help("IMPEDE QUE O USUÁRIO ACESSE SUA DASHBOARD.")] + Dashboard, + [Category("Seguros")] + [Description("RESTRINGIR ACESSO AOS LOGS")] + [Help("IMPEDE USUÁRIO DE ACESSAR OS LOGS.")] + Ocultarlogs, + [Category("Seguros")] + [Description("RESTRINGIR ALTERAÇÃO DE REMETENTE (MALA DIRETA)")] + [Help("IMPEDE QUE O USUÁRIO REALIZE ENVIOS E E-MAIL UTILIZANDO REMETENTES NÃO CADASTRADOS POR ELE.")] + RestringirRemetente, + [Category("Relatorios")] + [Description("RESTRINGIR ACESSO AO RELATÓRIO DE PLACA")] + [Help("IMPEDE O USUÁRIO DE ACESSAR O RELATÓRIO DE PLACAS.")] + [Tipo("RELATORIOS")] + RelatorioPlaca, + [Category("Relatorios")] + [Description("RESTRINGIR ACESSO AO RELATÓRIO DE ENDOSSOS")] + [Help("IMPEDE O USUÁRIO DE ACESSAR O RELATÓRIO DE ENDOSSOS.")] + [Tipo("RELATORIOS")] + RelatorioEndosso, + [Category("Seguros")] + [Description("RESTRINGIR ACESSO À CONTRATAÇÃO DE LICENÇAS AGGER SIGGNER")] + [Help("IMPEDE O USUÁRIO DE CONTRATAR MAIS LICENÇAS DE ASSINATURA DIGITAL NA PLATAFORMA AGGER SIGGNER.")] + AdquirirLicencasSiggner + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoSeguro.cs b/Codemerx/Gestor.Model/Model.Common/TipoSeguro.cs new file mode 100644 index 0000000..7f32927 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoSeguro.cs @@ -0,0 +1,33 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoSeguro + { + [Description("SEGURO NOVO")] + [OldValue("1")] + Novo = 1, + [Description("RENOVAÇÃO")] + [OldValue("2")] + Renovacao = 2, + [Description("CANCELADO")] + [OldValue("3")] + Cancelado = 3, + [Description("REABILITADO")] + [OldValue("4")] + Reabilitado = 4, + [Description("RENOVADO")] + [OldValue("5")] + Renovado = 5, + [Description("PERDIDO")] + [OldValue("6")] + Perdido = 6, + [Description("RECUSADO")] + [OldValue("7")] + Recusado = 7 + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoSinistro.cs b/Codemerx/Gestor.Model/Model.Common/TipoSinistro.cs new file mode 100644 index 0000000..bd053b3 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoSinistro.cs @@ -0,0 +1,18 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoSinistro + { + [Description("CLIENTE")] + [OldValue("0")] + Cliente, + [Description("TERCEIRO")] + [OldValue("1")] + Terceiro + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoTarefa.cs b/Codemerx/Gestor.Model/Model.Common/TipoTarefa.cs new file mode 100644 index 0000000..dad17ef --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoTarefa.cs @@ -0,0 +1,29 @@ +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoTarefa + { + [Description("APÓLICE")] + Apolice, + [Description("NOTAS")] + Notas, + [Description("CLIENTE")] + Cliente, + [Description("PARCELA")] + Parcela, + [Description("SINISTRO")] + Sinistro, + [Description("PROSPECÇÃO")] + Prospeccao, + [Description("META")] + Vendedor, + [Description("SEGURADORA")] + Seguradora, + [Description("AGENDA")] + Agenda + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoTela.cs b/Codemerx/Gestor.Model/Model.Common/TipoTela.cs new file mode 100644 index 0000000..cc95878 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoTela.cs @@ -0,0 +1,216 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoTela + { + [Description("Todas")] + Todas, + [Category("Seguros")] + [Description("CADASTRO DE CLIENTE")] + [Entity("ClienteView")] + Cliente, + [Category("Seguros")] + [Description("CADASTRO DE APÓLICE")] + [Entity("ApoliceView")] + Apolice, + [Category("Seguros")] + [Description("CADASTRO DE ITEM")] + [Entity("MenuItensView")] + Item, + [Description("TRILHA")] + Trilha, + [Category("Seguros")] + [Description("CADASTRO DE PARCELAS")] + [Entity("ApoliceView")] + Parcela, + [Description("CADASTRO DE ARQUIVO DIGITAL")] + Arquivo, + [Category("Seguros")] + [Description("SINISTRO")] + [Entity("SinistroView")] + Sinistro, + [Description("CONFIGURAÇÃO DE IMPORTAÇÃO")] + ConfigExtratoImport, + [Category("Ferramentas")] + [Description("CADASTRO DE ESTIPULANTE")] + [Entity("EstipulanteView")] + Estipulante, + [Category("Ferramentas")] + [Description("CADASTRO DE PRODUTO")] + [Entity("ProdutoView")] + Produto, + [Category("Ferramentas")] + [Description("CADASTRO DE STATUS")] + [Entity("StatusView")] + Status, + [Category("Ferramentas")] + [Description("MANUTENÇÃO DE RAMOS")] + [Entity("RamoView")] + Ramo, + [Category("Ferramentas")] + [Description("CADASTRO DE SEGURADORA")] + [Entity("SeguradoraView")] + Seguradora, + [Category("Ferramentas")] + [Description("CADASTRO DE TIPO DE VENDEDOR")] + [Entity("TipoVendedorView")] + TipoVendedor, + [Category("Ferramentas")] + [Description("CADASTRO DE VENDEDOR")] + [Entity("VendedorView")] + Vendedor, + [Category("Ferramentas")] + [Description("CADASTRO DE USUARIOS")] + [Entity("UsuarioView")] + Usuario, + [Category("Ferramentas")] + [Description("CADASTRO DE E-MAIL")] + [Entity("CadastroEmailView")] + Email, + [Category("Ferramentas")] + [Description("CADASTRO DE EMPRESA E FILIAIS")] + [Entity("EmpresaView")] + Empresa, + [Category("Ferramentas")] + [Description("CADASTRO DE SÓCIO")] + [Entity("SocioView")] + Socio, + [Description("CRÍTICA DE IMPORTACAO")] + [Entity("CriticaApoliceView")] + CriticaApolice, + [Category("Seguros")] + [Description("CONSULTA GERAL DE SEGUROS")] + [Entity("ConsultaOriginalView")] + Consulta, + [Category("Ferramentas")] + [Description("PARCEIRO")] + [Entity("CadastroParceiroView")] + Parceiro, + [Description("EXTRATO")] + Extrato, + [Category("Financeiro")] + [Description("FORNECEDOR")] + [Entity("FornecedorView")] + Fornecedor, + [Category("Financeiro")] + [Description("LANCAMENTO")] + [Entity("FinanceiroView")] + Lancamento, + [Category("Financeiro")] + [Description("BANCOS E CONTAS")] + [Entity("BancosContasView")] + Conta, + [Category("Financeiro")] + [Description("PLANO")] + Plano, + [Category("Financeiro")] + [Description("PLANOS")] + [Entity("PlanosView")] + Planos, + [Category("Financeiro")] + [Description("CENTRO")] + [Entity("CentroDeCustoView")] + Centro, + [Category("Ferramentas")] + [Description("META VENDEDOR")] + MetaVendedor, + [Category("Ferramentas")] + [Description("META SEGURADORA")] + MetaSeguradora, + [Category("Seguros")] + [Description("CADASTRO DE PERFIL")] + Perfil, + [Category("Prospeccao")] + [Description("PROSPECÇÃO")] + [Entity("ProspeccaoView")] + Prospeccao, + [Category("Seguros")] + [Description("AGENDA")] + Agenda, + [Description("BAIXA DE COMISSÃO AUTOMÁTICA")] + [Entity("ComissaoView")] + ComissaoAutomatica, + [Description("ADIANTAMENTO")] + Adiantamento, + [Description("PAGAMENTO VENDEDOR")] + PagamentoVendedor, + [Category("Ferramentas")] + [Description("TAREFA")] + [Entity("TarefaView")] + Tarefa, + [Description("MALA DIRETA")] + [Entity("MalaDiretaView")] + MalaDireta, + [Description("ATENDIMENTO")] + [Entity("AtendimentosView")] + Atendimento, + [Description("TROCA DE CLIENTE")] + TrocaCliente, + [Category("Ferramentas")] + [Description("CADASTRO DE RECIBOS")] + [Entity("ReciboView")] + Recibo, + [Category("Ferramentas")] + [Description("PERMISSÕES/RESTRIÇÕES")] + PermissaoRestricao, + [Category("Assinatura")] + [Description("ASSINATURA ELETRONICA")] + Assinatura, + [Description("VINCULO VENDEDOR")] + VinculoVendedor, + [Category("Seguros")] + [Description("INFORMAÇÔES DE EXPEDIÇÃO")] + Expedicao, + Restricao, + [Category("Ferramentas")] + [Description("CADASTRO DE QUALIFICACAO")] + [Entity("QualificacaoView")] + Qualificacao, + [Description("LOGIN")] + Login, + [Description("CONFIGURAÇÕES DO SISTEMA")] + Configuracoes, + [Description("PAINEL BI")] + [Entity("PainelBiView")] + PainelBi, + [Category("Ferramentas")] + [Description("TIPO DE TAREFA")] + [Entity("TipoTarefaView")] + TipoTarefa, + [Category("Ferramentas")] + [Description("VINCULO REPASSES")] + VinculoRepasses, + [Description("CADASTRO DE REPASSE")] + [Entity("VendedorView")] + Repasse, + [Category("Ferramentas")] + [Description("CADASTRO DE NOTA FISCAL")] + [Entity("NotaFiscalView")] + NotaFiscal, + [Category("Ferramentas")] + [Description("CADASTRO DE PERCENTUAIS DE IMPOSTOS")] + [Entity("ImpostoDrawer")] + Impostos, + [Category("Ferramentas")] + [Description("STATUS DE PROSPECÇÃO")] + [Entity("StatusProspeccaoView")] + StatusProspeccao, + [Category("Ferramentas")] + [Description("MANUTENÇÃO DE PAGAMENTOS")] + [Entity("ManutencaoPagamentosView")] + ManutencaoPagamentos, + [Category("Ferramentas")] + [Description("PROTOCOLOS E ETIQUETAS")] + [Entity("ProdutoView")] + ProtocolosEtiquetas, + [Category("Ferramentas")] + [Description("PROSPECÇÃO")] + [Entity("ProspeccaoView")] + ProspeccaoPermissao + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoTelaInicial.cs b/Codemerx/Gestor.Model/Model.Common/TipoTelaInicial.cs new file mode 100644 index 0000000..336835b --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoTelaInicial.cs @@ -0,0 +1,21 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoTelaInicial + { + [Description("CONSULTA GERAL")] + [OldValue("0")] + Consulta, + [Description("PAINEL B.I.")] + [OldValue("1")] + PainelBi, + [Description("FINANCEIRO")] + [OldValue("2")] + Financeiro + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoTelefone.cs b/Codemerx/Gestor.Model/Model.Common/TipoTelefone.cs new file mode 100644 index 0000000..74e4bae --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoTelefone.cs @@ -0,0 +1,56 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoTelefone + { + [Description("RESIDENCIAL")] + [OldValue("1")] + [Tipo("1")] + Residencial = 1, + [Description("COMERCIAL")] + [OldValue("2")] + [Tipo("1")] + Comercial = 2, + [Description("CELULAR")] + [OldValue("3")] + [Tipo("1")] + Celular = 3, + [Description("RADIO")] + [OldValue("4")] + [Tipo("1")] + Radio = 4, + [Description("RECADO")] + [OldValue("5")] + [Tipo("1")] + Recado = 5, + [Description("FAX")] + [OldValue("6")] + [Tipo("1")] + Fax = 6, + [Description("OUTROS")] + [OldValue("7")] + [Tipo("1")] + Outros = 7, + [Description("INTERNACIONAL")] + [OldValue("8")] + [Tipo("0")] + Internacional = 8, + [Description("WHATSAPP")] + [OldValue("9")] + [Tipo("2")] + Whatsapp = 9, + [Description("0800")] + [OldValue("10")] + [Tipo("0")] + Gratuita = 10, + [Description("0300")] + [OldValue("11")] + [Tipo("0")] + TarifaUnica = 11 + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoTitular.cs b/Codemerx/Gestor.Model/Model.Common/TipoTitular.cs new file mode 100644 index 0000000..2684f3f --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoTitular.cs @@ -0,0 +1,21 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoTitular + { + [Description("SÓCIO")] + [OldValue("0")] + Socio, + [Description("FUNCIONÁRIO")] + [OldValue("1")] + Funcionario, + [Description("DEPENDENTE")] + [OldValue("2")] + Dependente + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TipoTrilha.cs b/Codemerx/Gestor.Model/Model.Common/TipoTrilha.cs new file mode 100644 index 0000000..8a7c7fd --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TipoTrilha.cs @@ -0,0 +1,12 @@ +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TipoTrilha + { + Acompanhamento + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/TpoSituacaoSinistro.cs b/Codemerx/Gestor.Model/Model.Common/TpoSituacaoSinistro.cs new file mode 100644 index 0000000..6e79ebb --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/TpoSituacaoSinistro.cs @@ -0,0 +1,21 @@ +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum TpoSituacaoSinistro + { + [Description("EM ANDAMENTO")] + Andamento = 1, + [Description("LIQUIDADO")] + Liquidado = 2, + [Description("LIQUIDADO SEM INDENIZAÇÃO")] + LiquidadoSemIndenizacao = 3, + [Description("NEGADO")] + Negado = 4, + [Description("ATENDIDO COMO TERCEIRO")] + Terceiro = 5 + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/UsoDependetes.cs b/Codemerx/Gestor.Model/Model.Common/UsoDependetes.cs new file mode 100644 index 0000000..a6966c1 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/UsoDependetes.cs @@ -0,0 +1,27 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum UsoDependetes + { + [Description("NÃO POSSUI")] + [OldValue("0")] + NaoPossui, + [Description("SIM, DO SEXO MASCULINO")] + [OldValue("1")] + SimMasculino, + [Description("SIM, DO SEXO FEMININO")] + [OldValue("2")] + SimFeminino, + [Description("SIM, DE AMBOS OS SEXOS")] + [OldValue("3")] + SimAmbos, + [Description("NÃO UTILIZAM")] + [OldValue("4")] + NaoUtilizam + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/UsoVeiculo.cs b/Codemerx/Gestor.Model/Model.Common/UsoVeiculo.cs new file mode 100644 index 0000000..ed52257 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/UsoVeiculo.cs @@ -0,0 +1,24 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum UsoVeiculo + { + [Description("PARTICULAR")] + [OldValue("0")] + Particular, + [Description("PROFISSIONAL")] + [OldValue("1")] + Profissional, + [Description("TAXI")] + [OldValue("2")] + Taxi, + [Description("MOTORISTA DE APP")] + [OldValue("3")] + Aplicativo + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/Utilizacao.cs b/Codemerx/Gestor.Model/Model.Common/Utilizacao.cs new file mode 100644 index 0000000..17860c0 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/Utilizacao.cs @@ -0,0 +1,18 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Common +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum Utilizacao + { + [Description("RESIDENCIAL")] + [OldValue("1")] + Residencial = 1, + [Description("COMERCIAL")] + [OldValue("2")] + Comercial = 2 + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Common/ValidationStates.cs b/Codemerx/Gestor.Model/Model.Common/ValidationStates.cs new file mode 100644 index 0000000..e9b84e4 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Common/ValidationStates.cs @@ -0,0 +1,11 @@ +using System; + +namespace Gestor.Model.Common +{ + public enum ValidationStates + { + Ok, + Error, + Warning + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Converter/EnumDescriptionTypeConverter.cs b/Codemerx/Gestor.Model/Model.Converter/EnumDescriptionTypeConverter.cs new file mode 100644 index 0000000..8524561 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Converter/EnumDescriptionTypeConverter.cs @@ -0,0 +1,37 @@ +using System; +using System.ComponentModel; +using System.Globalization; +using System.Reflection; + +namespace Gestor.Model.Converter +{ + public class EnumDescriptionTypeConverter : EnumConverter + { + public EnumDescriptionTypeConverter(Type type) : base(type) + { + } + + public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) + { + if (destinationType != typeof(string)) + { + return base.ConvertTo(context, culture, value, destinationType); + } + if (value == null) + { + return string.Empty; + } + FieldInfo field = value.GetType().GetField(value.ToString()); + if (field == null) + { + return string.Empty; + } + DescriptionAttribute[] customAttributes = (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), false); + if (customAttributes.Length == 0 || string.IsNullOrEmpty(customAttributes[0].Description)) + { + return value.ToString(); + } + return customAttributes[0].Description; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Aggilizador/ArquivoVinculo.cs b/Codemerx/Gestor.Model/Model.Domain.Aggilizador/ArquivoVinculo.cs new file mode 100644 index 0000000..b899c13 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Aggilizador/ArquivoVinculo.cs @@ -0,0 +1,48 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Aggilizador +{ + public class ArquivoVinculo + { + public int Ano + { + get; + set; + } + + public byte[] Arquivo + { + get; + set; + } + + public string Chave + { + get; + set; + } + + public long Id + { + get; + set; + } + + public long IdVinculo + { + get; + set; + } + + public string Storage + { + get; + set; + } + + public ArquivoVinculo() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Aggilizador/Calculo.cs b/Codemerx/Gestor.Model/Model.Domain.Aggilizador/Calculo.cs new file mode 100644 index 0000000..27a20d8 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Aggilizador/Calculo.cs @@ -0,0 +1,39 @@ +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Aggilizador +{ + public class Calculo : DomainBase + { + public DateTime DataAtualizacao + { + get; + set; + } + + public long DocumentId + { + get; + set; + } + + public StatusCalculo Status + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Usuario Usuario + { + get; + set; + } + + public Calculo() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Aggilizador/LocalArquivo.cs b/Codemerx/Gestor.Model/Model.Domain.Aggilizador/LocalArquivo.cs new file mode 100644 index 0000000..ca974a6 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Aggilizador/LocalArquivo.cs @@ -0,0 +1,36 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Aggilizador +{ + public class LocalArquivo + { + public string Arquivo + { + get; + set; + } + + public long IdApoliceDigital + { + get; + set; + } + + public long IdExtratoDigital + { + get; + set; + } + + public long IdPropostaDigital + { + get; + set; + } + + public LocalArquivo() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Aggilizador/ParcelaPendente.cs b/Codemerx/Gestor.Model/Model.Domain.Aggilizador/ParcelaPendente.cs new file mode 100644 index 0000000..c56f34d --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Aggilizador/ParcelaPendente.cs @@ -0,0 +1,60 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Aggilizador +{ + public class ParcelaPendente + { + public string Apolice + { + get; + set; + } + + public string Cliente + { + get; + set; + } + + public long Id + { + get; + set; + } + + public long IdParcela + { + get; + set; + } + + public int Parcela + { + get; + set; + } + + public string Seguradora + { + get; + set; + } + + public decimal Valor + { + get; + set; + } + + public DateTime Vencimento + { + get; + set; + } + + public ParcelaPendente() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Aggilizador/VinculoDocumento.cs b/Codemerx/Gestor.Model/Model.Domain.Aggilizador/VinculoDocumento.cs new file mode 100644 index 0000000..6f9f470 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Aggilizador/VinculoDocumento.cs @@ -0,0 +1,36 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Aggilizador +{ + public class VinculoDocumento + { + public long Id + { + get; + set; + } + + public long IdApoliceDigital + { + get; + set; + } + + public long IdDocumento + { + get; + set; + } + + public long IdPropostaDigital + { + get; + set; + } + + public VinculoDocumento() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.BI/Analitico.cs b/Codemerx/Gestor.Model/Model.Domain.BI/Analitico.cs new file mode 100644 index 0000000..e425100 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.BI/Analitico.cs @@ -0,0 +1,240 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Relatorios.ClientesAtivosInativos; +using Gestor.Model.Domain.Seguros; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.BI +{ + public class Analitico + { + [Description("APÓLICE")] + public string Apolice + { + get; + set; + } + + public string Cep + { + get; + set; + } + + public string Cidade + { + get; + set; + } + + public ClientesAtivosInativos Cliente + { + get; + set; + } + + [Description("COMISSÃO")] + [Tipo("PERCENTUAL")] + public decimal Comissao + { + get; + set; + } + + public string DiaMes + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Documento Documento + { + get; + set; + } + + [Description("DOCUMENTO")] + public string DocumentoCliente + { + get; + set; + } + + public string Email + { + get; + set; + } + + [Description("ENDOSSO")] + public string Endosso + { + get; + set; + } + + [Description("NASCIMENTO")] + [Tipo("DATA?")] + public DateTime? Nascimento + { + get; + set; + } + + [Description("NEGÓCIO CORRETORA")] + public string Negocio + { + get; + set; + } + + [Description("NOME")] + public string Nome + { + get; + set; + } + + [Description("PARCELA")] + public int NumeroParcela + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Parcela Parcela + { + get; + set; + } + + [Description("PRÊMIO LÍQUIDO")] + [Tipo("VALOR")] + public decimal PremioLiquido + { + get; + set; + } + + [Description("PRÊMIO TOTAL")] + [Tipo("VALOR")] + public decimal PremioTotal + { + get; + set; + } + + public string Profissao + { + get; + set; + } + + [Description("RAMO")] + public string Ramo + { + get; + set; + } + + [Description("RECEBIMENTO")] + [Tipo("DATA?")] + public DateTime? Recebimento + { + get; + set; + } + + [Description("SEGURADORA")] + public string Seguradora + { + get; + set; + } + + public bool Selecionado + { + get; + set; + } + + [Description("STATUS")] + public string Status + { + get; + set; + } + + public string Telefone + { + get; + set; + } + + [Description("TIPO DE PESSOA")] + public string TipoPessoa + { + get; + set; + } + + public string Uf + { + get; + set; + } + + [Description("VALOR")] + [Tipo("VALOR")] + public decimal Valor + { + get; + set; + } + + [Description("VALOR COMISSÃO")] + [Tipo("VALOR")] + public decimal ValorComissao + { + get; + set; + } + + [Description("VENCIMENTO")] + [Tipo("DATA")] + public DateTime Vencimento + { + get; + set; + } + + [Description("VENCIMENTO CNH")] + [Tipo("DATA?")] + public DateTime? VencimentoHabilitacao + { + get; + set; + } + + [Description("VIGÊNCIA FINAL")] + [Tipo("DATA?")] + public DateTime? VigenciaFinal + { + get; + set; + } + + [Description("VIGÊNCIA INICIAL")] + [Tipo("DATA")] + public DateTime VigenciaInicial + { + get; + set; + } + + public Analitico() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.BI/AtalhosApolice.cs b/Codemerx/Gestor.Model/Model.Domain.BI/AtalhosApolice.cs new file mode 100644 index 0000000..6344463 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.BI/AtalhosApolice.cs @@ -0,0 +1,112 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.BI +{ + public class AtalhosApolice + { + public string Agrupamento + { + get; + set; + } + + [Description("CANCELADOS")] + [Tipo("VALOR")] + public Tuple<decimal, int, List<Documento>> Cancelados + { + get; + set; + } + + public DateTime Fim + { + get; + set; + } + + [Description("COMISSÃO GERADA")] + [Tipo("VALOR")] + public Tuple<decimal, int, List<Documento>> Gerada + { + get; + set; + } + + public long Id + { + get; + set; + } + + public DateTime Inicio + { + get; + set; + } + + [Description("NOVOS NEGÓCIOS")] + [Tipo("VALOR")] + public Tuple<decimal, int, List<Documento>> NovosNegocios + { + get; + set; + } + + [Description("APÓLICES PENDENTES")] + [Tipo("QUANTIDADE")] + public Tuple<decimal, int, List<Documento>> Pendencia + { + get; + set; + } + + [Description("PERDIDOS")] + [Tipo("VALOR")] + public Tuple<decimal, int, List<Documento>> Perdidos + { + get; + set; + } + + [Description("PRODUÇÃO")] + [Tipo("VALOR")] + public Tuple<decimal, int, List<Documento>> Producao + { + get; + set; + } + + [Description("RENOVADOS")] + [Tipo("VALOR")] + public Tuple<decimal, int, List<Documento>> Renovados + { + get; + set; + } + + [Description("SEGUROS VENCIDOS")] + [Tipo("QUANTIDADE")] + public Tuple<decimal, int, List<Documento>> Vencidos + { + get; + set; + } + + [Description("SEGUROS VENCENDO")] + [Tipo("QUANTIDADE")] + public Tuple<decimal, int, List<Documento>> Vencimento + { + get; + set; + } + + public AtalhosApolice() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.BI/AtalhosCalculo.cs b/Codemerx/Gestor.Model/Model.Domain.BI/AtalhosCalculo.cs new file mode 100644 index 0000000..c1a0ec4 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.BI/AtalhosCalculo.cs @@ -0,0 +1,28 @@ +using Gestor.Model.Attributes; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.BI +{ + public class AtalhosCalculo + { + public string Agrupamento + { + get; + set; + } + + [Description("COTAÇÕES")] + [Tipo("QUANTIDADE")] + public int Cotacoes + { + get; + set; + } + + public AtalhosCalculo() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.BI/AtalhosCliente.cs b/Codemerx/Gestor.Model/Model.Domain.BI/AtalhosCliente.cs new file mode 100644 index 0000000..89d1287 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.BI/AtalhosCliente.cs @@ -0,0 +1,50 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.BI +{ + public class AtalhosCliente + { + [Description("ANIVERSARIANTES")] + [Tipo("QUANTIDADE")] + public int Aniversariantes + { + get; + set; + } + + public List<Cliente> Clientes + { + get; + set; + } + + public DateTime Fim + { + get; + set; + } + + public DateTime Inicio + { + get; + set; + } + + [Description("VENCIMENTO CNH")] + [Tipo("QUANTIDADE")] + public int VencimentoCnh + { + get; + set; + } + + public AtalhosCliente() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.BI/AtalhosComissao.cs b/Codemerx/Gestor.Model/Model.Domain.BI/AtalhosComissao.cs new file mode 100644 index 0000000..1098202 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.BI/AtalhosComissao.cs @@ -0,0 +1,36 @@ +using Gestor.Model.Attributes; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.BI +{ + public class AtalhosComissao + { + public string Agrupamento + { + get; + set; + } + + [Description("AUDITORIA DE COMISSÃO")] + [Tipo("VALOR")] + public decimal Auditoria + { + get; + set; + } + + [Description("COMISSÃO RECEBIDA")] + [Tipo("VALOR")] + public decimal Recebida + { + get; + set; + } + + public AtalhosComissao() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.BI/AtalhosParcela.cs b/Codemerx/Gestor.Model/Model.Domain.BI/AtalhosParcela.cs new file mode 100644 index 0000000..c992a69 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.BI/AtalhosParcela.cs @@ -0,0 +1,72 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.BI +{ + public class AtalhosParcela + { + public string Agrupamento + { + get; + set; + } + + public DateTime Fim + { + get; + set; + } + + public long Id + { + get; + set; + } + + public DateTime Inicio + { + get; + set; + } + + [Description("PARCELAS PAGAS")] + [Tipo("QUANTIDADE")] + public Tuple<decimal, int, List<Parcela>> Pagas + { + get; + set; + } + + [Description("PARCELAS PENDENTES")] + [Tipo("QUANTIDADE")] + public Tuple<decimal, int, List<Parcela>> Pendente + { + get; + set; + } + + [Description("COMISSÃO RECEBIDA")] + [Tipo("VALOR")] + public Tuple<decimal, int, List<Parcela>> Recebida + { + get; + set; + } + + [Description("PARCELAS À VENCER")] + [Tipo("QUANTIDADE")] + public Tuple<decimal, int, List<Parcela>> Vencimento + { + get; + set; + } + + public AtalhosParcela() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.BI/AtalhosSinistro.cs b/Codemerx/Gestor.Model/Model.Domain.BI/AtalhosSinistro.cs new file mode 100644 index 0000000..d5f5a0d --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.BI/AtalhosSinistro.cs @@ -0,0 +1,28 @@ +using Gestor.Model.Attributes; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.BI +{ + public class AtalhosSinistro + { + public string Agrupamento + { + get; + set; + } + + [Description("SINISTROS")] + [Tipo("QUANTIDADE")] + public int Sinistros + { + get; + set; + } + + public AtalhosSinistro() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Card/Assistance.cs b/Codemerx/Gestor.Model/Model.Domain.Card/Assistance.cs new file mode 100644 index 0000000..79c8696 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Card/Assistance.cs @@ -0,0 +1,180 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Card +{ + public class Assistance + { + public string Apolice + { + get; + set; + } + + public string Assistencia1 + { + get; + set; + } + + public string Assistencia1Obs + { + get; + set; + } + + public int Assistencia1Tipo + { + get; + set; + } + + public string Assistencia2 + { + get; + set; + } + + public string Assistencia2Obs + { + get; + set; + } + + public int Assistencia2Tipo + { + get; + set; + } + + public string Assistencia3 + { + get; + set; + } + + public string Assistencia3Obs + { + get; + set; + } + + public int Assistencia3Tipo + { + get; + set; + } + + public string Assistencia4 + { + get; + set; + } + + public string Assistencia4Obs + { + get; + set; + } + + public int Assistencia4Tipo + { + get; + set; + } + + public string Corretora + { + get; + set; + } + + public string CustomId + { + get; + set; + } + + public long IdRamo + { + get; + set; + } + + public long IdSeguradora + { + get; + set; + } + + public string Item + { + get; + set; + } + + public string LinkAppAndroid + { + get; + set; + } + + public string LinkAppIos + { + get; + set; + } + + public byte[] Logo + { + get; + set; + } + + public string Nome + { + get; + set; + } + + public string Obs + { + get; + set; + } + + public decimal Premio + { + get; + set; + } + + public string Seguradora + { + get; + set; + } + + public DateTime VigenciaFinal + { + get; + set; + } + + public DateTime VigenciaInicial + { + get; + set; + } + + public string WhatsappSinistro + { + get; + set; + } + + public Assistance() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Card/AssistenciaCia.cs b/Codemerx/Gestor.Model/Model.Domain.Card/AssistenciaCia.cs new file mode 100644 index 0000000..1ca33a5 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Card/AssistenciaCia.cs @@ -0,0 +1,114 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Card +{ + public class AssistenciaCia + { + public string Assistencia1 + { + get; + set; + } + + public string Assistencia1Obs + { + get; + set; + } + + public int Assistencia1Tipo + { + get; + set; + } + + public string Assistencia2 + { + get; + set; + } + + public string Assistencia2Obs + { + get; + set; + } + + public int Assistencia2Tipo + { + get; + set; + } + + public string Assistencia3 + { + get; + set; + } + + public string Assistencia3Obs + { + get; + set; + } + + public int Assistencia3Tipo + { + get; + set; + } + + public string Assistencia4 + { + get; + set; + } + + public string Assistencia4Obs + { + get; + set; + } + + public int Assistencia4Tipo + { + get; + set; + } + + public string CustomId + { + get; + set; + } + + public long IdSeguradora + { + get; + set; + } + + public string LinkAppAndroid + { + get; + set; + } + + public string LinkAppIos + { + get; + set; + } + + public string Seguradora + { + get; + set; + } + + public AssistenciaCia() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Card/Card.cs b/Codemerx/Gestor.Model/Model.Domain.Card/Card.cs new file mode 100644 index 0000000..0e364c6 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Card/Card.cs @@ -0,0 +1,120 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Card +{ + public class Card + { + public string Cargo + { + get; + set; + } + + public string Corretora + { + get; + set; + } + + public string CustomId + { + get; + set; + } + + public string Email + { + get; + set; + } + + public string Endereco + { + get; + set; + } + + public string Facebook + { + get; + set; + } + + public string Instagram + { + get; + set; + } + + public string LinkAggilizador + { + get; + set; + } + + public string Linkdin + { + get; + set; + } + + public string Localizacao + { + get; + set; + } + + public byte[] Logo + { + get; + set; + } + + public string Nome + { + get; + set; + } + + public string Obs + { + get; + set; + } + + public string Site + { + get; + set; + } + + public string Telefone1 + { + get; + set; + } + + public string Telefone2 + { + get; + set; + } + + public string Twitter + { + get; + set; + } + + public string Whatsapp + { + get; + set; + } + + public Card() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Card/Logo.cs b/Codemerx/Gestor.Model/Model.Domain.Card/Logo.cs new file mode 100644 index 0000000..9c1596c --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Card/Logo.cs @@ -0,0 +1,42 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Card +{ + public class Logo + { + public string Corretora + { + get; + set; + } + + public string CustomId + { + get; + set; + } + + public byte[] Data + { + get; + set; + } + + public string Whatsapp + { + get; + set; + } + + public string WhatsappSinistro + { + get; + set; + } + + public Logo() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Common/ArquivoDigital.cs b/Codemerx/Gestor.Model/Model.Domain.Common/ArquivoDigital.cs new file mode 100644 index 0000000..d0fb6a1 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Common/ArquivoDigital.cs @@ -0,0 +1,213 @@ +using Gestor.Model.Domain.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Common +{ + public class ArquivoDigital : DomainBase + { + private string _descricao; + + private string _extensao; + + public byte[] Arquivo + { + get; + set; + } + + public Guid? AzureGuid + { + get; + set; + } + + public string AzureStorage + { + get; + set; + } + + public DateTime? DataAtualizacao + { + get; + set; + } + + public DateTime? DataCriacao + { + get; + set; + } + + public string Descricao + { + get + { + string str = this._descricao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._descricao = value; + } + } + + public bool Excluido + { + get; + set; + } + + public string Extensao + { + get + { + string str = this._extensao; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._extensao = value; + } + } + + public long IdCliente + { + get; + set; + } + + public long IdDocumento + { + get; + set; + } + + public long IdEmpresa + { + get; + set; + } + + public long IdEstipulante + { + get; + set; + } + + public long IdExtrato + { + get; + set; + } + + public long IdFornecedor + { + get; + set; + } + + public long IdItem + { + get; + set; + } + + public long IdLancamento + { + get; + set; + } + + public long IdNotaFiscal + { + get; + set; + } + + public long IdParcela + { + get; + set; + } + + public long IdProspeccao + { + get; + set; + } + + public long IdSeguradora + { + get; + set; + } + + public long IdSinistro + { + get; + set; + } + + public long IdSocio + { + get; + set; + } + + public long IdTarefa + { + get; + set; + } + + public long IdUsuario + { + get; + set; + } + + public long IdVendedor + { + get; + set; + } + + public int QuantidadeAcesso + { + get; + set; + } + + public DateTime? UltimoAcesso + { + get; + set; + } + + public long UsuarioAtualizacao + { + get; + set; + } + + public long UsuarioCriacao + { + get; + set; + } + + public ArquivoDigital() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Common/Atividade.cs b/Codemerx/Gestor.Model/Model.Domain.Common/Atividade.cs new file mode 100644 index 0000000..d5a67d7 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Common/Atividade.cs @@ -0,0 +1,50 @@ +using Gestor.Model.Domain.Generic; +using System; + +namespace Gestor.Model.Domain.Common +{ + public class Atividade : DomainBase + { + private string _cnac; + + private string _nome; + + public string Cnac + { + get + { + string str = this._cnac; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._cnac = value; + } + } + + public string Nome + { + get + { + string str = this._nome; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._nome = value; + } + } + + public Atividade() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Common/Banco.cs b/Codemerx/Gestor.Model/Model.Domain.Common/Banco.cs new file mode 100644 index 0000000..b74b1d4 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Common/Banco.cs @@ -0,0 +1,87 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Generic; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Common +{ + public class Banco : IDomain + { + private string _nome; + + private string _site; + + [Log(true)] + public int Codigo + { + get; + set; + } + + public int Id + { + get; + set; + } + + [Description("BANCO")] + [Log(true)] + [Name(true)] + public string Nome + { + get + { + string str = this._nome; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._nome = value; + } + } + + [Log(true)] + public string Site + { + get + { + string str = this._site; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._site = value; + } + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Banco banco = this; + return new Func<List<KeyValuePair<string, string>>>(banco.Validate); + } + } + + public Banco() + { + } + + public List<KeyValuePair<string, string>> Validate() + { + return new List<KeyValuePair<string, string>>(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Common/Contato.cs b/Codemerx/Gestor.Model/Model.Domain.Common/Contato.cs new file mode 100644 index 0000000..5691e6e --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Common/Contato.cs @@ -0,0 +1,31 @@ +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Common +{ + public class Contato + { + public string Numero + { + get; + set; + } + + public TipoContato Tipo + { + get; + set; + } + + public Gestor.Model.Common.TipoTelefone? TipoTelefone + { + get; + set; + } + + public Contato() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Common/ControleArquivoDigital.cs b/Codemerx/Gestor.Model/Model.Domain.Common/ControleArquivoDigital.cs new file mode 100644 index 0000000..de0c050 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Common/ControleArquivoDigital.cs @@ -0,0 +1,25 @@ +using Gestor.Model.Domain.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Common +{ + public class ControleArquivoDigital : DomainBase + { + public string Catalogo + { + get; + set; + } + + public string Tabela + { + get; + set; + } + + public ControleArquivoDigital() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Common/Empresa.cs b/Codemerx/Gestor.Model/Model.Domain.Common/Empresa.cs new file mode 100644 index 0000000..46a001c --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Common/Empresa.cs @@ -0,0 +1,546 @@ +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Common +{ + public class Empresa : EnderecoBase, IDomain + { + private string _nome; + + private string _documento; + + private string _serial; + + private string _site; + + private string _email; + + private string _primeiroPrefixo; + + private string _primeiroTelefone; + + private string _segundoPrefixo; + + private string _segundoTelefone; + + private string _quantidadeFiliais; + + private string _responsavel; + + private string _emailResponsavel; + + private TipoTelefone? _tipo1; + + private TipoTelefone? _tipo2; + + public string Documento + { + get + { + string str = this._documento; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._documento = value; + } + } + + public string Email + { + get + { + string str = this._email; + if (str == null) + { + return null; + } + return str.ToLower().Trim(); + } + set + { + this._email = value; + } + } + + public string EmailResponsavel + { + get + { + string str = this._emailResponsavel; + if (str == null) + { + return null; + } + return str.ToLower().Trim(); + } + set + { + this._emailResponsavel = value; + } + } + + public string Facebook + { + get; + set; + } + + public string Instagram + { + get; + set; + } + + public string Linkdin + { + get; + set; + } + + public string Localizacao + { + get; + set; + } + + public byte[] Logo + { + get; + set; + } + + public string LogoId + { + get; + set; + } + + public int MaxFileSize + { + get; + set; + } + + public string Nome + { + get + { + string str = this._nome; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._nome = value; + } + } + + public string NomeSocial + { + get; + set; + } + + public string PrimeiroPrefixo + { + get + { + string str = this._primeiroPrefixo; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._primeiroPrefixo = value; + } + } + + public string PrimeiroTelefone + { + get + { + string str = this._primeiroTelefone; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._primeiroTelefone = value; + } + } + + public string QuantidadeFiliais + { + get + { + string str = this._quantidadeFiliais; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._quantidadeFiliais = value; + } + } + + public long QuantidadeFuncionarios + { + get; + set; + } + + public string Responsavel + { + get + { + string str = this._responsavel; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._responsavel = value; + } + } + + public string SegundoPrefixo + { + get + { + string str = this._segundoPrefixo; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._segundoPrefixo = value; + } + } + + public string SegundoTelefone + { + get + { + string str = this._segundoTelefone; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._segundoTelefone = value; + } + } + + public string SenhaAdmin + { + get; + set; + } + + public string Serial + { + get + { + string str = this._serial; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._serial = value; + } + } + + public string Site + { + get + { + string str = this._site; + if (str != null) + { + return str.Trim(); + } + return null; + } + set + { + this._site = value; + } + } + + public TipoTelefone TipoTelefone1 + { + get + { + if (this._tipo1.HasValue) + { + TipoTelefone? nullable = this._tipo1; + if (!((int)nullable.GetValueOrDefault() == 0 & nullable.HasValue)) + { + return this._tipo1.Value; + } + } + return TipoTelefone.Comercial; + } + set + { + this._tipo1 = new TipoTelefone?(value); + } + } + + public TipoTelefone TipoTelefone2 + { + get + { + if (this._tipo2.HasValue) + { + TipoTelefone? nullable = this._tipo2; + if (!((int)nullable.GetValueOrDefault() == 0 & nullable.HasValue)) + { + return this._tipo2.Value; + } + } + return TipoTelefone.Comercial; + } + set + { + this._tipo2 = new TipoTelefone?(value); + } + } + + public string Twitter + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Empresa empresa = this; + return new Func<List<KeyValuePair<string, string>>>(empresa.Validate); + } + } + + public string Whatsapp + { + get; + set; + } + + public string WhatsappSinistro + { + get; + set; + } + + public Empresa() + { + } + + public List<TupleList> Log() + { + List<TupleList> tupleLists = new List<TupleList>(); + TupleList tupleList = new TupleList(); + ObservableCollection<Tuple<string, string, string>> observableCollection = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("DOCUMENTO (CPF/CNPJ)", (string.IsNullOrWhiteSpace(this.Documento) ? "" : this.Documento), ""), + new Tuple<string, string, string>("NÚMERO DE SÉRIE", (string.IsNullOrWhiteSpace(this.Serial) ? "" : this.Serial), ""), + new Tuple<string, string, string>("NOME", (string.IsNullOrWhiteSpace(this.Nome) ? "" : this.Nome), ""), + new Tuple<string, string, string>("CEP", (string.IsNullOrWhiteSpace(base.Cep) ? "" : base.Cep), ""), + new Tuple<string, string, string>("ENDEREÇO", (string.IsNullOrWhiteSpace(base.Endereco) ? "" : base.Endereco), ""), + new Tuple<string, string, string>("NÚMERO", (string.IsNullOrWhiteSpace(base.Numero) ? "" : base.Numero), ""), + new Tuple<string, string, string>("BAIRRO", (string.IsNullOrWhiteSpace(base.Bairro) ? "" : base.Bairro), ""), + new Tuple<string, string, string>("CIDADE", (string.IsNullOrWhiteSpace(base.Cidade) ? "" : base.Cidade), ""), + new Tuple<string, string, string>("ESTADO", (string.IsNullOrWhiteSpace(base.Estado) ? "" : base.Estado), ""), + new Tuple<string, string, string>("SITE", (string.IsNullOrWhiteSpace(this.Site) ? "" : this.Site), ""), + new Tuple<string, string, string>("E-MAIL", (string.IsNullOrWhiteSpace(this.Email) ? "" : this.Email), ""), + new Tuple<string, string, string>("PRIMEIRO PREFIXO", (string.IsNullOrWhiteSpace(this.PrimeiroPrefixo) ? "" : this.PrimeiroPrefixo), ""), + new Tuple<string, string, string>("PRIMEIRO TELEFONE", (string.IsNullOrWhiteSpace(this.PrimeiroTelefone) ? "" : this.PrimeiroTelefone), ""), + new Tuple<string, string, string>("SEGUNDO PREFIXO", (string.IsNullOrWhiteSpace(this.SegundoPrefixo) ? "" : this.SegundoPrefixo), ""), + new Tuple<string, string, string>("SEGUNDO TELEFONE", (string.IsNullOrWhiteSpace(this.SegundoTelefone) ? "" : this.SegundoTelefone), ""), + new Tuple<string, string, string>("E-MAIL", (string.IsNullOrWhiteSpace(this.Email) ? "" : this.Email), "") + }; + long quantidadeFuncionarios = this.QuantidadeFuncionarios; + observableCollection.Add(new Tuple<string, string, string>("NÚMERO DE FUNCIONÁRIOS", quantidadeFuncionarios.ToString(), "")); + observableCollection.Add(new Tuple<string, string, string>("RESPONSÁVEL FINANCEIRO", (string.IsNullOrWhiteSpace(this.Responsavel) ? "" : this.Responsavel), "")); + observableCollection.Add(new Tuple<string, string, string>("E-MAIL DO RESPONSÁVEL", (string.IsNullOrWhiteSpace(this.EmailResponsavel) ? "" : this.EmailResponsavel), "")); + tupleList.Tuples = observableCollection; + tupleLists.Add(tupleList); + return tupleLists; + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (string.IsNullOrWhiteSpace(this.Documento)) + { + keyValuePairs.AddValue<string, string>("Documento", Messages.Obrigatorio, true); + } + else if (!this.Documento.ValidacaoDocumento()) + { + keyValuePairs.AddValue<string, string>("Documento", Messages.Invalido, true); + } + if (string.IsNullOrWhiteSpace(this.Serial)) + { + keyValuePairs.AddValue<string, string>("Serial", Messages.Obrigatorio, true); + } + else if (this.Serial.Length > 18) + { + keyValuePairs.AddValue<string, string>("Serial", string.Format(Messages.MaiorQueLimite, 18), true); + } + if (!string.IsNullOrWhiteSpace(this.Site) && this.Site.Length > 80) + { + keyValuePairs.AddValue<string, string>("Site", string.Format(Messages.MaiorQueLimite, 80), true); + } + if (!string.IsNullOrWhiteSpace(this.SenhaAdmin) && this.SenhaAdmin.Length > 90) + { + keyValuePairs.AddValue<string, string>("SenhaAdmin", string.Format(Messages.MaiorQueLimite, 90), true); + } + if (string.IsNullOrWhiteSpace(this.Nome)) + { + keyValuePairs.AddValue<string, string>("Nome", Messages.Obrigatorio, true); + } + else if (this.Nome.Length > 60) + { + keyValuePairs.AddValue<string, string>("Nome", string.Format(Messages.MaiorQueLimite, 60), true); + } + if (string.IsNullOrWhiteSpace(base.Cep)) + { + keyValuePairs.AddValue<string, string>("Cep", Messages.Obrigatorio, true); + } + else if (!base.Cep.ValidacaoCep()) + { + keyValuePairs.AddValue<string, string>("Cep", Messages.Invalido, true); + } + if (string.IsNullOrWhiteSpace(base.Endereco)) + { + keyValuePairs.AddValue<string, string>("Endereco", Messages.Obrigatorio, true); + } + else if (base.Endereco.Length > 60) + { + keyValuePairs.AddValue<string, string>("Endereco", string.Format(Messages.MaiorQueLimite, 60), true); + } + if (string.IsNullOrWhiteSpace(base.Numero)) + { + keyValuePairs.AddValue<string, string>("Numero", Messages.Obrigatorio, true); + } + else if (base.Numero.Length > 10) + { + keyValuePairs.AddValue<string, string>("Numero", string.Format(Messages.MaiorQueLimite, 10), true); + } + if (!string.IsNullOrWhiteSpace(base.Complemento) && base.Complemento.Length > 100) + { + keyValuePairs.AddValue<string, string>("Complemento", string.Format(Messages.MaiorQueLimite, 100), true); + } + if (string.IsNullOrWhiteSpace(base.Bairro)) + { + keyValuePairs.AddValue<string, string>("Bairro", Messages.Obrigatorio, true); + } + else if (base.Bairro.Length > 150) + { + keyValuePairs.AddValue<string, string>("Bairro", string.Format(Messages.MaiorQueLimite, 150), true); + } + if (string.IsNullOrWhiteSpace(base.Cidade)) + { + keyValuePairs.AddValue<string, string>("Cidade", Messages.Obrigatorio, true); + } + else if (base.Cidade.Length > 30) + { + keyValuePairs.AddValue<string, string>("Cidade", string.Format(Messages.MaiorQueLimite, 30), true); + } + if (string.IsNullOrWhiteSpace(base.Estado)) + { + keyValuePairs.AddValue<string, string>("Estado", Messages.Obrigatorio, true); + } + else if (!base.Estado.ValidacaoEstado()) + { + keyValuePairs.AddValue<string, string>("Estado", Messages.Invalido, true); + } + if (string.IsNullOrWhiteSpace(this.Email)) + { + keyValuePairs.AddValue<string, string>("Email", Messages.Obrigatorio, true); + } + else if (!this.Email.ValidacaoEmail()) + { + keyValuePairs.AddValue<string, string>("Email", Messages.Invalido, true); + } + else if (this.Email.Length > 50) + { + keyValuePairs.AddValue<string, string>("Email", string.Format(Messages.MaiorQueLimite, 50), true); + } + if (string.IsNullOrWhiteSpace(this.EmailResponsavel)) + { + keyValuePairs.AddValue<string, string>("EmailResponsavel", Messages.Obrigatorio, true); + } + else if (!this.EmailResponsavel.ValidacaoEmail()) + { + keyValuePairs.AddValue<string, string>("EmailResponsavel", Messages.Invalido, true); + } + else if (this.EmailResponsavel.Length > 50) + { + keyValuePairs.AddValue<string, string>("EmailResponsavel", string.Format(Messages.MaiorQueLimite, 50), true); + } + if (!string.IsNullOrEmpty(this.Facebook) && !this.Facebook.Contains("http")) + { + this.Facebook = string.Concat("https://", this.Facebook.Trim()); + } + if (!string.IsNullOrEmpty(this.Instagram) && !this.Instagram.Contains("http")) + { + this.Instagram = string.Concat("https://", this.Instagram.Trim()); + } + if (!string.IsNullOrEmpty(this.Linkdin) && !this.Linkdin.Contains("http")) + { + this.Linkdin = string.Concat("https://", this.Linkdin.Trim()); + } + if (!string.IsNullOrEmpty(this.Twitter) && !this.Twitter.Contains("http")) + { + this.Twitter = string.Concat("https://", this.Twitter.Trim()); + } + if (!string.IsNullOrEmpty(this.Site) && !this.Site.Contains("http")) + { + this.Site = string.Concat("http://", this.Site.Trim()); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Common/Fipe.cs b/Codemerx/Gestor.Model/Model.Domain.Common/Fipe.cs new file mode 100644 index 0000000..3a3accc --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Common/Fipe.cs @@ -0,0 +1,138 @@ +using Gestor.Model.Helper; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Common +{ + public class Fipe + { + private string _codigo; + + private string _marca; + + private string _modelo; + + private int _anoMaximo; + + private int _anoMinimo; + + public int AnoMaximo + { + get + { + if (this.Detalhes == null || this.Detalhes.Count == 0) + { + return this._anoMaximo; + } + return ( + from d in this.Detalhes + orderby d.AnoModelo descending + select d).First<FipeDetalhe>().AnoModelo.ToInt(); + } + set + { + if (this.Detalhes == null || this.Detalhes.Count == 0) + { + this._anoMaximo = value; + } + } + } + + public int AnoMinimo + { + get + { + if (this.Detalhes == null || this.Detalhes.Count == 0) + { + return this._anoMinimo; + } + return ( + from d in this.Detalhes + orderby d.AnoModelo + select d).First<FipeDetalhe>().AnoModelo.ToInt(); + } + set + { + if (this.Detalhes == null || this.Detalhes.Count == 0) + { + this._anoMinimo = value; + } + } + } + + public string Codigo + { + get + { + string str = this._codigo; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._codigo = value; + } + } + + public List<FipeDetalhe> Detalhes + { + get; + set; + } + + public int? IdFabricante + { + get; + set; + } + + public string Marca + { + get + { + string str = this._marca; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._marca = value; + } + } + + public string Modelo + { + get + { + string str = this._modelo; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._modelo = value; + } + } + + public int TipoVeiculo + { + get; + set; + } + + public Fipe() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Common/FipeDetalhe.cs b/Codemerx/Gestor.Model/Model.Domain.Common/FipeDetalhe.cs new file mode 100644 index 0000000..c3a2803 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Common/FipeDetalhe.cs @@ -0,0 +1,24 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Common +{ + public class FipeDetalhe + { + public string AnoModelo + { + get; + set; + } + + public decimal Valor + { + get; + set; + } + + public FipeDetalhe() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Common/IndiceArquivoDigital.cs b/Codemerx/Gestor.Model/Model.Domain.Common/IndiceArquivoDigital.cs new file mode 100644 index 0000000..b50be29 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Common/IndiceArquivoDigital.cs @@ -0,0 +1,246 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Common +{ + public class IndiceArquivoDigital : DomainBase + { + private string _descricao; + + private string _extensao; + + public bool Assinado + { + get; + set; + } + + public bool Assinar + { + get; + set; + } + + public Guid? AzureGuid + { + get; + set; + } + + public string AzureStorage + { + get; + set; + } + + public string Bd + { + get; + set; + } + + public DateTime? DataAtualizacao + { + get; + set; + } + + public DateTime? DataCriacao + { + get; + set; + } + + [Log(true)] + [Name(true)] + public string Descricao + { + get + { + string str = this._descricao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._descricao = value; + } + } + + public bool EnviadoAssinatura + { + get; + set; + } + + public bool Excluido + { + get; + set; + } + + public string Extensao + { + get + { + string str = this._extensao; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._extensao = value; + } + } + + public long IdArquivoDigital + { + get; + set; + } + + public long IdCliente + { + get; + set; + } + + public long IdDocumento + { + get; + set; + } + + public long IdEmpresa + { + get; + set; + } + + public long IdEstipulante + { + get; + set; + } + + public long IdExtrato + { + get; + set; + } + + public long IdFornecedor + { + get; + set; + } + + public long IdItem + { + get; + set; + } + + public long IdLancamento + { + get; + set; + } + + public long IdNotaFiscal + { + get; + set; + } + + public long IdParcela + { + get; + set; + } + + public long IdProspeccao + { + get; + set; + } + + public long IdSeguradora + { + get; + set; + } + + public long IdSinistro + { + get; + set; + } + + public long IdSocio + { + get; + set; + } + + public long IdTarefa + { + get; + set; + } + + public long IdUsuario + { + get; + set; + } + + public long IdVendedor + { + get; + set; + } + + public bool NaoExcluir + { + get; + set; + } + + public bool Selecionado + { + get; + set; + } + + public string UrlAssinatura + { + get; + set; + } + + public long UsuarioAtualizacao + { + get; + set; + } + + public long UsuarioCriacao + { + get; + set; + } + + public IndiceArquivoDigital() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Common/PesquisaAvancada.cs b/Codemerx/Gestor.Model/Model.Domain.Common/PesquisaAvancada.cs new file mode 100644 index 0000000..452988b --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Common/PesquisaAvancada.cs @@ -0,0 +1,55 @@ +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Common +{ + public class PesquisaAvancada + { + public long IdCliente + { + get; + set; + } + + public long IdDocumento + { + get; + set; + } + + public long IdItem + { + get; + set; + } + + public long IdSinistro + { + get; + set; + } + + public string Nome + { + get; + set; + } + + public string Pesquisa + { + get; + set; + } + + public FiltroStatusDocumento Status + { + get; + set; + } + + public PesquisaAvancada() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Common/Profissao.cs b/Codemerx/Gestor.Model/Model.Domain.Common/Profissao.cs new file mode 100644 index 0000000..d4b6380 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Common/Profissao.cs @@ -0,0 +1,69 @@ +using Gestor.Model.Domain.Generic; +using System; + +namespace Gestor.Model.Domain.Common +{ + public class Profissao : DomainBase + { + private string _codigo; + + private string _nome; + + private string _aniversario; + + public string Aniversario + { + get + { + string str = this._aniversario; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._aniversario = value; + } + } + + public string Codigo + { + get + { + string str = this._codigo; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._codigo = value; + } + } + + public string Nome + { + get + { + string str = this._nome; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._nome = value; + } + } + + public Profissao() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Common/RegistroAcao.cs b/Codemerx/Gestor.Model/Model.Domain.Common/RegistroAcao.cs new file mode 100644 index 0000000..d89a8d4 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Common/RegistroAcao.cs @@ -0,0 +1,81 @@ +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Common +{ + public class RegistroAcao : DomainBase + { + public DateTime DataHora + { + get; + set; + } + + public string Descricao + { + get; + set; + } + + public long EntidadeId + { + get; + set; + } + + public string Ip + { + get; + set; + } + + public string NomeMaquina + { + get; + set; + } + + public string Observacao + { + get; + set; + } + + public Gestor.Model.Common.Relatorio? Relatorio + { + get; + set; + } + + public TipoTela? Tela + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Usuario Usuario + { + get; + set; + } + + public string UsuarioMaquina + { + get; + set; + } + + public string Versao + { + get; + set; + } + + public RegistroAcao() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Common/RegistroLog.cs b/Codemerx/Gestor.Model/Model.Domain.Common/RegistroLog.cs new file mode 100644 index 0000000..4fd1044 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Common/RegistroLog.cs @@ -0,0 +1,81 @@ +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Common +{ + public class RegistroLog : DomainBase + { + public TipoAcao Acao + { + get; + set; + } + + public DateTime DataHora + { + get; + set; + } + + public string Descricao + { + get; + set; + } + + public long EntidadeId + { + get; + set; + } + + public string Ip + { + get; + set; + } + + public bool ModeloNovo + { + get; + set; + } + + public string NomeMaquina + { + get; + set; + } + + public TipoTela Tela + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Usuario Usuario + { + get; + set; + } + + public string UsuarioMaquina + { + get; + set; + } + + public string Versao + { + get; + set; + } + + public RegistroLog() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Common/Socio.cs b/Codemerx/Gestor.Model/Model.Domain.Common/Socio.cs new file mode 100644 index 0000000..bf1da0c --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Common/Socio.cs @@ -0,0 +1,159 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Common +{ + public class Socio : EnderecoBase, IDomain + { + private string _nome; + + private string _email; + + private string _prefixo; + + private string _telefone; + + [Description("E-MAIL")] + [Log(true)] + public string Email + { + get + { + string str = this._email; + if (str == null) + { + return null; + } + return str.ToLower().Trim(); + } + set + { + this._email = value; + } + } + + public bool Excluido + { + get; + set; + } + + public long IdEmpresa + { + get; + set; + } + + [Log(true)] + [Name(true)] + public string Nome + { + get + { + string str = this._nome; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._nome = value; + } + } + + [Description("PREFIXO")] + [Log(true)] + public string Prefixo + { + get + { + string str = this._prefixo; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._prefixo = value; + } + } + + [Description("TELEFONE")] + [Log(true)] + public string Telefone + { + get + { + string str = this._telefone; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._telefone = value; + } + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Socio socio = this; + return new Func<List<KeyValuePair<string, string>>>(socio.Validate); + } + } + + public Socio() + { + } + + public List<TupleList> Log() + { + return new List<TupleList>() + { + new TupleList() + { + Tuples = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("NOME", (string.IsNullOrWhiteSpace(this.Nome) ? "" : this.Nome), ""), + new Tuple<string, string, string>("E-MAIL", (string.IsNullOrWhiteSpace(this.Email) ? "" : this.Email), ""), + new Tuple<string, string, string>("PREFIXO", (string.IsNullOrWhiteSpace(this.Prefixo) ? "" : this.Prefixo), ""), + new Tuple<string, string, string>("TELEFONE", (string.IsNullOrWhiteSpace(this.Telefone) ? "" : this.Telefone), ""), + new Tuple<string, string, string>("E-MAIL", (string.IsNullOrWhiteSpace(this.Email) ? "" : this.Email), "") + } + } + }; + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (string.IsNullOrWhiteSpace(this.Nome)) + { + keyValuePairs.AddValue<string, string>("Nome", Messages.Obrigatorio, true); + } + else if (this.Nome.Length > 60) + { + keyValuePairs.AddValue<string, string>("Nome", string.Format(Messages.MaiorQueLimite, 60), true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Common/TrocaCliente.cs b/Codemerx/Gestor.Model/Model.Domain.Common/TrocaCliente.cs new file mode 100644 index 0000000..00b03e1 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Common/TrocaCliente.cs @@ -0,0 +1,117 @@ +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; + +namespace Gestor.Model.Domain.Common +{ + public class TrocaCliente + { + private string _descricao; + + private long _idClienteTrocado; + + private string _nomeClienteTrocado; + + private long _idclienteNovo; + + private string _nomeClienteNovo; + + private Gestor.Model.Domain.Seguros.Documento _documento; + + public string Descricao + { + get + { + string str = this._descricao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._descricao = value; + } + } + + public Gestor.Model.Domain.Seguros.Documento Documento + { + get + { + return this._documento; + } + set + { + this._documento = value; + } + } + + public long IdClienteNovo + { + get + { + return this._idclienteNovo; + } + set + { + this._idclienteNovo = value; + } + } + + public long IdClienteTrocado + { + get + { + return this._idClienteTrocado; + } + set + { + this._idClienteTrocado = value; + } + } + + public string NomeClienteNovo + { + get + { + return this._nomeClienteNovo; + } + set + { + this._nomeClienteNovo = value; + } + } + + public string NomeClienteTrocado + { + get + { + return this._nomeClienteTrocado; + } + set + { + this._nomeClienteTrocado = value; + } + } + + public TrocaCliente() + { + } + + public List<TupleList> Log() + { + return new List<TupleList>() + { + new TupleList() + { + Tuples = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("DESCRICAO", (string.IsNullOrWhiteSpace(this.Descricao) ? "" : this.Descricao), "") + } + } + }; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Configuracoes/ConfiguracaoSistema.cs b/Codemerx/Gestor.Model/Model.Domain.Configuracoes/ConfiguracaoSistema.cs new file mode 100644 index 0000000..511bdfc --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Configuracoes/ConfiguracaoSistema.cs @@ -0,0 +1,20 @@ +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Configuracoes +{ + public class ConfiguracaoSistema : DomainBase + { + public Gestor.Model.Common.Configuracao Configuracao + { + get; + set; + } + + public ConfiguracaoSistema() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Ferramentas/Agenda.cs b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/Agenda.cs new file mode 100644 index 0000000..263f0bc --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/Agenda.cs @@ -0,0 +1,178 @@ +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Gestor.Model.Validation; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Ferramentas +{ + public class Agenda : DomainBase, IDomain + { + public string Bairro + { + get; + set; + } + + public string Cep + { + get; + set; + } + + public string Cidade + { + get; + set; + } + + public string Complemento + { + get; + set; + } + + public ObservableCollection<AgendaEmail> Emails + { + get; + set; + } + + public string Endereco + { + get; + set; + } + + public string Estado + { + get; + set; + } + + public string Nome + { + get; + set; + } + + public string Numero + { + get; + set; + } + + public string Observacao + { + get; + set; + } + + public ObservableCollection<AgendaTelefone> Telefones + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Agenda agenda = this; + return new Func<List<KeyValuePair<string, string>>>(agenda.Validate); + } + } + + public Agenda() + { + } + + public List<TupleList> Log() + { + string description; + List<TupleList> tupleLists = new List<TupleList>() + { + new TupleList() + { + Tuples = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("NOME", (string.IsNullOrWhiteSpace(this.Nome) ? "" : this.Nome), ""), + new Tuple<string, string, string>("CEP", (string.IsNullOrWhiteSpace(this.Cep) ? "" : this.Cep), ""), + new Tuple<string, string, string>("ENDEREÇO", (string.IsNullOrWhiteSpace(this.Endereco) ? "" : this.Endereco), ""), + new Tuple<string, string, string>("NÚMERO", (string.IsNullOrWhiteSpace(this.Numero) ? "" : this.Numero), ""), + new Tuple<string, string, string>("COMPLEMENTO", (string.IsNullOrWhiteSpace(this.Complemento) ? "" : this.Complemento), ""), + new Tuple<string, string, string>("BAIRRO", (string.IsNullOrWhiteSpace(this.Bairro) ? "" : this.Bairro), ""), + new Tuple<string, string, string>("CIDADE", (string.IsNullOrWhiteSpace(this.Cidade) ? "" : this.Cidade), ""), + new Tuple<string, string, string>("ESTADO", (string.IsNullOrWhiteSpace(this.Estado) ? "" : this.Estado), ""), + new Tuple<string, string, string>("OBSERVAÇÕES", (string.IsNullOrWhiteSpace(this.Observacao) ? "" : this.Observacao), "") + } + } + }; + ObservableCollection<Tuple<string, string, string>> observableCollection = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("TELEFONES$", "", "") + }; + foreach (AgendaTelefone telefone in this.Telefones) + { + observableCollection.Add(new Tuple<string, string, string>(string.Format(" TELEFONE {0}$", this.Telefones.IndexOf(telefone) + 1), "", "")); + ObservableCollection<Tuple<string, string, string>> observableCollection1 = observableCollection; + TipoTelefone? tipo = telefone.Tipo; + if (!tipo.HasValue) + { + description = ""; + } + else + { + tipo = telefone.Tipo; + if (tipo.HasValue) + { + description = tipo.GetValueOrDefault().GetDescription(); + } + else + { + description = null; + } + } + observableCollection1.Add(new Tuple<string, string, string>(" TIPO", description, "")); + observableCollection.Add(new Tuple<string, string, string>(" PREFIXO", (string.IsNullOrWhiteSpace(telefone.Prefixo) ? "" : telefone.Prefixo.ToUpper()), "")); + observableCollection.Add(new Tuple<string, string, string>(" NÚMERO", (string.IsNullOrWhiteSpace(telefone.Numero) ? "" : telefone.Numero), "")); + observableCollection.Add(new Tuple<string, string, string>(" DESCRIÇÃO", (string.IsNullOrWhiteSpace(telefone.Observacao) ? "" : telefone.Observacao), "")); + } + tupleLists.Add(new TupleList() + { + Tuples = observableCollection + }); + ObservableCollection<Tuple<string, string, string>> observableCollection2 = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("EMAILS$", "", "") + }; + foreach (AgendaEmail email in this.Emails) + { + observableCollection2.Add(new Tuple<string, string, string>(string.Format(" EMAIL {0}$", this.Emails.IndexOf(email) + 1), "", "")); + observableCollection2.Add(new Tuple<string, string, string>(" ENDEREÇO DE EMAIL", (string.IsNullOrWhiteSpace(email.Email) ? "" : email.Email), "")); + } + tupleLists.Add(new TupleList() + { + Tuples = observableCollection2 + }); + return tupleLists; + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (string.IsNullOrWhiteSpace(this.Nome)) + { + keyValuePairs.AddValue<string, string>("Nome", Messages.Obrigatorio, true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Ferramentas/AgendaEmail.cs b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/AgendaEmail.cs new file mode 100644 index 0000000..b3cfd4c --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/AgendaEmail.cs @@ -0,0 +1,57 @@ +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Ferramentas +{ + public class AgendaEmail : EmailBase, IDomain + { + public Gestor.Model.Domain.Ferramentas.Agenda Agenda + { + get; + set; + } + + public bool Selecionado + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + AgendaEmail agendaEmail = this; + return new Func<List<KeyValuePair<string, string>>>(agendaEmail.Validate); + } + } + + public AgendaEmail() + { + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (string.IsNullOrWhiteSpace(base.Email)) + { + keyValuePairs.AddValue<string, string>("Email", Messages.Obrigatorio, true); + } + else if (base.Email.Length > 80) + { + keyValuePairs.AddValue<string, string>("Email", string.Format(Messages.MaiorQueLimite, 80), true); + } + else if (!base.Email.ValidacaoEmail()) + { + keyValuePairs.AddValue<string, string>("Email", Messages.Invalido, true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Ferramentas/AgendaTelefone.cs b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/AgendaTelefone.cs new file mode 100644 index 0000000..49d2c6d --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/AgendaTelefone.cs @@ -0,0 +1,42 @@ +using Gestor.Model.Domain.Generic; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Ferramentas +{ + public class AgendaTelefone : TelefoneBase, IDomain + { + public Gestor.Model.Domain.Ferramentas.Agenda Agenda + { + get; + set; + } + + public string Observacao + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + AgendaTelefone agendaTelefone = this; + return new Func<List<KeyValuePair<string, string>>>(agendaTelefone.Validate); + } + } + + public AgendaTelefone() + { + } + + public List<KeyValuePair<string, string>> Validate() + { + return base.ValidateBase(true); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Ferramentas/CategoriaTarefa.cs b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/CategoriaTarefa.cs new file mode 100644 index 0000000..7fbc293 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/CategoriaTarefa.cs @@ -0,0 +1,19 @@ +using Gestor.Model.Domain.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Ferramentas +{ + public class CategoriaTarefa : DomainBase + { + public string Descricao + { + get; + set; + } + + public CategoriaTarefa() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Ferramentas/Credencial.cs b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/Credencial.cs new file mode 100644 index 0000000..a6e7464 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/Credencial.cs @@ -0,0 +1,278 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using System.Text.RegularExpressions; + +namespace Gestor.Model.Domain.Ferramentas +{ + public class Credencial : DomainBase, IDomain + { + private string _descricao; + + private string _assinatura; + + private string _header; + + private string _cabecalho; + + [Description("ASSINATURA")] + [Log(true)] + public string Assinatura + { + get + { + return this._assinatura; + } + set + { + this._assinatura = value ?? ""; + } + } + + public string Cabecalho + { + get + { + return this._cabecalho; + } + set + { + this._cabecalho = value ?? ""; + } + } + + [Description("DESCRIÇÃO")] + [Log(true)] + public string Descricao + { + get + { + string str = this._descricao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._descricao = value; + } + } + + [Description("DOMÍNIO")] + [Log(true)] + public string Dominio + { + get; + set; + } + + [Description("E-MAIL")] + [Log(true)] + public string Email + { + get; + set; + } + + public bool Excluido + { + get; + set; + } + + [Log(true)] + public string Header + { + get + { + return this._header; + } + set + { + this._header = value; + } + } + + public long IdEmpresa + { + get; + set; + } + + public long IdUsuario + { + get; + set; + } + + [Description("PORTA")] + [Log(true)] + public int? Porta + { + get; + set; + } + + public string Replyto + { + get; + set; + } + + [Description("SEGURO")] + [Log(true)] + public bool Seguro + { + get; + set; + } + + [Description("SENHA")] + [Log(true)] + public string Senha + { + get; + set; + } + + [Log(true)] + public TipoEmail Tipo + { + get; + set; + } + + [Description("USUÁRIO")] + [Log(true)] + public string Usuario + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Credencial credencial = this; + return new Func<List<KeyValuePair<string, string>>>(credencial.Validate); + } + } + + public Credencial() + { + } + + public List<TupleList> Log() + { + string str; + List<TupleList> tupleLists = new List<TupleList>(); + this.Assinatura = (new Regex("<title>.*<\\/title>")).Replace(this.Assinatura, "").Trim(); + this.Assinatura = (new Regex("(<[^>]*>)|(p\\s?{[^}]*})|(\\r)|(\\n)")).Replace(this.Assinatura, "").Trim(); + TupleList tupleList = new TupleList(); + ObservableCollection<Tuple<string, string, string>> observableCollection = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("DESCRIÇÃO", (string.IsNullOrWhiteSpace(this.Descricao) ? "" : this.Descricao), "") + }; + int? porta = this.Porta; + if (!porta.HasValue) + { + str = ""; + } + else + { + porta = this.Porta; + if (porta.HasValue) + { + str = porta.GetValueOrDefault().ToString(); + } + else + { + str = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("PORTA", str, "")); + observableCollection.Add(new Tuple<string, string, string>("DOMÍNIO", (string.IsNullOrWhiteSpace(this.Dominio) ? "" : this.Dominio), "")); + observableCollection.Add(new Tuple<string, string, string>("E-MAIL", (string.IsNullOrWhiteSpace(this.Email) ? "" : this.Email), "")); + observableCollection.Add(new Tuple<string, string, string>("LOGIN", (string.IsNullOrWhiteSpace(this.Usuario) ? "" : this.Usuario), "")); + observableCollection.Add(new Tuple<string, string, string>("CERTIFICADO DE SEGURANÇA", (this.Seguro ? "SIM" : "NÃO"), "")); + observableCollection.Add(new Tuple<string, string, string>("ASSINATURA", (string.IsNullOrWhiteSpace(this.Assinatura) ? "" : this.Assinatura), "")); + tupleList.Tuples = observableCollection; + tupleLists.Add(tupleList); + return tupleLists; + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (string.IsNullOrEmpty(this.Descricao)) + { + keyValuePairs.AddValue<string, string>("Descricao|DESCRIÇÃO", Messages.Obrigatorio, true); + } + else if (this.Descricao.Length > 50) + { + keyValuePairs.AddValue<string, string>("Descricao|DESCRIÇÃO", string.Format(Messages.MaiorQueLimite, 50), true); + } + if (this.Tipo == TipoEmail.Outros) + { + if (!this.Porta.HasValue) + { + keyValuePairs.AddValue<string, string>("Porta", Messages.Invalido, true); + } + if (string.IsNullOrWhiteSpace(this.Dominio)) + { + keyValuePairs.AddValue<string, string>("Dominio|DOMÍNIO", Messages.Obrigatorio, true); + } + else if (this.Dominio.Length > 80) + { + keyValuePairs.AddValue<string, string>("Dominio|DOMÍNIO", string.Format(Messages.MaiorQueLimite, 80), true); + } + if (string.IsNullOrEmpty(this.Usuario)) + { + keyValuePairs.AddValue<string, string>("Usuario|USUÁRIO", Messages.Obrigatorio, true); + } + else if (this.Usuario.Length > 50) + { + keyValuePairs.AddValue<string, string>("Usuario|USUÁRIO", string.Format(Messages.MaiorQueLimite, 50), true); + } + if (string.IsNullOrEmpty(this.Senha)) + { + keyValuePairs.AddValue<string, string>("Senha", Messages.Obrigatorio, true); + } + else if (this.Senha.Length > 50) + { + keyValuePairs.AddValue<string, string>("Senha", string.Format(Messages.MaiorQueLimite, 50), true); + } + } + if (string.IsNullOrWhiteSpace(this.Email)) + { + keyValuePairs.AddValue<string, string>("Email|E-MAIL", Messages.Obrigatorio, true); + } + else if (this.Email.Length > 80) + { + keyValuePairs.AddValue<string, string>("Email|E-MAIL", string.Format(Messages.MaiorQueLimite, 80), true); + } + else if (!this.Email.ValidacaoEmail()) + { + keyValuePairs.AddValue<string, string>("Email|E-MAIL", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.Replyto) && !this.Replyto.ValidacaoEmail()) + { + keyValuePairs.AddValue<string, string>("Replyto|RESPONDER PARA", Messages.Obrigatorio, true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Ferramentas/Destinatario.cs b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/Destinatario.cs new file mode 100644 index 0000000..c3fad19 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/Destinatario.cs @@ -0,0 +1,63 @@ +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Ferramentas +{ + public class Destinatario : DomainBase + { + public List<ArquivoDigital> Anexos + { + get; + set; + } + + public string Assunto + { + get; + set; + } + + public string Corpo + { + get; + set; + } + + public string Email + { + get; + set; + } + + public List<string> Encaminhar + { + get; + set; + } + + public List<string> EncaminharOculto + { + get; + set; + } + + public string Nome + { + get; + set; + } + + public string Sobrenome + { + get; + set; + } + + public Destinatario() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Ferramentas/Fase.cs b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/Fase.cs new file mode 100644 index 0000000..1694170 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/Fase.cs @@ -0,0 +1,44 @@ +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Ferramentas +{ + public class Fase : DomainBase + { + public string Descricao + { + get; + set; + } + + public DateTime? Expiracao + { + get; + set; + } + + public List<Tarefa> Tarefas + { + get; + set; + } + + public string Titulo + { + get; + set; + } + + public Gestor.Model.Domain.Ferramentas.Trilha Trilha + { + get; + set; + } + + public Fase() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Ferramentas/Imposto.cs b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/Imposto.cs new file mode 100644 index 0000000..7a65e49 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/Imposto.cs @@ -0,0 +1,177 @@ +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Ferramentas +{ + public class Imposto : DomainBase, IDomain + { + public bool Ativo + { + get; + set; + } + + public decimal Desconto + { + get; + set; + } + + public decimal Ir + { + get; + set; + } + + public decimal Iss + { + get; + set; + } + + public decimal Outros + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Ramo Ramo + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Seguradora Seguradora + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Imposto imposto = this; + return new Func<List<KeyValuePair<string, string>>>(imposto.Validate); + } + } + + public Imposto() + { + } + + public List<TupleList> Log() + { + object nome; + object nomeSocial; + List<TupleList> tupleLists = new List<TupleList>(); + TupleList tupleList = new TupleList(); + ObservableCollection<Tuple<string, string, string>> observableCollection = new ObservableCollection<Tuple<string, string, string>>(); + Gestor.Model.Domain.Seguros.Ramo ramo = this.Ramo; + if (ramo != null) + { + nome = ramo.Nome; + } + else + { + nome = null; + } + if (nome == null) + { + nome = ""; + } + observableCollection.Add(new Tuple<string, string, string>("RAMO", nome, "")); + Gestor.Model.Domain.Seguros.Seguradora seguradora = this.Seguradora; + if (seguradora != null) + { + nomeSocial = seguradora.NomeSocial; + } + else + { + nomeSocial = null; + } + if (nomeSocial == null) + { + Gestor.Model.Domain.Seguros.Seguradora seguradora1 = this.Seguradora; + if (seguradora1 != null) + { + nomeSocial = seguradora1.Nome; + } + else + { + nomeSocial = null; + } + if (nomeSocial == null) + { + nomeSocial = ""; + } + } + observableCollection.Add(new Tuple<string, string, string>("SEGURADORA", nomeSocial, "")); + decimal ir = this.Ir; + observableCollection.Add(new Tuple<string, string, string>("IR", ir.ToString("p"), "")); + ir = this.Iss; + observableCollection.Add(new Tuple<string, string, string>("ISS", ir.ToString("p"), "")); + ir = this.Outros; + observableCollection.Add(new Tuple<string, string, string>("OUTROS", ir.ToString("p"), "")); + ir = this.Desconto; + observableCollection.Add(new Tuple<string, string, string>("DESCONTO", ir.ToString("p"), "")); + observableCollection.Add(new Tuple<string, string, string>("ATIVO", (this.Ativo ? "SIM" : "NÃO"), "")); + tupleList.Tuples = observableCollection; + tupleLists.Add(tupleList); + return tupleLists; + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (this.Ir > decimal.One) + { + keyValuePairs.AddValue<string, string>("Ir|PORCENTAGEM IR", "O VALOR DE IR NÃO PODE SER MAIOR QUE 100%.", true); + } + if (this.Iss > decimal.One) + { + keyValuePairs.AddValue<string, string>("Iss|PORCENTAGEM ISS", "O VALOR DE ISS NÃO PODE SER MAIOR QUE 100%.", true); + } + if (this.Outros > decimal.One) + { + keyValuePairs.AddValue<string, string>("Outros|PORCENTAGEM OUTROS", "O VALOR DOS OUTROS DESCONTOS NÃO PODE SER MAIOR QUE 100%.", true); + } + if (this.Desconto > decimal.One) + { + keyValuePairs.AddValue<string, string>("Desconto|PORCENTAGEM DESCONTO", "O VALOR DE DESCONTO NÃO PODE SER MAIOR QUE 100%.", true); + } + if (this.Ir < decimal.Zero) + { + keyValuePairs.AddValue<string, string>("Ir|PORCENTAGEM IR", "O VALOR DE IR NÃO PODE SER MENOR QUE 0%.", true); + } + if (this.Iss < decimal.Zero) + { + keyValuePairs.AddValue<string, string>("Iss|PORCENTAGEM ISS", "O VALOR DE ISS NÃO PODE SER MENOR QUE 0%.", true); + } + if (this.Outros < decimal.Zero) + { + keyValuePairs.AddValue<string, string>("Outros|PORCENTAGEM OUTROS", "O VALOR DOS OUTROS DESCONTOS NÃO PODE SER MENOR QUE 0%.", true); + } + if (this.Desconto < decimal.Zero) + { + keyValuePairs.AddValue<string, string>("Desconto|PORCENTAGEM DESCONTO", "O VALOR DE DESCONTO NÃO PODE SER MENOR QUE 0%.", true); + } + if ((((this.Ir + this.Iss) + this.Outros) + this.Desconto) > decimal.One) + { + keyValuePairs.AddValue<string, string>("Ir|PORCENTAGEM TOTAL", "NÃO É POSSÍVEL DEDUZIR MAIS QUE 100% DO TOTAL RECEBIDO.", true); + } + if ((((this.Ir + this.Iss) + this.Outros) + this.Desconto) == decimal.Zero) + { + keyValuePairs.AddValue<string, string>("Ir|PORCENTAGEM TOTAL", "A SOMA DOS IMPOSTOS DEVEM SER MAIOR QUE 0 (ZERO).", true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Ferramentas/LogEmail.cs b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/LogEmail.cs new file mode 100644 index 0000000..a884b02 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/LogEmail.cs @@ -0,0 +1,157 @@ +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Validation; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.CompilerServices; +using System.Text.RegularExpressions; + +namespace Gestor.Model.Domain.Ferramentas +{ + public class LogEmail : DomainBase + { + public string Anexos + { + get; + set; + } + + public string Assunto + { + get; + set; + } + + public string Cco + { + get; + set; + } + + public string Corpo + { + get; + set; + } + + public Gestor.Model.Domain.Ferramentas.Credencial Credencial + { + get; + set; + } + + public DateTime Data + { + get; + set; + } + + public string Destinatarios + { + get; + set; + } + + public long EntityId + { + get; + set; + } + + public string Ip + { + get; + set; + } + + public string NomeMaquina + { + get; + set; + } + + public Gestor.Model.Common.Relatorio Relatorio + { + get; + set; + } + + public TipoTela Tela + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Usuario Usuario + { + get; + set; + } + + public string UsuarioMaquina + { + get; + set; + } + + public string Versao + { + get; + set; + } + + public LogEmail() + { + } + + public List<TupleList> CriarLogEmail() + { + string email; + string str; + this.Corpo = (new Regex("<title>.*<\\/title>")).Replace(this.Corpo, "").Trim(); + this.Corpo = (new Regex("(<[^>]*>)|(p\\s?{[^}]*})|(\\r)|(\\n)")).Replace(this.Corpo, "").Trim(); + List<TupleList> tupleLists = new List<TupleList>(); + TupleList tupleList = new TupleList(); + ObservableCollection<Tuple<string, string, string>> observableCollection = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("ASSUNTO", (string.IsNullOrWhiteSpace(this.Assunto) ? "" : this.Assunto), ""), + new Tuple<string, string, string>("CORPO", (string.IsNullOrWhiteSpace(this.Corpo) ? "" : this.Corpo), "") + }; + Gestor.Model.Domain.Ferramentas.Credencial credencial = this.Credencial; + if (credencial != null) + { + email = credencial.Email; + } + else + { + email = null; + } + if (string.IsNullOrWhiteSpace(email)) + { + str = ""; + } + else + { + Gestor.Model.Domain.Ferramentas.Credencial credencial1 = this.Credencial; + if (credencial1 != null) + { + str = credencial1.Email; + } + else + { + str = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("E-MAIL DE ENVIO", str, "")); + observableCollection.Add(new Tuple<string, string, string>("DESTINATÁRIOS", (string.IsNullOrWhiteSpace(this.Destinatarios) ? "" : this.Destinatarios), "")); + observableCollection.Add(new Tuple<string, string, string>("ANEXOS", (string.IsNullOrWhiteSpace(this.Anexos) ? "" : this.Anexos), "")); + observableCollection.Add(new Tuple<string, string, string>("CCO", (string.IsNullOrWhiteSpace(this.Cco) ? "" : this.Cco), "")); + observableCollection.Add(new Tuple<string, string, string>("RELATORIO", (string.IsNullOrWhiteSpace(this.Relatorio.GetDescription()) ? "" : this.Relatorio.GetDescription()), "")); + tupleList.Tuples = observableCollection; + tupleLists.Add(tupleList); + return tupleLists; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Ferramentas/LogEnvio.cs b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/LogEnvio.cs new file mode 100644 index 0000000..c01bfee --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/LogEnvio.cs @@ -0,0 +1,36 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Ferramentas +{ + public class LogEnvio + { + public Gestor.Model.Domain.Ferramentas.Credencial Credencial + { + get; + set; + } + + public Gestor.Model.Domain.Ferramentas.Destinatario Destinatario + { + get; + set; + } + + public bool Enviado + { + get; + set; + } + + public string Erro + { + get; + set; + } + + public LogEnvio() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Ferramentas/ManutencaoPagamentos.cs b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/ManutencaoPagamentos.cs new file mode 100644 index 0000000..5690621 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/ManutencaoPagamentos.cs @@ -0,0 +1,361 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Gestor.Model.Domain.Ferramentas +{ + public class ManutencaoPagamentos : INotifyPropertyChanged + { + private bool _isExpanded; + + private bool _selecionado; + + private string _nome; + + private string _empresa; + + private string _apolice; + + private string _endosso; + + private string _seguradora; + + private string _ramo; + + private string _produto; + + private SubTipo _tipo; + + private decimal _valorRepasse; + + private DateTime _pagamento; + + private DateTime _previsaoPagamento; + + private string _vendedor; + + private decimal _valor; + + private DateTime? _recebimento; + + private int _parcela; + + [Description("APÓLICE")] + public string Apolice + { + get + { + string str = this._apolice; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._apolice = value; + this.OnPropertyChanged("Apolice"); + } + } + + [Description("EMPRESA")] + public string Empresa + { + get + { + string str = this._empresa; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._empresa = value; + this.OnPropertyChanged("Empresa"); + } + } + + [Description("ENDOSSO")] + public string Endosso + { + get + { + string str = this._endosso; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._endosso = value; + this.OnPropertyChanged("Endosso"); + } + } + + [Tipo("INVALID")] + public long Id + { + get; + set; + } + + [Tipo("INVALID")] + public long IdDocumento + { + get; + set; + } + + [Tipo("INVALID")] + public long IdParcela + { + get; + set; + } + + [Tipo("INVALID")] + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + this.OnPropertyChanged("IsExpanded"); + } + } + + [Description("CLIENTE")] + public string Nome + { + get + { + string str = this._nome; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._nome = value; + this.OnPropertyChanged("Nome"); + } + } + + [Description("DATA DE PAGAMENTO")] + public DateTime Pagamento + { + get + { + return this._pagamento; + } + set + { + this._pagamento = value; + this.OnPropertyChanged("Pagamento"); + } + } + + [Description("PARCELA")] + public int Parcela + { + get + { + return this._parcela; + } + set + { + this._parcela = value; + this.OnPropertyChanged("Parcela"); + } + } + + [Description("PREVISÃO DE PAGAMENTO")] + public DateTime PrevisaoPagamento + { + get + { + return this._previsaoPagamento; + } + set + { + this._previsaoPagamento = value; + this.OnPropertyChanged("PrevisaoPagamento"); + } + } + + [Description("PRODUTO")] + public string Produto + { + get + { + string str = this._produto; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._produto = value; + this.OnPropertyChanged("Produto"); + } + } + + [Description("RAMO")] + public string Ramo + { + get + { + string str = this._ramo; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._ramo = value; + this.OnPropertyChanged("Ramo"); + } + } + + [Description("RECEBIMENTO")] + public DateTime? Recebimento + { + get + { + return this._recebimento; + } + set + { + this._recebimento = value; + this.OnPropertyChanged("Recebimento"); + } + } + + [Description("SEGURADORA")] + public string Seguradora + { + get + { + string str = this._seguradora; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._seguradora = value; + this.OnPropertyChanged("Seguradora"); + } + } + + [Tipo("INVALID")] + public bool Selecionado + { + get + { + return this._selecionado; + } + set + { + this._selecionado = value; + this.OnPropertyChanged("Selecionado"); + } + } + + [Description("TIPO DA PARCELA")] + public SubTipo Tipo + { + get + { + return this._tipo; + } + set + { + this._tipo = value; + this.OnPropertyChanged("Tipo"); + } + } + + [Description("VALOR DA PARCELA")] + public decimal Valor + { + get + { + return this._valor; + } + set + { + this._valor = value; + this.OnPropertyChanged("Valor"); + } + } + + [Description("VALOR DE REPASSE")] + public decimal ValorRepasse + { + get + { + return this._valorRepasse; + } + set + { + this._valorRepasse = value; + this.OnPropertyChanged("ValorRepasse"); + } + } + + [Description("VENDEDOR")] + public string Vendedor + { + get + { + string str = this._vendedor; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._vendedor = value; + this.OnPropertyChanged("Vendedor"); + } + } + + public ManutencaoPagamentos() + { + } + + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChangedEventHandler propertyChangedEventHandler = this.PropertyChanged; + if (propertyChangedEventHandler == null) + { + return; + } + propertyChangedEventHandler(this, new PropertyChangedEventArgs(propertyName)); + } + + public event PropertyChangedEventHandler PropertyChanged; + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Ferramentas/NotaFiscal.cs b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/NotaFiscal.cs new file mode 100644 index 0000000..40d9e92 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/NotaFiscal.cs @@ -0,0 +1,217 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Globalization; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Gestor.Model.Domain.Ferramentas +{ + public class NotaFiscal : DomainBase + { + private bool _selecionado; + + [Description("DATA")] + [Log(true)] + public DateTime? Data + { + get; + set; + } + + [Description("ESTIPULANTE")] + [Log(true)] + public Gestor.Model.Domain.Seguros.Estipulante Estipulante + { + get; + set; + } + + [Description("EXTRATO")] + [Log(true)] + public string Extrato + { + get; + set; + } + + [Log(true)] + public long? IdExtrato + { + get; + set; + } + + [Description("IR")] + [Log(true)] + public decimal Ir + { + get; + set; + } + + [Description("ISS")] + [Log(true)] + public decimal Iss + { + get; + set; + } + + [Description("OBS")] + [Log(true)] + public string Obs + { + get; + set; + } + + [Log(true)] + public Gestor.Model.Domain.Seguros.Seguradora Seguradora + { + get; + set; + } + + public bool Selecionado + { + get + { + return this._selecionado; + } + set + { + if (value == this._selecionado) + { + return; + } + this._selecionado = value; + this.OnPropertyChanged("Selecionado"); + } + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + return new Func<List<KeyValuePair<string, string>>>(this.Validate); + } + } + + [Description("VALOR BRUTO")] + [Log(true)] + public decimal ValorBruto + { + get; + set; + } + + [Description("VALOR LÍQUIDO")] + [Log(true)] + public decimal ValorLiquido + { + get; + set; + } + + public NotaFiscal() + { + } + + public List<TupleList> Log() + { + string nome; + string str; + string shortDateString; + List<TupleList> tupleLists = new List<TupleList>(); + TupleList tupleList = new TupleList(); + ObservableCollection<Tuple<string, string, string>> observableCollection = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("SEGURADORA", (string.IsNullOrWhiteSpace(this.Seguradora.Nome) ? "" : this.Seguradora.Nome), "") + }; + Gestor.Model.Domain.Seguros.Estipulante estipulante = this.Estipulante; + if (estipulante != null) + { + nome = estipulante.Nome; + } + else + { + nome = null; + } + if (string.IsNullOrWhiteSpace(nome)) + { + str = ""; + } + else + { + Gestor.Model.Domain.Seguros.Estipulante estipulante1 = this.Estipulante; + if (estipulante1 != null) + { + str = estipulante1.Nome; + } + else + { + str = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("ESTIPULANTE", str, "")); + decimal iss = this.Iss; + observableCollection.Add(new Tuple<string, string, string>("ISS", iss.ToString("C", new CultureInfo("pt-BR", false)), "")); + iss = this.ValorLiquido; + observableCollection.Add(new Tuple<string, string, string>("VALOR LÍQUIDO", iss.ToString("C", new CultureInfo("pt-BR", false)), "")); + iss = this.ValorBruto; + observableCollection.Add(new Tuple<string, string, string>("VALOR BRUTO", iss.ToString("C", new CultureInfo("pt-BR", false)), "")); + DateTime? data = this.Data; + if (!data.HasValue) + { + shortDateString = ""; + } + else + { + data = this.Data; + if (data.HasValue) + { + shortDateString = data.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("DATA", shortDateString, "")); + tupleList.Tuples = observableCollection; + tupleLists.Add(tupleList); + return tupleLists; + } + + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChangedEventHandler propertyChangedEventHandler = this.PropertyChanged; + if (propertyChangedEventHandler == null) + { + return; + } + propertyChangedEventHandler(this, new PropertyChangedEventArgs(propertyName)); + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (this.Seguradora == null || string.IsNullOrEmpty(this.Seguradora.Nome)) + { + keyValuePairs.AddValue<string, string>("Seguradora", Messages.Obrigatorio, true); + } + return keyValuePairs; + } + + public event PropertyChangedEventHandler PropertyChanged; + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Ferramentas/OrigemCliente.cs b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/OrigemCliente.cs new file mode 100644 index 0000000..dc47d63 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/OrigemCliente.cs @@ -0,0 +1,35 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Ferramentas +{ + public class OrigemCliente : DomainBase + { + public Gestor.Model.Domain.Seguros.Cliente Cliente + { + get; + set; + } + + [Log(true)] + [Name(true)] + public string Nome + { + get; + set; + } + + public long TipoOrigem + { + get; + set; + } + + public OrigemCliente() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Ferramentas/Recibo.cs b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/Recibo.cs new file mode 100644 index 0000000..c598a07 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/Recibo.cs @@ -0,0 +1,202 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Gestor.Model.Validation; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Globalization; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Ferramentas +{ + public class Recibo : DomainBase, IDomain + { + [Description("DATA DO RECIBO")] + [Log(true)] + public DateTime? DataRecibo + { + get; + set; + } + + [Description("DOCUMENTO PAGANTE")] + [Log(true)] + public string DocumentoPagante + { + get; + set; + } + + [Description("DOCUMENTO RECEBEDOR")] + [Log(true)] + public string DocumentoRecebedor + { + get; + set; + } + + [Log(true)] + public TipoPagamento? Pagamento + { + get; + set; + } + + [Log(true)] + public string Pagante + { + get; + set; + } + + [Log(true)] + public string Recebedor + { + get; + set; + } + + [Log(true)] + public string Referente + { + get; + set; + } + + [Log(true)] + public TipoRecibo? Tipo + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Recibo recibo = this; + return new Func<List<KeyValuePair<string, string>>>(recibo.Validate); + } + } + + [Log(true)] + public decimal Valor + { + get; + set; + } + + public Recibo() + { + } + + public List<TupleList> Log() + { + string description; + string shortDateString; + List<TupleList> tupleLists = new List<TupleList>(); + TupleList tupleList = new TupleList(); + ObservableCollection<Tuple<string, string, string>> observableCollection = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("PAGANTE", (string.IsNullOrWhiteSpace(this.Pagante) ? "" : this.Pagante), ""), + new Tuple<string, string, string>("DOCUMENTO PAGANTE", (string.IsNullOrWhiteSpace(this.DocumentoPagante) ? "" : this.DocumentoPagante), ""), + new Tuple<string, string, string>("RECEBEDOR", (string.IsNullOrWhiteSpace(this.Recebedor) ? "" : this.Recebedor), ""), + new Tuple<string, string, string>("DOCUMENTO", (string.IsNullOrWhiteSpace(this.DocumentoRecebedor) ? "" : this.DocumentoRecebedor), ""), + new Tuple<string, string, string>("TIPO DO RECIBO", this.Tipo.GetDescription(), "") + }; + TipoPagamento? pagamento = this.Pagamento; + if (!pagamento.HasValue) + { + description = ""; + } + else + { + pagamento = this.Pagamento; + if (pagamento.HasValue) + { + description = pagamento.GetValueOrDefault().GetDescription(); + } + else + { + description = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("PAGAMENTO", description, "")); + decimal valor = this.Valor; + observableCollection.Add(new Tuple<string, string, string>("VALOR", valor.ToString(new CultureInfo("pt-BR")), "")); + DateTime? dataRecibo = this.DataRecibo; + if (dataRecibo.HasValue) + { + shortDateString = dataRecibo.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString = null; + } + observableCollection.Add(new Tuple<string, string, string>("DATA DO RECIBO", shortDateString, "")); + observableCollection.Add(new Tuple<string, string, string>("PAGANTE", (string.IsNullOrWhiteSpace(this.Pagante) ? "" : this.Pagante), "")); + observableCollection.Add(new Tuple<string, string, string>("RECEBEDOR", (string.IsNullOrWhiteSpace(this.Recebedor) ? "" : this.Recebedor), "")); + observableCollection.Add(new Tuple<string, string, string>("REFERENTE", (string.IsNullOrWhiteSpace(this.Referente) ? "" : this.Referente), "")); + tupleList.Tuples = observableCollection; + tupleLists.Add(tupleList); + return tupleLists; + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (string.IsNullOrWhiteSpace(this.Referente)) + { + keyValuePairs.AddValue<string, string>("Referente|REFERENTE À(AO)", Messages.Obrigatorio, true); + } + if (this.DataRecibo.HasValue && (DateTime.Compare(this.DataRecibo.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.DataRecibo.Value, new DateTime(9999, 12, 31)) > 0)) + { + keyValuePairs.AddValue<string, string>("DataRecibo|DATA DO RECIBO", Messages.Obrigatorio, true); + } + if (!this.DataRecibo.HasValue) + { + keyValuePairs.AddValue<string, string>("DataRecibo|DATA DO RECIBO", Messages.Obrigatorio, true); + } + if (string.IsNullOrWhiteSpace(this.DocumentoPagante)) + { + keyValuePairs.AddValue<string, string>("DocumentoPagante|DOCUMENTO DO PAGANTE", Messages.Obrigatorio, true); + } + else if (!this.DocumentoPagante.ValidacaoDocumento()) + { + keyValuePairs.AddValue<string, string>("DocumentoPagante|DOCUMENTO DO PAGANTE", Messages.Invalido, true); + } + if (string.IsNullOrWhiteSpace(this.DocumentoRecebedor)) + { + keyValuePairs.AddValue<string, string>("DocumentoRecebedor|DOCUMENTO DO RECEBEDOR", Messages.Obrigatorio, true); + } + else if (!this.DocumentoRecebedor.ValidacaoDocumento()) + { + keyValuePairs.AddValue<string, string>("DocumentoRecebedor|DOCUMENTO DO RECEBEDOR", Messages.Invalido, true); + } + if (string.IsNullOrWhiteSpace(this.Recebedor)) + { + keyValuePairs.AddValue<string, string>("Recebedor", Messages.Obrigatorio, true); + } + if (string.IsNullOrWhiteSpace(this.Pagante)) + { + keyValuePairs.AddValue<string, string>("Pagante", Messages.Obrigatorio, true); + } + if (!this.Pagamento.HasValue) + { + keyValuePairs.AddValue<string, string>("Pagamento|FORMA DE PAGAMENTO", Messages.Obrigatorio, true); + } + if (!string.IsNullOrWhiteSpace(this.Referente) && this.Referente.Length >= 255) + { + keyValuePairs.AddValue<string, string>("Referente|REFERENTE À(AO)", string.Format(Messages.MaiorQueLimite, 255), true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Ferramentas/ResponsavelTarefa.cs b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/ResponsavelTarefa.cs new file mode 100644 index 0000000..1418879 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/ResponsavelTarefa.cs @@ -0,0 +1,54 @@ +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Ferramentas +{ + public class ResponsavelTarefa : DomainBase, IDomain + { + public long IdTarefa + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Usuario Usuario + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + ResponsavelTarefa responsavelTarefa = this; + return new Func<List<KeyValuePair<string, string>>>(responsavelTarefa.Validate); + } + } + + public ResponsavelTarefa() + { + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (this.Usuario == null || this.Usuario.Id == 0) + { + keyValuePairs.AddValue<string, string>("Usuario", Messages.Obrigatorio, true); + } + if (this.IdTarefa == 0) + { + keyValuePairs.AddValue<string, string>("IdTarefa", Messages.Obrigatorio, true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Ferramentas/StatusDeProspeccao.cs b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/StatusDeProspeccao.cs new file mode 100644 index 0000000..6c258c7 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/StatusDeProspeccao.cs @@ -0,0 +1,103 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Ferramentas +{ + public class StatusDeProspeccao : DomainBase + { + private string _nome; + + [Log(true)] + public bool Ativo + { + get; + set; + } + + [Description("DESCRIÇÃO")] + [Log(true)] + public string Descricao + { + get; + set; + } + + public bool Excluido + { + get; + set; + } + + [Log(true)] + [Name(true)] + public string Nome + { + get + { + string str = this._nome; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._nome = value; + } + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + return new Func<List<KeyValuePair<string, string>>>(this.Validate); + } + } + + public StatusDeProspeccao() + { + } + + public List<TupleList> Log() + { + return new List<TupleList>() + { + new TupleList() + { + Tuples = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("NOME", (string.IsNullOrWhiteSpace(this.Nome) ? "" : this.Nome), ""), + new Tuple<string, string, string>("DESCRIÇÃO", (string.IsNullOrWhiteSpace(this.Descricao) ? "" : this.Descricao), ""), + new Tuple<string, string, string>("ATIVO", (this.Ativo ? "SIM" : "NÃO"), ""), + new Tuple<string, string, string>("EXCLUÍDO", (this.Excluido ? "SIM" : "NÃO"), "") + } + } + }; + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (string.IsNullOrWhiteSpace(this.Nome)) + { + keyValuePairs.AddValue<string, string>("Nome", Messages.Obrigatorio, true); + } + else if (this.Nome.Length > 60) + { + keyValuePairs.AddValue<string, string>("Nome", string.Format(Messages.MaiorQueLimite, 60), true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Ferramentas/Tarefa.cs b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/Tarefa.cs new file mode 100644 index 0000000..165b244 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/Tarefa.cs @@ -0,0 +1,264 @@ +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Gestor.Model.Validation; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.CompilerServices; +using System.Text.RegularExpressions; + +namespace Gestor.Model.Domain.Ferramentas +{ + public class Tarefa : DomainBase, IDomain + { + public bool Aberto + { + get; + set; + } + + public DateTime Agendamento + { + get; + set; + } + + public bool AgendamentoRetroativo + { + get; + set; + } + + public string Anotacoes + { + get; + set; + } + + public string AnotacoesInternas + { + get; + set; + } + + public CategoriaTarefa Categoria + { + get; + set; + } + + public string Cliente + { + get; + set; + } + + public DateTime? Conclusao + { + get; + set; + } + + public string Descricao + { + get; + set; + } + + public string DescricaoInterna + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Documento Documento + { + get; + set; + } + + public TipoTarefa Entidade + { + get; + set; + } + + public Gestor.Model.Domain.Ferramentas.Fase Fase + { + get; + set; + } + + public bool HabilitarPublica + { + get; + set; + } + + public long IdCliente + { + get; + set; + } + + public long IdEntidade + { + get; + set; + } + + public bool Publica + { + get; + set; + } + + public string Referencia + { + get; + set; + } + + public List<ResponsavelTarefa> Responsaveis + { + get; + set; + } + + public bool? Restrito + { + get; + set; + } + + public StatusTarefa Status + { + get; + set; + } + + public Gestor.Model.Domain.Ferramentas.TipoDeTarefa TipoDeTarefa + { + get; + set; + } + + public string Titulo + { + get; + set; + } + + public Gestor.Model.Domain.Ferramentas.Trilha Trilha + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Usuario Usuario + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Usuario UsuarioCadastro + { + get; + set; + } + + public List<Gestor.Model.Domain.Seguros.Usuario> UsuariosVinculados + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Tarefa tarefa = this; + return new Func<List<KeyValuePair<string, string>>>(tarefa.Validate); + } + } + + public Tarefa() + { + } + + public List<TupleList> Log() + { + string nome; + this.Descricao = (new Regex("<title>.*<\\/title>")).Replace(this.Descricao, "").Trim(); + this.Descricao = (new Regex("(<[^>]*>)|(p\\s?{[^}]*})|(\\r)|(\\n)")).Replace(this.Descricao, "").Trim(); + List<TupleList> tupleLists = new List<TupleList>(); + TupleList tupleList = new TupleList(); + ObservableCollection<Tuple<string, string, string>> observableCollection = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("TÍTULO", (string.IsNullOrWhiteSpace(this.Titulo) ? "" : this.Titulo), "") + }; + DateTime agendamento = this.Agendamento; + observableCollection.Add(new Tuple<string, string, string>("AGENDAMENTO", agendamento.ToShortDateString(), "")); + agendamento = this.Agendamento; + observableCollection.Add(new Tuple<string, string, string>("HORA", agendamento.ToShortTimeString(), "")); + observableCollection.Add(new Tuple<string, string, string>("RESPONSÁVEL", (string.IsNullOrWhiteSpace(this.Usuario.Nome) ? "" : this.Usuario.Nome), "")); + observableCollection.Add(new Tuple<string, string, string>("STATUS", this.Status.GetDescription(), "")); + Gestor.Model.Domain.Ferramentas.TipoDeTarefa tipoDeTarefa = this.TipoDeTarefa; + if (tipoDeTarefa != null) + { + nome = tipoDeTarefa.Nome; + } + else + { + nome = null; + } + observableCollection.Add(new Tuple<string, string, string>("TIPO DE TAREFA", nome, "")); + observableCollection.Add(new Tuple<string, string, string>("ANOTAÇÕES", (string.IsNullOrWhiteSpace(this.Descricao) ? "" : this.Descricao), "")); + tupleList.Tuples = observableCollection; + tupleLists.Add(tupleList); + return tupleLists; + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (this.Entidade != TipoTarefa.Notas) + { + if (this.IdEntidade == 0 && this.Trilha == null) + { + keyValuePairs.AddValue<string, string>("IdEntidade", Messages.Obrigatorio, true); + } + if (!this.AgendamentoRetroativo && this.Status != StatusTarefa.Realizado && this.Agendamento < Funcoes.GetNetworkTime().AddMinutes(-15) && this.Trilha == null) + { + keyValuePairs.AddValue<string, string>("Agendamento", Messages.Invalido, true); + } + } + if (this.Usuario == null) + { + keyValuePairs.AddValue<string, string>("Usuario|RESPONSÁVEL", Messages.Obrigatorio, true); + } + if (string.IsNullOrWhiteSpace(this.Titulo)) + { + keyValuePairs.AddValue<string, string>("Titulo|TÍTULO", Messages.Obrigatorio, true); + } + if (DateTime.Compare(this.Agendamento, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.Agendamento, new DateTime(9999, 12, 31)) > 0) + { + keyValuePairs.AddValue<string, string>("Agendamento", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + if (this.Conclusao.HasValue && (DateTime.Compare(this.Conclusao.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.Conclusao.Value, new DateTime(9999, 12, 31)) > 0)) + { + keyValuePairs.AddValue<string, string>("Conclusao|CONCLUSÃO", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + if (this.Status == StatusTarefa.Realizado && !this.Conclusao.HasValue) + { + keyValuePairs.AddValue<string, string>("Conclusao|CONCLUSÃO", Messages.Obrigatorio, true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Ferramentas/TipoDeTarefa.cs b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/TipoDeTarefa.cs new file mode 100644 index 0000000..16a0d2a --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/TipoDeTarefa.cs @@ -0,0 +1,103 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Ferramentas +{ + public class TipoDeTarefa : DomainBase + { + private string _nome; + + [Log(true)] + public bool Ativo + { + get; + set; + } + + [Description("DESCRIÇÃO")] + [Log(true)] + public string Descricao + { + get; + set; + } + + public bool Excluido + { + get; + set; + } + + [Log(true)] + [Name(true)] + public string Nome + { + get + { + string str = this._nome; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._nome = value; + } + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + return new Func<List<KeyValuePair<string, string>>>(this.Validate); + } + } + + public TipoDeTarefa() + { + } + + public List<TupleList> Log() + { + return new List<TupleList>() + { + new TupleList() + { + Tuples = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("NOME", (string.IsNullOrWhiteSpace(this.Nome) ? "" : this.Nome), ""), + new Tuple<string, string, string>("DESCRIÇÃO", (string.IsNullOrWhiteSpace(this.Descricao) ? "" : this.Descricao), ""), + new Tuple<string, string, string>("ATIVO", (this.Ativo ? "SIM" : "NÃO"), ""), + new Tuple<string, string, string>("EXCLUÍDO", (this.Excluido ? "SIM" : "NÃO"), "") + } + } + }; + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (string.IsNullOrWhiteSpace(this.Nome)) + { + keyValuePairs.AddValue<string, string>("Nome", Messages.Obrigatorio, true); + } + else if (this.Nome.Length > 60) + { + keyValuePairs.AddValue<string, string>("Nome", string.Format(Messages.MaiorQueLimite, 60), true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Ferramentas/Trilha.cs b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/Trilha.cs new file mode 100644 index 0000000..cf4e075 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Ferramentas/Trilha.cs @@ -0,0 +1,122 @@ +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Gestor.Model.Validation; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Ferramentas +{ + public class Trilha : DomainBase, IDomain + { + public bool Ativo + { + get; + set; + } + + public string Descricao + { + get; + set; + } + + public List<Fase> Fases + { + get; + set; + } + + public TipoTrilha Tipo + { + get; + set; + } + + public string Titulo + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Trilha trilha = this; + return new Func<List<KeyValuePair<string, string>>>(trilha.Validate); + } + } + + public Trilha() + { + } + + public List<TupleList> Log() + { + List<TupleList> tupleLists = new List<TupleList>() + { + new TupleList() + { + Tuples = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("TÍTULO DA TRILHA", (string.IsNullOrWhiteSpace(this.Titulo) ? "" : this.Titulo), ""), + new Tuple<string, string, string>("DESCRIÇÃO DA TRILHA", (string.IsNullOrWhiteSpace(this.Descricao) ? "" : this.Descricao), ""), + new Tuple<string, string, string>("ATIVO", (this.Ativo ? "SIM" : "NÃO"), "") + } + } + }; + ObservableCollection<Tuple<string, string, string>> observableCollection = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("FASES$", "", "") + }; + if (this.Fases != null) + { + foreach (Fase fase in this.Fases) + { + observableCollection.Add(new Tuple<string, string, string>(string.Format(" FASE {0}$", this.Fases.IndexOf(fase) + 1), "", "")); + observableCollection.Add(new Tuple<string, string, string>(" TÍTULO DA FASE", (string.IsNullOrWhiteSpace(fase.Titulo) ? "" : fase.Titulo), "")); + observableCollection.Add(new Tuple<string, string, string>(" DESCRIÇÃO DA FASE", (string.IsNullOrWhiteSpace(fase.Descricao) ? "" : fase.Descricao), "")); + foreach (Tarefa tarefa in fase.Tarefas) + { + observableCollection.Add(new Tuple<string, string, string>(string.Format(" TAREFA {0}$", fase.Tarefas.IndexOf(tarefa) + 1), "", "")); + observableCollection.Add(new Tuple<string, string, string>(" TÍTULO DA TAREFA", (string.IsNullOrWhiteSpace(tarefa.Titulo) ? "" : tarefa.Titulo), "")); + DateTime agendamento = tarefa.Agendamento; + DateTime dateTime = tarefa.Agendamento; + observableCollection.Add(new Tuple<string, string, string>(" AGENDAMENTO DA TAREFA", dateTime.ToShortDateString(), "")); + DateTime agendamento1 = tarefa.Agendamento; + dateTime = tarefa.Agendamento; + observableCollection.Add(new Tuple<string, string, string>(" HORA DA TAREFA", dateTime.ToShortTimeString(), "")); + observableCollection.Add(new Tuple<string, string, string>(" ANOTAÇÕES DA TAREFA", (string.IsNullOrWhiteSpace(tarefa.Anotacoes) ? "" : tarefa.Anotacoes), "")); + observableCollection.Add(new Tuple<string, string, string>(" STATUS DA TAREFA", tarefa.Status.GetDescription(), "")); + } + } + tupleLists.Add(new TupleList() + { + Tuples = observableCollection + }); + } + return tupleLists; + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (string.IsNullOrWhiteSpace(this.Titulo)) + { + keyValuePairs.AddValue<string, string>("Titulo", Messages.Obrigatorio, true); + } + if (this.Fases == null || this.Fases.Count == 0) + { + keyValuePairs.AddValue<string, string>("Fases", Messages.Obrigatorio, true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Financeiro/BancosContas.cs b/Codemerx/Gestor.Model/Model.Domain.Financeiro/BancosContas.cs new file mode 100644 index 0000000..06eade3 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Financeiro/BancosContas.cs @@ -0,0 +1,195 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Financeiro +{ + public class BancosContas : DomainBase, IDomain + { + private string _descricao; + + private string _agencia; + + private string _conta; + + private string _observacao; + + [Description("AGÊNCIA")] + [Log(true)] + public string Agencia + { + get + { + string str = this._agencia; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._agencia = value; + } + } + + [Log(true)] + public bool Ativo + { + get; + set; + } + + [Log(true)] + public Gestor.Model.Domain.Common.Banco Banco + { + get; + set; + } + + [Log(true)] + public string Conta + { + get + { + string str = this._conta; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._conta = value; + } + } + + [Description("DESCRIÇÃO")] + [Log(true)] + [Name(true)] + public string Descricao + { + get + { + string str = this._descricao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._descricao = value; + } + } + + public long IdEmpresa { get; set; } = (long)1; + + [Description("OBSERVAÇÃO")] + [Log(true)] + public string Observacao + { + get + { + string str = this._observacao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._observacao = value; + } + } + + public bool Selecionado + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + BancosContas bancosConta = this; + return new Func<List<KeyValuePair<string, string>>>(bancosConta.Validate); + } + } + + public BancosContas() + { + } + + public List<TupleList> Log() + { + string nome; + List<TupleList> tupleLists = new List<TupleList>(); + TupleList tupleList = new TupleList(); + ObservableCollection<Tuple<string, string, string>> observableCollection = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("DESCRIÇÃO", (string.IsNullOrWhiteSpace(this.Descricao) ? "" : this.Descricao), ""), + new Tuple<string, string, string>("AGÊNCIA", (string.IsNullOrWhiteSpace(this.Agencia) ? "" : this.Agencia), "") + }; + if (this.Banco == null) + { + nome = ""; + } + else + { + Gestor.Model.Domain.Common.Banco banco = this.Banco; + if (banco != null) + { + nome = banco.Nome; + } + else + { + nome = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("BANCO", nome, "")); + observableCollection.Add(new Tuple<string, string, string>("CONTA CORRENTE/POUPANÇA", (string.IsNullOrWhiteSpace(this.Conta) ? "" : this.Conta), "")); + observableCollection.Add(new Tuple<string, string, string>("ATIVO", (this.Ativo ? "SIM" : "NÃO"), "")); + observableCollection.Add(new Tuple<string, string, string>("OBSERVAÇÕES", (string.IsNullOrWhiteSpace(this.Observacao) ? "" : this.Observacao), "")); + tupleList.Tuples = observableCollection; + tupleLists.Add(tupleList); + return tupleLists; + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = new List<KeyValuePair<string, string>>(); + if (string.IsNullOrWhiteSpace(this.Descricao)) + { + keyValuePairs.AddValue<string, string>("Descricao|DESCRIÇÃO", Messages.Obrigatorio, true); + } + if (this.Banco == null) + { + keyValuePairs.AddValue<string, string>("Banco", Messages.Obrigatorio, true); + } + if (string.IsNullOrWhiteSpace(this.Agencia)) + { + keyValuePairs.AddValue<string, string>("Agencia|AGÊNCIA", Messages.Obrigatorio, true); + } + if (string.IsNullOrWhiteSpace(this.Conta)) + { + keyValuePairs.AddValue<string, string>("Conta", Messages.Obrigatorio, true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Financeiro/Centro.cs b/Codemerx/Gestor.Model/Model.Domain.Financeiro/Centro.cs new file mode 100644 index 0000000..0236082 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Financeiro/Centro.cs @@ -0,0 +1,93 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Financeiro +{ + public class Centro : DomainBase, IDomain + { + private string _descricao; + + [Log(true)] + public bool Ativo + { + get; + set; + } + + [Description("DESCRIÇÃO")] + [Log(true)] + [Name(true)] + public string Descricao + { + get + { + string str = this._descricao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._descricao = value; + } + } + + public long IdEmpresa { get; set; } = (long)1; + + public bool Selecionado + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Centro centro = this; + return new Func<List<KeyValuePair<string, string>>>(centro.Validate); + } + } + + public Centro() + { + } + + public List<TupleList> Log() + { + return new List<TupleList>() + { + new TupleList() + { + Tuples = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("NOME", (string.IsNullOrWhiteSpace(this.Descricao) ? "" : this.Descricao), ""), + new Tuple<string, string, string>("ATIVO", (this.Ativo ? "SIM" : "NÃO"), "") + } + } + }; + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (string.IsNullOrWhiteSpace(this.Descricao)) + { + keyValuePairs.AddValue<string, string>("Descricao", Messages.Obrigatorio, true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Financeiro/ControleFinanceiro.cs b/Codemerx/Gestor.Model/Model.Domain.Financeiro/ControleFinanceiro.cs new file mode 100644 index 0000000..ad425c0 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Financeiro/ControleFinanceiro.cs @@ -0,0 +1,143 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Financeiro +{ + public class ControleFinanceiro : DomainBase, IDomain + { + private string _historico; + + [Description("CENTRO DE CUSTO")] + [Log(true)] + [Name(true)] + public Gestor.Model.Domain.Financeiro.Centro Centro + { + get; + set; + } + + [Description("FORNECEDOR")] + [Log(true)] + [Name(true)] + public Gestor.Model.Domain.Financeiro.Fornecedor Fornecedor + { + get; + set; + } + + public string Historico + { + get + { + string str = this._historico; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._historico = value; + } + } + + [Description("QUANTIDADE DE PARCELAS")] + [Log(true)] + public int Parcelas + { + get; + set; + } + + [Description("PLANO DE CONTAS")] + [Log(true)] + [Name(true)] + public Planos Plano + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + ControleFinanceiro controleFinanceiro = this; + return new Func<List<KeyValuePair<string, string>>>(controleFinanceiro.Validate); + } + } + + public ControleFinanceiro() + { + } + + public List<KeyValuePair<string, string>> Validate() + { + bool id; + bool flag; + bool id1; + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (this.Fornecedor == null) + { + keyValuePairs.AddValue<string, string>("Fornecedor", Messages.Obrigatorio, true); + } + Gestor.Model.Domain.Financeiro.Fornecedor fornecedor = this.Fornecedor; + if (fornecedor != null) + { + id = fornecedor.Id == (long)0; + } + else + { + id = false; + } + if (id) + { + keyValuePairs.AddValue<string, string>("Fornecedor|FORNECEDOR", string.Concat(Messages.Obrigatorio, "\nPROVAVELMENTE NÃO HÁ NENHUM FORNECEDOR INCLUÍDO\nACESSE A TELA DE CADASTRO DE FORNECEDORES PARA INCLUIR"), true); + } + if (this.Plano == null) + { + keyValuePairs.AddValue<string, string>("Plano|PLANO DE CONTAS", string.Concat(Messages.Obrigatorio, "\nPROVAVELMENTE NÃO HÁ NENHUM PLANO DE CONTAS INCLUÍDO\nACESSE A TELA PLANO DE CONTAS PARA INCLUIR"), true); + } + Planos plano = this.Plano; + if (plano != null) + { + flag = plano.Id == (long)0; + } + else + { + flag = false; + } + if (flag) + { + keyValuePairs.AddValue<string, string>("Plano|PLANO DE CONTAS", string.Concat(Messages.Obrigatorio, "\nPROVAVELMENTE NÃO HÁ NENHUM PLANO DE CONTAS INCLUÍDO\nACESSE A TELA PLANO DE CONTAS PARA INCLUIR"), true); + } + if (this.Centro == null) + { + keyValuePairs.AddValue<string, string>("Centro|CENTRO DE CUSTOS", string.Concat(Messages.Obrigatorio, "\nPROVAVELMENTE NÃO HÁ NENHUM CENTRO DE CUSTOS INCLUÍDO\nACESSE A TELA CENTRO DE CUSTOS PARA INCLUIR"), true); + } + Gestor.Model.Domain.Financeiro.Centro centro = this.Centro; + if (centro != null) + { + id1 = centro.Id == (long)0; + } + else + { + id1 = false; + } + if (id1) + { + keyValuePairs.AddValue<string, string>("Centro|CENTRO DE CUSTOS", string.Concat(Messages.Obrigatorio, "\nPROVAVELMENTE NÃO HÁ NENHUM CENTRO DE CUSTOS INCLUÍDO\nACESSE A TELA CENTRO DE CUSTOS PARA INCLUIR"), true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Financeiro/ExtratoConta.cs b/Codemerx/Gestor.Model/Model.Domain.Financeiro/ExtratoConta.cs new file mode 100644 index 0000000..7bfc742 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Financeiro/ExtratoConta.cs @@ -0,0 +1,97 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Financeiro +{ + public class ExtratoConta + { + private string _fornecedor; + + private string _historico; + + [Description("DATA BAIXA")] + [Tipo("DATA?")] + public DateTime? Baixa + { + get; + set; + } + + public bool Bold + { + get; + set; + } + + [Description("FORNECEDOR")] + public string Fornecedor + { + get + { + string str = this._fornecedor; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._fornecedor = value; + } + } + + [Description("HISTÓRICO")] + public string Historico + { + get + { + string str = this._historico; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._historico = value; + } + } + + public long IdLancamento + { + get; + set; + } + + public Gestor.Model.Common.Sinal Sinal + { + get; + set; + } + + [Description("TIPO PAGAMENTO")] + [Tipo("ENUM")] + public Gestor.Model.Common.TipoPagamento? TipoPagamento + { + get; + set; + } + + [Description("VALOR")] + [Tipo("VALOR?")] + public decimal? Valor + { + get; + set; + } + + public ExtratoConta() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Financeiro/FiltroPersonalizado.cs b/Codemerx/Gestor.Model/Model.Domain.Financeiro/FiltroPersonalizado.cs new file mode 100644 index 0000000..897bab4 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Financeiro/FiltroPersonalizado.cs @@ -0,0 +1,54 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Financeiro +{ + public class FiltroPersonalizado + { + private string _descricao; + + [Description("DESCRIÇÃO DO FILTRO")] + public string Descricao + { + get + { + return this._descricao; + } + set + { + this._descricao = value; + if (!string.IsNullOrWhiteSpace(value)) + { + this.Icone = value.Substring(0, 1); + } + } + } + + public string Icone + { + get; + set; + } + + public long Id + { + get; + set; + } + + [Description("TIPO DO FILTRO")] + [Tipo("ENUM")] + public TipoFiltroFinanceiro Tipo + { + get; + set; + } + + public FiltroPersonalizado() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Financeiro/Fornecedor.cs b/Codemerx/Gestor.Model/Model.Domain.Financeiro/Fornecedor.cs new file mode 100644 index 0000000..7bc6e4b --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Financeiro/Fornecedor.cs @@ -0,0 +1,430 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Gestor.Model.Validation; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Financeiro +{ + public class Fornecedor : EnderecoBase, IDomain + { + private string _nome; + + private string _documento; + + private string _email; + + private string _observacao; + + [Description("ATIVO")] + [Log(true)] + public bool Ativo + { + get; + set; + } + + [Log(true)] + public string Documento + { + get + { + string str = this._documento; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._documento = value; + } + } + + [Description("E-MAIL")] + [Log(true)] + public string Email + { + get + { + string str = this._email; + if (str != null) + { + return str.ToLower(); + } + return null; + } + set + { + this._email = value; + } + } + + public new long Id + { + get; + set; + } + + public long? IdCentro + { + get; + set; + } + + public long? IdConta + { + get; + set; + } + + public long IdEmpresa + { + get; + set; + } + + public long? IdPlano + { + get; + set; + } + + [Log(true)] + [Name(true)] + public string Nome + { + get + { + string str = this._nome; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + object upper; + this._nome = value; + if (value != null) + { + upper = value.ToUpper(); + } + else + { + upper = null; + } + this.NomeSocial = string.Format("{0} - {1}", upper, this.Id); + } + } + + [Description("NOME SOCIAL")] + [Log(true)] + public string NomeSocial + { + get; + set; + } + + [Description("OBSERVAÇÃO")] + [Log(true)] + public string Observacao + { + get + { + string str = this._observacao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._observacao = value; + } + } + + [Description("PREFIXO 1")] + [Log(true)] + public string Prefixo1 + { + get; + set; + } + + [Description("PREFIXO 2")] + [Log(true)] + public string Prefixo2 + { + get; + set; + } + + [Description("TELEFONE 1")] + [Log(true)] + public string Telefone1 + { + get; + set; + } + + [Description("TELEFONE 2")] + [Log(true)] + public string Telefone2 + { + get; + set; + } + + public Gestor.Model.Common.TipoPagamento? TipoPagamento + { + get; + set; + } + + [Description("TIPO TELEFONE")] + [Log(true)] + public TipoTelefone? TipoTelefone1 + { + get; + set; + } + + [Description("TIPO TELEFONE 2")] + [Log(true)] + public TipoTelefone? TipoTelefone2 + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Fornecedor fornecedor = this; + return new Func<List<KeyValuePair<string, string>>>(fornecedor.Validate); + } + } + + public Fornecedor() + { + } + + public List<TupleList> Log() + { + string description; + string str; + string str1; + string str2; + string str3; + string description1; + List<TupleList> tupleLists = new List<TupleList>(); + TupleList tupleList = new TupleList(); + ObservableCollection<Tuple<string, string, string>> observableCollection = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("NOME DO FORNECEDOR", (string.IsNullOrWhiteSpace(this.Nome) ? "" : this.Nome), ""), + new Tuple<string, string, string>("DOCUMENTO", (string.IsNullOrWhiteSpace(this.Documento) ? "" : this.Documento), ""), + new Tuple<string, string, string>("CEP", (string.IsNullOrWhiteSpace(base.Cep) ? "" : base.Cep), ""), + new Tuple<string, string, string>("ENDEREÇO", (string.IsNullOrWhiteSpace(base.Endereco) ? "" : base.Endereco), ""), + new Tuple<string, string, string>("NÚMERO", (string.IsNullOrWhiteSpace(base.Numero) ? "" : base.Numero), ""), + new Tuple<string, string, string>("COMPLEMENTO", (string.IsNullOrWhiteSpace(base.Complemento) ? "" : base.Complemento), ""), + new Tuple<string, string, string>("BAIRRO", (string.IsNullOrWhiteSpace(base.Bairro) ? "" : base.Bairro), ""), + new Tuple<string, string, string>("CIDADE", (string.IsNullOrWhiteSpace(base.Cidade) ? "" : base.Cidade), ""), + new Tuple<string, string, string>("ESTADO", (string.IsNullOrWhiteSpace(base.Estado) ? "" : base.Estado), "") + }; + TipoTelefone? tipoTelefone1 = this.TipoTelefone1; + if (!tipoTelefone1.HasValue) + { + description = ""; + } + else + { + tipoTelefone1 = this.TipoTelefone1; + if (tipoTelefone1.HasValue) + { + description = tipoTelefone1.GetValueOrDefault().GetDescription(); + } + else + { + description = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("TIPO DO PRIMEIRO TELEFONE", description, "")); + observableCollection.Add(new Tuple<string, string, string>("PRIMEIRO PREFIXO", (string.IsNullOrWhiteSpace(this.Prefixo1) ? "" : this.Prefixo1), "")); + observableCollection.Add(new Tuple<string, string, string>("PRIMEIRO TELEFONE", (string.IsNullOrWhiteSpace(this.Telefone1) ? "" : this.Telefone1), "")); + tipoTelefone1 = this.TipoTelefone2; + if (!tipoTelefone1.HasValue) + { + str = ""; + } + else + { + tipoTelefone1 = this.TipoTelefone2; + if (tipoTelefone1.HasValue) + { + str = tipoTelefone1.GetValueOrDefault().GetDescription(); + } + else + { + str = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("TIPO DO SEGUNDO TELEFONE", str, "")); + observableCollection.Add(new Tuple<string, string, string>("SEGUNDO PREFIXO", (string.IsNullOrWhiteSpace(this.Prefixo2) ? "" : this.Prefixo2), "")); + observableCollection.Add(new Tuple<string, string, string>("SEGUNDO TELEFONE", (string.IsNullOrWhiteSpace(this.Telefone2) ? "" : this.Telefone2), "")); + observableCollection.Add(new Tuple<string, string, string>("E-MAIL", (string.IsNullOrWhiteSpace(this.Email) ? "" : this.Email), "")); + long? idPlano = this.IdPlano; + if (!idPlano.HasValue) + { + str1 = ""; + } + else + { + idPlano = this.IdPlano; + if (idPlano.HasValue) + { + str1 = idPlano.GetValueOrDefault().ToString(); + } + else + { + str1 = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("PLANO DE CONTAS", str1, "")); + idPlano = this.IdCentro; + if (!idPlano.HasValue) + { + str2 = ""; + } + else + { + idPlano = this.IdCentro; + if (idPlano.HasValue) + { + str2 = idPlano.GetValueOrDefault().ToString(); + } + else + { + str2 = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("CENTRO DE CUSTO", str2, "")); + idPlano = this.IdConta; + if (!idPlano.HasValue) + { + str3 = ""; + } + else + { + idPlano = this.IdConta; + if (idPlano.HasValue) + { + str3 = idPlano.GetValueOrDefault().ToString(); + } + else + { + str3 = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("CONTA CORRENTE", str3, "")); + Gestor.Model.Common.TipoPagamento? tipoPagamento = this.TipoPagamento; + if (!tipoPagamento.HasValue) + { + description1 = ""; + } + else + { + tipoPagamento = this.TipoPagamento; + if (tipoPagamento.HasValue) + { + description1 = tipoPagamento.GetValueOrDefault().GetDescription(); + } + else + { + description1 = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("TIPO DE PAGAMENTO", description1, "")); + observableCollection.Add(new Tuple<string, string, string>("OBSERVAÇÕES", (string.IsNullOrWhiteSpace(this.Observacao) ? "" : this.Observacao), "")); + tupleList.Tuples = observableCollection; + tupleLists.Add(tupleList); + return tupleLists; + } + + public List<KeyValuePair<string, string>> Validate() + { + int? nullable; + int? nullable1; + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + string nome = this.Nome; + if (nome != null) + { + nullable1 = new int?((int)nome.Trim().Split(new char[] { ' ' }).Length); + } + else + { + nullable = null; + nullable1 = nullable; + } + int? nullable2 = nullable1; + if (nullable2.HasValue) + { + nullable = nullable2; + if (nullable.GetValueOrDefault() <= 1 & nullable.HasValue) + { + keyValuePairs.AddValue<string, string>("Nome", Messages.NomeInvalido, true); + } + } + else + { + keyValuePairs.AddValue<string, string>("Nome", Messages.Obrigatorio, true); + } + if (!string.IsNullOrWhiteSpace(this.Nome) && this.Nome.Length > 60) + { + keyValuePairs.AddValue<string, string>("Nome", string.Format(Messages.MaiorQueLimite, 60), true); + } + if (!string.IsNullOrWhiteSpace(this.Documento) && !this.Documento.ValidacaoDocumento()) + { + keyValuePairs.AddValue<string, string>("Documento", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.Prefixo1) && !this.Prefixo1.ValidacaoPrefixo()) + { + keyValuePairs.AddValue<string, string>("Prefixo1", Messages.Obrigatorio, true); + } + if (!string.IsNullOrWhiteSpace(this.Telefone1) && !this.Telefone1.ValidacaoTelefone()) + { + keyValuePairs.AddValue<string, string>("Telefone1", Messages.Obrigatorio, true); + } + if (!string.IsNullOrWhiteSpace(this.Email) && !this.Email.ValidacaoEmail()) + { + keyValuePairs.AddValue<string, string>("Email", Messages.Obrigatorio, true); + } + if (!string.IsNullOrWhiteSpace(base.Cidade) && base.Cidade.Length > 30) + { + keyValuePairs.AddValue<string, string>("Cidade", string.Format(Messages.MaiorQueLimite, 30), true); + } + if (!string.IsNullOrWhiteSpace(base.Bairro) && base.Bairro.Length > 60) + { + keyValuePairs.AddValue<string, string>("Bairro", string.Format(Messages.MaiorQueLimite, 60), true); + } + if (!string.IsNullOrWhiteSpace(base.Complemento) && base.Complemento.Length > 40) + { + keyValuePairs.AddValue<string, string>("Complemento", string.Format(Messages.MaiorQueLimite, 40), true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Financeiro/Lancamento.cs b/Codemerx/Gestor.Model/Model.Domain.Financeiro/Lancamento.cs new file mode 100644 index 0000000..2bdd404 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Financeiro/Lancamento.cs @@ -0,0 +1,285 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Financeiro +{ + public class Lancamento : DomainBase, IDomain + { + private decimal? _valorPago; + + private string _historico; + + private string _documento; + + private string _complemento; + + private string _competencia; + + [Description("DATA DA BAIXA")] + [Log(true)] + public DateTime? Baixa + { + get; + set; + } + + public bool Baixado + { + get; + set; + } + + [Description("CÓDIGO BANCO")] + [Log(true)] + public string CodigoBanco + { + get; + set; + } + + [Description("COMPETÊNCIA")] + [Log(true)] + public string Competencia + { + get + { + string str = this._competencia; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._competencia = value; + } + } + + [Log(true)] + public string Complemento + { + get + { + string str = this._complemento; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._complemento = value; + } + } + + [Log(true)] + public BancosContas Conta + { + get; + set; + } + + public ControleFinanceiro Controle + { + get; + set; + } + + [Description("DATA LANÇAMENTO")] + [Log(true)] + public DateTime? DataLancamento + { + get; + set; + } + + [Log(true)] + public string Documento + { + get + { + string str = this._documento; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._documento = value; + } + } + + [Description("HISTÓRICO")] + [Log(true)] + public string Historico + { + get + { + string str = this._historico; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._historico = value; + } + } + + [Description("OBSERVAÇÃO")] + [Log(true)] + public string Observacao + { + get; + set; + } + + [Log(true)] + public DateTime? Pagamento + { + get; + set; + } + + [Log(true)] + public int Parcela + { + get; + set; + } + + public bool Selecionado + { + get; + set; + } + + [Log(true)] + public Gestor.Model.Common.Sinal Sinal + { + get; + set; + } + + [Description("TIPO PAGAMENTO")] + [Log(true)] + public Gestor.Model.Common.TipoPagamento TipoPagamento + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Lancamento lancamento = this; + return new Func<List<KeyValuePair<string, string>>>(lancamento.Validate); + } + } + + [Log(true)] + public decimal Valor + { + get; + set; + } + + [Description("VALOR PAGO")] + [Log(true)] + public decimal? ValorPago + { + get + { + return new decimal?(this._valorPago.GetValueOrDefault()); + } + set + { + this._valorPago = value; + } + } + + [Log(true)] + public DateTime Vencimento + { + get; + set; + } + + public Lancamento() + { + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + keyValuePairs.AddRange(this.Controle.Validate()); + if (string.IsNullOrWhiteSpace(this.Historico)) + { + keyValuePairs.AddValue<string, string>("Historico", Messages.Obrigatorio, true); + } + else if (this.Historico.Length > 100) + { + keyValuePairs.AddValue<string, string>("Historico", string.Format(Messages.MaiorQueLimite, 100), true); + } + if (this.Valor <= decimal.Zero) + { + keyValuePairs.AddValue<string, string>("Valor", Messages.Obrigatorio, true); + } + decimal? valorPago = this.ValorPago; + decimal num = new decimal(); + if ((valorPago.GetValueOrDefault() < num) & valorPago.HasValue) + { + keyValuePairs.AddValue<string, string>("ValorPago", Messages.Obrigatorio, true); + } + if (this.Conta == null) + { + keyValuePairs.AddValue<string, string>("Conta|CONTA CORRENTE", string.Concat(Messages.Obrigatorio, "\nSE NÃO HOUVER NENHUMA CONTA CORRENTE CADASTRADA\nACESSE A TELA BANCOS E CONTAS PARA INCLUIR"), true); + } + if (!string.IsNullOrWhiteSpace(this.Documento) && this.Documento.Length > 50) + { + keyValuePairs.AddValue<string, string>("Documento", string.Format(Messages.MaiorQueLimite, 50), true); + } + if (!string.IsNullOrWhiteSpace(this.Competencia) && this.Competencia.Length > 8) + { + keyValuePairs.AddValue<string, string>("Competencia|COMPETÊNCIA", string.Format(Messages.MaiorQueLimite, 8), true); + } + if (!string.IsNullOrWhiteSpace(this.Complemento) && this.Complemento.Length > 50) + { + keyValuePairs.AddValue<string, string>("Complemento", string.Format(Messages.MaiorQueLimite, 50), true); + } + if (this.Baixa.HasValue && (DateTime.Compare(this.Baixa.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.Baixa.Value, new DateTime(9999, 12, 31)) > 0)) + { + keyValuePairs.AddValue<string, string>("Baixa", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + if (DateTime.Compare(this.Vencimento, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.Vencimento, new DateTime(9999, 12, 31)) > 0) + { + keyValuePairs.AddValue<string, string>("Vencimento", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + if (this.Pagamento.HasValue && (DateTime.Compare(this.Pagamento.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.Pagamento.Value, new DateTime(9999, 12, 31)) > 0)) + { + keyValuePairs.AddValue<string, string>("Pagamento", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + if (!this.Baixa.HasValue && this.Baixado) + { + keyValuePairs.AddValue<string, string>("Baixa", "NÃO É POSSÍVEL SALVAR UM DOCUMENTO SEM DATA DE BAIXA QUANDO O LANÇAMENTO POSSUÍ BAIXA", true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Financeiro/Plano.cs b/Codemerx/Gestor.Model/Model.Domain.Financeiro/Plano.cs new file mode 100644 index 0000000..9e9ab97 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Financeiro/Plano.cs @@ -0,0 +1,68 @@ +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Financeiro +{ + public class Plano : DomainBase, IDomain + { + private string _descricao; + + public bool Ativo + { + get; + set; + } + + public string Descricao + { + get + { + string str = this._descricao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._descricao = value; + } + } + + public bool Selecionado + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Plano plano = this; + return new Func<List<KeyValuePair<string, string>>>(plano.Validate); + } + } + + public Plano() + { + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (string.IsNullOrWhiteSpace(this.Descricao)) + { + keyValuePairs.AddValue<string, string>("Descricao", Messages.Obrigatorio, true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Financeiro/Planos.cs b/Codemerx/Gestor.Model/Model.Domain.Financeiro/Planos.cs new file mode 100644 index 0000000..94e7528 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Financeiro/Planos.cs @@ -0,0 +1,165 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Gestor.Model.Validation; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Financeiro +{ + public class Planos : DomainBase, IDomain + { + private string _descricao; + + private Gestor.Model.Common.Sinal _sinal; + + private string _nome; + + [Log(true)] + public bool Ativo + { + get; + set; + } + + [Description("DESCRIÇÃO")] + [Log(true)] + [Name(true)] + public string Descricao + { + get + { + string str = this._descricao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._descricao = value; + string str = (this.Sinal == Gestor.Model.Common.Sinal.Credito ? "(+)" : "(-)"); + this.Nome = string.Concat(value.ToUpper(), " ", str); + } + } + + [Log(true)] + public string Nome + { + get + { + return this._nome.ToUpper(); + } + set + { + this._nome = value; + } + } + + [Log(true)] + public Gestor.Model.Domain.Financeiro.Plano Plano + { + get; + set; + } + + public bool Selecionado + { + get; + set; + } + + [Log(true)] + public Gestor.Model.Common.Sinal Sinal + { + get + { + return this._sinal; + } + set + { + this._sinal = value; + string str = (value == Gestor.Model.Common.Sinal.Credito ? "(+)" : "(-)"); + this.Nome = string.Concat(this.Descricao, " ", str); + } + } + + [Description("TIPO CONTA")] + [Log(true)] + public Gestor.Model.Domain.Financeiro.TipoConta TipoConta + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Planos plano = this; + return new Func<List<KeyValuePair<string, string>>>(plano.Validate); + } + } + + public Planos() + { + } + + public List<TupleList> Log() + { + string descricao; + List<TupleList> tupleLists = new List<TupleList>(); + TupleList tupleList = new TupleList(); + ObservableCollection<Tuple<string, string, string>> observableCollection = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("NOME", (string.IsNullOrWhiteSpace(this.Nome) ? "" : this.Nome), "") + }; + if (this.Plano == null) + { + descricao = ""; + } + else + { + Gestor.Model.Domain.Financeiro.Plano plano = this.Plano; + if (plano != null) + { + descricao = plano.Descricao; + } + else + { + descricao = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("PLANO", descricao, "")); + observableCollection.Add(new Tuple<string, string, string>("ATIVO", (this.Ativo ? "SIM" : "NÃO"), "")); + Gestor.Model.Common.Sinal sinal = this.Sinal; + observableCollection.Add(new Tuple<string, string, string>("SINAL", this.Sinal.GetDescription(), "")); + tupleList.Tuples = observableCollection; + tupleLists.Add(tupleList); + return tupleLists; + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (string.IsNullOrWhiteSpace(this.Descricao)) + { + keyValuePairs.AddValue<string, string>("Descricao", Messages.Obrigatorio, true); + } + if (this.Plano == null) + { + keyValuePairs.AddValue<string, string>("Plano", Messages.Obrigatorio, true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Financeiro/RelatorioLancamentos.cs b/Codemerx/Gestor.Model/Model.Domain.Financeiro/RelatorioLancamentos.cs new file mode 100644 index 0000000..6caa83a --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Financeiro/RelatorioLancamentos.cs @@ -0,0 +1,132 @@ +using Gestor.Model.Attributes; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Financeiro +{ + public class RelatorioLancamentos + { + [Description("DATA BAIXA")] + [Tipo("DATA?")] + public DateTime? Baixa + { + get; + set; + } + + [Description("CENTRO DE CUSTO")] + public string Centro + { + get; + set; + } + + [Description("COMPETÊNCIA")] + public string Competencia + { + get; + set; + } + + [Description("CONTA")] + public string Conta + { + get; + set; + } + + [Description("DOCUMENTO")] + public string Documento + { + get; + set; + } + + [Description("FORNECEDOR")] + public string Fornecedor + { + get; + set; + } + + [Description("HISTORICO")] + public string Historico + { + get; + set; + } + + [Description("OBSERVAÇÃO")] + public string Observacao + { + get; + set; + } + + [Description("PAGAMENTO")] + [Tipo("DATA?")] + public DateTime? Pagamento + { + get; + set; + } + + [Description("PARCELA")] + [Tipo("QUANTIDADE")] + public int Parcela + { + get; + set; + } + + [Description("PLANO DE CONTAS")] + public string Plano + { + get; + set; + } + + [Description("PLANOS")] + public string Planos + { + get; + set; + } + + [Description("SINAL")] + public string Sinal + { + get; + set; + } + + [Description("VALOR")] + [Tipo("VALOR")] + public decimal Valor + { + get; + set; + } + + [Description("VALOR PAGO")] + [Tipo("VALOR")] + public decimal? ValorPago + { + get; + set; + } + + [Description("VENCIMENTO")] + [Tipo("DATA")] + public DateTime Vencimento + { + get; + set; + } + + public RelatorioLancamentos() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Financeiro/Relatorios/DadosFechamento.cs b/Codemerx/Gestor.Model/Model.Domain.Financeiro/Relatorios/DadosFechamento.cs new file mode 100644 index 0000000..fdaa81c --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Financeiro/Relatorios/DadosFechamento.cs @@ -0,0 +1,82 @@ +using Gestor.Model.Attributes; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Financeiro.Relatorios +{ + public class DadosFechamento + { + private string _planos; + + [Description("TOTAL CRÉDITO")] + [Tipo("VALOR")] + public decimal Credito + { + get; + set; + } + + [Description("TOTAL DÉBITO")] + [Tipo("VALOR")] + public decimal Debito + { + get; + set; + } + + [Description("% CRÉDITO")] + [Tipo("PERCENTUAL")] + public decimal PercentualCredito + { + get; + set; + } + + [Description("% DÉBITO")] + [Tipo("PERCENTUAL")] + public decimal PercentualDebito + { + get; + set; + } + + [Description("PLANO DE CONTAS")] + public string Planos + { + get + { + string str = this._planos; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._planos = value; + } + } + + [Description("TOTAL CRÉDITO - TOTAL DÉBITO")] + [Tipo("VALOR")] + public decimal Soma + { + get; + set; + } + + [Description("% TOTAL DE CRÉDITO - % TOTAL DE DÉBITO")] + [Tipo("PERCENTUAL")] + public decimal SomaPercentual + { + get; + set; + } + + public DadosFechamento() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Financeiro/Relatorios/DadosFechamentoAnalitico.cs b/Codemerx/Gestor.Model/Model.Domain.Financeiro/Relatorios/DadosFechamentoAnalitico.cs new file mode 100644 index 0000000..110118c --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Financeiro/Relatorios/DadosFechamentoAnalitico.cs @@ -0,0 +1,154 @@ +using Gestor.Model.Attributes; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Financeiro.Relatorios +{ + public class DadosFechamentoAnalitico + { + private string _nome; + + [Description("ABR")] + [Tipo("VALOR")] + public decimal? Abr + { + get; + set; + } + + [Description("AGO")] + [Tipo("VALOR")] + public decimal? Ago + { + get; + set; + } + + [Description("DEZ")] + [Tipo("VALOR")] + public decimal? Dez + { + get; + set; + } + + [Description("FEV")] + [Tipo("VALOR")] + public decimal? Fev + { + get; + set; + } + + [Description("JAN")] + [Tipo("VALOR")] + public decimal? Jan + { + get; + set; + } + + [Description("JUL")] + [Tipo("VALOR")] + public decimal? Jul + { + get; + set; + } + + [Description("JUN")] + [Tipo("VALOR")] + public decimal? Jun + { + get; + set; + } + + [Description("MAI")] + [Tipo("VALOR")] + public decimal? Mai + { + get; + set; + } + + [Description("MAR")] + [Tipo("VALOR")] + public decimal? Mar + { + get; + set; + } + + [Description("NOME")] + public string Nome + { + get + { + string str = this._nome; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._nome = value; + } + } + + [Description("NOV")] + [Tipo("VALOR")] + public decimal? Nov + { + get; + set; + } + + [Description("OUT")] + [Tipo("VALOR")] + public decimal? Out + { + get; + set; + } + + [Description("% CRÉDITO")] + [Tipo("PERCENTUAL")] + public decimal PercentualCredito + { + get; + set; + } + + [Description("% DÉBITO")] + [Tipo("PERCENTUAL")] + public decimal PercentualDebito + { + get; + set; + } + + [Description("SET")] + [Tipo("VALOR")] + public decimal? Set + { + get; + set; + } + + [Description("TOTAL")] + [Tipo("VALOR")] + public decimal? Total + { + get; + set; + } + + public DadosFechamentoAnalitico() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Financeiro/Relatorios/FechamentoFinanceiro.cs b/Codemerx/Gestor.Model/Model.Domain.Financeiro/Relatorios/FechamentoFinanceiro.cs new file mode 100644 index 0000000..53c72ad --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Financeiro/Relatorios/FechamentoFinanceiro.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Financeiro.Relatorios +{ + public class FechamentoFinanceiro + { + public List<DadosFechamento> Dados + { + get; + set; + } + + public string Plano + { + get; + set; + } + + public FechamentoFinanceiro() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Financeiro/Relatorios/FechamentoFinanceiroAnalitico.cs b/Codemerx/Gestor.Model/Model.Domain.Financeiro/Relatorios/FechamentoFinanceiroAnalitico.cs new file mode 100644 index 0000000..73998d1 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Financeiro/Relatorios/FechamentoFinanceiroAnalitico.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Financeiro.Relatorios +{ + public class FechamentoFinanceiroAnalitico + { + public List<DadosFechamentoAnalitico> Dados + { + get; + set; + } + + public string NomeConta + { + get; + set; + } + + public FechamentoFinanceiroAnalitico() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Financeiro/Relatorios/FiltroFinanceiro.cs b/Codemerx/Gestor.Model/Model.Domain.Financeiro/Relatorios/FiltroFinanceiro.cs new file mode 100644 index 0000000..2f79ff0 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Financeiro/Relatorios/FiltroFinanceiro.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Financeiro.Relatorios +{ + public class FiltroFinanceiro + { + public List<long> Centro + { + get; + set; + } + + public List<long> Conta + { + get; + set; + } + + public DateTime Fim + { + get; + set; + } + + public DateTime Inicio + { + get; + set; + } + + public List<long> Plano + { + get; + set; + } + + public List<long> Planos + { + get; + set; + } + + public string Referencia + { + get; + set; + } + + public FiltroFinanceiro() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Financeiro/Saldo.cs b/Codemerx/Gestor.Model/Model.Domain.Financeiro/Saldo.cs new file mode 100644 index 0000000..59731d3 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Financeiro/Saldo.cs @@ -0,0 +1,89 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Financeiro +{ + public class Saldo : DomainBase, IDomain + { + [Log(true)] + public BancosContas Conta + { + get; + set; + } + + [Description("DATA FINAL")] + [Log(true)] + public DateTime? DataFinal + { + get; + set; + } + + [Description("DATA INÍCIO")] + [Log(true)] + public DateTime? DataInicio + { + get; + set; + } + + [Log(true)] + public string Extrato + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Saldo saldo = this; + return new Func<List<KeyValuePair<string, string>>>(saldo.Validate); + } + } + + [Description("VALOR FINAL")] + [Log(true)] + public decimal? ValorFinal + { + get; + set; + } + + [Description("VALOR INÍCIO")] + [Log(true)] + public decimal ValorInicio + { + get; + set; + } + + public Saldo() + { + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (this.DataInicio.HasValue && (DateTime.Compare(this.DataInicio.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.DataInicio.Value, new DateTime(9999, 12, 31)) > 0)) + { + keyValuePairs.AddValue<string, string>("DataInicio|ABERTURA", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + if (this.DataFinal.HasValue && (DateTime.Compare(this.DataFinal.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.DataFinal.Value, new DateTime(9999, 12, 31)) > 0)) + { + keyValuePairs.AddValue<string, string>("DataFinal|FECHAMENTO", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Financeiro/SinteticoFinanceiro.cs b/Codemerx/Gestor.Model/Model.Domain.Financeiro/SinteticoFinanceiro.cs new file mode 100644 index 0000000..190d4ea --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Financeiro/SinteticoFinanceiro.cs @@ -0,0 +1,60 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Financeiro +{ + public class SinteticoFinanceiro + { + public BancosContas Conta + { + get; + set; + } + + public decimal Credito + { + get; + set; + } + + public decimal Debito + { + get; + set; + } + + public int Filtrados + { + get; + set; + } + + public decimal Liquido + { + get; + set; + } + + public decimal LiquidoPago + { + get; + set; + } + + public decimal LiquidoSelecionados + { + get; + set; + } + + public int Selecionados + { + get; + set; + } + + public SinteticoFinanceiro() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Financeiro/TipoConta.cs b/Codemerx/Gestor.Model/Model.Domain.Financeiro/TipoConta.cs new file mode 100644 index 0000000..8e8cb6c --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Financeiro/TipoConta.cs @@ -0,0 +1,62 @@ +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Financeiro +{ + public class TipoConta : DomainBase, IDomain + { + private string _descricao; + + public bool Ativo + { + get; + set; + } + + public string Descricao + { + get + { + string str = this._descricao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._descricao = value; + } + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + TipoConta tipoContum = this; + return new Func<List<KeyValuePair<string, string>>>(tipoContum.Validate); + } + } + + public TipoConta() + { + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (string.IsNullOrWhiteSpace(this.Descricao)) + { + keyValuePairs.AddValue<string, string>("Descricao", Messages.Obrigatorio, true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Financeiro/Transferencia.cs b/Codemerx/Gestor.Model/Model.Domain.Financeiro/Transferencia.cs new file mode 100644 index 0000000..8a12c2c --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Financeiro/Transferencia.cs @@ -0,0 +1,76 @@ +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Financeiro +{ + public class Transferencia + { + public DateTime Data + { + get; + set; + } + + public BancosContas Destino + { + get; + set; + } + + public BancosContas Origem + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + return new Func<List<KeyValuePair<string, string>>>(this.Validate); + } + } + + public decimal Valor + { + get; + set; + } + + public Transferencia() + { + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (this.Origem == null) + { + keyValuePairs.AddValue<string, string>("Origem", Messages.Obrigatorio, true); + } + if (this.Destino == null) + { + keyValuePairs.AddValue<string, string>("Destino", Messages.Obrigatorio, true); + } + if (this.Origem != null && this.Destino != null && this.Origem.Id == this.Destino.Id) + { + keyValuePairs.AddValue<string, string>("CONTAS", "A CONTA DE ORIGEM NÃO PODE SER A MESMA QUE A DESTINO.", true); + } + if (DateTime.Compare(this.Data, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.Data, new DateTime(9999, 12, 31)) > 0) + { + keyValuePairs.AddValue<string, string>("Data", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + if (this.Valor <= decimal.Zero) + { + keyValuePairs.AddValue<string, string>("Valor", Messages.Obrigatorio, true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Generic/Diferenca.cs b/Codemerx/Gestor.Model/Model.Domain.Generic/Diferenca.cs new file mode 100644 index 0000000..1d0765f --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Generic/Diferenca.cs @@ -0,0 +1,36 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Generic +{ + public class Diferenca + { + public string Campo + { + get; + set; + } + + public string Descricao + { + get; + set; + } + + public string ValorAnterior + { + get; + set; + } + + public string ValorAtual + { + get; + set; + } + + public Diferenca() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Generic/DomainBase.cs b/Codemerx/Gestor.Model/Model.Domain.Generic/DomainBase.cs new file mode 100644 index 0000000..beef091 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Generic/DomainBase.cs @@ -0,0 +1,1067 @@ +using Gestor.Model.Attributes; +using Microsoft.CSharp.RuntimeBinder; +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Generic +{ + public abstract class DomainBase : ICloneable + { + private List<FieldInformation> _originalValues = new List<FieldInformation>(); + + public long Id + { + get; + set; + } + + protected DomainBase() + { + } + + public object Clone() + { + return this.MemberwiseClone(); + } + + public List<Diferenca> Compare() + { + List<FieldInformation> properties = this.GetProperties(); + List<Diferenca> diferencas3 = new List<Diferenca>(); + PropertyInfo[] propertyInfoArray = this.GetType().GetProperties(); + this._originalValues.ToList<FieldInformation>().ForEach((FieldInformation x) => { + Diferenca diferenca; + object target; + object obj; + object target1; + object obj1; + object target2; + object obj2; + object target3; + object obj3; + Diferenca diferenca1; + object target4; + object obj4; + FieldInformation fieldInformation = properties.FirstOrDefault<FieldInformation>((FieldInformation k) => k.Description == x.Description); + if (DomainBase.u003cu003eo__18.u003cu003ep__4 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__4 = CallSite<Func<CallSite, object, bool>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(CSharpBinderFlags.None, ExpressionType.IsTrue, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + !0 _u00210 = DomainBase.u003cu003eo__18.u003cu003ep__4.Target; + CallSite<Func<CallSite, object, bool>> u003cu003ep_4 = DomainBase.u003cu003eo__18.u003cu003ep__4; + if (DomainBase.u003cu003eo__18.u003cu003ep__0 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__0 = CallSite<Func<CallSite, object, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(CSharpBinderFlags.None, ExpressionType.Equal, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.Constant, null) }))); + } + !0 _u002101 = DomainBase.u003cu003eo__18.u003cu003ep__0.Target; + CallSite<Func<CallSite, object, object, object>> u003cu003ep_0 = DomainBase.u003cu003eo__18.u003cu003ep__0; + FieldInformation fieldInformation1 = fieldInformation; + object value = _u002101(u003cu003ep_0, (fieldInformation1 != null ? fieldInformation1.Value : null), null); + if (DomainBase.u003cu003eo__18.u003cu003ep__3 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__3 = CallSite<Func<CallSite, object, bool>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(CSharpBinderFlags.None, ExpressionType.IsFalse, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + if (DomainBase.u003cu003eo__18.u003cu003ep__3.Target(DomainBase.u003cu003eo__18.u003cu003ep__3, value)) + { + target = value; + } + else + { + if (DomainBase.u003cu003eo__18.u003cu003ep__2 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__2 = CallSite<Func<CallSite, object, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(CSharpBinderFlags.BinaryOperationLogical, ExpressionType.And, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + !0 _u002102 = DomainBase.u003cu003eo__18.u003cu003ep__2.Target; + CallSite<Func<CallSite, object, object, object>> u003cu003ep_2 = DomainBase.u003cu003eo__18.u003cu003ep__2; + object obj5 = value; + if (DomainBase.u003cu003eo__18.u003cu003ep__1 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__1 = CallSite<Func<CallSite, object, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(CSharpBinderFlags.None, ExpressionType.Equal, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.Constant, null) }))); + } + target = _u002102(u003cu003ep_2, obj5, DomainBase.u003cu003eo__18.u003cu003ep__1.Target(DomainBase.u003cu003eo__18.u003cu003ep__1, x.Value, null)); + } + if (_u00210(u003cu003ep_4, target)) + { + return; + } + PropertyInfo propertyInfo = propertyInfoArray.FirstOrDefault<PropertyInfo>((PropertyInfo p) => p.Name == x.Name); + bool flag = (propertyInfo == null ? false : propertyInfo.GetCustomAttributes(typeof(ForceLogAttribute), true).Length != 0); + if (DomainBase.u003cu003eo__18.u003cu003ep__14 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__14 = CallSite<Func<CallSite, object, bool>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(CSharpBinderFlags.None, ExpressionType.IsTrue, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + !0 _u002103 = DomainBase.u003cu003eo__18.u003cu003ep__14.Target; + CallSite<Func<CallSite, object, bool>> u003cu003ep_14 = DomainBase.u003cu003eo__18.u003cu003ep__14; + if (DomainBase.u003cu003eo__18.u003cu003ep__5 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__5 = CallSite<Func<CallSite, object, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(CSharpBinderFlags.None, ExpressionType.Equal, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.Constant, null) }))); + } + !0 _u002104 = DomainBase.u003cu003eo__18.u003cu003ep__5.Target; + CallSite<Func<CallSite, object, object, object>> u003cu003ep_5 = DomainBase.u003cu003eo__18.u003cu003ep__5; + fieldInformation1 = fieldInformation; + object target5 = _u002104(u003cu003ep_5, (fieldInformation1 != null ? fieldInformation1.Value : null), null); + if (DomainBase.u003cu003eo__18.u003cu003ep__8 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__8 = CallSite<Func<CallSite, object, bool>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(CSharpBinderFlags.None, ExpressionType.IsFalse, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + if (DomainBase.u003cu003eo__18.u003cu003ep__8.Target(DomainBase.u003cu003eo__18.u003cu003ep__8, target5)) + { + obj = target5; + } + else + { + if (DomainBase.u003cu003eo__18.u003cu003ep__7 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__7 = CallSite<Func<CallSite, object, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(CSharpBinderFlags.BinaryOperationLogical, ExpressionType.And, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + !0 _u002105 = DomainBase.u003cu003eo__18.u003cu003ep__7.Target; + CallSite<Func<CallSite, object, object, object>> u003cu003ep_7 = DomainBase.u003cu003eo__18.u003cu003ep__7; + object obj6 = target5; + if (DomainBase.u003cu003eo__18.u003cu003ep__6 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__6 = CallSite<Func<CallSite, object, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(CSharpBinderFlags.None, ExpressionType.NotEqual, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.Constant, null) }))); + } + obj = _u002105(u003cu003ep_7, obj6, DomainBase.u003cu003eo__18.u003cu003ep__6.Target(DomainBase.u003cu003eo__18.u003cu003ep__6, x.Value, null)); + } + value = obj; + if (DomainBase.u003cu003eo__18.u003cu003ep__13 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__13 = CallSite<Func<CallSite, object, bool>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(CSharpBinderFlags.None, ExpressionType.IsFalse, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + if (DomainBase.u003cu003eo__18.u003cu003ep__13.Target(DomainBase.u003cu003eo__18.u003cu003ep__13, value)) + { + target1 = value; + } + else + { + if (DomainBase.u003cu003eo__18.u003cu003ep__12 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__12 = CallSite<Func<CallSite, object, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(CSharpBinderFlags.BinaryOperationLogical, ExpressionType.And, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + !0 target6 = DomainBase.u003cu003eo__18.u003cu003ep__12.Target; + CallSite<Func<CallSite, object, object, object>> u003cu003ep_12 = DomainBase.u003cu003eo__18.u003cu003ep__12; + object obj7 = value; + if (DomainBase.u003cu003eo__18.u003cu003ep__11 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__11 = CallSite<Func<CallSite, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(CSharpBinderFlags.None, ExpressionType.Not, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + !0 _u002106 = DomainBase.u003cu003eo__18.u003cu003ep__11.Target; + CallSite<Func<CallSite, object, object>> u003cu003ep_11 = DomainBase.u003cu003eo__18.u003cu003ep__11; + if (DomainBase.u003cu003eo__18.u003cu003ep__10 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__10 = CallSite<Func<CallSite, Type, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(CSharpBinderFlags.None, "IsNullOrWhiteSpace", null, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType | CSharpArgumentInfoFlags.IsStaticType, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + !0 target7 = DomainBase.u003cu003eo__18.u003cu003ep__10.Target; + CallSite<Func<CallSite, Type, object, object>> u003cu003ep_10 = DomainBase.u003cu003eo__18.u003cu003ep__10; + Type type = typeof(string); + if (DomainBase.u003cu003eo__18.u003cu003ep__9 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__9 = CallSite<Func<CallSite, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(CSharpBinderFlags.None, "ToString", null, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + target1 = target6(u003cu003ep_12, obj7, _u002106(u003cu003ep_11, target7(u003cu003ep_10, type, DomainBase.u003cu003eo__18.u003cu003ep__9.Target(DomainBase.u003cu003eo__18.u003cu003ep__9, x.Value)))); + } + if (_u002103(u003cu003ep_14, target1)) + { + List<Diferenca> diferencas = diferencas3; + diferenca = new Diferenca() + { + Campo = x.Name, + Descricao = x.Description + }; + Diferenca diferenca2 = diferenca; + if (DomainBase.u003cu003eo__18.u003cu003ep__16 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__16 = CallSite<Func<CallSite, object, string>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.Convert(CSharpBinderFlags.None, typeof(string), typeof(DomainBase))); + } + !0 _u002107 = DomainBase.u003cu003eo__18.u003cu003ep__16.Target; + CallSite<Func<CallSite, object, string>> u003cu003ep_16 = DomainBase.u003cu003eo__18.u003cu003ep__16; + if (DomainBase.u003cu003eo__18.u003cu003ep__15 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__15 = CallSite<Func<CallSite, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(CSharpBinderFlags.None, "ToString", null, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + diferenca2.ValorAnterior = _u002107(u003cu003ep_16, DomainBase.u003cu003eo__18.u003cu003ep__15.Target(DomainBase.u003cu003eo__18.u003cu003ep__15, x.Value)); + diferenca.ValorAtual = null; + diferencas.Add(diferenca); + return; + } + if (DomainBase.u003cu003eo__18.u003cu003ep__26 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__26 = CallSite<Func<CallSite, object, bool>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(CSharpBinderFlags.None, ExpressionType.IsTrue, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + !0 target8 = DomainBase.u003cu003eo__18.u003cu003ep__26.Target; + CallSite<Func<CallSite, object, bool>> u003cu003ep_26 = DomainBase.u003cu003eo__18.u003cu003ep__26; + if (DomainBase.u003cu003eo__18.u003cu003ep__17 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__17 = CallSite<Func<CallSite, object, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(CSharpBinderFlags.None, ExpressionType.NotEqual, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.Constant, null) }))); + } + target5 = DomainBase.u003cu003eo__18.u003cu003ep__17.Target(DomainBase.u003cu003eo__18.u003cu003ep__17, fieldInformation.Value, null); + if (DomainBase.u003cu003eo__18.u003cu003ep__20 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__20 = CallSite<Func<CallSite, object, bool>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(CSharpBinderFlags.None, ExpressionType.IsFalse, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + if (DomainBase.u003cu003eo__18.u003cu003ep__20.Target(DomainBase.u003cu003eo__18.u003cu003ep__20, target5)) + { + obj1 = target5; + } + else + { + if (DomainBase.u003cu003eo__18.u003cu003ep__19 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__19 = CallSite<Func<CallSite, object, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(CSharpBinderFlags.BinaryOperationLogical, ExpressionType.And, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + !0 _u002108 = DomainBase.u003cu003eo__18.u003cu003ep__19.Target; + CallSite<Func<CallSite, object, object, object>> u003cu003ep_19 = DomainBase.u003cu003eo__18.u003cu003ep__19; + object obj8 = target5; + if (DomainBase.u003cu003eo__18.u003cu003ep__18 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__18 = CallSite<Func<CallSite, object, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(CSharpBinderFlags.None, ExpressionType.Equal, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.Constant, null) }))); + } + obj1 = _u002108(u003cu003ep_19, obj8, DomainBase.u003cu003eo__18.u003cu003ep__18.Target(DomainBase.u003cu003eo__18.u003cu003ep__18, x.Value, null)); + } + value = obj1; + if (DomainBase.u003cu003eo__18.u003cu003ep__25 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__25 = CallSite<Func<CallSite, object, bool>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(CSharpBinderFlags.None, ExpressionType.IsFalse, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + if (DomainBase.u003cu003eo__18.u003cu003ep__25.Target(DomainBase.u003cu003eo__18.u003cu003ep__25, value)) + { + target2 = value; + } + else + { + if (DomainBase.u003cu003eo__18.u003cu003ep__24 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__24 = CallSite<Func<CallSite, object, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(CSharpBinderFlags.BinaryOperationLogical, ExpressionType.And, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + !0 target9 = DomainBase.u003cu003eo__18.u003cu003ep__24.Target; + CallSite<Func<CallSite, object, object, object>> u003cu003ep_24 = DomainBase.u003cu003eo__18.u003cu003ep__24; + object obj9 = value; + if (DomainBase.u003cu003eo__18.u003cu003ep__23 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__23 = CallSite<Func<CallSite, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(CSharpBinderFlags.None, ExpressionType.Not, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + !0 _u002109 = DomainBase.u003cu003eo__18.u003cu003ep__23.Target; + CallSite<Func<CallSite, object, object>> u003cu003ep_23 = DomainBase.u003cu003eo__18.u003cu003ep__23; + if (DomainBase.u003cu003eo__18.u003cu003ep__22 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__22 = CallSite<Func<CallSite, Type, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(CSharpBinderFlags.None, "IsNullOrWhiteSpace", null, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType | CSharpArgumentInfoFlags.IsStaticType, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + !0 target10 = DomainBase.u003cu003eo__18.u003cu003ep__22.Target; + CallSite<Func<CallSite, Type, object, object>> u003cu003ep_22 = DomainBase.u003cu003eo__18.u003cu003ep__22; + Type type1 = typeof(string); + if (DomainBase.u003cu003eo__18.u003cu003ep__21 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__21 = CallSite<Func<CallSite, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(CSharpBinderFlags.None, "ToString", null, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + target2 = target9(u003cu003ep_24, obj9, _u002109(u003cu003ep_23, target10(u003cu003ep_22, type1, DomainBase.u003cu003eo__18.u003cu003ep__21.Target(DomainBase.u003cu003eo__18.u003cu003ep__21, fieldInformation.Value)))); + } + if (target8(u003cu003ep_26, target2)) + { + List<Diferenca> diferencas1 = diferencas3; + diferenca = new Diferenca() + { + Campo = x.Name, + Descricao = x.Description, + ValorAnterior = null + }; + Diferenca diferenca3 = diferenca; + if (DomainBase.u003cu003eo__18.u003cu003ep__28 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__28 = CallSite<Func<CallSite, object, string>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.Convert(CSharpBinderFlags.None, typeof(string), typeof(DomainBase))); + } + !0 _u0021010 = DomainBase.u003cu003eo__18.u003cu003ep__28.Target; + CallSite<Func<CallSite, object, string>> u003cu003ep_28 = DomainBase.u003cu003eo__18.u003cu003ep__28; + if (DomainBase.u003cu003eo__18.u003cu003ep__27 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__27 = CallSite<Func<CallSite, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(CSharpBinderFlags.None, "ToString", null, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + diferenca3.ValorAtual = _u0021010(u003cu003ep_28, DomainBase.u003cu003eo__18.u003cu003ep__27.Target(DomainBase.u003cu003eo__18.u003cu003ep__27, fieldInformation.Value)); + diferencas1.Add(diferenca); + return; + } + if (DomainBase.u003cu003eo__18.u003cu003ep__34 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__34 = CallSite<Func<CallSite, object, bool>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(CSharpBinderFlags.None, ExpressionType.IsTrue, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + !0 target11 = DomainBase.u003cu003eo__18.u003cu003ep__34.Target; + CallSite<Func<CallSite, object, bool>> u003cu003ep_34 = DomainBase.u003cu003eo__18.u003cu003ep__34; + if (DomainBase.u003cu003eo__18.u003cu003ep__31 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__31 = CallSite<Func<CallSite, object, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(CSharpBinderFlags.None, ExpressionType.Equal, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + !0 _u0021011 = DomainBase.u003cu003eo__18.u003cu003ep__31.Target; + CallSite<Func<CallSite, object, object, object>> u003cu003ep_31 = DomainBase.u003cu003eo__18.u003cu003ep__31; + if (DomainBase.u003cu003eo__18.u003cu003ep__29 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__29 = CallSite<Func<CallSite, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(CSharpBinderFlags.None, "ToString", null, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + object obj10 = DomainBase.u003cu003eo__18.u003cu003ep__29.Target(DomainBase.u003cu003eo__18.u003cu003ep__29, fieldInformation.Value); + if (DomainBase.u003cu003eo__18.u003cu003ep__30 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__30 = CallSite<Func<CallSite, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(CSharpBinderFlags.None, "ToString", null, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + value = _u0021011(u003cu003ep_31, obj10, DomainBase.u003cu003eo__18.u003cu003ep__30.Target(DomainBase.u003cu003eo__18.u003cu003ep__30, x.Value)); + if (DomainBase.u003cu003eo__18.u003cu003ep__33 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__33 = CallSite<Func<CallSite, object, bool>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(CSharpBinderFlags.None, ExpressionType.IsFalse, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + if (DomainBase.u003cu003eo__18.u003cu003ep__33.Target(DomainBase.u003cu003eo__18.u003cu003ep__33, value)) + { + obj2 = value; + } + else + { + if (DomainBase.u003cu003eo__18.u003cu003ep__32 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__32 = CallSite<Func<CallSite, object, bool, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(CSharpBinderFlags.BinaryOperationLogical, ExpressionType.And, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType, null) }))); + } + obj2 = DomainBase.u003cu003eo__18.u003cu003ep__32.Target(DomainBase.u003cu003eo__18.u003cu003ep__32, value, !flag); + } + if (target11(u003cu003ep_34, obj2)) + { + return; + } + List<Diferenca> diferencas2 = diferencas3; + if (DomainBase.u003cu003eo__18.u003cu003ep__35 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__35 = CallSite<Func<CallSite, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(CSharpBinderFlags.None, "GetType", null, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + if (DomainBase.u003cu003eo__18.u003cu003ep__35.Target(DomainBase.u003cu003eo__18.u003cu003ep__35, x.Value) is DateTime) + { + diferenca = new Diferenca() + { + Campo = x.Name, + Descricao = x.Description + }; + Diferenca diferenca4 = diferenca; + if (DomainBase.u003cu003eo__18.u003cu003ep__37 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__37 = CallSite<Func<CallSite, object, string>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.Convert(CSharpBinderFlags.None, typeof(string), typeof(DomainBase))); + } + !0 target12 = DomainBase.u003cu003eo__18.u003cu003ep__37.Target; + CallSite<Func<CallSite, object, string>> u003cu003ep_37 = DomainBase.u003cu003eo__18.u003cu003ep__37; + value = x.Value; + if (value != null) + { + if (DomainBase.u003cu003eo__18.u003cu003ep__36 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__36 = CallSite<Func<CallSite, object, string, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(CSharpBinderFlags.None, "ToString", null, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType | CSharpArgumentInfoFlags.Constant, null) }))); + } + target3 = DomainBase.u003cu003eo__18.u003cu003ep__36.Target(DomainBase.u003cu003eo__18.u003cu003ep__36, value, "G"); + } + else + { + target3 = null; + } + diferenca4.ValorAnterior = target12(u003cu003ep_37, target3); + Diferenca diferenca5 = diferenca; + if (DomainBase.u003cu003eo__18.u003cu003ep__39 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__39 = CallSite<Func<CallSite, object, string>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.Convert(CSharpBinderFlags.None, typeof(string), typeof(DomainBase))); + } + !0 _u0021012 = DomainBase.u003cu003eo__18.u003cu003ep__39.Target; + CallSite<Func<CallSite, object, string>> u003cu003ep_39 = DomainBase.u003cu003eo__18.u003cu003ep__39; + value = fieldInformation.Value; + if (value != null) + { + if (DomainBase.u003cu003eo__18.u003cu003ep__38 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__38 = CallSite<Func<CallSite, object, string, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(CSharpBinderFlags.None, "ToString", null, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType | CSharpArgumentInfoFlags.Constant, null) }))); + } + obj3 = DomainBase.u003cu003eo__18.u003cu003ep__38.Target(DomainBase.u003cu003eo__18.u003cu003ep__38, value, "G"); + } + else + { + obj3 = null; + } + diferenca5.ValorAtual = _u0021012(u003cu003ep_39, obj3); + diferenca1 = diferenca; + } + else + { + diferenca = new Diferenca() + { + Campo = x.Name, + Descricao = x.Description + }; + Diferenca diferenca6 = diferenca; + if (DomainBase.u003cu003eo__18.u003cu003ep__41 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__41 = CallSite<Func<CallSite, object, string>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.Convert(CSharpBinderFlags.None, typeof(string), typeof(DomainBase))); + } + !0 target13 = DomainBase.u003cu003eo__18.u003cu003ep__41.Target; + CallSite<Func<CallSite, object, string>> u003cu003ep_41 = DomainBase.u003cu003eo__18.u003cu003ep__41; + value = x.Value; + if (value != null) + { + if (DomainBase.u003cu003eo__18.u003cu003ep__40 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__40 = CallSite<Func<CallSite, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(CSharpBinderFlags.None, "ToString", null, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + target4 = DomainBase.u003cu003eo__18.u003cu003ep__40.Target(DomainBase.u003cu003eo__18.u003cu003ep__40, value); + } + else + { + target4 = null; + } + diferenca6.ValorAnterior = target13(u003cu003ep_41, target4); + Diferenca diferenca7 = diferenca; + if (DomainBase.u003cu003eo__18.u003cu003ep__43 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__43 = CallSite<Func<CallSite, object, string>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.Convert(CSharpBinderFlags.None, typeof(string), typeof(DomainBase))); + } + !0 _u0021013 = DomainBase.u003cu003eo__18.u003cu003ep__43.Target; + CallSite<Func<CallSite, object, string>> u003cu003ep_43 = DomainBase.u003cu003eo__18.u003cu003ep__43; + value = fieldInformation.Value; + if (value != null) + { + if (DomainBase.u003cu003eo__18.u003cu003ep__42 == null) + { + DomainBase.u003cu003eo__18.u003cu003ep__42 = CallSite<Func<CallSite, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(CSharpBinderFlags.None, "ToString", null, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + obj4 = DomainBase.u003cu003eo__18.u003cu003ep__42.Target(DomainBase.u003cu003eo__18.u003cu003ep__42, value); + } + else + { + obj4 = null; + } + diferenca7.ValorAtual = _u0021013(u003cu003ep_43, obj4); + diferenca1 = diferenca; + } + diferencas2.Add(diferenca1); + }); + return diferencas3; + } + + public List<Diferenca> Compare(List<ValorOriginal> valoresOriginais) + { + List<FieldInformation> properties = this.GetProperties(); + List<Diferenca> diferencas2 = new List<Diferenca>(); + PropertyInfo[] propertyInfoArray = this.GetType().GetProperties(); + valoresOriginais.ForEach((ValorOriginal x) => { + Diferenca diferenca; + object target; + object obj; + object target1; + object obj1; + object target2; + object obj2; + object target3; + object obj3; + object target4; + Diferenca diferenca1; + string str; + object obj4; + FieldInformation fieldInformation = properties.First<FieldInformation>((FieldInformation k) => k.Name == x.Campo); + if (DomainBase.u003cu003eo__19.u003cu003ep__3 == null) + { + DomainBase.u003cu003eo__19.u003cu003ep__3 = CallSite<Func<CallSite, object, bool>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(CSharpBinderFlags.None, ExpressionType.IsTrue, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + !0 _u00210 = DomainBase.u003cu003eo__19.u003cu003ep__3.Target; + CallSite<Func<CallSite, object, bool>> u003cu003ep_3 = DomainBase.u003cu003eo__19.u003cu003ep__3; + if (DomainBase.u003cu003eo__19.u003cu003ep__0 == null) + { + DomainBase.u003cu003eo__19.u003cu003ep__0 = CallSite<Func<CallSite, object, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(CSharpBinderFlags.None, ExpressionType.Equal, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.Constant, null) }))); + } + object value = DomainBase.u003cu003eo__19.u003cu003ep__0.Target(DomainBase.u003cu003eo__19.u003cu003ep__0, fieldInformation.Value, null); + if (DomainBase.u003cu003eo__19.u003cu003ep__2 == null) + { + DomainBase.u003cu003eo__19.u003cu003ep__2 = CallSite<Func<CallSite, object, bool>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(CSharpBinderFlags.None, ExpressionType.IsFalse, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + if (DomainBase.u003cu003eo__19.u003cu003ep__2.Target(DomainBase.u003cu003eo__19.u003cu003ep__2, value)) + { + target = value; + } + else + { + if (DomainBase.u003cu003eo__19.u003cu003ep__1 == null) + { + DomainBase.u003cu003eo__19.u003cu003ep__1 = CallSite<Func<CallSite, object, bool, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(CSharpBinderFlags.BinaryOperationLogical, ExpressionType.And, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType, null) }))); + } + target = DomainBase.u003cu003eo__19.u003cu003ep__1.Target(DomainBase.u003cu003eo__19.u003cu003ep__1, value, x.ValorAtual == null); + } + if (_u00210(u003cu003ep_3, target)) + { + return; + } + PropertyInfo propertyInfo = propertyInfoArray.FirstOrDefault<PropertyInfo>((PropertyInfo p) => p.Name == x.Campo); + bool flag = (propertyInfo == null ? false : propertyInfo.GetCustomAttributes(typeof(ForceLogAttribute), true).Length != 0); + if (DomainBase.u003cu003eo__19.u003cu003ep__9 == null) + { + DomainBase.u003cu003eo__19.u003cu003ep__9 = CallSite<Func<CallSite, object, bool>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(CSharpBinderFlags.None, ExpressionType.IsTrue, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + !0 _u002101 = DomainBase.u003cu003eo__19.u003cu003ep__9.Target; + CallSite<Func<CallSite, object, bool>> u003cu003ep_9 = DomainBase.u003cu003eo__19.u003cu003ep__9; + if (DomainBase.u003cu003eo__19.u003cu003ep__4 == null) + { + DomainBase.u003cu003eo__19.u003cu003ep__4 = CallSite<Func<CallSite, object, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(CSharpBinderFlags.None, ExpressionType.Equal, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.Constant, null) }))); + } + object target5 = DomainBase.u003cu003eo__19.u003cu003ep__4.Target(DomainBase.u003cu003eo__19.u003cu003ep__4, fieldInformation.Value, null); + if (DomainBase.u003cu003eo__19.u003cu003ep__6 == null) + { + DomainBase.u003cu003eo__19.u003cu003ep__6 = CallSite<Func<CallSite, object, bool>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(CSharpBinderFlags.None, ExpressionType.IsFalse, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + if (DomainBase.u003cu003eo__19.u003cu003ep__6.Target(DomainBase.u003cu003eo__19.u003cu003ep__6, target5)) + { + obj = target5; + } + else + { + if (DomainBase.u003cu003eo__19.u003cu003ep__5 == null) + { + DomainBase.u003cu003eo__19.u003cu003ep__5 = CallSite<Func<CallSite, object, bool, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(CSharpBinderFlags.BinaryOperationLogical, ExpressionType.And, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType, null) }))); + } + obj = DomainBase.u003cu003eo__19.u003cu003ep__5.Target(DomainBase.u003cu003eo__19.u003cu003ep__5, target5, x.ValorAtual != null); + } + value = obj; + if (DomainBase.u003cu003eo__19.u003cu003ep__8 == null) + { + DomainBase.u003cu003eo__19.u003cu003ep__8 = CallSite<Func<CallSite, object, bool>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(CSharpBinderFlags.None, ExpressionType.IsFalse, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + if (DomainBase.u003cu003eo__19.u003cu003ep__8.Target(DomainBase.u003cu003eo__19.u003cu003ep__8, value)) + { + target1 = value; + } + else + { + if (DomainBase.u003cu003eo__19.u003cu003ep__7 == null) + { + DomainBase.u003cu003eo__19.u003cu003ep__7 = CallSite<Func<CallSite, object, bool, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(CSharpBinderFlags.BinaryOperationLogical, ExpressionType.And, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType, null) }))); + } + target1 = DomainBase.u003cu003eo__19.u003cu003ep__7.Target(DomainBase.u003cu003eo__19.u003cu003ep__7, value, !string.IsNullOrWhiteSpace(x.ValorAtual)); + } + if (_u002101(u003cu003ep_9, target1)) + { + diferencas2.Add(new Diferenca() + { + Campo = x.Campo, + Descricao = fieldInformation.Description, + ValorAnterior = x.ValorAtual, + ValorAtual = null + }); + return; + } + if (DomainBase.u003cu003eo__19.u003cu003ep__18 == null) + { + DomainBase.u003cu003eo__19.u003cu003ep__18 = CallSite<Func<CallSite, object, bool>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(CSharpBinderFlags.None, ExpressionType.IsTrue, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + !0 _u002102 = DomainBase.u003cu003eo__19.u003cu003ep__18.Target; + CallSite<Func<CallSite, object, bool>> u003cu003ep_18 = DomainBase.u003cu003eo__19.u003cu003ep__18; + if (DomainBase.u003cu003eo__19.u003cu003ep__10 == null) + { + DomainBase.u003cu003eo__19.u003cu003ep__10 = CallSite<Func<CallSite, object, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(CSharpBinderFlags.None, ExpressionType.NotEqual, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.Constant, null) }))); + } + target5 = DomainBase.u003cu003eo__19.u003cu003ep__10.Target(DomainBase.u003cu003eo__19.u003cu003ep__10, fieldInformation.Value, null); + if (DomainBase.u003cu003eo__19.u003cu003ep__12 == null) + { + DomainBase.u003cu003eo__19.u003cu003ep__12 = CallSite<Func<CallSite, object, bool>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(CSharpBinderFlags.None, ExpressionType.IsFalse, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + if (DomainBase.u003cu003eo__19.u003cu003ep__12.Target(DomainBase.u003cu003eo__19.u003cu003ep__12, target5)) + { + obj1 = target5; + } + else + { + if (DomainBase.u003cu003eo__19.u003cu003ep__11 == null) + { + DomainBase.u003cu003eo__19.u003cu003ep__11 = CallSite<Func<CallSite, object, bool, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(CSharpBinderFlags.BinaryOperationLogical, ExpressionType.And, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType, null) }))); + } + obj1 = DomainBase.u003cu003eo__19.u003cu003ep__11.Target(DomainBase.u003cu003eo__19.u003cu003ep__11, target5, x.ValorAtual == null); + } + value = obj1; + if (DomainBase.u003cu003eo__19.u003cu003ep__17 == null) + { + DomainBase.u003cu003eo__19.u003cu003ep__17 = CallSite<Func<CallSite, object, bool>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(CSharpBinderFlags.None, ExpressionType.IsFalse, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + if (DomainBase.u003cu003eo__19.u003cu003ep__17.Target(DomainBase.u003cu003eo__19.u003cu003ep__17, value)) + { + target2 = value; + } + else + { + if (DomainBase.u003cu003eo__19.u003cu003ep__16 == null) + { + DomainBase.u003cu003eo__19.u003cu003ep__16 = CallSite<Func<CallSite, object, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(CSharpBinderFlags.BinaryOperationLogical, ExpressionType.And, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + !0 _u002103 = DomainBase.u003cu003eo__19.u003cu003ep__16.Target; + CallSite<Func<CallSite, object, object, object>> u003cu003ep_16 = DomainBase.u003cu003eo__19.u003cu003ep__16; + object obj5 = value; + if (DomainBase.u003cu003eo__19.u003cu003ep__15 == null) + { + DomainBase.u003cu003eo__19.u003cu003ep__15 = CallSite<Func<CallSite, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(CSharpBinderFlags.None, ExpressionType.Not, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + !0 _u002104 = DomainBase.u003cu003eo__19.u003cu003ep__15.Target; + CallSite<Func<CallSite, object, object>> u003cu003ep_15 = DomainBase.u003cu003eo__19.u003cu003ep__15; + if (DomainBase.u003cu003eo__19.u003cu003ep__14 == null) + { + DomainBase.u003cu003eo__19.u003cu003ep__14 = CallSite<Func<CallSite, Type, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(CSharpBinderFlags.None, "IsNullOrWhiteSpace", null, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType | CSharpArgumentInfoFlags.IsStaticType, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + !0 _u002105 = DomainBase.u003cu003eo__19.u003cu003ep__14.Target; + CallSite<Func<CallSite, Type, object, object>> u003cu003ep_14 = DomainBase.u003cu003eo__19.u003cu003ep__14; + Type type = typeof(string); + if (DomainBase.u003cu003eo__19.u003cu003ep__13 == null) + { + DomainBase.u003cu003eo__19.u003cu003ep__13 = CallSite<Func<CallSite, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(CSharpBinderFlags.None, "ToString", null, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + target2 = _u002103(u003cu003ep_16, obj5, _u002104(u003cu003ep_15, _u002105(u003cu003ep_14, type, DomainBase.u003cu003eo__19.u003cu003ep__13.Target(DomainBase.u003cu003eo__19.u003cu003ep__13, fieldInformation.Value)))); + } + if (_u002102(u003cu003ep_18, target2)) + { + List<Diferenca> diferencas = diferencas2; + diferenca = new Diferenca() + { + Campo = x.Campo, + Descricao = fieldInformation.Description, + ValorAnterior = null + }; + Diferenca diferenca2 = diferenca; + if (DomainBase.u003cu003eo__19.u003cu003ep__20 == null) + { + DomainBase.u003cu003eo__19.u003cu003ep__20 = CallSite<Func<CallSite, object, string>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.Convert(CSharpBinderFlags.None, typeof(string), typeof(DomainBase))); + } + !0 target6 = DomainBase.u003cu003eo__19.u003cu003ep__20.Target; + CallSite<Func<CallSite, object, string>> u003cu003ep_20 = DomainBase.u003cu003eo__19.u003cu003ep__20; + if (DomainBase.u003cu003eo__19.u003cu003ep__19 == null) + { + DomainBase.u003cu003eo__19.u003cu003ep__19 = CallSite<Func<CallSite, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(CSharpBinderFlags.None, "ToString", null, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + diferenca2.ValorAtual = target6(u003cu003ep_20, DomainBase.u003cu003eo__19.u003cu003ep__19.Target(DomainBase.u003cu003eo__19.u003cu003ep__19, fieldInformation.Value)); + diferencas.Add(diferenca); + return; + } + if (DomainBase.u003cu003eo__19.u003cu003ep__28 == null) + { + DomainBase.u003cu003eo__19.u003cu003ep__28 = CallSite<Func<CallSite, object, bool>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(CSharpBinderFlags.None, ExpressionType.IsTrue, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + !0 _u002106 = DomainBase.u003cu003eo__19.u003cu003ep__28.Target; + CallSite<Func<CallSite, object, bool>> u003cu003ep_28 = DomainBase.u003cu003eo__19.u003cu003ep__28; + if (DomainBase.u003cu003eo__19.u003cu003ep__21 == null) + { + DomainBase.u003cu003eo__19.u003cu003ep__21 = CallSite<Func<CallSite, object, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(CSharpBinderFlags.None, ExpressionType.NotEqual, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.Constant, null) }))); + } + target5 = DomainBase.u003cu003eo__19.u003cu003ep__21.Target(DomainBase.u003cu003eo__19.u003cu003ep__21, fieldInformation.Value, null); + if (DomainBase.u003cu003eo__19.u003cu003ep__25 == null) + { + DomainBase.u003cu003eo__19.u003cu003ep__25 = CallSite<Func<CallSite, object, bool>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(CSharpBinderFlags.None, ExpressionType.IsFalse, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + if (DomainBase.u003cu003eo__19.u003cu003ep__25.Target(DomainBase.u003cu003eo__19.u003cu003ep__25, target5)) + { + obj2 = target5; + } + else + { + if (DomainBase.u003cu003eo__19.u003cu003ep__24 == null) + { + DomainBase.u003cu003eo__19.u003cu003ep__24 = CallSite<Func<CallSite, object, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(CSharpBinderFlags.BinaryOperationLogical, ExpressionType.And, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + !0 target7 = DomainBase.u003cu003eo__19.u003cu003ep__24.Target; + CallSite<Func<CallSite, object, object, object>> u003cu003ep_24 = DomainBase.u003cu003eo__19.u003cu003ep__24; + object obj6 = target5; + if (DomainBase.u003cu003eo__19.u003cu003ep__23 == null) + { + DomainBase.u003cu003eo__19.u003cu003ep__23 = CallSite<Func<CallSite, object, string, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(CSharpBinderFlags.None, ExpressionType.Equal, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType, null) }))); + } + !0 _u002107 = DomainBase.u003cu003eo__19.u003cu003ep__23.Target; + CallSite<Func<CallSite, object, string, object>> u003cu003ep_23 = DomainBase.u003cu003eo__19.u003cu003ep__23; + if (DomainBase.u003cu003eo__19.u003cu003ep__22 == null) + { + DomainBase.u003cu003eo__19.u003cu003ep__22 = CallSite<Func<CallSite, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(CSharpBinderFlags.None, "ToString", null, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + obj2 = target7(u003cu003ep_24, obj6, _u002107(u003cu003ep_23, DomainBase.u003cu003eo__19.u003cu003ep__22.Target(DomainBase.u003cu003eo__19.u003cu003ep__22, fieldInformation.Value), x.ValorAtual)); + } + value = obj2; + if (DomainBase.u003cu003eo__19.u003cu003ep__27 == null) + { + DomainBase.u003cu003eo__19.u003cu003ep__27 = CallSite<Func<CallSite, object, bool>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(CSharpBinderFlags.None, ExpressionType.IsFalse, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + if (DomainBase.u003cu003eo__19.u003cu003ep__27.Target(DomainBase.u003cu003eo__19.u003cu003ep__27, value)) + { + target3 = value; + } + else + { + if (DomainBase.u003cu003eo__19.u003cu003ep__26 == null) + { + DomainBase.u003cu003eo__19.u003cu003ep__26 = CallSite<Func<CallSite, object, bool, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(CSharpBinderFlags.BinaryOperationLogical, ExpressionType.And, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType, null) }))); + } + target3 = DomainBase.u003cu003eo__19.u003cu003ep__26.Target(DomainBase.u003cu003eo__19.u003cu003ep__26, value, !flag); + } + if (_u002106(u003cu003ep_28, target3)) + { + return; + } + List<Diferenca> diferencas1 = diferencas2; + value = fieldInformation.Value; + if (value != null) + { + if (DomainBase.u003cu003eo__19.u003cu003ep__29 == null) + { + DomainBase.u003cu003eo__19.u003cu003ep__29 = CallSite<Func<CallSite, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(CSharpBinderFlags.None, "GetType", null, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + obj3 = DomainBase.u003cu003eo__19.u003cu003ep__29.Target(DomainBase.u003cu003eo__19.u003cu003ep__29, value); + } + else + { + obj3 = null; + } + if (obj3 is DateTime) + { + diferenca = new Diferenca() + { + Campo = x.Campo, + Descricao = x.Descricao, + ValorAnterior = x.ValorAtual + }; + Diferenca diferenca3 = diferenca; + if (DomainBase.u003cu003eo__19.u003cu003ep__31 == null) + { + DomainBase.u003cu003eo__19.u003cu003ep__31 = CallSite<Func<CallSite, object, string>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.Convert(CSharpBinderFlags.None, typeof(string), typeof(DomainBase))); + } + !0 target8 = DomainBase.u003cu003eo__19.u003cu003ep__31.Target; + CallSite<Func<CallSite, object, string>> u003cu003ep_31 = DomainBase.u003cu003eo__19.u003cu003ep__31; + value = fieldInformation.Value; + if (value != null) + { + if (DomainBase.u003cu003eo__19.u003cu003ep__30 == null) + { + DomainBase.u003cu003eo__19.u003cu003ep__30 = CallSite<Func<CallSite, object, string, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(CSharpBinderFlags.None, "ToString", null, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType | CSharpArgumentInfoFlags.Constant, null) }))); + } + target4 = DomainBase.u003cu003eo__19.u003cu003ep__30.Target(DomainBase.u003cu003eo__19.u003cu003ep__30, value, "G"); + } + else + { + target4 = null; + } + diferenca3.ValorAtual = target8(u003cu003ep_31, target4); + diferenca1 = diferenca; + } + else + { + diferenca = new Diferenca() + { + Campo = x.Campo, + Descricao = x.Descricao + }; + Diferenca diferenca4 = diferenca; + string valorAtual = x.ValorAtual; + if (valorAtual != null) + { + str = valorAtual.ToString(); + } + else + { + str = null; + } + diferenca4.ValorAnterior = str; + Diferenca diferenca5 = diferenca; + if (DomainBase.u003cu003eo__19.u003cu003ep__33 == null) + { + DomainBase.u003cu003eo__19.u003cu003ep__33 = CallSite<Func<CallSite, object, string>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.Convert(CSharpBinderFlags.None, typeof(string), typeof(DomainBase))); + } + !0 _u002108 = DomainBase.u003cu003eo__19.u003cu003ep__33.Target; + CallSite<Func<CallSite, object, string>> u003cu003ep_33 = DomainBase.u003cu003eo__19.u003cu003ep__33; + value = fieldInformation.Value; + if (value != null) + { + if (DomainBase.u003cu003eo__19.u003cu003ep__32 == null) + { + DomainBase.u003cu003eo__19.u003cu003ep__32 = CallSite<Func<CallSite, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(CSharpBinderFlags.None, "ToString", null, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + obj4 = DomainBase.u003cu003eo__19.u003cu003ep__32.Target(DomainBase.u003cu003eo__19.u003cu003ep__32, value); + } + else + { + obj4 = null; + } + diferenca5.ValorAtual = _u002108(u003cu003ep_33, obj4); + diferenca1 = diferenca; + } + diferencas1.Add(diferenca1); + }); + return diferencas2; + } + + public static void Copy<TU, T>(TU dest, T source) + { + List<PropertyInfo> list = ( + from in (IEnumerable<PropertyInfo>)typeof(T).GetProperties() + where x.CanRead + select ).ToList<PropertyInfo>(); + List<PropertyInfo> propertyInfos = ( + from in (IEnumerable<PropertyInfo>)typeof(TU).GetProperties() + where x.CanWrite + select ).ToList<PropertyInfo>(); + foreach (PropertyInfo propertyInfo in list) + { + if (!propertyInfos.Any<PropertyInfo>((PropertyInfo x) => x.Name == propertyInfo.Name)) + { + continue; + } + propertyInfos.First<PropertyInfo>((PropertyInfo x) => x.Name == propertyInfo.Name).SetValue(dest, propertyInfo.GetValue(source, null), null); + } + } + + private bool GetDefaultAttribute(PropertyInfo info) + { + return info.GetCustomAttributes(typeof(NameAttribute), true).Length != 0; + } + + private string GetDescriptionAttribute(PropertyInfo info) + { + if (info == null) + { + return ""; + } + object[] customAttributes = info.GetCustomAttributes(typeof(DescriptionAttribute), true); + if (customAttributes.Length == 0) + { + return info.Name.ToUpper(); + } + return ((DescriptionAttribute)customAttributes[0]).Description; + } + + private bool? GetLogAttribute(PropertyInfo info) + { + object[] customAttributes = info.GetCustomAttributes(typeof(LogAttribute), true); + if (customAttributes.Length == 0) + { + return null; + } + return new bool?(((LogAttribute)customAttributes[0]).Description); + } + + public List<FieldInformation> GetProperties(object obj) + { + return obj.GetType().GetProperties().Where<PropertyInfo>((PropertyInfo x) => { + if (this.HasValidate(x.GetValue(obj))) + { + return false; + } + return this.GetLogAttribute(x).GetValueOrDefault(); + }).Select<PropertyInfo, FieldInformation>((PropertyInfo key) => new FieldInformation() + { + Name = key.Name, + Description = this.GetDescriptionAttribute(key), + Value = key.GetValue(obj) + }).ToList<FieldInformation>(); + } + + public List<FieldInformation> GetProperties() + { + List<FieldInformation> fieldInformations = new List<FieldInformation>(); + this.GetType().GetProperties().ToList<PropertyInfo>().ForEach((PropertyInfo x) => { + if (x.Name == "ValidationEvent") + { + return; + } + bool? logAttribute = this.GetLogAttribute(x); + if (logAttribute.HasValue) + { + bool? nullable = logAttribute; + if (!nullable.GetValueOrDefault() & nullable.HasValue) + { + return; + } + } + object value = x.GetValue(this); + if (this.HasValidate(value)) + { + fieldInformations.AddRange(this.GetPropertiesChield(value, this.GetDescriptionAttribute(x), logAttribute, true)); + } + else + { + FieldInformation property = this.GetProperty(x, value, logAttribute, null); + if (property != null) + { + fieldInformations.Add(property); + return; + } + } + }); + return fieldInformations; + } + + private List<FieldInformation> GetPropertiesChield(dynamic obj, string description, bool? log, bool defaultInfo = false) + { + List<FieldInformation> fieldInformations = new List<FieldInformation>(); + if (obj == (dynamic)null) + { + return fieldInformations; + } + foreach (dynamic obj1 in (IEnumerable)obj.GetType().GetProperties()) + { + if (obj1.Name == "ValidationEvent") + { + continue; + } + if ((!defaultInfo ? defaultInfo : defaultInfo & (dynamic)(!this.GetDefaultAttribute(obj1)))) + { + continue; + } + log = (bool?)this.GetLogAttribute(obj1); + if (log.HasValue) + { + bool? nullable = log; + if (!nullable.GetValueOrDefault() & nullable.HasValue) + { + continue; + } + } + dynamic obj2 = obj1.GetValue(obj); + dynamic obj3 = obj2 != (dynamic)null; + if ((!obj3 ? obj3 == null : (obj3 & this.HasValidate(obj2)) == 0)) + { + dynamic obj4 = this.GetProperty(obj1, obj2, log, description); + if (obj4 == (dynamic)null) + { + continue; + } + fieldInformations.Add(obj4); + } + else + { + fieldInformations.AddRange(this.GetPropertiesChield(obj2, this.GetDescriptionAttribute(obj1), log, true)); + } + } + return fieldInformations; + } + + public FieldInformation GetProperty(PropertyInfo property, dynamic value, bool? log, string description = null) + { + if (log.HasValue) + { + bool? nullable = log; + if (!(!nullable.GetValueOrDefault() & nullable.HasValue)) + { + return new FieldInformation() + { + Name = property.Name, + Description = description ?? this.GetDescriptionAttribute(property), + Value = value + }; + } + } + return null; + } + + public List<ValorOriginal> GetValorOriginal() + { + return this.GetProperties().Select<FieldInformation, ValorOriginal>((FieldInformation x) => { + object value; + object target; + ValorOriginal valorOriginal = new ValorOriginal() + { + Campo = x.Name, + Descricao = x.Description + }; + ValorOriginal valorOriginal1 = valorOriginal; + if (DomainBase.u003cu003eo__17.u003cu003ep__5 == null) + { + DomainBase.u003cu003eo__17.u003cu003ep__5 = CallSite<Func<CallSite, object, string>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.Convert(CSharpBinderFlags.None, typeof(string), typeof(DomainBase))); + } + !0 _u00210 = DomainBase.u003cu003eo__17.u003cu003ep__5.Target; + CallSite<Func<CallSite, object, string>> u003cu003ep_5 = DomainBase.u003cu003eo__17.u003cu003ep__5; + if (DomainBase.u003cu003eo__17.u003cu003ep__1 == null) + { + DomainBase.u003cu003eo__17.u003cu003ep__1 = CallSite<Func<CallSite, object, bool>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(CSharpBinderFlags.None, ExpressionType.IsTrue, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + !0 target1 = DomainBase.u003cu003eo__17.u003cu003ep__1.Target; + CallSite<Func<CallSite, object, bool>> u003cu003ep_1 = DomainBase.u003cu003eo__17.u003cu003ep__1; + if (DomainBase.u003cu003eo__17.u003cu003ep__0 == null) + { + DomainBase.u003cu003eo__17.u003cu003ep__0 = CallSite<Func<CallSite, object, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(CSharpBinderFlags.None, ExpressionType.NotEqual, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.Constant, null) }))); + } + if (target1(u003cu003ep_1, DomainBase.u003cu003eo__17.u003cu003ep__0.Target(DomainBase.u003cu003eo__17.u003cu003ep__0, x.Value, null))) + { + if (DomainBase.u003cu003eo__17.u003cu003ep__2 == null) + { + DomainBase.u003cu003eo__17.u003cu003ep__2 = CallSite<Func<CallSite, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(CSharpBinderFlags.None, "GetType", null, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + if (DomainBase.u003cu003eo__17.u003cu003ep__2.Target(DomainBase.u003cu003eo__17.u003cu003ep__2, x.Value) is DateTime) + { + value = x.Value; + if (value != null) + { + if (DomainBase.u003cu003eo__17.u003cu003ep__3 == null) + { + DomainBase.u003cu003eo__17.u003cu003ep__3 = CallSite<Func<CallSite, object, string, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(CSharpBinderFlags.None, "ToString", null, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType | CSharpArgumentInfoFlags.Constant, null) }))); + } + target = DomainBase.u003cu003eo__17.u003cu003ep__3.Target(DomainBase.u003cu003eo__17.u003cu003ep__3, value, "G"); + } + else + { + target = null; + } + } + else + { + value = x.Value; + if (value != null) + { + if (DomainBase.u003cu003eo__17.u003cu003ep__4 == null) + { + DomainBase.u003cu003eo__17.u003cu003ep__4 = CallSite<Func<CallSite, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(CSharpBinderFlags.None, "ToString", null, typeof(DomainBase), (IEnumerable<CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); + } + target = DomainBase.u003cu003eo__17.u003cu003ep__4.Target(DomainBase.u003cu003eo__17.u003cu003ep__4, value); + } + else + { + target = null; + } + } + } + else + { + target = null; + } + valorOriginal1.ValorAtual = _u00210(u003cu003ep_5, target); + return valorOriginal; + }).ToList<ValorOriginal>(); + } + + public bool HasChange() + { + List<FieldInformation> properties = this.GetProperties(); + List<FieldInformation> fieldInformations = this._originalValues; + return !properties.All<FieldInformation>(new Func<FieldInformation, bool>(fieldInformations.Contains)); + } + + public bool HasChange(string property) + { + IEnumerable<FieldInformation> name = + from x in this._originalValues + where x.Name == property + select x; + return !this.GetProperties().All<FieldInformation>(new Func<FieldInformation, bool>(name.Contains<FieldInformation>)); + } + + public bool HasProperty(object objectToCheck, string propertyName) + { + if (objectToCheck == null) + { + return false; + } + return objectToCheck.GetType().GetProperty(propertyName) != null; + } + + public bool HasValidate(object objectToCheck) + { + if (objectToCheck == null) + { + return false; + } + return objectToCheck.GetType().GetProperty("ValidationEvent") != null; + } + + public void Initialize() + { + this._originalValues = this.GetProperties(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Generic/EmailBase.cs b/Codemerx/Gestor.Model/Model.Domain.Generic/EmailBase.cs new file mode 100644 index 0000000..96eccc8 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Generic/EmailBase.cs @@ -0,0 +1,32 @@ +using Gestor.Model.Attributes; +using System; + +namespace Gestor.Model.Domain.Generic +{ + public class EmailBase : DomainBase + { + private string _email; + + [Log(true)] + public string Email + { + get + { + string str = this._email; + if (str == null) + { + return null; + } + return str.ToLower().Trim(); + } + set + { + this._email = value; + } + } + + public EmailBase() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Generic/EnderecoBase.cs b/Codemerx/Gestor.Model/Model.Domain.Generic/EnderecoBase.cs new file mode 100644 index 0000000..964fb70 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Generic/EnderecoBase.cs @@ -0,0 +1,128 @@ +using Gestor.Model.Attributes; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using System.Text.RegularExpressions; + +namespace Gestor.Model.Domain.Generic +{ + public class EnderecoBase : DomainBase + { + private string _cep; + + private string _endereco; + + private string _numero; + + private string _bairro; + + private string _cidade; + + private string _estado; + + [Log(true)] + public string Bairro + { + get + { + return this._bairro; + } + set + { + this._bairro = value; + } + } + + [Log(true)] + public string Cep + { + get + { + if (this._cep == null || !Regex.IsMatch(this._cep, "[0-9]+")) + { + return ""; + } + return this._cep.Trim(); + } + set + { + this._cep = value; + } + } + + [Log(true)] + public string Cidade + { + get + { + return this._cidade; + } + set + { + this._cidade = value; + } + } + + [Log(true)] + public string Complemento + { + get; + set; + } + + [Description("ENDEREÇO")] + [Log(true)] + public string Endereco + { + get + { + return this._endereco; + } + set + { + this._endereco = value; + } + } + + [Log(true)] + public string Estado + { + get + { + string str = this._estado; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._estado = value; + } + } + + [Description("NÚMERO")] + [Log(true)] + public string Numero + { + get + { + string str = this._numero; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._numero = value; + } + } + + public EnderecoBase() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Generic/FieldInformation.cs b/Codemerx/Gestor.Model/Model.Domain.Generic/FieldInformation.cs new file mode 100644 index 0000000..de124b5 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Generic/FieldInformation.cs @@ -0,0 +1,30 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Generic +{ + public class FieldInformation + { + public string Description + { + get; + set; + } + + public string Name + { + get; + set; + } + + public dynamic Value + { + get; + set; + } + + public FieldInformation() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Generic/IDomain.cs b/Codemerx/Gestor.Model/Model.Domain.Generic/IDomain.cs new file mode 100644 index 0000000..c6a2ca0 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Generic/IDomain.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; + +namespace Gestor.Model.Domain.Generic +{ + public interface IDomain + { + Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get; + } + + List<KeyValuePair<string, string>> Validate(); + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Generic/TelefoneBase.cs b/Codemerx/Gestor.Model/Model.Domain.Generic/TelefoneBase.cs new file mode 100644 index 0000000..23f0cbe --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Generic/TelefoneBase.cs @@ -0,0 +1,82 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Generic +{ + public class TelefoneBase : DomainBase + { + private string _numero; + + private string _prefixo; + + [Log(true)] + public string Numero + { + get + { + string str = this._numero; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._numero = value; + } + } + + [Log(true)] + public string Prefixo + { + get + { + string str = this._prefixo; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._prefixo = value; + } + } + + [Log(true)] + public TipoTelefone? Tipo + { + get; + set; + } + + public TelefoneBase() + { + } + + public List<KeyValuePair<string, string>> ValidateBase(bool obrigatorio = true) + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (!this.Tipo.HasValue || this.Tipo.GetValueOrDefault() == TipoTelefone.Gratuita || this.Tipo.GetValueOrDefault() == TipoTelefone.Internacional || this.Tipo.GetValueOrDefault() == TipoTelefone.Outros || this.Tipo.GetValueOrDefault() == TipoTelefone.Whatsapp || this.Tipo.GetValueOrDefault() == TipoTelefone.TarifaUnica || this.Tipo.GetValueOrDefault() == TipoTelefone.Comercial) + { + return keyValuePairs; + } + if (!string.IsNullOrWhiteSpace(this.Prefixo) && !this.Prefixo.ValidacaoPrefixo()) + { + keyValuePairs.AddValue<string, string>("Prefixo|DDD", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.Numero) && !this.Numero.ValidacaoTelefone()) + { + keyValuePairs.AddValue<string, string>("Numero|TELEFONE", Messages.Invalido, true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Generic/ValorOriginal.cs b/Codemerx/Gestor.Model/Model.Domain.Generic/ValorOriginal.cs new file mode 100644 index 0000000..7e2dbb3 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Generic/ValorOriginal.cs @@ -0,0 +1,30 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Generic +{ + public class ValorOriginal + { + public string Campo + { + get; + set; + } + + public string Descricao + { + get; + set; + } + + public string ValorAtual + { + get; + set; + } + + public ValorOriginal() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.MalaDireta/Copia.cs b/Codemerx/Gestor.Model/Model.Domain.MalaDireta/Copia.cs new file mode 100644 index 0000000..6701405 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.MalaDireta/Copia.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.MalaDireta +{ + public class Copia + { + public List<string> CopiaComum + { + get; + set; + } + + public List<string> CopiaOculta + { + get; + set; + } + + public Copia() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.MalaDireta/MalaDireta.cs b/Codemerx/Gestor.Model/Model.Domain.MalaDireta/MalaDireta.cs new file mode 100644 index 0000000..67f8dcd --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.MalaDireta/MalaDireta.cs @@ -0,0 +1,118 @@ +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.MalaDireta +{ + public class MalaDireta + { + public Documento Apolice + { + get; + set; + } + + public List<IndiceArquivoDigital> ArquivoDigital + { + get; + set; + } + + public string Assunto + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Cliente Cliente + { + get; + set; + } + + public Gestor.Model.Domain.MalaDireta.Copia Copia + { + get; + set; + } + + public string Corpo + { + get; + set; + } + + public string Email + { + get; + set; + } + + public bool? Enviado + { + get; + set; + } + + public string InfoEnvio + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Item Item + { + get; + set; + } + + public int Ordem + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Parcela Parcela + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Prospeccao Prospeccao + { + get; + set; + } + + public Gestor.Model.Common.Relatorio Relatorio + { + get; + set; + } + + public bool Selecionado + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Sinistro Sinistro + { + get; + set; + } + + public TipoTela Tela + { + get; + set; + } + + public MalaDireta() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.MalaDireta/ModeloMalaDireta.cs b/Codemerx/Gestor.Model/Model.Domain.MalaDireta/ModeloMalaDireta.cs new file mode 100644 index 0000000..1a3ce4a --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.MalaDireta/ModeloMalaDireta.cs @@ -0,0 +1,53 @@ +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.MalaDireta +{ + public class ModeloMalaDireta : DomainBase, IDomain + { + public string Assunto + { + get; + set; + } + + public string Corpo + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + ModeloMalaDireta modeloMalaDiretum = this; + return new Func<List<KeyValuePair<string, string>>>(modeloMalaDiretum.Validate); + } + } + + public ModeloMalaDireta() + { + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (string.IsNullOrWhiteSpace(this.Assunto)) + { + keyValuePairs.AddValue<string, string>("Assunto", Messages.Obrigatorio, true); + } + if (string.IsNullOrWhiteSpace(this.Corpo)) + { + keyValuePairs.AddValue<string, string>("Corpo", Messages.Obrigatorio, true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.MalaDireta/VariaveisMalaDireta.cs b/Codemerx/Gestor.Model/Model.Domain.MalaDireta/VariaveisMalaDireta.cs new file mode 100644 index 0000000..8794d13 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.MalaDireta/VariaveisMalaDireta.cs @@ -0,0 +1,87 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.Domain.MalaDireta +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum VariaveisMalaDireta + { + [Description("DATA ATUAL")] + [Entity("<|DATA|>")] + Data, + [Description("NOME DO CLIENTE")] + [Entity("<|CLIENTE|>")] + Cliente, + [Description("CPF/CNPJ")] + [Entity("<|CPFCNPJ|>")] + Documento, + [Description("NÚMERO PROPOSTA")] + [Entity("<|PROPOSTA|>")] + Proposta, + [Description("NÚMERO APÓLICE")] + [Entity("<|APOLICE|>")] + Apolice, + [Description("RAMO")] + [Entity("<|RAMO|>")] + Ramo, + [Description("SEGURADORA")] + [Entity("<|SEGURADORA|>")] + Seguradora, + [Description("VIGÊNCIA INICIAL")] + [Entity("<|VIGENCIA1|>")] + Vigencia1, + [Description("VIGÊNCIA FINAL")] + [Entity("<|VIGENCIA2|>")] + Vigencia2, + [Description("VENCIMENTO PARCELA")] + [Entity("<|VENCIMENTO|>")] + Vencimento, + [Description("VALOR PARCELA")] + [Entity("<|VALOR|>")] + Valor, + [Description("DESCRIÇÃO ITEM")] + [Entity("<|ITEM|>")] + Item, + [Description("NÚMERO SINISTRO")] + [Entity("<|SINISTRO|>")] + Sinistro, + [Description("NÚMERO DA PARCELA")] + [Entity("<|NUMPARCELA|>")] + NumParcela, + [Description("ANIVERSÁRIO")] + [Entity("<|ANIVERSARIO|>")] + Aniversario, + [Description("NASCIMENTO")] + [Entity("<|NASCIMENTO|>")] + Nascimento, + [Description("VENCIMENTO CNH")] + [Entity("<|VENCTOCNH|>")] + VencimentoCnh, + [Description("LINK ASSINATURA ELETRÔNICA")] + [Entity("<|LINKASSINATURA|>")] + LinkAssinatura, + [Description("LINK CARTÃO ELETRÔNICO")] + [Entity("<|LINKVISITA|>")] + LinkVisita, + [Description("LINK CARTÃO ASSISTÊNCIA")] + [Entity("<|LINKASSISTENCIA|>")] + LinkAssistencia, + [Description("PRÊMIO LIQUIDO")] + [Entity("<|LIQUIDO|>")] + Liquido, + [Description("PRÊMIO TOTAL")] + [Entity("<|TOTAL|>")] + Total, + [Description("FORMA DE PAGAMENTO")] + [Entity("<|PAGAMENTO|>")] + Pagamento, + [Description("NÚMERO DE PARCELAS")] + [Entity("<|NUMERODEPARCELAS|>")] + NumDeParcelas, + [Description("VALOR DAS PARCELAS")] + [Entity("<|VALORDASPARCELAS|>")] + ValorDasParcelas + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/ApolicePendente/ApolicePendente.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/ApolicePendente/ApolicePendente.cs new file mode 100644 index 0000000..76c9930 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/ApolicePendente/ApolicePendente.cs @@ -0,0 +1,244 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Seguros; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.ApolicePendente +{ + public class ApolicePendente + { + [Description("AGÊNCIA")] + public string Agencia + { + get; + set; + } + + [Description("BANCO")] + public string Banco + { + get; + set; + } + + [Description("CLIENTE")] + public string Cliente + { + get; + set; + } + + [Description("COMISSÃO")] + [Tipo("PERCENTUAL")] + public decimal Comissao + { + get; + set; + } + + [Description("CONTA")] + public string Conta + { + get; + set; + } + + [Description("DATA CONTROLE")] + public DateTime? DataControle + { + get; + set; + } + + [Tipo("INVALID")] + public Gestor.Model.Domain.Seguros.Documento Documento + { + get; + set; + } + + [Description("DOCUMENTO DO CLIENTE")] + public string DocumentoCli + { + get; + set; + } + + [Description("FILIAL")] + public string Empresa + { + get; + set; + } + + [Description("ESTIPULANTE")] + public string Estipulante + { + get; + set; + } + + [Tipo("INVALID")] + public long IdEmpresa + { + get; + set; + } + + [Description("ITEM")] + public string Item + { + get; + set; + } + + [Description("TIPO RENOVAÇÃO")] + public string Negocio + { + get; + set; + } + + [Description("PASTA")] + public string Pasta + { + get; + set; + } + + [Description("PASTA CLIENTE")] + public string PastaCliente + { + get; + set; + } + + [Description("PEDIDO ENDOSSO")] + public string PedidoEndosso + { + get; + set; + } + + [Description("PENDÊNCIA (DIAS)")] + public int Pendencia + { + get; + set; + } + + [Description("PRÊMIO LÍQUIDO")] + [Tipo("VALOR")] + public decimal PremioLiquido + { + get; + set; + } + + [Description("PRÊMIO TOTAL")] + [Tipo("VALOR")] + public decimal PremioTotal + { + get; + set; + } + + [Description("PRODUTO")] + public string Produto + { + get; + set; + } + + [Description("PROPOSTA")] + public string Proposta + { + get; + set; + } + + [Description("RAMO")] + public string Ramo + { + get; + set; + } + + [Description("SEGURADORA")] + public string Seguradora + { + get; + set; + } + + [Tipo("INVALID")] + public bool Selecionado + { + get; + set; + } + + [Description("STATUS")] + public string Status + { + get; + set; + } + + [Description("STATUS APÓLICE")] + public string StatusApolice + { + get; + set; + } + + [Tipo("INVALID")] + public int Tipo + { + get; + set; + } + + [Description("TODOS VENDEDORES")] + public string TodosVendedores + { + get; + set; + } + + [Description("VENDEDOR PRINCIPAL")] + public string Vendedor + { + get; + set; + } + + [Description("VIGÊNCIA FINAL")] + [Tipo("DATA?")] + public DateTime? VigenciaFinal + { + get; + set; + } + + [Description("VIGÊNCIA INICIAL")] + [Tipo("DATA")] + public DateTime VigenciaInicial + { + get; + set; + } + + [Tipo("INVALID")] + public bool Vinculo + { + get; + set; + } + + public ApolicePendente() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/ApolicePendente/ContainerApolicePendente.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/ApolicePendente/ContainerApolicePendente.cs new file mode 100644 index 0000000..fe24dcf --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/ApolicePendente/ContainerApolicePendente.cs @@ -0,0 +1,32 @@ +using Gestor.Model.Domain.Relatorios; +using System; +using System.Collections.ObjectModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.ApolicePendente +{ + public class ContainerApolicePendente + { + public string Agrupamento + { + get; + set; + } + + public ObservableCollection<Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente> Analitico + { + get; + set; + } + + public ObservableCollection<Gestor.Model.Domain.Relatorios.Sintetico> Sintetico + { + get; + set; + } + + public ContainerApolicePendente() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/Auditoria/Auditoria.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Auditoria/Auditoria.cs new file mode 100644 index 0000000..cd00b0e --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Auditoria/Auditoria.cs @@ -0,0 +1,221 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Seguros; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.Auditoria +{ + public class Auditoria + { + [Description("APÓLICE")] + public string Apolice + { + get; + set; + } + + [Description("CLIENTE")] + public string Cliente + { + get; + set; + } + + [Description("COMISSÃO")] + [Tipo("PERCENTUAL")] + public decimal Comissao + { + get; + set; + } + + [Description("COMISSÃO PENDENTE")] + [Tipo("VALOR")] + public decimal ComissaoPendente + { + get; + set; + } + + [Description("COMISSÃO PREVISTA")] + [Tipo("VALOR")] + public decimal ComissaoPrevista + { + get; + set; + } + + [Description("COMISSÃO RECEBIDA")] + [Tipo("VALOR")] + public decimal ComissaoRecebida + { + get; + set; + } + + [Description("RECEBIDO POR COMPLETO")] + public string Completo + { + get; + set; + } + + [Description("DATA CONTROLE")] + [Tipo("DATA?")] + public DateTime? DataControle + { + get; + set; + } + + [Tipo("INVALID")] + public Gestor.Model.Domain.Seguros.Documento Documento + { + get; + set; + } + + [Description("ENDOSSO")] + public string Endosso + { + get; + set; + } + + [Description("ESTIPULANTE")] + public string Estipulante + { + get; + set; + } + + [Description("ITEM")] + public string Item + { + get; + set; + } + + [Description("PASTA")] + public string Pasta + { + get; + set; + } + + [Description("PASTA CLIENTE")] + public string PastaCliente + { + get; + set; + } + + [Description("PRÊMIO ADICIONAL")] + [Tipo("VALOR")] + public decimal PremioAdicional + { + get; + set; + } + + [Description("PRÊMIO LÍQUIDO")] + [Tipo("VALOR")] + public decimal PremioLiquido + { + get; + set; + } + + [Description("PRÊMIO TOTAL")] + [Tipo("VALOR")] + public decimal PremioTotal + { + get; + set; + } + + [Description("PRODUTO")] + public string Produto + { + get; + set; + } + + [Description("RAMO")] + public string Ramo + { + get; + set; + } + + [Description("SEGURADORA")] + public string Seguradora + { + get; + set; + } + + [Tipo("INVALID")] + public bool Selecionado + { + get; + set; + } + + [Description("STATUS")] + public string Status + { + get; + set; + } + + [Description("STATUS APÓLICE")] + public string StatusApolice + { + get; + set; + } + + [Tipo("INVALID")] + public int Tipo + { + get; + set; + } + + [Description("TODOS VENDEDORES")] + public string TodosVendedores + { + get; + set; + } + + [Description("VENDEDOR PRINCIPAL")] + public string Vendedor + { + get; + set; + } + + [Description("VIGÊNCIA FINAL")] + [Tipo("DATA?")] + public DateTime? VigenciaFinal + { + get; + set; + } + + [Description("VIGÊNCIA INICIAL")] + [Tipo("DATA")] + public DateTime VigenciaInicial + { + get; + set; + } + + public Auditoria() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/CartaoSegurado.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/CartaoSegurado.cs new file mode 100644 index 0000000..e0edb18 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/CartaoSegurado.cs @@ -0,0 +1,60 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios +{ + public class CartaoSegurado + { + public string Apolice + { + get; + set; + } + + public string Assistencia + { + get; + set; + } + + public string Item + { + get; + set; + } + + public string LinkApolice + { + get; + set; + } + + public string Nome + { + get; + set; + } + + public string Seguradora + { + get; + set; + } + + public string TelefoneCorretor + { + get; + set; + } + + public string Vigencia + { + get; + set; + } + + public CartaoSegurado() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/Classificacao/Classificacao.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Classificacao/Classificacao.cs new file mode 100644 index 0000000..adc8ba7 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Classificacao/Classificacao.cs @@ -0,0 +1,71 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Seguros; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.Classificacao +{ + public class Classificacao + { + [Description("ATIVO")] + public string Ativo + { + get; + set; + } + + [Description("COMISSÃO")] + public string Comissao + { + get; + set; + } + + [Tipo("INVALID")] + public Gestor.Model.Domain.Seguros.Cliente EntidadeCliente + { + get; + set; + } + + [Description("GERAL")] + public string Geral + { + get; + set; + } + + [Description("NOME")] + public string Nome + { + get; + set; + } + + [Description("PREMIO LIQUIDO")] + public string Premioliquido + { + get; + set; + } + + [Description("RESULTADO")] + public string Resultado + { + get; + set; + } + + [Tipo("INVALID")] + public bool Selecionado + { + get; + set; + } + + public Classificacao() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/Cliente/SinteticoClientes.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Cliente/SinteticoClientes.cs new file mode 100644 index 0000000..a3ca90d --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Cliente/SinteticoClientes.cs @@ -0,0 +1,28 @@ +using Gestor.Model.Attributes; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.Cliente +{ + public class SinteticoClientes + { + public string Descricao + { + get; + set; + } + + [Description("TOTAL DE CLIENTES")] + [Tipo("QUANTIDADE")] + public decimal Total + { + get; + set; + } + + public SinteticoClientes() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/ClientesAtivosInativos/ClientesAtivosInativos.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/ClientesAtivosInativos/ClientesAtivosInativos.cs new file mode 100644 index 0000000..26cf93b --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/ClientesAtivosInativos/ClientesAtivosInativos.cs @@ -0,0 +1,477 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Seguros; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.ClientesAtivosInativos +{ + public class ClientesAtivosInativos + { + private string _nome; + + private string _ramo; + + private string _endereco; + + private string _bairro; + + private string _complemento; + + private string _cidade; + + private string _estado; + + private string _email; + + private string _vendedor; + + [Description("ANIVERSÁRIO")] + public string Aniversario + { + get; + set; + } + + [Description("ATIVO")] + public string Ativo + { + get; + set; + } + + [Description("BAIRRO")] + public string Bairro + { + get + { + return this._bairro; + } + set + { + string upper; + if (value != null) + { + string str = value.Trim(); + if (str != null) + { + upper = str.ToUpper(); + } + else + { + upper = null; + } + } + else + { + upper = null; + } + this._bairro = upper; + } + } + + [Description("CEP")] + public string Cep + { + get; + set; + } + + [Description("CIDADE")] + public string Cidade + { + get + { + return this._cidade; + } + set + { + string upper; + if (value != null) + { + string str = value.Trim(); + if (str != null) + { + upper = str.ToUpper(); + } + else + { + upper = null; + } + } + else + { + upper = null; + } + this._cidade = upper; + } + } + + [Description("CLIENTE DESDE")] + [Tipo("DATA?")] + public DateTime? ClienteDesde + { + get; + set; + } + + [Description("COMPLEMENTO")] + public string Complemento + { + get + { + return this._complemento; + } + set + { + string upper; + if (value != null) + { + string str = value.Trim(); + if (str != null) + { + upper = str.ToUpper(); + } + else + { + upper = null; + } + } + else + { + upper = null; + } + this._complemento = upper; + } + } + + [Description("CPF/CNPJ")] + public string Documento + { + get; + set; + } + + [Description("E-MAIL")] + public string Email + { + get + { + return this._email; + } + set + { + string lower; + if (value != null) + { + string str = value.Trim(); + if (str != null) + { + lower = str.ToLower(); + } + else + { + lower = null; + } + } + else + { + lower = null; + } + this._email = lower; + } + } + + [Description("FILIAL")] + public string Empresa + { + get; + set; + } + + [Description("ENDEREÇO")] + public string Endereco + { + get + { + return this._endereco; + } + set + { + string upper; + if (value != null) + { + string str = value.Trim(); + if (str != null) + { + upper = str.ToUpper(); + } + else + { + upper = null; + } + } + else + { + upper = null; + } + this._endereco = upper; + } + } + + [Tipo("INVALID")] + public Gestor.Model.Domain.Seguros.Cliente EntidadeCliente + { + get; + set; + } + + [Description("ESTADO")] + public string Estado + { + get + { + return this._estado; + } + set + { + string upper; + if (value != null) + { + string str = value.Trim(); + if (str != null) + { + upper = str.ToUpper(); + } + else + { + upper = null; + } + } + else + { + upper = null; + } + this._estado = upper; + } + } + + [Description("ESTADO CIVIL")] + public string EstadoCivil + { + get; + set; + } + + [Description("ESTIPULANTES")] + public string Estipulantes + { + get; + set; + } + + [Description("ID")] + [Tipo("INVALID")] + public long Id + { + get; + set; + } + + [Description("ANOS DE IDADE")] + [Tipo("QUANTIDADE?")] + public int? Idade + { + get; + set; + } + + [Tipo("INVALID")] + public long IdEmpresa + { + get; + set; + } + + [Description("NASCIMENTO")] + [Tipo("DATA?")] + public DateTime? Nascimento + { + get; + set; + } + + [Description("CLIENTE")] + public string Nome + { + get + { + return this._nome; + } + set + { + string upper; + if (value != null) + { + string str = value.Trim(); + if (str != null) + { + upper = str.ToUpper(); + } + else + { + upper = null; + } + } + else + { + upper = null; + } + this._nome = upper; + } + } + + [Description("NÚMERO")] + public string Numero + { + get; + set; + } + + [Description("PARENTESCO")] + public string Parentesco + { + get; + set; + } + + [Description("PASTA CLIENTE")] + public string PastaCliente + { + get; + set; + } + + [Description("PROFISSÃO")] + public string Profissao + { + get; + set; + } + + [Description("RAMO")] + public string Ramo + { + get + { + return this._ramo; + } + set + { + string upper; + if (value != null) + { + string str = value.Trim(); + if (str != null) + { + upper = str.ToUpper(); + } + else + { + upper = null; + } + } + else + { + upper = null; + } + this._ramo = upper; + } + } + + [Description("RECEBER E-MAIL")] + public string RecebeEmail + { + get; + set; + } + + [Description("RENDA MENSAL")] + [Tipo("VALOR")] + public decimal RendaMensal + { + get; + set; + } + + [Tipo("INVALID")] + public bool Selecionado + { + get; + set; + } + + [Description("SEXO")] + public string Sexo + { + get; + set; + } + + [Description("TELEFONE")] + public string Telefone + { + get; + set; + } + + [Description("TIPO DE PESSOA")] + public string TipoPessoa + { + get; + set; + } + + [Description("VENCIMENTO CNH")] + [Tipo("DATA?")] + public DateTime? VencimentoCnh + { + get; + set; + } + + [Description("VENDEDOR")] + public string Vendedor + { + get + { + return this._vendedor; + } + set + { + string upper; + if (value != null) + { + string str = value.Trim(); + if (str != null) + { + upper = str.ToUpper(); + } + else + { + upper = null; + } + } + else + { + upper = null; + } + this._vendedor = upper; + } + } + + public ClientesAtivosInativos() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/ClientesAtivosInativos/SinteticoClientesAtivosInativos.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/ClientesAtivosInativos/SinteticoClientesAtivosInativos.cs new file mode 100644 index 0000000..78dabab --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/ClientesAtivosInativos/SinteticoClientesAtivosInativos.cs @@ -0,0 +1,44 @@ +using Gestor.Model.Attributes; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.ClientesAtivosInativos +{ + public class SinteticoClientesAtivosInativos + { + [Description("TOTAL DE CLIENTES ATIVOS")] + [Tipo("QUANTIDADE")] + public decimal Ativos + { + get; + set; + } + + public string Descricao + { + get; + set; + } + + [Description("TOTAL DE CLIENTES INATIVOS")] + [Tipo("QUANTIDADE")] + public decimal Inativos + { + get; + set; + } + + [Description("TOTAL DE CLIENTES")] + [Tipo("QUANTIDADE")] + public decimal Total + { + get; + set; + } + + public SinteticoClientesAtivosInativos() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/Comissao/Comissao.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Comissao/Comissao.cs new file mode 100644 index 0000000..2c756f1 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Comissao/Comissao.cs @@ -0,0 +1,345 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using Gestor.Model.Domain.Seguros; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.Comissao +{ + public class Comissao + { + [Description("APÓLICE")] + public string Apolice + { + get; + set; + } + + [Description("CLIENTE")] + public string Cliente + { + get; + set; + } + + [Description("COMISSÃO APÓLICE")] + [Tipo("PERCENTUAL")] + public decimal ComissaoApolice + { + get; + set; + } + + [Description("RECEBIMENTO BRUTO")] + [Tipo("VALOR")] + public decimal ComissaoBruta + { + get; + set; + } + + [Description("COMISSÃO PARCELA")] + [Tipo("PERCENTUAL")] + public decimal ComissaoPerc + { + get; + set; + } + + [Description("COMISSÃO RECEBIDA")] + [Tipo("VALOR")] + public decimal ComissaoRecebida + { + get; + set; + } + + [Description("DATA PARCELA CONTROLE")] + [Tipo("DATA?")] + public DateTime? Controle + { + get; + set; + } + + [Description("DATA CONTROLE")] + [Tipo("DATA?")] + public DateTime? DataControle + { + get; + set; + } + + [Description("DESCONTO")] + [Tipo("VALOR")] + public decimal Desconto + { + get; + set; + } + + [Tipo("INVALID")] + public Gestor.Model.Domain.Seguros.Documento Documento + { + get; + set; + } + + [Description("FILIAL")] + public string Empresa + { + get; + set; + } + + [Description("ENDOSSO")] + public string Endosso + { + get; + set; + } + + [Description("ESTIPULANTE")] + public string Estipulante + { + get; + set; + } + + public long IdEmpresa + { + get; + set; + } + + [Description("VALOR IR")] + [Tipo("VALOR")] + public decimal Ir + { + get; + set; + } + + [Description("VALOR ISS")] + [Tipo("VALOR")] + public decimal Iss + { + get; + set; + } + + [Description("ITEM")] + public string Item + { + get; + set; + } + + [Description("TIPO RENOVAÇÃO")] + public string Negocio + { + get; + set; + } + + [Description("OUTROS")] + [Tipo("VALOR")] + public decimal Outros + { + get; + set; + } + + [Description("PARCELA")] + public string Parcela + { + get; + set; + } + + [Tipo("INVALID")] + public Gestor.Model.Domain.Seguros.Parcela ParcelaEntity + { + get; + set; + } + + [Description("PASTA")] + public string Pasta + { + get; + set; + } + + [Description("PASTA CLIENTE")] + public string PastaCliente + { + get; + set; + } + + [Description("PRÊMIO LÍQUIDO")] + [Tipo("VALOR")] + public decimal PremioLiquido + { + get; + set; + } + + [Description("PRÊMIO TOTAL")] + [Tipo("VALOR")] + public decimal PremioTotal + { + get; + set; + } + + [Description("PRODUTO")] + public string Produto + { + get; + set; + } + + [Description("DATA QUITAÇÃO")] + [Tipo("DATA?")] + public DateTime? Quitacao + { + get; + set; + } + + [Description("RAMO")] + public string Ramo + { + get; + set; + } + + [Description("RECEBIMENTO")] + [Tipo("DATA?")] + public DateTime? Recebimento + { + get; + set; + } + + [Description("REPASSE")] + [Tipo("VALOR")] + public decimal Repasse + { + get; + set; + } + + [Description("SEGURADORA")] + public string Seguradora + { + get; + set; + } + + [Tipo("INVALID")] + public bool Selecionado + { + get; + set; + } + + [Description("STATUS")] + public string Status + { + get; + set; + } + + [Description("STATUS APÓLICE")] + public string StatusApolice + { + get; + set; + } + + [Description("TIPO DE PARCELA")] + [Tipo("ENUM")] + public Gestor.Model.Common.SubTipo SubTipo + { + get; + set; + } + + [Description("TIPO")] + public string TipoDocumento + { + get; + set; + } + + [Description("TODOS VENDEDORES")] + public string TodosVendedores + { + get; + set; + } + + [Description("COMISSÃO GERADA")] + [Tipo("VALOR")] + public decimal ValorComissao + { + get; + set; + } + + [Description("VALOR LÍQUIDO PARCELA")] + [Tipo("VALOR")] + public decimal ValorLiquido + { + get; + set; + } + + [Description("VALOR REALIZADO")] + [Tipo("VALOR")] + public decimal ValorRealizado + { + get; + set; + } + + [Description("VENCIMENTO")] + [Tipo("DATA")] + public DateTime Vencimento + { + get; + set; + } + + [Description("VENDEDOR PRINCIPAL")] + public string Vendedor + { + get; + set; + } + + [Description("VIGÊNCIA FINAL")] + [Tipo("DATA?")] + public DateTime? VigenciaFinal + { + get; + set; + } + + [Description("VIGÊNCIA INICIAL")] + [Tipo("DATA")] + public DateTime VigenciaInicial + { + get; + set; + } + + public Comissao() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/Comissao/SinteticoComissao.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Comissao/SinteticoComissao.cs new file mode 100644 index 0000000..91b39a2 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Comissao/SinteticoComissao.cs @@ -0,0 +1,68 @@ +using Gestor.Model.Attributes; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.Comissao +{ + public class SinteticoComissao + { + [Description("QUANTIDADE DE APÓLICES")] + [Tipo("QUANTIDADE")] + public int Apolices + { + get; + set; + } + + [Description("SOMA COMISSÃO RECEBIDA")] + [Tipo("VALOR")] + public decimal Comissao + { + get; + set; + } + + public string Descricao + { + get; + set; + } + + [Description("QUANTIDADE DE ENDOSSOS")] + [Tipo("QUANTIDADE")] + public int Endossos + { + get; + set; + } + + [Description("SOMA REPASSE")] + [Tipo("VALOR")] + public decimal Repasse + { + get; + set; + } + + [Description("TOTAL DE DOCUMENTOS")] + [Tipo("QUANTIDADE")] + public int Total + { + get; + set; + } + + [Description("SOMA VALOR LÍQUIDO")] + [Tipo("VALOR")] + public decimal ValorLiquido + { + get; + set; + } + + public SinteticoComissao() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/CriticaApolice/ApoliceCritica.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/CriticaApolice/ApoliceCritica.cs new file mode 100644 index 0000000..07c87d7 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/CriticaApolice/ApoliceCritica.cs @@ -0,0 +1,123 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Seguros; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.CriticaApolice +{ + public class ApoliceCritica + { + [Description("APÓLICE")] + public string Apolice + { + get; + set; + } + + [Description("CLIENTE")] + public string Cliente + { + get; + set; + } + + [Tipo("INVALID")] + public Gestor.Model.Domain.Seguros.CriticaApolice Critica + { + get; + set; + } + + [Description("DATA CRÍTICA")] + [Tipo("DATA?")] + public DateTime? Criticado + { + get; + set; + } + + [Description("DATA IMPORTAÇÃO")] + [Tipo("DATA")] + public DateTime Importado + { + get; + set; + } + + [Description("PENDÊNCIA")] + public string Pendencia + { + get; + set; + } + + [Description("PROPOSTA")] + public string Proposta + { + get; + set; + } + + [Description("PROPOSTA ENDOSSO")] + public string PropostaEndosso + { + get; + set; + } + + [Description("RAMO")] + public string Ramo + { + get; + set; + } + + [Description("SEGURADORA")] + public string Seguradora + { + get; + set; + } + + [Tipo("INVALID")] + public bool Selecionado + { + get; + set; + } + + [Description("TIPO DOCUMENTO")] + public string Tipo + { + get; + set; + } + + [Description("USUÁRIO CRÍTICA")] + public string UsuarioCritica + { + get; + set; + } + + [Description("USUÁRIO IMPORTAÇÃO")] + public string UsuarioImportacao + { + get; + set; + } + + [Description("VIGÊNCIA INICIAL")] + [Tipo("DATA")] + public DateTime VigenciaInicial + { + get; + set; + } + + public ApoliceCritica() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/DadosRelatorio.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/DadosRelatorio.cs new file mode 100644 index 0000000..693a344 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/DadosRelatorio.cs @@ -0,0 +1,312 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Seguros; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios +{ + public class DadosRelatorio + { + [Description("Nº AGÊNCIA")] + public string Agencia + { + get; + set; + } + + [Description("APÓLICE")] + [Width("150")] + public string Apolice + { + get; + set; + } + + [Description("BANCO")] + public string Banco + { + get; + set; + } + + [Description("CLIENTE")] + [Width("200")] + public string Cliente + { + get; + set; + } + + [Description("COMISSÃO")] + [Tipo("PERCENTUAL")] + [Width("70")] + public decimal? Comissao + { + get; + set; + } + + [Description("% REPASSE")] + [Tipo("PERCENTUAL")] + [Width("70")] + public decimal? ComissaoRepasse + { + get; + set; + } + + [Description("Nº CONTA")] + public string Conta + { + get; + set; + } + + [Tipo("INVALID")] + public string CPFVendedor + { + get; + set; + } + + [Description("DATA DE CADASTRO DO DOCUMENTO")] + [Tipo("DATA?")] + public DateTime? DataCriacao + { + get; + set; + } + + [Description("DATA PAGAMENTO")] + [Tipo("DATA?")] + [Width("120")] + public DateTime? DataPagamento + { + get; + set; + } + + [Description("EMITIDO")] + public string DocumentoEmitido + { + get; + set; + } + + [Description("ENDOSSO")] + [Width("100")] + public string Endosso + { + get; + set; + } + + [Tipo("INVALID")] + public Adiantamento EntidadeAdiantamento + { + get; + set; + } + + [Tipo("INVALID")] + public Documento EntidadeDocumento + { + get; + set; + } + + [Tipo("INVALID")] + public Gestor.Model.Domain.Seguros.Parcela EntidadeParcela + { + get; + set; + } + + [Tipo("INVALID")] + public VendedorParcela EntidadeVendedorParcela + { + get; + set; + } + + [Description("ESTIPULANTE")] + public string Estipulante + { + get; + set; + } + + [Description("HOUVE RECEBIMENTO")] + public string HouveRecebimento + { + get; + set; + } + + [Tipo("INVALID")] + public long Id + { + get; + set; + } + + [Description("TIPO RENOVAÇÃO")] + public string Negocio + { + get; + set; + } + + [Description("PARCELA")] + [Width("60")] + public string Parcela + { + get; + set; + } + + [Description("PEDIDO ENDOSSO")] + public string PedidoEndosso + { + get; + set; + } + + [Description("PRÊMIO LÍQUIDO")] + [Tipo("VALOR?")] + [Width("110")] + public decimal? PremioLiquido + { + get; + set; + } + + [Description("PRÊMIO TOTAL")] + [Tipo("VALOR?")] + public decimal? PremioTotal + { + get; + set; + } + + [Description("PRODUTO")] + public string Produto + { + get; + set; + } + + [Description("PROPOSTA")] + public string Proposta + { + get; + set; + } + + [Description("RAMO")] + public string Ramo + { + get; + set; + } + + [Description("RECEBIDO POR COMPLETO")] + public string RecebidoPorCompleto + { + get; + set; + } + + [Description("RECEBIMENTO")] + [Tipo("DATA?")] + [Width("90")] + public DateTime? Recebimento + { + get; + set; + } + + [Description("REPASSE")] + [Tipo("VALOR")] + [Width("120")] + public decimal Repasse + { + get; + set; + } + + [Description("SEGURADORA")] + public string Seguradora + { + get; + set; + } + + [Tipo("INVALID")] + public bool Selecionado + { + get; + set; + } + + [Description("STATUS")] + public string Status + { + get; + set; + } + + [Tipo("INVALID")] + public int Tipo + { + get; + set; + } + + [Description("VALOR LÍQUIDO")] + [Tipo("VALOR")] + [Width("110")] + public decimal ValorLiquido + { + get; + set; + } + + [Description("VALOR PARCELA")] + [Tipo("VALOR?")] + public decimal? ValorParcela + { + get; + set; + } + + [Description("VENDEDOR")] + public string Vendedor + { + get; + set; + } + + [Description("VIGÊNCIA FINAL")] + [Tipo("DATA?")] + public DateTime? VigenciaFinal + { + get; + set; + } + + [Description("VIGÊNCIA INICIAL")] + [Tipo("DATA?")] + [Width("115")] + public DateTime? VigenciaIncial + { + get; + set; + } + + public DadosRelatorio() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/DadosVinculo.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/DadosVinculo.cs new file mode 100644 index 0000000..db83501 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/DadosVinculo.cs @@ -0,0 +1,67 @@ +using Gestor.Model.Domain.Aggilizador; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios +{ + public class DadosVinculo + { + public string Apolice + { + get; + set; + } + + public string Documento + { + get; + set; + } + + public string Endosso + { + get; + set; + } + + public long Id + { + get; + set; + } + + public long IdSeguradora + { + get; + set; + } + + public string Proposta + { + get; + set; + } + + public DateTime? Vigenciafinal + { + get; + set; + } + + public DateTime VigenciaInicial + { + get; + set; + } + + public VinculoDocumento Vinculo + { + get; + set; + } + + public DadosVinculo() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/Dashboard/Prospectar.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Dashboard/Prospectar.cs new file mode 100644 index 0000000..6c3059f --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Dashboard/Prospectar.cs @@ -0,0 +1,112 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Seguros; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.Dashboard +{ + public class Prospectar + { + private string _nome; + + private string _email; + + [Description("CPF/CNPJ")] + public string Documento + { + get; + set; + } + + [Description("E-MAIL")] + public string Email + { + get + { + string str = this._email; + if (str == null) + { + return null; + } + return str.ToLower().Trim(); + } + set + { + this._email = value; + } + } + + [Description("FILIAL")] + public string Empresa + { + get; + set; + } + + [Tipo("INVALID")] + public Gestor.Model.Domain.Seguros.Cliente EntidadeCliente + { + get; + set; + } + + [Description("ID")] + [Tipo("INVALID")] + public long Id + { + get; + set; + } + + [Tipo("INVALID")] + public long IdEmpresa + { + get; + set; + } + + [Description("CLIENTE")] + public string Nome + { + get + { + string str = this._nome; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._nome = value; + } + } + + [Tipo("INVALID")] + public bool Selecionado + { + get; + set; + } + + [Description("TELEFONE")] + public string Telefone + { + get; + set; + } + + [Description("TIPO DE PESSOA")] + public string TipoPessoa + { + get; + set; + } + + public Prospectar() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/EndossoCancelamento/Endosso.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/EndossoCancelamento/Endosso.cs new file mode 100644 index 0000000..c0fdadf --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/EndossoCancelamento/Endosso.cs @@ -0,0 +1,323 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.EndossoCancelamento +{ + public class Endosso + { + [Description("APÓLICE")] + public string Apolice + { + get; + set; + } + + [Description("APÓLICE CONFERIDA")] + public string ApoliceConferida + { + get; + set; + } + + [Description("PROP. ASSINADA SIGGNER")] + public string AssinadaSiggner + { + get; + set; + } + + [Tipo("INVALID")] + public List<StatusDocumentoAssinado> Assinaturas + { + get; + set; + } + + [Description("CLIENTE")] + public string Cliente + { + get; + set; + } + + [Description("COMISSÃO")] + [Tipo("PERCENTUAL")] + public decimal Comissao + { + get; + set; + } + + [Description("COMISSÃO GERADA")] + [Tipo("VALOR")] + public decimal ComissaoGerada + { + get; + set; + } + + [Description("DATA CONTROLE")] + public DateTime? DataControle + { + get; + set; + } + + [Description("DATA DE CADASTRO")] + [Tipo("DATA?")] + public DateTime? DataCriacao + { + get; + set; + } + + [Tipo("INVALID")] + public Gestor.Model.Domain.Seguros.Documento Documento + { + get; + set; + } + + [Description("DOCUMENTO DO CLIENTE")] + public string DocumentoCliente + { + get; + set; + } + + [Description("EMISSÃO")] + [Tipo("DATA?")] + public DateTime? Emissao + { + get; + set; + } + + [Description("FILIAL")] + public string Empresa + { + get; + set; + } + + [Description("ESTIPULANTE")] + public string Estipulante + { + get; + set; + } + + [Tipo("INVALID")] + public long IdEmpresa + { + get; + set; + } + + [Description("ITEM")] + public string Item + { + get; + set; + } + + [Description("NEGÓCIO CORRETORA")] + public string Negocio + { + get; + set; + } + + [Description("ENDOSSO")] + public string NumEndosso + { + get; + set; + } + + [Description("QUANTIDADE PARCELAS")] + [Tipo("QUANTIDADE")] + public decimal NumeroParcelas + { + get; + set; + } + + [Description("PASTA")] + public string Pasta + { + get; + set; + } + + [Description("PASTA CLIENTE")] + public string PastaCliente + { + get; + set; + } + + [Description("PRÊMIO LÍQUIDO")] + [Tipo("VALOR")] + public decimal PremioLiquido + { + get; + set; + } + + [Description("PRÊMIO TOTAL")] + [Tipo("VALOR")] + public decimal PremioTotal + { + get; + set; + } + + [Description("PRODUTO")] + public string Produto + { + get; + set; + } + + [Description("PROPOSTA ASSINADA")] + public string PropAssinada + { + get; + set; + } + + [Description("PROPOSTA")] + public string Proposta + { + get; + set; + } + + [Description("PROPOSTA ENDOSSO")] + public string PropostaEndosso + { + get; + set; + } + + [Description("RAMO")] + public string Ramo + { + get; + set; + } + + [Description("TRANSMISSÃO")] + [Tipo("DATA?")] + public DateTime? Remessa + { + get; + set; + } + + [Description("REPASSE VENDEDOR")] + [Tipo("VALORDECIMAL2")] + public decimal? RepasseVendedor + { + get; + set; + } + + [Description("SEGURADORA")] + public string Seguradora + { + get; + set; + } + + [Tipo("INVALID")] + public bool Selecionado + { + get; + set; + } + + [Description("STATUS")] + public string Status + { + get; + set; + } + + [Description("STATUS APÓLICE")] + public string StatusApolice + { + get; + set; + } + + [Description("STATUS ASSINATURA")] + [Tipo("ENUM")] + public Gestor.Model.Common.StatusAssinatura StatusAssinatura + { + get; + set; + } + + [Tipo("INVALID")] + public int Tipo + { + get; + set; + } + + [Description("TIPO DOCUMENTO")] + public string TipoDocumento + { + get; + set; + } + + [Description("TIPO PAGAMENTO")] + public string TipoPagamento + { + get; + set; + } + + [Description("TODOS VENDEDORES")] + public string TodosVendedores + { + get; + set; + } + + [Description("VENDEDOR PRINCIPAL")] + public string Vendedor + { + get; + set; + } + + [Description("VIGÊNCIA FINAL")] + [Tipo("DATA?")] + public DateTime? VigenciaFinal + { + get; + set; + } + + [Description("VIGÊNCIA INICIAL")] + [Tipo("DATA")] + public DateTime VigenciaInicial + { + get; + set; + } + + public Endosso() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/Extrato/DetalhesExtrato.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Extrato/DetalhesExtrato.cs new file mode 100644 index 0000000..d59635e --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Extrato/DetalhesExtrato.cs @@ -0,0 +1,73 @@ +using Gestor.Model.Attributes; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.Extrato +{ + public class DetalhesExtrato + { + [Description("APÓLICE")] + public string Apolice + { + get; + set; + } + + [Description("CLIENTE")] + public string Cliente + { + get; + set; + } + + [Description("% COMISSÃO")] + [Tipo("PERCENTUAL")] + public decimal? Comissao + { + get; + set; + } + + [Description("ENDOSSO")] + public string Endosso + { + get; + set; + } + + [Description("VALOR PAGTO")] + [Tipo("VALOR")] + public decimal? Pagto + { + get; + set; + } + + [Description("PARCELA")] + public string Parcela + { + get; + set; + } + + [Description("STATUS")] + public string Status + { + get; + set; + } + + [Description("COMISSÃO")] + [Tipo("VALOR")] + public decimal? ValorComissao + { + get; + set; + } + + public DetalhesExtrato() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/Extrato/Extrato.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Extrato/Extrato.cs new file mode 100644 index 0000000..5017fb7 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Extrato/Extrato.cs @@ -0,0 +1,120 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Seguros; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.Extrato +{ + public class Extrato + { + [Description("BRUTO")] + public decimal? Bruto + { + get; + set; + } + + [Description("DATA")] + public DateTime? Data + { + get; + set; + } + + [Description("DATA DE CRÉDITO")] + public DateTime? DataCredito + { + get; + set; + } + + public Gestor.Model.Domain.Common.Empresa Empresa + { + get; + set; + } + + [Description("HISTORICO")] + public string Historico + { + get; + set; + } + + [Description("ID")] + public long Id + { + get; + set; + } + + [Description("IR")] + public decimal? Ir + { + get; + set; + } + + [Description("ISS")] + public decimal? Iss + { + get; + set; + } + + [Description("LIQUIDO")] + public decimal? Liquido + { + get; + set; + } + + [Description("NUMERO")] + public string Numero + { + get; + set; + } + + [Description("OBSERVAÇÃO")] + public string Observacao + { + get; + set; + } + + [Description("OUTRO")] + public decimal? Outro + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Seguradora Seguradora + { + get; + set; + } + + public bool Selecionado + { + get; + set; + } + + [Description("STATUS")] + [Tipo("ENUM")] + public StatusExtrato Status + { + get; + set; + } + + public Extrato() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/Extrato/ExtratoComissao.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Extrato/ExtratoComissao.cs new file mode 100644 index 0000000..605c15d --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Extrato/ExtratoComissao.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.ObjectModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.Extrato +{ + public class ExtratoComissao + { + public ObservableCollection<Gestor.Model.Domain.Relatorios.Extrato.DetalhesExtrato> DetalhesExtrato + { + get; + set; + } + + public ObservableCollection<Gestor.Model.Domain.Relatorios.Extrato.InformacoesExtrato> InformacoesExtrato + { + get; + set; + } + + public string Seguradora + { + get; + set; + } + + public string Usuario + { + get; + set; + } + + public ExtratoComissao() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/Extrato/InformacoesExtrato.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Extrato/InformacoesExtrato.cs new file mode 100644 index 0000000..c7ac663 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Extrato/InformacoesExtrato.cs @@ -0,0 +1,93 @@ +using Gestor.Model.Attributes; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.Extrato +{ + public class InformacoesExtrato + { + [Description("BRUTO")] + [Tipo("VALOR")] + public decimal Bruto + { + get; + set; + } + + [Description("DATA EXTRATO")] + [Tipo("DATA?")] + public DateTime? DataExtrato + { + get; + set; + } + + [Description("IR")] + [Tipo("VALOR")] + public decimal Ir + { + get; + set; + } + + [Description("ISS")] + [Tipo("VALOR")] + public decimal Iss + { + get; + set; + } + + [Description("LÍQUIDO")] + [Tipo("VALOR")] + public decimal Liquido + { + get; + set; + } + + [Description("NÚMERO EXTRATO")] + public string NumeroExtrato + { + get; + set; + } + + [Description("OUTROS")] + [Tipo("VALOR")] + public decimal Outros + { + get; + set; + } + + [Description("QUANTIDADE")] + [Tipo("INT")] + public int Quantidade + { + get; + set; + } + + [Description("TOTAL BAIXADO")] + [Tipo("VALOR")] + public decimal TotalBaixado + { + get; + set; + } + + [Description("TOTAL PENDENTE")] + [Tipo("VALOR")] + public decimal TotalPendente + { + get; + set; + } + + public InformacoesExtrato() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/Extrato/SinteticoExtrato.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Extrato/SinteticoExtrato.cs new file mode 100644 index 0000000..b23bf99 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Extrato/SinteticoExtrato.cs @@ -0,0 +1,28 @@ +using Gestor.Model.Attributes; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.Extrato +{ + public class SinteticoExtrato + { + public string Descricao + { + get; + set; + } + + [Description("TOTAL DE DOCUMENTOS")] + [Tipo("QUANTIDADE")] + public int Total + { + get; + set; + } + + public SinteticoExtrato() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/ExtratoBaixado/ExtratoBaixadoRelatorio.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/ExtratoBaixado/ExtratoBaixadoRelatorio.cs new file mode 100644 index 0000000..0f72aa9 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/ExtratoBaixado/ExtratoBaixadoRelatorio.cs @@ -0,0 +1,127 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Seguros; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.ExtratoBaixado +{ + public class ExtratoBaixadoRelatorio + { + [Description("BRUTO")] + [Tipo("VALOR")] + public decimal? Bruto + { + get; + set; + } + + [Description("DATA")] + [Tipo("DATA?")] + public DateTime? Data + { + get; + set; + } + + [Description("DATA DE CRÉDITO")] + [Tipo("DATA?")] + public DateTime? DataCredito + { + get; + set; + } + + [Tipo("INVALID")] + public Gestor.Model.Domain.Seguros.Extrato Extrato + { + get; + set; + } + + [Description("HISTÓRICO")] + public string Historico + { + get; + set; + } + + [Tipo("INVALID")] + public long Id + { + get; + set; + } + + [Description("IR")] + [Tipo("VALOR")] + public decimal? Ir + { + get; + set; + } + + [Description("ISS")] + [Tipo("VALOR")] + public decimal? Iss + { + get; + set; + } + + [Description("LÍQUIDO")] + [Tipo("VALOR")] + public decimal? Liquido + { + get; + set; + } + + [Description("NÚMERO")] + public string Numero + { + get; + set; + } + + [Description("OBSERVAÇÃO")] + public string Observacao + { + get; + set; + } + + [Description("OUTRO")] + [Tipo("VALOR")] + public decimal? Outro + { + get; + set; + } + + [Description("SEGURADORA")] + public string Seguradora + { + get; + set; + } + + [Tipo("INVALID")] + public bool Selecionado + { + get; + set; + } + + [Description("STATUS")] + public string Status + { + get; + set; + } + + public ExtratoBaixadoRelatorio() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/FaturaPendente/FaturaPendente.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/FaturaPendente/FaturaPendente.cs new file mode 100644 index 0000000..2ca0d41 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/FaturaPendente/FaturaPendente.cs @@ -0,0 +1,189 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Seguros; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.FaturaPendente +{ + public class FaturaPendente + { + [Description("APÓLICE")] + public string Apolice + { + get; + set; + } + + [Description("CLIENTE")] + public string Cliente + { + get; + set; + } + + [Description("DATA CONTROLE")] + [Tipo("DATA?")] + public DateTime? DataControle + { + get; + set; + } + + [Tipo("INVALID")] + public Gestor.Model.Domain.Seguros.Documento Documento + { + get; + set; + } + + [Description("ENDOSSO")] + public string Endosso + { + get; + set; + } + + [Description("ESTIPULANTE")] + public string Estipulante + { + get; + set; + } + + [Description("ULTIMA FATURA")] + public string Fatura + { + get; + set; + } + + [Description("ITEM")] + public string Item + { + get; + set; + } + + [Tipo("INVALID")] + public Gestor.Model.Domain.Seguros.Parcela Parcela + { + get; + set; + } + + [Description("PASTA")] + public string Pasta + { + get; + set; + } + + [Description("PASTA CLIENTE")] + public string PastaCliente + { + get; + set; + } + + [Description("PENDÊNCIA")] + public int Pendencia + { + get; + set; + } + + [Description("PRODUTO")] + public string Produto + { + get; + set; + } + + [Description("RAMO")] + public string Ramo + { + get; + set; + } + + [Description("SEGURADORA")] + public string Seguradora + { + get; + set; + } + + [Tipo("INVALID")] + public bool Selecionado + { + get; + set; + } + + [Description("STATUS")] + public string Status + { + get; + set; + } + + [Description("STATUS APÓLICE")] + public string StatusApolice + { + get; + set; + } + + [Description("VENCIMENTO")] + [Tipo("DATA?")] + public DateTime? Vencimento + { + get; + set; + } + + [Description("VENDEDOR PRINCIPAL")] + public string Vendedor + { + get; + set; + } + + [Description("VIGÊNCIA FINAL")] + [Tipo("DATA?")] + public DateTime? VigenciaFinal + { + get; + set; + } + + [Description("FINAL FATURA")] + [Tipo("DATA?")] + public DateTime? VigenciaFinalFatura + { + get; + set; + } + + [Description("INICIO FATURA")] + [Tipo("DATA?")] + public DateTime? VigenciaIncialFatura + { + get; + set; + } + + [Description("VIGÊNCIA INICIAL")] + [Tipo("DATA")] + public DateTime VigenciaInicial + { + get; + set; + } + + public FaturaPendente() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/Fechamento/Fechamento.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Fechamento/Fechamento.cs new file mode 100644 index 0000000..39e894d --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Fechamento/Fechamento.cs @@ -0,0 +1,319 @@ +using Gestor.Model.Attributes; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.Fechamento +{ + public class Fechamento + { + [Description("ANO ANTERIOR")] + [Tipo("INVALID")] + public string AnoAnterior + { + get; + set; + } + + [Description("QTD APÓLICE")] + [Tipo("QUANTIDADE")] + public int Apolice + { + get; + set; + } + + [Description("QTD APÓLICE ANTERIOR")] + [Tipo("QUANTIDADE")] + public int ApoliceAnterior + { + get; + set; + } + + [Description("COMPARATIVO QTD APÓLICE")] + public string ApoliceAnteriorComparativo + { + get; + set; + } + + [Description("QTD ENDOSSO")] + [Tipo("QUANTIDADE")] + public int Endosso + { + get; + set; + } + + [Description("QTD ENDOSSO ANTERIOR")] + [Tipo("QUANTIDADE")] + public int EndossoAnterior + { + get; + set; + } + + [Description("COMPARATIVO QTD ENDOSSO")] + public string EndossoAnteriorComparativo + { + get; + set; + } + + [Tipo("INVALID")] + public int Entidade + { + get; + set; + } + + [Description("QTD FATURA")] + [Tipo("QUANTIDADE")] + public int Fatura + { + get; + set; + } + + [Description("QTD FATURA ANTERIOR")] + [Tipo("QUANTIDADE")] + public int FaturaAnterior + { + get; + set; + } + + [Description("COMPARATIVO QTD FATURA")] + public string FaturaAnteriorComparativo + { + get; + set; + } + + [Description("MÉDIA FECHADA")] + [Tipo("PERCENTUAL")] + public decimal Fechada + { + get; + set; + } + + [Description("MÉDIA FECHADA ANTERIOR")] + [Tipo("PERCENTUAL")] + public decimal FechadaAnterior + { + get; + set; + } + + [Description("COMPARATIVO MÉDIA FECHADA")] + public string FechadaAnteriorComparativo + { + get; + set; + } + + [Description("COMISSÃO GERADA")] + [Tipo("VALOR")] + public decimal Gerada + { + get; + set; + } + + [Description("COMISSÃO GERADA ANTERIOR")] + [Tipo("VALOR")] + public decimal GeradaAnterior + { + get; + set; + } + + [Description("COMPARATIVO COMISSÃO GERADA")] + public string GeradaAnteriorComparativo + { + get; + set; + } + + [Tipo("INVALID")] + public long Id + { + get; + set; + } + + [Description("QTD ITENS")] + [Tipo("QUANTIDADE")] + public int Itens + { + get; + set; + } + + [Description("QTD ITENS ANTERIOR")] + [Tipo("QUANTIDADE")] + public int ItensAnterior + { + get; + set; + } + + [Description("COMPARATIVO QTD ITENS")] + public string ItensAnteriorComparativo + { + get; + set; + } + + [Description("MÉDIA MIX %")] + [Tipo("PERCENTUAL")] + public decimal Mix + { + get; + set; + } + + [Description("MÉDIA MIX % ANTERIOR")] + [Tipo("PERCENTUAL")] + public decimal MixAnterior + { + get; + set; + } + + [Description("COMPARATIVO MÉDIA MIX %")] + public string MixAnteriorComparativo + { + get; + set; + } + + [Description("NOME")] + public string Nome + { + get; + set; + } + + [Description("COMISSÃO PAGA")] + [Tipo("VALOR")] + public decimal Paga + { + get; + set; + } + + [Description("COMISSÃO PAGA ANTERIOR")] + [Tipo("VALOR")] + public decimal PagaAnterior + { + get; + set; + } + + [Description("COMPARATIVO COMISSÃO PAGA")] + public string PagaAnteriorComparativo + { + get; + set; + } + + [Description("COMISSÃO PENDENTE")] + [Tipo("VALOR")] + public decimal Pendente + { + get; + set; + } + + [Description("COMISSÃO PENDENTE ANTERIOR")] + [Tipo("VALOR")] + public decimal PendenteAnterior + { + get; + set; + } + + [Description("COMPARATIVO COMISSÃO PENDENTE")] + public string PendenteAnteriorComparativo + { + get; + set; + } + + [Description("PRÊMIO LÍQUIDO")] + [Tipo("VALOR")] + public decimal PremioLiquido + { + get; + set; + } + + [Description("PRÊMIO LÍQUIDO ANTERIOR")] + [Tipo("VALOR")] + public decimal PremioLiquidoAnterior + { + get; + set; + } + + [Description("COMPARATIVO PRÊMIO LÍQUIDO")] + public string PremioLiquidoComparativo + { + get; + set; + } + + [Description("PRÊMIO TOTAL")] + [Tipo("VALOR")] + public decimal PremioTotal + { + get; + set; + } + + [Description("PRÊMIO TOTAL ANTERIOR")] + [Tipo("VALOR")] + public decimal PremioTotalAnterior + { + get; + set; + } + + [Description("COMPARATIVO PRÊMIO TOTAL")] + public string PremioTotalComparativo + { + get; + set; + } + + [Description("COMISSÃO RECEBIDA")] + [Tipo("VALOR")] + public decimal Recebida + { + get; + set; + } + + [Description("COMISSÃO RECEBIDA ANTERIOR")] + [Tipo("VALOR")] + public decimal RecebidaAnterior + { + get; + set; + } + + [Description("COMPARATIVO COMISSÃO RECEBIDA")] + public string RecebidaAnteriorComparativo + { + get; + set; + } + + public Fechamento() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/Fechamento/Fechamentos.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Fechamento/Fechamentos.cs new file mode 100644 index 0000000..d917005 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Fechamento/Fechamentos.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.ObjectModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.Fechamento +{ + public class Fechamentos + { + public bool Comparativo + { + get; + set; + } + + public ObservableCollection<Gestor.Model.Domain.Relatorios.Fechamento.Fechamento> Fechamento + { + get; + set; + } + + public string Title + { + get; + set; + } + + public Fechamentos() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/Fechamento/SinteticoFechamento.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Fechamento/SinteticoFechamento.cs new file mode 100644 index 0000000..5703d5e --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Fechamento/SinteticoFechamento.cs @@ -0,0 +1,94 @@ +using Gestor.Model.Attributes; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.Fechamento +{ + public class SinteticoFechamento + { + [Description("QUANTIDADE APÓLICE")] + [Tipo("QUANTIDADE")] + public int Apolice + { + get; + set; + } + + [Description("QUANTIDADE ENDOSSO")] + [Tipo("QUANTIDADE")] + public int Endosso + { + get; + set; + } + + [Description("QUANTIDADE FATURA")] + [Tipo("QUANTIDADE")] + public int Fatura + { + get; + set; + } + + [Description("MÉDIA FECHADA")] + [Tipo("PERCENTUAL")] + public decimal Fechada + { + get; + set; + } + + [Description("COMISSÃO GERADA")] + [Tipo("VALOR")] + public decimal Gerada + { + get; + set; + } + + [Description("QUANTIDADE ITENS")] + [Tipo("QUANTIDADE")] + public int Itens + { + get; + set; + } + + [Description("MÉDIA MIX %")] + [Tipo("PERCENTUAL")] + public decimal Mix + { + get; + set; + } + + [Description("SOMA PRÊMIO LÍQUIDO")] + [Tipo("VALOR")] + public decimal PremioLiquido + { + get; + set; + } + + [Description("SOMA PRÊMIO TOTAL")] + [Tipo("VALOR")] + public decimal PremioTotal + { + get; + set; + } + + [Description("COMISSÃO RECEBIDA")] + [Tipo("VALOR")] + public decimal Recebida + { + get; + set; + } + + public SinteticoFechamento() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/FiltroPersonalizado.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/FiltroPersonalizado.cs new file mode 100644 index 0000000..3de767e --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/FiltroPersonalizado.cs @@ -0,0 +1,66 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios +{ + public class FiltroPersonalizado + { + public string Descricao + { + get; + set; + } + + public bool Diferente + { + get; + set; + } + + public int Id + { + get; + set; + } + + public string Nome + { + get; + set; + } + + public string Propriedade + { + get; + set; + } + + public bool SemValor + { + get; + set; + } + + public Type Tipo + { + get; + set; + } + + public string ValorFinal + { + get; + set; + } + + public string ValorIncial + { + get; + set; + } + + public FiltroPersonalizado() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/FiltroRelatorio.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/FiltroRelatorio.cs new file mode 100644 index 0000000..99b9fab --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/FiltroRelatorio.cs @@ -0,0 +1,54 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios +{ + public class FiltroRelatorio + { + private string _descricao; + + [Description("DESCRIÇÃO DO FILTRO")] + public string Descricao + { + get + { + return this._descricao; + } + set + { + this._descricao = value; + if (!string.IsNullOrWhiteSpace(value)) + { + this.Icone = value.Substring(0, 1); + } + } + } + + public string Icone + { + get; + set; + } + + public long Id + { + get; + set; + } + + [Description("TIPO DO FILTRO")] + [Tipo("ENUM")] + public TipoFiltroRelatorio Tipo + { + get; + set; + } + + public FiltroRelatorio() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/FiltroTipoParcela.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/FiltroTipoParcela.cs new file mode 100644 index 0000000..7deef39 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/FiltroTipoParcela.cs @@ -0,0 +1,38 @@ +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios +{ + public class FiltroTipoParcela + { + private bool _selecionado; + + public bool IsEnable { get; set; } = true; + + public bool Selecionado + { + get + { + return this._selecionado; + } + set + { + if (this.IsEnable) + { + this._selecionado = value; + } + } + } + + public SubTipo Tipo + { + get; + set; + } + + public FiltroTipoParcela() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/Filtros.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Filtros.cs new file mode 100644 index 0000000..ef24f44 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Filtros.cs @@ -0,0 +1,138 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios +{ + public class Filtros : ICloneable + { + public List<long> Estipulantes + { + get; + set; + } + + public string FiltrarDocumento + { + get; + set; + } + + public DateTime Fim + { + get; + set; + } + + public long IdEmpresa + { + get; + set; + } + + public DateTime Inicio + { + get; + set; + } + + public List<long> Negocio + { + get; + set; + } + + public List<FiltroTipoParcela> ParcelasEspeciais + { + get; + set; + } + + public List<long> Produtos + { + get; + set; + } + + public List<long> Ramos + { + get; + set; + } + + public string Referencia + { + get; + set; + } + + public List<long> Relatorios + { + get; + set; + } + + public List<long> Seguradoras + { + get; + set; + } + + public List<long> Status + { + get; + set; + } + + public List<long> Telas + { + get; + set; + } + + public List<long> TipoVendedor + { + get; + set; + } + + public List<long> Usuarios + { + get; + set; + } + + public int ValorFim + { + get; + set; + } + + public int ValorInicio + { + get; + set; + } + + public List<long> Vendedores + { + get; + set; + } + + public List<long> VinculoVendedores + { + get; + set; + } + + public Filtros() + { + } + + public object Clone() + { + return (Filtros)this.MemberwiseClone(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/Licenciamento/Licenciamento.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Licenciamento/Licenciamento.cs new file mode 100644 index 0000000..7343bae --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Licenciamento/Licenciamento.cs @@ -0,0 +1,174 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Seguros; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.Licenciamento +{ + public class Licenciamento + { + private string _cliente; + + private string _email; + + [Description("CATEGORIA")] + public string Categoria + { + get; + set; + } + + [Description("CLIENTE")] + public string Cliente + { + get + { + string str = this._cliente; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._cliente = value; + } + } + + [Tipo("INVALID")] + public Gestor.Model.Domain.Seguros.Documento Documento + { + get; + set; + } + + [Description("E-MAIL")] + public string Email + { + get + { + string str = this._email; + if (str == null) + { + return null; + } + return str.ToLower().Trim(); + } + set + { + this._email = value; + } + } + + [Tipo("INVALID")] + public Gestor.Model.Domain.Seguros.Item EntidadeItem + { + get; + set; + } + + [Description("ESTIPULANTE")] + public string Estipulante + { + get; + set; + } + + [Tipo("INVALID")] + public long Id + { + get; + set; + } + + [Tipo("INVALID")] + public long IdCliente + { + get; + set; + } + + [Description("ITEM")] + public string Item + { + get; + set; + } + + [Description("PASTA CLIENTE")] + public string PastaCliente + { + get; + set; + } + + [Description("PLACA")] + public string Placa + { + get; + set; + } + + [Description("PRODUTO")] + public string Produto + { + get; + set; + } + + [Description("RAMO")] + public string Ramo + { + get; + set; + } + + [Description("SEGURADORA")] + public string Seguradora + { + get; + set; + } + + [Tipo("INVALID")] + public bool Selecionado + { + get; + set; + } + + [Description("TELEFONE")] + public string Telefone + { + get; + set; + } + + [Description("TODOS VENDEDORES")] + public string TodosVendedores + { + get; + set; + } + + [Tipo("INVALID")] + public string Vencimento + { + get; + set; + } + + [Description("VENDEDOR PRINCIPAL")] + public string Vendedor + { + get; + set; + } + + public Licenciamento() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/Listagem.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Listagem.cs new file mode 100644 index 0000000..4386cbd --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Listagem.cs @@ -0,0 +1,33 @@ +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios +{ + public class Listagem + { + [Description("AGRUPAMENTO")] + public string Agrupamento + { + get; + set; + } + + public string NomeRelatorio + { + get; + set; + } + + [Description("VALOR")] + public string Valor + { + get; + set; + } + + public Listagem() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/Log/LogAcaoRelatorio.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Log/LogAcaoRelatorio.cs new file mode 100644 index 0000000..70d529b --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Log/LogAcaoRelatorio.cs @@ -0,0 +1,145 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Common; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.Log +{ + public class LogAcaoRelatorio + { + private string _maquina; + + private string _usuarioAgger; + + private string _usuarioMaquina; + + private string _acesso; + + [Description("ACESSO")] + public string Acesso + { + get + { + string str = this._acesso; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._acesso = value; + } + } + + [Description("DATA")] + [Tipo("DATA/TIME")] + public DateTime Data + { + get; + set; + } + + [Description("DESCRIÇÃO")] + public string Descricao + { + get; + set; + } + + [Description("CÓDIGO")] + public long EntidadeId + { + get; + set; + } + + [Description("IP")] + public string Ip + { + get; + set; + } + + [Description("MÁQUINA")] + public string Maquina + { + get + { + string str = this._maquina; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._maquina = value; + } + } + + [Tipo("INVALID")] + public RegistroAcao RegistroEntity + { + get; + set; + } + + [Tipo("INVALID")] + public bool Selecionado + { + get; + set; + } + + [Description("USUÁRIO AGGER")] + public string UsuarioAgger + { + get + { + string str = this._usuarioAgger; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._usuarioAgger = value; + } + } + + [Description("USUÁRIO DA MÁQUINA")] + public string UsuarioMaquina + { + get + { + string str = this._usuarioMaquina; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._usuarioMaquina = value; + } + } + + [Description("VERSÃO SISTEMA")] + public string Versao + { + get; + set; + } + + public LogAcaoRelatorio() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/LogsEnvio/LogsEnvio.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/LogsEnvio/LogsEnvio.cs new file mode 100644 index 0000000..d0a713f --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/LogsEnvio/LogsEnvio.cs @@ -0,0 +1,211 @@ +using Gestor.Model.Attributes; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.LogsEnvio +{ + public class LogsEnvio + { + private string _remetente; + + private string _destinatarios; + + private string _cco; + + private string _assunto; + + private string _maquina; + + private string _usuarioAgger; + + private string _usuarioMaquina; + + private string _tela; + + [Description("ASSUNTO")] + public string Assunto + { + get + { + string str = this._assunto; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._assunto = value; + } + } + + [Description("CCO")] + public string Cco + { + get + { + string str = this._cco; + if (str != null) + { + return str.ToLower(); + } + return null; + } + set + { + this._cco = value; + } + } + + [Description("DATA")] + [Tipo("DATA")] + public DateTime Data + { + get; + set; + } + + [Description("DESTINATÁRIOS")] + public string Destinatarios + { + get + { + string str = this._destinatarios; + if (str != null) + { + return str.ToLower(); + } + return null; + } + set + { + this._destinatarios = value; + } + } + + [Description("ID")] + [Tipo("INVALID")] + public long Id + { + get; + set; + } + + [Description("IP")] + public string Ip + { + get; + set; + } + + [Description("MÁQUINA")] + public string Maquina + { + get + { + string str = this._maquina; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._maquina = value; + } + } + + [Description("REMETENTE")] + public string Remetente + { + get + { + string str = this._remetente; + if (str != null) + { + return str.ToLower(); + } + return null; + } + set + { + this._remetente = value; + } + } + + [Tipo("INVALID")] + public bool Selecionado + { + get; + set; + } + + [Description("TELA")] + public string Tela + { + get + { + string str = this._tela; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._tela = value; + } + } + + [Description("USUÁRIO AGGER")] + public string UsuarioAgger + { + get + { + string str = this._usuarioAgger; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._usuarioAgger = value; + } + } + + [Description("USUÁRIO DA MÁQUINA")] + public string UsuarioMaquina + { + get + { + string str = this._usuarioMaquina; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._usuarioMaquina = value; + } + } + + [Description("VERSÃO")] + public string Versao + { + get; + set; + } + + public LogsEnvio() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/MetaSeguradora/MetaSeguradoraRelatorio.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/MetaSeguradora/MetaSeguradoraRelatorio.cs new file mode 100644 index 0000000..e48f927 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/MetaSeguradora/MetaSeguradoraRelatorio.cs @@ -0,0 +1,51 @@ +using Gestor.Model.Attributes; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.MetaSeguradora +{ + public class MetaSeguradoraRelatorio + { + [Tipo("INVALID")] + public long Id + { + get; + set; + } + + [Description("META ATINGIR")] + [Tipo("VALOR")] + public decimal MetaAtingir + { + get; + set; + } + + [Description("META CUMPRIDA")] + [Tipo("VALOR")] + public decimal MetaCumprida + { + get; + set; + } + + [Description("SEGURADORA")] + public string Seguradora + { + get; + set; + } + + [Tipo("INVALID")] + public bool Selecionado + { + get; + set; + } + + public MetaSeguradoraRelatorio() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/MetaSeguradora/SinteticoMetaSeguradora.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/MetaSeguradora/SinteticoMetaSeguradora.cs new file mode 100644 index 0000000..c196b87 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/MetaSeguradora/SinteticoMetaSeguradora.cs @@ -0,0 +1,27 @@ +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.MetaSeguradora +{ + public class SinteticoMetaSeguradora + { + [Description("META ATINGIR")] + public decimal MetaAtingir + { + get; + set; + } + + [Description("META CUMPRIDA")] + public decimal MetaCumprida + { + get; + set; + } + + public SinteticoMetaSeguradora() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/MetaVendedor/MetaVendedorRelatorio.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/MetaVendedor/MetaVendedorRelatorio.cs new file mode 100644 index 0000000..8a6a169 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/MetaVendedor/MetaVendedorRelatorio.cs @@ -0,0 +1,51 @@ +using Gestor.Model.Attributes; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.MetaVendedor +{ + public class MetaVendedorRelatorio + { + [Tipo("INVALID")] + public long Id + { + get; + set; + } + + [Description("META ATINGIR")] + [Tipo("VALOR")] + public decimal MetaAtingir + { + get; + set; + } + + [Description("META CUMPRIDA")] + [Tipo("VALOR")] + public decimal MetaCumprida + { + get; + set; + } + + [Tipo("INVALID")] + public bool Selecionado + { + get; + set; + } + + [Description("VENDEDOR")] + public string Vendedor + { + get; + set; + } + + public MetaVendedorRelatorio() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/MetaVendedor/SinteticoMetaVendedor.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/MetaVendedor/SinteticoMetaVendedor.cs new file mode 100644 index 0000000..8a26b43 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/MetaVendedor/SinteticoMetaVendedor.cs @@ -0,0 +1,27 @@ +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.MetaVendedor +{ + public class SinteticoMetaVendedor + { + [Description("META ATINGIR")] + public decimal MetaAtingir + { + get; + set; + } + + [Description("META CUMPRIDA")] + public decimal MetaCumprida + { + get; + set; + } + + public SinteticoMetaVendedor() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/NegocioRelatorio.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/NegocioRelatorio.cs new file mode 100644 index 0000000..ebd59d3 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/NegocioRelatorio.cs @@ -0,0 +1,58 @@ +using Gestor.Model.Common; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Gestor.Model.Domain.Relatorios +{ + public class NegocioRelatorio : INotifyPropertyChanged + { + private bool _selecionado; + + public int Id + { + get; + set; + } + + public NegocioCorretora Negocio + { + get; + set; + } + + public bool Selecionado + { + get + { + return this._selecionado; + } + set + { + if (value == this._selecionado) + { + return; + } + this._selecionado = value; + this.OnPropertyChanged("Selecionado"); + } + } + + public NegocioRelatorio() + { + } + + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChangedEventHandler propertyChangedEventHandler = this.PropertyChanged; + if (propertyChangedEventHandler == null) + { + return; + } + propertyChangedEventHandler(this, new PropertyChangedEventArgs(propertyName)); + } + + public event PropertyChangedEventHandler PropertyChanged; + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/NotaFiscal/NotaFiscalRelatorio.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/NotaFiscal/NotaFiscalRelatorio.cs new file mode 100644 index 0000000..4868650 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/NotaFiscal/NotaFiscalRelatorio.cs @@ -0,0 +1,96 @@ +using Gestor.Model.Attributes; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.NotaFiscal +{ + public class NotaFiscalRelatorio + { + [Description("VALOR BRUTO")] + [Tipo("VALOR")] + public decimal Bruto + { + get; + set; + } + + [Description("CNPJ")] + public string Cnpj + { + get; + set; + } + + [Description("DATA")] + [Tipo("DATA?")] + public DateTime? Data + { + get; + set; + } + + [Description("ESTIPULANTE")] + public string Estipulante + { + get; + set; + } + + [Description("EXTRATO")] + public string Extrato + { + get; + set; + } + + [Tipo("INVALID")] + public long Id + { + get; + set; + } + + [Description("IR")] + [Tipo("VALOR")] + public decimal Ir + { + get; + set; + } + + [Description("ISS")] + [Tipo("VALOR")] + public decimal Iss + { + get; + set; + } + + [Description("VALOR LÍQUIDO")] + [Tipo("VALOR")] + public decimal Liquido + { + get; + set; + } + + [Description("SEGURADORA")] + public string Seguradora + { + get; + set; + } + + [Tipo("INVALID")] + public bool Selecionado + { + get; + set; + } + + public NotaFiscalRelatorio() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/Pagamento/AgrupamentoPagamentoSintetico.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Pagamento/AgrupamentoPagamentoSintetico.cs new file mode 100644 index 0000000..49bdf53 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Pagamento/AgrupamentoPagamentoSintetico.cs @@ -0,0 +1,37 @@ +using Gestor.Model.Attributes; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.Pagamento +{ + public class AgrupamentoPagamentoSintetico + { + [Description("NOME")] + public string Nome + { + get; + set; + } + + [Description("REPASSE")] + [Tipo("VALOR")] + public decimal Repasse + { + get; + set; + } + + [Description("VALOR LÍQUIDO")] + [Tipo("VALOR")] + public decimal VlrLiquido + { + get; + set; + } + + public AgrupamentoPagamentoSintetico() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/Pagamento/AgrupamentoVendedor.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Pagamento/AgrupamentoVendedor.cs new file mode 100644 index 0000000..6b4a47f --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Pagamento/AgrupamentoVendedor.cs @@ -0,0 +1,113 @@ +using Gestor.Model.Attributes; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.Pagamento +{ + public class AgrupamentoVendedor + { + [Description("ADIANTAMENTO LÍQUIDO")] + [Tipo("VALOR")] + public decimal Adiantamento + { + get; + set; + } + + [Description("Nº AGÊNCIA")] + public string Agencia + { + get; + set; + } + + [Description("BANCO")] + public string Banco + { + get; + set; + } + + [Description("Nº CONTA")] + public string Conta + { + get; + set; + } + + [Description("CPF")] + public string CPF + { + get; + set; + } + + [Description("ADIANTAMENTOS (+)")] + [Tipo("VALOR")] + public decimal Credito + { + get; + set; + } + + [Description("ADIANTAMENTOS (-)")] + [Tipo("VALOR")] + public decimal Debito + { + get; + set; + } + + [Description("DESCONTO")] + [Tipo("VALOR")] + public decimal Desconto + { + get; + set; + } + + [Description("ESTORNOS (-)")] + [Tipo("VALOR")] + public decimal Estorno + { + get; + set; + } + + [Description("REPASSE (+)")] + [Tipo("VALOR")] + public decimal Repasse + { + get; + set; + } + + [Description("REPASSE BRUTO")] + [Tipo("VALOR")] + public decimal RepasseBruto + { + get; + set; + } + + [Description("REPASSE LÍQUIDO")] + [Tipo("VALOR")] + public decimal ValorLiquido + { + get; + set; + } + + [Description("VENDEDOR")] + public string Vendedor + { + get; + set; + } + + public AgrupamentoVendedor() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/Pagamento/Pagamento.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Pagamento/Pagamento.cs new file mode 100644 index 0000000..2d8a0b3 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Pagamento/Pagamento.cs @@ -0,0 +1,38 @@ +using Gestor.Model.Domain.Relatorios; +using System; +using System.Collections.ObjectModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.Pagamento +{ + public class Pagamento + { + public ObservableCollection<DadosRelatorio> Dados + { + get; + set; + } + + public ObservableCollection<Gestor.Model.Domain.Relatorios.Sintetico> Sintetico + { + get; + set; + } + + public string Title + { + get; + set; + } + + public AgrupamentoVendedor Vendedores + { + get; + set; + } + + public Pagamento() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/Pagamento/PagamentoSintetico.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Pagamento/PagamentoSintetico.cs new file mode 100644 index 0000000..ef78ddc --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Pagamento/PagamentoSintetico.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.ObjectModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.Pagamento +{ + public class PagamentoSintetico + { + public ObservableCollection<AgrupamentoPagamentoSintetico> Agrupamento + { + get; + set; + } + + public string Titulo + { + get; + set; + } + + public PagamentoSintetico() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/Pagamento/SinteticoPagamento.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Pagamento/SinteticoPagamento.cs new file mode 100644 index 0000000..a3e3604 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Pagamento/SinteticoPagamento.cs @@ -0,0 +1,60 @@ +using Gestor.Model.Attributes; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.Pagamento +{ + public class SinteticoPagamento + { + [Description("QUANTIDADE DE APÓLICES")] + [Tipo("QUANTIDADE")] + public int Apolices + { + get; + set; + } + + public string Descricao + { + get; + set; + } + + [Description("QUANTIDADE DE ENDOSSOS")] + [Tipo("QUANTIDADE")] + public int Endossos + { + get; + set; + } + + [Description("SOMA REPASSE BRUTO")] + [Tipo("VALOR")] + public decimal RepasseBruto + { + get; + set; + } + + [Description("SOMA REPASSE LIQUIDO")] + [Tipo("VALOR")] + public decimal RepasseLiquido + { + get; + set; + } + + [Description("TOTAL DE DOCUMENTOS")] + [Tipo("QUANTIDADE")] + public int Total + { + get; + set; + } + + public SinteticoPagamento() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/ParametrosRelatorio.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/ParametrosRelatorio.cs new file mode 100644 index 0000000..5cd4470 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/ParametrosRelatorio.cs @@ -0,0 +1,90 @@ +using Gestor.Model.Common; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Gestor.Model.Domain.Relatorios +{ + public class ParametrosRelatorio : INotifyPropertyChanged + { + private bool _selecionado; + + public string Campo + { + get; + set; + } + + public string Header + { + get; + set; + } + + public long Id + { + get; + set; + } + + public long IdUsuario + { + get; + set; + } + + public int Ordem + { + get; + set; + } + + public Gestor.Model.Common.Relatorio Relatorio + { + get; + set; + } + + public bool Selecionado + { + get + { + return this._selecionado; + } + set + { + this._selecionado = value; + this.OnPropertyChanged("Selecionado"); + } + } + + public string Tipo + { + get; + set; + } + + public int Width + { + get; + set; + } + + public ParametrosRelatorio() + { + } + + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChangedEventHandler propertyChangedEventHandler = this.PropertyChanged; + if (propertyChangedEventHandler == null) + { + return; + } + propertyChangedEventHandler(this, new PropertyChangedEventArgs(propertyName)); + } + + public event PropertyChangedEventHandler PropertyChanged; + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/ParametrosTotalizacao.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/ParametrosTotalizacao.cs new file mode 100644 index 0000000..b176382 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/ParametrosTotalizacao.cs @@ -0,0 +1,49 @@ +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios +{ + public class ParametrosTotalizacao + { + public bool Ativa + { + get; + set; + } + + public string Campo + { + get; + set; + } + + public string Header + { + get; + set; + } + + public long Id + { + get; + set; + } + + public long IdUsuario + { + get; + set; + } + + public Gestor.Model.Common.Relatorio Relatorio + { + get; + set; + } + + public ParametrosTotalizacao() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/Pendente/Pendente.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Pendente/Pendente.cs new file mode 100644 index 0000000..3e11b11 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Pendente/Pendente.cs @@ -0,0 +1,308 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using Gestor.Model.Domain.Seguros; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.Pendente +{ + public class Pendente + { + [Description("APÓLICE")] + public string Apolice + { + get; + set; + } + + [Description("CLIENTE")] + public string Cliente + { + get; + set; + } + + [Description("COMISSÃO GERADA")] + [Tipo("VALOR")] + public decimal ComissaoGerada + { + get; + set; + } + + [Description("COMISSÃO")] + [Tipo("PERCENTUAL")] + public decimal ComissaoPerc + { + get; + set; + } + + [Description("COMISSÃO PREVISTA")] + [Tipo("VALOR")] + public decimal ComissaoPrevista + { + get; + set; + } + + [Description("DATA CONTROLE")] + [Tipo("DATA?")] + public DateTime? Controle + { + get; + set; + } + + [Description("DATA CONTROLE")] + [Tipo("DATA?")] + public DateTime? DataControle + { + get; + set; + } + + [Tipo("INVALID")] + public Gestor.Model.Domain.Seguros.Documento Documento + { + get; + set; + } + + [Description("DOCUMENTO DO CLIENTE")] + public string DocumentoCliente + { + get; + set; + } + + [Description("FILIAL")] + public string Empresa + { + get; + set; + } + + [Description("ENDOSSO")] + public string Endosso + { + get; + set; + } + + [Description("ESTIPULANTE")] + public string Estipulante + { + get; + set; + } + + [Description("FORMA DE PAGAMENTO")] + public string FormaPagamento + { + get; + set; + } + + [Tipo("INVALID")] + public long IdEmpresa + { + get; + set; + } + + [Description("ITEM")] + public string Item + { + get; + set; + } + + [Description("TIPO RENOVAÇÃO")] + public string Negocio + { + get; + set; + } + + [Tipo("INVALID")] + public Parcela ParcelaEntity + { + get; + set; + } + + [Description("PASTA")] + public string Pasta + { + get; + set; + } + + [Description("PASTA CLIENTE")] + public string PastaCliente + { + get; + set; + } + + [Description("PENDÊNCIA")] + public int Pendencia + { + get; + set; + } + + [Description("PARCELA")] + public string Pendentes + { + get; + set; + } + + [Description("PRODUTO")] + public string Produto + { + get; + set; + } + + [Description("PROPOSTA")] + public string Proposta + { + get; + set; + } + + [Description("DATA QUITAÇÃO")] + [Tipo("DATA?")] + public DateTime? Quitacao + { + get; + set; + } + + [Description("RAMO")] + public string Ramo + { + get; + set; + } + + [Description("SEGURADORA")] + public string Seguradora + { + get; + set; + } + + [Tipo("INVALID")] + public bool Selecionado + { + get; + set; + } + + [Description("STATUS")] + public string Status + { + get; + set; + } + + [Description("STATUS APÓLICE")] + public string StatusApolice + { + get; + set; + } + + [Description("STATUS PAGAMENTO")] + public string StatusPagamento + { + get; + set; + } + + [Description("TIPO DE PARCELA")] + [Tipo("ENUM")] + public Gestor.Model.Common.SubTipo SubTipo + { + get; + set; + } + + [Description("TELEFONES")] + public string Telefones + { + get; + set; + } + + [Description("TIPO DOCUMENTO")] + public string TipoDocumento + { + get; + set; + } + + [Description("TODOS VENDEDORES")] + public string TodosVendedores + { + get; + set; + } + + [Description("TOTAL PREVISTO")] + [Tipo("VALOR")] + public decimal TotalPrevisto + { + get; + set; + } + + [Description("VALOR PARCELA")] + [Tipo("VALOR")] + public decimal ValorParcela + { + get; + set; + } + + [Description("VENCIMENTO")] + [Tipo("DATA")] + public DateTime Vencimento + { + get; + set; + } + + [Description("VENDEDOR PRINCIPAL")] + public string Vendedor + { + get; + set; + } + + [Description("VIGÊNCIA FINAL")] + [Tipo("DATA?")] + public DateTime? VigenciaFinal + { + get; + set; + } + + [Description("VIGÊNCIA INICIAL")] + [Tipo("DATA")] + public DateTime VigenciaInicial + { + get; + set; + } + + public Pendente() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/Pendente/SinteticoPendente.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Pendente/SinteticoPendente.cs new file mode 100644 index 0000000..6017cea --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Pendente/SinteticoPendente.cs @@ -0,0 +1,52 @@ +using Gestor.Model.Attributes; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.Pendente +{ + public class SinteticoPendente + { + [Description("QUANTIDADE DE APÓLICES")] + [Tipo("QUANTIDADE")] + public int Apolices + { + get; + set; + } + + [Description("SOMA COMISSÃO PREVISTA")] + [Tipo("VALOR")] + public decimal Comissao + { + get; + set; + } + + public string Descricao + { + get; + set; + } + + [Description("QUANTIDADE DE ENDOSSOS")] + [Tipo("QUANTIDADE")] + public int Endossos + { + get; + set; + } + + [Description("TOTAL DE DOCUMENTOS")] + [Tipo("QUANTIDADE")] + public int Total + { + get; + set; + } + + public SinteticoPendente() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/Placa/Placas.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Placa/Placas.cs new file mode 100644 index 0000000..76b327c --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Placa/Placas.cs @@ -0,0 +1,167 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Seguros; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.Placa +{ + public class Placas + { + private string _cliente; + + private string _email; + + [Description("CATEGORIA")] + public string Categoria + { + get; + set; + } + + [Description("CLIENTE")] + public string Cliente + { + get + { + string str = this._cliente; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._cliente = value; + } + } + + [Tipo("INVALID")] + public Gestor.Model.Domain.Seguros.Documento Documento + { + get; + set; + } + + [Description("E-MAIL")] + public string Email + { + get + { + string str = this._email; + if (str == null) + { + return null; + } + return str.ToLower().Trim(); + } + set + { + this._email = value; + } + } + + [Tipo("INVALID")] + public Gestor.Model.Domain.Seguros.Item EntidadeItem + { + get; + set; + } + + [Description("ESTIPULANTE")] + public string Estipulante + { + get; + set; + } + + [Tipo("INVALID")] + public long Id + { + get; + set; + } + + [Tipo("INVALID")] + public long IdCliente + { + get; + set; + } + + [Description("ITEM")] + public string Item + { + get; + set; + } + + [Description("PASTA CLIENTE")] + public string PastaCliente + { + get; + set; + } + + [Description("PLACA")] + public string Placa + { + get; + set; + } + + [Description("PRODUTO")] + public string Produto + { + get; + set; + } + + [Description("RAMO")] + public string Ramo + { + get; + set; + } + + [Description("SEGURADORA")] + public string Seguradora + { + get; + set; + } + + [Tipo("INVALID")] + public bool Selecionado + { + get; + set; + } + + [Description("TELEFONE")] + public string Telefone + { + get; + set; + } + + [Description("TODOS VENDEDORES")] + public string TodosVendedores + { + get; + set; + } + + [Description("VENDEDOR PRINCIPAL")] + public string Vendedor + { + get; + set; + } + + public Placas() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/PlanilhaCompleta.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/PlanilhaCompleta.cs new file mode 100644 index 0000000..8d79dd3 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/PlanilhaCompleta.cs @@ -0,0 +1,1595 @@ +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios +{ + public class PlanilhaCompleta + { + [Description("COMISSÃO ADICIONAL")] + public bool AdicionalComiss + { + get; + set; + } + + [Description("AGÊNCIA")] + public string AgenciaCliente + { + get; + set; + } + + [Description("AGÊNCIA DO CONTATO")] + public string AgenciaContato + { + get; + set; + } + + [Description("AGENDAMENTO DA TAREFA")] + public DateTime? AgendamentoTarefa + { + get; + set; + } + + [Description("ANO DE FABRICAÇÃO")] + public string AnoFab + { + get; + set; + } + + [Description("ANO DE FABRICAÇÃO")] + public int? AnoFabAero + { + get; + set; + } + + [Description("ANO DO MODELO")] + public string AnoMod + { + get; + set; + } + + [Description("ACIDENTES PASSAGEIRO FRANQUIA")] + public decimal? AppFranquia + { + get; + set; + } + + [Description("ACIDENTES PASSAGEIRO LMI")] + public decimal? AppLmi + { + get; + set; + } + + [Description("ACIDENTES PASSAGEIRO PREMIO")] + public decimal? AppPremios + { + get; + set; + } + + [Description("ÁREA")] + public string AreaGranizo + { + get; + set; + } + + [Description("ÁREA")] + public string AreaRiscos + { + get; + set; + } + + [Description("ATIVIDADE")] + public string AtividadeCliente + { + get; + set; + } + + [Description("BAIRRO")] + public string Bairro + { + get; + set; + } + + [Description("BAIRRO DO ITEM")] + public string BairroItem + { + get; + set; + } + + [Description("BANCO")] + public string BancoCliente + { + get; + set; + } + + [Description("BANCO DO CONTATO")] + public string BancoContato + { + get; + set; + } + + [Description("BENS/CONSORCIO")] + public string BensConsorcio + { + get; + set; + } + + [Description("BENS DO ITEM")] + public string BensPatrimonial + { + get; + set; + } + + [Description("BÔNUS")] + public decimal? Bonus + { + get; + set; + } + + [Description("CAPACIDADE")] + public string Capacidade + { + get; + set; + } + + [Description("CAPITAL FUNCIONÁRIOS")] + public decimal? CapitalFuncionariosVida + { + get; + set; + } + + [Description("CAPITAL SÓCIO")] + public decimal? CapitalSociosVida + { + get; + set; + } + + [Description("CARRO RESERVA FRANQUIA")] + public decimal? CarroReservaFranquia + { + get; + set; + } + + [Description("CARRO RESERVA LMI")] + public decimal? CarroReservaLmi + { + get; + set; + } + + [Description("CARRO RESERVA OBS")] + public string CarroReservaObs + { + get; + set; + } + + [Description("CARRO RESERVA PREMIO")] + public decimal? CarroReservaPremios + { + get; + set; + } + + [Description("CASCO")] + public string CascoAero + { + get; + set; + } + + [Description("CATEGORIA")] + public string Categoria + { + get; + set; + } + + [Description("CATEGORIA DA HABILITAÇÃO")] + public string CategoriaHabilitacaoCliente + { + get; + set; + } + + [Description("C.E.I.")] + public string CeiCliente + { + get; + set; + } + + [Description("CEP")] + public string Cep + { + get; + set; + } + + [Description("CEP CIRCULAÇÃO PERFIL")] + public string CEPCirculacaoPerfil + { + get; + set; + } + + [Description("CEP DO ITEM")] + public string CepItem + { + get; + set; + } + + [Description("CEP PERNOITE")] + public string CepPernoite + { + get; + set; + } + + [Description("CEP PERNOITE PERFIL")] + public string CEPPernoitePerfil + { + get; + set; + } + + [Description("CERTIFICADO")] + public string CertificadoAero + { + get; + set; + } + + [Description("CHASSI")] + public string Chassi + { + get; + set; + } + + [Description("CI")] + public string Ci + { + get; + set; + } + + [Description("CIDADE")] + public string Cidade + { + get; + set; + } + + [Description("CIDADE DO ITEM")] + public string CidadeItem + { + get; + set; + } + + [Description("CLIENTE DESDE")] + public DateTime? ClienteDesde + { + get; + set; + } + + [Description("CÓDIGO FIPE")] + public string CodFipe + { + get; + set; + } + + [Description("COMBUSTÍVEL")] + public string Combustivel + { + get; + set; + } + + [Description("COMISSÃO")] + public decimal? Comissao + { + get; + set; + } + + [Description("COMISSÃO GERADA")] + public decimal? ComissaoGerada + { + get; + set; + } + + [Description("COMPLEMENTO")] + public string Complemento + { + get; + set; + } + + [Description("COMPLEMENTO DO ITEM")] + public string ComplementoItem + { + get; + set; + } + + [Description("CONTA")] + public string ContaCliente + { + get; + set; + } + + [Description("CONTA DO CONTATO")] + public string ContaContato + { + get; + set; + } + + [Description("CONTATO DO ITEM")] + public string ContatoPatrimonial + { + get; + set; + } + + [Description("COR")] + public string Cor + { + get; + set; + } + + [Description("CORREÇÃO")] + public string Correcao + { + get; + set; + } + + [Description("COTA")] + public string Cota + { + get; + set; + } + + [Description("CPF PERFIL")] + public string CpfPerfil + { + get; + set; + } + + [Description("CULTURA DO GRANIZO")] + public string CulturaGranizo + { + get; + set; + } + + [Description("DANOS CORPORAIS FRANQUIA")] + public decimal? DanosCorporaisFranquia + { + get; + set; + } + + [Description("DANOS CORPORAIS LMI")] + public decimal? DanosCorporaisLmi + { + get; + set; + } + + [Description("DANOS CORPORAIS PREMIO")] + public decimal? DanosCorporaisPremios + { + get; + set; + } + + [Description("DANOS MATERIAIS FRANQUIA")] + public decimal? DanosMateriasFranquia + { + get; + set; + } + + [Description("DANOS MATERIAIS LMI")] + public decimal? DanosMateriasLmi + { + get; + set; + } + + [Description("DANOS MATERIAIS PREMIO")] + public decimal? DanosMateriasPremios + { + get; + set; + } + + [Description("DANOS MORAIS FRANQUIA")] + public decimal? DanosMoraisFranquia + { + get; + set; + } + + [Description("DANOS MORAIS LMI")] + public decimal? DanosMoraisLmi + { + get; + set; + } + + [Description("DANOS MORAIS PREMIO")] + public decimal? DanosMoraisPremios + { + get; + set; + } + + [Description("DATA CONTROLE")] + public DateTime? DataControle + { + get; + set; + } + + [Description("DATA LIQUIDAÇÃO")] + public DateTime? DataLiquidacao + { + get; + set; + } + + [Description("DATA RECLAMAÇÃO")] + public DateTime? DataReclamacao + { + get; + set; + } + + [Description("DATA DO SINISTRO")] + public DateTime? DataSinistro + { + get; + set; + } + + [Description("DDD 2 PRIMEIRO LOCATÁRIO")] + public string Ddd2Locatario + { + get; + set; + } + + [Description("DDD PRIMEIRO LOCATÁRIO")] + public string DddLocatario + { + get; + set; + } + + [Description("DDD SEGUNDO LOCATÁRIO")] + public string DddLocatario2 + { + get; + set; + } + + [Description("DDD TERCEIRO LOCATÁRIO")] + public string DddLocatario3 + { + get; + set; + } + + [Description("DESCRIÇÃO DO ITEM")] + public string DescricaoItem + { + get; + set; + } + + [Description("DESCRIÇÃO DO SINISTRO")] + public string DescricaoSinistro + { + get; + set; + } + + [Description("DESCRIÇÃO DA TAREFA")] + public string DescricaoTarefa + { + get; + set; + } + + [Description("DOCUMENTO PRINCIPAL")] + public string DocumentoCliente + { + get; + set; + } + + [Description("DOCUMENTO DO CONTATO")] + public string DocumentoContato + { + get; + set; + } + + [Description("DOCUMENTO PRIMEIRO LOCATÁRIO")] + public string DocumentoLocatario + { + get; + set; + } + + [Description("DOCUMENTO SEGUNDO LOCATÁRIO")] + public string DocumentoLocatario2 + { + get; + set; + } + + [Description("DOCUMENTO TERCEIRO LOCATÁRIO")] + public string DocumentoLocatario3 + { + get; + set; + } + + [Description("DOCUMENTO SINISTRADO")] + public string DocumentoSinistrado + { + get; + set; + } + + [Description("E-MAIL1")] + public string Email1 + { + get; + set; + } + + [Description("E-MAIL2")] + public string Email2 + { + get; + set; + } + + [Description("E-MAIL DO CONTATO")] + public string EmailContato + { + get; + set; + } + + [Description("EMISSÃO")] + public DateTime? Emissao + { + get; + set; + } + + [Description("EMISSOR")] + public string EmissorCliente + { + get; + set; + } + + [Description("ENDEREÇO")] + public string Endereco + { + get; + set; + } + + [Description("ENDEREÇO DO ITEM")] + public string EnderecoItem + { + get; + set; + } + + [Description("ESTADO")] + public string Estado + { + get; + set; + } + + [Description("ESTADO CIVIL")] + public string EstadoCivilCliente + { + get; + set; + } + + [Description("ESTADO CIVIL PERFIL")] + public string EstadoCivilPerfil + { + get; + set; + } + + [Description("ESTADO EMISSOR")] + public string EstadoEmissorCliente + { + get; + set; + } + + [Description("ESTIPULANTE 1 DOCUMENTO")] + public string Estipulante + { + get; + set; + } + + [Description("ESTIPULANTE 2 DOCUMENTO")] + public string Estipulante2 + { + get; + set; + } + + [Description("ESTIPULANTE 3 DOCUMENTO")] + public string Estipulante3 + { + get; + set; + } + + [Description("ESTIPULANTE 4 DOCUMENTO")] + public string Estipulante4 + { + get; + set; + } + + [Description("ESTIPULANTE 5 DOCUMENTO")] + public string Estipulante5 + { + get; + set; + } + + [Description("EXPEDIÇÃO")] + public DateTime? ExpedicaoCliente + { + get; + set; + } + + [Description("EXPEDIÇÃO DO CONTATO")] + public DateTime? ExpedicaoContato + { + get; + set; + } + + [Description("FABRICANTE")] + public string Fabricante + { + get; + set; + } + + [Description("FABRICANTE AERONÁUTICO")] + public string FabricanteAero + { + get; + set; + } + + [Description("FALECIDO")] + public string FalecidoCliente + { + get; + set; + } + + [Description("FINANCIADO")] + public string Financiado + { + get; + set; + } + + [Description("FORMA DE PAGAMENTO")] + public string FormaPagamento + { + get; + set; + } + + [Description("FROTA")] + public string Frota + { + get; + set; + } + + [Description("FUNCIONÁRIOS")] + public int? FuncionariosVida + { + get; + set; + } + + [Description("GRUPO")] + public string Grupo + { + get; + set; + } + + [Description("HIBILITAÇÃO")] + public string HabilitacaoCliente + { + get; + set; + } + + [Description("HABILITAÇÃO DO CONTATO")] + public string HabilitacaoContato + { + get; + set; + } + + [Description("CÓDIGO DOCUMENTO")] + public long IdDocumento + { + get; + set; + } + + [Description("IDENTIDADE")] + public string IdentidadeCliente + { + get; + set; + } + + [Description("IDENTIDADE DO CONTATO")] + public string IdentidadeContato + { + get; + set; + } + + [Description("IMOBILIÁRIA DO ITEM")] + public string ImobiliariaPatrimonial + { + get; + set; + } + + [Description("IOF")] + public decimal? Iof + { + get; + set; + } + + [Description("INSENÇÃO")] + public string Isencao + { + get; + set; + } + + [Description("LÍQUIDO FATURA")] + public decimal? LiquidoFatura + { + get; + set; + } + + [Description("PRIMEIRO LOCATÁRIO")] + public string Locatario + { + get; + set; + } + + [Description("SEGUNDO LOCATÁRIO")] + public string Locatario2 + { + get; + set; + } + + [Description("TERCEIRO LOCATÁRIO")] + public string Locatario3 + { + get; + set; + } + + [Description("MARINA AÉREO")] + public string MarinaAero + { + get; + set; + } + + [Description("MODELO")] + public string Modelo + { + get; + set; + } + + [Description("MODELO")] + public string ModeloAero + { + get; + set; + } + + [Description("MOTIVO DO SINISTRO")] + public string MotivoSinistro + { + get; + set; + } + + [Description("NASCIMENTO")] + public DateTime? NascimentoCliente + { + get; + set; + } + + [Description("NASCIMENTO DO CONTATO")] + public DateTime? NascimentoContato + { + get; + set; + } + + [Description("NASCIMENTO PERFIL")] + public DateTime? NascimentoPerfil + { + get; + set; + } + + [Description("NAVEGAÇÃO")] + public string NavegacaoAero + { + get; + set; + } + + [Description("NEGÓCIO CORRETORA")] + public string Negocio + { + get; + set; + } + + [Description("NOME PREFIXO")] + public string NomeAero + { + get; + set; + } + + [Description("NOME DO CLIENTE")] + public string NomeCliente + { + get; + set; + } + + [Description("NOME DO CONTATO")] + public string NomeContato + { + get; + set; + } + + [Description("NOME PERFIL")] + public string NomePerfil + { + get; + set; + } + + [Description("NÚMERO")] + public string Numero + { + get; + set; + } + + [Description("APÓLICE")] + public string NumeroApolice + { + get; + set; + } + + [Description("ENDOSSO")] + public string NumeroEndosso + { + get; + set; + } + + [Description("NÚMERO DO ITEM")] + public string NumeroItem + { + get; + set; + } + + [Description("PEDIDO ENDOSSO")] + public string NumeroPedidoEndosso + { + get; + set; + } + + [Description("PROPOSTA")] + public string NumeroProposta + { + get; + set; + } + + [Description("NÚMERO DO SINISTRO")] + public string NumeroSinistro + { + get; + set; + } + + [Description("NÚMERO DE PARCELAS")] + public int? NumParcelas + { + get; + set; + } + + [Description("OBSERVAÇÃO DO AERO")] + public string ObsAero + { + get; + set; + } + + [Description("OBSERVAÇÃO DO AUTO")] + public string ObsAuto + { + get; + set; + } + + [Description("OBSERVAÇÃO")] + public string ObservacaoCliente + { + get; + set; + } + + [Description("OBSERVAÇÃO DOCUMENTO")] + public string ObservacaoDocumento + { + get; + set; + } + + [Description("OBSERVAÇÃO DO ITEM")] + public string ObsGranizo + { + get; + set; + } + + [Description("OBSERVAÇÃO DO ITEM")] + public string ObsItem + { + get; + set; + } + + [Description("OBSERVAÇÃO DO ITEM")] + public string ObsPatrimonial + { + get; + set; + } + + [Description("OBSERVAÇÕES DA PROSPECÇÃO")] + public string ObsProspeccao + { + get; + set; + } + + [Description("OBSERVAÇÃO RISCOS DIVERSOS")] + public string ObsRiscos + { + get; + set; + } + + [Description("OBSERVAÇÃO DO SINISTRO")] + public string ObsSinistro + { + get; + set; + } + + [Description("OBSERVAÇÃO DE VIDA")] + public string ObsVida + { + get; + set; + } + + [Description("PARENTESCO")] + public string Parentesco + { + get; + set; + } + + [Description("PASSAGEIROS")] + public int? PassageirosAero + { + get; + set; + } + + [Description("PASTA")] + public string PastaCliente + { + get; + set; + } + + [Description("PCD")] + public string Pcd + { + get; + set; + } + + [Description("PESO")] + public decimal? PesoAero + { + get; + set; + } + + [Description("PLACA")] + public string Placa + { + get; + set; + } + + [Description("PLANO")] + public string PlanoVida + { + get; + set; + } + + [Description("PORCENTAGEM DE REFERÊNCIA")] + public decimal? PorcRef + { + get; + set; + } + + [Description("PORTAS")] + public string Portas + { + get; + set; + } + + [Description("PREFIXO1")] + public string Prefixo1 + { + get; + set; + } + + [Description("PREFIXO2")] + public string Prefixo2 + { + get; + set; + } + + [Description("PREFIXO3")] + public string Prefixo3 + { + get; + set; + } + + [Description("PREFIXO DO CONTATO")] + public string PrefixoContato + { + get; + set; + } + + [Description("PRÊMIO ADICIONAL")] + public decimal? PremioAdicional + { + get; + set; + } + + [Description("PRÊMIO CUSTO")] + public decimal? PremioCusto + { + get; + set; + } + + [Description("PRÊMIO LÍQUIDO")] + public decimal? PremioLiquido + { + get; + set; + } + + [Description("PRÊMIO TOTAL")] + public decimal? PremioTotal + { + get; + set; + } + + [Description("PRIMEIRA HABILITAÇÃO")] + public DateTime? PrimeiraHabilitacaoCliente + { + get; + set; + } + + [Description("PRIMEIRA HABILITAÇÃO DO CONTATO")] + public DateTime? PrimeiraHabilitacaoContato + { + get; + set; + } + + [Description("PRODUTO")] + public string Produto + { + get; + set; + } + + [Description("PROFISSÃO")] + public string ProfissaoCliente + { + get; + set; + } + + [Description("QUANTIDADE DE ENDOSSOS")] + public int QtdeEndosso + { + get; + set; + } + + [Description("QUANTIDADE DE SINISTROS")] + public int QtdeSinistro + { + get; + set; + } + + [Description("RAMO")] + public string Ramo + { + get; + set; + } + + [Description("REGIÃO DE CIRCULAÇÃO")] + public string RegCirc + { + get; + set; + } + + [Description("TRANSMISSÃO")] + public DateTime? Remessa + { + get; + set; + } + + [Description("RENAVAM")] + public string Renavam + { + get; + set; + } + + [Description("R.N.E.")] + public string RneCliente + { + get; + set; + } + + [Description("SEGURADORA")] + public string Seguradora + { + get; + set; + } + + [Description("SEGURADORA ANTERIOR")] + public string SeguradoraAnterior + { + get; + set; + } + + [Description("SÉRIE DE REGISTRO")] + public string SerieAero + { + get; + set; + } + + [Description("SEXO")] + public string SexoCliente + { + get; + set; + } + + [Description("SEXO PERFIL")] + public string SexoPerfil + { + get; + set; + } + + [Description("ITEM SINISTRADO")] + public string SinistradoItem + { + get; + set; + } + + [Description("SÍTIO DO GRANIZO")] + public string SitioGranizo + { + get; + set; + } + + [Description("SÓCIOS")] + public int? SociosVida + { + get; + set; + } + + [Description("STATUS")] + public string Status + { + get; + set; + } + + [Description("STATUS DO ITEM")] + public string StatusItem + { + get; + set; + } + + [Description("SUBSÍDIO ESTADUAL DO GRANIZO")] + public decimal? SubEstGranizo + { + get; + set; + } + + [Description("SUBSÍDIO ESTADUAL RISCOS DIVERSOS")] + public decimal? SubEstRiscos + { + get; + set; + } + + [Description("SUBSÍDIO FEDERAL DO GRANIZO")] + public decimal? SubFedGranizo + { + get; + set; + } + + [Description("SUBSÍDIO FEDERAL RISCOS DIVERSOS")] + public decimal? SubFedRiscos + { + get; + set; + } + + [Description("TABELA DE REFERÊNCIA")] + public string TabelaRef + { + get; + set; + } + + [Description("TELEFONE1")] + public string Telefone1 + { + get; + set; + } + + [Description("TELEFONE2")] + public string Telefone2 + { + get; + set; + } + + [Description("TELEFONE 2 PRIMEIRO LOCATÁRIO")] + public string Telefone2Locatario + { + get; + set; + } + + [Description("TELEFONE3")] + public string Telefone3 + { + get; + set; + } + + [Description("TELEFONE DO CONTATO")] + public string TelefoneContato + { + get; + set; + } + + [Description("TELEFONE PRIMEIRO LOCATÁRIO")] + public string TelefoneLocatario + { + get; + set; + } + + [Description("TELEFONE SEGUNDO LOCATÁRIO")] + public string TelefoneLocatario2 + { + get; + set; + } + + [Description("TELEFONE TERCEIRO LOCATÁRIO")] + public string TelefoneLocatario3 + { + get; + set; + } + + [Description("TIPO DA PROSPECÇÃO")] + public string TipoProspeccao + { + get; + set; + } + + [Description("TIPO DO RECEBIMENTO")] + public string TipoRecebimento + { + get; + set; + } + + [Description("TIPO DE RESIDÊNCIA DO ITEM")] + public string TipoResidenciaPatrimonial + { + get; + set; + } + + [Description("TITULO DA TAREFA")] + public string TituloTarefa + { + get; + set; + } + + [Description("TOTAL FATURA")] + public decimal? TotalFatura + { + get; + set; + } + + [Description("TRIPULANTES")] + public int? TripulantesAero + { + get; + set; + } + + [Description("UF DO ITEM")] + public string UfItem + { + get; + set; + } + + [Description("VALOR CRÉDITO")] + public decimal? ValorCredito + { + get; + set; + } + + [Description("VALOR DETERMINADO")] + public decimal? ValorDeterminado + { + get; + set; + } + + [Description("FRANQUIA DA APÓLICE")] + public decimal? ValorFranquiaApolice + { + get; + set; + } + + [Description("VALOR FRANQUIA")] + public decimal? ValorFranquiaSinistro + { + get; + set; + } + + [Description("VALOR LIBERADO")] + public decimal? ValorLiberado + { + get; + set; + } + + [Description("VALOR ORÇADO")] + public decimal? ValorOrcado + { + get; + set; + } + + [Description("VALOR PAGO")] + public decimal? ValorPago + { + get; + set; + } + + [Description("VALOR PARCELAS")] + public decimal? ValorParcela + { + get; + set; + } + + [Description("VALOR SALVO")] + public decimal? ValorSalvo + { + get; + set; + } + + [Description("VALOR DO SINISTRO")] + public decimal? ValorSinistro + { + get; + set; + } + + [Description("VENCIMENTO DA HABILITAÇÃO")] + public DateTime? VencimentoHabilitacaoCliente + { + get; + set; + } + + [Description("VENDEDOR PRINCIPAL")] + public string Vendedor + { + get; + set; + } + + [Description("VIGÊNCIA FINAL")] + public DateTime? VigenciaFinal + { + get; + set; + } + + [Description("VIGÊNCIA INICIAL")] + public DateTime? VigenciaInicial + { + get; + set; + } + + [Description("VISTORIA")] + public DateTime? VistoriaAero + { + get; + set; + } + + [Description("ZERO KM")] + public string ZeroKm + { + get; + set; + } + + public PlanilhaCompleta() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/PrevisaoPagamentoComissao/AgrupamentoSintetico.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/PrevisaoPagamentoComissao/AgrupamentoSintetico.cs new file mode 100644 index 0000000..2ca7a64 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/PrevisaoPagamentoComissao/AgrupamentoSintetico.cs @@ -0,0 +1,37 @@ +using Gestor.Model.Attributes; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.PrevisaoPagamentoComissao +{ + public class AgrupamentoSintetico + { + [Description("NOME")] + public string Nome + { + get; + set; + } + + [Description("PREVISÃO LÍQUIDA")] + [Tipo("VALOR")] + public decimal PrevisaoLiquida + { + get; + set; + } + + [Description("PREVISÃO DE PAGAMENTO")] + [Tipo("VALOR")] + public decimal PrevisaoPagamento + { + get; + set; + } + + public AgrupamentoSintetico() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/PrevisaoPagamentoComissao/PrevisaoPagamento.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/PrevisaoPagamentoComissao/PrevisaoPagamento.cs new file mode 100644 index 0000000..f811010 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/PrevisaoPagamentoComissao/PrevisaoPagamento.cs @@ -0,0 +1,132 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Seguros; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.PrevisaoPagamentoComissao +{ + public class PrevisaoPagamento + { + [Description("APÓLICE")] + public string Apolice + { + get; + set; + } + + [Description("ENDOSSO")] + public string Endosso + { + get; + set; + } + + [Description("NOME")] + public string Nome + { + get; + set; + } + + [Description("RAMO")] + public string NomeRamo + { + get; + set; + } + + [Description("SEGURADORA")] + public string NomeSeguradora + { + get; + set; + } + + [Description("PARCELA")] + public string Parcela + { + get; + set; + } + + [Description("PRÊMIO LÍQUIDO")] + [Tipo("VALOR")] + public decimal PremioLiquido + { + get; + set; + } + + [Tipo("INVALID")] + public string Ramo + { + get; + set; + } + + [Description("REPASSE")] + [Tipo("VALOR")] + public decimal Repasse + { + get; + set; + } + + [Description("REPASSE LÍQUIDO")] + [Tipo("VALOR")] + public decimal RepasseLiquido + { + get; + set; + } + + [Tipo("INVALID")] + public string Seguradora + { + get; + set; + } + + [Description("STATUS")] + public string Status + { + get; + set; + } + + [Description("TIPO DOCUMENTO")] + public string TipoDocumento + { + get; + set; + } + + [Description("VENCIMENTO PARCELA")] + [Tipo("DATA")] + public DateTime VencimentoParcela + { + get; + set; + } + + [Tipo("INVALID")] + public Gestor.Model.Domain.Seguros.Vendedor Vendedor + { + get; + set; + } + + [Description("VIGÊNCIA INICIAL")] + [Tipo("DATA")] + public DateTime VigenciaInicial + { + get; + set; + } + + public PrevisaoPagamento() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/PrevisaoPagamentoComissao/PrevisaoPagamentoComissao.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/PrevisaoPagamentoComissao/PrevisaoPagamentoComissao.cs new file mode 100644 index 0000000..af70774 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/PrevisaoPagamentoComissao/PrevisaoPagamentoComissao.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.ObjectModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.PrevisaoPagamentoComissao +{ + public class PrevisaoPagamentoComissao + { + public ObservableCollection<Gestor.Model.Domain.Relatorios.PrevisaoPagamentoComissao.PrevisaoPagamento> PrevisaoPagamento + { + get; + set; + } + + public string Vendedor + { + get; + set; + } + + public PrevisaoPagamentoComissao() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/PrevisaoPagamentoComissao/PrevisaoPagamentoComissaoSintetico.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/PrevisaoPagamentoComissao/PrevisaoPagamentoComissaoSintetico.cs new file mode 100644 index 0000000..823aa88 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/PrevisaoPagamentoComissao/PrevisaoPagamentoComissaoSintetico.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.ObjectModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.PrevisaoPagamentoComissao +{ + public class PrevisaoPagamentoComissaoSintetico + { + public ObservableCollection<AgrupamentoSintetico> Agrupamento + { + get; + set; + } + + public string Titulo + { + get; + set; + } + + public PrevisaoPagamentoComissaoSintetico() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/Producao/Producao.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Producao/Producao.cs new file mode 100644 index 0000000..9202bb8 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Producao/Producao.cs @@ -0,0 +1,372 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.Producao +{ + public class Producao + { + [Description("AGÊNCIA")] + public string Agencia + { + get; + set; + } + + [Description("APÓLICE")] + public string Apolice + { + get; + set; + } + + [Description("APÓLICE CONFERIDA")] + public string ApoliceConferida + { + get; + set; + } + + [Description("PROP. ASSINADA SIGGNER")] + public string AssinadaSiggner + { + get; + set; + } + + [Tipo("INVALID")] + public List<StatusDocumentoAssinado> Assinaturas + { + get; + set; + } + + [Description("BANCO")] + public string Banco + { + get; + set; + } + + [Description("CLIENTE")] + public string Cliente + { + get; + set; + } + + [Description("COMISSÃO")] + [Tipo("PERCENTUAL")] + public decimal Comissao + { + get; + set; + } + + [Description("COMISSÃO GERADA")] + [Tipo("VALOR")] + public decimal ComissaoGerada + { + get; + set; + } + + [Description("CONTA")] + public string Conta + { + get; + set; + } + + [Description("DATA CONTROLE")] + public DateTime? DataControle + { + get; + set; + } + + [Description("DATA DE CADASTRO")] + [Tipo("DATA?")] + public DateTime? DataCriacao + { + get; + set; + } + + [Description("TIPO VENDEDORES")] + public string DescricaoTipoVendedor + { + get; + set; + } + + [Tipo("INVALID")] + public Gestor.Model.Domain.Seguros.Documento Documento + { + get; + set; + } + + [Description("DOCUMENTO DO CLIENTE")] + public string DocumentoCliente + { + get; + set; + } + + [Description("EMAILS")] + public string Emails + { + get; + set; + } + + [Description("EMISSÃO")] + [Tipo("DATA?")] + public DateTime? Emissao + { + get; + set; + } + + [Description("FILIAL")] + public string Empresa + { + get; + set; + } + + [Description("ENDOSSO")] + public string Endosso + { + get; + set; + } + + [Description("ESTIPULANTE")] + public string Estipulante + { + get; + set; + } + + [Tipo("INVALID")] + public long IdEmpresa + { + get; + set; + } + + [Description("ITEM")] + public string Item + { + get; + set; + } + + [Description("NEGÓCIO CORRETORA")] + public string Negocio + { + get; + set; + } + + [Description("QUANTIDADE PARCELAS")] + [Tipo("QUANTIDADE")] + public decimal NumeroParcelas + { + get; + set; + } + + [Description("PASTA")] + public string Pasta + { + get; + set; + } + + [Description("PASTA CLIENTE")] + public string PastaCliente + { + get; + set; + } + + [Description("PRÊMIO LÍQUIDO")] + [Tipo("VALOR")] + public decimal PremioLiquido + { + get; + set; + } + + [Description("PRÊMIO TOTAL")] + [Tipo("VALOR")] + public decimal PremioTotal + { + get; + set; + } + + [Description("PRODUTO")] + public string Produto + { + get; + set; + } + + [Description("PROPOSTA ASSINADA")] + public string PropAssinada + { + get; + set; + } + + [Description("PROPOSTA")] + public string Proposta + { + get; + set; + } + + [Description("PROPOSTA ENDOSSO")] + public string PropostaEndosso + { + get; + set; + } + + [Description("RAMO")] + public string Ramo + { + get; + set; + } + + [Description("TRANSMISSÃO")] + [Tipo("DATA?")] + public DateTime? Remessa + { + get; + set; + } + + [Description("REPASSE VENDEDOR")] + [Tipo("VALORDECIMAL2")] + public decimal? RepasseVendedor + { + get; + set; + } + + [Description("SEGURADORA")] + public string Seguradora + { + get; + set; + } + + [Tipo("INVALID")] + public bool Selecionado + { + get; + set; + } + + [Description("STATUS")] + public string Status + { + get; + set; + } + + [Description("STATUS APÓLICE")] + public string StatusApolice + { + get; + set; + } + + [Description("STATUS ASSINATURA")] + [Tipo("ENUM")] + public Gestor.Model.Common.StatusAssinatura StatusAssinatura + { + get; + set; + } + + [Description("TELEFONES")] + public string Telefones + { + get; + set; + } + + [Tipo("INVALID")] + public int Tipo + { + get; + set; + } + + [Description("TIPO DOCUMENTO")] + public string TipoDocumento + { + get; + set; + } + + [Description("TIPO PAGAMENTO")] + public string TipoPagamento + { + get; + set; + } + + [Description("TIPO PESSOA")] + public string TipoPessoa + { + get; + set; + } + + [Description("TODOS VENDEDORES")] + public string TodosVendedores + { + get; + set; + } + + [Description("VENDEDOR")] + public string Vendedor + { + get; + set; + } + + [Description("VIGÊNCIA FINAL")] + [Tipo("DATA?")] + public DateTime? VigenciaFinal + { + get; + set; + } + + [Description("VIGÊNCIA INICIAL")] + [Tipo("DATA")] + public DateTime VigenciaInicial + { + get; + set; + } + + public Producao() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/Producao/SinteticoProducao.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Producao/SinteticoProducao.cs new file mode 100644 index 0000000..534ddc0 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Producao/SinteticoProducao.cs @@ -0,0 +1,68 @@ +using Gestor.Model.Attributes; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.Producao +{ + public class SinteticoProducao + { + [Description("QUANTIDADE DE APÓLICES")] + [Tipo("QUANTIDADE")] + public int Apolices + { + get; + set; + } + + public string Descricao + { + get; + set; + } + + [Description("QUANTIDADE DE ENDOSSOS")] + [Tipo("QUANTIDADE")] + public int Endossos + { + get; + set; + } + + [Description("MÉDIA DE COMISSÃO")] + [Tipo("PERCENTUAL")] + public decimal MediaComissao + { + get; + set; + } + + [Description("SOMA PRÊMIO LÍQUIDO")] + [Tipo("VALOR")] + public decimal PremioLiquido + { + get; + set; + } + + [Description("SOMA PRÊMIO TOTAL")] + [Tipo("VALOR")] + public decimal PremioTotal + { + get; + set; + } + + [Description("TOTAL DE DOCUMENTOS")] + [Tipo("QUANTIDADE")] + public int Total + { + get; + set; + } + + public SinteticoProducao() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/Renovacao/Renovacao.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Renovacao/Renovacao.cs new file mode 100644 index 0000000..2c2c547 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Renovacao/Renovacao.cs @@ -0,0 +1,296 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Aggilizador; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.Renovacao +{ + public class Renovacao + { + [Description("AGÊNCIA")] + public string Agencia + { + get; + set; + } + + [Description("APÓLICE")] + public string Apolice + { + get; + set; + } + + [Description("BANCO")] + public string Banco + { + get; + set; + } + + [Tipo("INVALID")] + public List<Calculo> Calculos + { + get; + set; + } + + [Description("CLIENTE")] + public string Cliente + { + get; + set; + } + + [Description("COMISSÃO")] + [Tipo("PERCENTUAL")] + public decimal Comissao + { + get; + set; + } + + [Description("COMISSÃO GERADA")] + [Tipo("VALOR")] + public decimal ComissaoGerada + { + get; + set; + } + + [Description("CONTA")] + public string Conta + { + get; + set; + } + + [Description("DATA CONTROLE")] + [Tipo("DATA?")] + public DateTime? DataControle + { + get; + set; + } + + [Tipo("INVALID")] + public Gestor.Model.Domain.Seguros.Documento Documento + { + get; + set; + } + + [Description("DOCUMENTO DO CLIENTE")] + public string DocumentoCliente + { + get; + set; + } + + [Description("E-MAIL")] + public string Email + { + get; + set; + } + + [Description("FILIAL")] + public string Empresa + { + get; + set; + } + + [Description("ENDOSSO")] + public string Endosso + { + get; + set; + } + + [Description("ESTIPULANTE")] + public string Estipulante + { + get; + set; + } + + public long IdEmpresa + { + get; + set; + } + + [Description("ITEM")] + public string Item + { + get; + set; + } + + [Description("TIPO RENOVAÇÃO")] + public string Negocio + { + get; + set; + } + + [Description("PASTA")] + public string Pasta + { + get; + set; + } + + [Description("PASTA CLIENTE")] + public string PastaCliente + { + get; + set; + } + + [Description("PRÊMIO LÍQUIDO")] + [Tipo("VALOR")] + public decimal PremioLiquido + { + get; + set; + } + + [Description("PRÊMIO TOTAL")] + [Tipo("VALOR")] + public decimal PremioTotal + { + get; + set; + } + + [Description("PRODUTO")] + public string Produto + { + get; + set; + } + + [Tipo("INVALID")] + public Gestor.Model.Domain.Seguros.Prospeccao Prospeccao + { + get; + set; + } + + [Description("SINISTROS ITENS ATIVOS")] + [Tipo("INT")] + public int QtdSinistro + { + get; + set; + } + + [Description("RAMO")] + public string Ramo + { + get; + set; + } + + [Description("SEGURADORA")] + public string Seguradora + { + get; + set; + } + + [Tipo("INVALID")] + public bool Selecionado + { + get; + set; + } + + [Description("SINISTRO")] + public string Sinistro + { + get; + set; + } + + [Description("STATUS")] + public string Status + { + get; + set; + } + + [Description("STATUS APÓLICE")] + public string StatusApolice + { + get; + set; + } + + [Description("TELEFONE")] + public string Telefone + { + get; + set; + } + + [Tipo("INVALID")] + public int Tipo + { + get; + set; + } + + [Description("TIPO DOCUMENTO")] + public string TipoDocumento + { + get; + set; + } + + [Description("TIPO PAGAMENTO")] + public string TipoPagamento + { + get; + set; + } + + [Description("TIPO DE PESSOA")] + public string TipoPessoa + { + get; + set; + } + + [Description("TODOS VENDEDORES")] + public string TodosVendedores + { + get; + set; + } + + [Description("VENDEDOR PRINCIPAL")] + public string Vendedor + { + get; + set; + } + + [Description("VIGÊNCIA FINAL")] + [Tipo("DATA?")] + public DateTime? VigenciaFinal + { + get; + set; + } + + public Renovacao() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/Renovacao/SinteticoRenovacao.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Renovacao/SinteticoRenovacao.cs new file mode 100644 index 0000000..c2c3cb7 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Renovacao/SinteticoRenovacao.cs @@ -0,0 +1,76 @@ +using Gestor.Model.Attributes; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.Renovacao +{ + public class SinteticoRenovacao + { + [Description("CANCELADOS")] + [Tipo("QUANTIDADE")] + public int Cancelados + { + get; + set; + } + + public string Descricao + { + get; + set; + } + + [Description("NÃO TRABALHADOS")] + [Tipo("QUANTIDADE")] + public int NaoTrabalhados + { + get; + set; + } + + [Description("PERDIDOS")] + [Tipo("QUANTIDADE")] + public int Perdidos + { + get; + set; + } + + [Description("REABILITADOS")] + [Tipo("QUANTIDADE")] + public int Reabilitados + { + get; + set; + } + + [Description("RECUSADOS")] + [Tipo("QUANTIDADE")] + public int Recusados + { + get; + set; + } + + [Description("RENOVADOS")] + [Tipo("QUANTIDADE")] + public int Renovados + { + get; + set; + } + + [Description("TOTAL DE RENOVAÇÕES")] + [Tipo("QUANTIDADE")] + public int Total + { + get; + set; + } + + public SinteticoRenovacao() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/Sinistro/Sinistro.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Sinistro/Sinistro.cs new file mode 100644 index 0000000..67f9c76 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Sinistro/Sinistro.cs @@ -0,0 +1,359 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using Gestor.Model.Domain.Seguros; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.Sinistro +{ + public class Sinistro + { + [Description("APÓLICE")] + public string Apolice + { + get; + set; + } + + [Description("AUXILIAR")] + public string Auxiliar + { + get; + set; + } + + [Tipo("INVALID")] + public Gestor.Model.Domain.Seguros.Cliente Cliente + { + get; + set; + } + + [Description("CPF/CNPJ")] + public string CpfCnpj + { + get; + set; + } + + [Description("DATA ALTERAÇÃO")] + public DateTime? DataAlteracao + { + get; + set; + } + + [Description("DATA CONTROLE")] + [Tipo("DATA?")] + public DateTime? DataControle + { + get; + set; + } + + [Description("DATA CRIAÇÃO")] + public DateTime? DataCriacao + { + get; + set; + } + + [Description("DATA OCORRÊNCIA")] + [Tipo("DATA/TIME")] + public DateTime DataSinistro + { + get; + set; + } + + [Tipo("INVALID")] + public Gestor.Model.Domain.Seguros.Documento Documento + { + get; + set; + } + + [Description("E-MAIL")] + public string Email + { + get; + set; + } + + [Description("FILIAL")] + public string Empresa + { + get; + set; + } + + [Description("ENDOSSO")] + public string Endosso + { + get; + set; + } + + [Tipo("INVALID")] + public Gestor.Model.Domain.Seguros.Item EntidadeItem + { + get; + set; + } + + [Tipo("INVALID")] + public Gestor.Model.Domain.Seguros.Sinistro EntidadeSinistro + { + get; + set; + } + + [Description("ESTIPULANTE")] + public string Estipulante + { + get; + set; + } + + [Description("FUNILARIA")] + public string Funilaria + { + get; + set; + } + + [Tipo("INVALID")] + public long IdEmpresa + { + get; + set; + } + + [Description("ITEM")] + public string Item + { + get; + set; + } + + [Description("LIQUIDAÇÃO")] + [Tipo("DATA?")] + public DateTime? Liquidacao + { + get; + set; + } + + [Description("MECÂNICA")] + public string Mecanica + { + get; + set; + } + + [Description("MOTIVO")] + public string Motivo + { + get; + set; + } + + [Description("NOME")] + public string Nome + { + get; + set; + } + + [Description("NÚMERO SINISTRO")] + public string NumeroSinistro + { + get; + set; + } + + [Description("PASTA")] + public string Pasta + { + get; + set; + } + + [Description("PASTA CLIENTE")] + public string PastaCliente + { + get; + set; + } + + [Description("PENDÊNCIA")] + public int Pendencia + { + get; + set; + } + + [Description("RAMO")] + public string Ramo + { + get; + set; + } + + [Description("RECLAMAÇÃO")] + [Tipo("DATA/TIME")] + public DateTime Reclamacao + { + get; + set; + } + + [Description("SEGURADORA")] + public string Seguradora + { + get; + set; + } + + [Tipo("INVALID")] + public bool Selecionado + { + get; + set; + } + + [Description("STATUS APÓLICE")] + public string StatusApolice + { + get; + set; + } + + [Description("STATUS INTERNO")] + public string StatusPersonalizado + { + get; + set; + } + + [Description("STATUS")] + [Tipo("ENUM")] + public Gestor.Model.Common.StatusSinistro StatusSinistro + { + get; + set; + } + + [Description("TELEFONE")] + public string Telefone + { + get; + set; + } + + [Description("TIPO PERDA")] + public string TipoPerda + { + get; + set; + } + + [Description("TIPO")] + [Tipo("ENUM")] + public Gestor.Model.Common.TipoSinistro TipoSinistro + { + get; + set; + } + + [Description("USUÁRIO ALTERAÇÃO")] + public string UsuarioAlteracao + { + get; + set; + } + + [Description("USUÁRIO CRIAÇÃO")] + public string UsuarioCriacao + { + get; + set; + } + + [Description("VALOR")] + [Tipo("VALOR")] + public decimal Valor + { + get; + set; + } + + [Description("VALOR FRANQUIA")] + [Tipo("VALOR")] + public decimal ValorFranquia + { + get; + set; + } + + [Description("VALOR LIBERADO")] + [Tipo("VALOR")] + public decimal ValorLiberado + { + get; + set; + } + + [Description("VALOR ORÇADO")] + [Tipo("VALOR")] + public decimal ValorOrcado + { + get; + set; + } + + [Description("VALOR PAGO")] + [Tipo("VALOR")] + public decimal ValorPago + { + get; + set; + } + + [Description("VALOR SALVADO")] + [Tipo("VALOR")] + public decimal ValorSalvado + { + get; + set; + } + + [Description("VENDEDOR PRINCIPAL")] + public string Vendedor + { + get; + set; + } + + [Description("VIGÊNCIA FINAL")] + [Tipo("DATA?")] + public DateTime? VigenciaFinal + { + get; + set; + } + + [Description("VIGÊNCIA INICIAL")] + [Tipo("DATA?")] + public DateTime? VigenciaInicial + { + get; + set; + } + + public Sinistro() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/Sinistro/SinteticoSinistro.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Sinistro/SinteticoSinistro.cs new file mode 100644 index 0000000..51c4025 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Sinistro/SinteticoSinistro.cs @@ -0,0 +1,68 @@ +using Gestor.Model.Attributes; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.Sinistro +{ + public class SinteticoSinistro + { + public string Descricao + { + get; + set; + } + + [Description("QUANTIDADE LIQUIDADO")] + [Tipo("QUANTIDADE")] + public int Liquidado + { + get; + set; + } + + [Description("QUANTIDADE PENDENTE")] + [Tipo("QUANTIDADE")] + public int Pendente + { + get; + set; + } + + [Description("TOTAL")] + [Tipo("QUANTIDADE")] + public int Total + { + get; + set; + } + + [Description("VALOR LIQUIDADO")] + [Tipo("VALOR")] + public decimal ValorLiquidado + { + get; + set; + } + + [Description("VALOR PENDENTE")] + [Tipo("VALOR")] + public decimal ValorPendente + { + get; + set; + } + + [Description("VALOR TOTAL")] + [Tipo("VALOR")] + public decimal ValorTotal + { + get; + set; + } + + public SinteticoSinistro() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/SinteticModel.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/SinteticModel.cs new file mode 100644 index 0000000..6542ac7 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/SinteticModel.cs @@ -0,0 +1,30 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios +{ + public class SinteticModel + { + public string DescriptionField + { + get; + set; + } + + public string Hint + { + get; + set; + } + + public object Value + { + get; + set; + } + + public SinteticModel() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/SinteticModelList.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/SinteticModelList.cs new file mode 100644 index 0000000..1f0cc2a --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/SinteticModelList.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios +{ + public class SinteticModelList + { + public string Hint + { + get; + set; + } + + public List<object> Value + { + get; + set; + } + + public SinteticModelList() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/Sintetico.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Sintetico.cs new file mode 100644 index 0000000..021791a --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Sintetico.cs @@ -0,0 +1,448 @@ +using Gestor.Model.Attributes; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios +{ + public class Sintetico + { + private const string categoriaSeguros = "SEGUROS"; + + private const string tipoQuantidade = "QUANTIDADE"; + + public const string descricaoNegociosProprios = "QUANTIDADE DE NEGÓCIOS PRÓPRIOS"; + + public const string propriedadeNegociosProprios = "NegociosProprios"; + + public const string descricaoSegurosNovos = "QUANTIDADE DE SEGUROS NOVOS"; + + public const string propriedadeSegurosNovos = "SegurosNovos"; + + [Category("FINANCEIRO")] + [Description("AGRUPAMENTO")] + public string Agrupamento + { + get; + set; + } + + [Category("SEGUROS")] + [Description("QUANTIDADE DE APÓLICES")] + [Tipo("QUANTIDADE")] + public int? Apolices + { + get; + set; + } + + [Category("SEGUROS")] + [Description("QUANTIDADE DE CANCELAMENTOS")] + [Tipo("QUANTIDADE")] + public int? Cancelamentos + { + get; + set; + } + + [Category("SEGUROS")] + [Description("TOTAL DE COMISSÃO GERADA")] + [Tipo("VALOR")] + public decimal? ComissaoGerada + { + get; + set; + } + + [Category("SEGUROS")] + [Description("COMISSÃO PENDENTE")] + [Tipo("VALOR")] + public decimal? ComissaoPendente + { + get; + set; + } + + [Category("SEGUROS")] + [Description("COMISSÃO PREVISTA")] + [Tipo("VALOR")] + public decimal? ComissaoPrevista + { + get; + set; + } + + [Category("SEGUROS")] + [Description("COMISSÃO RECEBIDA BRUTA")] + [Tipo("VALOR")] + public decimal? ComissaoRecebidaBruta + { + get; + set; + } + + [Category("SEGUROS")] + [Description("COMISSÃO RECEBIDA LÍQUIDA")] + [Tipo("VALOR")] + public decimal? ComissaoRecebidaLiquida + { + get; + set; + } + + [Category("SEGUROS")] + [Description("QUANTIDADE DE ENDOSSOS")] + [Tipo("QUANTIDADE")] + public int? Endossos + { + get; + set; + } + + [Category("SEGUROS")] + [Description("QUANTIDADE DE FATURAS (DOCUMENTOS)")] + [Tipo("QUANTIDADE")] + public int? Faturas + { + get; + set; + } + + [Category("SEGUROS")] + [Description("IMPOSTOS")] + [Tipo("VALOR")] + public decimal? Impostos + { + get; + set; + } + + [Category("SEGUROS")] + [Description("ISS")] + [Tipo("VALOR")] + public decimal? Iss + { + get; + set; + } + + [Category("SEGUROS")] + [Description("QUANTIDADE LIQUIDADO")] + [Tipo("QUANTIDADE")] + public int? Liquidado + { + get; + set; + } + + [Category("SEGUROS")] + [Description("MÉDIA DE COMISSÃO FECHADA")] + [Tipo("PERCENTUAL")] + public decimal? MediaComissao + { + get; + set; + } + + [Category("SEGUROS")] + [Description("MÉDIA DE COMISSÃO PONDERADA")] + [Tipo("PERCENTUAL")] + public decimal? MediaPonderada + { + get; + set; + } + + [Category("SEGUROS")] + [Description("% CUMPRIDA")] + [Tipo("PERCENTUAL")] + public decimal? Meta + { + get; + set; + } + + [Category("SEGUROS")] + [Description("META ATINGIR")] + [Tipo("VALOR")] + public decimal? MetaAtingir + { + get; + set; + } + + [Category("SEGUROS")] + [Description("META CUMPRIDA")] + [Tipo("VALOR")] + public decimal? MetaCumprida + { + get; + set; + } + + [Category("SEGUROS")] + [Description("QUANTIDADE DE NEGÓCIOS PRÓPRIOS")] + [Tipo("QUANTIDADE")] + public int? NegociosProprios + { + get; + set; + } + + [Category("SEGUROS")] + [Description("QUANTIDADE DE NOVOS NEGÓCIOS")] + [Tipo("QUANTIDADE")] + public int? Novos + { + get; + set; + } + + [Category("SEGUROS")] + [Description("QUANTIDADE PENDENTE")] + [Tipo("QUANTIDADE")] + public int? Pendente + { + get; + set; + } + + [Category("SEGUROS")] + [Description("PRÊMIO LÍQUIDO")] + [Tipo("VALOR")] + public decimal? PremioLiquido + { + get; + set; + } + + [Category("SEGUROS")] + [Description("PRÊMIO TOTAL")] + [Tipo("VALOR")] + public decimal? PremioTotal + { + get; + set; + } + + [Category("SEGUROS")] + [Description("QUANTIDADE DE RENOVAÇÕES")] + [Tipo("QUANTIDADE")] + public int? Renovacoes + { + get; + set; + } + + [Category("SEGUROS")] + [Description("REPASSE")] + [Tipo("VALOR")] + public decimal? Repasse + { + get; + set; + } + + [Category("SEGUROS")] + [Description("QUANTIDADE DE SEGUROS NOVOS")] + [Tipo("QUANTIDADE")] + public int? SegurosNovos + { + get; + set; + } + + [Category("SEGUROS")] + [Description("TOTAL DE CLIENTES")] + [Tipo("QUANTIDADE")] + public int? TotalClientes + { + get; + set; + } + + [Category("SEGUROS")] + [Description("TOTAL DE CLIENTES ATIVOS")] + [Tipo("QUANTIDADE")] + public int? TotalClientesAtivos + { + get; + set; + } + + [Category("SEGUROS")] + [Description("TOTAL DE CLIENTES INATIVOS")] + [Tipo("QUANTIDADE")] + public int? TotalClientesInativos + { + get; + set; + } + + [Category("SEGUROS")] + [Description("TOTAL GERAL")] + [Tipo("QUANTIDADE")] + public int? TotalGeral + { + get; + set; + } + + [Category("SEGUROS")] + [Description("TOTAL DE LÍQUIDO")] + [Tipo("QUANTIDADE")] + public int? TotalLiquido + { + get; + set; + } + + [Category("SEGUROS")] + [Description("TOTAL PARCELAS")] + [Tipo("VALOR")] + public decimal? TotalParcela + { + get; + set; + } + + [Category("SEGUROS")] + [Description("TOTAL PREVISTO")] + [Tipo("VALOR")] + public decimal? TotalPrevista + { + get; + set; + } + + [Category("SEGUROS")] + [Description("QUANTIDADE DE PROSPECÇÕES")] + [Tipo("QUANTIDADE")] + public int? TotalProspeccao + { + get; + set; + } + + [Category("SEGUROS")] + [Description("TOTAL DE TAREFAS")] + [Tipo("QUANTIDADE")] + public int? TotalTarefas + { + get; + set; + } + + [Category("SEGUROS")] + [Description("TOTAL DE TERCEIROS")] + [Tipo("QUANTIDADE")] + public int? TotalTerceiros + { + get; + set; + } + + [Category("FINANCEIRO")] + [Description("VALOR")] + [Tipo("VALOR")] + public decimal? Valor + { + get; + set; + } + + [Category("FINANCEIRO")] + [Description("VALOR BRUTO")] + [Tipo("VALOR")] + public decimal? ValorBruto + { + get; + set; + } + + [Category("FINANCEIRO")] + [Description("VALOR FRANQUIA")] + [Tipo("VALOR")] + public decimal? ValorFranquia + { + get; + set; + } + + [Category("FINANCEIRO")] + [Description("ISS")] + [Tipo("VALOR")] + public decimal? ValorIss + { + get; + set; + } + + [Category("FINANCEIRO")] + [Description("VALOR LIBERADO")] + [Tipo("VALOR")] + public decimal? ValorLiberado + { + get; + set; + } + + [Category("SEGUROS")] + [Description("VALOR LIQUIDADO")] + [Tipo("VALOR")] + public decimal? ValorLiquidado + { + get; + set; + } + + [Category("SEGUROS")] + [Description("VALOR LÍQUIDO")] + [Tipo("VALOR")] + public decimal? ValorLiquido + { + get; + set; + } + + [Category("FINANCEIRO")] + [Description("VALOR ORÇADO")] + [Tipo("VALOR")] + public decimal? ValorOrcado + { + get; + set; + } + + [Category("FINANCEIRO")] + [Description("VALOR PAGO")] + [Tipo("VALOR")] + public decimal? ValorPago + { + get; + set; + } + + [Category("SEGUROS")] + [Description("VALOR PARCELA")] + [Tipo("VALOR")] + public decimal? ValorParcela + { + get; + set; + } + + [Category("FINANCEIRO")] + [Description("VALOR SALVADO")] + [Tipo("VALOR")] + public decimal? ValorSalvado + { + get; + set; + } + + public Sintetico() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/SinteticoFinanceiro.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/SinteticoFinanceiro.cs new file mode 100644 index 0000000..4518ff3 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/SinteticoFinanceiro.cs @@ -0,0 +1,37 @@ +using Gestor.Model.Attributes; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios +{ + public class SinteticoFinanceiro + { + [Description("AGRUPAMENTO")] + public string Agrupamento + { + get; + set; + } + + [Description("VALOR")] + [Tipo("VALOR")] + public decimal? Valor + { + get; + set; + } + + [Description("VALOR PAGO")] + [Tipo("VALOR")] + public decimal? ValorPago + { + get; + set; + } + + public SinteticoFinanceiro() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/StatusRelatorio.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/StatusRelatorio.cs new file mode 100644 index 0000000..e93e9ff --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/StatusRelatorio.cs @@ -0,0 +1,58 @@ +using Gestor.Model.Common; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Gestor.Model.Domain.Relatorios +{ + public class StatusRelatorio : INotifyPropertyChanged + { + private bool _selecionado; + + public int Id + { + get; + set; + } + + public bool Selecionado + { + get + { + return this._selecionado; + } + set + { + if (value == this._selecionado) + { + return; + } + this._selecionado = value; + this.OnPropertyChanged("Selecionado"); + } + } + + public TipoSeguro Status + { + get; + set; + } + + public StatusRelatorio() + { + } + + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChangedEventHandler propertyChangedEventHandler = this.PropertyChanged; + if (propertyChangedEventHandler == null) + { + return; + } + propertyChangedEventHandler(this, new PropertyChangedEventArgs(propertyName)); + } + + public event PropertyChangedEventHandler PropertyChanged; + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/Tarefa/Tarefa.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Tarefa/Tarefa.cs new file mode 100644 index 0000000..856081d --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/Tarefa/Tarefa.cs @@ -0,0 +1,160 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios.Tarefa +{ + public class Tarefa + { + private string _usuario; + + private string _cliente; + + private string _referencia; + + private string _tipoTarefa; + + [Description("AGENDAMENTO")] + [Tipo("DATA/TIME")] + public DateTime Agendamento + { + get; + set; + } + + [Description("CLIENTE")] + public string Cliente + { + get + { + string str = this._cliente; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._cliente = value; + } + } + + [Description("CONCLUSÃO")] + [Tipo("DATA/TIME?")] + public DateTime? Conclusao + { + get; + set; + } + + [Tipo("INVALID")] + public Gestor.Model.Common.TipoTarefa Entidade + { + get; + set; + } + + [Tipo("INVALID")] + public long Id + { + get; + set; + } + + [Tipo("INVALID")] + public long IdCliente + { + get; + set; + } + + [Tipo("INVALID")] + public long IdEntidade + { + get; + set; + } + + [Description("REFERÊNCIA")] + public string Referencia + { + get + { + string str = this._referencia; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._referencia = value; + } + } + + [Tipo("INVALID")] + public bool Selecionado + { + get; + set; + } + + [Description("STATUS")] + public string Status + { + get; + set; + } + + [Description("TIPO DE TAREFA")] + public string TipoTarefa + { + get + { + string str = this._tipoTarefa; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._tipoTarefa = value; + } + } + + [Description("TÍTULO")] + public string Titulo + { + get; + set; + } + + [Description("USUÁRIO")] + public string Usuario + { + get + { + string str = this._usuario; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._usuario = value; + } + } + + public Tarefa() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/TipoRelatorio.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/TipoRelatorio.cs new file mode 100644 index 0000000..660d675 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/TipoRelatorio.cs @@ -0,0 +1,30 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios +{ + public class TipoRelatorio + { + public DateTime Fim + { + get; + set; + } + + public DateTime Inicio + { + get; + set; + } + + public string Nome + { + get; + set; + } + + public TipoRelatorio() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Relatorios/ValorSintetico.cs b/Codemerx/Gestor.Model/Model.Domain.Relatorios/ValorSintetico.cs new file mode 100644 index 0000000..10004d7 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Relatorios/ValorSintetico.cs @@ -0,0 +1,55 @@ +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Relatorios +{ + public class ValorSintetico + { + public string Formato + { + get; + set; + } + + public string Indice + { + get; + set; + } + + public string NomeRelatorio + { + get; + set; + } + + public string Porcentagem + { + get; + set; + } + + public Gestor.Model.Common.Sinal Sinal + { + get; + set; + } + + public string Unidate + { + get; + set; + } + + public decimal Valor + { + get; + set; + } + + public ValorSintetico() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/Adiantamento.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/Adiantamento.cs new file mode 100644 index 0000000..979ce16 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/Adiantamento.cs @@ -0,0 +1,145 @@ +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Validation; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class Adiantamento : DomainBase + { + private string _historico; + + public DateTime? Data + { + get; + set; + } + + public string Historico + { + get + { + string str = this._historico; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._historico = value; + } + } + + public DateTime? Pagamento + { + get; + set; + } + + public bool Pago + { + get; + set; + } + + public Gestor.Model.Common.TipoPagamento? TipoPagamento + { + get; + set; + } + + public decimal Valor + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Vendedor Vendedor + { + get; + set; + } + + public Adiantamento() + { + } + + public List<TupleList> Log() + { + string shortDateString; + string description; + string str; + List<TupleList> tupleLists = new List<TupleList>(); + TupleList tupleList = new TupleList(); + ObservableCollection<Tuple<string, string, string>> observableCollection = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("HISTÓRICO", (string.IsNullOrWhiteSpace(this.Historico) ? "" : this.Historico), "") + }; + DateTime? data = this.Data; + if (!data.HasValue) + { + shortDateString = ""; + } + else + { + data = this.Data; + if (data.HasValue) + { + shortDateString = data.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("DATA DO ADIANTAMENTO", shortDateString, "")); + decimal valor = this.Valor; + observableCollection.Add(new Tuple<string, string, string>("VALOR DO ADIANTAMENTO", valor.ToString("c2"), "")); + Gestor.Model.Common.TipoPagamento? tipoPagamento = this.TipoPagamento; + if (!tipoPagamento.HasValue) + { + description = ""; + } + else + { + tipoPagamento = this.TipoPagamento; + if (tipoPagamento.HasValue) + { + description = tipoPagamento.GetValueOrDefault().GetDescription(); + } + else + { + description = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("TIPO DO PAGAMENTO", description, "")); + observableCollection.Add(new Tuple<string, string, string>("PAGO", (this.Pago ? "SIM" : "NÃO"), "")); + data = this.Pagamento; + if (!data.HasValue) + { + str = ""; + } + else + { + data = this.Pagamento; + if (data.HasValue) + { + str = data.GetValueOrDefault().ToShortDateString(); + } + else + { + str = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("DATA DO PAGAMENTO", str, "")); + tupleList.Tuples = observableCollection; + tupleLists.Add(tupleList); + return tupleLists; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/Aeronautico.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/Aeronautico.cs new file mode 100644 index 0000000..09f19f9 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/Aeronautico.cs @@ -0,0 +1,475 @@ +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Gestor.Model.Validation; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Globalization; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class Aeronautico : DomainBase, IDomain + { + private string _fabricante; + + private string _modelo; + + private string _serie; + + private string _prefixo; + + private string _marinaAero; + + private string _certificado; + + private string _casco; + + private string _navegacao; + + private string _observacao; + + public string Casco + { + get + { + string str = this._casco; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._casco = value; + } + } + + public string Certificado + { + get + { + string str = this._certificado; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._certificado = value; + } + } + + public int? Fabricacao + { + get; + set; + } + + public string Fabricante + { + get + { + string str = this._fabricante; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._fabricante = value; + } + } + + public Gestor.Model.Domain.Seguros.Item Item + { + get; + set; + } + + public string MarinaAero + { + get + { + string str = this._marinaAero; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._marinaAero = value; + } + } + + public string Modelo + { + get + { + string str = this._modelo; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._modelo = value; + } + } + + public string Navegacao + { + get + { + string str = this._navegacao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._navegacao = value; + } + } + + public string Observacao + { + get + { + string str = this._observacao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._observacao = value; + } + } + + public int? Passageiros + { + get; + set; + } + + public long? Peso + { + get; + set; + } + + public string Prefixo + { + get + { + string str = this._prefixo; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._prefixo = value; + } + } + + public string Serie + { + get + { + string str = this._serie; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._serie = value; + } + } + + public TipoAeronautico Tipo + { + get; + set; + } + + public int? Tripulantes + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Aeronautico aeronautico = this; + return new Func<List<KeyValuePair<string, string>>>(aeronautico.Validate); + } + } + + public DateTime? Vistoria + { + get; + set; + } + + public Aeronautico() + { + } + + public static List<TupleList> Log(Gestor.Model.Domain.Seguros.Item item) + { + string str; + string str1; + string str2; + string str3; + string shortDateString; + List<TupleList> tupleLists = new List<TupleList>(); + TupleList tupleList = new TupleList(); + ObservableCollection<Tuple<string, string, string>> observableCollection = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("TIPO DE AERONAVE", item.Aeronautico.Tipo.GetDescription(), ""), + new Tuple<string, string, string>("FABRICANTE", (string.IsNullOrWhiteSpace(item.Aeronautico.Fabricante) ? "" : item.Aeronautico.Fabricante.ToUpper()), ""), + new Tuple<string, string, string>("MODELO", (string.IsNullOrWhiteSpace(item.Aeronautico.Modelo) ? "" : item.Aeronautico.Modelo.ToUpper()), ""), + new Tuple<string, string, string>("REGISTRO", (string.IsNullOrWhiteSpace(item.Aeronautico.Serie) ? "" : item.Aeronautico.Serie.ToUpper()), ""), + new Tuple<string, string, string>("PREFIXO", (string.IsNullOrWhiteSpace(item.Aeronautico.Prefixo) ? "" : item.Aeronautico.Prefixo.ToUpper()), "") + }; + int? fabricacao = item.Aeronautico.Fabricacao; + if (!fabricacao.HasValue) + { + str = ""; + } + else + { + fabricacao = item.Aeronautico.Fabricacao; + if (fabricacao.HasValue) + { + str = fabricacao.GetValueOrDefault().ToString(); + } + else + { + str = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("ANO DE FABRICAÇÃO", str, "")); + fabricacao = item.Aeronautico.Tripulantes; + if (!fabricacao.HasValue) + { + str1 = ""; + } + else + { + fabricacao = item.Aeronautico.Tripulantes; + if (fabricacao.HasValue) + { + str1 = fabricacao.GetValueOrDefault().ToString(); + } + else + { + str1 = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("TRIPULANTES", str1, "")); + fabricacao = item.Aeronautico.Passageiros; + if (!fabricacao.HasValue) + { + str2 = ""; + } + else + { + fabricacao = item.Aeronautico.Passageiros; + if (fabricacao.HasValue) + { + str2 = fabricacao.GetValueOrDefault().ToString(); + } + else + { + str2 = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("PASSAGEIROS", str2, "")); + observableCollection.Add(new Tuple<string, string, string>("AERÓDROMO", (string.IsNullOrWhiteSpace(item.Aeronautico.MarinaAero) ? "" : item.Aeronautico.MarinaAero.ToUpper()), "")); + long? peso = item.Aeronautico.Peso; + if (!peso.HasValue) + { + str3 = ""; + } + else + { + peso = item.Aeronautico.Peso; + if (peso.HasValue) + { + str3 = peso.GetValueOrDefault().ToString(); + } + else + { + str3 = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("PESO", str3, "")); + observableCollection.Add(new Tuple<string, string, string>("NAVEGAÇÃO", (string.IsNullOrWhiteSpace(item.Aeronautico.Navegacao) ? "" : item.Aeronautico.Navegacao.ToUpper()), "")); + observableCollection.Add(new Tuple<string, string, string>("CERTIFICADO", (string.IsNullOrWhiteSpace(item.Aeronautico.Certificado) ? "" : item.Aeronautico.Certificado.ToUpper()), "")); + observableCollection.Add(new Tuple<string, string, string>("MATERIAL DO CASCO", (string.IsNullOrWhiteSpace(item.Aeronautico.Casco) ? "" : item.Aeronautico.Casco.ToUpper()), "")); + DateTime? vistoria = item.Aeronautico.Vistoria; + if (!vistoria.HasValue) + { + shortDateString = ""; + } + else + { + vistoria = item.Aeronautico.Vistoria; + if (vistoria.HasValue) + { + shortDateString = vistoria.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("VALIDADE DA VISTORIA", shortDateString, "")); + observableCollection.Add(new Tuple<string, string, string>("OBSERVAÇÃO", (string.IsNullOrWhiteSpace(item.Aeronautico.Observacao) ? "" : item.Aeronautico.Observacao.ToUpper()), "")); + tupleList.Tuples = observableCollection; + tupleLists.Add(tupleList); + List<TupleList> tupleLists1 = tupleLists; + ObservableCollection<Tuple<string, string, string>> observableCollection1 = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("COBERTURAS$", "", "") + }; + foreach (Cobertura cobertura in item.Coberturas) + { + observableCollection1.Add(new Tuple<string, string, string>(string.Format(" COBERTURA {0}$", item.Coberturas.IndexOf(cobertura) + 1), "", "")); + observableCollection1.Add(new Tuple<string, string, string>(" OBSERVAÇÃO", (string.IsNullOrWhiteSpace(cobertura.Observacao) ? "" : cobertura.Observacao.ToUpper()), "")); + decimal premio = cobertura.Premio; + observableCollection1.Add(new Tuple<string, string, string>(" PRÊMIO", premio.ToString("C", new CultureInfo("pt-BR", false)), "")); + premio = cobertura.Franquia; + observableCollection1.Add(new Tuple<string, string, string>(" FRANQUIA", premio.ToString("C", new CultureInfo("pt-BR", false)), "")); + premio = cobertura.Lmi; + observableCollection1.Add(new Tuple<string, string, string>(" L.M.I.", premio.ToString("C", new CultureInfo("pt-BR", false)), "")); + } + tupleLists1.Add(new TupleList() + { + Tuples = observableCollection1 + }); + return tupleLists1; + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (string.IsNullOrWhiteSpace(this.Fabricante)) + { + keyValuePairs.AddValue<string, string>("Fabricante", Messages.Obrigatorio, true); + } + else if (this.Fabricante != null && this.Fabricante.Length > 60) + { + keyValuePairs.AddValue<string, string>("Fabricante", string.Format(Messages.MaiorQueLimite, 60), true); + } + if ((int)this.Tipo == 0) + { + keyValuePairs.AddValue<string, string>("Tipo", Messages.Obrigatorio, true); + } + if (string.IsNullOrWhiteSpace(this.Modelo)) + { + keyValuePairs.AddValue<string, string>("Modelo", Messages.Obrigatorio, true); + } + else if (this.Modelo.Length > 60) + { + keyValuePairs.AddValue<string, string>("Modelo", string.Format(Messages.MaiorQueLimite, 60), true); + } + if (this.Vistoria.HasValue && (DateTime.Compare(this.Vistoria.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.Vistoria.Value, new DateTime(9999, 12, 31)) > 0)) + { + keyValuePairs.AddValue<string, string>("Vistoria", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + if (string.IsNullOrWhiteSpace(this.Serie)) + { + keyValuePairs.AddValue<string, string>("Serie", Messages.Obrigatorio, true); + } + else if (this.Serie.Length > 30) + { + keyValuePairs.AddValue<string, string>("Serie", string.Format(Messages.MaiorQueLimite, 30), true); + } + if (string.IsNullOrWhiteSpace(this.Prefixo)) + { + keyValuePairs.AddValue<string, string>("Prefixo", Messages.Obrigatorio, true); + } + else if (this.Prefixo.Length > 30) + { + keyValuePairs.AddValue<string, string>("Prefixo", string.Format(Messages.MaiorQueLimite, 30), true); + } + if (!this.Fabricacao.HasValue) + { + keyValuePairs.AddValue<string, string>("Fabricacao", Messages.Obrigatorio, true); + } + else if (!this.Fabricacao.Value.ToString().ValidacaoFabricacao()) + { + keyValuePairs.AddValue<string, string>("Fabricacao", Messages.Invalido, true); + } + if (!this.Tripulantes.HasValue) + { + keyValuePairs.AddValue<string, string>("Tripulantes", Messages.Obrigatorio, true); + } + if (!this.Passageiros.HasValue) + { + keyValuePairs.AddValue<string, string>("Passageiros", Messages.Obrigatorio, true); + } + if (string.IsNullOrWhiteSpace(this.MarinaAero)) + { + keyValuePairs.AddValue<string, string>("MarinaAero", Messages.Obrigatorio, true); + } + else if (this.MarinaAero.Length > 60) + { + keyValuePairs.AddValue<string, string>("MarinaAero", string.Format(Messages.MaiorQueLimite, 60), true); + } + if (!string.IsNullOrWhiteSpace(this.Certificado) && this.Certificado.Length > 60) + { + keyValuePairs.AddValue<string, string>("Certificado", string.Format(Messages.MaiorQueLimite, 60), true); + } + if (string.IsNullOrWhiteSpace(this.Casco) && this.Tipo.Categoria() == "Aero") + { + keyValuePairs.AddValue<string, string>("Casco", Messages.Obrigatorio, true); + } + else if (this.Tipo.Categoria() != "Aero" && this.Casco != null && this.Casco.Length > 60) + { + keyValuePairs.AddValue<string, string>("Casco", string.Format(Messages.MaiorQueLimite, 60), true); + } + if (!string.IsNullOrWhiteSpace(this.Navegacao) && this.Tipo.Categoria() != "Aero" && this.Navegacao.Length > 60) + { + keyValuePairs.AddValue<string, string>("Navegacao", string.Format(Messages.MaiorQueLimite, 60), true); + } + if (!this.Vistoria.HasValue && this.Tipo.Categoria() == "Aero") + { + keyValuePairs.AddValue<string, string>("Vistoria", Messages.Obrigatorio, true); + } + if (!this.Peso.HasValue && this.Tipo.Categoria() == "Aero") + { + keyValuePairs.AddValue<string, string>("Peso", Messages.Obrigatorio, true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/AggilizadorPermissao.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/AggilizadorPermissao.cs new file mode 100644 index 0000000..686e669 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/AggilizadorPermissao.cs @@ -0,0 +1,25 @@ +using Gestor.Model.Common; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class AggilizadorPermissao + { + public PermissaoAggilizador Aggilizador + { + get; + set; + } + + public bool Permissao + { + get; + set; + } + + public AggilizadorPermissao() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/Auto.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/Auto.cs new file mode 100644 index 0000000..25b7903 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/Auto.cs @@ -0,0 +1,793 @@ +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Gestor.Model.Validation; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Globalization; +using System.Runtime.CompilerServices; +using System.Text.RegularExpressions; + +namespace Gestor.Model.Domain.Seguros +{ + public class Auto : DomainBase, IDomain + { + private string _fipe; + + private string _chassi; + + private string _placa; + + private string _modelo; + + private string _anoFabricacao; + + private string _anoModelo; + + private string _renavam; + + private string _capacidade; + + private string _portas; + + private string _observacao; + + private string _regiaoCirculacao; + + private string _ci; + + private string _cepPernoite; + + private Gestor.Model.Common.Categoria? _categoria; + + private bool _fabricanteBranco = true; + + private bool _chassiInvalido; + + public string AnoFabricacao + { + get + { + string str = this._anoFabricacao; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._anoFabricacao = value; + } + } + + public string AnoModelo + { + get + { + string str = this._anoModelo; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._anoModelo = value; + } + } + + public bool? Blindagem + { + get; + set; + } + + public int? Bonus + { + get; + set; + } + + public string Capacidade + { + get + { + string str = this._capacidade; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._capacidade = value; + } + } + + public Gestor.Model.Common.Categoria? Categoria + { + get + { + return this._categoria; + } + set + { + this._categoria = value; + if (value.GetValueOrDefault() == Gestor.Model.Common.Categoria.Motocicleta) + { + this.Portas = "0"; + } + } + } + + public string CepPernoite + { + get + { + if (this._cepPernoite == null || !Regex.IsMatch(this._cepPernoite, "[0-9]+")) + { + return string.Empty; + } + return this._cepPernoite.FormataCep().Trim(); + } + set + { + this._cepPernoite = value; + } + } + + public string Chassi + { + get + { + string str = this._chassi; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._chassi = value; + } + } + + public string Ci + { + get + { + string str = this._ci; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._ci = value; + } + } + + public Gestor.Model.Common.Combustivel? Combustivel + { + get; + set; + } + + public Gestor.Model.Common.Cor? Cor + { + get; + set; + } + + public Gestor.Model.Common.Correcao? Correcao + { + get; + set; + } + + public bool Excluido + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Fabricante Fabricante + { + get; + set; + } + + public bool? Financiado + { + get; + set; + } + + public string Fipe + { + get + { + if (this._fipe == null || !Regex.IsMatch(this._fipe, "[0-9]+")) + { + return ""; + } + return this._fipe.Trim(); + } + set + { + this._fipe = value; + } + } + + public Gestor.Model.Common.Isencao? Isencao + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Item Item + { + get; + set; + } + + public bool? KitGas + { + get; + set; + } + + public string Modelo + { + get + { + string str = this._modelo; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._modelo = value; + } + } + + public string Observacao + { + get + { + string str = this._observacao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._observacao = value; + } + } + + public bool? Pcd + { + get; + set; + } + + public string Placa + { + get + { + string str = this._placa; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._placa = value; + } + } + + public decimal PorcentagemReferencia + { + get; + set; + } + + public string Portas + { + get + { + string str = this._portas; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._portas = value; + } + } + + public Gestor.Model.Common.Rastreador Rastreador + { + get; + set; + } + + public string RegiaoCirculacao + { + get + { + if (this._regiaoCirculacao == null || !Regex.IsMatch(this._regiaoCirculacao, "[0-9]+")) + { + return ""; + } + return this._regiaoCirculacao.FormataCep().Trim(); + } + set + { + this._regiaoCirculacao = value; + } + } + + public string Renavam + { + get + { + string str = this._renavam; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._renavam = value; + } + } + + public Gestor.Model.Common.TabelaReferencia? TabelaReferencia + { + get; + set; + } + + public Gestor.Model.Common.TipoCobertura? TipoCobertura + { + get; + set; + } + + public Gestor.Model.Common.UsoVeiculo? UsoVeiculo + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Auto auto = this; + return new Func<List<KeyValuePair<string, string>>>(auto.Validate); + } + } + + public decimal ValorDeterminado + { + get; + set; + } + + public bool? ZeroKm + { + get; + set; + } + + public Auto() + { + } + + public static List<TupleList> Log(Gestor.Model.Domain.Seguros.Item item) + { + string description; + string str; + string description1; + string str1; + string str2; + string description2; + string description3; + string str3; + string str4; + string str5; + string description4; + string description5; + string str6; + List<TupleList> tupleLists = new List<TupleList>(); + TupleList tupleList = new TupleList(); + ObservableCollection<Tuple<string, string, string>> observableCollection = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("CÓDIGO FIPE", (string.IsNullOrWhiteSpace(item.Auto.Fipe) ? "" : item.Auto.Fipe.ToUpper()), ""), + new Tuple<string, string, string>("CHASSI", (string.IsNullOrWhiteSpace(item.Auto.Chassi) ? "" : item.Auto.Chassi.ToUpper()), ""), + new Tuple<string, string, string>("PLACA", (string.IsNullOrWhiteSpace(item.Auto.Placa) ? "" : item.Auto.Placa.ToUpper()), ""), + new Tuple<string, string, string>("FABRICANTE", (item.Auto.Fabricante == null ? "" : item.Auto.Fabricante.Descricao.ToUpper()), ""), + new Tuple<string, string, string>("MODELO", (string.IsNullOrWhiteSpace(item.Auto.Modelo) ? "" : item.Auto.Modelo.ToUpper()), "") + }; + Gestor.Model.Common.UsoVeiculo? usoVeiculo = item.Auto.UsoVeiculo; + if (!usoVeiculo.HasValue) + { + description = ""; + } + else + { + Auto auto = item.Auto; + if (auto != null) + { + usoVeiculo = auto.UsoVeiculo; + if (usoVeiculo.HasValue) + { + description = usoVeiculo.GetValueOrDefault().GetDescription(); + } + else + { + description = null; + } + } + else + { + description = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("USO VEICULO", description, "")); + Gestor.Model.Common.Categoria? categoria = item.Auto.Categoria; + if (!categoria.HasValue) + { + str = ""; + } + else + { + categoria = item.Auto.Categoria; + if (categoria.HasValue) + { + str = categoria.GetValueOrDefault().GetDescription(); + } + else + { + str = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("CATEGORIA", str, "")); + Gestor.Model.Common.Combustivel? combustivel = item.Auto.Combustivel; + if (!combustivel.HasValue) + { + description1 = ""; + } + else + { + combustivel = item.Auto.Combustivel; + if (combustivel.HasValue) + { + description1 = combustivel.GetValueOrDefault().GetDescription(); + } + else + { + description1 = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("COMBUSTÍVEL", description1, "")); + Gestor.Model.Common.Cor? cor = item.Auto.Cor; + if (!cor.HasValue) + { + str1 = ""; + } + else + { + cor = item.Auto.Cor; + if (cor.HasValue) + { + str1 = cor.GetValueOrDefault().GetDescription(); + } + else + { + str1 = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("COR", str1, "")); + observableCollection.Add(new Tuple<string, string, string>("RENAVAM", (string.IsNullOrWhiteSpace(item.Auto.Renavam) ? "" : item.Auto.Renavam.ToUpper()), "")); + if (!item.Auto.ZeroKm.HasValue) + { + str2 = ""; + } + else + { + str2 = (item.Auto.ZeroKm.Value ? "SIM" : "NÃO"); + } + observableCollection.Add(new Tuple<string, string, string>("ZERO KM", str2, "")); + observableCollection.Add(new Tuple<string, string, string>("ANO DE FABRICAÇÃO", (string.IsNullOrWhiteSpace(item.Auto.AnoFabricacao) ? "" : item.Auto.AnoFabricacao.ToUpper()), "")); + observableCollection.Add(new Tuple<string, string, string>("ANO DO MODELO", (string.IsNullOrWhiteSpace(item.Auto.AnoModelo) ? "" : item.Auto.AnoModelo.ToUpper()), "")); + observableCollection.Add(new Tuple<string, string, string>("PORTAS", (string.IsNullOrWhiteSpace(item.Auto.Portas) ? "" : item.Auto.Portas), "")); + observableCollection.Add(new Tuple<string, string, string>("CAPACIDADE", (string.IsNullOrWhiteSpace(item.Auto.Capacidade) ? "" : item.Auto.Capacidade), "")); + observableCollection.Add(new Tuple<string, string, string>("CEP DE CIRCULAÇÃO", (string.IsNullOrWhiteSpace(item.Auto.RegiaoCirculacao) ? "" : item.Auto.RegiaoCirculacao.ToUpper()), "")); + observableCollection.Add(new Tuple<string, string, string>("CEP PERNOITE", (string.IsNullOrWhiteSpace(item.Auto.CepPernoite) ? "" : item.Auto.CepPernoite.ToUpper()), "")); + Gestor.Model.Common.Correcao? correcao = item.Auto.Correcao; + if (!correcao.HasValue) + { + description2 = ""; + } + else + { + correcao = item.Auto.Correcao; + if (correcao.HasValue) + { + description2 = correcao.GetValueOrDefault().GetDescription(); + } + else + { + description2 = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("CORREÇÃO", description2, "")); + Gestor.Model.Common.TabelaReferencia? tabelaReferencia = item.Auto.TabelaReferencia; + if (!tabelaReferencia.HasValue) + { + description3 = ""; + } + else + { + tabelaReferencia = item.Auto.TabelaReferencia; + if (tabelaReferencia.HasValue) + { + description3 = tabelaReferencia.GetValueOrDefault().GetDescription(); + } + else + { + description3 = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("REFERÊNCIA", description3, "")); + decimal porcentagemReferencia = item.Auto.PorcentagemReferencia; + observableCollection.Add(new Tuple<string, string, string>("PORCENTAGEM DE REFERÊNCIA", porcentagemReferencia.ToString(new CultureInfo("pt-BR")), "")); + observableCollection.Add(new Tuple<string, string, string>("C.I.", (string.IsNullOrWhiteSpace(item.Auto.Ci) ? "" : item.Auto.Ci.ToUpper()), "")); + if (!item.Auto.Financiado.HasValue) + { + str3 = ""; + } + else + { + str3 = (item.Auto.Financiado.Value ? "SIM" : "NÃO"); + } + observableCollection.Add(new Tuple<string, string, string>("FINANCEIRO/ALIENADO", str3, "")); + if (!item.Auto.Pcd.HasValue) + { + str4 = ""; + } + else + { + str4 = (item.Auto.Pcd.Value ? "SIM" : "NÃO"); + } + observableCollection.Add(new Tuple<string, string, string>("PCD", str4, "")); + if (!item.Auto.Blindagem.HasValue) + { + str5 = ""; + } + else + { + str5 = (item.Auto.Blindagem.Value ? "SIM" : "NÃO"); + } + observableCollection.Add(new Tuple<string, string, string>("BLINDAGEM", str5, "")); + Gestor.Model.Common.Isencao? isencao = item.Auto.Isencao; + if (!isencao.HasValue) + { + description4 = ""; + } + else + { + isencao = item.Auto.Isencao; + if (isencao.HasValue) + { + description4 = isencao.GetValueOrDefault().GetDescription(); + } + else + { + description4 = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("ISENÇÃO", description4, "")); + observableCollection.Add(new Tuple<string, string, string>("BÔNUS", (!item.Auto.Bonus.HasValue ? "" : item.Auto.Bonus.Value.ToString()), "")); + Gestor.Model.Common.TipoCobertura? tipoCobertura = item.Auto.TipoCobertura; + if (!tipoCobertura.HasValue) + { + description5 = ""; + } + else + { + tipoCobertura = item.Auto.TipoCobertura; + if (tipoCobertura.HasValue) + { + description5 = tipoCobertura.GetValueOrDefault().GetDescription(); + } + else + { + description5 = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("TIPO DE COBERTURA", description5, "")); + if (!item.Auto.Pcd.HasValue) + { + str6 = ""; + } + else + { + str6 = (item.Auto.KitGas.Value ? "SIM" : "NÃO"); + } + observableCollection.Add(new Tuple<string, string, string>("KIT GÁS", str6, "")); + observableCollection.Add(new Tuple<string, string, string>("OBSERVAÇÕES", (string.IsNullOrWhiteSpace(item.Auto.Observacao) ? "" : item.Auto.Observacao.ToUpper()), "")); + tupleList.Tuples = observableCollection; + tupleLists.Add(tupleList); + List<TupleList> tupleLists1 = tupleLists; + ObservableCollection<Tuple<string, string, string>> observableCollection1 = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("COBERTURAS$", "", "") + }; + foreach (Cobertura cobertura in item.Coberturas) + { + observableCollection1.Add(new Tuple<string, string, string>(string.Format(" COBERTURA {0}$", item.Coberturas.IndexOf(cobertura) + 1), "", "")); + observableCollection1.Add(new Tuple<string, string, string>(" OBSERVAÇÃO", (string.IsNullOrWhiteSpace(cobertura.Observacao) ? "" : cobertura.Observacao.ToUpper()), "")); + porcentagemReferencia = cobertura.Premio; + observableCollection1.Add(new Tuple<string, string, string>(" PRÊMIO", porcentagemReferencia.ToString("C", new CultureInfo("pt-BR", false)), "")); + porcentagemReferencia = cobertura.Franquia; + observableCollection1.Add(new Tuple<string, string, string>(" FRANQUIA", porcentagemReferencia.ToString("C", new CultureInfo("pt-BR", false)), "")); + porcentagemReferencia = cobertura.Lmi; + observableCollection1.Add(new Tuple<string, string, string>(" L.M.I.", porcentagemReferencia.ToString("C", new CultureInfo("pt-BR", false)), "")); + } + tupleLists1.Add(new TupleList() + { + Tuples = observableCollection1 + }); + return tupleLists1; + } + + public List<KeyValuePair<string, string>> Validate(bool chassiInvalido, bool fabricanteBranco) + { + this._chassiInvalido = chassiInvalido; + this._fabricanteBranco = fabricanteBranco; + return this.Validate(); + } + + public List<KeyValuePair<string, string>> Validate() + { + int num; + int num1; + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (string.IsNullOrWhiteSpace(this.Chassi)) + { + keyValuePairs.AddValue<string, string>("Chassi", Messages.Obrigatorio, true); + } + else if (!this._chassiInvalido && !this.Chassi.ValidacaoChassi()) + { + keyValuePairs.AddValue<string, string>("Chassi", Messages.Invalido, true); + } + if (!this._fabricanteBranco && (this.Fabricante == null || this.Fabricante.Id == 0)) + { + keyValuePairs.AddValue<string, string>("Fabricante", Messages.Obrigatorio, true); + } + if (string.IsNullOrWhiteSpace(this.Modelo)) + { + keyValuePairs.AddValue<string, string>("Modelo", Messages.Obrigatorio, true); + } + else if (this.Modelo.Length > 250) + { + keyValuePairs.AddValue<string, string>("Modelo", string.Format(Messages.MaiorQueLimite, 250), true); + } + if (!this.Categoria.HasValue) + { + keyValuePairs.AddValue<string, string>("Categoria", Messages.Obrigatorio, true); + } + if (!this.Combustivel.HasValue) + { + keyValuePairs.AddValue<string, string>("Combustivel|COMBUSTÍVEL", Messages.Obrigatorio, true); + } + if (!this.ZeroKm.HasValue) + { + keyValuePairs.AddValue<string, string>("ZeroKm|ZERO KM", Messages.Obrigatorio, true); + } + if (this.ZeroKm.HasValue && !this.ZeroKm.Value && string.IsNullOrWhiteSpace(this.Placa)) + { + keyValuePairs.AddValue<string, string>("Placa", Messages.Obrigatorio, true); + } + else if (this.ZeroKm.HasValue && !this.ZeroKm.Value && !this.Placa.ValidacaoPlaca()) + { + keyValuePairs.AddValue<string, string>("Placa", Messages.Invalido, true); + } + if (string.IsNullOrWhiteSpace(this.AnoFabricacao)) + { + keyValuePairs.AddValue<string, string>("AnoFabricacao|ANO DE FABRICAÇÃO", Messages.Obrigatorio, true); + } + else if (!this.AnoFabricacao.ValidacaoFabricacao()) + { + keyValuePairs.AddValue<string, string>("AnoFabricacao|ANO DE FABRICAÇÃO", Messages.Invalido, true); + } + if (string.IsNullOrWhiteSpace(this.AnoModelo)) + { + keyValuePairs.AddValue<string, string>("AnoModelo|ANO DO MODELO", Messages.Obrigatorio, true); + } + else if (!this.AnoModelo.ValidacaoModelo()) + { + keyValuePairs.AddValue<string, string>("AnoModelo|ANO DO MODELO", Messages.Invalido, true); + } + if (string.IsNullOrWhiteSpace(this.Portas)) + { + if (this.Categoria.GetValueOrDefault() != Gestor.Model.Common.Categoria.Motocicleta) + { + keyValuePairs.AddValue<string, string>("Portas", Messages.Obrigatorio, true); + } + else + { + this.Portas = "0"; + } + } + else if (!int.TryParse(this.Portas, out num1)) + { + keyValuePairs.AddValue<string, string>("Portas", Messages.Invalido, true); + } + if (string.IsNullOrWhiteSpace(this.Capacidade)) + { + keyValuePairs.AddValue<string, string>("Capacidade", Messages.Obrigatorio, true); + } + else if (!int.TryParse(this.Capacidade, out num1)) + { + keyValuePairs.AddValue<string, string>("Capacidade", Messages.Invalido, true); + } + if (!this.Financiado.HasValue) + { + keyValuePairs.AddValue<string, string>("Financiado", Messages.Obrigatorio, true); + } + if (!string.IsNullOrWhiteSpace(this.Ci) && this.Ci.Length > 20) + { + keyValuePairs.AddValue<string, string>("Ci|C.I.", string.Format(Messages.MaiorQueLimite, 20), true); + } + if (string.IsNullOrWhiteSpace(this.Fipe)) + { + keyValuePairs.AddValue<string, string>("Fipe|CÓDIGO FIPE", Messages.Obrigatorio, true); + } + else if (!this.Fipe.ValidaFipe()) + { + keyValuePairs.AddValue<string, string>("Fipe|CÓDIGO FIPE", Messages.Invalido, true); + } + if (int.TryParse(this.Capacidade, out num) && num > 99) + { + keyValuePairs.AddValue<string, string>("Capacidade", Messages.Invalido, true); + } + if (!this.UsoVeiculo.HasValue) + { + keyValuePairs.AddValue<string, string>("UsoVeiculo", Messages.Obrigatorio, true); + } + if (!string.IsNullOrEmpty(this.Renavam) && this.Renavam.Replace(".", "").Length > 11) + { + keyValuePairs.AddValue<string, string>("Renavam", Messages.Invalido, true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/Cliente.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/Cliente.cs new file mode 100644 index 0000000..7da5b5d --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/Cliente.cs @@ -0,0 +1,1193 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Gestor.Model.Validation; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Globalization; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class Cliente : DomainBase, IDomain + { + private string _nome; + + private string _documento; + + private string _identidade; + + private string _emissor; + + private string _estadoEmissor; + + private string _habilitacao; + + private string _categoriaHabilitacao; + + private string _pasta; + + private string _cei; + + private string _rne; + + private string _agencia; + + private string _tipoConta; + + private string _conta; + + private string _caepf; + + private bool? _malaDireta = new bool?(true); + + private string _nomeSocialRg; + + [Description("AGÊNCIA")] + [Log(true)] + public string Agencia + { + get + { + string str = this._agencia; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._agencia = value; + } + } + + public Gestor.Model.Domain.Common.Atividade Atividade + { + get; + set; + } + + public Gestor.Model.Domain.Common.Banco Banco + { + get; + set; + } + + [Log(true)] + public string Caepf + { + get + { + string str = this._caepf; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._caepf = value; + } + } + + [Description("CATEGORIA HABILITAÇÃO")] + [Log(true)] + public string CategoriaHabilitacao + { + get + { + string str = this._categoriaHabilitacao; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._categoriaHabilitacao = value; + } + } + + [Log(true)] + public string Cei + { + get + { + string str = this._cei; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._cei = value; + } + } + + [Description("CLIENTE DESDE")] + [Log(true)] + public DateTime? ClienteDesde + { + get; + set; + } + + [Log(true)] + public string Conta + { + get + { + string str = this._conta; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._conta = value; + } + } + + public ObservableCollection<MaisContato> Contatos + { + get; + set; + } + + [Log(true)] + public string Documento + { + get + { + string str = this._documento; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._documento = value; + } + } + + [Description("DOCUMENTO PRINCIPAL")] + [Log(true)] + public TipoDocumento? DocumentoPrincipal + { + get; + set; + } + + public ObservableCollection<ClienteEmail> Emails + { + get; + set; + } + + [Log(true)] + public string Emissor + { + get + { + string str = this._emissor; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._emissor = value; + } + } + + public ObservableCollection<ClienteEndereco> Enderecos + { + get; + set; + } + + [Description("ESTADO CIVIL")] + [Log(true)] + public Gestor.Model.Common.EstadoCivil? EstadoCivil + { + get; + set; + } + + [Description("ESTADO EMISSOR")] + [Log(true)] + public string EstadoEmissor + { + get + { + string str = this._estadoEmissor; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._estadoEmissor = value; + } + } + + public bool EstaNaCentralSegurado + { + get; + set; + } + + [Log(true)] + public bool Excluido + { + get; + set; + } + + [Description("EXPEDIÇÃO")] + [Log(true)] + public DateTime? Expedicao + { + get; + set; + } + + [Log(true)] + public bool Falecido + { + get; + set; + } + + [Description("HABILITAÇÃO")] + [Log(true)] + public string Habilitacao + { + get + { + string str = this._habilitacao; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._habilitacao = value; + } + } + + public long IdEmpresa + { + get; + set; + } + + [Log(true)] + public string Identidade + { + get + { + string str = this._identidade; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._identidade = value; + } + } + + [Description("DESEJA RECEBER MALA DIRETA")] + [Log(true)] + public bool? MalaDireta + { + get + { + return new bool?(this._malaDireta.GetValueOrDefault(true)); + } + set + { + this._malaDireta = new bool?(value.GetValueOrDefault(true)); + } + } + + [Log(true)] + public DateTime? Nascimento + { + get; + set; + } + + [Log(true)] + [Name(true)] + public string Nome + { + get + { + string str = this._nome; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + object upper; + this._nome = value; + if (value != null) + { + upper = value.ToUpper(); + } + else + { + upper = null; + } + this.NomeSocial = string.Format("{0} - {1}", upper, base.Id); + } + } + + public string NomeSocial + { + get; + set; + } + + public string NomeSocialRg + { + get + { + string str = this._nomeSocialRg; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._nomeSocialRg = value; + } + } + + [Description("OBSERVAÇÃO")] + [Log(true)] + public string Observacao + { + get; + set; + } + + public List<OrigemCliente> Origens + { + get; + set; + } + + [Log(true)] + public string Pasta + { + get + { + string str = this._pasta; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._pasta = value; + } + } + + public bool PessoaFisica + { + get + { + return this.Documento.Clear().Length < 12; + } + } + + [Description("PRIMEIRA HABILITAÇÃO")] + [Log(true)] + public DateTime? PrimeiraHabilitacao + { + get; + set; + } + + [Description("PROFISSÃO")] + public Gestor.Model.Domain.Common.Profissao Profissao + { + get; + set; + } + + [Description("RENDA MENSAL")] + [Log(true)] + public decimal RendaMensal + { + get; + set; + } + + [Log(true)] + public Gestor.Model.Domain.Seguros.ResponsavelAssinatura ResponsavelAssinatura + { + get; + set; + } + + [Log(true)] + public string Rne + { + get + { + string str = this._rne; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._rne = value; + } + } + + [Log(true)] + public Gestor.Model.Common.Sexo? Sexo + { + get; + set; + } + + [Log(true)] + public string Status + { + get; + set; + } + + public ObservableCollection<ClienteTelefone> Telefones + { + get; + set; + } + + [Description("TIPO CONTA")] + [Log(true)] + public string TipoConta + { + get + { + string str = this._tipoConta; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._tipoConta = value; + } + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Cliente cliente = this; + return new Func<List<KeyValuePair<string, string>>>(cliente.Validate); + } + } + + [Description("VENCIMENTO HABILITAÇÃO")] + [Log(true)] + public DateTime? VencimentoHabilitacao + { + get; + set; + } + + public ObservableCollection<ClienteVinculo> Vinculos + { + get; + set; + } + + public Cliente() + { + } + + public List<TupleList> Log() + { + TipoTelefone? tipo; + string description; + string str; + string shortDateString; + string shortDateString1; + string str1; + string shortDateString2; + string description1; + string description2; + string str2; + string shortDateString3; + string description3; + string str3; + string description4; + List<TupleList> tupleLists = new List<TupleList>(); + TupleList tupleList = new TupleList(); + ObservableCollection<Tuple<string, string, string>> observableCollection = new ObservableCollection<Tuple<string, string, string>>(); + TipoDocumento? documentoPrincipal = this.DocumentoPrincipal; + if (!documentoPrincipal.HasValue) + { + description = ""; + } + else + { + documentoPrincipal = this.DocumentoPrincipal; + if (documentoPrincipal.HasValue) + { + description = documentoPrincipal.GetValueOrDefault().GetDescription(); + } + else + { + description = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("TIPO DO DOCUMENTO PRINCIPAL", description, "")); + observableCollection.Add(new Tuple<string, string, string>("DOCUMENTO PRINCIPAL", (string.IsNullOrWhiteSpace(this.Documento) ? "" : this.Documento), "")); + observableCollection.Add(new Tuple<string, string, string>("CLIENTE", (string.IsNullOrWhiteSpace(this.Nome) ? "" : this.Nome.ToUpper()), "")); + str = (this.Documento.OnlyNumber().Length > 11 ? "FUNDAÇÃO" : "NASCIMENTO"); + DateTime? nascimento = this.Nascimento; + if (!nascimento.HasValue) + { + shortDateString = ""; + } + else + { + nascimento = this.Nascimento; + if (nascimento.HasValue) + { + shortDateString = nascimento.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString = null; + } + } + observableCollection.Add(new Tuple<string, string, string>(str, shortDateString, "")); + tupleList.Tuples = observableCollection; + tupleLists.Add(tupleList); + List<TupleList> tupleLists1 = tupleLists; + if (this.Documento == null || this.Documento.OnlyNumber().Length <= 11) + { + tupleLists1[0].Tuples.Add(new Tuple<string, string, string>("IDENTIDADE", (string.IsNullOrWhiteSpace(this.Identidade) ? "" : this.Identidade), "")); + tupleLists1[0].Tuples.Add(new Tuple<string, string, string>("ÓRGÃO EMISSOR", (string.IsNullOrWhiteSpace(this.Emissor) ? "" : this.Emissor.ToUpper()), "")); + tupleLists1[0].Tuples.Add(new Tuple<string, string, string>("ESTADO EMISSOR", (string.IsNullOrWhiteSpace(this.EstadoEmissor) ? "" : this.EstadoEmissor.ToUpper()), "")); + ObservableCollection<Tuple<string, string, string>> tuples = tupleLists1[0].Tuples; + nascimento = this.Expedicao; + if (!nascimento.HasValue) + { + shortDateString1 = ""; + } + else + { + nascimento = this.Expedicao; + if (nascimento.HasValue) + { + shortDateString1 = nascimento.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString1 = null; + } + } + tuples.Add(new Tuple<string, string, string>("DATA DE EXPEDIÇÃO", shortDateString1, "")); + tupleLists1[0].Tuples.Add(new Tuple<string, string, string>("HABILITAÇÃO", (string.IsNullOrWhiteSpace(this.Habilitacao) ? "" : this.Habilitacao.ToUpper()), "")); + tupleLists1[0].Tuples.Add(new Tuple<string, string, string>("CATEGORIA", (string.IsNullOrWhiteSpace(this.CategoriaHabilitacao) ? "" : this.CategoriaHabilitacao.ToUpper()), "")); + ObservableCollection<Tuple<string, string, string>> tuples1 = tupleLists1[0].Tuples; + nascimento = this.PrimeiraHabilitacao; + if (!nascimento.HasValue) + { + str1 = ""; + } + else + { + nascimento = this.PrimeiraHabilitacao; + if (nascimento.HasValue) + { + str1 = nascimento.GetValueOrDefault().ToShortDateString(); + } + else + { + str1 = null; + } + } + tuples1.Add(new Tuple<string, string, string>("PRIMEIRA HABILITAÇÃO", str1, "")); + ObservableCollection<Tuple<string, string, string>> observableCollection1 = tupleLists1[0].Tuples; + nascimento = this.VencimentoHabilitacao; + if (!nascimento.HasValue) + { + shortDateString2 = ""; + } + else + { + nascimento = this.VencimentoHabilitacao; + if (nascimento.HasValue) + { + shortDateString2 = nascimento.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString2 = null; + } + } + observableCollection1.Add(new Tuple<string, string, string>("VENCIMENTO DA HABILITAÇÃO", shortDateString2, "")); + ObservableCollection<Tuple<string, string, string>> tuples2 = tupleLists1[0].Tuples; + Gestor.Model.Common.Sexo? sexo = this.Sexo; + if (!sexo.HasValue) + { + description1 = ""; + } + else + { + sexo = this.Sexo; + if (sexo.HasValue) + { + description1 = sexo.GetValueOrDefault().GetDescription(); + } + else + { + description1 = null; + } + } + tuples2.Add(new Tuple<string, string, string>("SEXO", description1, "")); + ObservableCollection<Tuple<string, string, string>> observableCollection2 = tupleLists1[0].Tuples; + Gestor.Model.Common.EstadoCivil? estadoCivil = this.EstadoCivil; + if (!estadoCivil.HasValue) + { + description2 = ""; + } + else + { + estadoCivil = this.EstadoCivil; + if (estadoCivil.HasValue) + { + description2 = estadoCivil.GetValueOrDefault().GetDescription(); + } + else + { + description2 = null; + } + } + observableCollection2.Add(new Tuple<string, string, string>("ESTADO CIVIL", description2, "")); + tupleLists1[0].Tuples.Add(new Tuple<string, string, string>("PROFISSÃO DO CLIENTE", (this.Profissao == null ? "" : this.Profissao.Nome.ToUpper()), "")); + } + else + { + tupleLists1[0].Tuples.Add(new Tuple<string, string, string>("RAMO DE ATIVIDADE", (string.IsNullOrWhiteSpace(this.Atividade.Nome) ? "" : this.Atividade.Nome), "")); + } + ObservableCollection<Tuple<string, string, string>> tuples3 = tupleLists1[0].Tuples; + nascimento = this.ClienteDesde; + if (!nascimento.HasValue) + { + str2 = ""; + } + else + { + nascimento = this.ClienteDesde; + if (nascimento.HasValue) + { + str2 = nascimento.GetValueOrDefault().ToShortDateString(); + } + else + { + str2 = null; + } + } + tuples3.Add(new Tuple<string, string, string>("CLIENTE DESDE", str2, "")); + tupleLists1[0].Tuples.Add(new Tuple<string, string, string>("PASTA", (string.IsNullOrWhiteSpace(this.Pasta) ? "" : this.Pasta.ToUpper()), "")); + tupleLists1[0].Tuples.Add(new Tuple<string, string, string>("BANCO", (this.Banco == null ? "" : this.Banco.Nome.ToUpper()), "")); + tupleLists1[0].Tuples.Add(new Tuple<string, string, string>("AGÊNCIA", (string.IsNullOrWhiteSpace(this.Agencia) ? "" : this.Agencia.ToUpper()), "")); + tupleLists1[0].Tuples.Add(new Tuple<string, string, string>("TIPO DE CONTA", (string.IsNullOrWhiteSpace(this.TipoConta) ? "" : this.TipoConta.ToUpper()), "")); + tupleLists1[0].Tuples.Add(new Tuple<string, string, string>("NÚMERO DA CONTA", (string.IsNullOrWhiteSpace(this.Conta) ? "" : this.Conta.ToUpper()), "")); + tupleLists1[0].Tuples.Add(new Tuple<string, string, string>("FALECIDO", (this.Falecido ? "SIM" : "NÃO"), "")); + tupleLists1[0].Tuples.Add(new Tuple<string, string, string>("ÓRGÃO EMISSOR", (string.IsNullOrWhiteSpace(this.Emissor) ? "" : this.Emissor.ToUpper()), "")); + ObservableCollection<Tuple<string, string, string>> observableCollection3 = tupleLists1[0].Tuples; + decimal rendaMensal = this.RendaMensal; + observableCollection3.Add(new Tuple<string, string, string>("RENDA MENSAL", rendaMensal.ToString("C", new CultureInfo("pt-BR", false)), "")); + ObservableCollection<Tuple<string, string, string>> observableCollection4 = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("TELEFONES$", "", "") + }; + if (this.Telefones != null && this.Telefones.Count > 0) + { + foreach (ClienteTelefone telefone in this.Telefones) + { + observableCollection4.Add(new Tuple<string, string, string>(string.Format(" TELEFONE {0}$", this.Telefones.IndexOf(telefone) + 1), "", "")); + ObservableCollection<Tuple<string, string, string>> observableCollection5 = observableCollection4; + tipo = telefone.Tipo; + if (!tipo.HasValue) + { + description4 = ""; + } + else + { + tipo = telefone.Tipo; + if (tipo.HasValue) + { + description4 = tipo.GetValueOrDefault().GetDescription(); + } + else + { + description4 = null; + } + } + observableCollection5.Add(new Tuple<string, string, string>(" TIPO", description4, "")); + observableCollection4.Add(new Tuple<string, string, string>(" PREFIXO", (string.IsNullOrWhiteSpace(telefone.Prefixo) ? "" : telefone.Prefixo.ToUpper()), "")); + observableCollection4.Add(new Tuple<string, string, string>(" NÚMERO", (string.IsNullOrWhiteSpace(telefone.Numero) ? "" : telefone.Numero), "")); + observableCollection4.Add(new Tuple<string, string, string>(" ORDEM", (!telefone.Ordem.HasValue ? "" : telefone.Ordem.ToString()), "")); + } + } + tupleLists1.Add(new TupleList() + { + Tuples = observableCollection4 + }); + ObservableCollection<Tuple<string, string, string>> observableCollection6 = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("EMAILS$", "", "") + }; + if (this.Emails != null && this.Emails.Count > 0) + { + foreach (ClienteEmail email in this.Emails) + { + observableCollection6.Add(new Tuple<string, string, string>(string.Format(" EMAIL {0}$", this.Emails.IndexOf(email) + 1), "", "")); + observableCollection6.Add(new Tuple<string, string, string>(" ENDEREÇO DE EMAIL", (string.IsNullOrWhiteSpace(email.Email) ? "" : email.Email), "")); + observableCollection6.Add(new Tuple<string, string, string>(" ORDEM", (!email.Ordem.HasValue ? "" : email.Ordem.ToString()), "")); + } + } + tupleLists1.Add(new TupleList() + { + Tuples = observableCollection6 + }); + ObservableCollection<Tuple<string, string, string>> observableCollection7 = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("ENDEREÇOS$", "", "") + }; + if (this.Enderecos != null && this.Enderecos.Count > 0) + { + foreach (ClienteEndereco endereco in this.Enderecos) + { + observableCollection7.Add(new Tuple<string, string, string>(string.Format(" ENDEREÇO {0}$", this.Enderecos.IndexOf(endereco) + 1), "", "")); + observableCollection7.Add(new Tuple<string, string, string>(" LOGRADOURO", (string.IsNullOrWhiteSpace(endereco.Endereco) ? "" : endereco.Endereco), "")); + observableCollection7.Add(new Tuple<string, string, string>(" NÚMERO", (string.IsNullOrWhiteSpace(endereco.Numero) ? "" : endereco.Numero), "")); + observableCollection7.Add(new Tuple<string, string, string>(" COMPLEMENTO", (string.IsNullOrWhiteSpace(endereco.Complemento) ? "" : endereco.Complemento), "")); + observableCollection7.Add(new Tuple<string, string, string>(" BAIRRO", (string.IsNullOrWhiteSpace(endereco.Bairro) ? "" : endereco.Bairro), "")); + observableCollection7.Add(new Tuple<string, string, string>(" CIDADE", (string.IsNullOrWhiteSpace(endereco.Cidade) ? "" : endereco.Cidade), "")); + observableCollection7.Add(new Tuple<string, string, string>(" ESTADO", (string.IsNullOrWhiteSpace(endereco.Estado) ? "" : endereco.Estado), "")); + observableCollection7.Add(new Tuple<string, string, string>(" CEP", (string.IsNullOrWhiteSpace(endereco.Cep) ? "" : endereco.Cep), "")); + observableCollection7.Add(new Tuple<string, string, string>(" ORDEM", (!endereco.Ordem.HasValue ? "" : endereco.Ordem.ToString()), "")); + } + } + tupleLists1.Add(new TupleList() + { + Tuples = observableCollection7 + }); + ObservableCollection<Tuple<string, string, string>> observableCollection8 = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("CONTATOS$", "", "") + }; + if (this.Contatos != null && this.Contatos.Count > 0) + { + foreach (MaisContato contato in this.Contatos) + { + observableCollection8.Add(new Tuple<string, string, string>(string.Format(" CONTATO {0}$", this.Contatos.IndexOf(contato) + 1), "", "")); + observableCollection8.Add(new Tuple<string, string, string>(" DOCUMENTO", (string.IsNullOrWhiteSpace(contato.Documento) ? "" : contato.Documento), "")); + ObservableCollection<Tuple<string, string, string>> observableCollection9 = observableCollection8; + nascimento = contato.Nascimento; + if (!nascimento.HasValue) + { + shortDateString3 = ""; + } + else + { + nascimento = contato.Nascimento; + if (nascimento.HasValue) + { + shortDateString3 = nascimento.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString3 = null; + } + } + observableCollection9.Add(new Tuple<string, string, string>(" NASCIMENTO", shortDateString3, "")); + ObservableCollection<Tuple<string, string, string>> observableCollection10 = observableCollection8; + Parentesco? parentesco = contato.Parentesco; + if (!parentesco.HasValue) + { + description3 = ""; + } + else + { + parentesco = contato.Parentesco; + if (parentesco.HasValue) + { + description3 = parentesco.GetValueOrDefault().GetDescription(); + } + else + { + description3 = null; + } + } + observableCollection10.Add(new Tuple<string, string, string>(" PARENTESCO", description3, "")); + observableCollection8.Add(new Tuple<string, string, string>(" BANCO", (string.IsNullOrWhiteSpace(contato.Banco) ? "" : contato.Banco), "")); + observableCollection8.Add(new Tuple<string, string, string>(" AGÊNCIA", (string.IsNullOrWhiteSpace(contato.Agencia) ? "" : contato.Agencia), "")); + observableCollection8.Add(new Tuple<string, string, string>(" CONTA", (string.IsNullOrWhiteSpace(contato.Conta) ? "" : contato.Conta), "")); + ObservableCollection<Tuple<string, string, string>> observableCollection11 = observableCollection8; + tipo = contato.Tipo; + if (!tipo.HasValue) + { + str3 = ""; + } + else + { + tipo = contato.Tipo; + if (tipo.HasValue) + { + str3 = tipo.GetValueOrDefault().GetDescription(); + } + else + { + str3 = null; + } + } + observableCollection11.Add(new Tuple<string, string, string>(" TIPO DO TELEFONE", str3, "")); + observableCollection8.Add(new Tuple<string, string, string>(" PREFIXO", (string.IsNullOrWhiteSpace(contato.Prefixo) ? "" : contato.Prefixo), "")); + observableCollection8.Add(new Tuple<string, string, string>(" NÚMERO", (string.IsNullOrWhiteSpace(contato.Telefone) ? "" : contato.Telefone), "")); + observableCollection8.Add(new Tuple<string, string, string>(" EMAIL", (string.IsNullOrWhiteSpace(contato.Email) ? "" : contato.Email), "")); + } + } + tupleLists1.Add(new TupleList() + { + Tuples = observableCollection8 + }); + ObservableCollection<Tuple<string, string, string>> observableCollection12 = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("VÍNCULOS$", "", "") + }; + if (this.Vinculos == null) + { + this.Vinculos = new ObservableCollection<ClienteVinculo>(); + } + if (this.Vinculos != null && this.Vinculos.Count > 0) + { + foreach (ClienteVinculo vinculo in this.Vinculos) + { + observableCollection12.Add(new Tuple<string, string, string>(string.Format(" VÍNCULO {0}$", this.Vinculos.IndexOf(vinculo) + 1), "", "")); + observableCollection12.Add(new Tuple<string, string, string>(" COM CLIENTE", (vinculo.Cliente1.Id != base.Id ? vinculo.Cliente1.Nome : vinculo.Cliente2.Nome), "")); + observableCollection12.Add(new Tuple<string, string, string>(" PARENTESCO", (vinculo.Cliente1.Id == base.Id ? vinculo.Parentesco.GetDescription() : Funcoes.ParentescoInverso(vinculo.Parentesco).GetDescription()), "")); + } + } + tupleLists1.Add(new TupleList() + { + Tuples = observableCollection12 + }); + return tupleLists1; + } + + public List<KeyValuePair<string, string>> Validate() + { + int? nullable; + DateTime? primeiraHabilitacao; + int? nullable1; + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + string nome = this.Nome; + if (nome != null) + { + nullable1 = new int?((int)nome.Trim().Split(new char[] { ' ' }).Length); + } + else + { + nullable = null; + nullable1 = nullable; + } + int? nullable2 = nullable1; + if (nullable2.HasValue) + { + nullable = nullable2; + if (nullable.GetValueOrDefault() <= 1 & nullable.HasValue) + { + keyValuePairs.AddValue<string, string>("Nome", Messages.NomeInvalido, true); + } + } + else + { + keyValuePairs.AddValue<string, string>("Nome", Messages.Obrigatorio, true); + } + TipoDocumento? documentoPrincipal = this.DocumentoPrincipal; + if (!documentoPrincipal.HasValue) + { + keyValuePairs.AddValue<string, string>("DocumentoPrincipal|DOCUMENTO PRINCIPAL", string.Format(Messages.Obrigatorio, Array.Empty<object>()), true); + } + DateTime? clienteDesde = this.ClienteDesde; + if (clienteDesde.HasValue) + { + clienteDesde = this.ClienteDesde; + if (DateTime.Compare(clienteDesde.Value, new DateTime(1753, 1, 1)) >= 0) + { + clienteDesde = this.ClienteDesde; + if (DateTime.Compare(clienteDesde.Value, new DateTime(9999, 12, 31)) <= 0) + { + goto Label0; + } + } + keyValuePairs.AddValue<string, string>("ClienteDesde|CLIENTE DESDE", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + Label0: + DateTime networkTime = Funcoes.GetNetworkTime(); + DateTime date = networkTime.Date; + clienteDesde = this.Nascimento; + if (clienteDesde.HasValue) + { + clienteDesde = this.Nascimento; + networkTime = date; + if ((clienteDesde.HasValue ? clienteDesde.GetValueOrDefault() > networkTime : false)) + { + keyValuePairs.AddValue<string, string>(string.Concat("Nascimento|", (this.Documento.OnlyNumber().Length > 11 ? "FUNDAÇÃO" : "NASCIMENTO")), Messages.Invalido, true); + } + } + clienteDesde = this.Nascimento; + if (clienteDesde.HasValue) + { + clienteDesde = this.Nascimento; + if (DateTime.Compare(clienteDesde.Value, new DateTime(1753, 1, 1)) >= 0) + { + clienteDesde = this.Nascimento; + if (DateTime.Compare(clienteDesde.Value, new DateTime(9999, 12, 31)) <= 0) + { + goto Label1; + } + } + keyValuePairs.AddValue<string, string>(string.Concat("Nascimento|", (this.Documento.OnlyNumber().Length > 11 ? "FUNDAÇÃO" : "NASCIMENTO")), string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + if (string.IsNullOrWhiteSpace(this.Documento)) + { + keyValuePairs.AddValue<string, string>("Documento", Messages.Obrigatorio, true); + } + else if (!this.Documento.ValidacaoDocumento()) + { + keyValuePairs.AddValue<string, string>("Documento", Messages.Invalido, true); + } + documentoPrincipal = this.DocumentoPrincipal; + if (documentoPrincipal.HasValue) + { + switch (documentoPrincipal.GetValueOrDefault()) + { + case TipoDocumento.Rne: + { + if (!string.IsNullOrWhiteSpace(this.Rne)) + { + if (this.Rne.ValidacaoRne()) + { + break; + } + keyValuePairs.AddValue<string, string>("Rne", Messages.Invalido, true); + break; + } + else + { + keyValuePairs.AddValue<string, string>("Rne", Messages.Obrigatorio, true); + break; + } + } + case TipoDocumento.Cei: + { + if (!string.IsNullOrWhiteSpace(this.Cei)) + { + if (this.Cei.ValidacaoCei()) + { + break; + } + keyValuePairs.AddValue<string, string>("Cei", Messages.Invalido, true); + break; + } + else + { + keyValuePairs.AddValue<string, string>("Cei", Messages.Obrigatorio, true); + break; + } + } + case TipoDocumento.Caepf: + { + if (!string.IsNullOrWhiteSpace(this.Caepf)) + { + if (this.Caepf.ValidateCaepf()) + { + break; + } + keyValuePairs.AddValue<string, string>("Caepf", Messages.Invalido, true); + break; + } + else + { + keyValuePairs.AddValue<string, string>("Caepf", Messages.Obrigatorio, true); + break; + } + } + } + } + if (this.Documento == null || this.Documento.OnlyNumber().Length <= 11) + { + clienteDesde = this.PrimeiraHabilitacao; + if (clienteDesde.HasValue) + { + clienteDesde = this.PrimeiraHabilitacao; + networkTime = date; + if ((clienteDesde.HasValue ? clienteDesde.GetValueOrDefault() > networkTime : false)) + { + keyValuePairs.AddValue<string, string>("PrimeiraHabilitacao|PRIMEIRA HABILITAÇÃO", Messages.Invalido, true); + } + } + clienteDesde = this.PrimeiraHabilitacao; + if (clienteDesde.HasValue) + { + clienteDesde = this.PrimeiraHabilitacao; + if (DateTime.Compare(clienteDesde.Value, new DateTime(1753, 1, 1)) >= 0) + { + clienteDesde = this.PrimeiraHabilitacao; + if (DateTime.Compare(clienteDesde.Value, new DateTime(9999, 12, 31)) <= 0) + { + goto Label2; + } + } + keyValuePairs.AddValue<string, string>("PrimeiraHabilitacao|PRIMEIRA HABILITAÇÃO", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + Label2: + clienteDesde = this.VencimentoHabilitacao; + if (clienteDesde.HasValue) + { + clienteDesde = this.VencimentoHabilitacao; + primeiraHabilitacao = this.PrimeiraHabilitacao; + if ((clienteDesde.HasValue & primeiraHabilitacao.HasValue ? clienteDesde.GetValueOrDefault() <= primeiraHabilitacao.GetValueOrDefault() : false)) + { + keyValuePairs.AddValue<string, string>("VencimentoHabilitacao|VENCIMENTO HABILITAÇÃO", Messages.Invalido, true); + } + } + primeiraHabilitacao = this.VencimentoHabilitacao; + if (primeiraHabilitacao.HasValue) + { + primeiraHabilitacao = this.VencimentoHabilitacao; + if (DateTime.Compare(primeiraHabilitacao.Value, new DateTime(1753, 1, 1)) >= 0) + { + primeiraHabilitacao = this.VencimentoHabilitacao; + if (DateTime.Compare(primeiraHabilitacao.Value, new DateTime(9999, 12, 31)) <= 0) + { + goto Label3; + } + } + keyValuePairs.AddValue<string, string>("VencimentoHabilitacao|VENCIMENTO HABILITAÇÃO", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + Label3: + primeiraHabilitacao = this.Expedicao; + if (primeiraHabilitacao.HasValue) + { + primeiraHabilitacao = this.Expedicao; + if (DateTime.Compare(primeiraHabilitacao.Value, new DateTime(1753, 1, 1)) >= 0) + { + primeiraHabilitacao = this.Expedicao; + if (DateTime.Compare(primeiraHabilitacao.Value, new DateTime(9999, 12, 31)) <= 0) + { + goto Label4; + } + } + keyValuePairs.AddValue<string, string>("Expedicao|EXPEDIÇÃO", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + Label4: + primeiraHabilitacao = this.Expedicao; + if (primeiraHabilitacao.HasValue) + { + primeiraHabilitacao = this.Expedicao; + networkTime = date; + if ((primeiraHabilitacao.HasValue ? primeiraHabilitacao.GetValueOrDefault() > networkTime : false)) + { + keyValuePairs.AddValue<string, string>("Expedicao|EXPEDIÇÃO", Messages.Invalido, true); + } + } + if (!string.IsNullOrWhiteSpace(this.Identidade) && this.Identidade.Length > 14) + { + keyValuePairs.AddValue<string, string>("Identidade", string.Format(Messages.MaiorQueLimite, 14), true); + } + if (!string.IsNullOrWhiteSpace(this.Habilitacao) && this.Habilitacao.Length > 15) + { + keyValuePairs.AddValue<string, string>("Habilitacao|HABILITAÇÃO", string.Format(Messages.MaiorQueLimite, 15), true); + } + if (!string.IsNullOrWhiteSpace(this.CategoriaHabilitacao) && this.CategoriaHabilitacao.Length > 10) + { + keyValuePairs.AddValue<string, string>("CategoriaHabilitacao|CATEGORIA HABILITAÇÃO", string.Format(Messages.MaiorQueLimite, 10), true); + } + if (!string.IsNullOrWhiteSpace(this.Emissor) && !this.Emissor.ValidacaoOrgao()) + { + keyValuePairs.AddValue<string, string>("Emissor|EMISSOR", string.Format(Messages.MaiorQueLimite, 6), true); + } + if (!string.IsNullOrWhiteSpace(this.EstadoEmissor) && !this.EstadoEmissor.ValidacaoEstado()) + { + keyValuePairs.AddValue<string, string>("EstadoEmissor|ESTADO EMISSOR", Messages.Invalido, true); + } + } + if (!string.IsNullOrWhiteSpace(this.Pasta) && this.Pasta.Length > 8) + { + keyValuePairs.AddValue<string, string>("Pasta", string.Format(Messages.MaiorQueLimite, 8), true); + } + if (!string.IsNullOrWhiteSpace(this.Agencia) && this.Agencia.Length > 8) + { + keyValuePairs.AddValue<string, string>("Agencia|AGÊNCIA", string.Format(Messages.MaiorQueLimite, 8), true); + } + if (!string.IsNullOrWhiteSpace(this.TipoConta) && this.TipoConta.Length > 20) + { + keyValuePairs.AddValue<string, string>("TipoConta|TIPO CONTA", string.Format(Messages.MaiorQueLimite, 20), true); + } + if (!string.IsNullOrWhiteSpace(this.Conta) && this.Conta.Length > 12) + { + keyValuePairs.AddValue<string, string>("Conta", string.Format(Messages.MaiorQueLimite, 12), true); + } + if (this.ResponsavelAssinatura != null) + { + keyValuePairs.AddRange(this.ResponsavelAssinatura.Validate()); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/ClienteEmail.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/ClienteEmail.cs new file mode 100644 index 0000000..0175f31 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/ClienteEmail.cs @@ -0,0 +1,88 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class ClienteEmail : EmailBase, IDomain + { + private string _observacao; + + public Gestor.Model.Domain.Seguros.Cliente Cliente + { + get; + set; + } + + [Log(true)] + public string Observacao + { + get + { + string str = this._observacao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._observacao = value; + } + } + + public int? Ordem + { + get; + set; + } + + public bool Selecionado + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + ClienteEmail clienteEmail = this; + return new Func<List<KeyValuePair<string, string>>>(clienteEmail.Validate); + } + } + + public ClienteEmail() + { + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (string.IsNullOrWhiteSpace(base.Email)) + { + keyValuePairs.AddValue<string, string>("Email", Messages.Obrigatorio, true); + } + else if (base.Email.Length > 80) + { + keyValuePairs.AddValue<string, string>("Email", string.Format(Messages.MaiorQueLimite, 80), true); + } + else if (!base.Email.ValidacaoEmail()) + { + keyValuePairs.AddValue<string, string>("Email", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.Observacao) && this.Observacao.Length > 255) + { + keyValuePairs.AddValue<string, string>("Observacao", string.Format(Messages.MaiorQueLimite, 255), true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/ClienteEndereco.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/ClienteEndereco.cs new file mode 100644 index 0000000..5085632 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/ClienteEndereco.cs @@ -0,0 +1,155 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Gestor.Model.Domain.Seguros +{ + public class ClienteEndereco : EnderecoBase, IDomain, INotifyPropertyChanged + { + private bool _selecionado; + + private string _observacao; + + public Gestor.Model.Domain.Seguros.Cliente Cliente + { + get; + set; + } + + [Log(true)] + public string Observacao + { + get + { + string str = this._observacao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._observacao = value; + } + } + + public int? Ordem + { + get; + set; + } + + public bool Selecionado + { + get + { + return this._selecionado; + } + set + { + if (value == this._selecionado) + { + return; + } + this._selecionado = value; + this.OnPropertyChanged("Selecionado"); + } + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + ClienteEndereco clienteEndereco = this; + return new Func<List<KeyValuePair<string, string>>>(clienteEndereco.Validate); + } + } + + public ClienteEndereco() + { + } + + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChangedEventHandler propertyChangedEventHandler = this.PropertyChanged; + if (propertyChangedEventHandler == null) + { + return; + } + propertyChangedEventHandler(this, new PropertyChangedEventArgs(propertyName)); + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (string.IsNullOrWhiteSpace(base.Cep)) + { + keyValuePairs.AddValue<string, string>("Cep", Messages.Obrigatorio, true); + } + else if (!base.Cep.ValidacaoCep()) + { + keyValuePairs.AddValue<string, string>("Cep", Messages.Invalido, true); + } + if (string.IsNullOrWhiteSpace(base.Endereco)) + { + keyValuePairs.AddValue<string, string>("Endereco", Messages.Obrigatorio, true); + } + else if (base.Endereco.Length > 150) + { + keyValuePairs.AddValue<string, string>("Endereco", string.Format(Messages.MaiorQueLimite, 150), true); + } + if (string.IsNullOrWhiteSpace(base.Numero)) + { + keyValuePairs.AddValue<string, string>("Numero", Messages.Obrigatorio, true); + } + else if (base.Numero.Length > 6) + { + keyValuePairs.AddValue<string, string>("Numero", string.Format(Messages.MaiorQueLimite, 6), true); + } + if (!string.IsNullOrWhiteSpace(base.Complemento) && base.Complemento.Length > 45) + { + keyValuePairs.AddValue<string, string>("Complemento", string.Format(Messages.MaiorQueLimite, 45), true); + } + if (string.IsNullOrWhiteSpace(base.Bairro)) + { + keyValuePairs.AddValue<string, string>("Bairro", Messages.Obrigatorio, true); + } + else if (base.Bairro.Length > 100) + { + keyValuePairs.AddValue<string, string>("Bairro", string.Format(Messages.MaiorQueLimite, 100), true); + } + if (string.IsNullOrWhiteSpace(base.Cidade)) + { + keyValuePairs.AddValue<string, string>("Cidade", Messages.Obrigatorio, true); + } + else if (base.Cidade.Length > 50) + { + keyValuePairs.AddValue<string, string>("Cidade", string.Format(Messages.MaiorQueLimite, 50), true); + } + if (string.IsNullOrWhiteSpace(base.Estado)) + { + keyValuePairs.AddValue<string, string>("Estado", Messages.Obrigatorio, true); + } + else if (!base.Estado.ValidacaoEstado()) + { + keyValuePairs.AddValue<string, string>("Estado", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.Observacao) && this.Observacao.Length > 255) + { + keyValuePairs.AddValue<string, string>("Observacao", string.Format(Messages.MaiorQueLimite, 255), true); + } + return keyValuePairs; + } + + public event PropertyChangedEventHandler PropertyChanged; + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/ClienteTelefone.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/ClienteTelefone.cs new file mode 100644 index 0000000..794790b --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/ClienteTelefone.cs @@ -0,0 +1,82 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class ClienteTelefone : TelefoneBase, IDomain + { + private string _observacao; + + public Gestor.Model.Domain.Seguros.Cliente Cliente + { + get; + set; + } + + [Log(true)] + public string Observacao + { + get + { + string str = this._observacao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._observacao = value; + } + } + + public int? Ordem + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + ClienteTelefone clienteTelefone = this; + return new Func<List<KeyValuePair<string, string>>>(clienteTelefone.Validate); + } + } + + public ClienteTelefone() + { + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = base.ValidateBase(true); + if (!string.IsNullOrWhiteSpace(this.Observacao) && this.Observacao.Length > 30) + { + keyValuePairs.AddValue<string, string>("Observacao", string.Format(Messages.MaiorQueLimite, 30), true); + } + if (string.IsNullOrWhiteSpace(base.Numero)) + { + keyValuePairs.AddValue<string, string>("Numero", Messages.Obrigatorio, true); + } + if (string.IsNullOrWhiteSpace(base.Prefixo)) + { + keyValuePairs.AddValue<string, string>("Prefixo", Messages.Obrigatorio, true); + } + if (!base.Tipo.HasValue) + { + keyValuePairs.AddValue<string, string>("Tipo", Messages.Obrigatorio, true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/ClienteVinculo.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/ClienteVinculo.cs new file mode 100644 index 0000000..c8065fe --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/ClienteVinculo.cs @@ -0,0 +1,56 @@ +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class ClienteVinculo : DomainBase, IDomain + { + public Cliente Cliente1 + { + get; + set; + } + + public Cliente Cliente2 + { + get; + set; + } + + public ParentescoVinculo? Parentesco + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + ClienteVinculo clienteVinculo = this; + return new Func<List<KeyValuePair<string, string>>>(clienteVinculo.Validate); + } + } + + public ClienteVinculo() + { + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (!this.Parentesco.HasValue) + { + keyValuePairs.AddValue<string, string>("Parentesco", Messages.Obrigatorio, true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/Cobertura.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/Cobertura.cs new file mode 100644 index 0000000..f0b8c66 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/Cobertura.cs @@ -0,0 +1,86 @@ +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class Cobertura : DomainBase, IDomain + { + private string _observacao; + + public Gestor.Model.Domain.Seguros.CoberturaPadrao CoberturaPadrao + { + get; + set; + } + + public decimal Franquia + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Item Item + { + get; + set; + } + + public decimal Lmi + { + get; + set; + } + + public string Observacao + { + get + { + string str = this._observacao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._observacao = (!string.IsNullOrWhiteSpace(value) || this.CoberturaPadrao == null ? value : this.CoberturaPadrao.Descricao); + } + } + + public decimal Premio + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Cobertura cobertura = this; + return new Func<List<KeyValuePair<string, string>>>(cobertura.Validate); + } + } + + public Cobertura() + { + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if ((this.Lmi != decimal.Zero || this.Premio != decimal.Zero || this.Franquia != decimal.Zero) && string.IsNullOrWhiteSpace(this.Observacao)) + { + keyValuePairs.AddValue<string, string>("Observacao", Messages.Obrigatorio, true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/CoberturaGranizo.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/CoberturaGranizo.cs new file mode 100644 index 0000000..c2af1c3 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/CoberturaGranizo.cs @@ -0,0 +1,125 @@ +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class CoberturaGranizo : DomainBase, IDomain + { + private string _variedade; + + private string _quadra; + + public decimal? Area + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Granizo Granizo + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Item Item + { + get; + set; + } + + public decimal? Lmi + { + get; + set; + } + + public DateTime? Plantio + { + get; + set; + } + + public decimal? Premio + { + get; + set; + } + + public decimal? Produtividade + { + get; + set; + } + + public string Quadra + { + get + { + string str = this._quadra; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._quadra = value; + } + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + CoberturaGranizo coberturaGranizo = this; + return new Func<List<KeyValuePair<string, string>>>(coberturaGranizo.Validate); + } + } + + public string Variedade + { + get + { + string str = this._variedade; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._variedade = value; + } + } + + public CoberturaGranizo() + { + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (this.Plantio.HasValue && (DateTime.Compare(this.Plantio.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.Plantio.Value, new DateTime(9999, 12, 31)) > 0)) + { + keyValuePairs.AddValue<string, string>("Plantio", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + if (string.IsNullOrWhiteSpace(this.Variedade) && this.Variedade.Length > 60) + { + keyValuePairs.AddValue<string, string>("Variedade", string.Format(Messages.MaiorQueLimite, 60), true); + } + if (string.IsNullOrWhiteSpace(this.Quadra) && this.Quadra.Length > 30) + { + keyValuePairs.AddValue<string, string>("Quadra", string.Format(Messages.MaiorQueLimite, 30), true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/CoberturaPadrao.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/CoberturaPadrao.cs new file mode 100644 index 0000000..81a4e23 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/CoberturaPadrao.cs @@ -0,0 +1,67 @@ +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Text.RegularExpressions; + +namespace Gestor.Model.Domain.Seguros +{ + public class CoberturaPadrao : DomainBase, IDomain + { + private string _descricao; + + public string Descricao + { + get + { + if (!string.IsNullOrWhiteSpace(this._descricao)) + { + this._descricao = Regex.Replace(this._descricao, "[\n\r]", ""); + } + string str = this._descricao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._descricao = value; + } + } + + public long IdRamo + { + get; + set; + } + + public bool Padrao + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + CoberturaPadrao coberturaPadrao = this; + return new Func<List<KeyValuePair<string, string>>>(coberturaPadrao.Validate); + } + } + + public CoberturaPadrao() + { + } + + public List<KeyValuePair<string, string>> Validate() + { + return ValidationHelper.AddValue(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/CondicaoRepasse.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/CondicaoRepasse.cs new file mode 100644 index 0000000..c921485 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/CondicaoRepasse.cs @@ -0,0 +1,49 @@ +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class CondicaoRepasse : DomainBase, IDomain + { + public int Parcela + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Ramo Ramo + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Seguradora Seguradora + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + CondicaoRepasse condicaoRepasse = this; + return new Func<List<KeyValuePair<string, string>>>(condicaoRepasse.Validate); + } + } + + public CondicaoRepasse() + { + } + + public List<KeyValuePair<string, string>> Validate() + { + return ValidationHelper.AddValue(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/ConfigExtratoImport.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/ConfigExtratoImport.cs new file mode 100644 index 0000000..8a4cbbf --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/ConfigExtratoImport.cs @@ -0,0 +1,50 @@ +using Gestor.Model.Domain.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class ConfigExtratoImport : DomainBase + { + private string _descricao; + + public bool Ativo + { + get; + set; + } + + public string Codigo + { + get; + set; + } + + public string Descricao + { + get + { + string str = this._descricao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._descricao = value; + } + } + + public long IdSeguradora + { + get; + set; + } + + public ConfigExtratoImport() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/Consorcio.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/Consorcio.cs new file mode 100644 index 0000000..3efd5ad --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/Consorcio.cs @@ -0,0 +1,191 @@ +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Globalization; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class Consorcio : DomainBase, IDomain + { + private string _bensConsorcio; + + private string _grupo; + + private string _cota; + + private decimal? _valorCredito; + + private string _observacao; + + public string BensConsorcio + { + get + { + string str = this._bensConsorcio; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._bensConsorcio = value; + } + } + + public string Cota + { + get + { + string str = this._cota; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._cota = value; + } + } + + public string Grupo + { + get + { + string str = this._grupo; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._grupo = value; + } + } + + public Gestor.Model.Domain.Seguros.Item Item + { + get; + set; + } + + public string Observacao + { + get + { + string str = this._observacao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._observacao = value; + } + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Consorcio consorcio = this; + return new Func<List<KeyValuePair<string, string>>>(consorcio.Validate); + } + } + + public decimal? ValorCredito + { + get + { + return this._valorCredito; + } + set + { + this._valorCredito = value; + } + } + + public Consorcio() + { + } + + public static List<TupleList> Log(Gestor.Model.Domain.Seguros.Item item) + { + decimal valueOrDefault; + string str; + List<TupleList> tupleLists = new List<TupleList>(); + TupleList tupleList = new TupleList(); + ObservableCollection<Tuple<string, string, string>> observableCollection = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("DESCRIÇÃO", (string.IsNullOrWhiteSpace(item.Consorcio.BensConsorcio) ? "" : item.Consorcio.BensConsorcio), ""), + new Tuple<string, string, string>("GRUPO", (string.IsNullOrWhiteSpace(item.Consorcio.Grupo) ? "" : item.Consorcio.Grupo), ""), + new Tuple<string, string, string>("COTA", (string.IsNullOrWhiteSpace(item.Consorcio.Cota) ? "" : item.Consorcio.Cota), "") + }; + decimal? valorCredito = item.Consorcio.ValorCredito; + if (!valorCredito.HasValue) + { + str = ""; + } + else + { + valorCredito = item.Consorcio.ValorCredito; + if (valorCredito.HasValue) + { + valueOrDefault = valorCredito.GetValueOrDefault(); + str = valueOrDefault.ToString("C", new CultureInfo("pt-BR", false)); + } + else + { + str = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("GRUPO", str, "")); + tupleList.Tuples = observableCollection; + tupleLists.Add(tupleList); + List<TupleList> tupleLists1 = tupleLists; + ObservableCollection<Tuple<string, string, string>> observableCollection1 = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("COBERTURAS$", "", "") + }; + foreach (Cobertura cobertura in item.Coberturas) + { + observableCollection1.Add(new Tuple<string, string, string>(string.Format(" COBERTURA {0}$", item.Coberturas.IndexOf(cobertura) + 1), "", "")); + observableCollection1.Add(new Tuple<string, string, string>(" OBSERVAÇÃO", (string.IsNullOrWhiteSpace(cobertura.Observacao) ? "" : cobertura.Observacao.ToUpper()), "")); + valueOrDefault = cobertura.Premio; + observableCollection1.Add(new Tuple<string, string, string>(" PRÊMIO", valueOrDefault.ToString("C", new CultureInfo("pt-BR", false)), "")); + valueOrDefault = cobertura.Franquia; + observableCollection1.Add(new Tuple<string, string, string>(" FRANQUIA", valueOrDefault.ToString("C", new CultureInfo("pt-BR", false)), "")); + valueOrDefault = cobertura.Lmi; + observableCollection1.Add(new Tuple<string, string, string>(" L.M.I.", valueOrDefault.ToString("C", new CultureInfo("pt-BR", false)), "")); + } + tupleLists1.Add(new TupleList() + { + Tuples = observableCollection1 + }); + return tupleLists1; + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (string.IsNullOrWhiteSpace(this.BensConsorcio)) + { + keyValuePairs.AddValue<string, string>("BensConsorcio", Messages.Obrigatorio, true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/Controle.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/Controle.cs new file mode 100644 index 0000000..3ae91c6 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/Controle.cs @@ -0,0 +1,128 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class Controle : DomainBase, IDomain + { + private long _idEmpresa; + + public string AssistenciaId + { + get; + set; + } + + [Log(false)] + public Gestor.Model.Domain.Seguros.Cliente Cliente + { + get; + set; + } + + [Log(false)] + public IList<Documento> Documentos + { + get; + set; + } + + public long IdEmpresa + { + get + { + return this._idEmpresa; + } + set + { + this._idEmpresa = (value == 0 ? (long)1 : value); + } + } + + [Log(false)] + public Gestor.Model.Domain.Seguros.Item Item + { + get; + set; + } + + [Description("PRODUTO")] + [Log(true)] + [Name(true)] + public Gestor.Model.Domain.Seguros.Produto Produto + { + get; + set; + } + + [Description("RAMO")] + [Log(true)] + [Name(true)] + public Gestor.Model.Domain.Seguros.Ramo Ramo + { + get; + set; + } + + [Description("SEGURADORA")] + [Log(true)] + [Name(true)] + public Gestor.Model.Domain.Seguros.Seguradora Seguradora + { + get; + set; + } + + [Description("SEGURADORA ANTERIOR")] + [Log(true)] + [Name(true)] + public Gestor.Model.Domain.Seguros.Seguradora SeguradoraAnterior + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Controle controle = this; + return new Func<List<KeyValuePair<string, string>>>(controle.Validate); + } + } + + public Controle() + { + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (this.Cliente == null || this.Cliente.Id == 0) + { + keyValuePairs.AddValue<string, string>("Cliente", Messages.Obrigatorio, true); + } + if (this.Seguradora == null || this.Seguradora.Id == 0) + { + keyValuePairs.AddValue<string, string>("Seguradora", Messages.Obrigatorio, true); + } + if (this.Ramo == null || this.Ramo.Id == 0) + { + keyValuePairs.AddValue<string, string>("Ramo", Messages.Obrigatorio, true); + } + if (this.IdEmpresa == 0) + { + keyValuePairs.AddValue<string, string>("Empresa", Messages.Obrigatorio, true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/ControleSinistro.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/ControleSinistro.cs new file mode 100644 index 0000000..13207b6 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/ControleSinistro.cs @@ -0,0 +1,118 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class ControleSinistro : DomainBase, IDomain + { + private DateTime? _dataSinistro; + + private DateTime? _horaSinistro; + + [Description("DATA SINISTRO")] + [Log(true)] + [Name(true)] + public DateTime? DataSinistro + { + get + { + return this._dataSinistro; + } + set + { + if (!value.HasValue) + { + this._dataSinistro = null; + return; + } + if (!this.HoraSinistro.HasValue) + { + this.HoraSinistro = value; + } + object obj = value.Value; + DateTime? horaSinistro = this.HoraSinistro; + this._dataSinistro = new DateTime?(DateTime.Parse(string.Format("{0:d} {1:T}", obj, horaSinistro.Value))); + } + } + + public DateTime? HoraSinistro + { + get + { + return this._horaSinistro; + } + set + { + DateTime? nullable; + this._horaSinistro = value; + if (!value.HasValue) + { + return; + } + DateTime? dataSinistro = this.DataSinistro; + if (!dataSinistro.HasValue || !value.HasValue) + { + dataSinistro = null; + nullable = dataSinistro; + } + else + { + dataSinistro = this.DataSinistro; + nullable = new DateTime?(DateTime.Parse(string.Format("{0:d} {1:T}", dataSinistro.Value, value))); + } + this.DataSinistro = nullable; + } + } + + public Gestor.Model.Domain.Seguros.Item Item + { + get; + set; + } + + public List<Sinistro> Sinistros + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + ControleSinistro controleSinistro = this; + return new Func<List<KeyValuePair<string, string>>>(controleSinistro.Validate); + } + } + + public ControleSinistro() + { + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (!this.DataSinistro.HasValue) + { + keyValuePairs.AddValue<string, string>("DataSinistro", Messages.Obrigatorio, true); + } + if (this.DataSinistro.HasValue && (DateTime.Compare(this.DataSinistro.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.DataSinistro.Value, new DateTime(9999, 12, 31)) > 0)) + { + keyValuePairs.AddValue<string, string>("DataSinistro", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + if (this.HoraSinistro.HasValue && (DateTime.Compare(this.HoraSinistro.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.HoraSinistro.Value, new DateTime(9999, 12, 31)) > 0)) + { + keyValuePairs.AddValue<string, string>("HoraSinistro", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/CriticaApolice.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/CriticaApolice.cs new file mode 100644 index 0000000..efdfa8c --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/CriticaApolice.cs @@ -0,0 +1,116 @@ +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class CriticaApolice : DomainBase, IDomain + { + private string _naoEncontrados; + + private bool? _critica; + + public bool? Aggilizador + { + get; + set; + } + + public bool? Critica + { + get + { + return this._critica; + } + set + { + this._critica = new bool?(value.GetValueOrDefault()); + } + } + + public DateTime? DataCritica + { + get; + set; + } + + public DateTime? DataImportacao + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Documento Documento + { + get; + set; + } + + public string NaoEncontrados + { + get + { + string str = this._naoEncontrados; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._naoEncontrados = value; + } + } + + public string Tipo + { + get; + set; + } + + public long? UsuarioCritica + { + get; + set; + } + + public Usuario UsuarioImportacao + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + CriticaApolice criticaApolouse = this; + return new Func<List<KeyValuePair<string, string>>>(criticaApolouse.Validate); + } + } + + public CriticaApolice() + { + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (this.DataImportacao.HasValue && (DateTime.Compare(this.DataImportacao.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.DataImportacao.Value, new DateTime(9999, 12, 31)) > 0)) + { + keyValuePairs.AddValue<string, string>("DataImportacao", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + if (this.DataCritica.HasValue && (DateTime.Compare(this.DataCritica.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.DataCritica.Value, new DateTime(9999, 12, 31)) > 0)) + { + keyValuePairs.AddValue<string, string>("DataCritica", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/DetalheExtrato.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/DetalheExtrato.cs new file mode 100644 index 0000000..c03bd40 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/DetalheExtrato.cs @@ -0,0 +1,250 @@ +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Gestor.Model.Domain.Seguros +{ + public class DetalheExtrato : DomainBase, IDomain, INotifyPropertyChanged + { + private bool _selecionado; + + private string _cliente; + + private string _apolice; + + private string _endosso; + + private string _numeroParcela; + + private string _historico; + + public bool IsNormal = true; + + public string Apolice + { + get + { + string str = this._apolice; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._apolice = value; + } + } + + public string Cliente + { + get + { + string str = this._cliente; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._cliente = value; + } + } + + public decimal? Comissao + { + get; + set; + } + + public bool Corrigir + { + get; + set; + } + + public DateTime? Credito + { + get; + set; + } + + public long? Documento + { + get; + set; + } + + public string Endosso + { + get + { + string str = this._endosso; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._endosso = value; + } + } + + public Gestor.Model.Domain.Seguros.Extrato Extrato + { + get; + set; + } + + public string Historico + { + get + { + string str = this._historico; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._historico = value; + } + } + + public string NumeroParcela + { + get + { + string str = this._numeroParcela; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._numeroParcela = value; + } + } + + public long? Parcela + { + get; + set; + } + + public DateTime? Recebimento + { + get; + set; + } + + public bool Selecionado + { + get + { + return this._selecionado; + } + set + { + this._selecionado = value; + this.OnPropertyChanged("Selecionado"); + } + } + + public StatusParcela? Status + { + get; + set; + } + + public Gestor.Model.Common.SubTipo? SubTipo + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + DetalheExtrato detalheExtrato = this; + return new Func<List<KeyValuePair<string, string>>>(detalheExtrato.Validate); + } + } + + public decimal? Valor + { + get; + set; + } + + public decimal? ValorComissao + { + get; + set; + } + + public DetalheExtrato() + { + } + + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChangedEventHandler propertyChangedEventHandler = this.PropertyChanged; + if (propertyChangedEventHandler == null) + { + return; + } + propertyChangedEventHandler(this, new PropertyChangedEventArgs(propertyName)); + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (this.Recebimento.HasValue && (DateTime.Compare(this.Recebimento.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.Recebimento.Value, new DateTime(9999, 12, 31)) > 0)) + { + keyValuePairs.AddValue<string, string>("Recebimento", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + if (this.Credito.HasValue && (DateTime.Compare(this.Credito.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.Credito.Value, new DateTime(9999, 12, 31)) > 0)) + { + keyValuePairs.AddValue<string, string>("Credito", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + if (string.IsNullOrWhiteSpace(this.Cliente) && this.Cliente.Length > 100) + { + keyValuePairs.AddValue<string, string>("Cliente", string.Format(Messages.MaiorQueLimite, 100), true); + } + if (string.IsNullOrWhiteSpace(this.Apolice) && this.Apolice.Length > 30) + { + keyValuePairs.AddValue<string, string>("Apolice", string.Format(Messages.MaiorQueLimite, 30), true); + } + if (string.IsNullOrWhiteSpace(this.Endosso) && this.Endosso.Length > 20) + { + keyValuePairs.AddValue<string, string>("Endosso", string.Format(Messages.MaiorQueLimite, 20), true); + } + if (string.IsNullOrWhiteSpace(this.NumeroParcela) && this.NumeroParcela.Length > 4) + { + keyValuePairs.AddValue<string, string>("NumeroParcela", string.Format(Messages.MaiorQueLimite, 4), true); + } + return keyValuePairs; + } + + public event PropertyChangedEventHandler PropertyChanged; + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/Documento.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/Documento.cs new file mode 100644 index 0000000..00ae7de --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/Documento.cs @@ -0,0 +1,1426 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using Gestor.Model.Domain.Aggilizador; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Gestor.Model.Validation; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Globalization; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Gestor.Model.Domain.Seguros +{ + public class Documento : DomainBase, IDomain + { + private bool _selecionado; + + private string _proposta; + + private string _propostaEndosso; + + private string _apoliceAnterior; + + private string _apolice; + + private string _endosso; + + private string _pasta; + + private string _agencia; + + private string _conta; + + private string _numeroCartao; + + private string _vencimentoCartao; + + private string _nomeProponente; + + private bool _isEndosso; + + private bool _vencimentoParcela; + + [Description("ADICIONAL DE COMISSÃO")] + [Log(true)] + public bool AdicionalComiss + { + get; + set; + } + + [Description("AGÊNCIA")] + [Log(true)] + public string Agencia + { + get + { + string str = this._agencia; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._agencia = value; + } + } + + [Description("APÓLICE")] + [Log(true)] + public string Apolice + { + get + { + string str = this._apolice; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._apolice = value; + } + } + + [Description("APÓLICE ANTERIOR")] + [Log(true)] + public string ApoliceAnterior + { + get + { + string str = this._apoliceAnterior; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._apoliceAnterior = value; + } + } + + [Description("APÓLICE CONFERIDA")] + [Log(true)] + public bool ApoliceConferida + { + get; + set; + } + + public bool AssinadaSiggner + { + get; + set; + } + + [Log(false)] + public List<StatusDocumentoAssinado> Assinaturas + { + get; + set; + } + + [Log(true)] + public Gestor.Model.Domain.Common.Banco Banco + { + get; + set; + } + + [Log(true)] + public BandeiraCartao? Bandeira + { + get; + set; + } + + [Log(false)] + public List<Calculo> Calculos + { + get; + set; + } + + [Description("COMISSÃO")] + [Log(true)] + public decimal Comissao + { + get; + set; + } + + public decimal? ComissaoTotal + { + get; + set; + } + + [Log(true)] + public string Conta + { + get + { + string str = this._conta; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._conta = value; + } + } + + public Gestor.Model.Domain.Seguros.Controle Controle + { + get; + set; + } + + [Description("CUSTO DE EMISSÃO")] + [Log(true)] + public decimal Custo + { + get; + set; + } + + [Description("DATA DE CONTROLE")] + [Log(true)] + public DateTime? DataControle + { + get; + set; + } + + public DateTime? DataCriacao + { + get; + set; + } + + [Description("DIFERENÇA")] + [Log(true)] + public decimal Diferenca + { + get; + set; + } + + [Description("EMISSÃO")] + [Log(true)] + public DateTime? Emissao + { + get; + set; + } + + [Log(true)] + public string Endosso + { + get + { + string str = this._endosso; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._endosso = value; + } + } + + [Description("ESTIPULANTE 1")] + [Log(true)] + public Estipulante Estipulante1 + { + get; + set; + } + + [Description("ESTIPULANTE 2")] + [Log(true)] + public Estipulante Estipulante2 + { + get; + set; + } + + [Description("ESTIPULANTE 3")] + [Log(true)] + public Estipulante Estipulante3 + { + get; + set; + } + + [Description("ESTIPULANTE 4")] + [Log(true)] + public Estipulante Estipulante4 + { + get; + set; + } + + [Description("ESTIPULANTE 5")] + [Log(true)] + public Estipulante Estipulante5 + { + get; + set; + } + + public string Estipulantes + { + get; + set; + } + + public bool Excluido + { + get; + set; + } + + public bool FinalVigencia + { + get; + set; + } + + [Description("FORMA DE PAGAMENTO")] + [Log(true)] + public Gestor.Model.Common.FormaPagamento? FormaPagamento + { + get; + set; + } + + [Description("IOF")] + [Log(true)] + public decimal Iof + { + get; + set; + } + + [Log(false)] + public List<Item> ItensAtivo + { + get; + set; + } + + [Log(false)] + public Gestor.Model.Common.Negocio? Negocio + { + get; + set; + } + + [Description("NEGÓCIO CORRETORA")] + [Log(true)] + public Gestor.Model.Common.NegocioCorretora? NegocioCorretora + { + get; + set; + } + + [Description("PROPONENTE")] + [Log(true)] + public string NomeProponente + { + get + { + string str = this._nomeProponente; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._nomeProponente = value; + } + } + + [Description("NÚMERO CARTÃO")] + [Log(true)] + public string NumeroCartao + { + get + { + string str = this._numeroCartao; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._numeroCartao = value; + } + } + + [Description("QUANTIDADE DE PARCELAS")] + [Log(true)] + public decimal NumeroParcelas + { + get; + set; + } + + [Log(true)] + public string Observacao + { + get; + set; + } + + public string ObsProtocolo + { + get; + set; + } + + public int Ordem + { + get; + set; + } + + [Log(false)] + public List<VendedorParcela> Pagamentos + { + get; + set; + } + + [Log(false)] + public ObservableCollection<Parcela> Parcelas + { + get; + set; + } + + [Log(true)] + public string Pasta + { + get + { + string str = this._pasta; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._pasta = value; + } + } + + [Log(false)] + public decimal? PercentualRepasse + { + get; + set; + } + + [Description("PRÊMIO ADICIONAL")] + [Log(true)] + public decimal PremioAdicional + { + get; + set; + } + + [Description("PRÊMIO LÍQUIDO")] + [Log(true)] + public decimal PremioLiquido + { + get; + set; + } + + [Description("PRÊMIO TOTAL")] + [Log(true)] + public decimal PremioTotal + { + get; + set; + } + + [Log(true)] + public string Proposta + { + get + { + string str = this._proposta; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._proposta = value; + } + } + + [Log(true)] + public bool PropostaAssinada + { + get; + set; + } + + [Description("PROPOSTA DE ENDOSSO")] + [Log(true)] + public string PropostaEndosso + { + get + { + string str = this._propostaEndosso; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._propostaEndosso = value; + } + } + + public bool ProtocoloEmail + { + get; + set; + } + + public bool ProtocoloEndereco + { + get; + set; + } + + public bool ProtocoloParcela + { + get; + set; + } + + public bool ProtocoloTelefone + { + get; + set; + } + + public bool ProtocoloVendedor + { + get; + set; + } + + [Description("TRANSMISSÃO DA PROPOSTA")] + [Log(true)] + public DateTime? Remessa + { + get; + set; + } + + public bool Selecionado + { + get + { + return this._selecionado; + } + set + { + if (value == this._selecionado) + { + return; + } + this._selecionado = value; + this.OnPropertyChanged("Selecionado"); + } + } + + [Log(false)] + public bool Sinistro + { + get; + set; + } + + [Description("SITUAÇÃO")] + [Log(true)] + public TipoSeguro Situacao + { + get; + set; + } + + [Log(false)] + public TipoSeguro? SituacaoAnterior + { + get; + set; + } + + [Description("STATUS INTERNO")] + [Log(true)] + public Gestor.Model.Domain.Seguros.Status Status + { + get; + set; + } + + public Gestor.Model.Common.StatusAssinatura StatusAssinatura + { + get; + set; + } + + [Log(false)] + public bool TemEndosso + { + get; + set; + } + + public int Tipo + { + get; + set; + } + + [Description("TIPO DO ENDOSSO")] + [Log(true)] + public Gestor.Model.Common.TipoEndosso? TipoEndosso + { + get; + set; + } + + [Description("TIPO RECEBIMENTO")] + [Log(true)] + public Gestor.Model.Common.TipoRecebimento? TipoRecebimento + { + get; + set; + } + + [Log(false)] + public Usuario UsuarioCriacao + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Documento documento = this; + return new Func<List<KeyValuePair<string, string>>>(documento.Validate); + } + } + + [Description("VENCIMENTO CARTÃO")] + [Log(true)] + public string VencimentoCartao + { + get + { + string str = this._vencimentoCartao; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._vencimentoCartao = value; + } + } + + [Log(false)] + public List<Vendedor> Vendedores + { + get; + set; + } + + [Log(false)] + public Vendedor VendedorPrincipal + { + get; + set; + } + + [Description("VIGÊNCIA INICIAL")] + [Log(true)] + public DateTime Vigencia1 + { + get; + set; + } + + [Description("VIGÊNCIA FINAL")] + [Log(true)] + public DateTime? Vigencia2 + { + get; + set; + } + + [Log(false)] + public VinculoDocumento Vinculo + { + get; + set; + } + + public Documento() + { + } + + public Documento DeepCopy() + { + return JsonConvert.DeserializeObject<Documento>(JsonConvert.SerializeObject(this)); + } + + public List<TupleList> Log(bool restricaoComissao) + { + decimal comissao; + string nome; + string str; + string nome1; + string description; + string description1; + string str1; + string shortDateString; + string shortDateString1; + string shortDateString2; + string nome2; + string description2; + string str2; + string str3; + string shortDateString3; + List<Tuple<string, string, string>> tuples = new List<Tuple<string, string, string>>(); + Gestor.Model.Domain.Seguros.Controle controle = this.Controle; + if (controle != null) + { + Seguradora seguradora = controle.Seguradora; + if (seguradora != null) + { + nome = seguradora.Nome; + } + else + { + nome = null; + } + } + else + { + nome = null; + } + tuples.Add(new Tuple<string, string, string>("SEGURADORA", (string.IsNullOrWhiteSpace(nome) ? "" : this.Controle.Seguradora.Nome.ToUpper()), "")); + Gestor.Model.Domain.Seguros.Controle controle1 = this.Controle; + if (controle1 != null) + { + Ramo ramo = controle1.Ramo; + if (ramo != null) + { + str = ramo.Nome; + } + else + { + str = null; + } + } + else + { + str = null; + } + tuples.Add(new Tuple<string, string, string>("RAMO", (string.IsNullOrWhiteSpace(str) ? "" : this.Controle.Ramo.Nome.ToUpper()), "")); + Gestor.Model.Domain.Seguros.Controle controle2 = this.Controle; + if (controle2 != null) + { + Produto produto = controle2.Produto; + if (produto != null) + { + nome1 = produto.Nome; + } + else + { + nome1 = null; + } + } + else + { + nome1 = null; + } + tuples.Add(new Tuple<string, string, string>("PRODUTO", (string.IsNullOrWhiteSpace(nome1) ? "" : this.Controle.Produto.Nome.ToUpper()), "")); + Gestor.Model.Common.NegocioCorretora? negocioCorretora = this.NegocioCorretora; + if (!negocioCorretora.HasValue) + { + description = ""; + } + else + { + negocioCorretora = this.NegocioCorretora; + if (negocioCorretora.HasValue) + { + description = negocioCorretora.GetValueOrDefault().GetDescription(); + } + else + { + description = null; + } + } + tuples.Add(new Tuple<string, string, string>("NEGÓCIO CORRETORA", description, "")); + tuples.Add(new Tuple<string, string, string>("STATUS DO SEGURO", this.Situacao.GetDescription(), "")); + Gestor.Model.Common.TipoRecebimento? tipoRecebimento = this.TipoRecebimento; + if (!tipoRecebimento.HasValue) + { + description1 = ""; + } + else + { + tipoRecebimento = this.TipoRecebimento; + if (tipoRecebimento.HasValue) + { + description1 = tipoRecebimento.GetValueOrDefault().GetDescription(); + } + else + { + description1 = null; + } + } + tuples.Add(new Tuple<string, string, string>("TIPO DE RECEBIMENTO", description1, "")); + Gestor.Model.Common.TipoEndosso? tipoEndosso = this.TipoEndosso; + if (!tipoEndosso.HasValue) + { + str1 = ""; + } + else + { + tipoEndosso = this.TipoEndosso; + if (tipoEndosso.HasValue) + { + str1 = tipoEndosso.GetValueOrDefault().GetDescription(); + } + else + { + str1 = null; + } + } + tuples.Add(new Tuple<string, string, string>("TIPO ENDOSSO", str1, "")); + tuples.Add(new Tuple<string, string, string>("PROPOSTA", (string.IsNullOrWhiteSpace(this.Proposta) ? "" : this.Proposta.ToUpper()), "")); + tuples.Add(new Tuple<string, string, string>("PROPOSTA ENDOSSO", (string.IsNullOrWhiteSpace(this.PropostaEndosso) ? "" : this.PropostaEndosso.ToUpper()), "")); + tuples.Add(new Tuple<string, string, string>("APÓLICE", (string.IsNullOrWhiteSpace(this.Apolice) ? "" : this.Apolice.ToUpper()), "")); + tuples.Add(new Tuple<string, string, string>("ENDOSSO", (string.IsNullOrWhiteSpace(this.Endosso) ? "" : this.Endosso.ToUpper()), "")); + DateTime vigencia1 = this.Vigencia1; + tuples.Add(new Tuple<string, string, string>("VIGÊNCIA INICIAL", vigencia1.ToShortDateString(), "")); + DateTime? vigencia2 = this.Vigencia2; + if (!vigencia2.HasValue) + { + shortDateString = ""; + } + else + { + vigencia2 = this.Vigencia2; + if (vigencia2.HasValue) + { + shortDateString = vigencia2.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString = null; + } + } + tuples.Add(new Tuple<string, string, string>("VIGÊNCIA FINAL", shortDateString, "")); + vigencia2 = this.Remessa; + if (!vigencia2.HasValue) + { + shortDateString1 = ""; + } + else + { + vigencia2 = this.Remessa; + if (vigencia2.HasValue) + { + shortDateString1 = vigencia2.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString1 = null; + } + } + tuples.Add(new Tuple<string, string, string>("TRANSMISSÃO DA PROPOSTA", shortDateString1, "")); + vigencia2 = this.Emissao; + if (!vigencia2.HasValue) + { + shortDateString2 = ""; + } + else + { + vigencia2 = this.Emissao; + if (vigencia2.HasValue) + { + shortDateString2 = vigencia2.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString2 = null; + } + } + tuples.Add(new Tuple<string, string, string>("EMISSÃO DA APÓLICE", shortDateString2, "")); + Gestor.Model.Domain.Seguros.Controle controle3 = this.Controle; + if (controle3 != null) + { + Seguradora seguradoraAnterior = controle3.SeguradoraAnterior; + if (seguradoraAnterior != null) + { + nome2 = seguradoraAnterior.Nome; + } + else + { + nome2 = null; + } + } + else + { + nome2 = null; + } + tuples.Add(new Tuple<string, string, string>("SEGURADORA ANTERIOR", (string.IsNullOrWhiteSpace(nome2) ? "" : this.Controle.SeguradoraAnterior.Nome.ToUpper()), "")); + tuples.Add(new Tuple<string, string, string>("APÓLICE ANTERIOR", (string.IsNullOrWhiteSpace(this.ApoliceAnterior) ? "" : this.ApoliceAnterior.ToUpper()), "")); + Gestor.Model.Common.FormaPagamento? formaPagamento = this.FormaPagamento; + if (!formaPagamento.HasValue) + { + description2 = ""; + } + else + { + formaPagamento = this.FormaPagamento; + if (formaPagamento.HasValue) + { + description2 = formaPagamento.GetValueOrDefault().GetDescription(); + } + else + { + description2 = null; + } + } + tuples.Add(new Tuple<string, string, string>("FORMA DE PAGAMENTO", description2, "")); + tuples.Add(new Tuple<string, string, string>("PROPOSTA ASSINADA", (this.PropostaAssinada ? "SIM" : "NÃO"), "")); + tuples.Add(new Tuple<string, string, string>("APÓLICE CONFERIDA", (this.ApoliceConferida ? "SIM" : "NÃO"), "")); + tuples.Add(new Tuple<string, string, string>("ADICIONAL DE COMISSÃO", (this.AdicionalComiss ? "SIM" : "NÃO"), "")); + List<Tuple<string, string, string>> tuples1 = tuples; + if (!restricaoComissao) + { + comissao = this.Comissao / new decimal(100); + tuples1.Add(new Tuple<string, string, string>("COMISSÃO", comissao.ToString("P", new CultureInfo("pt-BR", false)), "")); + } + List<Tuple<string, string, string>> tuples2 = tuples1; + List<Tuple<string, string, string>> tuples3 = new List<Tuple<string, string, string>>(); + comissao = this.Comissao / new decimal(100); + tuples3.Add(new Tuple<string, string, string>("COMISSÃO", comissao.ToString("P", new CultureInfo("pt-BR", false)), "")); + comissao = this.PremioLiquido; + tuples3.Add(new Tuple<string, string, string>("PRÊMIO LÍQUIDO", comissao.ToString("C", new CultureInfo("pt-BR", false)), "")); + comissao = this.PremioAdicional; + tuples3.Add(new Tuple<string, string, string>("PRÊMIO ADICIONAL", comissao.ToString("C", new CultureInfo("pt-BR", false)), "")); + comissao = this.Iof; + tuples3.Add(new Tuple<string, string, string>("I.O.F.", comissao.ToString("C", new CultureInfo("pt-BR", false)), "")); + comissao = this.Diferenca; + tuples3.Add(new Tuple<string, string, string>("DIFERENÇA", comissao.ToString("C", new CultureInfo("pt-BR", false)), "")); + comissao = this.PremioTotal; + tuples3.Add(new Tuple<string, string, string>("PRÊMIO TOTAL", comissao.ToString("C", new CultureInfo("pt-BR", false)), "")); + int num = decimal.ToInt32(this.NumeroParcelas); + tuples3.Add(new Tuple<string, string, string>("NÚMERO DE PARCELAS", num.ToString(), "")); + tuples3.Add(new Tuple<string, string, string>("BANCO", (this.Banco == null ? "" : this.Banco.Nome.ToUpper()), "")); + tuples3.Add(new Tuple<string, string, string>("AGÊNCIA", (string.IsNullOrWhiteSpace(this.Agencia) ? "" : this.Agencia.ToUpper()), "")); + tuples3.Add(new Tuple<string, string, string>("CONTA", (string.IsNullOrWhiteSpace(this.Conta) ? "" : this.Conta.ToUpper()), "")); + tuples3.Add(new Tuple<string, string, string>("CARTÃO DE CRÉDITO", (string.IsNullOrWhiteSpace(this.NumeroCartao) ? "" : this.NumeroCartao.ToUpper()), "")); + BandeiraCartao? bandeira = this.Bandeira; + if (!bandeira.HasValue) + { + str2 = ""; + } + else + { + bandeira = this.Bandeira; + if (bandeira.HasValue) + { + str2 = bandeira.GetValueOrDefault().GetDescription(); + } + else + { + str2 = null; + } + } + tuples3.Add(new Tuple<string, string, string>("BANDEIRA", str2, "")); + tuples3.Add(new Tuple<string, string, string>("PROPONENTE", (string.IsNullOrWhiteSpace(this.NomeProponente) ? "" : this.NomeProponente.ToUpper()), "")); + string vencimentoCartao = this.VencimentoCartao; + if (vencimentoCartao != null) + { + str3 = vencimentoCartao.Replace("/", ""); + } + else + { + str3 = null; + } + tuples3.Add(new Tuple<string, string, string>("VENCIMENTO DO CARTÃO", (string.IsNullOrWhiteSpace(str3) ? "" : this.VencimentoCartao.ToUpper()), "")); + tuples3.Add(new Tuple<string, string, string>("PASTA", (string.IsNullOrWhiteSpace(this.Pasta) ? "" : this.Pasta.ToUpper()), "")); + tuples3.Add(new Tuple<string, string, string>("ESTIPULANTE 1", (this.Estipulante1 == null ? "" : this.Estipulante1.Nome.ToUpper()), "")); + tuples3.Add(new Tuple<string, string, string>("ESTIPULANTE 2", (this.Estipulante2 == null ? "" : this.Estipulante2.Nome.ToUpper()), "")); + tuples3.Add(new Tuple<string, string, string>("ESTIPULANTE 3", (this.Estipulante3 == null ? "" : this.Estipulante3.Nome.ToUpper()), "")); + tuples3.Add(new Tuple<string, string, string>("ESTIPULANTE 4", (this.Estipulante4 == null ? "" : this.Estipulante4.Nome.ToUpper()), "")); + tuples3.Add(new Tuple<string, string, string>("ESTIPULANTE 5", (this.Estipulante5 == null ? "" : this.Estipulante5.Nome.ToUpper()), "")); + tuples3.Add(new Tuple<string, string, string>("STATUS", (this.Status == null ? "" : this.Status.Nome.ToUpper()), "")); + vigencia2 = this.DataControle; + if (!vigencia2.HasValue) + { + shortDateString3 = ""; + } + else + { + vigencia2 = this.DataControle; + if (vigencia2.HasValue) + { + shortDateString3 = vigencia2.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString3 = null; + } + } + tuples3.Add(new Tuple<string, string, string>("DATA DE CONTROLE", shortDateString3, "")); + tuples3.Add(new Tuple<string, string, string>("ANOTAÇÕES", (string.IsNullOrWhiteSpace(this.Observacao) ? "" : this.Observacao.ToUpper()), "")); + tuples2.AddRange(tuples3); + return new List<TupleList>() + { + new TupleList() + { + Tuples = new ObservableCollection<Tuple<string, string, string>>(tuples1) + } + }; + } + + private List<KeyValuePair<string, string>> ObrigarValores(bool valores = true) + { + DateTime dateTime; + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (valores) + { + if (this.Comissao <= decimal.Zero) + { + keyValuePairs.AddValue<string, string>("Comissao|COMISSÃO", Messages.Obrigatorio, true); + } + if (this.PremioLiquido == decimal.Zero) + { + keyValuePairs.AddValue<string, string>("PremioLiquido|PRÊMIO LÍQUIDO", Messages.Obrigatorio, true); + } + if (this.PremioTotal == decimal.Zero) + { + keyValuePairs.AddValue<string, string>("PremioTotal|PRÊMIO TOTAL", Messages.Obrigatorio, true); + } + if (this.NumeroParcelas <= decimal.Zero) + { + keyValuePairs.AddValue<string, string>("NumeroParcelas|NÚMERO DE PARCELAS", Messages.Obrigatorio, true); + } + if (!this._vencimentoParcela) + { + if (this.NumeroParcelas > decimal.Zero && this.NumeroParcelas < new decimal(998)) + { + DateTime vigencia1 = this.Vigencia1; + if (this.NumeroParcelas == decimal.One || vigencia1 == DateTime.MinValue) + { + dateTime = vigencia1; + } + else + { + decimal numeroParcelas = this.NumeroParcelas; + dateTime = vigencia1.AddMonths(int.Parse(numeroParcelas.ToString(new CultureInfo("pt-BR"))) - 1); + } + DateTime dateTime1 = dateTime; + DateTime? vigencia2 = this.Vigencia2; + if ((vigencia2.HasValue ? dateTime1 > vigencia2.GetValueOrDefault() : false) && (this.Controle.Ramo == null || this.Controle.Ramo.Id != (long)23)) + { + keyValuePairs.AddValue<string, string>("NumeroParcelas|NÚMERO DE PARCELAS", Messages.VencimentoParcela, true); + } + } + else if (this.NumeroParcelas > new decimal(1000)) + { + keyValuePairs.AddValue<string, string>("NumeroParcelas|NÚMERO DE PARCELAS", "NUMERO DE PARCELAS ESTA NO FORMATO INCORRETO", true); + } + } + } + if (!valores) + { + if (this.PremioLiquido != decimal.Zero) + { + keyValuePairs.AddValue<string, string>("PremioLiquido|PRÊMIO LÍQUIDO", Messages.Invalido, true); + } + if (this.PremioAdicional != decimal.Zero) + { + keyValuePairs.AddValue<string, string>("PremioAdicional|PRÊMIO ADICIONAL", Messages.Invalido, true); + } + if (this.Iof != decimal.Zero) + { + keyValuePairs.AddValue<string, string>("Iof", Messages.Invalido, true); + } + if (this.Diferenca != decimal.Zero) + { + keyValuePairs.AddValue<string, string>("Diferenca|DIFERÊNÇA", Messages.Invalido, true); + } + if (this.PremioTotal != decimal.Zero) + { + keyValuePairs.AddValue<string, string>("PremioTotal|PRÊMIO TOTAL", Messages.Invalido, true); + } + if (this.NumeroParcelas != decimal.Zero) + { + keyValuePairs.AddValue<string, string>("NumeroParcelas|NÚMERO DE PARCELAS", Messages.Invalido, true); + } + } + return keyValuePairs; + } + + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChangedEventHandler propertyChangedEventHandler = this.PropertyChanged; + if (propertyChangedEventHandler == null) + { + return; + } + propertyChangedEventHandler(this, new PropertyChangedEventArgs(propertyName)); + } + + public List<KeyValuePair<string, string>> Validate(bool isEndosso, bool vencimentoParcela) + { + this._isEndosso = isEndosso; + this._vencimentoParcela = vencimentoParcela; + return this.Validate(); + } + + public List<KeyValuePair<string, string>> Validate() + { + Gestor.Model.Common.TipoEndosso? tipoEndosso; + Gestor.Model.Common.TipoEndosso valueOrDefault; + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + keyValuePairs.AddRange(this.Controle.Validate()); + if (!this.NegocioCorretora.HasValue) + { + keyValuePairs.AddValue<string, string>("NegocioCorretora|NEGÓCIO CORRETORA", Messages.Obrigatorio, true); + } + if (string.IsNullOrWhiteSpace(this.Proposta) && !this._isEndosso) + { + keyValuePairs.AddValue<string, string>("Proposta", Messages.Obrigatorio, true); + } + else if (!string.IsNullOrEmpty(this.Proposta) && this.Proposta.Length > 50) + { + keyValuePairs.AddValue<string, string>("Proposta", string.Format(Messages.MaiorQueLimite, 50), true); + } + if (!string.IsNullOrWhiteSpace(this.PropostaEndosso) && this.PropostaEndosso.Length > 50) + { + keyValuePairs.AddValue<string, string>("PropostaEndosso|PROPOSTA DE ENDOSSO", string.Format(Messages.MaiorQueLimite, 50), true); + } + if (!string.IsNullOrWhiteSpace(this.ApoliceAnterior) && this.ApoliceAnterior.Length > 50) + { + keyValuePairs.AddValue<string, string>("ApoliceAnterior|APÓLICE ANTERIOR", string.Format(Messages.MaiorQueLimite, 50), true); + } + if (!string.IsNullOrWhiteSpace(this.Endosso) && this.Endosso.Length > 30) + { + keyValuePairs.AddValue<string, string>("Endosso", string.Format(Messages.MaiorQueLimite, 30), true); + } + if (!string.IsNullOrWhiteSpace(this.Pasta) && this.Pasta.Length > 15) + { + keyValuePairs.AddValue<string, string>("Pasta", string.Format(Messages.MaiorQueLimite, 15), true); + } + if (!string.IsNullOrWhiteSpace(this.Agencia) && this.Agencia.Length > 10) + { + keyValuePairs.AddValue<string, string>("Agencia|AGÊNCIA", string.Format(Messages.MaiorQueLimite, 10), true); + } + if (!string.IsNullOrWhiteSpace(this.Conta) && this.Conta.Length > 15) + { + keyValuePairs.AddValue<string, string>("Conta", string.Format(Messages.MaiorQueLimite, 15), true); + } + if (!string.IsNullOrWhiteSpace(this.NumeroCartao) && this.NumeroCartao.Length > 20) + { + keyValuePairs.AddValue<string, string>("NumeroCartao|NÚMERO DO CARTÃO", string.Format(Messages.MaiorQueLimite, 20), true); + } + if (!string.IsNullOrWhiteSpace(this.VencimentoCartao) && this.VencimentoCartao.Length > 5) + { + keyValuePairs.AddValue<string, string>("VencimentoCartao|VENCIMENTO DO CARTÃO", string.Format(Messages.MaiorQueLimite, 5), true); + } + if (!string.IsNullOrWhiteSpace(this.NomeProponente) && this.NomeProponente.Length > 100) + { + keyValuePairs.AddValue<string, string>("NomeProponente|PROPONENTE", string.Format(Messages.MaiorQueLimite, 100), true); + } + DateTime? emissao = this.Emissao; + if (emissao.HasValue) + { + emissao = this.Emissao; + if (DateTime.Compare(emissao.Value, new DateTime(1753, 1, 1)) >= 0) + { + emissao = this.Emissao; + if (DateTime.Compare(emissao.Value, new DateTime(9999, 12, 31)) <= 0) + { + goto Label0; + } + } + keyValuePairs.AddValue<string, string>(string.Concat("Emissao|", (this._isEndosso ? "EMISSÃO DO ENDOSSO" : "EMISSÃO DA APÓLICE")), string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + Label0: + emissao = this.Remessa; + if (emissao.HasValue) + { + emissao = this.Remessa; + if (DateTime.Compare(emissao.Value, new DateTime(1753, 1, 1)) >= 0) + { + emissao = this.Remessa; + if (DateTime.Compare(emissao.Value, new DateTime(9999, 12, 31)) <= 0) + { + goto Label1; + } + } + keyValuePairs.AddValue<string, string>(string.Concat("Remessa|", (this._isEndosso ? "TRANSMISSÃO DA PROPOSTA DE ENDOSSO" : "TRANSMISSÃO DA PROPOSTA")), string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + Label1: + DateTime vigencia1 = this.Vigencia1; + if (DateTime.Compare(this.Vigencia1, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.Vigencia1, new DateTime(9999, 12, 31)) > 0) + { + keyValuePairs.AddValue<string, string>("Vigencia1|VIGÊNCIA INICIAL", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + emissao = this.Vigencia2; + if (emissao.HasValue) + { + emissao = this.Vigencia2; + if (DateTime.Compare(emissao.Value, new DateTime(1753, 1, 1)) >= 0) + { + emissao = this.Vigencia2; + if (DateTime.Compare(emissao.Value, new DateTime(9999, 12, 31)) <= 0) + { + goto Label2; + } + } + keyValuePairs.AddValue<string, string>("Vigencia2|VIGÊNCIA FINAL", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + Label2: + DateTime dateTime = this.Vigencia1; + emissao = this.Vigencia2; + if (emissao.HasValue) + { + DateTime vigencia11 = this.Vigencia1; + emissao = this.Vigencia2; + if ((emissao.HasValue ? vigencia11 > emissao.GetValueOrDefault() : false)) + { + keyValuePairs.AddValue<string, string>("Vigencia2|VIGÊNCIA FINAL", "A DATA DE VIGÊNCIA FINAL NÃO PODE SER ANTERIOR A DATA DE VIGÊNCIA INCIAL", true); + } + } + if (this.Tipo == 0) + { + if (string.IsNullOrWhiteSpace(this.Apolice)) + { + emissao = this.Emissao; + if (emissao.HasValue) + { + keyValuePairs.AddValue<string, string>("Apolice|APÓLICE", Messages.Obrigatorio, true); + } + } + if (!string.IsNullOrWhiteSpace(this.Apolice)) + { + emissao = this.Emissao; + if (!emissao.HasValue) + { + keyValuePairs.AddValue<string, string>(string.Concat("Emissao|", (this._isEndosso ? "EMISSÃO DO ENDOSSO" : "EMISSÃO DA APÓLICE")), Messages.Obrigatorio, true); + } + } + if (!string.IsNullOrWhiteSpace(this.Apolice) && this.Apolice.Length > 50) + { + keyValuePairs.AddValue<string, string>("Apolice|APÓLICE", string.Format(Messages.MaiorQueLimite, 50), true); + } + } + if (this.Tipo > 0) + { + if (string.IsNullOrWhiteSpace(this.PropostaEndosso)) + { + keyValuePairs.AddValue<string, string>("PropostaEndosso|PROPOSTA DE ENDOSSO", Messages.Obrigatorio, true); + } + else if (this.PropostaEndosso.Length > 30) + { + keyValuePairs.AddValue<string, string>("PropostaEndosso|PROPOSTA DE ENDOSSO", string.Format(Messages.MaiorQueLimite, 30), true); + } + if (!string.IsNullOrWhiteSpace(this.Endosso)) + { + if (this.Endosso.Length > 30) + { + keyValuePairs.AddValue<string, string>("Endosso", string.Format(Messages.MaiorQueLimite, 30), true); + } + emissao = this.Emissao; + if (!emissao.HasValue && this.Tipo > 0) + { + keyValuePairs.AddValue<string, string>(string.Concat("Emissao|", (this._isEndosso ? "EMISSÃO DO ENDOSSO" : "EMISSÃO DA APÓLICE")), Messages.Obrigatorio, true); + } + } + else + { + emissao = this.Emissao; + if (emissao.HasValue) + { + keyValuePairs.AddValue<string, string>("Endosso", Messages.Obrigatorio, true); + } + } + } + if (this.Tipo > 0) + { + tipoEndosso = this.TipoEndosso; + if (!tipoEndosso.HasValue) + { + keyValuePairs.AddValue<string, string>("TipoEndosso|TIPO DE ENDOSSO", Messages.Obrigatorio, true); + } + } + if (this.TipoRecebimento.GetValueOrDefault() == Gestor.Model.Common.TipoRecebimento.Parcela) + { + emissao = this.Vigencia2; + if (!emissao.HasValue) + { + keyValuePairs.AddValue<string, string>("Vigencia2|VIGÊNCIA FINAL", Messages.Obrigatorio, true); + } + } + if (this.TipoRecebimento.GetValueOrDefault() == Gestor.Model.Common.TipoRecebimento.Parcela && this.Tipo == 0) + { + keyValuePairs.AddRange(this.ObrigarValores(true)); + } + if (this.TipoRecebimento.GetValueOrDefault() == Gestor.Model.Common.TipoRecebimento.Fatura && this.Tipo == 0) + { + keyValuePairs.AddRange(this.ObrigarValores(false)); + } + tipoEndosso = this.TipoEndosso; + if (tipoEndosso.GetValueOrDefault() == Gestor.Model.Common.TipoEndosso.Cancelamento && (this.PremioLiquido != decimal.Zero || this.Comissao != decimal.Zero) && this.NumeroParcelas == decimal.Zero) + { + keyValuePairs.AddValue<string, string>("NumeroParcelas|NÚMERO DE PARCELAS", Messages.Obrigatorio, true); + } + tipoEndosso = this.TipoEndosso; + if (tipoEndosso.GetValueOrDefault() == Gestor.Model.Common.TipoEndosso.Cancelamento && (this.PremioLiquido != new decimal(0, 0, 0, false, 1) || this.NumeroParcelas != decimal.Zero)) + { + if (this.Comissao == decimal.Zero) + { + keyValuePairs.AddValue<string, string>("Comissao|COMISSÃO", Messages.Obrigatorio, true); + } + if (this.NumeroParcelas == decimal.Zero) + { + keyValuePairs.AddValue<string, string>("NumeroParcelas|NÚMERO DE PARCELAS", Messages.Obrigatorio, true); + } + if (this.PremioLiquido == decimal.Zero) + { + keyValuePairs.AddValue<string, string>("PremioLiquido|PRÊMIO LÍQUID", Messages.Obrigatorio, true); + } + } + long num = 10000000000L; + if (this.PremioTotal > num) + { + keyValuePairs.AddValue<string, string>("PremioTotal|PRÊMIO TOTAL", Messages.Invalido, true); + } + if (this.PremioLiquido > num) + { + keyValuePairs.AddValue<string, string>("PremioLiquido|PRÊMIO LÍQUIDO", Messages.Invalido, true); + } + if (this.NumeroParcelas > new decimal(1000)) + { + keyValuePairs.AddValue<string, string>("NumeroParcelas|NÚMERO DE PARCELAS", "NUMERO DE PARCELAS ESTA NO FORMATO INCORRETO", true); + } + if (this.Tipo > 0) + { + tipoEndosso = this.TipoEndosso; + if (tipoEndosso.HasValue) + { + valueOrDefault = tipoEndosso.GetValueOrDefault(); + if (valueOrDefault != Gestor.Model.Common.TipoEndosso.ComMovimento) + { + goto Label4; + } + keyValuePairs.AddRange(this.ObrigarValores(true)); + return keyValuePairs; + } + Label5: + if (this.PremioTotal == decimal.Zero && this.Comissao == decimal.Zero) + { + return keyValuePairs; + } + keyValuePairs.AddRange(this.ObrigarValores(true)); + } + return keyValuePairs; + Label4: + if ((int)valueOrDefault - (int)Gestor.Model.Common.TipoEndosso.SemMovimento <= (int)Gestor.Model.Common.TipoEndosso.SemMovimento) + { + return keyValuePairs; + } + else + { + goto Label5; + } + } + + public List<KeyValuePair<string, string>> ValidateEndossar() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (string.IsNullOrWhiteSpace(this.Proposta)) + { + keyValuePairs.AddValue<string, string>("Proposta", Messages.Obrigatorio, true); + } + if (this.Emissao.HasValue && (DateTime.Compare(this.Emissao.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.Emissao.Value, new DateTime(9999, 12, 31)) > 0)) + { + keyValuePairs.AddValue<string, string>("Emissao|EMISSÃO DA APÓLICE", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + if (this.Remessa.HasValue && (DateTime.Compare(this.Remessa.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.Remessa.Value, new DateTime(9999, 12, 31)) > 0)) + { + keyValuePairs.AddValue<string, string>("Remessa|TRANSMISSÃO DA PROPOSTA", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + if (string.IsNullOrWhiteSpace(this.Apolice) && this.Emissao.HasValue) + { + keyValuePairs.AddValue<string, string>("Apolice|APÓLICE", Messages.Obrigatorio, true); + } + if (!string.IsNullOrWhiteSpace(this.Apolice) && !this.Emissao.HasValue) + { + keyValuePairs.AddValue<string, string>(string.Concat("Emissao|", (this._isEndosso ? "EMISSÃO DO ENDOSSO" : "EMISSÃO DA APÓLICE")), Messages.Obrigatorio, true); + } + if (string.IsNullOrWhiteSpace(this.Apolice) && !this.Emissao.HasValue) + { + keyValuePairs.AddValue<string, string>("Apolice|EMISSÃO DA APÓLICE", "NÃO É POSSÍVEL ENDOSSAR UM DOCUMENTO SEM EMISSÃO DE APÓLICE", true); + } + return keyValuePairs; + } + + public event PropertyChangedEventHandler PropertyChanged; + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/Estipulante.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/Estipulante.cs new file mode 100644 index 0000000..76976ea --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/Estipulante.cs @@ -0,0 +1,373 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Gestor.Model.Validation; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Gestor.Model.Domain.Seguros +{ + public class Estipulante : EnderecoBase, IDomain, INotifyPropertyChanged + { + private bool _selecionado; + + private string _nome; + + private string _documento; + + private string _primeiroPrefixo; + + private string _primeiroTelefone; + + private string _segundoPrefixo; + + private string _segundoTelefone; + + private string _email; + + private string _observacao; + + [Log(true)] + public bool Ativo + { + get; + set; + } + + [Log(true)] + public string Documento + { + get + { + string str = this._documento; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._documento = value; + } + } + + [Log(true)] + public string Email + { + get + { + string str = this._email; + if (str == null) + { + return null; + } + return str.ToLower().Trim(); + } + set + { + this._email = value; + } + } + + public long IdEmpresa + { + get; + set; + } + + [Log(true)] + [Name(true)] + public string Nome + { + get + { + string str = this._nome; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._nome = value; + } + } + + [Log(true)] + public string Observacao + { + get + { + string str = this._observacao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._observacao = value; + } + } + + [Description("PREFIXO")] + [Log(true)] + public string PrimeiroPrefixo + { + get + { + string str = this._primeiroPrefixo; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._primeiroPrefixo = value; + } + } + + [Description("TELEFONE")] + [Log(true)] + public string PrimeiroTelefone + { + get + { + string str = this._primeiroTelefone; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._primeiroTelefone = value; + } + } + + [Description("TIPO TELEFONE")] + [Log(true)] + public TipoTelefone? PrimeiroTipo + { + get; + set; + } + + [Description("PREFIXO")] + [Log(true)] + public string SegundoPrefixo + { + get + { + string str = this._segundoPrefixo; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._segundoPrefixo = value; + } + } + + [Description("TELEFONE")] + [Log(true)] + public string SegundoTelefone + { + get + { + string str = this._segundoTelefone; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._segundoTelefone = value; + } + } + + [Description("TIPO TELEFONE")] + [Log(true)] + public TipoTelefone? SegundoTipo + { + get; + set; + } + + public bool Selecionado + { + get + { + return this._selecionado; + } + set + { + if (value == this._selecionado) + { + return; + } + this._selecionado = value; + this.OnPropertyChanged("Selecionado"); + } + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Estipulante estipulante = this; + return new Func<List<KeyValuePair<string, string>>>(estipulante.Validate); + } + } + + public Estipulante() + { + } + + public List<TupleList> Log() + { + string description; + string str; + List<TupleList> tupleLists = new List<TupleList>(); + TupleList tupleList = new TupleList(); + ObservableCollection<Tuple<string, string, string>> observableCollection = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("NOME", (string.IsNullOrWhiteSpace(this.Nome) ? "" : this.Nome), ""), + new Tuple<string, string, string>("CPF", (string.IsNullOrWhiteSpace(this.Documento) ? "" : this.Documento), ""), + new Tuple<string, string, string>("ATIVO", (this.Ativo ? "SIM" : "NÃO"), "") + }; + TipoTelefone? primeiroTipo = this.PrimeiroTipo; + if (!primeiroTipo.HasValue) + { + description = ""; + } + else + { + primeiroTipo = this.PrimeiroTipo; + if (primeiroTipo.HasValue) + { + description = primeiroTipo.GetValueOrDefault().GetDescription(); + } + else + { + description = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("PRIMEIRO TIPO", description, "")); + observableCollection.Add(new Tuple<string, string, string>("PRIMEIRO PREFIXO", (string.IsNullOrWhiteSpace(this.PrimeiroPrefixo) ? "" : this.PrimeiroPrefixo), "")); + observableCollection.Add(new Tuple<string, string, string>("PRIMEIRO TELEFONE", (string.IsNullOrWhiteSpace(this.PrimeiroTelefone) ? "" : this.PrimeiroTelefone), "")); + primeiroTipo = this.SegundoTipo; + if (!primeiroTipo.HasValue) + { + str = ""; + } + else + { + primeiroTipo = this.SegundoTipo; + if (primeiroTipo.HasValue) + { + str = primeiroTipo.GetValueOrDefault().GetDescription(); + } + else + { + str = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("SEGUNDO TIPO", str, "")); + observableCollection.Add(new Tuple<string, string, string>("SEGUNDO PREFIXO", (string.IsNullOrWhiteSpace(this.SegundoPrefixo) ? "" : this.SegundoPrefixo), "")); + observableCollection.Add(new Tuple<string, string, string>("SEGUNDO TELEFONE", (string.IsNullOrWhiteSpace(this.SegundoTelefone) ? "" : this.SegundoTelefone), "")); + observableCollection.Add(new Tuple<string, string, string>("E-MAIL", (string.IsNullOrWhiteSpace(this.Email) ? "" : this.Email), "")); + observableCollection.Add(new Tuple<string, string, string>("CEP", (string.IsNullOrWhiteSpace(base.Cep) ? "" : base.Cep), "")); + observableCollection.Add(new Tuple<string, string, string>("ENDEREÇO", (string.IsNullOrWhiteSpace(base.Endereco) ? "" : base.Endereco), "")); + observableCollection.Add(new Tuple<string, string, string>("NÚMERO", (string.IsNullOrWhiteSpace(base.Numero) ? "" : base.Numero), "")); + observableCollection.Add(new Tuple<string, string, string>("COMPLEMENTO", (string.IsNullOrWhiteSpace(base.Complemento) ? "" : base.Complemento), "")); + observableCollection.Add(new Tuple<string, string, string>("BAIRRO", (string.IsNullOrWhiteSpace(base.Bairro) ? "" : base.Bairro), "")); + observableCollection.Add(new Tuple<string, string, string>("CIDADE", (string.IsNullOrWhiteSpace(base.Cidade) ? "" : base.Cidade), "")); + observableCollection.Add(new Tuple<string, string, string>("ESTADO", (string.IsNullOrWhiteSpace(base.Estado) ? "" : base.Estado), "")); + tupleList.Tuples = observableCollection; + tupleLists.Add(tupleList); + return tupleLists; + } + + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChangedEventHandler propertyChangedEventHandler = this.PropertyChanged; + if (propertyChangedEventHandler == null) + { + return; + } + propertyChangedEventHandler(this, new PropertyChangedEventArgs(propertyName)); + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (string.IsNullOrEmpty(this.Nome)) + { + keyValuePairs.AddValue<string, string>("Nome", Messages.Obrigatorio, true); + } + else if (this.Nome.Length > 100) + { + keyValuePairs.AddValue<string, string>("Nome", string.Format(Messages.MaiorQueLimite, 100), true); + } + if (!string.IsNullOrEmpty(this.Documento) && !this.Documento.ValidacaoDocumento()) + { + keyValuePairs.AddValue<string, string>("Documento", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.PrimeiroPrefixo) && !this.PrimeiroPrefixo.ValidacaoPrefixo()) + { + keyValuePairs.AddValue<string, string>("PrimeiroPrefixo|PRIMEIRO DDD", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.PrimeiroTelefone) && !this.PrimeiroTelefone.ValidacaoTelefone()) + { + keyValuePairs.AddValue<string, string>("PrimeiroTelefone|PRIMEIRO TELEFONE", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.SegundoPrefixo) && !this.SegundoPrefixo.ValidacaoPrefixo()) + { + keyValuePairs.AddValue<string, string>("SegundoPrefixo|SEGUNDO DDD", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.SegundoTelefone) && !this.SegundoTelefone.ValidacaoTelefone()) + { + keyValuePairs.AddValue<string, string>("SegundoTelefone|SEGUNDO TELEFONE", Messages.Invalido, true); + } + if (!string.IsNullOrEmpty(this.Email) && this.Email.Length > 100) + { + keyValuePairs.AddValue<string, string>("Email|E-MAIL", string.Format(Messages.MaiorQueLimite, 100), true); + } + if (!string.IsNullOrEmpty(this.Email) && !this.Email.ValidacaoEmail()) + { + keyValuePairs.AddValue<string, string>("Email|E-MAIL", Messages.Invalido, true); + } + if (!string.IsNullOrEmpty(base.Cep) && !base.Cep.ValidacaoCep()) + { + keyValuePairs.AddValue<string, string>("Cep|CEP", Messages.Invalido, true); + } + if (!string.IsNullOrEmpty(base.Estado) && !base.Estado.ValidacaoEstado()) + { + keyValuePairs.AddValue<string, string>("Estado|ESTADO", Messages.Invalido, true); + } + return keyValuePairs; + } + + public event PropertyChangedEventHandler PropertyChanged; + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/Expedicao.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/Expedicao.cs new file mode 100644 index 0000000..5dbd8f3 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/Expedicao.cs @@ -0,0 +1,94 @@ +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class Expedicao : DomainBase + { + public Gestor.Model.Domain.Seguros.Documento Apolice + { + get; + set; + } + + public DateTime? DataAlteracao + { + get; + set; + } + + public DateTime? DataCriacao + { + get; + set; + } + + public DateTime? DataEnvio + { + get; + set; + } + + public DateTime? DataRecebimento + { + get; + set; + } + + public string Destino + { + get; + set; + } + + public string Documento + { + get; + set; + } + + public string Responsavel + { + get; + set; + } + + public long? UsuarioAlteracao + { + get; + set; + } + + public long? UsuarioCriacao + { + get; + set; + } + + public Expedicao() + { + } + + public List<TupleList> Log() + { + List<TupleList> tupleLists = new List<TupleList>(); + TupleList tupleList = new TupleList(); + ObservableCollection<Tuple<string, string, string>> observableCollection = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("DOCUMENTO", this.Documento, ""), + new Tuple<string, string, string>("DESTINO", this.Destino, "") + }; + DateTime? dataEnvio = this.DataEnvio; + observableCollection.Add(new Tuple<string, string, string>("DATA ENVIO", dataEnvio.ToString(), "")); + dataEnvio = this.DataRecebimento; + observableCollection.Add(new Tuple<string, string, string>("DATA RECEBIMENTO", dataEnvio.ToString(), "")); + observableCollection.Add(new Tuple<string, string, string>("RESPONSÁVEL", this.Responsavel, "")); + tupleList.Tuples = observableCollection; + tupleLists.Add(tupleList); + return tupleLists; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/Extrato.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/Extrato.cs new file mode 100644 index 0000000..fcf3ccd --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/Extrato.cs @@ -0,0 +1,177 @@ +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class Extrato : DomainBase, IDomain + { + private string _numero; + + private string _historico; + + private string _observacao; + + public decimal? Bruto + { + get; + set; + } + + public bool Completo + { + get; + set; + } + + public DateTime? Data + { + get; + set; + } + + public DateTime? DataCredito + { + get; + set; + } + + public string Historico + { + get + { + string str = this._historico; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._historico = value; + } + } + + public long IdEmpresa + { + get; + set; + } + + public virtual long IdUsuario + { + get; + set; + } + + public decimal? Ir + { + get; + set; + } + + public decimal? Iss + { + get; + set; + } + + public decimal? Liquido + { + get; + set; + } + + public string Numero + { + get + { + string str = this._numero; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._numero = value; + } + } + + public string Observacao + { + get + { + string str = this._observacao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._observacao = value; + } + } + + public decimal? Outro + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Seguradora Seguradora + { + get; + set; + } + + public bool Selecionado + { + get; + set; + } + + public StatusExtrato Status + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Extrato extrato = this; + return new Func<List<KeyValuePair<string, string>>>(extrato.Validate); + } + } + + public Extrato() + { + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (!string.IsNullOrWhiteSpace(this.Numero) && this.Numero.Length > 50) + { + keyValuePairs.AddValue<string, string>("Numero", string.Format(Messages.MaiorQueLimite, 50), true); + } + if (this.Data.HasValue && (DateTime.Compare(this.Data.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.Data.Value, new DateTime(9999, 12, 31)) > 0)) + { + keyValuePairs.AddValue<string, string>("Data", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/Fabricante.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/Fabricante.cs new file mode 100644 index 0000000..b20207d --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/Fabricante.cs @@ -0,0 +1,62 @@ +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class Fabricante : IDomain + { + private string _descricao; + + public string Descricao + { + get + { + string str = this._descricao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._descricao = value; + } + } + + public int Id + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Fabricante fabricante = this; + return new Func<List<KeyValuePair<string, string>>>(fabricante.Validate); + } + } + + public Fabricante() + { + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (!string.IsNullOrWhiteSpace(this.Descricao) && this.Descricao.Length > 150) + { + keyValuePairs.AddValue<string, string>("Descricao", string.Format(Messages.MaiorQueLimite, 150), true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/Granizo.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/Granizo.cs new file mode 100644 index 0000000..8f6036c --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/Granizo.cs @@ -0,0 +1,247 @@ +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Globalization; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class Granizo : EnderecoBase, IDomain + { + private string _cultura; + + private string _sitio; + + private string _observacao; + + public string Area + { + get; + set; + } + + public string Cultura + { + get + { + string str = this._cultura; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._cultura = value; + } + } + + public Gestor.Model.Domain.Seguros.Item Item + { + get; + set; + } + + public string Observacao + { + get + { + string str = this._observacao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._observacao = value; + } + } + + public string Sitio + { + get + { + string str = this._sitio; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._sitio = value; + } + } + + public decimal? SubsidioEstadual + { + get; + set; + } + + public decimal? SubsidioFederal + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Granizo granizo = this; + return new Func<List<KeyValuePair<string, string>>>(granizo.Validate); + } + } + + public Granizo() + { + } + + public static List<TupleList> Log(Gestor.Model.Domain.Seguros.Item item) + { + decimal valueOrDefault; + string str; + string str1; + List<TupleList> tupleLists = new List<TupleList>(); + TupleList tupleList = new TupleList(); + ObservableCollection<Tuple<string, string, string>> observableCollection = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("CEP", (string.IsNullOrWhiteSpace(item.Granizo.Cep) ? "" : item.Granizo.Cep), ""), + new Tuple<string, string, string>("ENDEREÇO", (string.IsNullOrWhiteSpace(item.Granizo.Endereco) ? "" : item.Granizo.Endereco.ToUpper()), ""), + new Tuple<string, string, string>("NÚMERO", (string.IsNullOrWhiteSpace(item.Granizo.Numero) ? "" : item.Granizo.Numero), ""), + new Tuple<string, string, string>("COMPLEMENTO", (string.IsNullOrWhiteSpace(item.Granizo.Complemento) ? "" : item.Granizo.Complemento.ToUpper()), ""), + new Tuple<string, string, string>("BAIRRO", (string.IsNullOrWhiteSpace(item.Granizo.Bairro) ? "" : item.Granizo.Bairro.ToUpper()), ""), + new Tuple<string, string, string>("CIDADE", (string.IsNullOrWhiteSpace(item.Granizo.Cidade) ? "" : item.Granizo.Cidade.ToUpper()), ""), + new Tuple<string, string, string>("ESTADO", (string.IsNullOrWhiteSpace(item.Granizo.Estado) ? "" : item.Granizo.Estado.ToUpper()), ""), + new Tuple<string, string, string>("CULTURA", (string.IsNullOrWhiteSpace(item.Granizo.Cultura) ? "" : item.Granizo.Cultura.ToUpper()), ""), + new Tuple<string, string, string>("SÍTIO", (string.IsNullOrWhiteSpace(item.Granizo.Sitio) ? "" : item.Granizo.Sitio.ToUpper()), "") + }; + decimal? subsidioFederal = item.Granizo.SubsidioFederal; + if (!subsidioFederal.HasValue) + { + str = ""; + } + else + { + subsidioFederal = item.Granizo.SubsidioFederal; + if (subsidioFederal.HasValue) + { + valueOrDefault = subsidioFederal.GetValueOrDefault(); + str = valueOrDefault.ToString("C", new CultureInfo("pt-BR", false)); + } + else + { + str = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("SUBSÍDIO FEDERAL", str, "")); + subsidioFederal = item.Granizo.SubsidioEstadual; + if (!subsidioFederal.HasValue) + { + str1 = ""; + } + else + { + subsidioFederal = item.Granizo.SubsidioEstadual; + if (subsidioFederal.HasValue) + { + valueOrDefault = subsidioFederal.GetValueOrDefault(); + str1 = valueOrDefault.ToString("C", new CultureInfo("pt-BR", false)); + } + else + { + str1 = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("SUBSÍDIO ESTADUAL", str1, "")); + observableCollection.Add(new Tuple<string, string, string>("OBSERVAÇÕES", (string.IsNullOrWhiteSpace(item.Granizo.Observacao) ? "" : item.Granizo.Observacao.ToUpper()), "")); + tupleList.Tuples = observableCollection; + tupleLists.Add(tupleList); + List<TupleList> tupleLists1 = tupleLists; + ObservableCollection<Tuple<string, string, string>> observableCollection1 = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("COBERTURAS$", "", "") + }; + foreach (Cobertura cobertura in item.Coberturas) + { + observableCollection1.Add(new Tuple<string, string, string>(string.Format(" COBERTURA {0}$", item.Coberturas.IndexOf(cobertura) + 1), "", "")); + observableCollection1.Add(new Tuple<string, string, string>(" OBSERVAÇÃO", (string.IsNullOrWhiteSpace(cobertura.Observacao) ? "" : cobertura.Observacao.ToUpper()), "")); + valueOrDefault = cobertura.Premio; + observableCollection1.Add(new Tuple<string, string, string>(" PRÊMIO", valueOrDefault.ToString("C", new CultureInfo("pt-BR", false)), "")); + valueOrDefault = cobertura.Franquia; + observableCollection1.Add(new Tuple<string, string, string>(" FRANQUIA", valueOrDefault.ToString("C", new CultureInfo("pt-BR", false)), "")); + valueOrDefault = cobertura.Lmi; + observableCollection1.Add(new Tuple<string, string, string>(" L.M.I.", valueOrDefault.ToString("C", new CultureInfo("pt-BR", false)), "")); + } + tupleLists1.Add(new TupleList() + { + Tuples = observableCollection1 + }); + return tupleLists1; + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (string.IsNullOrWhiteSpace(base.Cep)) + { + keyValuePairs.AddValue<string, string>("Cep", Messages.Obrigatorio, true); + } + else if (!base.Cep.ValidacaoCep()) + { + keyValuePairs.AddValue<string, string>("Cep", Messages.Invalido, true); + } + if (string.IsNullOrWhiteSpace(this.Cultura)) + { + keyValuePairs.AddValue<string, string>("Cultura", Messages.Obrigatorio, true); + } + if (!string.IsNullOrWhiteSpace(this.Cultura) && this.Cultura.Length > 60) + { + keyValuePairs.AddValue<string, string>("Cultura", string.Format(Messages.MaiorQueLimite, 60), true); + } + if (string.IsNullOrWhiteSpace(this.Sitio)) + { + keyValuePairs.AddValue<string, string>("Sitio", Messages.Obrigatorio, true); + } + if (!string.IsNullOrWhiteSpace(this.Sitio) && this.Sitio.Length > 100) + { + keyValuePairs.AddValue<string, string>("Sitio", string.Format(Messages.MaiorQueLimite, 100), true); + } + if (string.IsNullOrWhiteSpace(base.Endereco)) + { + keyValuePairs.AddValue<string, string>("Endereco", Messages.Obrigatorio, true); + } + if (string.IsNullOrWhiteSpace(base.Numero)) + { + keyValuePairs.AddValue<string, string>("Numero", Messages.Obrigatorio, true); + } + if (string.IsNullOrWhiteSpace(base.Bairro)) + { + keyValuePairs.AddValue<string, string>("Bairro", Messages.Obrigatorio, true); + } + if (string.IsNullOrWhiteSpace(base.Cidade)) + { + keyValuePairs.AddValue<string, string>("Cidade", Messages.Obrigatorio, true); + } + if (string.IsNullOrWhiteSpace(base.Estado)) + { + keyValuePairs.AddValue<string, string>("Estado", Messages.Obrigatorio, true); + } + else if (!base.Estado.ValidacaoEstado()) + { + keyValuePairs.AddValue<string, string>("Estado", Messages.Invalido, true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/Item.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/Item.cs new file mode 100644 index 0000000..7adcea9 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/Item.cs @@ -0,0 +1,505 @@ +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Gestor.Model.Domain.Seguros +{ + public class Item : DomainBase, IDomain, INotifyPropertyChanged + { + private bool _selecionado; + + private string _descricao; + + private string _status; + + private string _statusInclusao; + + private string _observacao; + + private string _valorCredito; + + private bool _config = true; + + private bool _fabricanteBranco; + + public Gestor.Model.Domain.Seguros.Aeronautico Aeronautico + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Auto Auto + { + get; + set; + } + + public bool Cancelado + { + get; + set; + } + + public IList<Cobertura> Coberturas + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Consorcio Consorcio + { + get; + set; + } + + public string Descricao + { + get + { + string str = this._descricao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._descricao = value; + } + } + + public Gestor.Model.Domain.Seguros.Documento Documento + { + get; + set; + } + + public long? Endosso + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Granizo Granizo + { + get; + set; + } + + public long? IdDocumentoCancelado + { + get; + set; + } + + public string Observacao + { + get + { + string str = this._observacao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._observacao = value; + } + } + + public int? Ordem + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Patrimonial Patrimonial + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.RiscosDiversos RiscosDiversos + { + get; + set; + } + + public bool Selecionado + { + get + { + return this._selecionado; + } + set + { + if (value == this._selecionado) + { + return; + } + this._selecionado = value; + this.OnPropertyChanged("Selecionado"); + } + } + + public bool Sinistrado + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Sinistro Sinistro + { + get; + set; + } + + public IList<ControleSinistro> Sinistros + { + get; + set; + } + + public string Status + { + get + { + string str = this._status; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._status = value; + } + } + + public string StatusInclusao + { + get + { + string str = this._statusInclusao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._statusInclusao = value; + } + } + + public long? Substituicao + { + get; + set; + } + + public long? Substituido + { + get; + set; + } + + public Gestor.Model.Common.TipoEndosso? TipoEndosso + { + get; + set; + } + + public IList<TitularesVida> Titulares + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Item item = this; + return new Func<List<KeyValuePair<string, string>>>(item.Validate); + } + } + + public Gestor.Model.Domain.Seguros.Vida Vida + { + get; + set; + } + + public Item() + { + } + + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChangedEventHandler propertyChangedEventHandler = this.PropertyChanged; + if (propertyChangedEventHandler == null) + { + return; + } + propertyChangedEventHandler(this, new PropertyChangedEventArgs(propertyName)); + } + + public List<KeyValuePair<string, string>> Validate(bool config, bool fabricanteBranco = false) + { + this._config = config; + this._fabricanteBranco = fabricanteBranco; + return this.Validate(); + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + int? ordem = this.Ordem; + if (ordem.HasValue) + { + ordem = this.Ordem; + if (!(ordem.GetValueOrDefault() == 0 & ordem.HasValue)) + { + goto Label0; + } + } + keyValuePairs.AddValue<string, string>("Ordem", Messages.Invalido, true); + if (string.IsNullOrWhiteSpace(this.Descricao)) + { + keyValuePairs.AddValue<string, string>("Descricao", Messages.Obrigatorio, true); + } + else if (this.Descricao.Length > 250) + { + keyValuePairs.AddValue<string, string>("Descricao", string.Format(Messages.MaiorQueLimite, 250), true); + } + if (this.Documento == null) + { + return keyValuePairs; + } + long id = this.Documento.Controle.Ramo.Id; + if (id > (long)38) + { + if (id == (long)47 || id == (long)53 || id == (long)66) + { + goto Label1; + } + goto Label2; + } + else + { + long num = id - (long)1; + if (num <= (long)19) + { + switch ((uint)num) + { + case 0: + case 1: + case 2: + case 14: + case 17: + { + goto Label4; + } + case 3: + case 7: + case 10: + case 11: + case 13: + case 15: + case 16: + case 18: + { + goto Label2; + } + case 4: + { + goto Label5; + } + case 5: + case 6: + case 8: + case 9: + { + goto Label1; + } + case 12: + { + if (this.Aeronautico != null) + { + keyValuePairs.AddRange(this.Aeronautico.Validate()); + return keyValuePairs; + } + else + { + keyValuePairs.AddValue<string, string>("Aeronautico", Messages.Obrigatorio, true); + return keyValuePairs; + } + } + case 19: + { + if (this.Granizo != null) + { + keyValuePairs.AddRange(this.Granizo.Validate()); + return keyValuePairs; + } + else + { + keyValuePairs.AddValue<string, string>("Granizo", Messages.Obrigatorio, true); + return keyValuePairs; + } + } + } + } + else + { + } + long num1 = id - (long)30; + if (num1 <= (long)8) + { + switch ((uint)num1) + { + case 0: + { + break; + } + case 1: + { + if (this.RiscosDiversos != null) + { + keyValuePairs.AddRange(this.RiscosDiversos.Validate()); + } + else + { + keyValuePairs.AddValue<string, string>("RiscosDiversos", Messages.Obrigatorio, true); + } + if (this.Titulares == null || this.Titulares.Count <= 0) + { + return keyValuePairs; + } + using (IEnumerator<TitularesVida> enumerator = this.Titulares.GetEnumerator()) + { + while (enumerator.MoveNext()) + { + keyValuePairs.AddRange(enumerator.Current.Validate()); + } + return keyValuePairs; + } + break; + } + case 6: + { + if (this.Consorcio != null) + { + keyValuePairs.AddRange(this.Consorcio.Validate()); + return keyValuePairs; + } + else + { + keyValuePairs.AddValue<string, string>("Consorcio", Messages.Obrigatorio, true); + return keyValuePairs; + } + } + case 7: + { + goto Label5; + } + case 8: + { + if (this.Patrimonial != null) + { + keyValuePairs.AddRange(this.Patrimonial.ValidateGarantia()); + return keyValuePairs; + } + else + { + keyValuePairs.AddValue<string, string>("Patrimonial", Messages.Obrigatorio, true); + return keyValuePairs; + } + } + default: + { + goto Label2; + } + } + } + else + { + goto Label2; + } + Label4: + if (this.Patrimonial != null) + { + keyValuePairs.AddRange(this.Patrimonial.Validate()); + } + else + { + keyValuePairs.AddValue<string, string>("Patrimonial", Messages.Obrigatorio, true); + } + } + return keyValuePairs; + Label1: + if (this.Vida != null) + { + keyValuePairs.AddRange(this.Vida.Validate()); + } + else + { + keyValuePairs.AddValue<string, string>("Vida", Messages.Obrigatorio, true); + } + if (this.Titulares != null && this.Titulares.Count > 0 && this.Documento.Controle.Ramo.Id != (long)6) + { + using (enumerator = this.Titulares.GetEnumerator()) + { + while (enumerator.MoveNext()) + { + keyValuePairs.AddRange(enumerator.Current.Validate()); + } + return keyValuePairs; + } + } + else + { + return keyValuePairs; + } + Label2: + if (this.RiscosDiversos != null) + { + keyValuePairs.AddRange(this.RiscosDiversos.Validate()); + return keyValuePairs; + } + else + { + keyValuePairs.AddValue<string, string>("RiscosDiversos", Messages.Obrigatorio, true); + return keyValuePairs; + } + Label5: + if (this.Auto != null) + { + keyValuePairs.AddRange(this.Auto.Validate(this._config, this._fabricanteBranco)); + return keyValuePairs; + } + else + { + keyValuePairs.AddValue<string, string>("Auto", Messages.Obrigatorio, true); + return keyValuePairs; + } + } + + public event PropertyChangedEventHandler PropertyChanged; + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/MaisContato.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/MaisContato.cs new file mode 100644 index 0000000..6266547 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/MaisContato.cs @@ -0,0 +1,340 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class MaisContato : DomainBase, IDomain + { + private string _nome; + + private string _documento; + + private string _identidade; + + private string _prefixo; + + private string _telefone; + + private string _email; + + private string _habilitacao; + + private string _banco; + + private string _agencia; + + private string _conta; + + [Log(true)] + public string Agencia + { + get + { + string str = this._agencia; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._agencia = value; + } + } + + public string Banco + { + get + { + string str = this._banco; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._banco = value; + } + } + + public Gestor.Model.Domain.Seguros.Cliente Cliente + { + get; + set; + } + + [Log(true)] + public string Conta + { + get + { + string str = this._conta; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._conta = value; + } + } + + [Log(true)] + public string Documento + { + get + { + string str = this._documento; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._documento = value; + } + } + + [Log(true)] + public string Email + { + get + { + string str = this._email; + if (str == null) + { + return null; + } + return str.ToLower().Trim(); + } + set + { + this._email = value; + } + } + + public bool Excluido + { + get; + set; + } + + [Log(true)] + public DateTime? Expedicao + { + get; + set; + } + + [Log(true)] + public string Habilitacao + { + get + { + string str = this._habilitacao; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._habilitacao = value; + } + } + + [Log(true)] + public string Identidade + { + get + { + string str = this._identidade; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._identidade = value; + } + } + + [Log(true)] + public DateTime? Nascimento + { + get; + set; + } + + [Log(true)] + public string Nome + { + get + { + string str = this._nome; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._nome = value; + } + } + + [Log(true)] + public Gestor.Model.Common.Parentesco? Parentesco + { + get; + set; + } + + [Log(true)] + public string Prefixo + { + get + { + string str = this._prefixo; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._prefixo = value; + } + } + + [Log(true)] + public DateTime? PrimeiraHabilitacao + { + get; + set; + } + + [Log(true)] + public Gestor.Model.Domain.Common.Profissao Profissao + { + get; + set; + } + + [Log(true)] + public string Telefone + { + get + { + string str = this._telefone; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._telefone = value; + } + } + + public TipoTelefone? Tipo + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + MaisContato maisContato = this; + return new Func<List<KeyValuePair<string, string>>>(maisContato.Validate); + } + } + + public MaisContato() + { + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (!string.IsNullOrWhiteSpace(this.Nome) && this.Nome.Length > 90) + { + keyValuePairs.AddValue<string, string>("Nome", string.Format(Messages.MaiorQueLimite, 90), true); + } + if (this.PrimeiraHabilitacao.HasValue && (DateTime.Compare(this.PrimeiraHabilitacao.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.PrimeiraHabilitacao.Value, new DateTime(9999, 12, 31)) > 0)) + { + keyValuePairs.AddValue<string, string>("PrimeiraHabilitacao|PRIMEIRA HABILITAÇÃO", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + if (this.Expedicao.HasValue && (DateTime.Compare(this.Expedicao.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.Expedicao.Value, new DateTime(9999, 12, 31)) > 0)) + { + keyValuePairs.AddValue<string, string>("Expedicao|EXPEDIÇÃO", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + if (this.Nascimento.HasValue && (DateTime.Compare(this.Nascimento.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.Nascimento.Value, new DateTime(9999, 12, 31)) > 0)) + { + keyValuePairs.AddValue<string, string>("Nascimento", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + if (!string.IsNullOrWhiteSpace(this.Documento) && this.Documento.Length > 30) + { + keyValuePairs.AddValue<string, string>("Documento", string.Format(Messages.MaiorQueLimite, 30), true); + } + if (!string.IsNullOrWhiteSpace(this.Identidade) && this.Identidade.Length > 40) + { + keyValuePairs.AddValue<string, string>("Identidade", string.Format(Messages.MaiorQueLimite, 40), true); + } + if (!string.IsNullOrWhiteSpace(this.Prefixo) && this.Prefixo.Length > 6) + { + keyValuePairs.AddValue<string, string>("Prefixo", string.Format(Messages.MaiorQueLimite, 6), true); + } + if (!string.IsNullOrWhiteSpace(this.Telefone) && this.Telefone.Length > 11) + { + keyValuePairs.AddValue<string, string>("Telefone", string.Format(Messages.MaiorQueLimite, 11), true); + } + if (!string.IsNullOrWhiteSpace(this.Email) && this.Email.Length > 80) + { + keyValuePairs.AddValue<string, string>("Email|E-MAIL", string.Format(Messages.MaiorQueLimite, 80), true); + } + if (!string.IsNullOrWhiteSpace(this.Habilitacao) && this.Habilitacao.Length > 40) + { + keyValuePairs.AddValue<string, string>("Habilitacao|HABILITAÇÃO", string.Format(Messages.MaiorQueLimite, 40), true); + } + if (!string.IsNullOrWhiteSpace(this.Banco) && this.Banco.Length > 15) + { + keyValuePairs.AddValue<string, string>("Banco", string.Format(Messages.MaiorQueLimite, 15), true); + } + if (!string.IsNullOrWhiteSpace(this.Agencia) && this.Agencia.Length > 15) + { + keyValuePairs.AddValue<string, string>("Agencia|AGÊNCIA", string.Format(Messages.MaiorQueLimite, 15), true); + } + if (!string.IsNullOrWhiteSpace(this.Conta) && this.Conta.Length > 20) + { + keyValuePairs.AddValue<string, string>("Conta", string.Format(Messages.MaiorQueLimite, 20), true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/MetaSeguradora.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/MetaSeguradora.cs new file mode 100644 index 0000000..4b628e7 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/MetaSeguradora.cs @@ -0,0 +1,60 @@ +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class MetaSeguradora : DomainBase + { + public long Ano + { + get; + set; + } + + public Gestor.Model.Common.Mes Mes + { + get; + set; + } + + public bool Recorrente { get; set; } = true; + + public Gestor.Model.Domain.Seguros.Seguradora Seguradora + { + get; + set; + } + + public int TipoCalculo { get; set; } = 1; + + public decimal Valor + { + get; + set; + } + + public MetaSeguradora() + { + } + + public List<TupleList> Log() + { + List<TupleList> tupleLists = new List<TupleList>(); + TupleList tupleList = new TupleList(); + ObservableCollection<Tuple<string, string, string>> observableCollection = new ObservableCollection<Tuple<string, string, string>>(); + decimal valor = this.Valor; + observableCollection.Add(new Tuple<string, string, string>("VALOR DA META", valor.ToString(), "")); + Gestor.Model.Common.Mes mes = this.Mes; + observableCollection.Add(new Tuple<string, string, string>("MÊS", mes.ToString(), "")); + long ano = this.Ano; + observableCollection.Add(new Tuple<string, string, string>("ANO", ano.ToString(), "")); + tupleList.Tuples = observableCollection; + tupleLists.Add(tupleList); + return tupleLists; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/MetaVendedor.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/MetaVendedor.cs new file mode 100644 index 0000000..6483feb --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/MetaVendedor.cs @@ -0,0 +1,56 @@ +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class MetaVendedor : DomainBase + { + public long Ano + { + get; + set; + } + + public Gestor.Model.Common.Mes Mes + { + get; + set; + } + + public decimal Valor + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Vendedor Vendedor + { + get; + set; + } + + public MetaVendedor() + { + } + + public List<TupleList> Log() + { + List<TupleList> tupleLists = new List<TupleList>(); + TupleList tupleList = new TupleList(); + ObservableCollection<Tuple<string, string, string>> observableCollection = new ObservableCollection<Tuple<string, string, string>>(); + decimal valor = this.Valor; + observableCollection.Add(new Tuple<string, string, string>("VALOR DA META", valor.ToString("c2"), "")); + Gestor.Model.Common.Mes mes = this.Mes; + observableCollection.Add(new Tuple<string, string, string>("MÊS", mes.ToString(), "")); + long ano = this.Ano; + observableCollection.Add(new Tuple<string, string, string>("ANO", ano.ToString(), "")); + tupleList.Tuples = observableCollection; + tupleLists.Add(tupleList); + return tupleLists; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/Parceiro.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/Parceiro.cs new file mode 100644 index 0000000..16bbdaf --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/Parceiro.cs @@ -0,0 +1,528 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text.RegularExpressions; + +namespace Gestor.Model.Domain.Seguros +{ + public class Parceiro : DomainBase, IDomain + { + private string _nome; + + private string _cep; + + private string _endereco; + + private string _numero; + + private string _complemento; + + private string _bairro; + + private string _cidade; + + private string _uf; + + private string _cgccpf; + + private string _contato; + + private string _email; + + private string _ddd1; + + private string _telefone1; + + private string _ddd2; + + private string _telefone2; + + private string _ddd3; + + private string _telefone3; + + private string _obs; + + [Log(true)] + public string Bairro + { + get + { + string str = this._bairro; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._bairro = value; + } + } + + [Log(true)] + public string Cep + { + get + { + if (this._cep == null || !Regex.IsMatch(this._cep, "[0-9]+")) + { + return ""; + } + return this._cep.Trim(); + } + set + { + this._cep = value; + } + } + + [Description("DOCUMENTO")] + [Log(true)] + public string Cgccpf + { + get + { + string str = this._cgccpf; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._cgccpf = value; + } + } + + [Log(true)] + public string Cidade + { + get + { + string str = this._cidade; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._cidade = value; + } + } + + [Log(true)] + public string Complemento + { + get + { + string str = this._complemento; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._complemento = value; + } + } + + [Log(true)] + public string Contato + { + get + { + string str = this._contato; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._contato = value; + } + } + + [Description("PREFIXO 1")] + [Log(true)] + public string Ddd1 + { + get + { + string str = this._ddd1; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._ddd1 = value; + } + } + + [Description("PREFIXO 2")] + [Log(true)] + public string Ddd2 + { + get + { + string str = this._ddd2; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._ddd2 = value; + } + } + + [Description("PREFIXO 3")] + [Log(true)] + public string Ddd3 + { + get + { + string str = this._ddd3; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._ddd3 = value; + } + } + + [Log(true)] + public string Email + { + get + { + string str = this._email; + if (str == null) + { + return null; + } + return str.ToLower().Trim(); + } + set + { + this._email = value; + } + } + + [Log(true)] + public string Endereco + { + get + { + string str = this._endereco; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._endereco = value; + } + } + + [Log(true)] + [Name(true)] + public string Nome + { + get + { + string str = this._nome; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._nome = value; + } + } + + [Description("NÚMERO")] + [Log(true)] + public string Numero + { + get + { + string str = this._numero; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._numero = value; + } + } + + [Description("OBSERVAÇÃO")] + [Log(true)] + public string Obs + { + get + { + string str = this._obs; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._obs = value; + } + } + + [Description("TELEFONE 1")] + [Log(true)] + public string Telefone1 + { + get + { + string str = this._telefone1; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._telefone1 = value; + } + } + + [Description("TELEFONE 2")] + [Log(true)] + public string Telefone2 + { + get + { + string str = this._telefone2; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._telefone2 = value; + } + } + + [Description("TELEFONE 3")] + [Log(true)] + public string Telefone3 + { + get + { + string str = this._telefone3; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._telefone3 = value; + } + } + + public Gestor.Model.Common.TipoPerda? TipoPerda + { + get; + set; + } + + [Description("ESTADO")] + [Log(true)] + public string Uf + { + get + { + string str = this._uf; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._uf = value; + } + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Parceiro parceiro = this; + return new Func<List<KeyValuePair<string, string>>>(parceiro.Validate); + } + } + + public Parceiro() + { + } + + public List<TupleList> Log() + { + return new List<TupleList>() + { + new TupleList() + { + Tuples = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("NOME", (string.IsNullOrWhiteSpace(this.Nome) ? "" : this.Nome), ""), + new Tuple<string, string, string>("DOCUMENTO", (string.IsNullOrWhiteSpace(this.Cgccpf) ? "" : this.Cgccpf), ""), + new Tuple<string, string, string>("PRIMEIRO PREFIXO", (string.IsNullOrWhiteSpace(this.Ddd1) ? "" : this.Ddd1), ""), + new Tuple<string, string, string>("PRIMEIRO TELEFONE", (string.IsNullOrWhiteSpace(this.Telefone1) ? "" : this.Telefone1), ""), + new Tuple<string, string, string>("SEGUNDO PREFIXO", (string.IsNullOrWhiteSpace(this.Ddd2) ? "" : this.Ddd2), ""), + new Tuple<string, string, string>("SEGUNDO TELEFONE", (string.IsNullOrWhiteSpace(this.Telefone2) ? "" : this.Telefone2), ""), + new Tuple<string, string, string>("TERCEIRO PREFIXO", (string.IsNullOrWhiteSpace(this.Ddd3) ? "" : this.Ddd3), ""), + new Tuple<string, string, string>("TERCEIRO TELEFONE", (string.IsNullOrWhiteSpace(this.Telefone3) ? "" : this.Telefone3), ""), + new Tuple<string, string, string>("E-MAIL", (string.IsNullOrWhiteSpace(this.Email) ? "" : this.Email), ""), + new Tuple<string, string, string>("CEP", (string.IsNullOrWhiteSpace(this.Cep) ? "" : this.Cep), ""), + new Tuple<string, string, string>("ENDEREÇO", (string.IsNullOrWhiteSpace(this.Endereco) ? "" : this.Endereco), ""), + new Tuple<string, string, string>("NÚMERO", (string.IsNullOrWhiteSpace(this.Numero) ? "" : this.Numero), ""), + new Tuple<string, string, string>("COMPLEMENTO", (string.IsNullOrWhiteSpace(this.Complemento) ? "" : this.Complemento), ""), + new Tuple<string, string, string>("BAIRRO", (string.IsNullOrWhiteSpace(this.Bairro) ? "" : this.Bairro), ""), + new Tuple<string, string, string>("CIDADE", (string.IsNullOrWhiteSpace(this.Cidade) ? "" : this.Cidade), ""), + new Tuple<string, string, string>("ESTADO", (string.IsNullOrWhiteSpace(this.Uf) ? "" : this.Uf), "") + } + } + }; + } + + public List<KeyValuePair<string, string>> Validate() + { + int num; + int? nullable; + bool flag; + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + string nome = this.Nome; + if (nome != null) + { + nullable = new int?((int)nome.Trim().Split(new char[] { ' ' }).Length); + } + else + { + nullable = null; + } + if (!nullable.HasValue) + { + keyValuePairs.AddValue<string, string>("Nome", Messages.Obrigatorio, true); + } + else if (this.Nome.Length > 100) + { + keyValuePairs.AddValue<string, string>("Nome", string.Format(Messages.MaiorQueLimite, 100), true); + } + if (!string.IsNullOrEmpty(this.Cgccpf) && !this.Cgccpf.ValidacaoDocumento()) + { + keyValuePairs.AddValue<string, string>("Cgccpf", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.Ddd1) && !this.Ddd1.ValidacaoPrefixo()) + { + keyValuePairs.AddValue<string, string>("Ddd1|PRIMEIRO DDD", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.Telefone1) && !this.Telefone1.ValidacaoTelefone()) + { + keyValuePairs.AddValue<string, string>("Telefone1|PRIMEIRO TELEFONE", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.Ddd2) && !this.Ddd2.ValidacaoPrefixo()) + { + keyValuePairs.AddValue<string, string>("Ddd2|SEGUNDO DDD", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.Telefone2) && !this.Telefone2.ValidacaoTelefone()) + { + keyValuePairs.AddValue<string, string>("Telefone2|SEGUNDO TELEFONE", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.Ddd3) && !this.Ddd3.ValidacaoPrefixo()) + { + keyValuePairs.AddValue<string, string>("Ddd3|TERCEIRO DDD", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.Telefone3) && !this.Telefone3.ValidacaoTelefone()) + { + keyValuePairs.AddValue<string, string>("Telefone3|TERCEIRO TELEFONE", Messages.Invalido, true); + } + if (!string.IsNullOrEmpty(this.Email) && this.Email.Length > 100) + { + keyValuePairs.AddValue<string, string>("Email|E-MAIL", string.Format(Messages.MaiorQueLimite, 100), true); + } + if (!string.IsNullOrEmpty(this.Email) && !this.Email.ValidacaoEmail()) + { + keyValuePairs.AddValue<string, string>("Email|E-MAIL", Messages.Invalido, true); + } + if (!string.IsNullOrEmpty(this.Cep) && !this.Cep.ValidacaoCep()) + { + keyValuePairs.AddValue<string, string>("Cep|CEP", Messages.Invalido, true); + } + if (!string.IsNullOrEmpty(this.Uf) && !this.Uf.ValidacaoEstado()) + { + keyValuePairs.AddValue<string, string>("Uf|ESTADO", Messages.Invalido, true); + } + if (!string.IsNullOrEmpty(this.Numero) && !int.TryParse(this.Numero, out num)) + { + keyValuePairs.AddValue<string, string>("Numero|NÚMERO", Messages.Invalido, true); + } + if (!string.IsNullOrEmpty(this.Numero)) + { + string numero = this.Numero; + if (numero != null) + { + flag = numero.Count<char>() > 5; + } + else + { + flag = false; + } + if (flag) + { + keyValuePairs.AddValue<string, string>("Numero|NÚMERO", Messages.Invalido, true); + } + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/Parcela.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/Parcela.cs new file mode 100644 index 0000000..d97f5c8 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/Parcela.cs @@ -0,0 +1,789 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class Parcela : DomainBase, IDomain + { + private string _extrato; + + private string _fatura; + + [Description("STATUS PAGAMENTO")] + [ForceLog(true)] + [Log(true)] + private Gestor.Model.Common.StatusPagamento? _statusPagamento; + + private bool _percentualmaiorque100; + + private bool _alteracao; + + private bool _permitirVencimentoMenor; + + private bool _permitirVencimentoMaior; + + public bool Baixando + { + get; + set; + } + + [Description("COMISSÃO")] + [ForceLog(true)] + [Log(true)] + public decimal Comissao + { + get; + set; + } + + [Description("CONTROLE")] + [ForceLog(true)] + [Log(true)] + public DateTime? DataControle + { + get; + set; + } + + [Description("CRÉDITO")] + [ForceLog(true)] + [Log(true)] + public DateTime? DataCredito + { + get; + set; + } + + [Log(false)] + public DateTime? DataCriacao + { + get; + set; + } + + [Description("QUITAÇÃO")] + [ForceLog(true)] + [Log(true)] + public DateTime? DataQuitacao + { + get; + set; + } + + [Description("RECEBIMENTO")] + [ForceLog(true)] + [Log(true)] + public DateTime? DataRecebimento + { + get; + set; + } + + [Description("DESCONTO")] + [ForceLog(true)] + [Log(true)] + public decimal Desconto + { + get; + set; + } + + [ForceLog(true)] + [Log(false)] + public Gestor.Model.Domain.Seguros.Documento Documento + { + get; + set; + } + + [Description("EMISSÃO FATURA")] + [ForceLog(true)] + [Log(true)] + public DateTime? Emissao + { + get; + set; + } + + [Description("EXTRATO")] + [ForceLog(true)] + [Log(true)] + public string Extrato + { + get + { + string str = this._extrato; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._extrato = value; + } + } + + [Description("FATURA")] + [ForceLog(true)] + [Log(true)] + public string Fatura + { + get + { + string str = this._fatura; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._fatura = value; + } + } + + public long IdEmpresa + { + get; + set; + } + + [Log(false)] + public long IdParcelaPendente + { + get; + set; + } + + [Description("IR")] + [ForceLog(true)] + [Log(true)] + public decimal Irr + { + get; + set; + } + + [Description("ISS")] + [ForceLog(true)] + [Log(true)] + public decimal Iss + { + get; + set; + } + + [Description("PARCELA")] + [ForceLog(true)] + [Log(true)] + public int NumeroParcela + { + get; + set; + } + + public string Observacao + { + get; + set; + } + + [Description("OUTROS")] + [ForceLog(true)] + [Log(true)] + public decimal Outros + { + get; + set; + } + + [Log(false)] + public Gestor.Model.Common.StatusPagamento? StatusPagamento + { + get + { + return this._statusPagamento; + } + set + { + this._statusPagamento = new Gestor.Model.Common.StatusPagamento?(value.GetValueOrDefault()); + } + } + + [Description("TIPO DA PARCELA")] + [ForceLog(true)] + [Log(true)] + public Gestor.Model.Common.SubTipo SubTipo + { + get; + set; + } + + public Gestor.Model.Common.TipoPagamento TipoPagamento + { + get; + set; + } + + [Log(false)] + public long UsuarioCriacao + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Parcela parcela = this; + return new Func<List<KeyValuePair<string, string>>>(parcela.Validate); + } + } + + [Description("VALOR")] + [ForceLog(true)] + [Log(true)] + public decimal Valor + { + get; + set; + } + + [Description("COMISSÃO LÍQUIDA")] + [ForceLog(true)] + [Log(true)] + public decimal ValorComDesconto + { + get; + set; + } + + [Description("VALOR DE COMISSÃO")] + [ForceLog(true)] + [Log(true)] + public decimal ValorComissao + { + get; + set; + } + + public decimal ValorExtrato + { + get; + set; + } + + [Description("VALOR LÍQUIDO FATURA")] + [ForceLog(true)] + [Log(true)] + public decimal ValorLiquidoFatura + { + get; + set; + } + + public decimal ValorPago + { + get; + set; + } + + [Description("VALOR PARCELA EXTRATO")] + [ForceLog(true)] + [Log(true)] + public decimal ValorRealizado + { + get; + set; + } + + [Description("VENCIMENTO")] + [ForceLog(true)] + [Log(true)] + public DateTime Vencimento + { + get; + set; + } + + [Log(false)] + public ObservableCollection<VendedorParcela> Vendedores + { + get; + set; + } + + [Description("FIM FATURA")] + [ForceLog(true)] + [Log(true)] + public DateTime? VigenciaFinal + { + get; + set; + } + + [Description("INÍCIO FATURA")] + [ForceLog(true)] + [Log(true)] + public DateTime? VigenciaIncial + { + get; + set; + } + + public Parcela() + { + } + + public List<KeyValuePair<string, string>> Validate(bool permitirVencimentoMenor, bool permitirVencimentoMaior, bool alteracao = false, bool percentualmaiorque100 = false) + { + this._permitirVencimentoMenor = permitirVencimentoMenor; + this._permitirVencimentoMaior = permitirVencimentoMaior; + this._alteracao = alteracao; + this._percentualmaiorque100 = percentualmaiorque100; + return this.Validate(); + } + + public List<KeyValuePair<string, string>> Validate() + { + decimal? nullable; + decimal numeroParcelas; + decimal? nullable1; + decimal? nullable2; + decimal? nullable3; + DateTime vencimento; + DateTime? vigencia2; + int num; + decimal? tolerancia; + decimal? tolerancia1; + decimal? nullable4; + decimal? nullable5; + decimal? tolerancia2; + decimal? tolerancia3; + decimal? nullable6; + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + DateTime? emissao = this.Emissao; + if (emissao.HasValue) + { + emissao = this.Emissao; + if (DateTime.Compare(emissao.Value, new DateTime(1753, 1, 1)) >= 0) + { + emissao = this.Emissao; + if (DateTime.Compare(emissao.Value, new DateTime(9999, 12, 31)) <= 0) + { + goto Label0; + } + } + keyValuePairs.AddValue<string, string>("Emissao|EMISSÃO", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + Label0: + emissao = this.VigenciaFinal; + if (emissao.HasValue) + { + emissao = this.VigenciaFinal; + if (DateTime.Compare(emissao.Value, new DateTime(1753, 1, 1)) >= 0) + { + emissao = this.VigenciaFinal; + if (DateTime.Compare(emissao.Value, new DateTime(9999, 12, 31)) <= 0) + { + goto Label1; + } + } + keyValuePairs.AddValue<string, string>("VigenciaFinal|VIGÊNCIA FINAL", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + Label1: + emissao = this.VigenciaIncial; + if (emissao.HasValue) + { + emissao = this.VigenciaIncial; + if (DateTime.Compare(emissao.Value, new DateTime(1753, 1, 1)) >= 0) + { + emissao = this.VigenciaIncial; + if (DateTime.Compare(emissao.Value, new DateTime(9999, 12, 31)) <= 0) + { + goto Label2; + } + } + keyValuePairs.AddValue<string, string>("VigenciaIncial|VIGÊNCIA INICIAL", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + Label2: + emissao = this.DataCredito; + if (emissao.HasValue) + { + emissao = this.DataCredito; + if (DateTime.Compare(emissao.Value, new DateTime(1753, 1, 1)) >= 0) + { + emissao = this.DataCredito; + if (DateTime.Compare(emissao.Value, new DateTime(9999, 12, 31)) <= 0) + { + goto Label3; + } + } + keyValuePairs.AddValue<string, string>("DataCredito|DATA DE CRÉDITO", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + Label3: + emissao = this.DataRecebimento; + if (emissao.HasValue) + { + emissao = this.DataRecebimento; + if (DateTime.Compare(emissao.Value, new DateTime(1753, 1, 1)) >= 0) + { + emissao = this.DataRecebimento; + if (DateTime.Compare(emissao.Value, new DateTime(9999, 12, 31)) <= 0) + { + goto Label4; + } + } + keyValuePairs.AddValue<string, string>("DataRecebimento|DATA RECEBIMENTO", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + Label4: + if (DateTime.Compare(this.Vencimento, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.Vencimento, new DateTime(9999, 12, 31)) > 0) + { + keyValuePairs.AddValue<string, string>("Vencimento", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + if (this.NumeroParcela == 0) + { + keyValuePairs.AddValue<string, string>("NumeroParcela|NÚMERO DA PARCELA", Messages.Obrigatorio, true); + } + if (this.Valor == decimal.Zero) + { + keyValuePairs.AddValue<string, string>("Valor", Messages.Obrigatorio, true); + } + if (this.Comissao == decimal.Zero && this.Documento.TipoRecebimento.GetValueOrDefault() != TipoRecebimento.Fatura) + { + keyValuePairs.AddValue<string, string>("Comissao|COMISSÃO", Messages.Obrigatorio, true); + } + if (this.Comissao > new decimal(100) && (this.Documento.TipoRecebimento.GetValueOrDefault() != TipoRecebimento.Fatura || !this._percentualmaiorque100)) + { + keyValuePairs.AddValue<string, string>("Comissao|% COMISSÃO", "MAIOR QUE 100%", true); + } + emissao = this.DataRecebimento; + if (emissao.HasValue) + { + emissao = this.DataCredito; + if (!emissao.HasValue) + { + keyValuePairs.AddValue<string, string>("DataCredito|DATA DE CRÉDITO", Messages.Obrigatorio, true); + } + } + emissao = this.DataCredito; + if (emissao.HasValue) + { + emissao = this.DataRecebimento; + if (!emissao.HasValue) + { + keyValuePairs.AddValue<string, string>("DataRecebimento|DATA RECEBIMENTO", Messages.Obrigatorio, true); + } + } + if (this.Baixando) + { + emissao = this.DataRecebimento; + if (!emissao.HasValue) + { + keyValuePairs.AddValue<string, string>("DataRecebimento|DATA DE RECEBIMENTO", Messages.Obrigatorio, true); + } + emissao = this.DataCredito; + if (!emissao.HasValue) + { + keyValuePairs.AddValue<string, string>("DataCredito|DATA DE CRÉDITO", Messages.Obrigatorio, true); + } + } + if (!this._alteracao) + { + emissao = this.DataCredito; + if (!emissao.HasValue) + { + emissao = this.DataRecebimento; + if (!emissao.HasValue) + { + goto Label5; + } + } + if (this.ValorRealizado == decimal.Zero) + { + keyValuePairs.AddValue<string, string>("ValorRealizado|VALOR REALIZADO", Messages.Obrigatorio, true); + } + } + Label5: + if (this.Documento.TipoRecebimento.GetValueOrDefault() != TipoRecebimento.Fatura && this.SubTipo == Gestor.Model.Common.SubTipo.ParcelaNormal) + { + if (this.Documento.NumeroParcelas != decimal.One) + { + decimal num1 = Math.Abs(this.Valor); + decimal num2 = Math.Abs(this.Documento.PremioTotal); + Controle controle = this.Documento.Controle; + if (controle != null) + { + Seguradora seguradora = controle.Seguradora; + if (seguradora != null) + { + tolerancia1 = seguradora.Tolerancia; + } + else + { + nullable3 = null; + tolerancia1 = nullable3; + } + } + else + { + nullable3 = null; + tolerancia1 = nullable3; + } + nullable2 = tolerancia1; + if (nullable2.HasValue) + { + nullable4 = new decimal?(num2 + nullable2.GetValueOrDefault()); + } + else + { + nullable3 = null; + nullable4 = nullable3; + } + nullable1 = nullable4; + numeroParcelas = this.Documento.NumeroParcelas; + if (nullable1.HasValue) + { + nullable5 = new decimal?(nullable1.GetValueOrDefault() - numeroParcelas); + } + else + { + nullable2 = null; + nullable5 = nullable2; + } + nullable = nullable5; + if ((num1 > nullable.GetValueOrDefault()) & nullable.HasValue) + { + decimal valor = this.Valor; + Controle controle1 = this.Documento.Controle; + if (controle1 != null) + { + Seguradora seguradora1 = controle1.Seguradora; + if (seguradora1 != null) + { + tolerancia2 = seguradora1.Tolerancia; + } + else + { + nullable1 = null; + tolerancia2 = nullable1; + } + } + else + { + nullable1 = null; + tolerancia2 = nullable1; + } + nullable = tolerancia2; + if ((valor > nullable.GetValueOrDefault()) & nullable.HasValue) + { + keyValuePairs.AddValue<string, string>("Valor", Messages.ValorParcelaInvalido, true); + } + } + } + else + { + decimal num3 = Math.Abs(this.Valor); + numeroParcelas = Math.Abs(this.Documento.PremioTotal); + Controle controle2 = this.Documento.Controle; + if (controle2 != null) + { + Seguradora seguradora2 = controle2.Seguradora; + if (seguradora2 != null) + { + tolerancia3 = seguradora2.Tolerancia; + } + else + { + nullable2 = null; + tolerancia3 = nullable2; + } + } + else + { + nullable2 = null; + tolerancia3 = nullable2; + } + nullable1 = tolerancia3; + if (nullable1.HasValue) + { + nullable6 = new decimal?(numeroParcelas + nullable1.GetValueOrDefault()); + } + else + { + nullable2 = null; + nullable6 = nullable2; + } + nullable = nullable6; + if ((num3 > nullable.GetValueOrDefault()) & nullable.HasValue) + { + keyValuePairs.AddValue<string, string>("Valor", Messages.ValorParcelaInvalido, true); + } + } + } + if (this.Documento.TipoRecebimento.GetValueOrDefault() != TipoRecebimento.Fatura && this.SubTipo == Gestor.Model.Common.SubTipo.ParcelaNormal && this.Documento.Parcelas != null && this.Documento.NumeroParcelas == this.Documento.Parcelas.Count) + { + decimal num4 = Math.Abs(( + from x in this.Documento.Parcelas + where x.SubTipo == Gestor.Model.Common.SubTipo.ParcelaNormal + select x).Sum<Parcela>((Parcela x) => x.Valor)); + decimal num5 = Math.Abs(this.Documento.PremioTotal); + Controle controle3 = this.Documento.Controle; + if (controle3 != null) + { + Seguradora seguradora3 = controle3.Seguradora; + if (seguradora3 != null) + { + tolerancia = seguradora3.Tolerancia; + } + else + { + nullable = null; + tolerancia = nullable; + } + } + else + { + nullable = null; + tolerancia = nullable; + } + nullable = tolerancia; + if (num4 > (num5 + nullable.GetValueOrDefault()) && this.NumeroParcela == this.Documento.NumeroParcelas) + { + keyValuePairs.AddValue<string, string>("Valor", Messages.ValorParcelaInvalido, true); + } + } + if (!this._permitirVencimentoMaior) + { + emissao = this.Documento.Vigencia2; + if (emissao.HasValue) + { + vencimento = this.Vencimento; + emissao = this.Documento.Vigencia2; + if ((emissao.HasValue ? vencimento > emissao.GetValueOrDefault() : false) && this.Documento.Controle.Ramo.Id != (long)23) + { + keyValuePairs.AddValue<string, string>("Vencimento", Messages.VencimentoMaior, true); + } + } + } + if (!this._permitirVencimentoMenor) + { + if (this.Documento.Vigencia1 > DateTime.MinValue && this.NumeroParcela == 1) + { + DateTime dateTime = this.Vencimento; + vencimento = this.Documento.Vigencia1; + if (dateTime < vencimento.AddDays(-30)) + { + goto Label6; + } + } + if (this.NumeroParcela == 1 || !(this.Vencimento < this.Documento.Vigencia1)) + { + goto Label7; + } + Label6: + keyValuePairs.AddValue<string, string>("Vencimento", Messages.VencimentoMenor, true); + } + Label7: + if (this.Documento == null || this.Documento.TipoRecebimento.GetValueOrDefault() != TipoRecebimento.Fatura) + { + return keyValuePairs; + } + if (string.IsNullOrWhiteSpace(this.Fatura)) + { + keyValuePairs.AddValue<string, string>("Fatura", Messages.Obrigatorio, true); + } + else if (this.Fatura.Length > 50) + { + keyValuePairs.AddValue<string, string>("Fatura", string.Format(Messages.MaiorQueLimite, 255), true); + } + if (this.ValorLiquidoFatura == decimal.Zero) + { + keyValuePairs.AddValue<string, string>("ValorLiquidoFatura|VALOR LÍQUIDO DA FATURA", Messages.Obrigatorio, true); + } + emissao = this.VigenciaIncial; + if (!emissao.HasValue) + { + keyValuePairs.AddValue<string, string>("VigenciaIncial|VIGÊNCIA INICIAL", Messages.Obrigatorio, true); + } + emissao = this.VigenciaFinal; + if (!emissao.HasValue) + { + keyValuePairs.AddValue<string, string>("VigenciaFinal|VIGÊNCIA FINAL", Messages.Obrigatorio, true); + } + emissao = this.Emissao; + if (!emissao.HasValue) + { + keyValuePairs.AddValue<string, string>("Emissao|EMISSÃO", Messages.Obrigatorio, true); + } + if (!string.IsNullOrWhiteSpace(this.Extrato) && this.Extrato.Length > 50) + { + keyValuePairs.AddValue<string, string>("Extrato", string.Format(Messages.MaiorQueLimite, 50), true); + } + emissao = this.VigenciaFinal; + if (emissao.HasValue) + { + emissao = this.Documento.Vigencia2; + if (emissao.HasValue) + { + emissao = this.VigenciaFinal; + vigencia2 = this.Documento.Vigencia2; + if ((emissao.HasValue & vigencia2.HasValue ? emissao.GetValueOrDefault() > vigencia2.GetValueOrDefault() : false) && !this._permitirVencimentoMaior) + { + keyValuePairs.AddValue<string, string>("VigenciaFinal|VIGÊNCIA FINAL", Messages.VencimentoMaior, true); + } + } + } + vigencia2 = this.DataRecebimento; + if (!vigencia2.HasValue && this.ValorComissao != decimal.Zero && this.Documento.TipoRecebimento.GetValueOrDefault() == TipoRecebimento.Fatura) + { + keyValuePairs.AddValue<string, string>("DataRecebimento|DATA RECEBIMENTO", Messages.Obrigatorio, true); + } + if (this.Documento.TipoRecebimento.GetValueOrDefault() != TipoRecebimento.Fatura && this.Documento.Parcelas != null && this.Documento.Parcelas.Any<Parcela>((Parcela x) => { + if (x.NumeroParcela >= this.NumeroParcela) + { + return false; + } + return !x.DataRecebimento.HasValue; + })) + { + keyValuePairs.AddValue<string, string>("DataRecebimento|DATA RECEBIMENTO", Messages.BaixaInvalida, true); + } + vigencia2 = this.DataRecebimento; + if (vigencia2.HasValue && this.ValorComissao != decimal.Zero && this.Documento.TipoRecebimento.GetValueOrDefault() == TipoRecebimento.Fatura) + { + decimal num6 = (this.ValorExtrato == decimal.Zero ? this.ValorLiquidoFatura : this.ValorExtrato); + if (num6 > decimal.Zero) + { + num = num6.CompareTo(this.ValorComissao); + } + else + { + numeroParcelas = this.ValorComissao; + num = numeroParcelas.CompareTo(num6); + } + if (num < 0) + { + keyValuePairs.AddValue<string, string>("ValorComissao|RECEBIDO", "VALOR RECEBIDO MAIOR QUE VALOR PARCELA", true); + } + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/Parcelas.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/Parcelas.cs new file mode 100644 index 0000000..aa31cbb --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/Parcelas.cs @@ -0,0 +1,204 @@ +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Globalization; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class Parcelas : DomainBase + { + public ObservableCollection<Parcela> ParcelasList + { + get; + set; + } + + public Gestor.Model.Common.TipoRecebimento? TipoRecebimento + { + get; + set; + } + + public Parcelas() + { + } + + public List<TupleList> Log(bool restricaoComissao, bool restricaoComissaoPorcentagem) + { + DateTime? vigenciaIncial; + string shortDateString; + string str; + string shortDateString1; + string str1; + string shortDateString2; + string str2; + ObservableCollection<Tuple<string, string, string>> observableCollection = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("PARCELAS$", "", "") + }; + if (this.ParcelasList != null) + { + foreach (Parcela parcelasList in this.ParcelasList) + { + observableCollection.Add(new Tuple<string, string, string>(string.Format(" PARCELA {0}$", parcelasList.NumeroParcela), "", "")); + if (this.TipoRecebimento.GetValueOrDefault() == Gestor.Model.Common.TipoRecebimento.Fatura) + { + observableCollection.Add(new Tuple<string, string, string>(" FATURA", (string.IsNullOrWhiteSpace(parcelasList.Fatura) ? "" : parcelasList.Fatura.ToUpper()), "")); + ObservableCollection<Tuple<string, string, string>> observableCollection1 = observableCollection; + vigenciaIncial = parcelasList.VigenciaIncial; + if (!vigenciaIncial.HasValue) + { + str1 = ""; + } + else + { + vigenciaIncial = parcelasList.VigenciaIncial; + if (vigenciaIncial.HasValue) + { + str1 = vigenciaIncial.GetValueOrDefault().ToShortDateString(); + } + else + { + str1 = null; + } + } + observableCollection1.Add(new Tuple<string, string, string>(" INÍCIO", str1, "")); + ObservableCollection<Tuple<string, string, string>> observableCollection2 = observableCollection; + vigenciaIncial = parcelasList.VigenciaFinal; + if (!vigenciaIncial.HasValue) + { + shortDateString2 = ""; + } + else + { + vigenciaIncial = parcelasList.VigenciaFinal; + if (vigenciaIncial.HasValue) + { + shortDateString2 = vigenciaIncial.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString2 = null; + } + } + observableCollection2.Add(new Tuple<string, string, string>(" FIM", shortDateString2, "")); + ObservableCollection<Tuple<string, string, string>> observableCollection3 = observableCollection; + vigenciaIncial = parcelasList.Emissao; + if (!vigenciaIncial.HasValue) + { + str2 = ""; + } + else + { + vigenciaIncial = parcelasList.Emissao; + if (vigenciaIncial.HasValue) + { + str2 = vigenciaIncial.GetValueOrDefault().ToShortDateString(); + } + else + { + str2 = null; + } + } + observableCollection3.Add(new Tuple<string, string, string>(" EMISSÃO", str2, "")); + } + DateTime vencimento = parcelasList.Vencimento; + observableCollection.Add(new Tuple<string, string, string>(" VENCIMENTO", vencimento.ToShortDateString(), "")); + ObservableCollection<Tuple<string, string, string>> observableCollection4 = observableCollection; + vigenciaIncial = parcelasList.DataRecebimento; + if (!vigenciaIncial.HasValue) + { + shortDateString = ""; + } + else + { + vigenciaIncial = parcelasList.DataRecebimento; + if (vigenciaIncial.HasValue) + { + shortDateString = vigenciaIncial.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString = null; + } + } + observableCollection4.Add(new Tuple<string, string, string>(" RECEBIMENTO", shortDateString, "")); + ObservableCollection<Tuple<string, string, string>> observableCollection5 = observableCollection; + vigenciaIncial = parcelasList.DataQuitacao; + if (!vigenciaIncial.HasValue) + { + str = ""; + } + else + { + vigenciaIncial = parcelasList.DataQuitacao; + if (vigenciaIncial.HasValue) + { + str = vigenciaIncial.GetValueOrDefault().ToShortDateString(); + } + else + { + str = null; + } + } + observableCollection5.Add(new Tuple<string, string, string>(" QUITAÇÃO", str, "")); + ObservableCollection<Tuple<string, string, string>> observableCollection6 = observableCollection; + vigenciaIncial = parcelasList.DataControle; + if (!vigenciaIncial.HasValue) + { + shortDateString1 = ""; + } + else + { + vigenciaIncial = parcelasList.DataControle; + if (vigenciaIncial.HasValue) + { + shortDateString1 = vigenciaIncial.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString1 = null; + } + } + observableCollection6.Add(new Tuple<string, string, string>(" DATA PARCELA CONTROLE", shortDateString1, "")); + decimal valor = parcelasList.Valor; + observableCollection.Add(new Tuple<string, string, string>(" VALOR", valor.ToString("C", new CultureInfo("pt-BR", false)), "")); + valor = parcelasList.ValorLiquidoFatura; + observableCollection.Add(new Tuple<string, string, string>(" LÍQUIDO", valor.ToString("C", new CultureInfo("pt-BR", false)), "")); + if (!restricaoComissao) + { + valor = parcelasList.ValorRealizado; + observableCollection.Add(new Tuple<string, string, string>(" REALIZADO", valor.ToString("C", new CultureInfo("pt-BR", false)), "")); + valor = parcelasList.Comissao / new decimal(100); + observableCollection.Add(new Tuple<string, string, string>(" COMISSÃO", valor.ToString("P", new CultureInfo("pt-BR", false)), "")); + valor = parcelasList.ValorComissao; + observableCollection.Add(new Tuple<string, string, string>(" RECEBIDO", valor.ToString("C", new CultureInfo("pt-BR", false)), "")); + } + else if (!restricaoComissaoPorcentagem) + { + observableCollection.Add(new Tuple<string, string, string>(" REALIZADO", "", "")); + observableCollection.Add(new Tuple<string, string, string>(" COMISSÃO", "", "")); + observableCollection.Add(new Tuple<string, string, string>(" RECEBIDO", "", "")); + } + else + { + observableCollection.Add(new Tuple<string, string, string>(" REALIZADO", "", "")); + valor = parcelasList.Comissao / new decimal(100); + observableCollection.Add(new Tuple<string, string, string>(" COMISSÃO", valor.ToString("P", new CultureInfo("pt-BR", false)), "")); + observableCollection.Add(new Tuple<string, string, string>(" RECEBIDO", "", "")); + } + } + } + return new List<TupleList>() + { + new TupleList() + { + Tuples = observableCollection + } + }; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/Patrimonial.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/Patrimonial.cs new file mode 100644 index 0000000..c54f32b --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/Patrimonial.cs @@ -0,0 +1,574 @@ +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Gestor.Model.Validation; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Globalization; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class Patrimonial : EnderecoBase, IDomain + { + private string _bens; + + private string _imobiliaria; + + private string _locatario; + + private string _locatario2; + + private string _locatario3; + + private string _cpfLocatario1; + + private string _cpfLocatario2; + + private string _cpfLocatario3; + + private string _contato; + + private string _prefixo; + + private string _telefone; + + private Gestor.Model.Common.TipoMoradia _tipoResidencia; + + public string Bens + { + get + { + string str = this._bens; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._bens = value; + } + } + + public string Contato + { + get + { + string str = this._contato; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._contato = value; + } + } + + public string CpfLocatario1 + { + get + { + string str = this._cpfLocatario1; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._cpfLocatario1 = value; + } + } + + public string CpfLocatario2 + { + get + { + string str = this._cpfLocatario2; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._cpfLocatario2 = value; + } + } + + public string CpfLocatario3 + { + get + { + string str = this._cpfLocatario3; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._cpfLocatario3 = value; + } + } + + public string Imobiliaria + { + get + { + string str = this._imobiliaria; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._imobiliaria = value; + } + } + + public Gestor.Model.Domain.Seguros.Item Item + { + get; + set; + } + + public string Locatario1 + { + get + { + string str = this._locatario; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._locatario = value; + } + } + + public string Locatario2 + { + get + { + string str = this._locatario2; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._locatario2 = value; + } + } + + public string Locatario3 + { + get + { + string str = this._locatario3; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._locatario3 = value; + } + } + + public string Prefixo + { + get + { + string str = this._prefixo; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._prefixo = value; + } + } + + public string PrefixoLocatario1 + { + get; + set; + } + + public string PrefixoLocatario2 + { + get; + set; + } + + public string PrefixoLocatario3 + { + get; + set; + } + + public string Telefone + { + get + { + string str = this._telefone; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._telefone = value; + } + } + + public string TelefoneLocatario1 + { + get; + set; + } + + public string TelefoneLocatario2 + { + get; + set; + } + + public string TelefoneLocatario3 + { + get; + set; + } + + public TipoTelefone? Tipo + { + get; + set; + } + + public Gestor.Model.Common.TipoMoradia TipoMoradia + { + get + { + return this._tipoResidencia; + } + set + { + this._tipoResidencia = value; + } + } + + public Gestor.Model.Common.Utilizacao? Utilizacao + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Patrimonial patrimonial = this; + return new Func<List<KeyValuePair<string, string>>>(patrimonial.Validate); + } + } + + public Patrimonial() + { + } + + public static List<TupleList> Log(Gestor.Model.Domain.Seguros.Item item) + { + string description; + string str; + List<TupleList> tupleLists = new List<TupleList>() + { + new TupleList() + { + Tuples = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("CEP", (string.IsNullOrWhiteSpace(item.Patrimonial.Cep) ? "" : item.Patrimonial.Cep), ""), + new Tuple<string, string, string>("ENDEREÇO", (string.IsNullOrWhiteSpace(item.Patrimonial.Endereco) ? "" : item.Patrimonial.Endereco.ToUpper()), ""), + new Tuple<string, string, string>("NÚMERO", (string.IsNullOrWhiteSpace(item.Patrimonial.Numero) ? "" : item.Patrimonial.Numero), ""), + new Tuple<string, string, string>("COMPLEMENTO", (string.IsNullOrWhiteSpace(item.Patrimonial.Complemento) ? "" : item.Patrimonial.Complemento.ToUpper()), ""), + new Tuple<string, string, string>("BAIRRO", (string.IsNullOrWhiteSpace(item.Patrimonial.Bairro) ? "" : item.Patrimonial.Bairro.ToUpper()), ""), + new Tuple<string, string, string>("CIDADE", (string.IsNullOrWhiteSpace(item.Patrimonial.Cidade) ? "" : item.Patrimonial.Cidade.ToUpper()), ""), + new Tuple<string, string, string>("ESTADO", (string.IsNullOrWhiteSpace(item.Patrimonial.Estado) ? "" : item.Patrimonial.Estado.ToUpper()), ""), + new Tuple<string, string, string>("BENS", (string.IsNullOrWhiteSpace(item.Patrimonial.Bens) ? "" : item.Patrimonial.Bens.ToUpper()), ""), + new Tuple<string, string, string>("OBSERVAÇÕES", (string.IsNullOrWhiteSpace(item.Patrimonial.Item.Observacao) ? "" : item.Patrimonial.Item.Observacao.ToUpper()), "") + } + } + }; + if (item.Documento.Controle.Ramo.Id == (long)15) + { + ObservableCollection<Tuple<string, string, string>> tuples = tupleLists[0].Tuples; + Gestor.Model.Common.Utilizacao? utilizacao = item.Patrimonial.Utilizacao; + if (!utilizacao.HasValue) + { + description = ""; + } + else + { + utilizacao = item.Patrimonial.Utilizacao; + if (utilizacao.HasValue) + { + description = utilizacao.GetValueOrDefault().GetDescription(); + } + else + { + description = null; + } + } + tuples.Add(new Tuple<string, string, string>("UTILIZAÇÃO", description, "")); + tupleLists[0].Tuples.Add(new Tuple<string, string, string>("IMOBILIÁRIA", (string.IsNullOrWhiteSpace(item.Patrimonial.Imobiliaria) ? "" : item.Patrimonial.Imobiliaria.ToUpper()), "")); + tupleLists[0].Tuples.Add(new Tuple<string, string, string>("CONTATO", (string.IsNullOrWhiteSpace(item.Patrimonial.Contato) ? "" : item.Patrimonial.Contato.ToUpper()), "")); + ObservableCollection<Tuple<string, string, string>> observableCollection = tupleLists[0].Tuples; + TipoTelefone? tipo = item.Patrimonial.Tipo; + if (!tipo.HasValue) + { + str = ""; + } + else + { + tipo = item.Patrimonial.Tipo; + if (tipo.HasValue) + { + str = tipo.GetValueOrDefault().GetDescription(); + } + else + { + str = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("TIPO TELEFONE", str, "")); + tupleLists[0].Tuples.Add(new Tuple<string, string, string>("PREFIXO", (string.IsNullOrWhiteSpace(item.Patrimonial.Prefixo) ? "" : item.Patrimonial.Prefixo.ToUpper()), "")); + tupleLists[0].Tuples.Add(new Tuple<string, string, string>("NÚMERO", (string.IsNullOrWhiteSpace(item.Patrimonial.Telefone) ? "" : item.Patrimonial.Telefone.ToUpper()), "")); + tupleLists[0].Tuples.Add(new Tuple<string, string, string>("LOCATÁRIO 1", (string.IsNullOrWhiteSpace(item.Patrimonial.Locatario1) ? "" : item.Patrimonial.Locatario1.ToUpper()), "")); + tupleLists[0].Tuples.Add(new Tuple<string, string, string>("PREFIXO LOCATÁRIO 1", (string.IsNullOrWhiteSpace(item.Patrimonial.PrefixoLocatario1) ? "" : item.Patrimonial.PrefixoLocatario1), "")); + tupleLists[0].Tuples.Add(new Tuple<string, string, string>("NÚMERO LOCATÁRIO 1", (string.IsNullOrWhiteSpace(item.Patrimonial.TelefoneLocatario1) ? "" : item.Patrimonial.TelefoneLocatario1), "")); + tupleLists[0].Tuples.Add(new Tuple<string, string, string>("LOCATÁRIO 2", (string.IsNullOrWhiteSpace(item.Patrimonial.Locatario2) ? "" : item.Patrimonial.Locatario2.ToUpper()), "")); + tupleLists[0].Tuples.Add(new Tuple<string, string, string>("PREFIXO LOCATÁRIO 2", (string.IsNullOrWhiteSpace(item.Patrimonial.PrefixoLocatario2) ? "" : item.Patrimonial.PrefixoLocatario2), "")); + tupleLists[0].Tuples.Add(new Tuple<string, string, string>("NÚMERO LOCATÁRIO 2", (string.IsNullOrWhiteSpace(item.Patrimonial.TelefoneLocatario2) ? "" : item.Patrimonial.TelefoneLocatario2), "")); + tupleLists[0].Tuples.Add(new Tuple<string, string, string>("LOCATÁRIO 3", (string.IsNullOrWhiteSpace(item.Patrimonial.Locatario3) ? "" : item.Patrimonial.Locatario3.ToUpper()), "")); + tupleLists[0].Tuples.Add(new Tuple<string, string, string>("PREFIXO LOCATÁRIO 3", (string.IsNullOrWhiteSpace(item.Patrimonial.PrefixoLocatario3) ? "" : item.Patrimonial.PrefixoLocatario3), "")); + tupleLists[0].Tuples.Add(new Tuple<string, string, string>("NÚMERO LOCATÁRIO 3", (string.IsNullOrWhiteSpace(item.Patrimonial.TelefoneLocatario3) ? "" : item.Patrimonial.TelefoneLocatario3), "")); + } + ObservableCollection<Tuple<string, string, string>> observableCollection1 = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("COBERTURAS$", "", "") + }; + foreach (Cobertura cobertura in item.Coberturas) + { + observableCollection1.Add(new Tuple<string, string, string>(string.Format(" COBERTURA {0}$", item.Coberturas.IndexOf(cobertura) + 1), "", "")); + observableCollection1.Add(new Tuple<string, string, string>(" OBSERVAÇÃO", (string.IsNullOrWhiteSpace(cobertura.Observacao) ? "" : cobertura.Observacao.ToUpper()), "")); + decimal premio = cobertura.Premio; + observableCollection1.Add(new Tuple<string, string, string>(" PRÊMIO", premio.ToString("C", new CultureInfo("pt-BR", false)), "")); + premio = cobertura.Franquia; + observableCollection1.Add(new Tuple<string, string, string>(" FRANQUIA", premio.ToString("C", new CultureInfo("pt-BR", false)), "")); + premio = cobertura.Lmi; + observableCollection1.Add(new Tuple<string, string, string>(" L.M.I.", premio.ToString("C", new CultureInfo("pt-BR", false)), "")); + } + tupleLists.Add(new TupleList() + { + Tuples = observableCollection1 + }); + return tupleLists; + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (!string.IsNullOrWhiteSpace(this.Imobiliaria) && this.Imobiliaria.Length > 60) + { + keyValuePairs.AddValue<string, string>("Imobiliaria", string.Format(Messages.MaiorQueLimite, 60), true); + } + if (!string.IsNullOrWhiteSpace(this.Locatario1) && this.Locatario1.Length > 100) + { + keyValuePairs.AddValue<string, string>("Locatario1", string.Format(Messages.MaiorQueLimite, 100), true); + } + if (!string.IsNullOrWhiteSpace(this.Locatario2) && this.Locatario2.Length > 100) + { + keyValuePairs.AddValue<string, string>("Locatario2", string.Format(Messages.MaiorQueLimite, 100), true); + } + if (!string.IsNullOrWhiteSpace(this.Locatario3) && this.Locatario3.Length > 100) + { + keyValuePairs.AddValue<string, string>("Locatario3", string.Format(Messages.MaiorQueLimite, 100), true); + } + if (!string.IsNullOrWhiteSpace(this.CpfLocatario1) && !this.CpfLocatario1.ValidacaoDocumento()) + { + keyValuePairs.AddValue<string, string>("CpfLocatario1", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.CpfLocatario2) && !this.CpfLocatario2.ValidacaoDocumento()) + { + keyValuePairs.AddValue<string, string>("CpfLocatario2", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.CpfLocatario3) && !this.CpfLocatario3.ValidacaoDocumento()) + { + keyValuePairs.AddValue<string, string>("CpfLocatario3", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.Contato) && this.Contato.Length > 60) + { + keyValuePairs.AddValue<string, string>("Contato", string.Format(Messages.MaiorQueLimite, 60), true); + } + if (!string.IsNullOrWhiteSpace(this.Prefixo) && !this.Prefixo.ValidacaoPrefixo()) + { + keyValuePairs.AddValue<string, string>("Prefixo", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.Telefone) && !this.Telefone.ValidacaoTelefone()) + { + keyValuePairs.AddValue<string, string>("Telefone", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.PrefixoLocatario1) && !this.PrefixoLocatario1.ValidacaoPrefixo()) + { + keyValuePairs.AddValue<string, string>("PrefixoLocatario1", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.TelefoneLocatario1) && !this.TelefoneLocatario1.ValidacaoTelefone()) + { + keyValuePairs.AddValue<string, string>("TelefoneLocatario1", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.PrefixoLocatario2) && !this.PrefixoLocatario2.ValidacaoPrefixo()) + { + keyValuePairs.AddValue<string, string>("PrefixoLocatario2", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.TelefoneLocatario2) && !this.TelefoneLocatario2.ValidacaoTelefone()) + { + keyValuePairs.AddValue<string, string>("TelefoneLocatario2", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.PrefixoLocatario3) && !this.PrefixoLocatario3.ValidacaoPrefixo()) + { + keyValuePairs.AddValue<string, string>("PrefixoLocatario3", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.TelefoneLocatario3) && !this.TelefoneLocatario3.ValidacaoTelefone()) + { + keyValuePairs.AddValue<string, string>("TelefoneLocatario3", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(base.Bairro) && base.Bairro.Length > 60) + { + keyValuePairs.AddValue<string, string>("Bairro", string.Format(Messages.MaiorQueLimite, 60), true); + } + if (!string.IsNullOrWhiteSpace(base.Cidade) && base.Cidade.Length > 30) + { + keyValuePairs.AddValue<string, string>("Cidade", string.Format(Messages.MaiorQueLimite, 30), true); + } + if (!string.IsNullOrWhiteSpace(base.Numero) && base.Numero.Length > 10) + { + keyValuePairs.AddValue<string, string>("Numero", string.Format(Messages.MaiorQueLimite, 10), true); + } + if (string.IsNullOrWhiteSpace(base.Cep)) + { + keyValuePairs.AddValue<string, string>("Cep", Messages.Obrigatorio, true); + } + else if (!base.Cep.ValidacaoCep()) + { + keyValuePairs.AddValue<string, string>("Cep", Messages.Invalido, true); + } + if (string.IsNullOrWhiteSpace(base.Endereco)) + { + keyValuePairs.AddValue<string, string>("Endereco", Messages.Obrigatorio, true); + } + if (string.IsNullOrWhiteSpace(base.Numero)) + { + keyValuePairs.AddValue<string, string>("Numero", Messages.Obrigatorio, true); + } + if (string.IsNullOrWhiteSpace(base.Bairro)) + { + keyValuePairs.AddValue<string, string>("Bairro", Messages.Obrigatorio, true); + } + if (string.IsNullOrWhiteSpace(base.Cidade)) + { + keyValuePairs.AddValue<string, string>("Cidade", Messages.Obrigatorio, true); + } + if (string.IsNullOrWhiteSpace(base.Estado)) + { + keyValuePairs.AddValue<string, string>("Estado", Messages.Obrigatorio, true); + } + else if (!base.Estado.ValidacaoEstado()) + { + keyValuePairs.AddValue<string, string>("Estado", Messages.Invalido, true); + } + return keyValuePairs; + } + + public List<KeyValuePair<string, string>> ValidateGarantia() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (!string.IsNullOrWhiteSpace(this.Locatario1) && this.Locatario1.Length > 100) + { + keyValuePairs.AddValue<string, string>("Locatario1", string.Format(Messages.MaiorQueLimite, 100), true); + } + if (!string.IsNullOrWhiteSpace(this.Locatario2) && this.Locatario2.Length > 100) + { + keyValuePairs.AddValue<string, string>("Locatario2", string.Format(Messages.MaiorQueLimite, 100), true); + } + if (!string.IsNullOrWhiteSpace(this.Locatario3) && this.Locatario3.Length > 100) + { + keyValuePairs.AddValue<string, string>("Locatario3", string.Format(Messages.MaiorQueLimite, 100), true); + } + if (!string.IsNullOrWhiteSpace(this.CpfLocatario1) && !this.CpfLocatario1.ValidacaoDocumento()) + { + keyValuePairs.AddValue<string, string>("CpfLocatario1", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.CpfLocatario2) && !this.CpfLocatario2.ValidacaoDocumento()) + { + keyValuePairs.AddValue<string, string>("CpfLocatario2", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.CpfLocatario3) && !this.CpfLocatario3.ValidacaoDocumento()) + { + keyValuePairs.AddValue<string, string>("CpfLocatario3", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.PrefixoLocatario1) && !this.PrefixoLocatario1.ValidacaoPrefixo()) + { + keyValuePairs.AddValue<string, string>("PrefixoLocatario1", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.TelefoneLocatario1) && !this.TelefoneLocatario1.ValidacaoTelefone()) + { + keyValuePairs.AddValue<string, string>("TelefoneLocatario1", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.PrefixoLocatario2) && !this.PrefixoLocatario2.ValidacaoPrefixo()) + { + keyValuePairs.AddValue<string, string>("PrefixoLocatario2", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.TelefoneLocatario2) && !this.TelefoneLocatario2.ValidacaoTelefone()) + { + keyValuePairs.AddValue<string, string>("TelefoneLocatario2", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.PrefixoLocatario3) && !this.PrefixoLocatario3.ValidacaoPrefixo()) + { + keyValuePairs.AddValue<string, string>("PrefixoLocatario3", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.TelefoneLocatario3) && !this.TelefoneLocatario3.ValidacaoTelefone()) + { + keyValuePairs.AddValue<string, string>("TelefoneLocatario3", Messages.Invalido, true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/Perfil.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/Perfil.cs new file mode 100644 index 0000000..e9113b8 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/Perfil.cs @@ -0,0 +1,275 @@ +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class Perfil : DomainBase, IDomain + { + private string _nome; + + private string _cepCirculacao; + + private string _cepPernoite; + + public Antifurto? AntiFurto + { + get; + set; + } + + public string CepCirculacao + { + get + { + return this._cepCirculacao; + } + set + { + this._cepCirculacao = value; + } + } + + public string CepPernoite + { + get + { + return this._cepPernoite; + } + set + { + this._cepPernoite = value; + } + } + + public Gestor.Model.Domain.Seguros.Cliente Cliente + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Controle Controle + { + get; + set; + } + + public string Cpf + { + get; + set; + } + + public DistanciaTrabalho? DistanciaResidenciaTrabalho + { + get; + set; + } + + public Gestor.Model.Common.EstadoCivil? EstadoCivil + { + get; + set; + } + + public bool? EstenderCobertura + { + get; + set; + } + + public GaragemTrabalhoEstudo? GaragemEstudo + { + get; + set; + } + + public Gestor.Model.Common.GaragemResidencia? GaragemResidencia + { + get; + set; + } + + public GaragemTrabalhoEstudo? GaragemTrabalho + { + get; + set; + } + + public string Habilitacao + { + get; + set; + } + + public bool? Isencao + { + get; + set; + } + + public string KmMensal + { + get; + set; + } + + public DateTime? Nascimento + { + get; + set; + } + + public string Nome + { + get + { + string str = this._nome; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._nome = value; + } + } + + public Gestor.Model.Common.Ocupacao? Ocupacao + { + get; + set; + } + + public Gestor.Model.Common.Relacao? Relacao + { + get; + set; + } + + public bool? SeguroVida + { + get; + set; + } + + public Gestor.Model.Common.Sexo? Sexo + { + get; + set; + } + + public Gestor.Model.Common.TempoHabilitacao? TempoHabilitacao + { + get; + set; + } + + public Gestor.Model.Common.TipoResidencia? TipoResidencia + { + get; + set; + } + + public UsoDependetes? UsoDependentes + { + get; + set; + } + + public bool? UsoProfissional + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Perfil perfil = this; + return new Func<List<KeyValuePair<string, string>>>(perfil.Validate); + } + } + + public int? VeiculoResidencia + { + get; + set; + } + + public Perfil() + { + } + + public List<KeyValuePair<string, string>> Validate() + { + bool length; + bool flag; + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (this.Nascimento.HasValue && (DateTime.Compare(this.Nascimento.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.Nascimento.Value, new DateTime(9999, 12, 31)) > 0)) + { + keyValuePairs.AddValue<string, string>("Nascimento", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + if (string.IsNullOrWhiteSpace(this.Nome)) + { + keyValuePairs.AddValue<string, string>("Nome", Messages.Obrigatorio, true); + } + else if (this.Nome.Length > 255) + { + keyValuePairs.AddValue<string, string>("Nome", string.Format(Messages.MaiorQueLimite, 255), true); + } + string kmMensal = this.KmMensal; + if (kmMensal != null) + { + length = kmMensal.Length > 5; + } + else + { + length = false; + } + if (length) + { + keyValuePairs.AddValue<string, string>("KmMensal", string.Format(Messages.MaiorQueLimite, 5), true); + } + string habilitacao = this.Habilitacao; + if (habilitacao != null) + { + flag = habilitacao.Length > 15; + } + else + { + flag = false; + } + if (flag) + { + keyValuePairs.AddValue<string, string>("Habilitacao", string.Format(Messages.MaiorQueLimite, 15), true); + } + if (!this.Relacao.HasValue) + { + keyValuePairs.AddValue<string, string>("Relacao", Messages.Obrigatorio, true); + } + if (!string.IsNullOrWhiteSpace(this.Cpf) && !this.Cpf.ValidacaoDocumento()) + { + keyValuePairs.AddValue<string, string>("Cpf", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.CepPernoite) && !this.CepPernoite.FormataCep().ValidacaoCep()) + { + keyValuePairs.AddValue<string, string>("CepPernoite", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.CepCirculacao) && !this.CepCirculacao.FormataCep().ValidacaoCep()) + { + keyValuePairs.AddValue<string, string>("CepCirculacao", Messages.Invalido, true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/PerfilEmpresa.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/PerfilEmpresa.cs new file mode 100644 index 0000000..e772c5d --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/PerfilEmpresa.cs @@ -0,0 +1,141 @@ +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class PerfilEmpresa : DomainBase, IDomain + { + public DateTime? AnoConstrucao + { + get; + set; + } + + public Gestor.Model.Common.AtividadeEmpresa? AtividadeEmpresa + { + get; + set; + } + + public string AtividadePrincipal + { + get; + set; + } + + public bool? CaixasEletronicos + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Cliente Cliente + { + get; + set; + } + + public bool? ConstrucaoReforma + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Controle Controle + { + get; + set; + } + + public bool? DivisaTerrenoBaldio + { + get; + set; + } + + public string EquipamentoIncendio + { + get; + set; + } + + public string EquipamentoSeguranca + { + get; + set; + } + + public bool? ExclusivoDeposito + { + get; + set; + } + + public bool? Isopainel + { + get; + set; + } + + public Gestor.Model.Common.Localizacao? Localizacao + { + get; + set; + } + + public bool? PatrimonioHistorio + { + get; + set; + } + + public bool? PossuiTelhado + { + get; + set; + } + + public Gestor.Model.Common.TipoConstrucao? TipoConstrucao + { + get; + set; + } + + public TipoPavimentacao? TipoPavimento + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + PerfilEmpresa perfilEmpresa = this; + return new Func<List<KeyValuePair<string, string>>>(perfilEmpresa.Validate); + } + } + + public PerfilEmpresa() + { + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + Gestor.Model.Common.AtividadeEmpresa? atividadeEmpresa = this.AtividadeEmpresa; + if (atividadeEmpresa.GetValueOrDefault() == Gestor.Model.Common.AtividadeEmpresa.Outro & atividadeEmpresa.HasValue && (this.AtividadePrincipal == null || this.AtividadePrincipal == "")) + { + keyValuePairs.AddValue<string, string>("Atividade Empresa", Messages.Invalido, true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/PermissaoArquivoDigital.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/PermissaoArquivoDigital.cs new file mode 100644 index 0000000..39ab35a --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/PermissaoArquivoDigital.cs @@ -0,0 +1,69 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Validation; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class PermissaoArquivoDigital : DomainBase + { + [Log(true)] + public bool Consultar + { + get; + set; + } + + [Log(true)] + public bool Excluir + { + get; + set; + } + + [Log(true)] + public bool Incluir + { + get; + set; + } + + [ForceLog(true)] + [Log(true)] + public TipoArquivoDigital Tela + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Usuario Usuario + { + get; + set; + } + + public PermissaoArquivoDigital() + { + } + + public List<TupleList> Log() + { + return new List<TupleList>() + { + new TupleList() + { + Tuples = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("$TELA", this.Tela.GetDescription(), ""), + new Tuple<string, string, string>(" INCLUIR", (this.Incluir ? "SIM" : "NÃO"), ""), + new Tuple<string, string, string>(" EXCLUIR", (this.Excluir ? "SIM" : "NÃO"), "") + } + } + }; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/PermissaoUsuario.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/PermissaoUsuario.cs new file mode 100644 index 0000000..92ea6f6 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/PermissaoUsuario.cs @@ -0,0 +1,57 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class PermissaoUsuario : DomainBase + { + [Log(true)] + public bool Alterar + { + get; + set; + } + + [Log(true)] + public bool Consultar + { + get; + set; + } + + [Log(true)] + public bool Excluir + { + get; + set; + } + + [Log(true)] + public bool Incluir + { + get; + set; + } + + [ForceLog(true)] + [Log(true)] + public TipoTela Tela + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Usuario Usuario + { + get; + set; + } + + public PermissaoUsuario() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/Produto.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/Produto.cs new file mode 100644 index 0000000..85f07c5 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/Produto.cs @@ -0,0 +1,120 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Gestor.Model.Domain.Seguros +{ + public class Produto : DomainBase, IDomain, INotifyPropertyChanged + { + private bool _selecionado; + + private string _nome; + + [Log(true)] + public bool Ativo + { + get; + set; + } + + [Description("PRODUTO")] + [Log(true)] + [Name(true)] + public string Nome + { + get + { + string str = this._nome; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._nome = value; + } + } + + public bool Selecionado + { + get + { + return this._selecionado; + } + set + { + if (value == this._selecionado) + { + return; + } + this._selecionado = value; + this.OnPropertyChanged("Selecionado"); + } + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Produto produto = this; + return new Func<List<KeyValuePair<string, string>>>(produto.Validate); + } + } + + public Produto() + { + } + + public List<TupleList> Log() + { + return new List<TupleList>() + { + new TupleList() + { + Tuples = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("NOME", (string.IsNullOrWhiteSpace(this.Nome) ? "" : this.Nome), ""), + new Tuple<string, string, string>("ATIVO", (this.Ativo ? "SIM" : "NÃO"), "") + } + } + }; + } + + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChangedEventHandler propertyChangedEventHandler = this.PropertyChanged; + if (propertyChangedEventHandler == null) + { + return; + } + propertyChangedEventHandler(this, new PropertyChangedEventArgs(propertyName)); + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (string.IsNullOrWhiteSpace(this.Nome)) + { + keyValuePairs.AddValue<string, string>("Nome", Messages.Obrigatorio, true); + } + else if (this.Nome.Length > 60) + { + keyValuePairs.AddValue<string, string>("Nome", string.Format(Messages.MaiorQueLimite, 60), true); + } + return keyValuePairs; + } + + public event PropertyChangedEventHandler PropertyChanged; + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/Prospeccao.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/Prospeccao.cs new file mode 100644 index 0000000..059b612 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/Prospeccao.cs @@ -0,0 +1,400 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Gestor.Model.Validation; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class Prospeccao : DomainBase, IDomain + { + private string _nome; + + private string _item; + + private string _observacao; + + public bool AbrirTarefa + { + get; + set; + } + + public List<ArquivoDigital> Anexos + { + get; + set; + } + + public bool CriarTarefa + { + get; + set; + } + + public DateTime? DataCriacao + { + get; + set; + } + + [Description("DOCUMENTO")] + public string Documento + { + get; + set; + } + + [Description("E-MAIL")] + public string Email + { + get; + set; + } + + public bool Excluido + { + get; + set; + } + + public long IdEmpresa + { + get; + set; + } + + [Description("ITEM")] + public string Item + { + get + { + string str = this._item; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._item = value; + } + } + + [Description("NASCIMENTO")] + [Tipo("DATA?")] + public DateTime? Nascimento + { + get; + set; + } + + [Description("CLIENTE")] + public string Nome + { + get + { + string str = this._nome; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._nome = value; + } + } + + public string Observacao + { + get + { + string str = this._observacao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._observacao = value; + } + } + + [Description("DDD")] + public string Prefixo1 + { + get; + set; + } + + [Description("DDD")] + public string Prefixo2 + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Produto Produto + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Ramo Ramo + { + get; + set; + } + + public bool Renovacao + { + get; + set; + } + + [Description("STATUS")] + [Tipo("ENUM?")] + public StatusProspeccao? Status + { + get; + set; + } + + [Description("STATUS PERSONALIZADO")] + public StatusDeProspeccao StatusPersonalizado + { + get; + set; + } + + public Gestor.Model.Domain.Ferramentas.Tarefa Tarefa + { + get; + set; + } + + [Description("TELEFONE")] + public string Telefone1 + { + get; + set; + } + + [Description("TELEFONE")] + public string Telefone2 + { + get; + set; + } + + [Description("TIPO")] + public string Tipo + { + get; + set; + } + + public long UsuarioCriacao + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Prospeccao prospeccao = this; + return new Func<List<KeyValuePair<string, string>>>(prospeccao.Validate); + } + } + + [Description("VALOR")] + public decimal Valor + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Vendedor Vendedor + { + get; + set; + } + + [Description("VIGÊNCIA FINAL")] + [Tipo("DATA?")] + public DateTime? VigenciaFinal + { + get; + set; + } + + public Prospeccao() + { + } + + public List<TupleList> Log() + { + string shortDateString; + string nome; + string str; + string nome1; + string description; + List<TupleList> tupleLists = new List<TupleList>(); + TupleList tupleList = new TupleList(); + ObservableCollection<Tuple<string, string, string>> observableCollection = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("NOME", (string.IsNullOrWhiteSpace(this.Nome) ? "" : this.Nome), ""), + new Tuple<string, string, string>("DOCUMENTO", (string.IsNullOrWhiteSpace(this.Documento) ? "" : this.Documento), "") + }; + DateTime? nascimento = this.Nascimento; + if (!nascimento.HasValue) + { + shortDateString = ""; + } + else + { + nascimento = this.Nascimento; + if (nascimento.HasValue) + { + shortDateString = nascimento.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("NASCIMENTO", shortDateString, "")); + observableCollection.Add(new Tuple<string, string, string>("PRIMEIRO PREFIXO", (string.IsNullOrWhiteSpace(this.Prefixo1) ? "" : this.Prefixo1), "")); + observableCollection.Add(new Tuple<string, string, string>("PRIMEIRO TELEFONE", (string.IsNullOrWhiteSpace(this.Telefone1) ? "" : this.Telefone1), "")); + observableCollection.Add(new Tuple<string, string, string>("SEGUNDO PREFIXO", (string.IsNullOrWhiteSpace(this.Prefixo2) ? "" : this.Prefixo2), "")); + observableCollection.Add(new Tuple<string, string, string>("SEGUNDO TELEFONE", (string.IsNullOrWhiteSpace(this.Telefone2) ? "" : this.Telefone2), "")); + observableCollection.Add(new Tuple<string, string, string>("E-MAIL", (string.IsNullOrWhiteSpace(this.Email) ? "" : this.Email), "")); + observableCollection.Add(new Tuple<string, string, string>("ITEM", (string.IsNullOrWhiteSpace(this.Item) ? "" : this.Item), "")); + Gestor.Model.Domain.Seguros.Produto produto = this.Produto; + if (produto != null) + { + nome = produto.Nome; + } + else + { + nome = null; + } + observableCollection.Add(new Tuple<string, string, string>("PRODUTO", (string.IsNullOrWhiteSpace(nome) ? "" : this.Produto.Nome), "")); + nascimento = this.VigenciaFinal; + if (!nascimento.HasValue) + { + str = ""; + } + else + { + nascimento = this.VigenciaFinal; + if (nascimento.HasValue) + { + str = nascimento.GetValueOrDefault().ToShortDateString(); + } + else + { + str = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("VENCIMENTO", str, "")); + Gestor.Model.Domain.Seguros.Vendedor vendedor = this.Vendedor; + if (vendedor != null) + { + nome1 = vendedor.Nome; + } + else + { + nome1 = null; + } + observableCollection.Add(new Tuple<string, string, string>("VENDEDOR", (string.IsNullOrWhiteSpace(nome1) ? "" : this.Vendedor.Nome), "")); + StatusProspeccao? status = this.Status; + if (!status.HasValue) + { + description = ""; + } + else + { + status = this.Status; + if (status.HasValue) + { + description = status.GetValueOrDefault().GetDescription(); + } + else + { + description = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("STATUS", description, "")); + observableCollection.Add(new Tuple<string, string, string>("STATUS PERSONALIZADO", (this.StatusPersonalizado == null ? "" : this.StatusPersonalizado.Nome), "")); + observableCollection.Add(new Tuple<string, string, string>("OBSERVAÇÃO", (string.IsNullOrWhiteSpace(this.Observacao) ? "" : this.Observacao), "")); + tupleList.Tuples = observableCollection; + tupleLists.Add(tupleList); + List<TupleList> tupleLists1 = tupleLists; + if (this.Tarefa != null) + { + ObservableCollection<Tuple<string, string, string>> observableCollection1 = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("TAREFA$", "", ""), + new Tuple<string, string, string>(" RESPONSÁVEL", (string.IsNullOrWhiteSpace(this.Tarefa.Usuario.Nome) ? "" : this.Tarefa.Usuario.Nome), "") + }; + DateTime agendamento = this.Tarefa.Agendamento; + observableCollection1.Add(new Tuple<string, string, string>(" DATA DO AGENDAMENTO", agendamento.ToShortDateString(), "")); + agendamento = this.Tarefa.Agendamento; + observableCollection1.Add(new Tuple<string, string, string>(" HORA DO AGENDAMENTO", agendamento.ToShortTimeString(), "")); + tupleLists1.Add(new TupleList() + { + Tuples = observableCollection1 + }); + } + return tupleLists1; + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (this.Nascimento.HasValue && (DateTime.Compare(this.Nascimento.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.Nascimento.Value, new DateTime(9999, 12, 31)) > 0)) + { + keyValuePairs.AddValue<string, string>("Nascimento", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + if (this.VigenciaFinal.HasValue && (DateTime.Compare(this.VigenciaFinal.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.VigenciaFinal.Value, new DateTime(9999, 12, 31)) > 0)) + { + keyValuePairs.AddValue<string, string>("VigenciaFinal|VENCIMENTO", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + if (string.IsNullOrWhiteSpace(this.Nome)) + { + keyValuePairs.AddValue<string, string>("Nome", Messages.Obrigatorio, true); + } + if (string.IsNullOrWhiteSpace(this.Telefone1) && string.IsNullOrWhiteSpace(this.Telefone2) && string.IsNullOrWhiteSpace(this.Email)) + { + keyValuePairs.AddValue<string, string>("Telefone1|TELEFONE 1", Messages.Obrigatorio, true); + } + if (!this.VigenciaFinal.HasValue) + { + keyValuePairs.AddValue<string, string>("VigenciaFinal|VENCIMENTO", Messages.Obrigatorio, true); + } + if (string.IsNullOrWhiteSpace(this.Item)) + { + keyValuePairs.AddValue<string, string>("Item", Messages.Obrigatorio, true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/ProspeccaoToPrint.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/ProspeccaoToPrint.cs new file mode 100644 index 0000000..389234b --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/ProspeccaoToPrint.cs @@ -0,0 +1,149 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class ProspeccaoToPrint + { + private string _nome; + + private string _item; + + [Description("DOCUMENTO")] + public string Documento + { + get; + set; + } + + [Description("E-MAIL")] + public string Email + { + get; + set; + } + + [Description("ITEM")] + public string Item + { + get + { + string str = this._item; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._item = value; + } + } + + [Description("NASCIMENTO")] + [Tipo("DATA?")] + public DateTime? Nascimento + { + get; + set; + } + + [Description("CLIENTE")] + public string Nome + { + get + { + string str = this._nome; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._nome = value; + } + } + + [Description("DDD")] + public string Prefixo1 + { + get; + set; + } + + [Description("DDD")] + public string Prefixo2 + { + get; + set; + } + + [Description("STATUS")] + [Tipo("ENUM?")] + public StatusProspeccao? Status + { + get; + set; + } + + [Description("STATUS PERSONALIZADO")] + public string StatusPersonalizadotoPrint + { + get; + set; + } + + [Description("TELEFONE")] + public string Telefone1 + { + get; + set; + } + + [Description("TELEFONE")] + public string Telefone2 + { + get; + set; + } + + [Description("TIPO")] + public string Tipo + { + get; + set; + } + + [Description("VALOR")] + public decimal Valor + { + get; + set; + } + + [Description("VENDEDOR")] + public string Vendedor + { + get; + set; + } + + [Description("VIGÊNCIA FINAL")] + [Tipo("DATA?")] + public DateTime? VigenciaFinal + { + get; + set; + } + + public ProspeccaoToPrint() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/Qualificacao.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/Qualificacao.cs new file mode 100644 index 0000000..06e84ed --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/Qualificacao.cs @@ -0,0 +1,152 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Globalization; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class Qualificacao : DomainBase, IDomain + { + [Description("MÉDIA DE COMISSÃO BRONZE")] + [Log(true)] + public decimal Comissao1 + { + get; + set; + } + + [Description("MÉDIA DE COMISSÃO PRATA")] + [Log(true)] + public decimal Comissao2 + { + get; + set; + } + + [Description("MÉDIA DE COMISSÃO OURO")] + [Log(true)] + public decimal Comissao3 + { + get; + set; + } + + [Description("PRÊMIO LÍQUIDO BROZE")] + [Log(true)] + public decimal Liquido1 + { + get; + set; + } + + [Description("PRÊMIO LÍQUIDO PRATA")] + [Log(true)] + public decimal Liquido2 + { + get; + set; + } + + [Description("PRÊMIO LÍQUIDO OURO")] + [Log(true)] + public decimal Liquido3 + { + get; + set; + } + + [Description("RESULTADO BRONZE")] + [Log(true)] + public decimal Resultado1 + { + get; + set; + } + + [Description("RESULTADO PRATA")] + [Log(true)] + public decimal Resultado2 + { + get; + set; + } + + [Description("RESULTADO OURO")] + [Log(true)] + public decimal Resultado3 + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Qualificacao qualificacao = this; + return new Func<List<KeyValuePair<string, string>>>(qualificacao.Validate); + } + } + + public Qualificacao() + { + } + + public List<TupleList> Log() + { + List<TupleList> tupleLists = new List<TupleList>(); + TupleList tupleList = new TupleList(); + ObservableCollection<Tuple<string, string, string>> observableCollection = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("PRÊMIO LÍQUIDO$", "", "") + }; + decimal liquido1 = this.Liquido1; + observableCollection.Add(new Tuple<string, string, string>(" BRONZE", liquido1.ToString(new CultureInfo("pt-BR")), "")); + liquido1 = this.Liquido2; + observableCollection.Add(new Tuple<string, string, string>(" PRATA", liquido1.ToString(new CultureInfo("pt-BR")), "")); + liquido1 = this.Liquido3; + observableCollection.Add(new Tuple<string, string, string>(" OURO", liquido1.ToString(new CultureInfo("pt-BR")), "")); + tupleList.Tuples = observableCollection; + tupleLists.Add(tupleList); + TupleList tupleList1 = new TupleList(); + ObservableCollection<Tuple<string, string, string>> observableCollection1 = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("MÉDIA DE COMISSÃO$", "", "") + }; + liquido1 = this.Comissao1; + observableCollection1.Add(new Tuple<string, string, string>(" BRONZE", liquido1.ToString(new CultureInfo("pt-BR")), "")); + liquido1 = this.Comissao2; + observableCollection1.Add(new Tuple<string, string, string>(" PRATA", liquido1.ToString(new CultureInfo("pt-BR")), "")); + liquido1 = this.Comissao3; + observableCollection1.Add(new Tuple<string, string, string>(" OURO", liquido1.ToString(new CultureInfo("pt-BR")), "")); + tupleList1.Tuples = observableCollection1; + tupleLists.Add(tupleList1); + TupleList tupleList2 = new TupleList(); + ObservableCollection<Tuple<string, string, string>> observableCollection2 = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("RESULTADO$", "", "") + }; + liquido1 = this.Resultado1; + observableCollection2.Add(new Tuple<string, string, string>(" BRONZE", liquido1.ToString(new CultureInfo("pt-BR")), "")); + liquido1 = this.Resultado2; + observableCollection2.Add(new Tuple<string, string, string>(" PRATA", liquido1.ToString(new CultureInfo("pt-BR")), "")); + liquido1 = this.Resultado3; + observableCollection2.Add(new Tuple<string, string, string>(" OURO", liquido1.ToString(new CultureInfo("pt-BR")), "")); + tupleList2.Tuples = observableCollection2; + tupleLists.Add(tupleList2); + return tupleLists; + } + + public List<KeyValuePair<string, string>> Validate() + { + return ValidationHelper.AddValue(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/Ramo.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/Ramo.cs new file mode 100644 index 0000000..32f3099 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/Ramo.cs @@ -0,0 +1,165 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Globalization; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Gestor.Model.Domain.Seguros +{ + public class Ramo : DomainBase, IDomain, INotifyPropertyChanged + { + private bool _selecionado; + + private string _nome; + + private string _ramoSusep; + + [Log(true)] + public bool Ativo + { + get; + set; + } + + public long CodigoSusep + { + get; + set; + } + + public bool Fatura + { + get; + set; + } + + [Log(true)] + public decimal Iof + { + get; + set; + } + + [Description("RAMO")] + [Log(true)] + [Name(true)] + public string Nome + { + get + { + string str = this._nome; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._nome = value; + } + } + + public string RamoSusep + { + get + { + string str = this._ramoSusep; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._ramoSusep = value; + } + } + + public bool Selecionado + { + get + { + return this._selecionado; + } + set + { + if (value == this._selecionado) + { + return; + } + this._selecionado = value; + this.OnPropertyChanged("Selecionado"); + } + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Ramo ramo = this; + return new Func<List<KeyValuePair<string, string>>>(ramo.Validate); + } + } + + public Ramo() + { + } + + public List<TupleList> Log(List<CoberturaPadrao> listCoberturas) + { + List<TupleList> tupleLists = new List<TupleList>(); + TupleList tupleList = new TupleList(); + ObservableCollection<Tuple<string, string, string>> observableCollection = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("NOME", (string.IsNullOrWhiteSpace(this.Nome) ? "" : this.Nome), "") + }; + decimal iof = this.Iof / new decimal(100); + observableCollection.Add(new Tuple<string, string, string>("I.O.F.", iof.ToString("P", new CultureInfo("pt-BR", false)), "")); + observableCollection.Add(new Tuple<string, string, string>("ATIVO", (this.Ativo ? "SIM" : "NÃO"), "")); + tupleList.Tuples = observableCollection; + tupleLists.Add(tupleList); + List<TupleList> tupleLists1 = tupleLists; + ObservableCollection<Tuple<string, string, string>> observableCollection1 = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("COBERTURAS$", "", "") + }; + foreach (CoberturaPadrao listCobertura in listCoberturas) + { + observableCollection1.Add(new Tuple<string, string, string>(string.Format(" COBERTURA {0}$", listCoberturas.IndexOf(listCobertura) + 1), "", "")); + observableCollection1.Add(new Tuple<string, string, string>(" DESCRIÇÃO", (string.IsNullOrWhiteSpace(listCobertura.Descricao) ? "" : listCobertura.Descricao.ToUpper()), "")); + observableCollection1.Add(new Tuple<string, string, string>(" PADRÃO", (listCobertura.Padrao ? "SIM" : "NÃO"), "")); + } + tupleLists1.Add(new TupleList() + { + Tuples = observableCollection1 + }); + return tupleLists1; + } + + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChangedEventHandler propertyChangedEventHandler = this.PropertyChanged; + if (propertyChangedEventHandler == null) + { + return; + } + propertyChangedEventHandler(this, new PropertyChangedEventArgs(propertyName)); + } + + public List<KeyValuePair<string, string>> Validate() + { + return ValidationHelper.AddValue(); + } + + public event PropertyChangedEventHandler PropertyChanged; + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/Repasse.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/Repasse.cs new file mode 100644 index 0000000..691586a --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/Repasse.cs @@ -0,0 +1,187 @@ +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Gestor.Model.Validation; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class Repasse : DomainBase, IDomain + { + private string _incidenciaVendedor = ""; + + private string _pgtoVendedor = ""; + + public bool Ativo + { + get; + set; + } + + public BaseRepasse? Base + { + get; + set; + } + + public FormaRepasse? Forma + { + get; + set; + } + + public TipoIncidencia? Incidencia + { + get; + set; + } + + public string IncidenciaVendedor + { + get + { + string description = this.Incidencia.GetDescription(); + string str = description; + this._incidenciaVendedor = description; + return str; + } + } + + public string PagtoVendedor + { + get + { + string description = this.Forma.GetDescription(); + string str = description; + this._pgtoVendedor = description; + return str; + } + } + + public Gestor.Model.Domain.Seguros.Ramo Ramo + { + get; + set; + } + + public long? Seguradora + { + get; + set; + } + + public TipoRepasse? Tipo + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Repasse repasse = this; + return new Func<List<KeyValuePair<string, string>>>(repasse.Validate); + } + } + + public decimal ValorNovo + { + get; + set; + } + + public decimal ValorRenovacao + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Vendedor Vendedor + { + get; + set; + } + + public List<VinculoRepasse> Vinculo + { + get; + set; + } + + public Repasse() + { + } + + public List<TupleList> Log() + { + return new List<TupleList>() + { + new TupleList() + { + Tuples = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("TIPO", this.Tipo.GetDescription(), ""), + new Tuple<string, string, string>("VALOR NOVO", string.Format("{0:##.00}", this.ValorNovo), ""), + new Tuple<string, string, string>("VALOR RENOVAÇÃO", string.Format("{0:##.00}", this.ValorRenovacao), ""), + new Tuple<string, string, string>("INCIDÊNCIA", this.Incidencia.GetDescription(), ""), + new Tuple<string, string, string>("FORMA PAGAMENTO", this.Forma.GetDescription(), ""), + new Tuple<string, string, string>("BASE PAGAMENTO", this.Base.GetDescription(), ""), + new Tuple<string, string, string>("ATIVO", (this.Ativo ? "SIM" : "NÃO"), "") + } + } + }; + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (this.Vendedor == null) + { + keyValuePairs.AddValue<string, string>("Vendedor", Messages.Obrigatorio, true); + } + if (TipoRepasse.CoCorretagem != this.Tipo.GetValueOrDefault() && this.ValorNovo == decimal.Zero) + { + keyValuePairs.AddValue<string, string>("ValorNovo", Messages.Obrigatorio, true); + } + if (TipoRepasse.CoCorretagem != this.Tipo.GetValueOrDefault() && this.ValorRenovacao == decimal.Zero) + { + keyValuePairs.AddValue<string, string>("ValorRenovacao", Messages.Obrigatorio, true); + } + if (!this.Tipo.HasValue) + { + keyValuePairs.AddValue<string, string>("Tipo", Messages.Obrigatorio, true); + } + if (!this.Incidencia.HasValue && this.Forma.HasValue && this.Forma.GetValueOrDefault() == FormaRepasse.Recebimento) + { + keyValuePairs.AddValue<string, string>("Incidencia", Messages.Obrigatorio, true); + } + if (!this.Forma.HasValue) + { + keyValuePairs.AddValue<string, string>("Forma", Messages.Obrigatorio, true); + } + if (this.Forma.HasValue && this.Forma.GetValueOrDefault() != FormaRepasse.Recebimento) + { + if (!this.Base.HasValue) + { + keyValuePairs.AddValue<string, string>("Base", Messages.Obrigatorio, true); + } + if (this.Forma.GetValueOrDefault() == FormaRepasse.Prazo && this.Base.GetValueOrDefault() != BaseRepasse.Vencimento) + { + keyValuePairs.AddValue<string, string>("Base", Messages.Invalido, true); + } + } + if (this.Forma.HasValue && this.Forma.GetValueOrDefault() == FormaRepasse.Recebimento && this.Base.HasValue) + { + keyValuePairs.AddValue<string, string>("Base", Messages.Invalido, true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/ResponsavelAssinatura.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/ResponsavelAssinatura.cs new file mode 100644 index 0000000..6896680 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/ResponsavelAssinatura.cs @@ -0,0 +1,109 @@ +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class ResponsavelAssinatura : DomainBase, IDomain + { + public string DocumentoResponsavel + { + get; + set; + } + + public string EmailResponsavel + { + get; + set; + } + + public long IdCliente + { + get; + set; + } + + public string NomeResponsavel + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + ResponsavelAssinatura responsavelAssinatura = this; + return new Func<List<KeyValuePair<string, string>>>(responsavelAssinatura.Validate); + } + } + + public ResponsavelAssinatura() + { + } + + public List<KeyValuePair<string, string>> Validate() + { + int? nullable; + int? nullable1; + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (string.IsNullOrWhiteSpace(this.NomeResponsavel)) + { + nullable = null; + nullable1 = nullable; + } + else + { + string nomeResponsavel = this.NomeResponsavel; + if (nomeResponsavel != null) + { + nullable1 = new int?((int)nomeResponsavel.Trim().Split(new char[] { ' ' }).Length); + } + else + { + nullable = null; + nullable1 = nullable; + } + } + int? nullable2 = nullable1; + if (nullable2.HasValue) + { + nullable = nullable2; + if (nullable.GetValueOrDefault() <= 1 & nullable.HasValue) + { + keyValuePairs.AddValue<string, string>("NomeResponsavel", Messages.NomeInvalido, true); + } + } + if (!string.IsNullOrWhiteSpace(this.DocumentoResponsavel) && !this.DocumentoResponsavel.ValidacaoDocumento()) + { + keyValuePairs.AddValue<string, string>("DocumentoResponsavel", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.EmailResponsavel) && !this.EmailResponsavel.ValidacaoEmail()) + { + keyValuePairs.AddValue<string, string>("EmailResponsavel", Messages.Invalido, true); + } + if (nullable2.HasValue || !string.IsNullOrWhiteSpace(this.DocumentoResponsavel) || !string.IsNullOrWhiteSpace(this.EmailResponsavel)) + { + if (!nullable2.HasValue) + { + keyValuePairs.AddValue<string, string>("NomeResponsavel", Messages.Obrigatorio, true); + } + if (string.IsNullOrWhiteSpace(this.DocumentoResponsavel)) + { + keyValuePairs.AddValue<string, string>("DocumentoResponsavel", Messages.Obrigatorio, true); + } + if (string.IsNullOrWhiteSpace(this.EmailResponsavel)) + { + keyValuePairs.AddValue<string, string>("EmailResponsavel", Messages.Obrigatorio, true); + } + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/RestricaoUsuario.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/RestricaoUsuario.cs new file mode 100644 index 0000000..0912cb2 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/RestricaoUsuario.cs @@ -0,0 +1,60 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Validation; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class RestricaoUsuario : DomainBase + { + public string Ajuda + { + get; + set; + } + + [Log(true)] + public bool Restricao + { + get; + set; + } + + [ForceLog(true)] + [Log(true)] + public TipoRestricao Tipo + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Usuario Usuario + { + get; + set; + } + + public RestricaoUsuario() + { + } + + public List<TupleList> Log() + { + return new List<TupleList>() + { + new TupleList() + { + Tuples = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("$TIPO DE RESTRIÇÃO", this.Tipo.GetDescription(), ""), + new Tuple<string, string, string>(" RESTRIÇÃO ATIVA?", (this.Restricao ? "SIM" : "NÃO"), "") + } + } + }; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/RestricaoUsuarioCamposRelatorios.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/RestricaoUsuarioCamposRelatorios.cs new file mode 100644 index 0000000..450780e --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/RestricaoUsuarioCamposRelatorios.cs @@ -0,0 +1,61 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class RestricaoUsuarioCamposRelatorios : DomainBase + { + [ForceLog(true)] + [Log(true)] + public string Campo + { + get; + set; + } + + [ForceLog(true)] + [Log(true)] + public Gestor.Model.Common.Relatorio Relatorio + { + get; + set; + } + + [Log(true)] + public bool Restricao + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Usuario Usuario + { + get; + set; + } + + public RestricaoUsuarioCamposRelatorios() + { + } + + public List<TupleList> Log() + { + return new List<TupleList>() + { + new TupleList() + { + Tuples = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("$TIPO DE RESTRIÇÃO", this.Campo, ""), + new Tuple<string, string, string>(" RESTRIÇÃO ATIVA?", (this.Restricao ? "SIM" : "NÃO"), "") + } + } + }; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/RiscosDiversos.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/RiscosDiversos.cs new file mode 100644 index 0000000..1f8772f --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/RiscosDiversos.cs @@ -0,0 +1,130 @@ +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Globalization; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class RiscosDiversos : DomainBase, IDomain + { + private string _observacao; + + public string Area + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Item Item + { + get; + set; + } + + public string Observacao + { + get + { + string str = this._observacao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._observacao = value; + } + } + + public decimal? SubsidioEstadual + { + get; + set; + } + + public decimal? SubsidioFederal + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + RiscosDiversos riscosDiverso = this; + return new Func<List<KeyValuePair<string, string>>>(riscosDiverso.Validate); + } + } + + public RiscosDiversos() + { + } + + public static List<TupleList> Log(Gestor.Model.Domain.Seguros.Item item) + { + List<TupleList> tupleLists = new List<TupleList>() + { + new TupleList() + { + Tuples = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("DESCRIÇÃO", (string.IsNullOrWhiteSpace(item.Descricao) ? "" : item.Descricao), ""), + new Tuple<string, string, string>("OBSERVAÇÕES", (string.IsNullOrWhiteSpace(item.RiscosDiversos.Observacao) ? "" : item.RiscosDiversos.Observacao.ToUpper()), "") + } + } + }; + ObservableCollection<Tuple<string, string, string>> observableCollection = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("COBERTURAS$", "", "") + }; + foreach (Cobertura cobertura in item.Coberturas) + { + observableCollection.Add(new Tuple<string, string, string>(string.Format(" COBERTURA {0}$", item.Coberturas.IndexOf(cobertura) + 1), "", "")); + observableCollection.Add(new Tuple<string, string, string>(" OBSERVAÇÃO", (string.IsNullOrWhiteSpace(cobertura.Observacao) ? "" : cobertura.Observacao.ToUpper()), "")); + decimal premio = cobertura.Premio; + observableCollection.Add(new Tuple<string, string, string>(" PRÊMIO", premio.ToString("C", new CultureInfo("pt-BR", false)), "")); + premio = cobertura.Franquia; + observableCollection.Add(new Tuple<string, string, string>(" FRANQUIA", premio.ToString("C", new CultureInfo("pt-BR", false)), "")); + premio = cobertura.Lmi; + observableCollection.Add(new Tuple<string, string, string>(" L.M.I.", premio.ToString("C", new CultureInfo("pt-BR", false)), "")); + } + tupleLists.Add(new TupleList() + { + Tuples = observableCollection + }); + return tupleLists; + } + + public List<KeyValuePair<string, string>> Validate() + { + bool id; + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (string.IsNullOrWhiteSpace(this.Observacao)) + { + Gestor.Model.Domain.Seguros.Item item = this.Item; + if (item != null) + { + id = item.Documento.Controle.Ramo.Id != (long)23; + } + else + { + id = true; + } + if (id) + { + keyValuePairs.AddValue<string, string>("Observacao", Messages.Obrigatorio, true); + } + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/Seguradora.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/Seguradora.cs new file mode 100644 index 0000000..d036a66 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/Seguradora.cs @@ -0,0 +1,1804 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Gestor.Model.Validation; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Gestor.Model.Domain.Seguros +{ + public class Seguradora : DomainBase, IDomain, INotifyPropertyChanged + { + private bool _selecionado; + + private string _nome; + + private string _susep; + + private string _assistencia; + + private string _documento; + + private string _observacao; + + private string _codigo; + + private string _codigoSusep; + + private string _codigoSeguradora; + + private string _nomeSocial; + + private string _nomeSocialBanco; + + [Log(true)] + public string Assistencia + { + get + { + string str = this._assistencia; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._assistencia = value; + } + } + + [Log(true)] + public bool Ativo + { + get; + set; + } + + public string Codigo + { + get + { + string str = this._codigo; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._codigo = value; + } + } + + public string CodigoSeguradora + { + get + { + string str = this._codigoSeguradora; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._codigoSeguradora = value; + } + } + + public string CodigoSusep + { + get + { + string str = this._codigoSusep; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._codigoSusep = value; + } + } + + public List<SeguradoraContato> Contatos + { + get; + set; + } + + public string CustomId + { + get; + set; + } + + [Log(true)] + public string Documento + { + get + { + string str = this._documento; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._documento = value; + } + } + + public List<SeguradoraEndereco> Enderecos + { + get; + set; + } + + public long? IdAggilizador + { + get; + set; + } + + [Description("LINK APP ANDROID")] + [Log(true)] + public string LinkAppAndroid + { + get; + set; + } + + [Description("LINK APP IOS")] + [Log(true)] + public string LinkAppIos + { + get; + set; + } + + [Description("SEGURADORA")] + [Log(true)] + [Name(true)] + public string Nome + { + get + { + string str = this._nome; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._nome = value; + } + } + + public string NomeSocial + { + get + { + string str = this._nomeSocial; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + string str; + string nome; + this._nomeSocial = value; + if (!string.IsNullOrWhiteSpace(value)) + { + this.NomeSocialBanco = (this.NomeSocialBanco == " " ? "" : value); + return; + } + long id = base.Id; + if (id <= (long)694) + { + if (id <= (long)678) + { + long num = id - (long)1; + if (num <= (long)606) + { + switch ((uint)num) + { + case 0: + { + this.NomeSocial = "ABSOLUTA"; + return; + } + case 1: + case 2: + case 3: + case 4: + { + this.NomeSocial = "ACE"; + return; + } + case 5: + case 6: + case 7: + case 19: + case 20: + case 21: + case 22: + case 23: + case 28: + case 29: + case 30: + case 31: + case 35: + case 36: + case 37: + case 38: + case 42: + case 43: + case 44: + case 45: + case 46: + case 47: + case 49: + case 50: + case 51: + case 57: + case 58: + case 61: + case 62: + case 66: + case 67: + case 68: + case 70: + case 71: + case 72: + case 73: + case 74: + case 75: + case 76: + case 77: + case 78: + case 79: + case 80: + case 81: + case 82: + case 83: + case 84: + case 85: + case 86: + case 87: + case 97: + case 101: + case 102: + case 103: + case 104: + case 109: + case 110: + case 113: + case 114: + case 118: + case 121: + case 122: + case 123: + case 124: + case 127: + case 131: + case 132: + case 133: + case 134: + case 135: + case 136: + case 137: + case 138: + case 139: + case 140: + case 141: + case 142: + case 143: + case 146: + case 147: + case 148: + case 149: + case 150: + case 153: + case 154: + case 155: + case 156: + case 157: + case 158: + case 159: + case 162: + case 163: + case 164: + case 165: + case 166: + case 167: + case 168: + case 169: + case 170: + case 171: + case 172: + case 173: + case 174: + case 175: + case 179: + case 182: + case 183: + case 186: + case 187: + case 189: + case 190: + case 191: + case 192: + case 193: + case 194: + case 195: + case 198: + case 199: + case 202: + case 203: + case 204: + case 207: + case 208: + case 209: + case 210: + case 211: + case 214: + case 219: + case 220: + case 223: + case 224: + case 227: + case 228: + case 229: + case 233: + case 234: + case 237: + case 238: + case 239: + case 240: + case 244: + case 245: + case 246: + case 247: + case 250: + case 252: + case 253: + case 256: + case 261: + case 262: + case 263: + case 270: + case 276: + case 277: + case 278: + case 279: + case 280: + case 281: + case 282: + case 286: + case 287: + case 288: + case 300: + case 301: + case 302: + case 303: + case 304: + case 305: + case 306: + case 312: + case 313: + case 314: + case 315: + case 316: + case 329: + case 331: + case 332: + case 333: + case 334: + case 335: + case 338: + case 339: + case 341: + case 342: + case 343: + case 344: + case 350: + case 357: + case 358: + case 359: + case 360: + case 361: + case 362: + case 363: + case 366: + case 367: + case 368: + case 369: + case 370: + case 371: + case 373: + case 376: + case 377: + case 381: + case 382: + case 383: + case 388: + case 389: + case 390: + case 391: + case 392: + case 393: + case 396: + case 397: + case 402: + case 403: + case 404: + case 405: + case 406: + case 407: + case 408: + case 409: + case 410: + case 413: + case 414: + case 415: + case 419: + case 420: + case 421: + case 422: + case 425: + case 433: + case 434: + case 442: + case 443: + case 444: + case 451: + case 452: + case 453: + case 454: + case 457: + case 460: + case 461: + case 462: + case 463: + case 464: + case 467: + case 468: + case 469: + case 470: + case 472: + case 473: + case 488: + case 495: + case 496: + case 502: + case 504: + case 505: + case 506: + case 510: + case 511: + case 512: + case 519: + case 524: + case 525: + case 526: + case 529: + case 530: + case 531: + case 532: + case 533: + case 534: + case 535: + case 536: + case 552: + case 555: + case 562: + case 563: + case 564: + case 565: + case 566: + case 567: + case 568: + case 575: + case 576: + case 577: + case 578: + case 580: + case 585: + case 586: + case 587: + case 588: + case 589: + case 592: + case 596: + case 598: + case 599: + case 600: + case 601: + { + str = (base.Id == 0 ? " " : this.NomeSocial); + this.NomeSocialBanco = str; + nome = this.Nome ?? ""; + this.NomeSocial = nome; + return; + } + case 8: + case 9: + case 517: + case 518: + { + this.NomeSocial = "AIG"; + return; + } + case 10: + { + this.NomeSocial = "AJAX"; + return; + } + case 11: + case 12: + case 13: + { + this.NomeSocial = "ALFA"; + return; + } + case 14: + case 15: + case 16: + case 176: + case 177: + { + this.NomeSocial = "ALIANÇA"; + return; + } + case 17: + case 18: + { + this.NomeSocial = "ALLIANZ"; + return; + } + case 24: + case 25: + case 26: + case 180: + { + this.NomeSocial = "ALLSEG"; + return; + } + case 27: + case 590: + case 591: + case 593: + { + this.NomeSocial = "AMIL"; + return; + } + case 32: + case 33: + case 34: + { + this.NomeSocial = "APLUB"; + return; + } + case 39: + case 40: + { + this.NomeSocial = "ARCH"; + return; + } + case 41: + { + this.NomeSocial = "ARGO"; + return; + } + case 48: + case 243: + { + this.NomeSocial = "GENERALI"; + return; + } + case 52: + case 53: + case 54: + case 55: + case 56: + { + this.NomeSocial = "ATLANTICA"; + return; + } + case 59: + case 60: + { + this.NomeSocial = "AUSTRAL"; + return; + } + case 63: + case 64: + case 65: + case 602: + { + this.NomeSocial = "AXA"; + return; + } + case 69: + { + this.NomeSocial = "AZUL"; + return; + } + case 88: + case 89: + case 90: + case 91: + case 92: + case 583: + { + this.NomeSocial = "BRADESCO"; + return; + } + case 93: + { + this.NomeSocial = "BRASIL LIBANO"; + return; + } + case 94: + { + this.NomeSocial = "BRASILCAP"; + return; + } + case 95: + case 96: + { + this.NomeSocial = "BRASILPREV"; + return; + } + case 98: + case 100: + { + this.NomeSocial = "BRASILUSITANA"; + return; + } + case 99: + { + this.NomeSocial = "BRASIL VEÍCULOS"; + return; + } + case 105: + case 106: + case 107: + case 108: + case 372: + { + this.NomeSocial = "CAIXA"; + return; + } + case 111: + case 112: + { + this.NomeSocial = "CAPEMISA"; + return; + } + case 115: + case 116: + case 117: + { + this.NomeSocial = "CARDIF"; + return; + } + case 119: + case 120: + { + this.NomeSocial = "CASTELLO"; + return; + } + case 125: + case 126: + { + this.NomeSocial = "CESCEBRASIL"; + return; + } + case 128: + case 129: + { + this.NomeSocial = "CHARTIS"; + return; + } + case 130: + { + this.NomeSocial = "CHUBB"; + return; + } + case 144: + case 184: + case 185: + { + this.NomeSocial = "INTERNACIONAL"; + return; + } + case 145: + case 289: + case 292: + case 293: + case 294: + { + this.NomeSocial = "ITAÉ"; + return; + } + case 151: + case 152: + case 188: + case 416: + case 417: + case 418: + { + this.NomeSocial = "REAL"; + return; + } + case 160: + case 161: + { + this.NomeSocial = "URBANIA"; + return; + } + case 178: + case 251: + { + this.NomeSocial = "GRALHA AZUL"; + return; + } + case 181: + { + this.NomeSocial = "EXCELSIOR"; + return; + } + case 196: + case 197: + { + this.NomeSocial = "CREDITO Y CAUCIAN"; + return; + } + case 200: + case 201: + { + this.NomeSocial = "CRUZEIRO DO SUL"; + return; + } + case 205: + case 206: + { + this.NomeSocial = "ECC"; + return; + } + case 212: + case 213: + { + this.NomeSocial = "EQUITATIVA"; + return; + } + case 215: + { + this.NomeSocial = "ESSOR"; + return; + } + case 216: + case 217: + case 218: + { + this.NomeSocial = "EULER HERMES"; + return; + } + case 221: + case 222: + { + this.NomeSocial = "EVEREST"; + return; + } + case 225: + case 226: + { + this.NomeSocial = "FACTORY"; + return; + } + case 230: + case 231: + case 232: + { + this.NomeSocial = "FEDERAL"; + return; + } + case 235: + case 236: + { + this.NomeSocial = "FINANCIAL"; + return; + } + case 241: + case 242: + { + this.NomeSocial = "GENERAL"; + return; + } + case 248: + case 249: + { + this.NomeSocial = "GNPP"; + return; + } + case 254: + case 255: + { + this.NomeSocial = "HANNOVER"; + return; + } + case 257: + case 258: + case 259: + case 260: + case 569: + case 597: + { + this.NomeSocial = "HDI"; + return; + } + case 264: + case 265: + case 266: + case 267: + case 268: + case 269: + { + this.NomeSocial = "HSBC"; + return; + } + case 271: + case 272: + { + this.NomeSocial = "ICATU"; + return; + } + case 273: + case 274: + { + this.NomeSocial = "IF P&C INSURANCE"; + return; + } + case 275: + { + this.NomeSocial = "INDIANA"; + return; + } + case 283: + case 284: + case 285: + case 603: + { + this.NomeSocial = "KOVR"; + return; + } + case 290: + case 291: + case 295: + case 296: + { + this.NomeSocial = "ITAÚ"; + return; + } + case 297: + case 298: + case 299: + { + this.NomeSocial = "J. MALUCELLI"; + return; + } + case 307: + case 308: + case 309: + { + this.NomeSocial = "YELUM"; + return; + } + case 310: + case 311: + { + this.NomeSocial = "LIDERANÇA"; + return; + } + case 317: + case 318: + case 319: + case 320: + case 321: + case 322: + case 323: + case 324: + case 325: + case 326: + case 327: + case 328: + { + this.NomeSocial = "MAPFRE"; + return; + } + case 330: + case 542: + case 561: + { + this.NomeSocial = "YASUDA MARITIMA"; + return; + } + case 336: + case 337: + { + this.NomeSocial = "MBM"; + return; + } + case 340: + { + this.NomeSocial = "METLIFE"; + return; + } + case 345: + case 346: + case 347: + { + this.NomeSocial = "MITSUI"; + return; + } + case 348: + case 349: + { + this.NomeSocial = "MONGERAL"; + return; + } + case 351: + case 352: + case 353: + case 354: + case 355: + case 356: + { + this.NomeSocial = "MONTEPIO"; + return; + } + case 364: + case 365: + case 380: + { + this.NomeSocial = "NATIONAL"; + return; + } + case 374: + case 375: + { + this.NomeSocial = "NOVA YORK"; + return; + } + case 378: + case 379: + { + this.NomeSocial = "ODYSSEY"; + return; + } + case 384: + case 385: + { + this.NomeSocial = "PARANÁ"; + return; + } + case 386: + case 387: + { + this.NomeSocial = "PARIS"; + return; + } + case 394: + case 395: + { + this.NomeSocial = "PLANALTO"; + return; + } + case 398: + case 399: + case 400: + case 401: + case 553: + case 554: + case 573: + { + this.NomeSocial = "PORTO SEGURO"; + return; + } + case 411: + case 412: + { + this.NomeSocial = "PRUDENTIAL"; + return; + } + case 423: + case 424: + { + this.NomeSocial = "ROYAL & SUN ALLIANCE"; + return; + } + case 426: + case 427: + case 428: + { + this.NomeSocial = "SABEMI"; + return; + } + case 429: + case 430: + case 431: + case 432: + { + this.NomeSocial = "SAFRA"; + return; + } + case 435: + case 436: + case 437: + { + this.NomeSocial = "SANTANDER"; + return; + } + case 438: + case 439: + { + this.NomeSocial = "SANTOS"; + return; + } + case 440: + case 441: + { + this.NomeSocial = "SANTOS"; + return; + } + case 445: + case 446: + case 447: + case 448: + { + this.NomeSocial = "SCOR"; + return; + } + case 449: + case 450: + { + this.NomeSocial = "SDB"; + return; + } + case 455: + case 456: + { + this.NomeSocial = "MINEIRA"; + return; + } + case 458: + case 459: + { + this.NomeSocial = "PONTUAL"; + return; + } + case 465: + case 466: + { + this.NomeSocial = "SIRIUS"; + return; + } + case 471: + case 594: + { + this.NomeSocial = "SOMPO"; + return; + } + case 474: + case 475: + case 476: + case 477: + case 478: + case 479: + case 480: + case 481: + case 482: + case 483: + case 484: + case 485: + case 486: + case 487: + case 557: + case 579: + { + this.NomeSocial = "SULAMERICA"; + return; + } + case 489: + case 490: + case 491: + case 492: + case 493: + case 494: + { + this.NomeSocial = "SWISS"; + return; + } + case 497: + case 498: + case 499: + case 500: + case 501: + { + this.NomeSocial = "TOKIO"; + return; + } + case 503: + { + this.NomeSocial = "TOTAL"; + return; + } + case 507: + case 508: + case 509: + { + this.NomeSocial = "TREVO"; + return; + } + case 513: + case 514: + case 515: + case 516: + { + this.NomeSocial = "UNIÃO"; + return; + } + case 520: + case 521: + case 584: + case 595: + { + this.NomeSocial = "UNIMED"; + return; + } + case 522: + case 523: + { + this.NomeSocial = "UNIVERSAL"; + return; + } + case 527: + case 528: + { + this.NomeSocial = "VALOR CAPITALIZAÇÃO"; + return; + } + case 537: + case 538: + case 539: + case 540: + case 541: + { + this.NomeSocial = "XL"; + return; + } + case 543: + case 544: + case 545: + case 546: + case 547: + case 548: + case 549: + case 550: + case 551: + { + this.NomeSocial = "ZURICH"; + return; + } + case 556: + { + this.NomeSocial = "SUHAI"; + return; + } + case 558: + { + this.NomeSocial = "SANCOR"; + return; + } + case 559: + { + this.NomeSocial = "AGROBRASIL"; + return; + } + case 560: + case 570: + { + this.NomeSocial = "SURA"; + return; + } + case 571: + case 572: + case 574: + case 605: + case 606: + { + this.NomeSocial = "SÃO FRANCISCO"; + return; + } + case 581: + { + this.NomeSocial = "SANTA CASA"; + return; + } + case 582: + { + this.NomeSocial = "AMEX"; + return; + } + case 604: + { + this.NomeSocial = "BANCO DO BRASIL"; + return; + } + } + } + else + { + } + long num1 = id - (long)621; + if (num1 <= (long)57) + { + switch ((uint)num1) + { + case 0: + case 3: + case 24: + case 32: + case 33: + case 34: + case 35: + case 36: + case 37: + case 41: + case 42: + { + this.NomeSocial = "UNIMED"; + return; + } + case 1: + case 2: + case 4: + case 5: + case 6: + case 7: + case 8: + case 12: + case 13: + case 16: + case 17: + case 19: + case 23: + case 25: + case 26: + case 27: + case 30: + case 31: + case 38: + case 39: + case 40: + case 44: + case 47: + case 48: + case 49: + case 50: + case 51: + case 54: + { + str = (base.Id == 0 ? " " : this.NomeSocial); + this.NomeSocialBanco = str; + nome = this.Nome ?? ""; + this.NomeSocial = nome; + return; + } + case 9: + case 18: + { + this.NomeSocial = "ALIRO"; + return; + } + case 10: + { + break; + } + case 11: + { + this.NomeSocial = "VR"; + return; + } + case 14: + { + this.NomeSocial = "ALLIANZ"; + return; + } + case 15: + { + this.NomeSocial = "HS"; + return; + } + case 20: + case 22: + case 53: + { + this.NomeSocial = "PORTO SEGURO"; + return; + } + case 21: + { + this.NomeSocial = "SURA"; + return; + } + case 28: + { + this.NomeSocial = "AMIL"; + return; + } + case 29: + { + this.NomeSocial = "YELUM"; + return; + } + case 43: + { + this.NomeSocial = "SULAMERICA"; + return; + } + case 45: + { + this.NomeSocial = "AFFINITY"; + return; + } + case 46: + { + this.NomeSocial = "BR"; + return; + } + case 52: + { + this.NomeSocial = "YAMAHA"; + return; + } + case 55: + { + this.NomeSocial = "SÃO FRANCISCO"; + return; + } + case 56: + { + this.NomeSocial = "EMBRACON"; + return; + } + case 57: + { + this.NomeSocial = "MAPFRE"; + return; + } + default: + { + str = (base.Id == 0 ? " " : this.NomeSocial); + this.NomeSocialBanco = str; + nome = this.Nome ?? ""; + this.NomeSocial = nome; + return; + } + } + } + else + { + str = (base.Id == 0 ? " " : this.NomeSocial); + this.NomeSocialBanco = str; + nome = this.Nome ?? ""; + this.NomeSocial = nome; + return; + } + this.NomeSocial = "METLIFE"; + return; + } + else if (id != (long)683) + { + long num2 = id - (long)687; + if (num2 <= (long)3) + { + switch ((uint)num2) + { + case 0: + { + this.NomeSocial = "ITAÚ"; + return; + } + case 1: + { + str = (base.Id == 0 ? " " : this.NomeSocial); + this.NomeSocialBanco = str; + nome = this.Nome ?? ""; + this.NomeSocial = nome; + return; + } + case 2: + { + this.NomeSocial = "SÃO LUCAS"; + return; + } + case 3: + { + this.NomeSocial = "UNIMED"; + return; + } + } + } + else + { + } + if (id == (long)694) + { + this.NomeSocial = "PORTO SEGURO"; + return; + } + str = (base.Id == 0 ? " " : this.NomeSocial); + this.NomeSocialBanco = str; + nome = this.Nome ?? ""; + this.NomeSocial = nome; + return; + } + else + { + this.NomeSocial = "UNIMED"; + return; + } + this.NomeSocial = "PORTO SEGURO"; + return; + } + else if (id > (long)716) + { + if (id == (long)717) + { + this.NomeSocial = "CHUBB"; + return; + } + if (id == (long)734) + { + this.NomeSocial = "RC"; + return; + } + if (id == (long)741) + { + this.NomeSocial = "SOMPO"; + return; + } + } + else + { + long num3 = id - (long)703; + if (num3 <= (long)8) + { + switch ((uint)num3) + { + case 0: + case 6: + { + this.NomeSocial = "UNIMED"; + return; + } + case 1: + case 4: + case 8: + { + this.NomeSocial = "MAPFRE"; + return; + } + case 2: + case 3: + case 5: + case 7: + { + str = (base.Id == 0 ? " " : this.NomeSocial); + this.NomeSocialBanco = str; + nome = this.Nome ?? ""; + this.NomeSocial = nome; + return; + } + } + } + else + { + } + if (id == (long)716) + { + this.NomeSocial = "UNIMED"; + return; + } + } + str = (base.Id == 0 ? " " : this.NomeSocial); + this.NomeSocialBanco = str; + nome = this.Nome ?? ""; + this.NomeSocial = nome; + } + } + + [Description("APELIDO")] + [Log(true)] + public string NomeSocialBanco + { + get + { + string str = this._nomeSocialBanco; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._nomeSocialBanco = value; + } + } + + [Log(true)] + public string Observacao + { + get + { + return this._observacao; + } + set + { + this._observacao = value; + } + } + + public bool Selecionado + { + get + { + return this._selecionado; + } + set + { + if (value == this._selecionado) + { + return; + } + this._selecionado = value; + this.OnPropertyChanged("Selecionado"); + } + } + + public string Senha + { + get; + set; + } + + [Log(true)] + public string Susep + { + get + { + string str = this._susep; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._susep = value; + } + } + + [Log(true)] + public decimal? Tolerancia + { + get; + set; + } + + [Log(true)] + public decimal? ToleranciaPremio + { + get; + set; + } + + public string Usuario + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Seguradora seguradora = this; + return new Func<List<KeyValuePair<string, string>>>(seguradora.Validate); + } + } + + public Seguradora() + { + } + + public List<TupleList> Log() + { + string str; + string str1; + string description; + List<TupleList> tupleLists = new List<TupleList>(); + TupleList tupleList = new TupleList(); + ObservableCollection<Tuple<string, string, string>> observableCollection = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("SEGURADORA", (string.IsNullOrWhiteSpace(this.Nome) ? "" : this.Nome), ""), + new Tuple<string, string, string>("CNPJ", (string.IsNullOrWhiteSpace(this.Documento) ? "" : this.Documento), ""), + new Tuple<string, string, string>("ASSISTÊNCIA 24 HORAS", (string.IsNullOrWhiteSpace(this.Assistencia) ? "" : this.Assistencia), ""), + new Tuple<string, string, string>("SUSEP", (string.IsNullOrWhiteSpace(this.Susep) ? "" : this.Susep), ""), + new Tuple<string, string, string>("CÓDIGO COMPANHIA", (string.IsNullOrWhiteSpace(this.Codigo) ? "" : this.Codigo), "") + }; + decimal? tolerancia = this.Tolerancia; + if (!tolerancia.HasValue) + { + str = ""; + } + else + { + tolerancia = this.Tolerancia; + if (tolerancia.HasValue) + { + str = tolerancia.GetValueOrDefault().ToString(); + } + else + { + str = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("TOLERÂNCIA DE COMISSÃO", str, "")); + tolerancia = this.ToleranciaPremio; + if (!tolerancia.HasValue) + { + str1 = ""; + } + else + { + tolerancia = this.ToleranciaPremio; + if (tolerancia.HasValue) + { + str1 = tolerancia.GetValueOrDefault().ToString(); + } + else + { + str1 = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("TOLERÂNCIA DE PRÊMIO", str1, "")); + observableCollection.Add(new Tuple<string, string, string>("SEGURADORA ATIVA", (this.Ativo ? "SIM" : "NÃO"), "")); + observableCollection.Add(new Tuple<string, string, string>("OBSERVAÇÃO", (string.IsNullOrWhiteSpace(this.Observacao) ? "" : this.Observacao), "")); + tupleList.Tuples = observableCollection; + tupleLists.Add(tupleList); + List<TupleList> tupleLists1 = tupleLists; + if (this.Contatos != null) + { + ObservableCollection<Tuple<string, string, string>> observableCollection1 = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("CONTATOS$", "", "") + }; + foreach (SeguradoraContato contato in this.Contatos) + { + observableCollection1.Add(new Tuple<string, string, string>(string.Format(" CONTATO {0}$", this.Contatos.IndexOf(contato) + 1), "", "")); + observableCollection1.Add(new Tuple<string, string, string>(" NOME", (string.IsNullOrWhiteSpace(contato.NomeContato) ? "" : contato.NomeContato.ToUpper()), "")); + ObservableCollection<Tuple<string, string, string>> observableCollection2 = observableCollection1; + TipoTelefone? tipo = contato.Tipo; + if (!tipo.HasValue) + { + description = ""; + } + else + { + tipo = contato.Tipo; + if (tipo.HasValue) + { + description = tipo.GetValueOrDefault().GetDescription(); + } + else + { + description = null; + } + } + observableCollection2.Add(new Tuple<string, string, string>(" TIPO TELEFONE", description, "")); + observableCollection1.Add(new Tuple<string, string, string>(" PREFIXO", (string.IsNullOrWhiteSpace(contato.Prefixo) ? "" : contato.Prefixo), "")); + observableCollection1.Add(new Tuple<string, string, string>(" TELEFONE", (string.IsNullOrWhiteSpace(contato.Numero) ? "" : contato.Numero), "")); + } + tupleLists1.Add(new TupleList() + { + Tuples = observableCollection1 + }); + } + if (this.Enderecos != null) + { + ObservableCollection<Tuple<string, string, string>> observableCollection3 = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("ENDEREÇOS$", "", "") + }; + foreach (SeguradoraEndereco endereco in this.Enderecos) + { + observableCollection3.Add(new Tuple<string, string, string>(string.Format(" ENDEREÇO {0}$", this.Enderecos.IndexOf(endereco) + 1), "", "")); + observableCollection3.Add(new Tuple<string, string, string>(" TIPO DO ENDEREÇO", endereco.Tipo.GetDescription(), "")); + observableCollection3.Add(new Tuple<string, string, string>(" CEP", (string.IsNullOrWhiteSpace(endereco.Cep) ? "" : endereco.Cep), "")); + observableCollection3.Add(new Tuple<string, string, string>(" ENDEREÇO", (string.IsNullOrWhiteSpace(endereco.Endereco) ? "" : endereco.Endereco), "")); + observableCollection3.Add(new Tuple<string, string, string>(" NÚMERO", (string.IsNullOrWhiteSpace(endereco.Numero) ? "" : endereco.Numero), "")); + observableCollection3.Add(new Tuple<string, string, string>(" COMPLEMENTO", (string.IsNullOrWhiteSpace(endereco.Complemento) ? "" : endereco.Complemento), "")); + observableCollection3.Add(new Tuple<string, string, string>(" BAIRRO", (string.IsNullOrWhiteSpace(endereco.Bairro) ? "" : endereco.Bairro), "")); + observableCollection3.Add(new Tuple<string, string, string>(" CIDADE", (string.IsNullOrWhiteSpace(endereco.Cidade) ? "" : endereco.Cidade), "")); + observableCollection3.Add(new Tuple<string, string, string>(" ESTADO", (string.IsNullOrWhiteSpace(endereco.Estado) ? "" : endereco.Estado), "")); + } + tupleLists1.Add(new TupleList() + { + Tuples = observableCollection3 + }); + } + return tupleLists1; + } + + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChangedEventHandler propertyChangedEventHandler = this.PropertyChanged; + if (propertyChangedEventHandler == null) + { + return; + } + propertyChangedEventHandler(this, new PropertyChangedEventArgs(propertyName)); + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (!string.IsNullOrWhiteSpace(this.Documento) && !this.Documento.ValidacaoDocumento()) + { + keyValuePairs.AddValue<string, string>("Documento", Messages.Invalido, true); + } + decimal? tolerancia = this.Tolerancia; + decimal num = 999; + if ((tolerancia.GetValueOrDefault() > num) & tolerancia.HasValue) + { + keyValuePairs.AddValue<string, string>("Tolerancia", Messages.Invalido, true); + } + tolerancia = this.ToleranciaPremio; + num = 999999; + if ((tolerancia.GetValueOrDefault() > num) & tolerancia.HasValue) + { + keyValuePairs.AddValue<string, string>("ToleranciaPremio", Messages.Invalido, true); + } + return keyValuePairs; + } + + public event PropertyChangedEventHandler PropertyChanged; + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/SeguradoraContato.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/SeguradoraContato.cs new file mode 100644 index 0000000..61caa17 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/SeguradoraContato.cs @@ -0,0 +1,90 @@ +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class SeguradoraContato : TelefoneBase, IDomain + { + private string _nome; + + private string _email; + + public string Email + { + get + { + string str = this._email; + if (str != null) + { + return str.ToLower(); + } + return null; + } + set + { + this._email = value; + } + } + + public Gestor.Model.Domain.Common.Empresa Empresa + { + get; + set; + } + + public string NomeContato + { + get + { + return this._nome; + } + set + { + this._nome = value; + } + } + + public Gestor.Model.Domain.Seguros.Seguradora Seguradora + { + get; + set; + } + + public TipoContatoSeguradora TipoContato + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + SeguradoraContato seguradoraContato = this; + return new Func<List<KeyValuePair<string, string>>>(seguradoraContato.Validate); + } + } + + public SeguradoraContato() + { + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = base.ValidateBase(true); + if (string.IsNullOrWhiteSpace(this.NomeContato) && this.TipoContato == TipoContatoSeguradora.Contato) + { + keyValuePairs.AddValue<string, string>("NomeContato|NOME CONTATO", Messages.Obrigatorio, true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/SeguradoraEndereco.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/SeguradoraEndereco.cs new file mode 100644 index 0000000..f103e05 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/SeguradoraEndereco.cs @@ -0,0 +1,115 @@ +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class SeguradoraEndereco : EnderecoBase, IDomain + { + public Gestor.Model.Domain.Common.Empresa Empresa + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Seguradora Seguradora + { + get; + set; + } + + public TipoEndereco Tipo + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + SeguradoraEndereco seguradoraEndereco = this; + return new Func<List<KeyValuePair<string, string>>>(seguradoraEndereco.Validate); + } + } + + public SeguradoraEndereco() + { + } + + public List<KeyValuePair<string, string>> Validate() + { + bool length; + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (string.IsNullOrWhiteSpace(base.Cep)) + { + keyValuePairs.AddValue<string, string>("Cep", Messages.Obrigatorio, true); + } + else if (!base.Cep.ValidacaoCep()) + { + keyValuePairs.AddValue<string, string>("Cep", Messages.Invalido, true); + } + if (string.IsNullOrWhiteSpace(base.Estado)) + { + keyValuePairs.AddValue<string, string>("Estado", Messages.Obrigatorio, true); + } + else if (!base.Estado.ValidacaoEstado()) + { + keyValuePairs.AddValue<string, string>("Estado", Messages.Invalido, true); + } + if (string.IsNullOrWhiteSpace(base.Endereco)) + { + keyValuePairs.AddValue<string, string>("Endereco", Messages.Obrigatorio, true); + } + else if (base.Endereco.Length > 60) + { + keyValuePairs.AddValue<string, string>("Endereco", string.Format(Messages.MaiorQueLimite, 60), true); + } + if (string.IsNullOrWhiteSpace(base.Numero)) + { + keyValuePairs.AddValue<string, string>("Numero", Messages.Obrigatorio, true); + } + else if (base.Numero.Length > 5) + { + keyValuePairs.AddValue<string, string>("Numero", string.Format(Messages.MaiorQueLimite, 5), true); + } + if (string.IsNullOrWhiteSpace(base.Bairro)) + { + keyValuePairs.AddValue<string, string>("Bairro", Messages.Obrigatorio, true); + } + else if (base.Bairro.Length > 60) + { + keyValuePairs.AddValue<string, string>("Bairro", string.Format(Messages.MaiorQueLimite, 60), true); + } + if (string.IsNullOrWhiteSpace(base.Cidade)) + { + keyValuePairs.AddValue<string, string>("Cidade", Messages.Obrigatorio, true); + } + else if (base.Cidade.Length > 30) + { + keyValuePairs.AddValue<string, string>("Cidade", string.Format(Messages.MaiorQueLimite, 30), true); + } + string complemento = base.Complemento; + if (complemento != null) + { + length = complemento.Length > 30; + } + else + { + length = false; + } + if (length) + { + keyValuePairs.AddValue<string, string>("Complemento", string.Format(Messages.MaiorQueLimite, 30), true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/Sinistro.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/Sinistro.cs new file mode 100644 index 0000000..21cb5c2 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/Sinistro.cs @@ -0,0 +1,1132 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Gestor.Model.Validation; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Globalization; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class Sinistro : DomainBase, IDomain + { + private string _numero; + + private DateTime? _dataReclamacao; + + private string _itemSinistrado; + + private string _descricao; + + private string _observacao; + + private string _motivo; + + private string _auxiliar; + + private string _observacaoInterna; + + private DateTime? _horaReclamacao; + + public bool Ativo + { + get; + set; + } + + [Description("AUXILIAR")] + [Log(true)] + public string Auxiliar + { + get + { + string str = this._auxiliar; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._auxiliar = value; + } + } + + public Gestor.Model.Domain.Seguros.ControleSinistro ControleSinistro + { + get; + set; + } + + [Description("DATA CRIAÇÃO")] + [Log(true)] + public DateTime? DataAlteracao + { + get; + set; + } + + [Description("DATA CRIACAO")] + [Log(true)] + public DateTime? DataCriacao + { + get; + set; + } + + [Description("DATA LIQUIDAÇÃO")] + [Log(true)] + public DateTime? DataLiquidacao + { + get; + set; + } + + [Description("DATA RECLAMAÇÃO")] + [Log(true)] + public DateTime? DataReclamacao + { + get + { + return this._dataReclamacao; + } + set + { + if (!value.HasValue) + { + this._dataReclamacao = null; + return; + } + if (!this.HoraReclamacao.HasValue) + { + this.HoraReclamacao = value; + } + object obj = value.Value; + DateTime? horaReclamacao = this.HoraReclamacao; + this._dataReclamacao = new DateTime?(DateTime.Parse(string.Format("{0:d} {1:T}", obj, horaReclamacao.Value))); + } + } + + [Description("DESCRIÇÃO")] + [Log(true)] + public string Descricao + { + get + { + string str = this._descricao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._descricao = value; + } + } + + public DateTime? HoraReclamacao + { + get + { + return this._horaReclamacao; + } + set + { + DateTime? nullable; + this._horaReclamacao = value; + if (!value.HasValue) + { + return; + } + DateTime? dataReclamacao = this.DataReclamacao; + if (dataReclamacao.HasValue) + { + dataReclamacao = this.DataReclamacao; + nullable = new DateTime?(DateTime.Parse(string.Format("{0:d} {1:T}", dataReclamacao.Value, value))); + } + else + { + dataReclamacao = null; + nullable = dataReclamacao; + } + this.DataReclamacao = nullable; + } + } + + [Description("USUARIO ALTERACAO")] + [Log(true)] + public long IdUsuarioAlteracao + { + get; + set; + } + + [Description("USUARIO CRIACAO")] + [Log(true)] + public long IdUsuarioCriacao + { + get; + set; + } + + [Description("ITEM SINISTRADO")] + [Log(true)] + public string ItemSinistrado + { + get + { + string str = this._itemSinistrado; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._itemSinistrado = value; + } + } + + [Description("MOTIVO")] + [Log(true)] + public string Motivo + { + get + { + string str = this._motivo; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._motivo = value; + } + } + + [Log(true)] + public string Numero + { + get + { + string str = this._numero; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._numero = value; + } + } + + public string Observacao + { + get + { + return this._observacao; + } + set + { + this._observacao = value; + } + } + + public string ObservacaoInterna + { + get + { + return this._observacaoInterna; + } + set + { + this._observacaoInterna = value; + } + } + + [Log(true)] + public Gestor.Model.Domain.Seguros.SinistroAuto SinistroAuto + { + get; + set; + } + + [Log(true)] + public Gestor.Model.Domain.Seguros.SinistroVida SinistroVida + { + get; + set; + } + + [Description("STATUS PERSONALIZADO")] + [Log(true)] + public string StatusPersonalizado + { + get; + set; + } + + [Description("STATUS")] + [Log(true)] + public Gestor.Model.Common.StatusSinistro? StatusSinistro + { + get; + set; + } + + [Description("TIPO")] + [Log(true)] + public Gestor.Model.Common.TipoSinistro? TipoSinistro + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Sinistro sinistro = this; + return new Func<List<KeyValuePair<string, string>>>(sinistro.Validate); + } + } + + [Description("VALOR")] + [Log(true)] + public decimal Valor + { + get; + set; + } + + [Description("VALOR FRANQUIA")] + [Log(true)] + public decimal ValorFranquia + { + get; + set; + } + + [Description("VALOR LIBERADO")] + [Log(true)] + public decimal ValorLiberado + { + get; + set; + } + + [Description("VALOR ORÇADO")] + [Log(true)] + public decimal ValorOrcado + { + get; + set; + } + + [Description("VALOR PAGO")] + [Log(true)] + public decimal ValorPago + { + get; + set; + } + + [Description("VALOR SALVADO")] + [Log(true)] + public decimal? ValorSalvado + { + get; + set; + } + + public Sinistro() + { + } + + public List<TupleList> Log() + { + DateTime? dataSinistro; + TipoPerda? tipoPerda; + bool? culpado; + EstadoCivil? estadoCivil; + string description; + string shortDateString; + string shortTimeString; + string str; + string shortTimeString1; + string shortDateString1; + string description1; + bool hasValue; + string str1; + bool flag; + string str2; + bool hasValue1; + string description2; + string certObito; + string certObito1; + string beneficiario; + string beneficiario1; + bool? nullable; + string numeroBo; + string numeroBo1; + string description3; + string str3; + string shortDateString2; + string endereco; + string endereco1; + string envolvido; + string envolvido1; + string motorista; + string motorista1; + string ddd; + string ddd1; + string telefone; + string telefone1; + string email; + string email1; + string str4; + bool parceiroMecanica; + string nome; + string str5; + bool parceiroFunilaria; + string nome1; + bool valueOrDefault; + List<TupleList> tupleLists = new List<TupleList>(); + TupleList tupleList = new TupleList(); + ObservableCollection<Tuple<string, string, string>> observableCollection = new ObservableCollection<Tuple<string, string, string>>(); + Gestor.Model.Common.TipoSinistro? tipoSinistro = this.TipoSinistro; + if (!tipoSinistro.HasValue) + { + description = ""; + } + else + { + tipoSinistro = this.TipoSinistro; + if (tipoSinistro.HasValue) + { + description = tipoSinistro.GetValueOrDefault().GetDescription(); + } + else + { + description = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("TIPO DO SINISTRO", description, "")); + observableCollection.Add(new Tuple<string, string, string>("ITEM SINISTRADO", (string.IsNullOrWhiteSpace(this.ItemSinistrado) ? "" : this.ItemSinistrado), "")); + observableCollection.Add(new Tuple<string, string, string>("NÚMERO DO SINISTRO", (string.IsNullOrWhiteSpace(this.Numero) ? "" : this.Numero), "")); + if (this.ControleSinistro == null) + { + shortDateString = ""; + } + else + { + Gestor.Model.Domain.Seguros.ControleSinistro controleSinistro = this.ControleSinistro; + if (controleSinistro != null) + { + dataSinistro = controleSinistro.DataSinistro; + if (dataSinistro.HasValue) + { + shortDateString = dataSinistro.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString = null; + } + } + else + { + shortDateString = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("DATA DO SINISTRO", shortDateString, "")); + if (this.ControleSinistro == null) + { + shortTimeString = ""; + } + else + { + Gestor.Model.Domain.Seguros.ControleSinistro controleSinistro1 = this.ControleSinistro; + if (controleSinistro1 != null) + { + dataSinistro = controleSinistro1.HoraSinistro; + if (dataSinistro.HasValue) + { + shortTimeString = dataSinistro.GetValueOrDefault().ToShortTimeString(); + } + else + { + shortTimeString = null; + } + } + else + { + shortTimeString = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("HORA DO SINISTRO", shortTimeString, "")); + dataSinistro = this.DataReclamacao; + if (!dataSinistro.HasValue) + { + str = ""; + } + else + { + dataSinistro = this.DataReclamacao; + if (dataSinistro.HasValue) + { + str = dataSinistro.GetValueOrDefault().ToShortDateString(); + } + else + { + str = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("DATA DA RECLAMAÇÃO", str, "")); + dataSinistro = this.HoraReclamacao; + if (!dataSinistro.HasValue) + { + shortTimeString1 = ""; + } + else + { + dataSinistro = this.HoraReclamacao; + if (dataSinistro.HasValue) + { + shortTimeString1 = dataSinistro.GetValueOrDefault().ToShortTimeString(); + } + else + { + shortTimeString1 = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("HORA DA RECLAMAÇÃO", shortTimeString1, "")); + dataSinistro = this.DataLiquidacao; + if (!dataSinistro.HasValue) + { + shortDateString1 = ""; + } + else + { + dataSinistro = this.DataLiquidacao; + if (dataSinistro.HasValue) + { + shortDateString1 = dataSinistro.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString1 = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("DATA DE LIQUIDAÇÃO", shortDateString1, "")); + Gestor.Model.Common.StatusSinistro? statusSinistro = this.StatusSinistro; + if (!statusSinistro.HasValue) + { + description1 = ""; + } + else + { + statusSinistro = this.StatusSinistro; + if (statusSinistro.HasValue) + { + description1 = statusSinistro.GetValueOrDefault().GetDescription(); + } + else + { + description1 = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("SITUAÇÃO", description1, "")); + decimal valor = this.Valor; + observableCollection.Add(new Tuple<string, string, string>("VALOR", valor.ToString(new CultureInfo("pt-BR")), "")); + valor = this.ValorOrcado; + observableCollection.Add(new Tuple<string, string, string>("VALOR ORÇADO", valor.ToString(new CultureInfo("pt-BR")), "")); + valor = this.ValorLiberado; + observableCollection.Add(new Tuple<string, string, string>("VALOR LIBERADO", valor.ToString(new CultureInfo("pt-BR")), "")); + valor = this.ValorPago; + observableCollection.Add(new Tuple<string, string, string>("VALOR PAGO", valor.ToString(new CultureInfo("pt-BR")), "")); + decimal? valorSalvado = this.ValorSalvado; + observableCollection.Add(new Tuple<string, string, string>("VALOR SALVADO", valorSalvado.ToString(), "")); + valor = this.ValorFranquia; + observableCollection.Add(new Tuple<string, string, string>("VALOR FRANQUIA", valor.ToString(new CultureInfo("pt-BR")), "")); + observableCollection.Add(new Tuple<string, string, string>("MOTIVO", (string.IsNullOrWhiteSpace(this.Motivo) ? "" : this.Motivo), "")); + observableCollection.Add(new Tuple<string, string, string>("AUXILIAR", (string.IsNullOrWhiteSpace(this.Auxiliar) ? "" : this.Auxiliar), "")); + observableCollection.Add(new Tuple<string, string, string>("DESCRIÇÃO", (string.IsNullOrWhiteSpace(this.Descricao) ? "" : this.Descricao), "")); + tupleList.Tuples = observableCollection; + tupleLists.Add(tupleList); + List<TupleList> tupleLists1 = tupleLists; + if (this.SinistroAuto != null) + { + ObservableCollection<Tuple<string, string, string>> tuples = tupleLists1[0].Tuples; + Gestor.Model.Domain.Seguros.SinistroAuto sinistroAuto = this.SinistroAuto; + if (sinistroAuto != null) + { + numeroBo = sinistroAuto.NumeroBo; + } + else + { + numeroBo = null; + } + if (string.IsNullOrWhiteSpace(numeroBo)) + { + numeroBo1 = ""; + } + else + { + Gestor.Model.Domain.Seguros.SinistroAuto sinistroAuto1 = this.SinistroAuto; + if (sinistroAuto1 != null) + { + numeroBo1 = sinistroAuto1.NumeroBo; + } + else + { + numeroBo1 = null; + } + } + tuples.Add(new Tuple<string, string, string>("NÚMERO DO B.O.", numeroBo1, "")); + ObservableCollection<Tuple<string, string, string>> tuples1 = tupleLists1[0].Tuples; + tipoPerda = this.SinistroAuto.TipoPerda; + if (!tipoPerda.HasValue) + { + description3 = ""; + } + else + { + Gestor.Model.Domain.Seguros.SinistroAuto sinistroAuto2 = this.SinistroAuto; + if (sinistroAuto2 != null) + { + tipoPerda = sinistroAuto2.TipoPerda; + if (tipoPerda.HasValue) + { + description3 = tipoPerda.GetValueOrDefault().GetDescription(); + } + else + { + description3 = null; + } + } + else + { + description3 = null; + } + } + tuples1.Add(new Tuple<string, string, string>("TIPO DE PERDA", description3, "")); + ObservableCollection<Tuple<string, string, string>> observableCollection1 = tupleLists1[0].Tuples; + culpado = this.SinistroAuto.Culpado; + if (culpado.HasValue) + { + Gestor.Model.Domain.Seguros.SinistroAuto sinistroAuto3 = this.SinistroAuto; + if (sinistroAuto3 != null) + { + culpado = sinistroAuto3.Culpado; + bool flag1 = false; + valueOrDefault = culpado.GetValueOrDefault() == flag1 & culpado.HasValue; + } + else + { + valueOrDefault = false; + } + if (valueOrDefault) + { + goto Label1; + } + str3 = "SIM"; + goto Label0; + } + Label1: + str3 = "NÃO"; + Label0: + observableCollection1.Add(new Tuple<string, string, string>("CONSIDERA-SE CULPADO?", str3, "")); + ObservableCollection<Tuple<string, string, string>> tuples2 = tupleLists1[0].Tuples; + dataSinistro = this.SinistroAuto.UltimoDocEnviado; + if (!dataSinistro.HasValue) + { + shortDateString2 = ""; + } + else + { + Gestor.Model.Domain.Seguros.SinistroAuto sinistroAuto4 = this.SinistroAuto; + if (sinistroAuto4 != null) + { + dataSinistro = sinistroAuto4.UltimoDocEnviado; + if (dataSinistro.HasValue) + { + shortDateString2 = dataSinistro.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString2 = null; + } + } + else + { + shortDateString2 = null; + } + } + tuples2.Add(new Tuple<string, string, string>("ÚLTIMO DOC. ENVIADO", shortDateString2, "")); + ObservableCollection<Tuple<string, string, string>> observableCollection2 = tupleLists1[0].Tuples; + Gestor.Model.Domain.Seguros.SinistroAuto sinistroAuto5 = this.SinistroAuto; + if (sinistroAuto5 != null) + { + endereco = sinistroAuto5.Endereco; + } + else + { + endereco = null; + } + if (string.IsNullOrWhiteSpace(endereco)) + { + endereco1 = ""; + } + else + { + Gestor.Model.Domain.Seguros.SinistroAuto sinistroAuto6 = this.SinistroAuto; + if (sinistroAuto6 != null) + { + endereco1 = sinistroAuto6.Endereco; + } + else + { + endereco1 = null; + } + } + observableCollection2.Add(new Tuple<string, string, string>("ENDEREÇO", endereco1, "")); + ObservableCollection<Tuple<string, string, string>> tuples3 = tupleLists1[0].Tuples; + Gestor.Model.Domain.Seguros.SinistroAuto sinistroAuto7 = this.SinistroAuto; + if (sinistroAuto7 != null) + { + envolvido = sinistroAuto7.Envolvido; + } + else + { + envolvido = null; + } + if (string.IsNullOrWhiteSpace(envolvido)) + { + envolvido1 = ""; + } + else + { + Gestor.Model.Domain.Seguros.SinistroAuto sinistroAuto8 = this.SinistroAuto; + if (sinistroAuto8 != null) + { + envolvido1 = sinistroAuto8.Envolvido; + } + else + { + envolvido1 = null; + } + } + tuples3.Add(new Tuple<string, string, string>("ENVOLVIDO/PROPRIETÁRIO", envolvido1, "")); + ObservableCollection<Tuple<string, string, string>> observableCollection3 = tupleLists1[0].Tuples; + Gestor.Model.Domain.Seguros.SinistroAuto sinistroAuto9 = this.SinistroAuto; + if (sinistroAuto9 != null) + { + motorista = sinistroAuto9.Motorista; + } + else + { + motorista = null; + } + if (string.IsNullOrWhiteSpace(motorista)) + { + motorista1 = ""; + } + else + { + Gestor.Model.Domain.Seguros.SinistroAuto sinistroAuto10 = this.SinistroAuto; + if (sinistroAuto10 != null) + { + motorista1 = sinistroAuto10.Motorista; + } + else + { + motorista1 = null; + } + } + observableCollection3.Add(new Tuple<string, string, string>("MOTORISTA", motorista1, "")); + ObservableCollection<Tuple<string, string, string>> tuples4 = tupleLists1[0].Tuples; + Gestor.Model.Domain.Seguros.SinistroAuto sinistroAuto11 = this.SinistroAuto; + if (sinistroAuto11 != null) + { + ddd = sinistroAuto11.Ddd; + } + else + { + ddd = null; + } + if (string.IsNullOrWhiteSpace(ddd)) + { + ddd1 = ""; + } + else + { + Gestor.Model.Domain.Seguros.SinistroAuto sinistroAuto12 = this.SinistroAuto; + if (sinistroAuto12 != null) + { + ddd1 = sinistroAuto12.Ddd; + } + else + { + ddd1 = null; + } + } + tuples4.Add(new Tuple<string, string, string>("DDD", ddd1, "")); + ObservableCollection<Tuple<string, string, string>> observableCollection4 = tupleLists1[0].Tuples; + Gestor.Model.Domain.Seguros.SinistroAuto sinistroAuto13 = this.SinistroAuto; + if (sinistroAuto13 != null) + { + telefone = sinistroAuto13.Telefone; + } + else + { + telefone = null; + } + if (string.IsNullOrWhiteSpace(telefone)) + { + telefone1 = ""; + } + else + { + Gestor.Model.Domain.Seguros.SinistroAuto sinistroAuto14 = this.SinistroAuto; + if (sinistroAuto14 != null) + { + telefone1 = sinistroAuto14.Telefone; + } + else + { + telefone1 = null; + } + } + observableCollection4.Add(new Tuple<string, string, string>("TELEFONE", telefone1, "")); + ObservableCollection<Tuple<string, string, string>> tuples5 = tupleLists1[0].Tuples; + Gestor.Model.Domain.Seguros.SinistroAuto sinistroAuto15 = this.SinistroAuto; + if (sinistroAuto15 != null) + { + email = sinistroAuto15.Email; + } + else + { + email = null; + } + if (string.IsNullOrWhiteSpace(email)) + { + email1 = ""; + } + else + { + Gestor.Model.Domain.Seguros.SinistroAuto sinistroAuto16 = this.SinistroAuto; + if (sinistroAuto16 != null) + { + email1 = sinistroAuto16.Email; + } + else + { + email1 = null; + } + } + tuples5.Add(new Tuple<string, string, string>("E-MAIL", email1, "")); + ObservableCollection<Tuple<string, string, string>> observableCollection5 = tupleLists1[0].Tuples; + Gestor.Model.Domain.Seguros.SinistroAuto sinistroAuto17 = this.SinistroAuto; + if (sinistroAuto17 != null) + { + valor = sinistroAuto17.ValorMecanica; + str4 = valor.ToString(new CultureInfo("pt-BR")); + } + else + { + str4 = null; + } + observableCollection5.Add(new Tuple<string, string, string>("VALOR MECÂNICA", str4, "")); + ObservableCollection<Tuple<string, string, string>> tuples6 = tupleLists1[0].Tuples; + Gestor.Model.Domain.Seguros.SinistroAuto sinistroAuto18 = this.SinistroAuto; + if (sinistroAuto18 != null) + { + parceiroMecanica = sinistroAuto18.ParceiroMecanica; + } + else + { + parceiroMecanica = false; + } + if (!parceiroMecanica) + { + nome = ""; + } + else + { + Gestor.Model.Domain.Seguros.SinistroAuto sinistroAuto19 = this.SinistroAuto; + if (sinistroAuto19 != null) + { + Parceiro parceiro = sinistroAuto19.ParceiroMecanica; + if (parceiro != null) + { + nome = parceiro.Nome; + } + else + { + nome = null; + } + } + else + { + nome = null; + } + } + tuples6.Add(new Tuple<string, string, string>("PARCEIRO MECÂNICA", nome, "")); + ObservableCollection<Tuple<string, string, string>> observableCollection6 = tupleLists1[0].Tuples; + Gestor.Model.Domain.Seguros.SinistroAuto sinistroAuto20 = this.SinistroAuto; + if (sinistroAuto20 != null) + { + valor = sinistroAuto20.ValorFunilaria; + str5 = valor.ToString(new CultureInfo("pt-BR")); + } + else + { + str5 = null; + } + observableCollection6.Add(new Tuple<string, string, string>("VALOR FUNILARIA", str5, "")); + ObservableCollection<Tuple<string, string, string>> tuples7 = tupleLists1[0].Tuples; + Gestor.Model.Domain.Seguros.SinistroAuto sinistroAuto21 = this.SinistroAuto; + if (sinistroAuto21 != null) + { + parceiroFunilaria = sinistroAuto21.ParceiroFunilaria; + } + else + { + parceiroFunilaria = false; + } + if (!parceiroFunilaria) + { + nome1 = ""; + } + else + { + Gestor.Model.Domain.Seguros.SinistroAuto sinistroAuto22 = this.SinistroAuto; + if (sinistroAuto22 != null) + { + Parceiro parceiroFunilaria1 = sinistroAuto22.ParceiroFunilaria; + if (parceiroFunilaria1 != null) + { + nome1 = parceiroFunilaria1.Nome; + } + else + { + nome1 = null; + } + } + else + { + nome1 = null; + } + } + tuples7.Add(new Tuple<string, string, string>("PARCEIRO FUNILARIA", nome1, "")); + } + if (this.SinistroVida != null) + { + ObservableCollection<Tuple<string, string, string>> observableCollection7 = tupleLists1[0].Tuples; + Gestor.Model.Domain.Seguros.SinistroVida sinistroVida = this.SinistroVida; + if (sinistroVida != null) + { + tipoPerda = sinistroVida.TipoPerda; + hasValue = !tipoPerda.HasValue; + } + else + { + hasValue = true; + } + if (hasValue) + { + str1 = ""; + } + else + { + Gestor.Model.Domain.Seguros.SinistroVida sinistroVida1 = this.SinistroVida; + if (sinistroVida1 != null) + { + tipoPerda = sinistroVida1.TipoPerda; + if (tipoPerda.HasValue) + { + str1 = tipoPerda.GetValueOrDefault().GetDescription(); + } + else + { + str1 = null; + } + } + else + { + str1 = null; + } + } + observableCollection7.Add(new Tuple<string, string, string>("TIPO DE PERDA", str1, "")); + ObservableCollection<Tuple<string, string, string>> tuples8 = tupleLists1[0].Tuples; + Gestor.Model.Domain.Seguros.SinistroVida sinistroVida2 = this.SinistroVida; + if (sinistroVida2 != null) + { + culpado = sinistroVida2.AuxFuneral; + flag = !culpado.HasValue; + } + else + { + flag = true; + } + if (flag) + { + str2 = ""; + } + else + { + Gestor.Model.Domain.Seguros.SinistroVida sinistroVida3 = this.SinistroVida; + if (sinistroVida3 != null) + { + culpado = sinistroVida3.AuxFuneral; + nullable = new bool?(culpado.Value); + } + else + { + culpado = null; + nullable = culpado; + } + culpado = nullable; + str2 = (culpado.Value ? "SIM" : "NÃO"); + } + tuples8.Add(new Tuple<string, string, string>("AUXÍLIO FUNERAL", str2, "")); + ObservableCollection<Tuple<string, string, string>> observableCollection8 = tupleLists1[0].Tuples; + Gestor.Model.Domain.Seguros.SinistroVida sinistroVida4 = this.SinistroVida; + if (sinistroVida4 != null) + { + estadoCivil = sinistroVida4.EstadoCivil; + hasValue1 = !estadoCivil.HasValue; + } + else + { + hasValue1 = true; + } + if (hasValue1) + { + description2 = ""; + } + else + { + Gestor.Model.Domain.Seguros.SinistroVida sinistroVida5 = this.SinistroVida; + if (sinistroVida5 != null) + { + estadoCivil = sinistroVida5.EstadoCivil; + if (estadoCivil.HasValue) + { + description2 = estadoCivil.GetValueOrDefault().GetDescription(); + } + else + { + description2 = null; + } + } + else + { + description2 = null; + } + } + observableCollection8.Add(new Tuple<string, string, string>("ESTADO CIVIL", description2, "")); + ObservableCollection<Tuple<string, string, string>> tuples9 = tupleLists1[0].Tuples; + Gestor.Model.Domain.Seguros.SinistroVida sinistroVida6 = this.SinistroVida; + if (sinistroVida6 != null) + { + certObito = sinistroVida6.CertObito; + } + else + { + certObito = null; + } + if (string.IsNullOrWhiteSpace(certObito)) + { + certObito1 = ""; + } + else + { + Gestor.Model.Domain.Seguros.SinistroVida sinistroVida7 = this.SinistroVida; + if (sinistroVida7 != null) + { + certObito1 = sinistroVida7.CertObito; + } + else + { + certObito1 = null; + } + } + tuples9.Add(new Tuple<string, string, string>("CERTIDÃO DE ÓBITO", certObito1, "")); + ObservableCollection<Tuple<string, string, string>> observableCollection9 = tupleLists1[0].Tuples; + Gestor.Model.Domain.Seguros.SinistroVida sinistroVida8 = this.SinistroVida; + if (sinistroVida8 != null) + { + beneficiario = sinistroVida8.Beneficiario; + } + else + { + beneficiario = null; + } + if (string.IsNullOrWhiteSpace(beneficiario)) + { + beneficiario1 = ""; + } + else + { + Gestor.Model.Domain.Seguros.SinistroVida sinistroVida9 = this.SinistroVida; + if (sinistroVida9 != null) + { + beneficiario1 = sinistroVida9.Beneficiario; + } + else + { + beneficiario1 = null; + } + } + observableCollection9.Add(new Tuple<string, string, string>("BENEFICIÁRIO", beneficiario1, "")); + } + return tupleLists1; + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (this.DataReclamacao.HasValue && (DateTime.Compare(this.DataReclamacao.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.DataReclamacao.Value, new DateTime(9999, 12, 31)) > 0)) + { + keyValuePairs.AddValue<string, string>("DataReclamacao", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + if (this.HoraReclamacao.HasValue && (DateTime.Compare(this.HoraReclamacao.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.HoraReclamacao.Value, new DateTime(9999, 12, 31)) > 0)) + { + keyValuePairs.AddValue<string, string>("HoraReclamacao", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + if (this.DataLiquidacao.HasValue && (DateTime.Compare(this.DataLiquidacao.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.DataLiquidacao.Value, new DateTime(9999, 12, 31)) > 0)) + { + keyValuePairs.AddValue<string, string>("DataLiquidacao", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + if (this.ControleSinistro != null) + { + keyValuePairs.AddRange(this.ControleSinistro.Validate()); + } + if (!this.DataReclamacao.HasValue) + { + keyValuePairs.AddValue<string, string>("DataReclamacao", Messages.Obrigatorio, true); + } + if (this.StatusSinistro.GetValueOrDefault() != Gestor.Model.Common.StatusSinistro.EmAndamento && !this.DataLiquidacao.HasValue) + { + keyValuePairs.AddValue<string, string>("DataLiquidacao", Messages.Obrigatorio, true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/SinistroAuto.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/SinistroAuto.cs new file mode 100644 index 0000000..65cc4cd --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/SinistroAuto.cs @@ -0,0 +1,284 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class SinistroAuto : DomainBase, IDomain + { + private string _numeroBo; + + private string _endereco; + + private string _envolvido; + + private string _motorista; + + private string _ddd; + + private string _telefone; + + private string _email; + + private string _cnh; + + [Log(true)] + [Name(true)] + public string Cnh + { + get + { + string str = this._cnh; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._cnh = value; + } + } + + [Description("DECLARA-SE CULPADO")] + [Log(true)] + [Name(true)] + public bool? Culpado + { + get; + set; + } + + [Description("PREFIXO")] + [Log(true)] + [Name(true)] + public string Ddd + { + get + { + string str = this._ddd; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._ddd = value; + } + } + + [Description("E-MAIL")] + [Log(true)] + [Name(true)] + public string Email + { + get + { + string str = this._email; + if (str == null) + { + return null; + } + return str.ToLower().Trim(); + } + set + { + this._email = value; + } + } + + [Description("ENDEREÇO")] + [Log(true)] + [Name(true)] + public string Endereco + { + get + { + string str = this._endereco; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._endereco = value; + } + } + + [Log(true)] + [Name(true)] + public string Envolvido + { + get + { + string str = this._envolvido; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._envolvido = value; + } + } + + [Log(true)] + [Name(true)] + public string Motorista + { + get + { + string str = this._motorista; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._motorista = value; + } + } + + [Description("NUMERO B.O.")] + [Log(true)] + [Name(true)] + public string NumeroBo + { + get + { + string str = this._numeroBo; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._numeroBo = value; + } + } + + [Description("FUNILARIA")] + [Log(true)] + public Parceiro ParceiroFunilaria + { + get; + set; + } + + [Description("MECÂNICA")] + [Log(true)] + public Parceiro ParceiroMecanica + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Sinistro Sinistro + { + get; + set; + } + + [Description("TELEFONE")] + [Log(true)] + [Name(true)] + public string Telefone + { + get + { + string str = this._telefone; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._telefone = value; + } + } + + [Description("TIPO PERDA")] + [Log(true)] + [Name(true)] + public Gestor.Model.Common.TipoPerda? TipoPerda + { + get; + set; + } + + [Description("DATA ÚLTIMO DOC. ENVIADO")] + [Log(true)] + [Name(true)] + public DateTime? UltimoDocEnviado + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + SinistroAuto sinistroAuto = this; + return new Func<List<KeyValuePair<string, string>>>(sinistroAuto.Validate); + } + } + + [Description("VALOR FINILARIA")] + [Log(true)] + [Name(true)] + public decimal ValorFunilaria + { + get; + set; + } + + [Description("VALOR MECÂNICA")] + [Log(true)] + [Name(true)] + public decimal ValorMecanica + { + get; + set; + } + + public SinistroAuto() + { + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (this.Sinistro != null) + { + keyValuePairs.AddRange(this.Sinistro.Validate()); + } + if (this.UltimoDocEnviado.HasValue && (DateTime.Compare(this.UltimoDocEnviado.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.UltimoDocEnviado.Value, new DateTime(9999, 12, 31)) > 0)) + { + keyValuePairs.AddValue<string, string>("UltimoDocEnviado", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/SinistroVida.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/SinistroVida.cs new file mode 100644 index 0000000..bdd167c --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/SinistroVida.cs @@ -0,0 +1,138 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class SinistroVida : DomainBase, IDomain + { + private string _certObito; + + private string _beneficiario; + + private string _observacao; + + [Description("AUXÍLIO FUNERAL")] + [Log(true)] + [Name(true)] + public bool? AuxFuneral + { + get; + set; + } + + [Description("BENEFICIÁRIO")] + [Log(true)] + [Name(true)] + public string Beneficiario + { + get + { + string str = this._beneficiario; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._beneficiario = value; + } + } + + [Description("CERT. ÓBITO")] + [Log(true)] + [Name(true)] + public string CertObito + { + get + { + string str = this._certObito; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._certObito = value; + } + } + + [Description("ESTADO CÍVIL")] + [Log(true)] + [Name(true)] + public Gestor.Model.Common.EstadoCivil? EstadoCivil + { + get; + set; + } + + [Description("OBSERVAÇÃO")] + [Log(true)] + [Name(true)] + public string Observacao + { + get + { + string str = this._observacao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._observacao = value; + } + } + + public Gestor.Model.Domain.Seguros.Sinistro Sinistro + { + get; + set; + } + + [Description("TIPO PERDA")] + [Log(true)] + [Name(true)] + public Gestor.Model.Common.TipoPerda? TipoPerda + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + SinistroVida sinistroVida = this; + return new Func<List<KeyValuePair<string, string>>>(sinistroVida.Validate); + } + } + + public SinistroVida() + { + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (this.Sinistro != null) + { + keyValuePairs.AddRange(this.Sinistro.Validate()); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/Status.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/Status.cs new file mode 100644 index 0000000..3649416 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/Status.cs @@ -0,0 +1,86 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class Status : DomainBase, IDomain + { + private string _nome; + + [Log(true)] + public bool Ativo + { + get; + set; + } + + [Log(true)] + [Name(true)] + public string Nome + { + get + { + string str = this._nome; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._nome = value; + } + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Status statu = this; + return new Func<List<KeyValuePair<string, string>>>(statu.Validate); + } + } + + public Status() + { + } + + public List<TupleList> Log() + { + return new List<TupleList>() + { + new TupleList() + { + Tuples = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("NOME", (string.IsNullOrWhiteSpace(this.Nome) ? "" : this.Nome), ""), + new Tuple<string, string, string>("ATIVO", (this.Ativo ? "SIM" : "NÃO"), "") + } + } + }; + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (string.IsNullOrWhiteSpace(this.Nome)) + { + keyValuePairs.AddValue<string, string>("Nome", Messages.Obrigatorio, true); + } + else if (this.Nome.Length > 60) + { + keyValuePairs.AddValue<string, string>("Nome", string.Format(Messages.MaiorQueLimite, 60), true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/TipoVendedor.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/TipoVendedor.cs new file mode 100644 index 0000000..47d2048 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/TipoVendedor.cs @@ -0,0 +1,138 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Gestor.Model.Domain.Seguros +{ + public class TipoVendedor : DomainBase, IDomain + { + private bool _selecionado; + + private string _descricao; + + private bool? _ativo; + + [Log(true)] + public bool? Ativo + { + get + { + return this._ativo; + } + set + { + this._ativo = new bool?(value.GetValueOrDefault(true)); + } + } + + [Description("DESCRIÇÃO")] + [Log(true)] + [Name(true)] + public string Descricao + { + get + { + string str = this._descricao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._descricao = value; + } + } + + public bool? Inserido + { + get; + set; + } + + public bool Selecionado + { + get + { + return this._selecionado; + } + set + { + if (value == this._selecionado) + { + return; + } + this._selecionado = value; + this.OnPropertyChanged("Selecionado"); + } + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + TipoVendedor tipoVendedor = this; + return new Func<List<KeyValuePair<string, string>>>(tipoVendedor.Validate); + } + } + + public TipoVendedor() + { + } + + public List<TupleList> Log() + { + string str; + List<TupleList> tupleLists = new List<TupleList>(); + TupleList tupleList = new TupleList(); + ObservableCollection<Tuple<string, string, string>> observableCollection = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("DESCRIÇÃO", (string.IsNullOrWhiteSpace(this.Descricao) ? "" : this.Descricao), "") + }; + if (!this.Ativo.HasValue) + { + str = ""; + } + else + { + str = (this.Ativo.Value ? "SIM" : "NÃO"); + } + observableCollection.Add(new Tuple<string, string, string>("ATIVO", str, "")); + tupleList.Tuples = observableCollection; + tupleLists.Add(tupleList); + return tupleLists; + } + + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChangedEventHandler propertyChangedEventHandler = this.PropertyChanged; + if (propertyChangedEventHandler == null) + { + return; + } + propertyChangedEventHandler(this, new PropertyChangedEventArgs(propertyName)); + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (string.IsNullOrWhiteSpace(this.Descricao)) + { + keyValuePairs.AddValue<string, string>("Descricao", Messages.Obrigatorio, true); + } + return keyValuePairs; + } + + public event PropertyChangedEventHandler PropertyChanged; + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/TitularesVida.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/TitularesVida.cs new file mode 100644 index 0000000..3956270 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/TitularesVida.cs @@ -0,0 +1,269 @@ +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Gestor.Model.Validation; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Gestor.Model.Domain.Seguros +{ + public class TitularesVida : DomainBase, IDomain, INotifyPropertyChanged + { + private string _codigo; + + private string _fatura; + + private string _nome; + + private string _observacao; + + private string _matricula; + + private decimal? _premio; + + private decimal? _capital; + + private bool _selecionado; + + public decimal? Capital + { + get + { + return new decimal?(this._capital.GetValueOrDefault()); + } + set + { + this._capital = value; + } + } + + public string Codigo + { + get + { + string str = this._codigo; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._codigo = value; + } + } + + public string Cpf + { + get; + set; + } + + public TitularesVida Dependente + { + get; + set; + } + + public string Fatura + { + get + { + string str = this._fatura; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._fatura = value; + } + } + + public DateTime? Fim + { + get; + set; + } + + public long IdItem + { + get; + set; + } + + public DateTime? Inicio + { + get; + set; + } + + public string Matricula + { + get + { + string str = this._matricula; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._matricula = value; + } + } + + public DateTime? Nascimento + { + get; + set; + } + + public string Nome + { + get + { + string str = this._nome; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._nome = value; + } + } + + public string Observacao + { + get + { + string str = this._observacao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._observacao = value; + } + } + + public decimal? Premio + { + get + { + return new decimal?(this._premio.GetValueOrDefault()); + } + set + { + this._premio = value; + } + } + + public bool Selecionado + { + get + { + return this._selecionado; + } + set + { + if (value == this._selecionado) + { + return; + } + this._selecionado = value; + this.OnPropertyChanged("Selecionado"); + } + } + + public TipoTitular? Tipo + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + TitularesVida titularesVida = this; + return new Func<List<KeyValuePair<string, string>>>(titularesVida.Validate); + } + } + + public TitularesVida() + { + } + + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChangedEventHandler propertyChangedEventHandler = this.PropertyChanged; + if (propertyChangedEventHandler == null) + { + return; + } + propertyChangedEventHandler(this, new PropertyChangedEventArgs(propertyName)); + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (string.IsNullOrWhiteSpace(this.Nome)) + { + keyValuePairs.AddValue<string, string>("Nome", Messages.Obrigatorio, true); + } + else if (this.Nome.Length > 150) + { + keyValuePairs.AddValue<string, string>("Nome", string.Format(Messages.MaiorQueLimite, 150), true); + } + if (!this.Inicio.HasValue) + { + keyValuePairs.AddValue<string, string>("Inicio|INÍCIO", Messages.Obrigatorio, true); + } + else if (DateTime.Compare(this.Inicio.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.Inicio.Value, new DateTime(9999, 12, 31)) > 0) + { + keyValuePairs.AddValue<string, string>("Inicio|INÍCIO", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + if (this.Fim.HasValue && (DateTime.Compare(this.Fim.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.Fim.Value, new DateTime(9999, 12, 31)) > 0)) + { + keyValuePairs.AddValue<string, string>("Fim", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + if (this.Nascimento.HasValue && (DateTime.Compare(this.Nascimento.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.Nascimento.Value, new DateTime(9999, 12, 31)) > 0)) + { + keyValuePairs.AddValue<string, string>("Nascimento", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + if ((!this.Nascimento.HasValue || Funcoes.GetAge(this.Nascimento.Value) >= 18) && !string.IsNullOrWhiteSpace(this.Cpf) && !this.Cpf.ValidacaoDocumento()) + { + keyValuePairs.AddValue<string, string>("Cpf", Messages.Invalido, true); + } + if (!this.Tipo.HasValue) + { + keyValuePairs.AddValue<string, string>("Tipo", Messages.Obrigatorio, true); + } + if (this.Tipo.GetValueOrDefault() == TipoTitular.Dependente && this.Dependente == null) + { + keyValuePairs.AddValue<string, string>("Dependente", "OBRIGATÓRIO. PESQUISE POR UM DOS TITULARES\nQUE SEJA DO TIPO SÓCIO OU FUNCIONÁRIO", true); + } + return keyValuePairs; + } + + public event PropertyChangedEventHandler PropertyChanged; + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/TupleList.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/TupleList.cs new file mode 100644 index 0000000..406b072 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/TupleList.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.ObjectModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class TupleList + { + public ObservableCollection<Tuple<string, string, string>> Tuples + { + get; + set; + } + + public TupleList() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/Usuario.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/Usuario.cs new file mode 100644 index 0000000..39c6cc1 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/Usuario.cs @@ -0,0 +1,872 @@ +using Gestor.Model.API; +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Gestor.Model.Validation; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using System.Text.RegularExpressions; + +namespace Gestor.Model.Domain.Seguros +{ + public class Usuario : EnderecoBase, IDomain + { + private string _nome; + + private string _prefixo; + + private string _telefone; + + private string _prefixo2; + + private string _telefone2; + + private string _email; + + private string _documento; + + private string _identidade; + + private string _estadoEmissor; + + private string _agencia; + + private string _conta; + + private string _login; + + private bool? _segunda; + + private bool? _terca; + + private bool? _quarta; + + private bool? _quinta; + + private bool? _sexta; + + private bool? _sabado; + + private bool? _domingo; + + private bool? _dashboard; + + private TipoTelaInicial? _telaInicial; + + [Log(true)] + public bool Administrador + { + get; + set; + } + + [Description("PERMISSÃO ADMINISTRADOR CENTRAL SEGURADO")] + [Log(true)] + public bool AdministradorCentralSegurado + { + get; + set; + } + + [Description("AGÊNCIA")] + [Log(true)] + public string Agencia + { + get + { + string str = this._agencia; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._agencia = value; + } + } + + public bool Aggilizador + { + get; + set; + } + + [Log(true)] + public Gestor.Model.Domain.Common.Banco Banco + { + get; + set; + } + + [Log(true)] + public string Cargo + { + get; + set; + } + + [Log(true)] + public string Conta + { + get + { + string str = this._conta; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._conta = value; + } + } + + [Description("ACESSO AO DASHBOARD")] + [Log(true)] + public bool? Dashboard + { + get + { + return this._dashboard; + } + set + { + this._dashboard = new bool?(value.GetValueOrDefault(true)); + } + } + + [Log(true)] + public string Documento + { + get + { + string str = this._documento; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._documento = value; + } + } + + [Description("ACESSO AOS DOMINGOS")] + [Log(true)] + public bool? Domingo + { + get + { + return this._domingo; + } + set + { + this._domingo = new bool?(value.GetValueOrDefault(true)); + } + } + + [Log(true)] + public string Email + { + get + { + string str = this._email; + if (str == null) + { + return null; + } + return str.ToLower().Trim(); + } + set + { + this._email = value; + } + } + + [Description("ESTADO EMISSOR")] + [Log(true)] + public string EstadoEmissor + { + get + { + string str = this._estadoEmissor; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._estadoEmissor = value; + } + } + + public bool Excluido + { + get; + set; + } + + [Description("DATA DE EXPEDIÇÃO")] + [Log(true)] + public DateTime? Expedicao + { + get; + set; + } + + [Description("FILTRO INICIAL")] + [Log(true)] + public TipoFiltroCliente? FiltroInicial + { + get; + set; + } + + [Description("FIM DO ACESSO")] + public DateTime? FimAcesso + { + get; + set; + } + + public long IdEmpresa + { + get; + set; + } + + [Log(true)] + public string Identidade + { + get + { + string str = this._identidade; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._identidade = value; + } + } + + [Description("INÍCIO DO ACESSO")] + public DateTime? InicioAcesso + { + get; + set; + } + + [Log(true)] + public string Login + { + get + { + string str = this._login; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._login = value; + } + } + + [Description("ACESSO AO MOBILE")] + [Log(true)] + public bool Mobile + { + get; + set; + } + + [Description("DATA DE NASCIMENTO")] + [Log(true)] + public DateTime? Nascimento + { + get; + set; + } + + [Log(true)] + [Name(true)] + public string Nome + { + get + { + return this._nome; + } + set + { + this._nome = value; + } + } + + [Description("PERMISSÃO ACESSO AGGILIZADOR")] + [Log(true)] + public long? PermissaoAggilizador + { + get; + set; + } + + [Description("PREFIXO TELEFONE 1")] + [Log(true)] + public string Prefixo + { + get + { + string str = this._prefixo; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._prefixo = value; + } + } + + [Description("PREFIXO TELEFONE 2")] + [Log(true)] + public string Prefixo2 + { + get + { + string str = this._prefixo2; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._prefixo2 = value; + } + } + + [Description("ACESSO ÁS QUARTAS-FEIRAS")] + [Log(true)] + public bool? Quarta + { + get + { + return this._quarta; + } + set + { + this._quarta = new bool?(value.GetValueOrDefault(true)); + } + } + + [Description("ACESSO ÁS QUINTAS-FEIRAS")] + [Log(true)] + public bool? Quinta + { + get + { + return this._quinta; + } + set + { + this._quinta = new bool?(value.GetValueOrDefault(true)); + } + } + + [Description("ACESSO AOS RESULTADOS MOBILE")] + [Log(true)] + public bool Resultados + { + get; + set; + } + + [Description("ACESSO AOS SÁBADOS")] + [Log(true)] + public bool? Sabado + { + get + { + return this._sabado; + } + set + { + this._sabado = new bool?(value.GetValueOrDefault(true)); + } + } + + [Description("ACESSO ÀS SEGUNDAS-FEIRAS")] + [Log(true)] + public bool? Segunda + { + get + { + return this._segunda; + } + set + { + this._segunda = new bool?(value.GetValueOrDefault(true)); + } + } + + public bool Selecionado + { + get; + set; + } + + public string Senha + { + get; + set; + } + + public string SenhaAnterior { get; set; } = string.Empty; + + [Log(true)] + public Gestor.Model.Common.Sexo Sexo + { + get; + set; + } + + [Description("ACESSO ÁS SEXTAS-FEIRAS")] + [Log(true)] + public bool? Sexta + { + get + { + return this._sexta; + } + set + { + this._sexta = new bool?(value.GetValueOrDefault(true)); + } + } + + public string SsoId + { + get; + set; + } + + [Log(true)] + public TipoTelaInicial? TelaInicial + { + get + { + return new TipoTelaInicial?(this._telaInicial.GetValueOrDefault()); + } + set + { + this._telaInicial = new TipoTelaInicial?(value.GetValueOrDefault()); + } + } + + [Description("TELEFONE 1")] + [Log(true)] + public string Telefone + { + get + { + string str = this._telefone; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._telefone = value; + } + } + + [Description("TELEFONE 2")] + [Log(true)] + public string Telefone2 + { + get + { + string str = this._telefone2; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._telefone2 = value; + } + } + + [Description("ACESSO ÀS TERÇAS-FEIRAS")] + [Log(true)] + public bool? Terca + { + get + { + return this._terca; + } + set + { + this._terca = new bool?(value.GetValueOrDefault(true)); + } + } + + [Description("TIPO DO TELEFONE 1")] + [Log(true)] + public Gestor.Model.Common.TipoTelefone? TipoTelefone + { + get; + set; + } + + [Description("TIPO DO TELEFONE 2")] + [Log(true)] + public Gestor.Model.Common.TipoTelefone? TipoTelefone2 + { + get; + set; + } + + public string TokenSso + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Usuario usuario = this; + return new Func<List<KeyValuePair<string, string>>>(usuario.Validate); + } + } + + public string Visita + { + get; + set; + } + + public Usuario() + { + } + + public List<TupleList> Log() + { + string shortDateString; + string str; + string nome; + string shortTimeString; + string shortTimeString1; + List<TupleList> tupleLists = new List<TupleList>(); + TupleList tupleList = new TupleList(); + ObservableCollection<Tuple<string, string, string>> observableCollection = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("NOME", (string.IsNullOrWhiteSpace(this.Nome) ? "" : this.Nome), ""), + new Tuple<string, string, string>("CPF/CNPJ", (string.IsNullOrWhiteSpace(this.Documento) ? "" : this.Documento), ""), + new Tuple<string, string, string>("USUÁRIO", (string.IsNullOrWhiteSpace(this.Login) ? "" : this.Login), ""), + new Tuple<string, string, string>("IDENTIDADE", (string.IsNullOrWhiteSpace(this.Identidade) ? "" : this.Identidade), ""), + new Tuple<string, string, string>("ESTADO EMISSOR", (string.IsNullOrWhiteSpace(this.EstadoEmissor) ? "" : this.EstadoEmissor), "") + }; + DateTime? expedicao = this.Expedicao; + if (!expedicao.HasValue) + { + shortDateString = ""; + } + else + { + expedicao = this.Expedicao; + if (expedicao.HasValue) + { + shortDateString = expedicao.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("DATA DE EXPEDIÇÃO", shortDateString, "")); + observableCollection.Add(new Tuple<string, string, string>("SEXO", this.Sexo.GetDescription(), "")); + expedicao = this.Nascimento; + if (!expedicao.HasValue) + { + str = ""; + } + else + { + expedicao = this.Nascimento; + if (expedicao.HasValue) + { + str = expedicao.GetValueOrDefault().ToShortDateString(); + } + else + { + str = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("DATA DE NASCIMENTO", str, "")); + if (this.Banco == null) + { + nome = ""; + } + else + { + Gestor.Model.Domain.Common.Banco banco = this.Banco; + if (banco != null) + { + nome = banco.Nome; + } + else + { + nome = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("BANCO", nome, "")); + observableCollection.Add(new Tuple<string, string, string>("AGÊNCIA", (string.IsNullOrWhiteSpace(this.Agencia) ? "" : this.Agencia), "")); + observableCollection.Add(new Tuple<string, string, string>("CONTA", (string.IsNullOrWhiteSpace(this.Conta) ? "" : this.Conta), "")); + observableCollection.Add(new Tuple<string, string, string>("ENDEREÇO", (string.IsNullOrWhiteSpace(base.Endereco) ? "" : base.Endereco), "")); + observableCollection.Add(new Tuple<string, string, string>("NÚMERO", (string.IsNullOrWhiteSpace(base.Numero) ? "" : base.Numero), "")); + observableCollection.Add(new Tuple<string, string, string>("COMPLEMENTO", (string.IsNullOrWhiteSpace(base.Complemento) ? "" : base.Complemento), "")); + observableCollection.Add(new Tuple<string, string, string>("BAIRRO", (string.IsNullOrWhiteSpace(base.Bairro) ? "" : base.Bairro), "")); + observableCollection.Add(new Tuple<string, string, string>("CIDADE", (string.IsNullOrWhiteSpace(base.Cidade) ? "" : base.Cidade), "")); + observableCollection.Add(new Tuple<string, string, string>("ESTADO", (string.IsNullOrWhiteSpace(base.Estado) ? "" : base.Estado), "")); + observableCollection.Add(new Tuple<string, string, string>("CEP", (string.IsNullOrWhiteSpace(base.Cep) ? "" : base.Cep), "")); + observableCollection.Add(new Tuple<string, string, string>("TIPO TELEFONE", (!this.TipoTelefone.HasValue ? "" : this.TipoTelefone.GetDescription()), "")); + observableCollection.Add(new Tuple<string, string, string>("PRIMEIRO PREFIXO", (string.IsNullOrWhiteSpace(this.Prefixo) ? "" : this.Prefixo), "")); + observableCollection.Add(new Tuple<string, string, string>("PRIMEIRO TELEFONE", (string.IsNullOrWhiteSpace(this.Telefone) ? "" : this.Telefone), "")); + observableCollection.Add(new Tuple<string, string, string>("TIPO TELEFONE", (!this.TipoTelefone2.HasValue ? "" : this.TipoTelefone2.GetDescription()), "")); + observableCollection.Add(new Tuple<string, string, string>("SEGUNDO PREFIXO", (string.IsNullOrWhiteSpace(this.Prefixo2) ? "" : this.Prefixo2), "")); + observableCollection.Add(new Tuple<string, string, string>("SEGUNDO TELEFONE", (string.IsNullOrWhiteSpace(this.Telefone2) ? "" : this.Telefone2), "")); + observableCollection.Add(new Tuple<string, string, string>("EMAIL", (string.IsNullOrWhiteSpace(this.Email) ? "" : this.Email), "")); + observableCollection.Add(new Tuple<string, string, string>("ACESSO MOBILE", (this.Mobile ? "SIM" : "NÃO"), "")); + observableCollection.Add(new Tuple<string, string, string>("ACESSO RESULTADOS", (this.Resultados ? "SIM" : "NÃO"), "")); + observableCollection.Add(new Tuple<string, string, string>("ACESSO INDIVIDUAL AGGILIZADOR", (this.Aggilizador ? "SIM" : "NÃO"), "")); + expedicao = this.InicioAcesso; + if (!expedicao.HasValue) + { + shortTimeString = ""; + } + else + { + expedicao = this.InicioAcesso; + if (expedicao.HasValue) + { + shortTimeString = expedicao.GetValueOrDefault().ToShortTimeString(); + } + else + { + shortTimeString = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("INÍCIO DO ACESSO", shortTimeString, "")); + expedicao = this.FimAcesso; + if (!expedicao.HasValue) + { + shortTimeString1 = ""; + } + else + { + expedicao = this.FimAcesso; + if (expedicao.HasValue) + { + shortTimeString1 = expedicao.GetValueOrDefault().ToShortTimeString(); + } + else + { + shortTimeString1 = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("FIM DO ACESSO", shortTimeString1, "")); + observableCollection.Add(new Tuple<string, string, string>("ADMINISTRADOR CENTRAL SEGURADO", (this.AdministradorCentralSegurado ? "SIM" : "NÃO"), "")); + tupleList.Tuples = observableCollection; + tupleLists.Add(tupleList); + return tupleLists; + } + + public UserSso ToUserSso(string serial, string documentoEmpresa, string ssoId = null) + { + return new UserSso() + { + Id = ssoId, + Name = this.Nome, + Username = this.Login, + Password = this.Senha, + Serial = serial, + CustomerDocument = documentoEmpresa, + IdEmpresa = this.IdEmpresa, + Document = this.Documento, + IsDeleted = false, + Email = this.Email ?? string.Empty, + Phone = (string.IsNullOrEmpty(this.Prefixo) || string.IsNullOrEmpty(this.Telefone) ? string.Empty : string.Concat(this.Prefixo.Clear(), this.Telefone.Clear())) + }; + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (this.Expedicao.HasValue && (DateTime.Compare(this.Expedicao.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.Expedicao.Value, new DateTime(9999, 12, 31)) > 0)) + { + keyValuePairs.AddValue<string, string>("Expedicao", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + if (this.Nascimento.HasValue && (DateTime.Compare(this.Nascimento.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.Nascimento.Value, new DateTime(9999, 12, 31)) > 0)) + { + keyValuePairs.AddValue<string, string>("Nascimento", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + if (this.InicioAcesso.HasValue && this.FimAcesso.HasValue && this.InicioAcesso.Value.TimeOfDay > this.FimAcesso.Value.TimeOfDay) + { + keyValuePairs.AddValue<string, string>("FimAcesso|FIM DO ACESSO", "O HORÁRIO DO FIM DO ACESSO NÃO PODE SER ANTERIOR AO HORÁRIO DO INICIO DO ACESSO", true); + } + if (string.IsNullOrEmpty(this.Nome)) + { + keyValuePairs.AddValue<string, string>("Nome", Messages.Obrigatorio, true); + } + else if (this.Nome.Length > 50) + { + keyValuePairs.AddValue<string, string>("Nome", string.Format(Messages.MaiorQueLimite, 50), true); + } + if (!string.IsNullOrEmpty(this.Documento) && !this.Documento.ValidacaoDocumento()) + { + keyValuePairs.AddValue<string, string>("Documento", Messages.Invalido, true); + } + if (string.IsNullOrEmpty(this.Login)) + { + keyValuePairs.AddValue<string, string>("Login", Messages.Obrigatorio, true); + } + else if (this.Login.Length > 30) + { + keyValuePairs.AddValue<string, string>("Login", string.Format(Messages.MaiorQueLimite, 30), true); + } + if (!string.IsNullOrEmpty(this.Login) && !Regex.IsMatch(this.Login, "^(?!.* {2})[a-zA-Z0-9](?:[a-zA-Z0-9 .]{0,49}[a-zA-Z0-9])?$")) + { + keyValuePairs.AddValue<string, string>("Login|USUARIO", "USUARIO INVALIDO,\nUSUARIO SOMENTE DEVE CONTER LETRAS E NUMEROS,\nNÃO DEVE CONTER MAIS DE UM ESPAÇO,\nNÃO DEVE TER ESPAÇO NO INICIO E NO FIM.\nEXEMPLO VALIDO:\nUSUARIO01 OU USUARIO 02 OU USUARIO.03", true); + } + if (string.IsNullOrEmpty(this.Senha)) + { + keyValuePairs.AddValue<string, string>("Senha", Messages.Obrigatorio, true); + } + if (string.IsNullOrEmpty(this.Email)) + { + keyValuePairs.AddValue<string, string>("Email", Messages.Obrigatorio, true); + } + if (!string.IsNullOrEmpty(this.EstadoEmissor) && !this.EstadoEmissor.ValidacaoEstado()) + { + keyValuePairs.AddValue<string, string>("EstadoEmissor", Messages.Invalido, true); + } + if (this.Expedicao.HasValue && !this.Expedicao.ValidacaoDataPassada()) + { + keyValuePairs.AddValue<string, string>("Expedicao", Messages.Invalido, true); + } + if (this.Nascimento.HasValue && !this.Nascimento.ValidacaoDataPassada()) + { + keyValuePairs.AddValue<string, string>("Nascimento", Messages.Invalido, true); + } + if (!string.IsNullOrEmpty(base.Cep) && !base.Cep.ValidacaoCep()) + { + keyValuePairs.AddValue<string, string>("Cep", Messages.Invalido, true); + } + if (!string.IsNullOrEmpty(base.Endereco) && base.Endereco.Length > 60) + { + keyValuePairs.AddValue<string, string>("Endereco", string.Format(Messages.MaiorQueLimite, 60), true); + } + if (!string.IsNullOrEmpty(base.Numero) && base.Numero.Length > 5) + { + keyValuePairs.AddValue<string, string>("Numero", string.Format(Messages.MaiorQueLimite, 5), true); + } + if (!string.IsNullOrEmpty(base.Bairro) && base.Bairro.Length > 60) + { + keyValuePairs.AddValue<string, string>("Bairro", string.Format(Messages.MaiorQueLimite, 60), true); + } + if (!string.IsNullOrEmpty(base.Cidade) && base.Cidade.Length > 30) + { + keyValuePairs.AddValue<string, string>("Cidade", string.Format(Messages.MaiorQueLimite, 30), true); + } + if (!string.IsNullOrEmpty(base.Estado) && !base.Estado.ValidacaoEstado()) + { + keyValuePairs.AddValue<string, string>("Estado", Messages.Invalido, true); + } + if (!string.IsNullOrEmpty(base.Cep) || !string.IsNullOrEmpty(base.Numero) || !string.IsNullOrEmpty(base.Complemento) || !string.IsNullOrEmpty(base.Endereco) || !string.IsNullOrEmpty(base.Bairro) || !string.IsNullOrEmpty(base.Cidade) || !string.IsNullOrEmpty(base.Estado)) + { + if (string.IsNullOrEmpty(base.Cep)) + { + keyValuePairs.AddValue<string, string>("Cep", Messages.Obrigatorio, true); + } + if (string.IsNullOrEmpty(base.Endereco)) + { + keyValuePairs.AddValue<string, string>("Endereco", Messages.Obrigatorio, true); + } + if (string.IsNullOrEmpty(base.Numero)) + { + keyValuePairs.AddValue<string, string>("Numero", Messages.Obrigatorio, true); + } + if (string.IsNullOrEmpty(base.Bairro)) + { + keyValuePairs.AddValue<string, string>("Bairro", Messages.Obrigatorio, true); + } + if (string.IsNullOrEmpty(base.Cidade)) + { + keyValuePairs.AddValue<string, string>("Cidade", Messages.Obrigatorio, true); + } + if (string.IsNullOrEmpty(base.Estado)) + { + keyValuePairs.AddValue<string, string>("Estado", Messages.Obrigatorio, true); + } + } + if (this.AdministradorCentralSegurado && string.IsNullOrEmpty(this.Documento)) + { + keyValuePairs.AddValue<string, string>("Documento", Messages.Obrigatorio, true); + } + if (this.AdministradorCentralSegurado && string.IsNullOrEmpty(this.Prefixo)) + { + keyValuePairs.AddValue<string, string>("Prefixo", Messages.Obrigatorio, true); + } + if (this.AdministradorCentralSegurado && string.IsNullOrEmpty(this.Telefone)) + { + keyValuePairs.AddValue<string, string>("Telefone", Messages.Obrigatorio, true); + } + if (this.AdministradorCentralSegurado && string.IsNullOrEmpty(this.Email)) + { + keyValuePairs.AddValue<string, string>("Email", Messages.Obrigatorio, true); + } + if (this.InicioAcesso.HasValue && this.FimAcesso.HasValue && this.FimAcesso.Value.TimeOfDay == this.InicioAcesso.Value.TimeOfDay) + { + keyValuePairs.AddValue<string, string>("InicioAcesso", Messages.Invalido, true); + keyValuePairs.AddValue<string, string>("FimAcesso", Messages.Invalido, true); + } + if (this.Documento == null || string.IsNullOrEmpty(this.Documento)) + { + keyValuePairs.AddValue<string, string>("Documento", Messages.Obrigatorio, true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/Vendedor.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/Vendedor.cs new file mode 100644 index 0000000..200f397 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/Vendedor.cs @@ -0,0 +1,375 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Gestor.Model.Validation; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Globalization; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Gestor.Model.Domain.Seguros +{ + public class Vendedor : EnderecoBase, IDomain, INotifyPropertyChanged + { + private bool _selecionado; + + private string _nome; + + private string _documento; + + private string _conta; + + private string _agencia; + + private string _observacao; + + private string _titularConta; + + private string _documentoTitular; + + public string Agencia + { + get + { + string str = this._agencia; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._agencia = value; + } + } + + public bool Ativo + { + get; + set; + } + + public Gestor.Model.Domain.Common.Banco Banco + { + get; + set; + } + + public string Conta + { + get + { + string str = this._conta; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._conta = value; + } + } + + public Gestor.Model.Domain.Seguros.Controle Controle + { + get; + set; + } + + public bool Corretora + { + get; + set; + } + + public decimal? Desconto + { + get; + set; + } + + public string Documento + { + get + { + string str = this._documento; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._documento = value; + } + } + + public long IdEmpresa + { + get; + set; + } + + [Log(true)] + [Name(true)] + public string Nome + { + get + { + string str = this._nome; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._nome = value; + } + } + + public string Observacao + { + get + { + string str = this._observacao; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._observacao = value; + } + } + + public bool Selecionado + { + get + { + return this._selecionado; + } + set + { + if (value == this._selecionado) + { + return; + } + this._selecionado = value; + this.OnPropertyChanged("Selecionado"); + } + } + + public List<VendedorTelefone> Telefones + { + get; + set; + } + + public Gestor.Model.Common.TipoConta TipoConta + { + get; + set; + } + + public Gestor.Model.Common.TipoIncidenciaDesconto TipoIncidenciaDesconto + { + get; + set; + } + + public string TitularConta + { + get + { + string str = this._titularConta; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._titularConta = value; + } + } + + public string TitularDocumento + { + get + { + string str = this._documentoTitular; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._documentoTitular = value; + } + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Vendedor vendedor = this; + return new Func<List<KeyValuePair<string, string>>>(vendedor.Validate); + } + } + + public Vendedor() + { + } + + public List<TupleList> Log() + { + decimal? nullable; + string str; + string description; + decimal? nullable1; + List<TupleList> tupleLists = new List<TupleList>(); + TupleList tupleList = new TupleList(); + ObservableCollection<Tuple<string, string, string>> observableCollection = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("NOME", (string.IsNullOrWhiteSpace(this.Nome) ? "" : this.Nome), ""), + new Tuple<string, string, string>("CPF", (string.IsNullOrWhiteSpace(this.Documento) ? "" : this.Documento), ""), + new Tuple<string, string, string>("ATIVO", (this.Ativo ? "SIM" : "NÃO"), ""), + new Tuple<string, string, string>("BANCO", (this.Banco == null ? "" : this.Banco.Nome), ""), + new Tuple<string, string, string>("AGÊNCIA", (string.IsNullOrWhiteSpace(this.Agencia) ? "" : this.Agencia), ""), + new Tuple<string, string, string>("CONTA CORRENTE/POUPANÇA", (string.IsNullOrWhiteSpace(this.Conta) ? "" : this.Conta), ""), + new Tuple<string, string, string>("TITULAR DA CONTA", (string.IsNullOrWhiteSpace(this.TitularConta) ? "" : this.TitularConta), ""), + new Tuple<string, string, string>("DOCUMENTO TITULAR DA CONTA", (string.IsNullOrWhiteSpace(this.TitularDocumento) ? "" : this.TitularDocumento), ""), + new Tuple<string, string, string>("TIPO CONTA", (string.IsNullOrWhiteSpace(this.TipoConta.GetDescription()) ? "" : this.TipoConta.GetDescription()), "") + }; + decimal? desconto = this.Desconto; + if (!desconto.HasValue) + { + str = ""; + } + else + { + desconto = this.Desconto; + decimal num = 100; + if (desconto.HasValue) + { + nullable1 = new decimal?(desconto.GetValueOrDefault() / num); + } + else + { + nullable = null; + nullable1 = nullable; + } + nullable = nullable1; + if (nullable.HasValue) + { + decimal valueOrDefault = nullable.GetValueOrDefault(); + str = valueOrDefault.ToString("P", new CultureInfo("pt-BR", false)); + } + else + { + str = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("DESCONTO", str, "")); + tupleList.Tuples = observableCollection; + tupleLists.Add(tupleList); + List<TupleList> tupleLists1 = tupleLists; + ObservableCollection<Tuple<string, string, string>> observableCollection1 = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("CONTATOS$", "", "") + }; + if (this.Telefones != null && this.Telefones.Count != 0) + { + foreach (VendedorTelefone telefone in this.Telefones) + { + observableCollection1.Add(new Tuple<string, string, string>(string.Format(" CONTATO {0}$", this.Telefones.IndexOf(telefone) + 1), "", "")); + observableCollection1.Add(new Tuple<string, string, string>(" NOME", (string.IsNullOrWhiteSpace(telefone.Nome) ? "" : telefone.Nome), "")); + ObservableCollection<Tuple<string, string, string>> observableCollection2 = observableCollection1; + TipoTelefone? tipo = telefone.Tipo; + if (!tipo.HasValue) + { + description = ""; + } + else + { + tipo = telefone.Tipo; + if (tipo.HasValue) + { + description = tipo.GetValueOrDefault().GetDescription(); + } + else + { + description = null; + } + } + observableCollection2.Add(new Tuple<string, string, string>(" TIPO DE TELEFONE", description, "")); + observableCollection1.Add(new Tuple<string, string, string>(" PREFIXO", (string.IsNullOrWhiteSpace(telefone.Prefixo) ? "" : telefone.Prefixo), "")); + observableCollection1.Add(new Tuple<string, string, string>(" NÚMERO DE TELEFONE", (string.IsNullOrWhiteSpace(telefone.Numero) ? "" : telefone.Numero), "")); + observableCollection1.Add(new Tuple<string, string, string>(" E-MAIL", (string.IsNullOrWhiteSpace(telefone.Email) ? "" : telefone.Email), "")); + } + tupleLists1.Add(new TupleList() + { + Tuples = observableCollection1 + }); + } + return tupleLists1; + } + + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChangedEventHandler propertyChangedEventHandler = this.PropertyChanged; + if (propertyChangedEventHandler == null) + { + return; + } + propertyChangedEventHandler(this, new PropertyChangedEventArgs(propertyName)); + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (string.IsNullOrEmpty(this.Nome)) + { + keyValuePairs.AddValue<string, string>("Nome", Messages.Obrigatorio, true); + } + if (!string.IsNullOrWhiteSpace(this.Documento) && !this.Documento.ValidacaoDocumento()) + { + keyValuePairs.AddValue<string, string>("Documento", Messages.Invalido, true); + } + if (!string.IsNullOrWhiteSpace(this.TitularDocumento) && !this.TitularDocumento.ValidacaoDocumento()) + { + keyValuePairs.AddValue<string, string>("TitularDocumento", Messages.Invalido, true); + } + if (this.Telefones == null) + { + return keyValuePairs; + } + foreach (VendedorTelefone telefone in this.Telefones) + { + keyValuePairs.AddRange(telefone.Validate()); + } + return keyValuePairs; + } + + public event PropertyChangedEventHandler PropertyChanged; + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/VendedorParcela.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/VendedorParcela.cs new file mode 100644 index 0000000..8d40450 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/VendedorParcela.cs @@ -0,0 +1,235 @@ +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class VendedorParcela : DomainBase, IDomain + { + private string _vCondRep; + + public bool CoCorretagem + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.CondicaoRepasse CondicaoRepasse + { + get; + set; + } + + [Description("DATA DO PAGAMENTO")] + [Log(true)] + public DateTime? DataPagamento + { + get; + set; + } + + [Description("DATA PREVISÃO DE PAGAMENTO")] + [Log(true)] + public DateTime? DataPrePagamento + { + get; + set; + } + + [Log(false)] + public Gestor.Model.Domain.Seguros.Documento Documento + { + get; + set; + } + + [Log(false)] + public Gestor.Model.Domain.Seguros.Parcela Parcela + { + get; + set; + } + + [Description("PORCENTAGEM REPASSE")] + [Log(true)] + public decimal? PorcentagemRepasse + { + get; + set; + } + + public decimal? PorcentagemRepasseB + { + get; + set; + } + + public string RecebidoPorCompleto + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Repasse Repasse + { + get; + set; + } + + public bool Selecionado + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.TipoVendedor TipoVendedor + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + VendedorParcela vendedorParcela = this; + return new Func<List<KeyValuePair<string, string>>>(vendedorParcela.Validate); + } + } + + [Description("VALOR REPASSE")] + [Log(true)] + public decimal? ValorRepasse + { + get; + set; + } + + public decimal? ValorRepasseB + { + get; + set; + } + + public decimal? ValorTotal + { + get; + set; + } + + public decimal? ValorTotalPago + { + get; + set; + } + + public string VCondRep + { + get + { + string str = this._vCondRep; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._vCondRep = value; + } + } + + [Log(true)] + public Gestor.Model.Domain.Seguros.Vendedor Vendedor + { + get; + set; + } + + public VendedorParcela() + { + } + + public List<KeyValuePair<string, string>> Validate() + { + decimal num; + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (this.DataPagamento.HasValue && (DateTime.Compare(this.DataPagamento.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.DataPagamento.Value, new DateTime(9999, 12, 31)) > 0)) + { + keyValuePairs.AddValue<string, string>("DataPagamento", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + if (this.DataPrePagamento.HasValue && (DateTime.Compare(this.DataPrePagamento.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.DataPrePagamento.Value, new DateTime(9999, 12, 31)) > 0)) + { + keyValuePairs.AddValue<string, string>("DataPrePagamento", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + if (this.Vendedor == null) + { + keyValuePairs.AddValue<string, string>("Vendedor", Messages.Obrigatorio, true); + } + if (this.Documento == null) + { + keyValuePairs.AddValue<string, string>("Documento", Messages.Obrigatorio, true); + } + if (this.Documento != null && this.Documento.Id > (long)0 && this.Parcela == null) + { + keyValuePairs.AddValue<string, string>("Parcela", Messages.Obrigatorio, true); + } + if (this.Repasse == null) + { + keyValuePairs.AddValue<string, string>("Repasse", Messages.Obrigatorio, true); + } + if (this.TipoVendedor == null && !this.CoCorretagem) + { + keyValuePairs.AddValue<string, string>("TipoVendedor", Messages.Obrigatorio, true); + } + decimal? porcentagemRepasse = this.PorcentagemRepasse; + if (!porcentagemRepasse.HasValue && !this.CoCorretagem) + { + keyValuePairs.AddValue<string, string>("PorcentagemRepasse", Messages.Obrigatorio, true); + } + porcentagemRepasse = this.ValorRepasse; + if (!porcentagemRepasse.HasValue) + { + keyValuePairs.AddValue<string, string>("ValorRepasse", Messages.Obrigatorio, true); + } + if (this.Vendedor == null || this.Vendedor.Corretora) + { + return keyValuePairs; + } + porcentagemRepasse = this.PorcentagemRepasse; + if (porcentagemRepasse.HasValue) + { + porcentagemRepasse = this.PorcentagemRepasse; + num = new decimal(); + if ((porcentagemRepasse.GetValueOrDefault() <= num) & porcentagemRepasse.HasValue) + { + keyValuePairs.AddValue<string, string>("PorcentagemRepasse", Messages.Invalido, true); + } + } + porcentagemRepasse = this.ValorRepasse; + if (porcentagemRepasse.HasValue) + { + porcentagemRepasse = this.ValorRepasse; + num = new decimal(); + if ((porcentagemRepasse.GetValueOrDefault() == num) & porcentagemRepasse.HasValue && !this.CoCorretagem) + { + keyValuePairs.AddValue<string, string>("ValorRepasse", Messages.Invalido, true); + } + } + if (this.Repasse != null && this.Documento != null && this.Documento.TipoRecebimento.GetValueOrDefault() == TipoRecebimento.Parcela && this.Repasse.Base.GetValueOrDefault() == BaseRepasse.Transmissao && (!this.Documento.Remessa.HasValue || DateTime.Compare(this.Documento.Remessa.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.Documento.Remessa.Value, new DateTime(9999, 12, 31)) > 0)) + { + keyValuePairs.AddValue<string, string>("TRANSMISSÃO DA PROPOSTA", string.Format(Messages.DataInvalida, Array.Empty<object>()), true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/VendedorParcelas.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/VendedorParcelas.cs new file mode 100644 index 0000000..c3a7261 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/VendedorParcelas.cs @@ -0,0 +1,162 @@ +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Globalization; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class VendedorParcelas : DomainBase + { + public ObservableCollection<VendedorParcela> VendedorParcelasList + { + get; + set; + } + + public VendedorParcelas() + { + } + + public List<TupleList> Log(bool restricaoComissao, bool restricaoComissaoPorcentagem) + { + decimal? porcentagemRepasse; + decimal valueOrDefault; + string shortDateString; + string str; + string str1; + string str2; + string str3; + ObservableCollection<Tuple<string, string, string>> observableCollection = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("VENDEDORES$", "", "") + }; + if (this.VendedorParcelasList != null) + { + foreach (VendedorParcela vendedorParcelasList in this.VendedorParcelasList) + { + observableCollection.Add(new Tuple<string, string, string>(" NOME", (vendedorParcelasList.Vendedor == null ? "" : vendedorParcelasList.Vendedor.Nome.ToUpper()), "")); + observableCollection.Add(new Tuple<string, string, string>(" TIPO VENDEDOR", (vendedorParcelasList.TipoVendedor == null ? "" : vendedorParcelasList.TipoVendedor.Descricao), "")); + if (!restricaoComissao) + { + ObservableCollection<Tuple<string, string, string>> observableCollection1 = observableCollection; + porcentagemRepasse = vendedorParcelasList.PorcentagemRepasse; + if (!porcentagemRepasse.HasValue) + { + str2 = ""; + } + else + { + porcentagemRepasse = vendedorParcelasList.PorcentagemRepasse; + if (porcentagemRepasse.HasValue) + { + valueOrDefault = porcentagemRepasse.GetValueOrDefault(); + str2 = valueOrDefault.ToString("C", new CultureInfo("pt-BR", false)); + } + else + { + str2 = null; + } + } + observableCollection1.Add(new Tuple<string, string, string>(" COMISSÃO", str2, "")); + ObservableCollection<Tuple<string, string, string>> observableCollection2 = observableCollection; + porcentagemRepasse = vendedorParcelasList.ValorRepasse; + if (!porcentagemRepasse.HasValue) + { + str3 = ""; + } + else + { + porcentagemRepasse = vendedorParcelasList.ValorRepasse; + if (porcentagemRepasse.HasValue) + { + valueOrDefault = porcentagemRepasse.GetValueOrDefault(); + str3 = valueOrDefault.ToString("C", new CultureInfo("pt-BR", false)); + } + else + { + str3 = null; + } + } + observableCollection2.Add(new Tuple<string, string, string>(" REPASSE", str3, "")); + } + else if (!restricaoComissaoPorcentagem) + { + observableCollection.Add(new Tuple<string, string, string>(" COMISSÃO", "", "")); + observableCollection.Add(new Tuple<string, string, string>(" REPASSE", "", "")); + } + else + { + ObservableCollection<Tuple<string, string, string>> observableCollection3 = observableCollection; + porcentagemRepasse = vendedorParcelasList.PorcentagemRepasse; + if (!porcentagemRepasse.HasValue) + { + str1 = ""; + } + else + { + porcentagemRepasse = vendedorParcelasList.PorcentagemRepasse; + if (porcentagemRepasse.HasValue) + { + valueOrDefault = porcentagemRepasse.GetValueOrDefault(); + str1 = valueOrDefault.ToString("C", new CultureInfo("pt-BR", false)); + } + else + { + str1 = null; + } + } + observableCollection3.Add(new Tuple<string, string, string>(" COMISSÃO", str1, "")); + observableCollection.Add(new Tuple<string, string, string>(" REPASSE", "", "")); + } + ObservableCollection<Tuple<string, string, string>> observableCollection4 = observableCollection; + DateTime? dataPrePagamento = vendedorParcelasList.DataPrePagamento; + if (!dataPrePagamento.HasValue) + { + shortDateString = ""; + } + else + { + dataPrePagamento = vendedorParcelasList.DataPrePagamento; + if (dataPrePagamento.HasValue) + { + shortDateString = dataPrePagamento.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString = null; + } + } + observableCollection4.Add(new Tuple<string, string, string>(" DATA PRÉ PAGAMENTO", shortDateString, "")); + ObservableCollection<Tuple<string, string, string>> observableCollection5 = observableCollection; + dataPrePagamento = vendedorParcelasList.DataPagamento; + if (!dataPrePagamento.HasValue) + { + str = ""; + } + else + { + dataPrePagamento = vendedorParcelasList.DataPagamento; + if (dataPrePagamento.HasValue) + { + str = dataPrePagamento.GetValueOrDefault().ToShortDateString(); + } + else + { + str = null; + } + } + observableCollection5.Add(new Tuple<string, string, string>(" DATA PAGAMENTO", str, "")); + } + } + return new List<TupleList>() + { + new TupleList() + { + Tuples = observableCollection + } + }; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/VendedorTelefone.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/VendedorTelefone.cs new file mode 100644 index 0000000..7117ff5 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/VendedorTelefone.cs @@ -0,0 +1,89 @@ +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class VendedorTelefone : TelefoneBase, IDomain + { + private string _nome; + + private string _email; + + public string Email + { + get + { + string str = this._email; + if (str == null) + { + return null; + } + return str.ToLower().Trim(); + } + set + { + this._email = value; + } + } + + public string Nome + { + get + { + string str = this._nome; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._nome = value; + } + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + VendedorTelefone vendedorTelefone = this; + return new Func<List<KeyValuePair<string, string>>>(vendedorTelefone.Validate); + } + } + + public Gestor.Model.Domain.Seguros.Vendedor Vendedor + { + get; + set; + } + + public VendedorTelefone() + { + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = base.ValidateBase(false); + if (string.IsNullOrWhiteSpace(this.Nome)) + { + keyValuePairs.AddValue<string, string>("Nome", Messages.Obrigatorio, true); + } + if (!string.IsNullOrEmpty(this.Email) && this.Email.Length > 100) + { + keyValuePairs.AddValue<string, string>("Email|E-MAIL", string.Format(Messages.MaiorQueLimite, 100), true); + } + if (!string.IsNullOrEmpty(this.Email) && !this.Email.ValidacaoEmail()) + { + keyValuePairs.AddValue<string, string>("Email|E-MAIL", Messages.Invalido, true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/VendedorUsuario.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/VendedorUsuario.cs new file mode 100644 index 0000000..a53782f --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/VendedorUsuario.cs @@ -0,0 +1,51 @@ +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class VendedorUsuario : DomainBase, IDomain + { + public Gestor.Model.Domain.Seguros.Usuario Usuario + { + get; + set; + } + + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + VendedorUsuario vendedorUsuario = this; + return new Func<List<KeyValuePair<string, string>>>(vendedorUsuario.Validate); + } + } + + public Gestor.Model.Domain.Seguros.Vendedor Vendedor + { + get; + set; + } + + public VendedorUsuario() + { + } + + public List<KeyValuePair<string, string>> Validate() + { + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (this.Usuario == null) + { + keyValuePairs.AddValue<string, string>("Usuario", Messages.Obrigatorio, true); + } + if (this.Vendedor == null) + { + keyValuePairs.AddValue<string, string>("Vendedor", Messages.Obrigatorio, true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/Vida.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/Vida.cs new file mode 100644 index 0000000..4d945c4 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/Vida.cs @@ -0,0 +1,306 @@ +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Globalization; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class Vida : DomainBase, IDomain + { + private string _plano; + + public decimal? CapitalFuncionarios + { + get; + set; + } + + public decimal? CapitalSocios + { + get; + set; + } + + public int? Funcionarios + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Item Item + { + get; + set; + } + + public string Observacao + { + get; + set; + } + + public string Plano + { + get + { + string str = this._plano; + if (str != null) + { + return str.ToUpper(); + } + return null; + } + set + { + this._plano = value; + } + } + + public int? Socios + { + get; + set; + } + + [JsonIgnore] + public Func<List<KeyValuePair<string, string>>> ValidationEvent + { + get + { + Vida vida = this; + return new Func<List<KeyValuePair<string, string>>>(vida.Validate); + } + } + + public Vida() + { + } + + public static List<TupleList> Log(Gestor.Model.Domain.Seguros.Item item) + { + string str; + string str1; + string str2; + string str3; + string str4; + string str5; + List<TupleList> tupleLists = new List<TupleList>(); + TupleList tupleList = new TupleList(); + ObservableCollection<Tuple<string, string, string>> observableCollection = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("PLANO", (string.IsNullOrWhiteSpace(item.Vida.Plano) ? "" : item.Vida.Plano), ""), + new Tuple<string, string, string>("DESCRIÇÃO", (string.IsNullOrWhiteSpace(item.Descricao) ? "" : item.Descricao.ToUpper()), "") + }; + int? socios = item.Vida.Socios; + if (!socios.HasValue) + { + str = ""; + } + else + { + socios = item.Vida.Socios; + if (socios.HasValue) + { + str = socios.GetValueOrDefault().ToString(); + } + else + { + str = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("SÓCIOS", str, "")); + decimal? capitalSocios = item.Vida.CapitalSocios; + if (!capitalSocios.HasValue) + { + str1 = ""; + } + else + { + capitalSocios = item.Vida.CapitalSocios; + if (capitalSocios.HasValue) + { + str1 = capitalSocios.GetValueOrDefault().ToString(); + } + else + { + str1 = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("CAPITAL SÓCIO", str1, "")); + socios = item.Vida.Funcionarios; + if (!socios.HasValue) + { + str2 = ""; + } + else + { + socios = item.Vida.Funcionarios; + if (socios.HasValue) + { + str2 = socios.GetValueOrDefault().ToString(); + } + else + { + str2 = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("FUNCIONÁRIOS", str2, "")); + capitalSocios = item.Vida.CapitalFuncionarios; + if (!capitalSocios.HasValue) + { + str3 = ""; + } + else + { + capitalSocios = item.Vida.CapitalFuncionarios; + if (capitalSocios.HasValue) + { + str3 = capitalSocios.GetValueOrDefault().ToString(); + } + else + { + str3 = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("CAPITAL FUNCIONÁRIOS", str3, "")); + socios = item.Vida.Socios; + if (!socios.HasValue) + { + str4 = ""; + } + else + { + socios = item.Vida.Socios; + if (socios.HasValue) + { + str4 = socios.GetValueOrDefault().ToString(); + } + else + { + str4 = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("QUANTIDADE DE TITULARES", str4, "")); + socios = item.Vida.Funcionarios; + if (!socios.HasValue) + { + str5 = ""; + } + else + { + socios = item.Vida.Funcionarios; + if (socios.HasValue) + { + str5 = socios.GetValueOrDefault().ToString(); + } + else + { + str5 = null; + } + } + observableCollection.Add(new Tuple<string, string, string>("QUANTIDADE DE BENEFICIÁRIOS", str5, "")); + tupleList.Tuples = observableCollection; + tupleLists.Add(tupleList); + List<TupleList> tupleLists1 = tupleLists; + ObservableCollection<Tuple<string, string, string>> observableCollection1 = new ObservableCollection<Tuple<string, string, string>>() + { + new Tuple<string, string, string>("COBERTURAS$", "", "") + }; + foreach (Cobertura cobertura in item.Coberturas) + { + observableCollection1.Add(new Tuple<string, string, string>(string.Format(" COBERTURA {0}$", item.Coberturas.IndexOf(cobertura) + 1), "", "")); + observableCollection1.Add(new Tuple<string, string, string>(" OBSERVAÇÃO", (string.IsNullOrWhiteSpace(cobertura.Observacao) ? "" : cobertura.Observacao.ToUpper()), "")); + decimal premio = cobertura.Premio; + observableCollection1.Add(new Tuple<string, string, string>(" PRÊMIO", premio.ToString("C", new CultureInfo("pt-BR", false)), "")); + premio = cobertura.Franquia; + observableCollection1.Add(new Tuple<string, string, string>(" FRANQUIA", premio.ToString("C", new CultureInfo("pt-BR", false)), "")); + premio = cobertura.Lmi; + observableCollection1.Add(new Tuple<string, string, string>(" L.M.I.", premio.ToString("C", new CultureInfo("pt-BR", false)), "")); + } + tupleLists1.Add(new TupleList() + { + Tuples = observableCollection1 + }); + return tupleLists1; + } + + public List<KeyValuePair<string, string>> Validate() + { + decimal num; + bool documento; + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (string.IsNullOrWhiteSpace(this.Plano)) + { + keyValuePairs.AddValue<string, string>("Plano", Messages.Obrigatorio, true); + } + Gestor.Model.Domain.Seguros.Item item = this.Item; + if (item != null) + { + documento = item.Documento; + } + else + { + documento = false; + } + if (!documento) + { + return keyValuePairs; + } + long id = this.Item.Documento.Controle.Ramo.Id; + if (id == (long)7 || id == (long)10 || id == (long)53) + { + int? socios = this.Socios; + if (socios.HasValue) + { + socios = this.Socios; + if (!(socios.GetValueOrDefault() < 0 & socios.HasValue)) + { + goto Label0; + } + } + keyValuePairs.AddValue<string, string>("Socios|SÓCIOS", Messages.Obrigatorio, true); + Label0: + socios = this.Funcionarios; + if (socios.HasValue) + { + socios = this.Funcionarios; + if (!(socios.GetValueOrDefault() < 0 & socios.HasValue)) + { + goto Label1; + } + } + keyValuePairs.AddValue<string, string>("Funcionarios|FUNCIONÁRIOS", Messages.Obrigatorio, true); + Label1: + decimal? capitalSocios = this.CapitalSocios; + if (capitalSocios.HasValue) + { + capitalSocios = this.CapitalSocios; + num = new decimal(); + if (!((capitalSocios.GetValueOrDefault() < num) & capitalSocios.HasValue)) + { + goto Label2; + } + } + keyValuePairs.AddValue<string, string>("CapitalSocios|CAPITAL SÓCIO", Messages.Obrigatorio, true); + Label2: + capitalSocios = this.CapitalFuncionarios; + if (capitalSocios.HasValue) + { + capitalSocios = this.CapitalFuncionarios; + num = new decimal(); + if (!((capitalSocios.GetValueOrDefault() < num) & capitalSocios.HasValue)) + { + return keyValuePairs; + } + } + keyValuePairs.AddValue<string, string>("CapitalFuncionarios|CAPITAL FUNCIONÁRIO", Messages.Obrigatorio, true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/VinculoRepasse.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/VinculoRepasse.cs new file mode 100644 index 0000000..002f83e --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/VinculoRepasse.cs @@ -0,0 +1,159 @@ +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class VinculoRepasse : DomainBase + { + public long IdRepasse + { + get; + set; + } + + public Repasse RepasseVinculo + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.TipoVendedor TipoVendedor + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.TipoVendedor TipoVendedorVinculo + { + get; + set; + } + + public VinculoRepasse() + { + } + + public List<KeyValuePair<string, string>> Validate(List<VinculoRepasse> vinculos, Repasse repasse) + { + decimal zero; + decimal num; + decimal zero1; + decimal num1; + List<KeyValuePair<string, string>> keyValuePairs = ValidationHelper.AddValue(); + if (this.TipoVendedor == null) + { + keyValuePairs.AddValue<string, string>("TipoVendedor|TIPO VENDEDOR DO REPASSE", Messages.Obrigatorio, true); + } + if (this.IdRepasse == 0) + { + keyValuePairs.AddValue<string, string>("IdRepasse|REPASSE", Messages.Obrigatorio, true); + } + if (this.TipoVendedorVinculo == null) + { + keyValuePairs.AddValue<string, string>("TipoVendedorVinculo|TIPO VENDEDOR DO VÍNCULO", Messages.Obrigatorio, true); + } + if (this.RepasseVinculo == null) + { + keyValuePairs.AddValue<string, string>("RepasseVinculo|REPASSE DO VÍNCULO", Messages.Obrigatorio, true); + } + if (this.TipoVendedor != null && this.TipoVendedorVinculo != null && this.TipoVendedor.Id == this.TipoVendedorVinculo.Id) + { + keyValuePairs.AddValue<string, string>("TipoVendedor", "TIPO VENDEDOR SELECIONADO NÃO PODE SER O MESMO TIPO VENDEDOR DO VINCULO", true); + } + if (this.IdRepasse > (long)0 && this.RepasseVinculo != null && this.IdRepasse == this.RepasseVinculo.Id) + { + keyValuePairs.AddValue<string, string>("RepasseVinculo|REPASSE DO VÍNCULO", "NÃO É POSSÍVEL VINCULAR O MESMO REPASSE", true); + } + if (this.RepasseVinculo == null) + { + zero = decimal.Zero; + } + else + { + zero = (this.RepasseVinculo.Tipo.GetValueOrDefault() != TipoRepasse.Percentual || this.RepasseVinculo.Incidencia.GetValueOrDefault() != TipoIncidencia.SobreComissao ? decimal.Zero : this.RepasseVinculo.ValorNovo); + } + decimal num2 = zero; + decimal num3 = (repasse.Tipo.GetValueOrDefault() != TipoRepasse.Percentual || repasse.Incidencia.GetValueOrDefault() != TipoIncidencia.SobreComissao ? decimal.Zero : repasse.ValorNovo) + num2; + decimal num4 = num3; + if (this.TipoVendedor == null) + { + num = decimal.Zero; + } + else + { + num = (vinculos != null ? vinculos.Where<VinculoRepasse>((VinculoRepasse x) => { + if (this.TipoVendedor.Id != x.TipoVendedor.Id || x.RepasseVinculo.Tipo.GetValueOrDefault() != TipoRepasse.Percentual) + { + return false; + } + return x.RepasseVinculo.Incidencia.GetValueOrDefault() == TipoIncidencia.SobreComissao; + }).Sum<VinculoRepasse>((VinculoRepasse x) => x.RepasseVinculo.ValorNovo) : decimal.Zero); + } + num3 = num4 + num; + if (this.RepasseVinculo == null) + { + zero1 = decimal.Zero; + } + else + { + zero1 = (this.RepasseVinculo.Tipo.GetValueOrDefault() != TipoRepasse.Percentual || this.RepasseVinculo.Incidencia.GetValueOrDefault() != TipoIncidencia.SobreComissao ? decimal.Zero : this.RepasseVinculo.ValorRenovacao); + } + decimal num5 = zero1; + decimal num6 = (repasse.Tipo.GetValueOrDefault() != TipoRepasse.Percentual || repasse.Incidencia.GetValueOrDefault() != TipoIncidencia.SobreComissao ? decimal.Zero : repasse.ValorRenovacao) + num5; + if (this.TipoVendedor == null) + { + num1 = decimal.Zero; + } + else + { + num1 = (vinculos != null ? vinculos.Where<VinculoRepasse>((VinculoRepasse x) => { + if (this.TipoVendedor.Id != x.TipoVendedor.Id || x.RepasseVinculo.Tipo.GetValueOrDefault() != TipoRepasse.Percentual) + { + return false; + } + return x.RepasseVinculo.Incidencia.GetValueOrDefault() == TipoIncidencia.SobreComissao; + }).Sum<VinculoRepasse>((VinculoRepasse x) => x.RepasseVinculo.ValorRenovacao) : decimal.Zero); + } + decimal num7 = num6 + num1; + if (num3 > new decimal(100)) + { + keyValuePairs.AddValue<string, string>("RepasseVinculo|VALOR NOVO", "O VALOR DE REPASSE PARA SEGUROS NOVOS ULTRAPASSARÁ 100% DA COMISSÃO RECEBIDA", true); + } + if (num7 > new decimal(100)) + { + keyValuePairs.AddValue<string, string>("RepasseVinculo|VALOR RENOVAÇÃO", "O VALOR DE REPASSE PARA RENOVAÇÕES ULTRAPASSARÁ 100% DA COMISSÃO RECEBIDA", true); + } + if (vinculos == null || vinculos.Count <= 0) + { + return keyValuePairs; + } + if (this.TipoVendedor != null && this.TipoVendedorVinculo != null && vinculos.Any<VinculoRepasse>((VinculoRepasse x) => { + if (x.TipoVendedor.Id != this.TipoVendedor.Id) + { + return false; + } + return x.TipoVendedorVinculo.Id == this.TipoVendedorVinculo.Id; + })) + { + keyValuePairs.AddValue<string, string>("TipoVendedorVinculo|TIPO VENDEDOR DO VÍNCULO", string.Concat("JÁ EXISTE UM VINCULO DE REPASSE PARA ", this.TipoVendedorVinculo.Descricao), true); + } + if (this.TipoVendedor != null && this.RepasseVinculo != null && vinculos.Any<VinculoRepasse>((VinculoRepasse x) => { + if (x.TipoVendedor.Id != this.TipoVendedor.Id) + { + return false; + } + return x.RepasseVinculo.Vendedor.Id == this.RepasseVinculo.Vendedor.Id; + })) + { + keyValuePairs.AddValue<string, string>("TipoVendedorVinculo|VENDEDOR DO VÍNCULO", string.Concat("JÁ EXISTE UM VINCULO DE REPASSE PARA PARA ", this.RepasseVinculo.Vendedor.Nome), true); + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Domain.Seguros/VinculoVendedor.cs b/Codemerx/Gestor.Model/Model.Domain.Seguros/VinculoVendedor.cs new file mode 100644 index 0000000..03ef440 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Domain.Seguros/VinculoVendedor.cs @@ -0,0 +1,25 @@ +using Gestor.Model.Domain.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Domain.Seguros +{ + public class VinculoVendedor : DomainBase + { + public Gestor.Model.Domain.Seguros.Vendedor Vendedor + { + get; + set; + } + + public bool Vinculado + { + get; + set; + } + + public VinculoVendedor() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Helper/ValidationHelper.cs b/Codemerx/Gestor.Model/Model.Helper/ValidationHelper.cs new file mode 100644 index 0000000..2420e7c --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Helper/ValidationHelper.cs @@ -0,0 +1,518 @@ +using Gestor.Model.Common; +using Gestor.Model.Validation; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Globalization; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Text; +using System.Text.RegularExpressions; + +namespace Gestor.Model.Helper +{ + public static class ValidationHelper + { + public static List<KeyValuePair<T, T2>> AddValue<T, T2>(this List<KeyValuePair<T, T2>> keyValuePairs, T name, T2 value, bool condition = true) + { + if (name == null || name.ToString() == string.Empty || !condition) + { + return keyValuePairs; + } + if (keyValuePairs == null) + { + keyValuePairs = ValidationHelper.AddValue<T, T2>(name, value, true); + return keyValuePairs; + } + keyValuePairs.Add(new KeyValuePair<T, T2>(name, value)); + return keyValuePairs; + } + + public static List<KeyValuePair<T, T2>> AddValue<T, T2>(T name, T2 value, bool condition = true) + { + if (name == null || name.ToString() == string.Empty || !condition) + { + return new List<KeyValuePair<T, T2>>(); + } + return new List<KeyValuePair<T, T2>>() + { + new KeyValuePair<T, T2>(name, value) + }; + } + + public static List<KeyValuePair<string, string>> AddValue() + { + return new List<KeyValuePair<string, string>>(); + } + + public static int Age(this DateTime birthDate) + { + DateTime date = Funcoes.GetNetworkTime().Date; + int year = date.Year - birthDate.Year; + if (birthDate > date.AddYears(-year)) + { + year--; + } + return year; + } + + public static string Categoria(this Enum genericEnum) + { + MemberInfo[] member = genericEnum.GetType().GetMember(genericEnum.ToString()); + if (member.Length == 0) + { + return genericEnum.ToString(); + } + object[] customAttributes = member[0].GetCustomAttributes(typeof(CategoryAttribute), false); + if (!customAttributes.Any<object>()) + { + return genericEnum.ToString(); + } + return ((CategoryAttribute)customAttributes.ElementAt<object>(0)).Category; + } + + public static string Clear(this string stringToClean) + { + if (stringToClean == null) + { + return null; + } + return Regex.Replace(stringToClean, "[^\\d]", string.Empty); + } + + public static string ClearCurrency(this string stringToClean) + { + if (string.IsNullOrEmpty(stringToClean)) + { + return string.Empty; + } + if (stringToClean.Count<char>((char x) => x == '.') == 1) + { + if (stringToClean.Count<char>((char x) => x == ',') == 0) + { + stringToClean = stringToClean.Replace(".", ","); + } + } + if (stringToClean.Count<char>((char x) => x == '.') > 0) + { + if (stringToClean.Count<char>((char x) => x == ',') == 1) + { + stringToClean = stringToClean.Replace(".", ""); + } + } + if (stringToClean.Count<char>((char x) => x == '.') <= 1) + { + return Regex.Replace(stringToClean, "[^\\d\\,\\-]", string.Empty); + } + int num = stringToClean.Count<char>((char x) => x == '.'); + for (int i = 0; i < num; i++) + { + int num1 = stringToClean.IndexOf(".", StringComparison.CurrentCultureIgnoreCase); + StringBuilder stringBuilder = new StringBuilder(stringToClean); + stringBuilder[num1] = (i < num - 1 ? 'a' : ','); + stringToClean = stringBuilder.ToString(); + } + return Regex.Replace(stringToClean, "[^\\d\\,\\-]", string.Empty); + } + + public static string DocumentoFornecedor(this string sentence) + { + if (sentence == null) + { + return null; + } + return (new Regex("[^\\d]")).Replace(sentence, ""); + } + + public static string FormataCep(this string cep) + { + if (string.IsNullOrWhiteSpace(cep) || Regex.IsMatch(cep, "^\\d{2}\\d{3}-\\d{3}$")) + { + return cep; + } + string str = Regex.Replace(cep, "\\D", ""); + if (!Regex.IsMatch(str, "^\\d{8}$")) + { + return cep; + } + return Regex.Replace(str, "(\\d{5})(\\d{3})", "$1-$2"); + } + + public static string FormataFipe(this string value) + { + if (string.IsNullOrWhiteSpace(value)) + { + return ""; + } + ulong num = Convert.ToUInt64(value.OnlyNumber()); + return num.ToString("000000\\-0"); + } + + public static string FormataPlaca(this string placa) + { + if (string.IsNullOrWhiteSpace(placa) || Regex.IsMatch(placa.Trim(), "[^a-zA-Z0-9]{1,7}")) + { + return placa.Trim(); + } + return Regex.Replace(placa.Trim(), "[^a-zA-Z0-9]{1,7}", ""); + } + + public static string GetValueExact(this List<KeyValuePair<string, string>> keyValuePairs, string keyName) + { + KeyValuePair<string, string> keyValuePair = keyValuePairs.Find((KeyValuePair<string, string> x) => x.Key.Substring(0, (x.Key.Contains("|") ? x.Key.IndexOf("|", StringComparison.Ordinal) : x.Key.Length)).Equals(keyName)); + return keyValuePair.Value; + } + + public static string Index(this string[] stringArray, int currentIndex) + { + if (stringArray == null || !stringArray.Any<string>()) + { + return string.Empty; + } + if (currentIndex <= -1 || currentIndex >= (int)stringArray.Length) + { + return string.Empty; + } + return stringArray[currentIndex]; + } + + public static string Join(this IEnumerable<string> stringValues, string separator) + { + return string.Join(separator, stringValues); + } + + public static string Length(this string stringValue, int maxLength) + { + if (stringValue.Length <= maxLength) + { + return stringValue; + } + return stringValue.Substring(0, maxLength); + } + + public static string OnlyNumber(this string sentence) + { + if (sentence == null) + { + return null; + } + return (new Regex("[^\\d]")).Replace(sentence, ""); + } + + public static decimal ToDecimal(this string currencyString, string currentCulture = "pt-BR") + { + decimal num; + decimal.TryParse(currencyString.ClearCurrency(), NumberStyles.Any, new CultureInfo(currentCulture), out num); + return num; + } + + public static float ToFloat(this string stringValue) + { + float single; + float.TryParse(stringValue, out single); + return single; + } + + public static int ToInt(this string stringValue) + { + int num; + int.TryParse(stringValue, out num); + return num; + } + + public static bool ValidacaoCei(this string cei) + { + if (string.IsNullOrEmpty(cei)) + { + return false; + } + cei = cei.Trim(); + cei = Regex.Replace(cei, "[^\\d]", ""); + if (cei.Length != 12) + { + return false; + } + int num = 0; + for (int i = 1; i < 12; i++) + { + int num1 = Convert.ToInt32("74185216374".Substring(i - 1, 1)); + int num2 = Convert.ToInt32(cei.Substring(i - 1, 1)); + num = num + num1 * num2; + } + int num3 = num / 10; + int num4 = num - num / 10 * 10; + num = num3 + num4; + num4 = num - num / 10 * 10; + int num5 = 10 - num4; + return Convert.ToInt32(cei.Substring(11, 1)) == num5; + } + + public static bool ValidacaoCep(this string postCode) + { + if (postCode == null) + { + return false; + } + return Regex.Match(postCode, "^[0-9]{5}-[0-9]{3}$").Success; + } + + public static bool ValidacaoChassi(this string chassiNumber) + { + string upper; + if (chassiNumber != null) + { + upper = chassiNumber.ToUpper(); + } + else + { + upper = null; + } + chassiNumber = upper; + if (string.IsNullOrEmpty(chassiNumber)) + { + return true; + } + if (chassiNumber.Length != 17 || Regex.IsMatch(chassiNumber, "^0| |^.{4,}([0-9A-Z])\\1{5,}|[iIoOqQ]")) + { + return false; + } + return Regex.IsMatch(chassiNumber, "[0-9]{4}$"); + } + + public static bool ValidacaoDataPassada(this DateTime? data) + { + DateTime? nullable = data; + DateTime date = Funcoes.GetNetworkTime().Date; + if (!nullable.HasValue) + { + return false; + } + return nullable.GetValueOrDefault() < date; + } + + public static bool ValidacaoDocumento(this string cpfCnpj) + { + int j; + int i; + int num; + string str; + if (cpfCnpj != null) + { + str = cpfCnpj.Clear(); + } + else + { + str = null; + } + string str1 = str; + if (string.IsNullOrEmpty(str1)) + { + return false; + } + int[] numArray = new int[14]; + int[] numArray1 = new int[2]; + if (new string(str1[0], str1.Length) == str1) + { + return false; + } + if (str1.Length == 11) + { + for (i = 0; i <= 10; i++) + { + numArray[i] = Convert.ToInt32(str1.Substring(i, 1)); + } + for (i = 0; i <= 1; i++) + { + num = 0; + for (j = 0; j <= 8 + i; j++) + { + num = num + numArray[j] * (10 + i - j); + } + numArray1[i] = num * 10 % 11; + if (numArray1[i] == 10) + { + numArray1[i] = 0; + } + } + return numArray1[0] == numArray[9] & numArray1[1] == numArray[10]; + } + if (str1.Length != 14) + { + return false; + } + for (i = 0; i <= 13; i++) + { + numArray[i] = Convert.ToInt32(str1.Substring(i, 1)); + } + for (i = 0; i <= 1; i++) + { + num = 0; + for (j = 0; j <= 11 + i; j++) + { + num = num + numArray[j] * Convert.ToInt32("6543298765432".Substring(j + 1 - i, 1)); + } + numArray1[i] = num * 10 % 11; + if (numArray1[i] == 10) + { + numArray1[i] = 0; + } + } + return numArray1[0] == numArray[12] & numArray1[1] == numArray[13]; + } + + public static bool ValidacaoEmail(this string mail) + { + if (mail == null) + { + return false; + } + if (mail.StartsWith("'") || mail.EndsWith("'")) + { + string str = ""; + mail = Regex.Replace((new Regex("[\\']")).Replace(mail, str), "\\s+", ""); + } + if ((new Regex("[à-ú]")).IsMatch(mail)) + { + return false; + } + return (new Regex("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")).IsMatch(mail); + } + + public static bool ValidacaoEstado(this string state) + { + if (string.IsNullOrEmpty(state)) + { + return false; + } + return (new string[] { "AC", "AL", "AP", "AM", "BA", "CE", "DF", "ES", "GO", "MA", "MT", "MS", "MG", "PA", "PB", "PR", "PE", "PI", "RJ", "RN", "RS", "RO", "RR", "SC", "SP", "SE", "TO" }).Contains<string>(state.ToUpper()); + } + + public static bool ValidacaoFabricacao(this string ano) + { + int num; + if (!int.TryParse(ano, out num)) + { + return false; + } + if (num <= 1900) + { + return false; + } + return num <= Funcoes.GetNetworkTime().Year; + } + + public static bool ValidacaoModelo(this string ano) + { + int num; + if (!int.TryParse(ano, out num)) + { + return false; + } + if (num <= 1900) + { + return false; + } + return num <= Funcoes.GetNetworkTime().Year + 1; + } + + public static bool ValidacaoOrgao(this string orgao) + { + if (string.IsNullOrEmpty(orgao)) + { + return true; + } + return orgao.Length < 7; + } + + public static bool ValidacaoPlaca(this string numeroPlaca) + { + if (numeroPlaca == null) + { + return false; + } + numeroPlaca.FormataPlaca(); + return true; + } + + public static bool ValidacaoPrefixo(this string prefix) + { + int num; + if (!int.TryParse(prefix, out num)) + { + return false; + } + if (num != 20 && num != 23 && num != 25 && num != 26 && num != 29 && num != 30 && num != 36 && num != 39 && num != 40 && num != 50 && num != 52 && num != 56 && num != 57 && num != 58 && num != 59 && num != 60 && num != 70 && num != 72 && num != 76 && num != 78 && num != 80 && num != 90 && num >= 11 && num <= 99) + { + return true; + } + return false; + } + + public static bool ValidacaoPrefixo(this string number, TipoTelefone tipo) + { + if (tipo != TipoTelefone.Internacional && tipo != TipoTelefone.Whatsapp && tipo != TipoTelefone.Gratuita && tipo != TipoTelefone.TarifaUnica) + { + return number.ValidacaoPrefixo(); + } + return number.Trim().Length == 0; + } + + public static bool ValidacaoRne(this string rne) + { + return true; + } + + public static bool ValidacaoTelefone(this string number) + { + if (number == null) + { + return false; + } + return Regex.Match(number, "^(\\d{8,9}$|\\d{4,5}[- ]\\d{4}$|\\d{4}\\s\\d{3}\\s\\d{4})$").Success; + } + + public static bool ValidacaoTelefone(this string number, TipoTelefone tipo) + { + if (tipo == TipoTelefone.Internacional || tipo == TipoTelefone.Whatsapp) + { + if (number == null) + { + return false; + } + return Regex.IsMatch(number.Trim(), "^[0-9]{7,16}$"); + } + if (tipo == TipoTelefone.Gratuita || tipo == TipoTelefone.TarifaUnica) + { + if (number == null) + { + return false; + } + return Regex.IsMatch(number.Trim(), "^[0-9]{4,7}$"); + } + if (tipo != TipoTelefone.Celular) + { + return number.ValidacaoTelefone(); + } + if (number == null) + { + return false; + } + return Regex.IsMatch(number.Trim(), "^\\d{4,5}[- ]?\\d{4}$"); + } + + public static bool ValidaFipe(this string value) + { + if ((new Regex("^\\d{6}\\-\\d{1}$")).IsMatch(value)) + { + return true; + } + return false; + } + + public static bool ValidateCaepf(this string caepf) + { + return !string.IsNullOrEmpty(caepf); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.License/Instalacao.cs b/Codemerx/Gestor.Model/Model.License/Instalacao.cs new file mode 100644 index 0000000..59d9bb8 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.License/Instalacao.cs @@ -0,0 +1,79 @@ +using Gestor.Model.Domain.Generic; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.License +{ + public class Instalacao : DomainBase + { + public string Aggilizador + { + get; + set; + } + + public DateTime Data + { + get; + set; + } + + public string Gerenciador + { + get; + set; + } + + public long IdFornecedor + { + get; + set; + } + + public string Ip + { + get; + set; + } + + public string NomeMaquina + { + get; + set; + } + + public string OSInfo + { + get; + set; + } + + public DateTime UltimoAcesso + { + get; + set; + } + + public long UsuarioId + { + get; + set; + } + + public string UsuarioMaquina + { + get; + set; + } + + public string UsuarioSistema + { + get; + set; + } + + public Instalacao() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.License/Licenca.cs b/Codemerx/Gestor.Model/Model.License/Licenca.cs new file mode 100644 index 0000000..dfece96 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.License/Licenca.cs @@ -0,0 +1,42 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.License +{ + public class Licenca + { + public bool AcessoLiberado + { + get; + set; + } + + public DateTime Liberacao + { + get; + set; + } + + public Gestor.Model.License.Produto Produto + { + get; + set; + } + + public int Quantidade + { + get; + set; + } + + public int Status + { + get; + set; + } + + public Licenca() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.License/Produto.cs b/Codemerx/Gestor.Model/Model.License/Produto.cs new file mode 100644 index 0000000..357cce1 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.License/Produto.cs @@ -0,0 +1,41 @@ +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.License +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum Produto + { + [Description("GERENCIADOR")] + Gerenciador = 1, + [Description("MATRIZ/FILIAL")] + MatrizFilial = 2, + [Description("FINANCEIRO")] + Financeiro = 4, + [Description("IMPORTADOR")] + Importador = 5, + [Description("WEBSITE")] + Website = 19, + [Description("MOBILE")] + Mobile = 27, + [Description("LICENÇA ONLINE")] + LicencaOnline = 73, + [Description("AGGILIZADOR DOCUMENTOS")] + AggilizadorDocumentos = 77, + [Description("AGGILIZADOR CALCULOS")] + AggilizadorCalculos = 79, + [Description("AGGILIZADOR CÁLCULOS INDEPENDENTE")] + AggilizadorCalculosIndependente = 81, + [Description("SUA CORRETORA DIGITAL")] + SuaCorretoraDigital = 82, + [Description("EPIC")] + Epic = 83, + [Description("AGGILIZADOR DOCUMENTOS INDEPENDENTE")] + AggilizadorDocumentosIndependente = 84, + [Description("ASSINATURA ELETRÔNICA")] + AssinaturaEletronica = 86, + [Description("NOVO AGGILIZADOR")] + NovoAggilizador = 91 + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.License/StatusLicenca.cs b/Codemerx/Gestor.Model/Model.License/StatusLicenca.cs new file mode 100644 index 0000000..2cc22bc --- /dev/null +++ b/Codemerx/Gestor.Model/Model.License/StatusLicenca.cs @@ -0,0 +1,19 @@ +using Gestor.Model.Converter; +using System; +using System.ComponentModel; + +namespace Gestor.Model.License +{ + [TypeConverter(typeof(EnumDescriptionTypeConverter))] + public enum StatusLicenca + { + [Description("NORMAL")] + Normal, + [Description("BLOQUEADO")] + Bloqueado, + [Description("CONSULTA")] + Consulta, + [Description("CANCELADO")] + Cancelado + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Relatorios/Cliente.cs b/Codemerx/Gestor.Model/Model.Relatorios/Cliente.cs new file mode 100644 index 0000000..0bf172d --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Relatorios/Cliente.cs @@ -0,0 +1,18 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Relatorios +{ + public class Cliente + { + public long Id + { + get; + set; + } + + public Cliente() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Relatorios/ClienteEmail.cs b/Codemerx/Gestor.Model/Model.Relatorios/ClienteEmail.cs new file mode 100644 index 0000000..6f8e853 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Relatorios/ClienteEmail.cs @@ -0,0 +1,41 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Relatorios +{ + public class ClienteEmail + { + private string _email; + + public Gestor.Model.Relatorios.Cliente Cliente + { + get; + set; + } + + public string Email + { + get + { + return this._email; + } + set + { + string str; + if (value != null) + { + str = value.Trim(); + } + else + { + str = null; + } + this._email = str; + } + } + + public ClienteEmail() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Relatorios/ClienteEndereco.cs b/Codemerx/Gestor.Model/Model.Relatorios/ClienteEndereco.cs new file mode 100644 index 0000000..37bb19e --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Relatorios/ClienteEndereco.cs @@ -0,0 +1,191 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Relatorios +{ + public class ClienteEndereco + { + private string _endereco; + + private string _numero; + + private string _complemento; + + private string _cidade; + + private string _estado; + + private string _cep; + + private string _bairro; + + public string Bairro + { + get + { + return this._bairro; + } + set + { + string str; + if (value != null) + { + str = value.Trim(); + } + else + { + str = null; + } + this._bairro = str; + } + } + + public string Cep + { + get + { + return this._cep; + } + set + { + string str; + if (value != null) + { + str = value.Trim(); + } + else + { + str = null; + } + this._cep = str; + } + } + + public string Cidade + { + get + { + return this._cidade; + } + set + { + string str; + if (value != null) + { + str = value.Trim(); + } + else + { + str = null; + } + this._cidade = str; + } + } + + public Gestor.Model.Relatorios.Cliente Cliente + { + get; + set; + } + + public string Complemento + { + get + { + return this._complemento; + } + set + { + string str; + if (value != null) + { + str = value.Trim(); + } + else + { + str = null; + } + this._complemento = str; + } + } + + public string Endereco + { + get + { + return this._endereco; + } + set + { + string str; + if (value != null) + { + str = value.Trim(); + } + else + { + str = null; + } + this._endereco = str; + } + } + + public string Estado + { + get + { + return this._estado; + } + set + { + string str; + if (value != null) + { + str = value.Trim(); + } + else + { + str = null; + } + this._estado = str; + } + } + + public long IdCliEnd + { + get; + set; + } + + public string Numero + { + get + { + return this._numero; + } + set + { + string str; + if (value != null) + { + str = value.Trim(); + } + else + { + str = null; + } + this._numero = str; + } + } + + public int Ordem + { + get; + set; + } + + public ClienteEndereco() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Relatorios/ClienteTelefone.cs b/Codemerx/Gestor.Model/Model.Relatorios/ClienteTelefone.cs new file mode 100644 index 0000000..d47ef10 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Relatorios/ClienteTelefone.cs @@ -0,0 +1,64 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Relatorios +{ + public class ClienteTelefone + { + private string _prefixo; + + private string _numero; + + public Gestor.Model.Relatorios.Cliente Cliente + { + get; + set; + } + + public string Numero + { + get + { + return this._numero; + } + set + { + string str; + if (value != null) + { + str = value.Trim(); + } + else + { + str = null; + } + this._numero = str; + } + } + + public string Prefixo + { + get + { + return this._prefixo; + } + set + { + string str; + if (value != null) + { + str = value.Trim(); + } + else + { + str = null; + } + this._prefixo = str; + } + } + + public ClienteTelefone() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Relatorios/Controle.cs b/Codemerx/Gestor.Model/Model.Relatorios/Controle.cs new file mode 100644 index 0000000..63bd5f5 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Relatorios/Controle.cs @@ -0,0 +1,30 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Relatorios +{ + public class Controle + { + public Gestor.Model.Relatorios.Cliente Cliente + { + get; + set; + } + + public long Id + { + get; + set; + } + + public Gestor.Model.Relatorios.Ramo Ramo + { + get; + set; + } + + public Controle() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Relatorios/Documento.cs b/Codemerx/Gestor.Model/Model.Relatorios/Documento.cs new file mode 100644 index 0000000..f40e84d --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Relatorios/Documento.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Relatorios +{ + public class Documento + { + public Gestor.Model.Relatorios.Controle Controle + { + get; + set; + } + + public long Id + { + get; + set; + } + + public int? Ordem + { + get; + set; + } + + public IList<Vendedor> Vendedores + { + get; + set; + } + + public Documento() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Relatorios/EstipulanteCliente.cs b/Codemerx/Gestor.Model/Model.Relatorios/EstipulanteCliente.cs new file mode 100644 index 0000000..9738d14 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Relatorios/EstipulanteCliente.cs @@ -0,0 +1,30 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Relatorios +{ + public class EstipulanteCliente + { + public long IdCliente + { + get; + set; + } + + public long IdEstiputante + { + get; + set; + } + + public string NomeEstipulante + { + get; + set; + } + + public EstipulanteCliente() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Relatorios/Ramo.cs b/Codemerx/Gestor.Model/Model.Relatorios/Ramo.cs new file mode 100644 index 0000000..0bad648 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Relatorios/Ramo.cs @@ -0,0 +1,41 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Relatorios +{ + public class Ramo + { + private string _nome; + + public long Id + { + get; + set; + } + + public string Nome + { + get + { + return this._nome; + } + set + { + string str; + if (value != null) + { + str = value.Trim(); + } + else + { + str = null; + } + this._nome = str; + } + } + + public Ramo() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Relatorios/Vendedor.cs b/Codemerx/Gestor.Model/Model.Relatorios/Vendedor.cs new file mode 100644 index 0000000..9c69760 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Relatorios/Vendedor.cs @@ -0,0 +1,41 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Relatorios +{ + public class Vendedor + { + private string _nome; + + public long Id + { + get; + set; + } + + public string Nome + { + get + { + return this._nome; + } + set + { + string str; + if (value != null) + { + str = value.Trim(); + } + else + { + str = null; + } + this._nome = str; + } + } + + public Vendedor() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Validation/ControleValidacao.cs b/Codemerx/Gestor.Model/Model.Validation/ControleValidacao.cs new file mode 100644 index 0000000..2c3af2c --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Validation/ControleValidacao.cs @@ -0,0 +1,36 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Validation +{ + public class ControleValidacao + { + public string Estilo + { + get; + set; + } + + public string Nome + { + get; + set; + } + + public string Tag + { + get; + set; + } + + public Type Tipo + { + get; + set; + } + + public ControleValidacao() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Model.Validation/Funcoes.cs b/Codemerx/Gestor.Model/Model.Validation/Funcoes.cs new file mode 100644 index 0000000..a1790a2 --- /dev/null +++ b/Codemerx/Gestor.Model/Model.Validation/Funcoes.cs @@ -0,0 +1,167 @@ +using Gestor.Model.Common; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace Gestor.Model.Validation +{ + public static class Funcoes + { + public static System.Diagnostics.Stopwatch Stopwatch; + + public static DateTime? StartTime; + + public static int GetAge(DateTime birth) + { + DateTime date = Funcoes.GetNetworkTime().Date; + int year = date.Year - birth.Year; + if (birth > date.AddYears(-year)) + { + year--; + } + return year; + } + + public static string GetDescription(this Enum genericEnum) + { + if (genericEnum == null) + { + return ""; + } + MemberInfo[] member = genericEnum.GetType().GetMember(genericEnum.ToString()); + if (member.Length == 0) + { + return genericEnum.ToString(); + } + object[] customAttributes = member[0].GetCustomAttributes(typeof(DescriptionAttribute), false); + if (!customAttributes.Any<object>()) + { + return genericEnum.ToString(); + } + return ((DescriptionAttribute)customAttributes.ElementAt<object>(0)).Description; + } + + public static DateTime GetNetworkTime() + { + DateTime value; + try + { + if (!Funcoes.StartTime.HasValue) + { + byte[] numArray = new byte[48]; + numArray[0] = 27; + IPEndPoint pEndPoint = new IPEndPoint(((IEnumerable<IPAddress>)Dns.GetHostEntry("time.google.com").AddressList).First<IPAddress>((IPAddress a) => a.AddressFamily == AddressFamily.InterNetwork), 123); + using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) + { + socket.Connect(pEndPoint); + socket.ReceiveTimeout = 3000; + socket.Send(numArray); + socket.Receive(numArray); + socket.Close(); + } + ulong num = (ulong)numArray[40] << 24 | (ulong)numArray[41] << 16 | (ulong)numArray[42] << 8 | (ulong)numArray[43]; + ulong num1 = (ulong)numArray[44] << 24 | (ulong)numArray[45] << 16 | (ulong)numArray[46] << 8 | (ulong)numArray[47]; + ulong num2 = num * (long)1000 + num1 * (long)1000 / 4294967296L; + DateTime dateTime = new DateTime(1900, 1, 1); + dateTime = dateTime.AddMilliseconds((double)num2); + Funcoes.StartTime = new DateTime?(dateTime.ToLocalTime()); + Funcoes.Stopwatch = System.Diagnostics.Stopwatch.StartNew(); + value = Funcoes.StartTime.Value; + } + else + { + value = Funcoes.StartTime.Value; + value = value.AddMilliseconds((double)Funcoes.Stopwatch.ElapsedMilliseconds); + } + } + catch (Exception exception) + { + Funcoes.StartTime = new DateTime?(DateTime.Now); + Funcoes.Stopwatch = System.Diagnostics.Stopwatch.StartNew(); + value = Funcoes.StartTime.Value; + } + return value; + } + + public static ParentescoVinculo? ParentescoInverso(ParentescoVinculo? parentesco) + { + if (parentesco.HasValue) + { + switch (parentesco.GetValueOrDefault()) + { + case ParentescoVinculo.MaePai: + { + return new ParentescoVinculo?(ParentescoVinculo.Filho); + } + case ParentescoVinculo.Filho: + { + return new ParentescoVinculo?(ParentescoVinculo.MaePai); + } + case ParentescoVinculo.Avo: + { + return new ParentescoVinculo?(ParentescoVinculo.Neto); + } + case ParentescoVinculo.Neto: + { + return new ParentescoVinculo?(ParentescoVinculo.Avo); + } + case ParentescoVinculo.Tio: + { + return new ParentescoVinculo?(ParentescoVinculo.Sobrinho); + } + case ParentescoVinculo.Sobrinho: + { + return new ParentescoVinculo?(ParentescoVinculo.Tio); + } + case ParentescoVinculo.Bisavo: + { + return new ParentescoVinculo?(ParentescoVinculo.Bisneto); + } + case ParentescoVinculo.Bisneto: + { + return new ParentescoVinculo?(ParentescoVinculo.Bisavo); + } + case ParentescoVinculo.Sogro: + { + return new ParentescoVinculo?(ParentescoVinculo.Genro); + } + case ParentescoVinculo.Genro: + { + return new ParentescoVinculo?(ParentescoVinculo.Sogro); + } + case ParentescoVinculo.MadrastaPadrasto: + { + return new ParentescoVinculo?(ParentescoVinculo.Enteado); + } + case ParentescoVinculo.Enteado: + { + return new ParentescoVinculo?(ParentescoVinculo.MadrastaPadrasto); + } + case ParentescoVinculo.Proprietario: + { + return new ParentescoVinculo?(ParentescoVinculo.Propriedade); + } + case ParentescoVinculo.Propriedade: + { + return new ParentescoVinculo?(ParentescoVinculo.Proprietario); + } + case ParentescoVinculo.Contratante: + { + return new ParentescoVinculo?(ParentescoVinculo.Funcionario); + } + case ParentescoVinculo.Funcionario: + { + return new ParentescoVinculo?(ParentescoVinculo.Contratante); + } + } + } + return parentesco; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Model/Properties/AssemblyInfo.cs b/Codemerx/Gestor.Model/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..cf432df --- /dev/null +++ b/Codemerx/Gestor.Model/Properties/AssemblyInfo.cs @@ -0,0 +1,20 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; + +[assembly: AssemblyCompany("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCopyright("Copyright © 2019")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyFileVersion("8.4.0.0")] +[assembly: AssemblyProduct("Gestor.Model")] +[assembly: AssemblyTitle("Gestor.Model")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyVersion("8.4.0.0")] +[assembly: CompilationRelaxations(8)] +[assembly: ComVisible(false)] +[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] +[assembly: Guid("5cdf128b-c74f-43e3-99be-96ed8c50bf61")] +[assembly: RuntimeCompatibility(WrapNonExceptionThrows=true)] diff --git a/Codemerx/Properties/AssemblyInfo.cs b/Codemerx/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..d6cd7a7 --- /dev/null +++ b/Codemerx/Properties/AssemblyInfo.cs @@ -0,0 +1,30 @@ +using System.Diagnostics; +using System.Reflection; +using System.Resources; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; +using System.Windows; +using System.Windows.Resources; + +[assembly: AssemblyAssociatedContentFile("assets/new.html")] +[assembly: AssemblyAssociatedContentFile("migration/files/20251202_280.sql")] +[assembly: AssemblyAssociatedContentFile("migration/files/20251202_281.sql")] +[assembly: AssemblyAssociatedContentFile("migration/files/20251230_282.sql")] +[assembly: AssemblyAssociatedContentFile("resources/relatoriomultipletemplate.html")] +[assembly: AssemblyAssociatedContentFile("resources/tablemultipletemplate.html")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCopyright("Copyright © 2019")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyFileVersion("8.4.0.0")] +[assembly: AssemblyProduct("Gestor.Application")] +[assembly: AssemblyTitle("Gestor.Application")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyVersion("8.4.0.0")] +[assembly: CompilationRelaxations(8)] +[assembly: ComVisible(false)] +[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] +[assembly: NeutralResourcesLanguage("pt-BR", UltimateResourceFallbackLocation.MainAssembly)] +[assembly: RuntimeCompatibility(WrapNonExceptionThrows=true)] +[assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)] -- cgit v1.2.3